From b06f91c4fe52088a0ccbdcadeec24997cdfdb770 Mon Sep 17 00:00:00 2001 From: Max Johnson <162359438+maxj-oai@users.noreply.github.com> Date: Thu, 19 Feb 2026 21:29:05 -0800 Subject: [PATCH 001/385] app-server: improve thread resume rejoin flow (#11776) thread/resume response includes latest turn with all items, in band so no events are stale or lost Testing - e2e tested using app-server-test-client using flow described in "Testing Thread Rejoin Behavior" in codex-rs/app-server-test-client/README.md - e2e tested in codex desktop by reconnecting to a running turn --- codex-rs/Cargo.lock | 1 + codex-rs/app-server-protocol/Cargo.toml | 1 + .../src/protocol/thread_history.rs | 577 +++++++++++++++--- .../app-server-protocol/src/protocol/v2.rs | 20 + .../app-server/src/bespoke_event_handling.rs | 43 +- .../app-server/src/codex_message_processor.rs | 220 +++++-- codex-rs/app-server/src/lib.rs | 4 +- codex-rs/app-server/src/message_processor.rs | 3 + codex-rs/app-server/src/thread_state.rs | 60 +- 9 files changed, 733 insertions(+), 196 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 4e3ec84e8f..20099b02eb 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1354,6 +1354,7 @@ dependencies = [ "strum_macros 0.27.2", "tempfile", "thiserror 2.0.18", + "tracing", "ts-rs", "uuid", ] diff --git a/codex-rs/app-server-protocol/Cargo.toml b/codex-rs/app-server-protocol/Cargo.toml index 2ab6f291f6..f5df7af034 100644 --- a/codex-rs/app-server-protocol/Cargo.toml +++ b/codex-rs/app-server-protocol/Cargo.toml @@ -25,6 +25,7 @@ strum_macros = { workspace = true } thiserror = { workspace = true } ts-rs = { workspace = true } inventory = { workspace = true } +tracing = { workspace = true } uuid = { workspace = true, features = ["serde", "v7"] } [dev-dependencies] diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index e5005077e5..52850a67e4 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -24,9 +24,13 @@ use codex_protocol::protocol::CompactedItem; use codex_protocol::protocol::ContextCompactedEvent; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandBeginEvent; use codex_protocol::protocol::ExecCommandEndEvent; use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::ItemStartedEvent; +use codex_protocol::protocol::McpToolCallBeginEvent; use codex_protocol::protocol::McpToolCallEndEvent; +use codex_protocol::protocol::PatchApplyBeginEvent; use codex_protocol::protocol::PatchApplyEndEvent; use codex_protocol::protocol::ReviewOutputEvent; use codex_protocol::protocol::RolloutItem; @@ -36,8 +40,10 @@ use codex_protocol::protocol::TurnCompleteEvent; use codex_protocol::protocol::TurnStartedEvent; use codex_protocol::protocol::UserMessageEvent; use codex_protocol::protocol::ViewImageToolCallEvent; +use codex_protocol::protocol::WebSearchBeginEvent; use codex_protocol::protocol::WebSearchEndEvent; use std::collections::HashMap; +use tracing::warn; use uuid::Uuid; #[cfg(test)] @@ -57,14 +63,20 @@ pub fn build_turns_from_rollout_items(items: &[RolloutItem]) -> Vec { builder.finish() } -struct ThreadHistoryBuilder { +pub struct ThreadHistoryBuilder { turns: Vec, current_turn: Option, next_item_index: i64, } +impl Default for ThreadHistoryBuilder { + fn default() -> Self { + Self::new() + } +} + impl ThreadHistoryBuilder { - fn new() -> Self { + pub fn new() -> Self { Self { turns: Vec::new(), current_turn: None, @@ -72,14 +84,32 @@ impl ThreadHistoryBuilder { } } - fn finish(mut self) -> Vec { + pub fn reset(&mut self) { + *self = Self::new(); + } + + pub fn finish(mut self) -> Vec { self.finish_current_turn(); self.turns } + pub fn active_turn_snapshot(&self) -> Option { + self.current_turn + .as_ref() + .map(Turn::from) + .or_else(|| self.turns.last().cloned()) + } + + pub fn has_active_turn(&self) -> bool { + self.current_turn.is_some() + } + + /// Shared reducer for persisted rollout replay and in-memory current-turn + /// tracking used by running thread resume/rejoin. + /// /// This function should handle all EventMsg variants that can be persisted in a rollout file. /// See `should_persist_event_msg` in `codex-rs/core/rollout/policy.rs`. - fn handle_event(&mut self, event: &EventMsg) { + pub fn handle_event(&mut self, event: &EventMsg) { match event { EventMsg::UserMessage(payload) => self.handle_user_message(payload), EventMsg::AgentMessage(payload) => { @@ -89,21 +119,35 @@ impl ThreadHistoryBuilder { EventMsg::AgentReasoningRawContent(payload) => { self.handle_agent_reasoning_raw_content(payload) } + EventMsg::WebSearchBegin(payload) => self.handle_web_search_begin(payload), EventMsg::WebSearchEnd(payload) => self.handle_web_search_end(payload), + EventMsg::ExecCommandBegin(payload) => self.handle_exec_command_begin(payload), EventMsg::ExecCommandEnd(payload) => self.handle_exec_command_end(payload), + EventMsg::PatchApplyBegin(payload) => self.handle_patch_apply_begin(payload), EventMsg::PatchApplyEnd(payload) => self.handle_patch_apply_end(payload), + EventMsg::McpToolCallBegin(payload) => self.handle_mcp_tool_call_begin(payload), EventMsg::McpToolCallEnd(payload) => self.handle_mcp_tool_call_end(payload), EventMsg::ViewImageToolCall(payload) => self.handle_view_image_tool_call(payload), + EventMsg::CollabAgentSpawnBegin(payload) => { + self.handle_collab_agent_spawn_begin(payload) + } EventMsg::CollabAgentSpawnEnd(payload) => self.handle_collab_agent_spawn_end(payload), + EventMsg::CollabAgentInteractionBegin(payload) => { + self.handle_collab_agent_interaction_begin(payload) + } EventMsg::CollabAgentInteractionEnd(payload) => { self.handle_collab_agent_interaction_end(payload) } + EventMsg::CollabWaitingBegin(payload) => self.handle_collab_waiting_begin(payload), EventMsg::CollabWaitingEnd(payload) => self.handle_collab_waiting_end(payload), + EventMsg::CollabCloseBegin(payload) => self.handle_collab_close_begin(payload), EventMsg::CollabCloseEnd(payload) => self.handle_collab_close_end(payload), + EventMsg::CollabResumeBegin(payload) => self.handle_collab_resume_begin(payload), EventMsg::CollabResumeEnd(payload) => self.handle_collab_resume_end(payload), EventMsg::ContextCompacted(payload) => self.handle_context_compacted(payload), EventMsg::EnteredReviewMode(payload) => self.handle_entered_review_mode(payload), EventMsg::ExitedReviewMode(payload) => self.handle_exited_review_mode(payload), + EventMsg::ItemStarted(payload) => self.handle_item_started(payload), EventMsg::ItemCompleted(payload) => self.handle_item_completed(payload), EventMsg::Error(payload) => self.handle_error(payload), EventMsg::TokenCount(_) => {} @@ -116,7 +160,7 @@ impl ThreadHistoryBuilder { } } - fn handle_rollout_item(&mut self, item: &RolloutItem) { + pub fn handle_rollout_item(&mut self, item: &RolloutItem) { match item { RolloutItem::EventMsg(event) => self.handle_event(event), RolloutItem::Compacted(payload) => self.handle_compacted(payload), @@ -199,15 +243,51 @@ impl ThreadHistoryBuilder { }); } - fn handle_item_completed(&mut self, payload: &ItemCompletedEvent) { - if let codex_protocol::items::TurnItem::Plan(plan) = &payload.item - && plan.text.is_empty() - { - return; + fn handle_item_started(&mut self, payload: &ItemStartedEvent) { + match &payload.item { + codex_protocol::items::TurnItem::Plan(plan) => { + if plan.text.is_empty() { + return; + } + self.upsert_item_in_turn_id( + &payload.turn_id, + ThreadItem::from(payload.item.clone()), + ); + } + codex_protocol::items::TurnItem::UserMessage(_) + | codex_protocol::items::TurnItem::AgentMessage(_) + | codex_protocol::items::TurnItem::Reasoning(_) + | codex_protocol::items::TurnItem::WebSearch(_) + | codex_protocol::items::TurnItem::ContextCompaction(_) => {} } + } - let item = ThreadItem::from(payload.item.clone()); - self.ensure_turn().items.push(item); + fn handle_item_completed(&mut self, payload: &ItemCompletedEvent) { + match &payload.item { + codex_protocol::items::TurnItem::Plan(plan) => { + if plan.text.is_empty() { + return; + } + self.upsert_item_in_turn_id( + &payload.turn_id, + ThreadItem::from(payload.item.clone()), + ); + } + codex_protocol::items::TurnItem::UserMessage(_) + | codex_protocol::items::TurnItem::AgentMessage(_) + | codex_protocol::items::TurnItem::Reasoning(_) + | codex_protocol::items::TurnItem::WebSearch(_) + | codex_protocol::items::TurnItem::ContextCompaction(_) => {} + } + } + + fn handle_web_search_begin(&mut self, payload: &WebSearchBeginEvent) { + let item = ThreadItem::WebSearch { + id: payload.call_id.clone(), + query: String::new(), + action: None, + }; + self.upsert_item_in_current_turn(item); } fn handle_web_search_end(&mut self, payload: &WebSearchEndEvent) { @@ -216,7 +296,30 @@ impl ThreadHistoryBuilder { query: payload.query.clone(), action: Some(WebSearchAction::from(payload.action.clone())), }; - self.ensure_turn().items.push(item); + self.upsert_item_in_current_turn(item); + } + + fn handle_exec_command_begin(&mut self, payload: &ExecCommandBeginEvent) { + let command = shlex::try_join(payload.command.iter().map(String::as_str)) + .unwrap_or_else(|_| payload.command.join(" ")); + let command_actions = payload + .parsed_cmd + .iter() + .cloned() + .map(CommandAction::from) + .collect(); + let item = ThreadItem::CommandExecution { + id: payload.call_id.clone(), + command, + cwd: payload.cwd.clone(), + process_id: payload.process_id.clone(), + status: CommandExecutionStatus::InProgress, + command_actions, + aggregated_output: None, + exit_code: None, + duration_ms: None, + }; + self.upsert_item_in_turn_id(&payload.turn_id, item); } fn handle_exec_command_end(&mut self, payload: &ExecCommandEndEvent) { @@ -246,33 +349,25 @@ impl ThreadHistoryBuilder { exit_code: Some(payload.exit_code), duration_ms: Some(duration_ms), }; - // Command completions can arrive out of order. Unified exec may return // while a PTY is still running, then emit ExecCommandEnd later from a // background exit watcher when that process finally exits. By then, a // newer user turn may already have started. Route by event turn_id so // replay preserves the original turn association. - if let Some(turn) = self.current_turn.as_mut() - && turn.id == payload.turn_id - { - turn.items.push(item); - return; - } + self.upsert_item_in_turn_id(&payload.turn_id, item); + } - // If the originating turn is already finalized, append there instead - // of attaching to whichever turn is currently active during replay. - if let Some(turn) = self - .turns - .iter_mut() - .find(|turn| turn.id == payload.turn_id) - { - turn.items.push(item); - return; + fn handle_patch_apply_begin(&mut self, payload: &PatchApplyBeginEvent) { + let item = ThreadItem::FileChange { + id: payload.call_id.clone(), + changes: convert_patch_changes(&payload.changes), + status: PatchApplyStatus::InProgress, + }; + if payload.turn_id.is_empty() { + self.upsert_item_in_current_turn(item); + } else { + self.upsert_item_in_turn_id(&payload.turn_id, item); } - - // Backward-compatibility fallback for partial/legacy streams where the - // event turn_id does not match any known replay turn. - self.ensure_turn().items.push(item); } fn handle_patch_apply_end(&mut self, payload: &PatchApplyEndEvent) { @@ -282,7 +377,29 @@ impl ThreadHistoryBuilder { changes: convert_patch_changes(&payload.changes), status, }; - self.ensure_turn().items.push(item); + if payload.turn_id.is_empty() { + self.upsert_item_in_current_turn(item); + } else { + self.upsert_item_in_turn_id(&payload.turn_id, item); + } + } + + fn handle_mcp_tool_call_begin(&mut self, payload: &McpToolCallBeginEvent) { + let item = ThreadItem::McpToolCall { + id: payload.call_id.clone(), + server: payload.invocation.server.clone(), + tool: payload.invocation.tool.clone(), + status: McpToolCallStatus::InProgress, + arguments: payload + .invocation + .arguments + .clone() + .unwrap_or(serde_json::Value::Null), + result: None, + error: None, + duration_ms: None, + }; + self.upsert_item_in_current_turn(item); } fn handle_mcp_tool_call_end(&mut self, payload: &McpToolCallEndEvent) { @@ -321,7 +438,7 @@ impl ThreadHistoryBuilder { error, duration_ms, }; - self.ensure_turn().items.push(item); + self.upsert_item_in_current_turn(item); } fn handle_view_image_tool_call(&mut self, payload: &ViewImageToolCallEvent) { @@ -329,7 +446,23 @@ impl ThreadHistoryBuilder { id: payload.call_id.clone(), path: payload.path.to_string_lossy().into_owned(), }; - self.ensure_turn().items.push(item); + self.upsert_item_in_current_turn(item); + } + + fn handle_collab_agent_spawn_begin( + &mut self, + payload: &codex_protocol::protocol::CollabAgentSpawnBeginEvent, + ) { + let item = ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::SpawnAgent, + status: CollabAgentToolCallStatus::InProgress, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: Vec::new(), + prompt: Some(payload.prompt.clone()), + agents_states: HashMap::new(), + }; + self.upsert_item_in_current_turn(item); } fn handle_collab_agent_spawn_end( @@ -353,17 +486,31 @@ impl ThreadHistoryBuilder { } None => (Vec::new(), HashMap::new()), }; - self.ensure_turn() - .items - .push(ThreadItem::CollabAgentToolCall { - id: payload.call_id.clone(), - tool: CollabAgentTool::SpawnAgent, - status, - sender_thread_id: payload.sender_thread_id.to_string(), - receiver_thread_ids, - prompt: Some(payload.prompt.clone()), - agents_states, - }); + self.upsert_item_in_current_turn(ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::SpawnAgent, + status, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids, + prompt: Some(payload.prompt.clone()), + agents_states, + }); + } + + fn handle_collab_agent_interaction_begin( + &mut self, + payload: &codex_protocol::protocol::CollabAgentInteractionBeginEvent, + ) { + let item = ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::SendInput, + status: CollabAgentToolCallStatus::InProgress, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: vec![payload.receiver_thread_id.to_string()], + prompt: Some(payload.prompt.clone()), + agents_states: HashMap::new(), + }; + self.upsert_item_in_current_turn(item); } fn handle_collab_agent_interaction_end( @@ -376,17 +523,35 @@ impl ThreadHistoryBuilder { }; let receiver_id = payload.receiver_thread_id.to_string(); let received_status = CollabAgentState::from(payload.status.clone()); - self.ensure_turn() - .items - .push(ThreadItem::CollabAgentToolCall { - id: payload.call_id.clone(), - tool: CollabAgentTool::SendInput, - status, - sender_thread_id: payload.sender_thread_id.to_string(), - receiver_thread_ids: vec![receiver_id.clone()], - prompt: Some(payload.prompt.clone()), - agents_states: [(receiver_id, received_status)].into_iter().collect(), - }); + self.upsert_item_in_current_turn(ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::SendInput, + status, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: vec![receiver_id.clone()], + prompt: Some(payload.prompt.clone()), + agents_states: [(receiver_id, received_status)].into_iter().collect(), + }); + } + + fn handle_collab_waiting_begin( + &mut self, + payload: &codex_protocol::protocol::CollabWaitingBeginEvent, + ) { + let item = ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::Wait, + status: CollabAgentToolCallStatus::InProgress, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: payload + .receiver_thread_ids + .iter() + .map(ToString::to_string) + .collect(), + prompt: None, + agents_states: HashMap::new(), + }; + self.upsert_item_in_current_turn(item); } fn handle_collab_waiting_end( @@ -410,17 +575,31 @@ impl ThreadHistoryBuilder { .iter() .map(|(id, status)| (id.to_string(), CollabAgentState::from(status.clone()))) .collect(); - self.ensure_turn() - .items - .push(ThreadItem::CollabAgentToolCall { - id: payload.call_id.clone(), - tool: CollabAgentTool::Wait, - status, - sender_thread_id: payload.sender_thread_id.to_string(), - receiver_thread_ids, - prompt: None, - agents_states, - }); + self.upsert_item_in_current_turn(ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::Wait, + status, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids, + prompt: None, + agents_states, + }); + } + + fn handle_collab_close_begin( + &mut self, + payload: &codex_protocol::protocol::CollabCloseBeginEvent, + ) { + let item = ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::CloseAgent, + status: CollabAgentToolCallStatus::InProgress, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: vec![payload.receiver_thread_id.to_string()], + prompt: None, + agents_states: HashMap::new(), + }; + self.upsert_item_in_current_turn(item); } fn handle_collab_close_end(&mut self, payload: &codex_protocol::protocol::CollabCloseEndEvent) { @@ -435,17 +614,31 @@ impl ThreadHistoryBuilder { )] .into_iter() .collect(); - self.ensure_turn() - .items - .push(ThreadItem::CollabAgentToolCall { - id: payload.call_id.clone(), - tool: CollabAgentTool::CloseAgent, - status, - sender_thread_id: payload.sender_thread_id.to_string(), - receiver_thread_ids: vec![receiver_id], - prompt: None, - agents_states, - }); + self.upsert_item_in_current_turn(ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::CloseAgent, + status, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: vec![receiver_id], + prompt: None, + agents_states, + }); + } + + fn handle_collab_resume_begin( + &mut self, + payload: &codex_protocol::protocol::CollabResumeBeginEvent, + ) { + let item = ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::ResumeAgent, + status: CollabAgentToolCallStatus::InProgress, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: vec![payload.receiver_thread_id.to_string()], + prompt: None, + agents_states: HashMap::new(), + }; + self.upsert_item_in_current_turn(item); } fn handle_collab_resume_end( @@ -463,17 +656,15 @@ impl ThreadHistoryBuilder { )] .into_iter() .collect(); - self.ensure_turn() - .items - .push(ThreadItem::CollabAgentToolCall { - id: payload.call_id.clone(), - tool: CollabAgentTool::ResumeAgent, - status, - sender_thread_id: payload.sender_thread_id.to_string(), - receiver_thread_ids: vec![receiver_id], - prompt: None, - agents_states, - }); + self.upsert_item_in_current_turn(ThreadItem::CollabAgentToolCall { + id: payload.call_id.clone(), + tool: CollabAgentTool::ResumeAgent, + status, + sender_thread_id: payload.sender_thread_id.to_string(), + receiver_thread_ids: vec![receiver_id], + prompt: None, + agents_states, + }); } fn handle_context_compacted(&mut self, _payload: &ContextCompactedEvent) { @@ -548,6 +739,7 @@ impl ThreadHistoryBuilder { self.finish_current_turn(); self.current_turn = Some( self.new_turn(Some(payload.turn_id.clone())) + .with_status(TurnStatus::InProgress) .opened_explicitly(), ); } @@ -642,6 +834,30 @@ impl ThreadHistoryBuilder { unreachable!("current turn must exist after initialization"); } + fn upsert_item_in_turn_id(&mut self, turn_id: &str, item: ThreadItem) { + if let Some(turn) = self.current_turn.as_mut() + && turn.id == turn_id + { + upsert_turn_item(&mut turn.items, item); + return; + } + + if let Some(turn) = self.turns.iter_mut().find(|turn| turn.id == turn_id) { + upsert_turn_item(&mut turn.items, item); + return; + } + + warn!( + item_id = item.id(), + "dropping turn-scoped item for unknown turn id `{turn_id}`" + ); + } + + fn upsert_item_in_current_turn(&mut self, item: ThreadItem) { + let turn = self.ensure_turn(); + upsert_turn_item(&mut turn.items, item); + } + fn next_item_id(&mut self) -> String { let id = format!("item-{}", self.next_item_index); self.next_item_index += 1; @@ -684,7 +900,7 @@ fn render_review_output_text(output: &ReviewOutputEvent) -> String { } } -fn convert_patch_changes( +pub fn convert_patch_changes( changes: &HashMap, ) -> Vec { let mut converted: Vec = changes @@ -726,6 +942,17 @@ fn format_file_change_diff(change: &codex_protocol::protocol::FileChange) -> Str } } +fn upsert_turn_item(items: &mut Vec, item: ThreadItem) { + if let Some(existing_item) = items + .iter_mut() + .find(|existing_item| existing_item.id() == item.id()) + { + *existing_item = item; + return; + } + items.push(item); +} + struct PendingTurn { id: String, items: Vec, @@ -744,6 +971,11 @@ impl PendingTurn { self.opened_explicitly = true; self } + + fn with_status(mut self, status: TurnStatus) -> Self { + self.status = status; + self + } } impl From for Turn { @@ -757,10 +989,23 @@ impl From for Turn { } } +impl From<&PendingTurn> for Turn { + fn from(value: &PendingTurn) -> Self { + Self { + id: value.id.clone(), + items: value.items.clone(), + error: value.error.clone(), + status: value.status.clone(), + } + } +} + #[cfg(test)] mod tests { use super::*; use codex_protocol::ThreadId; + use codex_protocol::items::TurnItem as CoreTurnItem; + use codex_protocol::items::UserMessageItem as CoreUserMessageItem; use codex_protocol::models::MessagePhase as CoreMessagePhase; use codex_protocol::models::WebSearchAction as CoreWebSearchAction; use codex_protocol::parse_command::ParsedCommand; @@ -771,6 +1016,7 @@ mod tests { use codex_protocol::protocol::CompactedItem; use codex_protocol::protocol::ExecCommandEndEvent; use codex_protocol::protocol::ExecCommandSource; + use codex_protocol::protocol::ItemStartedEvent; use codex_protocol::protocol::McpInvocation; use codex_protocol::protocol::McpToolCallEndEvent; use codex_protocol::protocol::ThreadRolledBackEvent; @@ -816,11 +1062,11 @@ mod tests { }), ]; - let items = events - .into_iter() - .map(RolloutItem::EventMsg) - .collect::>(); - let turns = build_turns_from_rollout_items(&items); + let mut builder = ThreadHistoryBuilder::new(); + for event in &events { + builder.handle_event(event); + } + let turns = builder.finish(); assert_eq!(turns.len(), 2); let first = &turns[0]; @@ -883,6 +1129,55 @@ mod tests { ); } + #[test] + fn ignores_non_plan_item_lifecycle_events() { + let turn_id = "turn-1"; + let thread_id = ThreadId::new(); + let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: turn_id.to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::UserMessage(UserMessageEvent { + message: "hello".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + }), + EventMsg::ItemStarted(ItemStartedEvent { + thread_id, + turn_id: turn_id.to_string(), + item: CoreTurnItem::UserMessage(CoreUserMessageItem { + id: "user-item-id".to_string(), + content: Vec::new(), + }), + }), + EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: turn_id.to_string(), + last_agent_message: None, + }), + ]; + + let items = events + .into_iter() + .map(RolloutItem::EventMsg) + .collect::>(); + let turns = build_turns_from_rollout_items(&items); + assert_eq!(turns.len(), 1); + assert_eq!(turns[0].items.len(), 1); + assert_eq!( + turns[0].items[0], + ThreadItem::UserMessage { + id: "item-1".into(), + content: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + } + ); + } + #[test] fn preserves_agent_message_phase_in_history() { let events = vec![EventMsg::AgentMessage(AgentMessageEvent { @@ -1212,6 +1507,11 @@ mod tests { #[test] fn reconstructs_tool_items_from_persisted_completion_events() { let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".into(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), EventMsg::UserMessage(UserMessageEvent { message: "run tools".into(), images: None, @@ -1311,6 +1611,11 @@ mod tests { #[test] fn reconstructs_declined_exec_and_patch_items() { let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".into(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), EventMsg::UserMessage(UserMessageEvent { message: "run tools".into(), images: None, @@ -1471,6 +1776,82 @@ mod tests { ); } + #[test] + fn drops_late_turn_scoped_item_for_unknown_turn_id() { + let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-a".into(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::UserMessage(UserMessageEvent { + message: "first".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + }), + EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-a".into(), + last_agent_message: None, + }), + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-b".into(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::UserMessage(UserMessageEvent { + message: "second".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + }), + EventMsg::ExecCommandEnd(ExecCommandEndEvent { + call_id: "exec-unknown-turn".into(), + process_id: Some("pid-42".into()), + turn_id: "turn-missing".into(), + command: vec!["echo".into(), "done".into()], + cwd: PathBuf::from("/tmp"), + parsed_cmd: vec![ParsedCommand::Unknown { + cmd: "echo done".into(), + }], + source: ExecCommandSource::Agent, + interaction_input: None, + stdout: "done\n".into(), + stderr: String::new(), + aggregated_output: "done\n".into(), + exit_code: 0, + duration: Duration::from_millis(5), + formatted_output: "done\n".into(), + status: CoreExecCommandStatus::Completed, + }), + EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-b".into(), + last_agent_message: None, + }), + ]; + + let mut builder = ThreadHistoryBuilder::new(); + for event in &events { + builder.handle_event(event); + } + let turns = builder.finish(); + assert_eq!(turns.len(), 2); + assert_eq!(turns[0].id, "turn-a"); + assert_eq!(turns[1].id, "turn-b"); + assert_eq!(turns[0].items.len(), 1); + assert_eq!(turns[1].items.len(), 1); + assert_eq!( + turns[1].items[0], + ThreadItem::UserMessage { + id: "item-2".into(), + content: vec![UserInput::Text { + text: "second".into(), + text_elements: Vec::new(), + }], + } + ); + } + #[test] fn late_turn_complete_does_not_close_active_turn() { let events = vec![ @@ -1572,7 +1953,7 @@ mod tests { assert_eq!(turns.len(), 2); assert_eq!(turns[0].id, "turn-a"); assert_eq!(turns[1].id, "turn-b"); - assert_eq!(turns[1].status, TurnStatus::Completed); + assert_eq!(turns[1].status, TurnStatus::InProgress); assert_eq!(turns[1].items.len(), 2); } diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 328fdc0912..6a1959bb25 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2727,6 +2727,26 @@ pub enum ThreadItem { ContextCompaction { id: String }, } +impl ThreadItem { + pub fn id(&self) -> &str { + match self { + ThreadItem::UserMessage { id, .. } + | ThreadItem::AgentMessage { id, .. } + | ThreadItem::Plan { id, .. } + | ThreadItem::Reasoning { id, .. } + | ThreadItem::CommandExecution { id, .. } + | ThreadItem::FileChange { id, .. } + | ThreadItem::McpToolCall { id, .. } + | ThreadItem::CollabAgentToolCall { id, .. } + | ThreadItem::WebSearch { id, .. } + | ThreadItem::ImageView { id, .. } + | ThreadItem::EnteredReviewMode { id, .. } + | ThreadItem::ExitedReviewMode { id, .. } + | ThreadItem::ContextCompaction { id, .. } => id, + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "camelCase")] #[ts(tag = "type", rename_all = "camelCase")] diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index b206eac355..2e87a16844 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -45,7 +45,6 @@ use codex_app_server_protocol::McpToolCallResult; use codex_app_server_protocol::McpToolCallStatus; use codex_app_server_protocol::ModelReroutedNotification; use codex_app_server_protocol::PatchApplyStatus; -use codex_app_server_protocol::PatchChangeKind as V2PatchChangeKind; use codex_app_server_protocol::PlanDeltaNotification; use codex_app_server_protocol::RawResponseItemCompletedNotification; use codex_app_server_protocol::ReasoningSummaryPartAddedNotification; @@ -72,6 +71,7 @@ use codex_app_server_protocol::TurnPlanStep; use codex_app_server_protocol::TurnPlanUpdatedNotification; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::build_turns_from_rollout_items; +use codex_app_server_protocol::convert_patch_changes; use codex_core::CodexThread; use codex_core::ThreadManager; use codex_core::parse_command::shlex_join; @@ -81,7 +81,6 @@ use codex_core::protocol::Event; use codex_core::protocol::EventMsg; use codex_core::protocol::ExecApprovalRequestEvent; use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::FileChange as CoreFileChange; use codex_core::protocol::McpToolCallBeginEvent; use codex_core::protocol::McpToolCallEndEvent; use codex_core::protocol::Op; @@ -1706,46 +1705,6 @@ fn render_review_output_text(output: &ReviewOutputEvent) -> String { } } -fn convert_patch_changes(changes: &HashMap) -> Vec { - let mut converted: Vec = changes - .iter() - .map(|(path, change)| FileUpdateChange { - path: path.to_string_lossy().into_owned(), - kind: map_patch_change_kind(change), - diff: format_file_change_diff(change), - }) - .collect(); - converted.sort_by(|a, b| a.path.cmp(&b.path)); - converted -} - -fn map_patch_change_kind(change: &CoreFileChange) -> V2PatchChangeKind { - match change { - CoreFileChange::Add { .. } => V2PatchChangeKind::Add, - CoreFileChange::Delete { .. } => V2PatchChangeKind::Delete, - CoreFileChange::Update { move_path, .. } => V2PatchChangeKind::Update { - move_path: move_path.clone(), - }, - } -} - -fn format_file_change_diff(change: &CoreFileChange) -> String { - match change { - CoreFileChange::Add { content } => content.clone(), - CoreFileChange::Delete { content } => content.clone(), - CoreFileChange::Update { - unified_diff, - move_path, - } => { - if let Some(path) = move_path { - format!("{unified_diff}\n\nMoved to: {}", path.display()) - } else { - unified_diff.clone() - } - } - } -} - fn map_file_change_approval_decision( decision: FileChangeApprovalDecision, ) -> (ReviewDecision, Option) { diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 58ca63306e..ea2701d635 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -336,6 +336,7 @@ pub(crate) struct CodexMessageProcessor { outgoing: Arc, codex_linux_sandbox_exe: Option, config: Arc, + single_client_mode: bool, cli_overrides: Vec<(String, TomlValue)>, cloud_requirements: Arc>, active_login: Arc>>, @@ -361,6 +362,7 @@ pub(crate) struct CodexMessageProcessorArgs { pub(crate) config: Arc, pub(crate) cli_overrides: Vec<(String, TomlValue)>, pub(crate) cloud_requirements: Arc>, + pub(crate) single_client_mode: bool, pub(crate) feedback: CodexFeedback, } @@ -397,6 +399,7 @@ impl CodexMessageProcessor { config, cli_overrides, cloud_requirements, + single_client_mode, feedback, } = args; Self { @@ -405,6 +408,7 @@ impl CodexMessageProcessor { outgoing: outgoing.clone(), codex_linux_sandbox_exe, config, + single_client_mode, cli_overrides, cloud_requirements, active_login: Arc::new(Mutex::new(None)), @@ -3042,21 +3046,14 @@ impl CodexMessageProcessor { return true; } - if let Err(err) = self - .ensure_conversation_listener( - existing_thread_id, - request_id.connection_id, - false, - ApiVersion::V2, - ) - .await - { - tracing::warn!( - "failed to attach listener for thread {}: {}", - existing_thread_id, - err.message - ); - } + let thread_state = self.thread_state_manager.thread_state(existing_thread_id); + self.ensure_listener_task_running( + existing_thread_id, + existing_thread.clone(), + thread_state.clone(), + ApiVersion::V2, + ) + .await; let config_snapshot = existing_thread.config_snapshot().await; let mismatch_details = collect_resume_override_mismatches(params, &config_snapshot); @@ -3068,41 +3065,39 @@ impl CodexMessageProcessor { ); } - let Some(mut thread) = self - .load_thread_from_rollout_or_send_internal( - request_id.clone(), - existing_thread_id, - rollout_path.as_path(), - config_snapshot.model_provider_id.as_str(), - ) - .await - else { + let listener_command_tx = { + let thread_state = thread_state.lock().await; + thread_state.listener_command_tx() + }; + let Some(listener_command_tx) = listener_command_tx else { + let err = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!( + "failed to enqueue running thread resume for thread {existing_thread_id}: thread listener is not running" + ), + data: None, + }; + self.outgoing.send_error(request_id, err).await; return true; }; - let ThreadConfigSnapshot { - model, - model_provider_id, - approval_policy, - sandbox_policy, - cwd, - reasoning_effort, - .. - } = config_snapshot; - thread.status = self - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; - let response = ThreadResumeResponse { - thread, - model, - model_provider: model_provider_id, - cwd, - approval_policy: approval_policy.into(), - sandbox: sandbox_policy.into(), - reasoning_effort, - }; - self.outgoing.send_response(request_id, response).await; + let command = crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse( + crate::thread_state::PendingThreadResumeRequest { + request_id: request_id.clone(), + rollout_path, + config_snapshot, + }, + ); + if listener_command_tx.send(command).is_err() { + let err = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!( + "failed to enqueue running thread resume for thread {existing_thread_id}: thread listener command channel is closed" + ), + data: None, + }; + self.outgoing.send_error(request_id, err).await; + } return true; } false @@ -5817,17 +5812,18 @@ impl CodexMessageProcessor { api_version: ApiVersion, ) { let (cancel_tx, mut cancel_rx) = oneshot::channel(); - { + let mut listener_command_rx = { let mut thread_state = thread_state.lock().await; if thread_state.listener_matches(&conversation) { return; } - thread_state.set_listener(cancel_tx, &conversation); - } + thread_state.set_listener(cancel_tx, &conversation) + }; let outgoing_for_task = self.outgoing.clone(); let thread_manager = self.thread_manager.clone(); let thread_watch_manager = self.thread_watch_manager.clone(); let fallback_model_provider = self.config.model_provider_id.clone(); + let single_client_mode = self.single_client_mode; tokio::spawn(async move { loop { tokio::select! { @@ -5869,7 +5865,10 @@ impl CodexMessageProcessor { conversation_id.to_string().into(), ); let (subscribed_connection_ids, raw_events_enabled) = { - let thread_state = thread_state.lock().await; + let mut thread_state = thread_state.lock().await; + if !single_client_mode { + thread_state.track_current_turn_event(&event.msg); + } ( thread_state.subscribed_connection_ids(), thread_state.experimental_raw_events, @@ -5908,6 +5907,25 @@ impl CodexMessageProcessor { ) .await; } + listener_command = listener_command_rx.recv() => { + let Some(listener_command) = listener_command else { + break; + }; + match listener_command { + crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse( + resume_request, + ) => { + handle_pending_thread_resume_request( + conversation_id, + &thread_state, + &thread_watch_manager, + &outgoing_for_task, + resume_request, + ) + .await; + } + } + } } } }); @@ -6206,6 +6224,106 @@ impl CodexMessageProcessor { } } +async fn handle_pending_thread_resume_request( + conversation_id: ThreadId, + thread_state: &Arc>, + thread_watch_manager: &ThreadWatchManager, + outgoing: &Arc, + pending: crate::thread_state::PendingThreadResumeRequest, +) { + let active_turn = { + let state = thread_state.lock().await; + state.active_turn_snapshot() + }; + + let request_id = pending.request_id; + let connection_id = request_id.connection_id; + let mut thread = match load_thread_for_running_resume_response( + conversation_id, + pending.rollout_path.as_path(), + pending.config_snapshot.model_provider_id.as_str(), + active_turn.as_ref(), + ) + .await + { + Ok(thread) => thread, + Err(message) => { + outgoing + .send_error( + request_id, + JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message, + data: None, + }, + ) + .await; + return; + } + }; + thread.status = thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await; + + let ThreadConfigSnapshot { + model, + model_provider_id, + approval_policy, + sandbox_policy, + cwd, + reasoning_effort, + .. + } = pending.config_snapshot; + let response = ThreadResumeResponse { + thread, + model, + model_provider: model_provider_id, + cwd, + approval_policy: approval_policy.into(), + sandbox: sandbox_policy.into(), + reasoning_effort, + }; + outgoing.send_response(request_id, response).await; + thread_state.lock().await.add_connection(connection_id); +} + +async fn load_thread_for_running_resume_response( + conversation_id: ThreadId, + rollout_path: &Path, + fallback_provider: &str, + active_turn: Option<&Turn>, +) -> std::result::Result { + let mut thread = read_summary_from_rollout(rollout_path, fallback_provider) + .await + .map(summary_to_thread) + .map_err(|err| { + format!( + "failed to load rollout `{}` for thread {conversation_id}: {err}", + rollout_path.display() + ) + })?; + + let mut turns = read_rollout_items_from_rollout(rollout_path) + .await + .map(|items| build_turns_from_rollout_items(&items)) + .map_err(|err| { + format!( + "failed to load rollout `{}` for thread {conversation_id}: {err}", + rollout_path.display() + ) + })?; + if let Some(active_turn) = active_turn { + merge_turn_history_with_active_turn(&mut turns, active_turn.clone()); + } + thread.turns = turns; + Ok(thread) +} + +fn merge_turn_history_with_active_turn(turns: &mut Vec, active_turn: Turn) { + turns.retain(|turn| turn.id != active_turn.id); + turns.push(active_turn); +} + fn collect_resume_override_mismatches( request: &ThreadResumeParams, config_snapshot: &ThreadConfigSnapshot, diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 7752ee92c7..8e7e1455c4 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -238,7 +238,8 @@ pub async fn run_main_with_transport( Some(start_websocket_acceptor(bind_address, transport_event_tx.clone()).await?); } } - let shutdown_when_no_connections = matches!(transport, AppServerTransport::Stdio); + let single_client_mode = matches!(transport, AppServerTransport::Stdio); + let shutdown_when_no_connections = single_client_mode; // Parse CLI overrides once and derive the base Config eagerly so later // components do not need to work with raw TOML values. @@ -439,6 +440,7 @@ pub async fn run_main_with_transport( outgoing: outgoing_message_sender, codex_linux_sandbox_exe, config: Arc::new(config), + single_client_mode, cli_overrides, loader_overrides, cloud_requirements: cloud_requirements.clone(), diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index f1c6029a21..e80e1790f8 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -139,6 +139,7 @@ pub(crate) struct MessageProcessorArgs { pub(crate) outgoing: Arc, pub(crate) codex_linux_sandbox_exe: Option, pub(crate) config: Arc, + pub(crate) single_client_mode: bool, pub(crate) cli_overrides: Vec<(String, TomlValue)>, pub(crate) loader_overrides: LoaderOverrides, pub(crate) cloud_requirements: CloudRequirementsLoader, @@ -154,6 +155,7 @@ impl MessageProcessor { outgoing, codex_linux_sandbox_exe, config, + single_client_mode, cli_overrides, loader_overrides, cloud_requirements, @@ -184,6 +186,7 @@ impl MessageProcessor { config: Arc::clone(&config), cli_overrides: cli_overrides.clone(), cloud_requirements: cloud_requirements.clone(), + single_client_mode, feedback, }); let config_api = ConfigApi::new( diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index fd0f58abd1..264c9a39d6 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -1,13 +1,19 @@ use crate::outgoing_message::ConnectionId; use crate::outgoing_message::ConnectionRequestId; +use codex_app_server_protocol::ThreadHistoryBuilder; +use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnError; use codex_core::CodexThread; +use codex_core::ThreadConfigSnapshot; use codex_protocol::ThreadId; +use codex_protocol::protocol::EventMsg; use std::collections::HashMap; use std::collections::HashSet; +use std::path::PathBuf; use std::sync::Arc; use std::sync::Weak; use tokio::sync::Mutex; +use tokio::sync::mpsc; use tokio::sync::oneshot; use uuid::Uuid; @@ -16,6 +22,16 @@ type PendingInterruptQueue = Vec<( crate::codex_message_processor::ApiVersion, )>; +pub(crate) struct PendingThreadResumeRequest { + pub(crate) request_id: ConnectionRequestId, + pub(crate) rollout_path: PathBuf, + pub(crate) config_snapshot: ThreadConfigSnapshot, +} + +pub(crate) enum ThreadListenerCommand { + SendThreadResumeResponse(PendingThreadResumeRequest), +} + /// Per-conversation accumulation of the latest states e.g. error message while a turn runs. #[derive(Default, Clone)] pub(crate) struct TurnSummary { @@ -31,6 +47,8 @@ pub(crate) struct ThreadState { pub(crate) turn_summary: TurnSummary, pub(crate) cancel_tx: Option>, pub(crate) experimental_raw_events: bool, + listener_command_tx: Option>, + current_turn_history: ThreadHistoryBuilder, listener_thread: Option>, subscribed_connections: HashSet, } @@ -47,17 +65,22 @@ impl ThreadState { &mut self, cancel_tx: oneshot::Sender<()>, conversation: &Arc, - ) { + ) -> mpsc::UnboundedReceiver { if let Some(previous) = self.cancel_tx.replace(cancel_tx) { let _ = previous.send(()); } + let (listener_command_tx, listener_command_rx) = mpsc::unbounded_channel(); + self.listener_command_tx = Some(listener_command_tx); self.listener_thread = Some(Arc::downgrade(conversation)); + listener_command_rx } pub(crate) fn clear_listener(&mut self) { if let Some(cancel_tx) = self.cancel_tx.take() { let _ = cancel_tx.send(()); } + self.listener_command_tx = None; + self.current_turn_history.reset(); self.listener_thread = None; } @@ -76,6 +99,23 @@ impl ThreadState { pub(crate) fn set_experimental_raw_events(&mut self, enabled: bool) { self.experimental_raw_events = enabled; } + + pub(crate) fn listener_command_tx( + &self, + ) -> Option> { + self.listener_command_tx.clone() + } + + pub(crate) fn active_turn_snapshot(&self) -> Option { + self.current_turn_history.active_turn_snapshot() + } + + pub(crate) fn track_current_turn_event(&mut self, event: &EventMsg) { + self.current_turn_history.handle_event(event); + if !self.current_turn_history.has_active_turn() { + self.current_turn_history.reset(); + } + } } #[derive(Clone, Copy)] @@ -200,12 +240,24 @@ impl ThreadStateManager { } pub(crate) async fn remove_connection(&mut self, connection_id: ConnectionId) { - let Some(thread_ids) = self.thread_ids_by_connection.remove(&connection_id) else { - return; - }; + let thread_ids = self + .thread_ids_by_connection + .remove(&connection_id) + .unwrap_or_default(); self.subscription_state_by_id .retain(|_, state| state.connection_id != connection_id); + if thread_ids.is_empty() { + for thread_state in self.thread_states.values() { + let mut thread_state = thread_state.lock().await; + thread_state.remove_connection(connection_id); + if thread_state.subscribed_connection_ids().is_empty() { + thread_state.clear_listener(); + } + } + return; + } + for thread_id in thread_ids { if let Some(thread_state) = self.thread_states.get(&thread_id) { let mut thread_state = thread_state.lock().await; From 18bd6d2d71f0055d08ee9856de469fcfd28899cf Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Thu, 19 Feb 2026 22:06:51 -0800 Subject: [PATCH 002/385] [apps] Store apps tool cache in disk to reduce startup time. (#11822) We now write MCP tools from installed apps to disk cache so that they can be picked up instantly at startup. We still do a fresh fetch from remote MCP server but it's non blocking unless there's a cache miss. - [x] Store apps tool cache in disk to reduce startup time. --- codex-rs/chatgpt/src/connectors.rs | 64 +- codex-rs/core/src/codex.rs | 5 + codex-rs/core/src/connectors.rs | 194 ++++- codex-rs/core/src/mcp/mod.rs | 3 + codex-rs/core/src/mcp_connection_manager.rs | 745 +++++++++++++++----- codex-rs/tui/src/chatwidget.rs | 44 +- codex-rs/tui/src/chatwidget/tests.rs | 37 + 7 files changed, 848 insertions(+), 244 deletions(-) diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index 6dc2161f0c..27f2f1de94 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -4,8 +4,6 @@ use std::sync::LazyLock; use std::sync::Mutex as StdMutex; use codex_core::config::Config; -use codex_core::default_client::is_first_party_chat_originator; -use codex_core::default_client::originator; use codex_core::features::Feature; use codex_core::token_data::TokenData; use serde::Deserialize; @@ -22,8 +20,10 @@ use codex_core::connectors::AppMetadata; use codex_core::connectors::CONNECTORS_CACHE_TTL; pub use codex_core::connectors::connector_display_label; use codex_core::connectors::connector_install_url; +use codex_core::connectors::filter_disallowed_connectors; pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools; pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options; +pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status; pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools; use codex_core::connectors::merge_connectors; pub use codex_core::connectors::with_app_enabled_state; @@ -106,7 +106,7 @@ pub async fn list_cached_all_connectors(config: &Config) -> Option> } let token_data = get_chatgpt_token_data()?; let cache_key = all_connectors_cache_key(config, &token_data); - read_cached_all_connectors(&cache_key) + read_cached_all_connectors(&cache_key).map(filter_disallowed_connectors) } pub async fn list_all_connectors_with_options( @@ -123,7 +123,7 @@ pub async fn list_all_connectors_with_options( get_chatgpt_token_data().ok_or_else(|| anyhow::anyhow!("ChatGPT token not available"))?; let cache_key = all_connectors_cache_key(config, &token_data); if !force_refetch && let Some(cached_connectors) = read_cached_all_connectors(&cache_key) { - return Ok(cached_connectors); + return Ok(filter_disallowed_connectors(cached_connectors)); } let mut apps = list_directory_connectors(config).await?; @@ -149,6 +149,7 @@ pub async fn list_all_connectors_with_options( .cmp(&right.name) .then_with(|| left.id.cmp(&right.id)) }); + let connectors = filter_disallowed_connectors(connectors); write_cached_all_connectors(cache_key, &connectors); Ok(connectors) } @@ -453,45 +454,6 @@ fn normalize_connector_value(value: Option<&str>) -> Option { .filter(|value| !value.is_empty()) .map(str::to_string) } - -const DISALLOWED_CONNECTOR_IDS: &[&str] = &[ - "asdk_app_6938a94a61d881918ef32cb999ff937c", - "connector_2b0a9009c9c64bf9933a3dae3f2b1254", - "connector_68de829bf7648191acd70a907364c67c", - "connector_68e004f14af881919eb50893d3d9f523", - "connector_69272cb413a081919685ec3c88d1744e", - "connector_0f9c9d4592e54d0a9a12b3f44a1e2010", -]; -const FIRST_PARTY_CHAT_DISALLOWED_CONNECTOR_IDS: &[&str] = - &["connector_0f9c9d4592e54d0a9a12b3f44a1e2010"]; -const DISALLOWED_CONNECTOR_PREFIX: &str = "connector_openai_"; - -fn filter_disallowed_connectors(connectors: Vec) -> Vec { - filter_disallowed_connectors_for_originator(connectors, originator().value.as_str()) -} - -fn filter_disallowed_connectors_for_originator( - connectors: Vec, - originator_value: &str, -) -> Vec { - let disallowed_connector_ids = if is_first_party_chat_originator(originator_value) { - FIRST_PARTY_CHAT_DISALLOWED_CONNECTOR_IDS - } else { - DISALLOWED_CONNECTOR_IDS - }; - - connectors - .into_iter() - .filter(|connector| is_connector_allowed(connector, disallowed_connector_ids)) - .collect() -} - -fn is_connector_allowed(connector: &AppInfo, disallowed_connector_ids: &[&str]) -> bool { - let connector_id = connector.id.as_str(); - !connector_id.starts_with(DISALLOWED_CONNECTOR_PREFIX) - && !disallowed_connector_ids.contains(&connector_id) -} - #[cfg(test)] mod tests { use super::*; @@ -554,22 +516,6 @@ mod tests { assert_eq!(filtered, vec![app("delta")]); } - #[test] - fn first_party_chat_originator_filters_target_and_openai_prefixed_connectors() { - let filtered = filter_disallowed_connectors_for_originator( - vec![ - app("connector_openai_foo"), - app("asdk_app_6938a94a61d881918ef32cb999ff937c"), - app("connector_0f9c9d4592e54d0a9a12b3f44a1e2010"), - ], - "codex_atlas", - ); - assert_eq!( - filtered, - vec![app("asdk_app_6938a94a61d881918ef32cb999ff937c"),] - ); - } - fn merged_app(id: &str, is_accessible: bool) -> AppInfo { AppInfo { id: id.to_string(), diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index d9ba1ca3f6..a384ffc00f 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -149,6 +149,7 @@ use crate::mcp::effective_mcp_servers; use crate::mcp::maybe_prompt_and_install_mcp_dependencies; use crate::mcp::with_codex_apps_mcp; use crate::mcp_connection_manager::McpConnectionManager; +use crate::mcp_connection_manager::codex_apps_tools_cache_key; use crate::mcp_connection_manager::filter_codex_apps_mcp_tools_only; use crate::mcp_connection_manager::filter_mcp_tools_by_name; use crate::mcp_connection_manager::filter_non_codex_apps_mcp_tools_only; @@ -1420,6 +1421,8 @@ impl Session { &session_configuration.approval_policy, tx_event.clone(), sandbox_state, + config.codex_home.clone(), + codex_apps_tools_cache_key(auth), ) .await; { @@ -3068,6 +3071,8 @@ impl Session { &turn_context.config.permissions.approval_policy, self.get_tx_event(), sandbox_state, + config.codex_home.clone(), + codex_apps_tools_cache_key(auth.as_ref()), ) .await; { diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index 884e32dd17..a34477850d 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -19,15 +19,18 @@ use crate::CodexAuth; use crate::SandboxState; use crate::config::Config; use crate::config::types::AppsConfigToml; +use crate::default_client::is_first_party_chat_originator; +use crate::default_client::originator; use crate::features::Feature; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::auth::compute_auth_statuses; use crate::mcp::with_codex_apps_mcp; -use crate::mcp_connection_manager::DEFAULT_STARTUP_TIMEOUT; use crate::mcp_connection_manager::McpConnectionManager; +use crate::mcp_connection_manager::codex_apps_tools_cache_key; use crate::token_data::TokenData; pub const CONNECTORS_CACHE_TTL: Duration = Duration::from_secs(3600); +const CONNECTORS_READY_TIMEOUT_ON_EMPTY_TOOLS: Duration = Duration::from_secs(30); #[derive(Clone, PartialEq, Eq)] struct AccessibleConnectorsCacheKey { @@ -47,10 +50,20 @@ struct CachedAccessibleConnectors { static ACCESSIBLE_CONNECTORS_CACHE: LazyLock>> = LazyLock::new(|| StdMutex::new(None)); +#[derive(Debug, Clone)] +pub struct AccessibleConnectorsStatus { + pub connectors: Vec, + pub codex_apps_ready: bool, +} + pub async fn list_accessible_connectors_from_mcp_tools( config: &Config, ) -> anyhow::Result> { - list_accessible_connectors_from_mcp_tools_with_options(config, false).await + Ok( + list_accessible_connectors_from_mcp_tools_with_options_and_status(config, false) + .await? + .connectors, + ) } pub async fn list_cached_accessible_connectors_from_mcp_tools( @@ -63,15 +76,29 @@ pub async fn list_cached_accessible_connectors_from_mcp_tools( let auth_manager = auth_manager_from_config(config); let auth = auth_manager.auth().await; let cache_key = accessible_connectors_cache_key(config, auth.as_ref()); - read_cached_accessible_connectors(&cache_key) + read_cached_accessible_connectors(&cache_key).map(filter_disallowed_connectors) } pub async fn list_accessible_connectors_from_mcp_tools_with_options( config: &Config, force_refetch: bool, ) -> anyhow::Result> { + Ok( + list_accessible_connectors_from_mcp_tools_with_options_and_status(config, force_refetch) + .await? + .connectors, + ) +} + +pub async fn list_accessible_connectors_from_mcp_tools_with_options_and_status( + config: &Config, + force_refetch: bool, +) -> anyhow::Result { if !config.features.enabled(Feature::Apps) { - return Ok(Vec::new()); + return Ok(AccessibleConnectorsStatus { + connectors: Vec::new(), + codex_apps_ready: true, + }); } let auth_manager = auth_manager_from_config(config); @@ -79,12 +106,19 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_options( let cache_key = accessible_connectors_cache_key(config, auth.as_ref()); if !force_refetch && let Some(cached_connectors) = read_cached_accessible_connectors(&cache_key) { - return Ok(cached_connectors); + let cached_connectors = filter_disallowed_connectors(cached_connectors); + return Ok(AccessibleConnectorsStatus { + connectors: cached_connectors, + codex_apps_ready: true, + }); } let mcp_servers = with_codex_apps_mcp(HashMap::new(), true, auth.as_ref(), config); if mcp_servers.is_empty() { - return Ok(Vec::new()); + return Ok(AccessibleConnectorsStatus { + connectors: Vec::new(), + codex_apps_ready: true, + }); } let auth_status_entries = @@ -107,6 +141,8 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_options( &config.permissions.approval_policy, tx_event, sandbox_state, + config.codex_home.clone(), + codex_apps_tools_cache_key(auth.as_ref()), ) .await; @@ -120,23 +156,45 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_options( ); } + let mut tools = mcp_connection_manager.list_all_tools().await; + let mut should_reload_tools = false; let codex_apps_ready = if let Some(cfg) = mcp_servers.get(CODEX_APPS_MCP_SERVER_NAME) { - let timeout = cfg.startup_timeout_sec.unwrap_or(DEFAULT_STARTUP_TIMEOUT); - mcp_connection_manager - .wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, timeout) - .await + let immediate_ready = mcp_connection_manager + .wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, Duration::ZERO) + .await; + if immediate_ready { + true + } else if tools.is_empty() { + let timeout = cfg + .startup_timeout_sec + .unwrap_or(CONNECTORS_READY_TIMEOUT_ON_EMPTY_TOOLS); + let ready = mcp_connection_manager + .wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, timeout) + .await; + should_reload_tools = ready; + ready + } else { + false + } } else { false }; + if should_reload_tools { + tools = mcp_connection_manager.list_all_tools().await; + } + if codex_apps_ready { + cancel_token.cancel(); + } - let tools = mcp_connection_manager.list_all_tools().await; - cancel_token.cancel(); - - let accessible_connectors = accessible_connectors_from_mcp_tools(&tools); + let accessible_connectors = + filter_disallowed_connectors(accessible_connectors_from_mcp_tools(&tools)); if codex_apps_ready || !accessible_connectors.is_empty() { write_cached_accessible_connectors(cache_key, &accessible_connectors); } - Ok(accessible_connectors) + Ok(AccessibleConnectorsStatus { + connectors: accessible_connectors, + codex_apps_ready, + }) } fn accessible_connectors_cache_key( @@ -288,6 +346,48 @@ pub fn with_app_enabled_state(mut connectors: Vec, config: &Config) -> connectors } +const DISALLOWED_CONNECTOR_IDS: &[&str] = &[ + "asdk_app_6938a94a61d881918ef32cb999ff937c", + "connector_2b0a9009c9c64bf9933a3dae3f2b1254", + "connector_68de829bf7648191acd70a907364c67c", + "connector_68e004f14af881919eb50893d3d9f523", + "connector_69272cb413a081919685ec3c88d1744e", +]; +const FIRST_PARTY_CHAT_DISALLOWED_CONNECTOR_IDS: &[&str] = + &["connector_0f9c9d4592e54d0a9a12b3f44a1e2010"]; +const DISALLOWED_CONNECTOR_PREFIX: &str = "connector_openai_"; + +pub fn filter_disallowed_connectors(connectors: Vec) -> Vec { + filter_disallowed_connectors_for_originator(connectors, originator().value.as_str()) +} + +pub(crate) fn is_connector_id_allowed(connector_id: &str) -> bool { + is_connector_id_allowed_for_originator(connector_id, originator().value.as_str()) +} + +fn filter_disallowed_connectors_for_originator( + connectors: Vec, + originator_value: &str, +) -> Vec { + connectors + .into_iter() + .filter(|connector| { + is_connector_id_allowed_for_originator(connector.id.as_str(), originator_value) + }) + .collect() +} + +fn is_connector_id_allowed_for_originator(connector_id: &str, originator_value: &str) -> bool { + let disallowed_connector_ids = if is_first_party_chat_originator(originator_value) { + FIRST_PARTY_CHAT_DISALLOWED_CONNECTOR_IDS + } else { + DISALLOWED_CONNECTOR_IDS + }; + + !connector_id.starts_with(DISALLOWED_CONNECTOR_PREFIX) + && !disallowed_connector_ids.contains(&connector_id) +} + fn read_apps_config(config: &Config) -> Option { let effective_config = config.config_layer_stack.effective_config(); let apps_config = effective_config.as_table()?.get("apps")?.clone(); @@ -368,3 +468,67 @@ pub fn connector_name_slug(name: &str) -> String { fn format_connector_label(name: &str, _id: &str) -> String { name.to_string() } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + fn app(id: &str) -> AppInfo { + AppInfo { + id: id.to_string(), + name: id.to_string(), + description: None, + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: None, + branding: None, + app_metadata: None, + labels: None, + is_accessible: false, + is_enabled: true, + } + } + + #[test] + fn filter_disallowed_connectors_allows_non_disallowed_connectors() { + let filtered = filter_disallowed_connectors(vec![app("asdk_app_hidden"), app("alpha")]); + assert_eq!(filtered, vec![app("asdk_app_hidden"), app("alpha")]); + } + + #[test] + fn filter_disallowed_connectors_filters_openai_prefix() { + let filtered = filter_disallowed_connectors(vec![ + app("connector_openai_foo"), + app("connector_openai_bar"), + app("gamma"), + ]); + assert_eq!(filtered, vec![app("gamma")]); + } + + #[test] + fn filter_disallowed_connectors_filters_disallowed_connector_ids() { + let filtered = filter_disallowed_connectors(vec![ + app("asdk_app_6938a94a61d881918ef32cb999ff937c"), + app("delta"), + ]); + assert_eq!(filtered, vec![app("delta")]); + } + + #[test] + fn first_party_chat_originator_filters_target_and_openai_prefixed_connectors() { + let filtered = filter_disallowed_connectors_for_originator( + vec![ + app("connector_openai_foo"), + app("asdk_app_6938a94a61d881918ef32cb999ff937c"), + app("connector_0f9c9d4592e54d0a9a12b3f44a1e2010"), + ], + "codex_atlas", + ); + assert_eq!( + filtered, + vec![app("asdk_app_6938a94a61d881918ef32cb999ff937c"),] + ); + } +} diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index 681b1674b6..f2c2557514 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -24,6 +24,7 @@ use crate::features::Feature; use crate::mcp::auth::compute_auth_statuses; use crate::mcp_connection_manager::McpConnectionManager; use crate::mcp_connection_manager::SandboxState; +use crate::mcp_connection_manager::codex_apps_tools_cache_key; const MCP_TOOL_NAME_PREFIX: &str = "mcp"; const MCP_TOOL_NAME_DELIMITER: &str = "__"; @@ -208,6 +209,8 @@ pub async fn collect_mcp_snapshot(config: &Config) -> McpListToolsResponseEvent &config.permissions.approval_policy, tx_event, sandbox_state, + config.codex_home.clone(), + codex_apps_tools_cache_key(auth.as_ref()), ) .await; diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index c872a9732f..c76e19809f 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -12,8 +12,9 @@ use std::env; use std::ffi::OsString; use std::path::PathBuf; use std::sync::Arc; -use std::sync::LazyLock; use std::sync::Mutex as StdMutex; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; @@ -76,6 +77,7 @@ use tracing::warn; use crate::codex::INITIAL_SUBMIT_ID; use crate::config::types::McpServerConfig; use crate::config::types::McpServerTransportConfig; +use crate::connectors::is_connector_id_allowed; /// Delimiter used to separate the server name from the tool name in a fully /// qualified tool name. @@ -91,7 +93,8 @@ pub const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(10); /// Default timeout for individual tool calls. const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(60); -const CODEX_APPS_TOOLS_CACHE_TTL: Duration = Duration::from_secs(3600); +const CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION: u8 = 1; +const CODEX_APPS_TOOLS_CACHE_DIR: &str = "cache/codex_apps_tools"; const MCP_TOOLS_LIST_DURATION_METRIC: &str = "codex.mcp.tools.list.duration_ms"; const MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC: &str = "codex.mcp.tools.fetch_uncached.duration_ms"; const MCP_TOOLS_CACHE_WRITE_DURATION_METRIC: &str = "codex.mcp.tools.cache_write.duration_ms"; @@ -123,6 +126,27 @@ fn sha1_hex(s: &str) -> String { format!("{sha1:x}") } +pub(crate) fn codex_apps_tools_cache_key( + auth: Option<&crate::CodexAuth>, +) -> CodexAppsToolsCacheKey { + let token_data = auth.and_then(|auth| auth.get_token_data().ok()); + let account_id = token_data + .as_ref() + .and_then(|token_data| token_data.account_id.clone()); + let chatgpt_user_id = token_data + .as_ref() + .and_then(|token_data| token_data.id_token.chatgpt_user_id.clone()); + let is_workspace_account = token_data + .as_ref() + .is_some_and(|token_data| token_data.id_token.is_workspace_account()); + + CodexAppsToolsCacheKey { + account_id, + chatgpt_user_id, + is_workspace_account, + } +} + fn qualify_tools(tools: I) -> HashMap where I: IntoIterator, @@ -165,7 +189,7 @@ where qualified_tools } -#[derive(Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct ToolInfo { pub(crate) server_name: String, pub(crate) tool_name: String, @@ -174,14 +198,40 @@ pub(crate) struct ToolInfo { pub(crate) connector_name: Option, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct CodexAppsToolsCacheKey { + account_id: Option, + chatgpt_user_id: Option, + is_workspace_account: bool, +} + #[derive(Clone)] -struct CachedCodexAppsTools { - expires_at: Instant, +struct CodexAppsToolsCacheContext { + codex_home: PathBuf, + user_key: CodexAppsToolsCacheKey, +} + +impl CodexAppsToolsCacheContext { + fn cache_path(&self) -> PathBuf { + let user_key_json = serde_json::to_string(&self.user_key).unwrap_or_default(); + let user_key_hash = sha1_hex(&user_key_json); + self.codex_home + .join(CODEX_APPS_TOOLS_CACHE_DIR) + .join(format!("{user_key_hash}.json")) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CodexAppsToolsDiskCache { + schema_version: u8, tools: Vec, } -static CODEX_APPS_TOOLS_CACHE: LazyLock>> = - LazyLock::new(|| StdMutex::new(None)); +enum CachedCodexAppsToolsLoad { + Hit(Vec), + Missing, + Invalid, +} type ResponderMap = HashMap<(String, RequestId), oneshot::Sender>; @@ -289,9 +339,35 @@ struct ManagedClient { tool_filter: ToolFilter, tool_timeout: Option, server_supports_sandbox_state_capability: bool, + codex_apps_tools_cache_context: Option, } impl ManagedClient { + fn listed_tools(&self) -> Vec { + let total_start = Instant::now(); + if let Some(cache_context) = self.codex_apps_tools_cache_context.as_ref() + && let CachedCodexAppsToolsLoad::Hit(tools) = + load_cached_codex_apps_tools(cache_context) + { + emit_duration( + MCP_TOOLS_LIST_DURATION_METRIC, + total_start.elapsed(), + &[("cache", "hit")], + ); + return filter_tools(tools, &self.tool_filter); + } + + if self.codex_apps_tools_cache_context.is_some() { + emit_duration( + MCP_TOOLS_LIST_DURATION_METRIC, + total_start.elapsed(), + &[("cache", "miss")], + ); + } + + self.tools.clone() + } + /// Returns once the server has ack'd the sandbox state update. async fn notify_sandbox_state_change(&self, sandbox_state: &SandboxState) -> Result<()> { if !self.server_supports_sandbox_state_capability { @@ -312,6 +388,8 @@ impl ManagedClient { #[derive(Clone)] struct AsyncManagedClient { client: Shared>>, + startup_snapshot: Option>, + startup_complete: Arc, } impl AsyncManagedClient { @@ -322,33 +400,63 @@ impl AsyncManagedClient { cancel_token: CancellationToken, tx_event: Sender, elicitation_requests: ElicitationRequestManager, + codex_apps_tools_cache_context: Option, ) -> Self { let tool_filter = ToolFilter::from_config(&config); + let startup_snapshot = load_startup_cached_codex_apps_tools_snapshot( + &server_name, + codex_apps_tools_cache_context.as_ref(), + ) + .map(|tools| filter_tools(tools, &tool_filter)); + let startup_tool_filter = tool_filter; + let startup_complete = Arc::new(AtomicBool::new(false)); + let startup_complete_for_fut = Arc::clone(&startup_complete); let fut = async move { - if let Err(error) = validate_mcp_server_name(&server_name) { - return Err(error.into()); - } + let outcome = async { + if let Err(error) = validate_mcp_server_name(&server_name) { + return Err(error.into()); + } - let client = - Arc::new(make_rmcp_client(&server_name, config.transport, store_mode).await?); - match start_server_task( - server_name, - client, - config.startup_timeout_sec.or(Some(DEFAULT_STARTUP_TIMEOUT)), - config.tool_timeout_sec.unwrap_or(DEFAULT_TOOL_TIMEOUT), - tool_filter, - tx_event, - elicitation_requests, - ) - .or_cancel(&cancel_token) - .await - { - Ok(result) => result, - Err(CancelErr::Cancelled) => Err(StartupOutcomeError::Cancelled), + let client = + Arc::new(make_rmcp_client(&server_name, config.transport, store_mode).await?); + match start_server_task( + server_name, + client, + StartServerTaskParams { + startup_timeout: config + .startup_timeout_sec + .or(Some(DEFAULT_STARTUP_TIMEOUT)), + tool_timeout: config.tool_timeout_sec.unwrap_or(DEFAULT_TOOL_TIMEOUT), + tool_filter: startup_tool_filter, + tx_event, + elicitation_requests, + codex_apps_tools_cache_context, + }, + ) + .or_cancel(&cancel_token) + .await + { + Ok(result) => result, + Err(CancelErr::Cancelled) => Err(StartupOutcomeError::Cancelled), + } } + .await; + + startup_complete_for_fut.store(true, Ordering::Release); + outcome }; + let client = fut.boxed().shared(); + if startup_snapshot.is_some() { + let startup_task = client.clone(); + tokio::spawn(async move { + let _ = startup_task.await; + }); + } + Self { - client: fut.boxed().shared(), + client, + startup_snapshot, + startup_complete, } } @@ -356,6 +464,24 @@ impl AsyncManagedClient { self.client.clone().await } + fn startup_snapshot_while_initializing(&self) -> Option> { + if !self.startup_complete.load(Ordering::Acquire) { + return self.startup_snapshot.clone(); + } + None + } + + async fn listed_tools(&self) -> Option> { + if let Some(startup_tools) = self.startup_snapshot_while_initializing() { + return Some(startup_tools); + } + + match self.client().await { + Ok(client) => Some(client.listed_tools()), + Err(_) => self.startup_snapshot.clone(), + } + } + async fn notify_sandbox_state_change(&self, sandbox_state: &SandboxState) -> Result<()> { let managed = self.client().await?; managed.notify_sandbox_state_change(sandbox_state).await @@ -417,6 +543,8 @@ impl McpConnectionManager { approval_policy: &Constrained, tx_event: Sender, initial_sandbox_state: SandboxState, + codex_home: PathBuf, + codex_apps_tools_cache_key: CodexAppsToolsCacheKey, ) -> (Self, CancellationToken) { let cancel_token = CancellationToken::new(); let mut clients = HashMap::new(); @@ -433,6 +561,14 @@ impl McpConnectionManager { }, ) .await; + let codex_apps_tools_cache_context = if server_name == CODEX_APPS_MCP_SERVER_NAME { + Some(CodexAppsToolsCacheContext { + codex_home: codex_home.clone(), + user_key: codex_apps_tools_cache_key.clone(), + }) + } else { + None + }; let async_managed_client = AsyncManagedClient::new( server_name.clone(), cfg, @@ -440,6 +576,7 @@ impl McpConnectionManager { cancel_token.clone(), tx_event.clone(), elicitation_requests.clone(), + codex_apps_tools_cache_context, ); clients.insert(server_name.clone(), async_managed_client.clone()); let tx_event = tx_event.clone(); @@ -575,29 +712,11 @@ impl McpConnectionManager { #[instrument(level = "trace", skip_all)] pub async fn list_all_tools(&self) -> HashMap { let mut tools = HashMap::new(); - for (server_name, managed_client) in &self.clients { - let client = managed_client.client().await.ok(); - if let Some(client) = client { - let rmcp_client = client.client; - let tool_timeout = client.tool_timeout; - let tool_filter = client.tool_filter; - let mut server_tools = client.tools; - - if server_name == CODEX_APPS_MCP_SERVER_NAME { - match list_tools_for_client(server_name, &rmcp_client, tool_timeout).await { - Ok(fresh_or_cached_tools) => { - server_tools = fresh_or_cached_tools; - } - Err(err) => { - warn!( - "Failed to refresh tools for MCP server '{server_name}', using startup snapshot: {err:#}" - ); - } - } - } - - tools.extend(qualify_tools(filter_tools(server_tools, tool_filter))); - } + for managed_client in self.clients.values() { + let Some(server_tools) = managed_client.listed_tools().await else { + continue; + }; + tools.extend(qualify_tools(server_tools)); } tools } @@ -615,6 +734,8 @@ impl McpConnectionManager { .await .context("failed to get client")?; + let list_start = Instant::now(); + let fetch_start = Instant::now(); let tools = list_tools_for_client_uncached( CODEX_APPS_MCP_SERVER_NAME, &managed_client.client, @@ -624,8 +745,22 @@ impl McpConnectionManager { .with_context(|| { format!("failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'") })?; + emit_duration( + MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, + fetch_start.elapsed(), + &[], + ); - write_cached_codex_apps_tools(&tools); + write_cached_codex_apps_tools_if_needed( + CODEX_APPS_MCP_SERVER_NAME, + managed_client.codex_apps_tools_cache_context.as_ref(), + &tools, + ); + emit_duration( + MCP_TOOLS_LIST_DURATION_METRIC, + list_start.elapsed(), + &[("cache", "miss")], + ); Ok(()) } @@ -934,7 +1069,7 @@ impl ToolFilter { } } -fn filter_tools(tools: Vec, filter: ToolFilter) -> Vec { +fn filter_tools(tools: Vec, filter: &ToolFilter) -> Vec { tools .into_iter() .filter(|tool| filter.allows(&tool.tool_name)) @@ -1077,14 +1212,17 @@ fn elicitation_capability_for_server(server_name: &str) -> Option, - startup_timeout: Option, // TODO: cancel_token should handle this. - tool_timeout: Duration, - tool_filter: ToolFilter, - tx_event: Sender, - elicitation_requests: ElicitationRequestManager, + params: StartServerTaskParams, ) -> Result { + let StartServerTaskParams { + startup_timeout, + tool_timeout, + tool_filter, + tx_event, + elicitation_requests, + codex_apps_tools_cache_context, + } = params; let elicitation = elicitation_capability_for_server(&server_name); - let params = InitializeRequestParams { meta: None, capabilities: ClientCapabilities { @@ -1113,9 +1251,29 @@ async fn start_server_task( .await .map_err(StartupOutcomeError::from)?; - let tools = list_tools_for_client(&server_name, &client, startup_timeout) + let list_start = Instant::now(); + let fetch_start = Instant::now(); + let tools = list_tools_for_client_uncached(&server_name, &client, startup_timeout) .await .map_err(StartupOutcomeError::from)?; + emit_duration( + MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, + fetch_start.elapsed(), + &[], + ); + write_cached_codex_apps_tools_if_needed( + &server_name, + codex_apps_tools_cache_context.as_ref(), + &tools, + ); + if server_name == CODEX_APPS_MCP_SERVER_NAME { + emit_duration( + MCP_TOOLS_LIST_DURATION_METRIC, + list_start.elapsed(), + &[("cache", "miss")], + ); + } + let tools = filter_tools(tools, &tool_filter); let server_supports_sandbox_state_capability = initialize_result .capabilities @@ -1130,11 +1288,21 @@ async fn start_server_task( tool_timeout: Some(tool_timeout), tool_filter, server_supports_sandbox_state_capability, + codex_apps_tools_cache_context, }; Ok(managed) } +struct StartServerTaskParams { + startup_timeout: Option, // TODO: cancel_token should handle this. + tool_timeout: Duration, + tool_filter: ToolFilter, + tx_event: Sender, + elicitation_requests: ElicitationRequestManager, + codex_apps_tools_cache_context: Option, +} + async fn make_rmcp_client( server_name: &str, transport: McpServerTransportConfig, @@ -1179,80 +1347,99 @@ async fn make_rmcp_client( } } -async fn list_tools_for_client( +fn write_cached_codex_apps_tools_if_needed( server_name: &str, - client: &Arc, - timeout: Option, -) -> Result> { - let total_start = Instant::now(); - if server_name == CODEX_APPS_MCP_SERVER_NAME - && let Some(cached_tools) = read_cached_codex_apps_tools() - { - emit_duration( - MCP_TOOLS_LIST_DURATION_METRIC, - total_start.elapsed(), - &[("cache", "hit")], - ); - return Ok(cached_tools); + cache_context: Option<&CodexAppsToolsCacheContext>, + tools: &[ToolInfo], +) { + if server_name != CODEX_APPS_MCP_SERVER_NAME { + return; } - let fetch_start = Instant::now(); - let tools = list_tools_for_client_uncached(server_name, client, timeout).await?; - emit_duration( - MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, - fetch_start.elapsed(), - &[], - ); - - if server_name == CODEX_APPS_MCP_SERVER_NAME { + if let Some(cache_context) = cache_context { let cache_write_start = Instant::now(); - write_cached_codex_apps_tools(&tools); + write_cached_codex_apps_tools(cache_context, tools); emit_duration( MCP_TOOLS_CACHE_WRITE_DURATION_METRIC, cache_write_start.elapsed(), &[], ); } - - if server_name == CODEX_APPS_MCP_SERVER_NAME { - emit_duration( - MCP_TOOLS_LIST_DURATION_METRIC, - total_start.elapsed(), - &[("cache", "miss")], - ); - } - Ok(tools) } -fn read_cached_codex_apps_tools() -> Option> { - let mut cache_guard = CODEX_APPS_TOOLS_CACHE - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let now = Instant::now(); - - if let Some(cached) = cache_guard.as_ref() - && now < cached.expires_at - { - return Some(cached.tools.clone()); +fn load_startup_cached_codex_apps_tools_snapshot( + server_name: &str, + cache_context: Option<&CodexAppsToolsCacheContext>, +) -> Option> { + if server_name != CODEX_APPS_MCP_SERVER_NAME { + return None; } - if cache_guard - .as_ref() - .is_some_and(|cached| now >= cached.expires_at) - { - *cache_guard = None; + let cache_context = cache_context?; + + match load_cached_codex_apps_tools(cache_context) { + CachedCodexAppsToolsLoad::Hit(tools) => Some(tools), + CachedCodexAppsToolsLoad::Missing | CachedCodexAppsToolsLoad::Invalid => None, } - None } -fn write_cached_codex_apps_tools(tools: &[ToolInfo]) { - let mut cache_guard = CODEX_APPS_TOOLS_CACHE - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - *cache_guard = Some(CachedCodexAppsTools { - expires_at: Instant::now() + CODEX_APPS_TOOLS_CACHE_TTL, - tools: tools.to_vec(), - }); +#[cfg(test)] +fn read_cached_codex_apps_tools( + cache_context: &CodexAppsToolsCacheContext, +) -> Option> { + match load_cached_codex_apps_tools(cache_context) { + CachedCodexAppsToolsLoad::Hit(tools) => Some(tools), + CachedCodexAppsToolsLoad::Missing | CachedCodexAppsToolsLoad::Invalid => None, + } +} + +fn load_cached_codex_apps_tools( + cache_context: &CodexAppsToolsCacheContext, +) -> CachedCodexAppsToolsLoad { + let cache_path = cache_context.cache_path(); + let bytes = match std::fs::read(cache_path) { + Ok(bytes) => bytes, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + return CachedCodexAppsToolsLoad::Missing; + } + Err(_) => return CachedCodexAppsToolsLoad::Invalid, + }; + let cache: CodexAppsToolsDiskCache = match serde_json::from_slice(&bytes) { + Ok(cache) => cache, + Err(_) => return CachedCodexAppsToolsLoad::Invalid, + }; + if cache.schema_version != CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION { + return CachedCodexAppsToolsLoad::Invalid; + } + CachedCodexAppsToolsLoad::Hit(filter_disallowed_codex_apps_tools(cache.tools)) +} + +fn write_cached_codex_apps_tools(cache_context: &CodexAppsToolsCacheContext, tools: &[ToolInfo]) { + let cache_path = cache_context.cache_path(); + if let Some(parent) = cache_path.parent() + && std::fs::create_dir_all(parent).is_err() + { + return; + } + let tools = filter_disallowed_codex_apps_tools(tools.to_vec()); + let Ok(bytes) = serde_json::to_vec_pretty(&CodexAppsToolsDiskCache { + schema_version: CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION, + tools, + }) else { + return; + }; + let _ = std::fs::write(cache_path, bytes); +} + +fn filter_disallowed_codex_apps_tools(tools: Vec) -> Vec { + tools + .into_iter() + .filter(|tool| { + tool.connector_id + .as_deref() + .is_none_or(is_connector_id_allowed) + }) + .collect() } fn emit_duration(metric: &str, duration: Duration, tags: &[(&str, &str)]) { @@ -1267,7 +1454,7 @@ async fn list_tools_for_client_uncached( timeout: Option, ) -> Result> { let resp = client.list_tools_with_connector_ids(None, timeout).await?; - Ok(resp + let tools = resp .tools .into_iter() .map(|tool| { @@ -1288,7 +1475,11 @@ async fn list_tools_for_client_uncached( connector_name, } }) - .collect()) + .collect(); + if server_name == CODEX_APPS_MCP_SERVER_NAME { + return Ok(filter_disallowed_codex_apps_tools(tools)); + } + Ok(tools) } fn validate_mcp_server_name(server_name: &str) -> Result<()> { @@ -1376,6 +1567,7 @@ mod tests { use rmcp::model::JsonObject; use std::collections::HashSet; use std::sync::Arc; + use tempfile::tempdir; fn create_test_tool(server_name: &str, tool_name: &str) -> ToolInfo { ToolInfo { @@ -1397,19 +1589,31 @@ mod tests { } } - fn with_clean_codex_apps_tools_cache(f: impl FnOnce() -> T) -> T { - let previous_cache = { - let mut cache_guard = CODEX_APPS_TOOLS_CACHE - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - cache_guard.take() - }; - let result = f(); - let mut cache_guard = CODEX_APPS_TOOLS_CACHE - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - *cache_guard = previous_cache; - result + fn create_test_tool_with_connector( + server_name: &str, + tool_name: &str, + connector_id: &str, + connector_name: Option<&str>, + ) -> ToolInfo { + let mut tool = create_test_tool(server_name, tool_name); + tool.connector_id = Some(connector_id.to_string()); + tool.connector_name = connector_name.map(ToOwned::to_owned); + tool + } + + fn create_codex_apps_tools_cache_context( + codex_home: PathBuf, + account_id: Option<&str>, + chatgpt_user_id: Option<&str>, + ) -> CodexAppsToolsCacheContext { + CodexAppsToolsCacheContext { + codex_home, + user_key: CodexAppsToolsCacheKey { + account_id: account_id.map(ToOwned::to_owned), + chatgpt_user_id: chatgpt_user_id.map(ToOwned::to_owned), + is_workspace_account: false, + }, + } } #[test] @@ -1586,9 +1790,9 @@ mod tests { disabled: HashSet::from(["tool_a".to_string()]), }; - let filtered: Vec<_> = filter_tools(server1_tools, server1_filter) + let filtered: Vec<_> = filter_tools(server1_tools, &server1_filter) .into_iter() - .chain(filter_tools(server2_tools, server2_filter)) + .chain(filter_tools(server2_tools, &server2_filter)) .collect(); assert_eq!(filtered.len(), 1); @@ -1598,43 +1802,260 @@ mod tests { #[test] fn codex_apps_tools_cache_is_overwritten_by_last_write() { - with_clean_codex_apps_tools_cache(|| { - let tools_gateway_1 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "one")]; - let tools_gateway_2 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "two")]; + let codex_home = tempdir().expect("tempdir"); + let cache_context = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let tools_gateway_1 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "one")]; + let tools_gateway_2 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "two")]; - write_cached_codex_apps_tools(&tools_gateway_1); - let cached_gateway_1 = - read_cached_codex_apps_tools().expect("cache entry exists for first write"); - assert_eq!(cached_gateway_1[0].tool_name, "one"); + write_cached_codex_apps_tools(&cache_context, &tools_gateway_1); + let cached_gateway_1 = read_cached_codex_apps_tools(&cache_context) + .expect("cache entry exists for first write"); + assert_eq!(cached_gateway_1[0].tool_name, "one"); - write_cached_codex_apps_tools(&tools_gateway_2); - let cached_gateway_2 = - read_cached_codex_apps_tools().expect("cache entry exists for second write"); - assert_eq!(cached_gateway_2[0].tool_name, "two"); - }); + write_cached_codex_apps_tools(&cache_context, &tools_gateway_2); + let cached_gateway_2 = read_cached_codex_apps_tools(&cache_context) + .expect("cache entry exists for second write"); + assert_eq!(cached_gateway_2[0].tool_name, "two"); } #[test] - fn codex_apps_tools_cache_is_cleared_when_expired() { - with_clean_codex_apps_tools_cache(|| { - let tools = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "stale_tool")]; - write_cached_codex_apps_tools(&tools); + fn codex_apps_tools_cache_is_scoped_per_user() { + let codex_home = tempdir().expect("tempdir"); + let cache_context_user_1 = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let cache_context_user_2 = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-two"), + Some("user-two"), + ); + let tools_user_1 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "one")]; + let tools_user_2 = vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "two")]; - { - let mut cache_guard = CODEX_APPS_TOOLS_CACHE - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - cache_guard.as_mut().expect("cache exists").expires_at = - Instant::now() - Duration::from_secs(1); - } + write_cached_codex_apps_tools(&cache_context_user_1, &tools_user_1); + write_cached_codex_apps_tools(&cache_context_user_2, &tools_user_2); - assert!(read_cached_codex_apps_tools().is_none()); + let read_user_1 = + read_cached_codex_apps_tools(&cache_context_user_1).expect("cache entry for user one"); + let read_user_2 = + read_cached_codex_apps_tools(&cache_context_user_2).expect("cache entry for user two"); - let cache_guard = CODEX_APPS_TOOLS_CACHE - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - assert!(cache_guard.is_none()); - }); + assert_eq!(read_user_1[0].tool_name, "one"); + assert_eq!(read_user_2[0].tool_name, "two"); + assert_ne!( + cache_context_user_1.cache_path(), + cache_context_user_2.cache_path(), + "each user should get an isolated cache file" + ); + } + + #[test] + fn codex_apps_tools_cache_filters_disallowed_connectors() { + let codex_home = tempdir().expect("tempdir"); + let cache_context = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let tools = vec![ + create_test_tool_with_connector( + CODEX_APPS_MCP_SERVER_NAME, + "blocked_tool", + "connector_openai_hidden", + Some("Hidden"), + ), + create_test_tool_with_connector( + CODEX_APPS_MCP_SERVER_NAME, + "allowed_tool", + "calendar", + Some("Calendar"), + ), + ]; + + write_cached_codex_apps_tools(&cache_context, &tools); + let cached = + read_cached_codex_apps_tools(&cache_context).expect("cache entry exists for user"); + + assert_eq!(cached.len(), 1); + assert_eq!(cached[0].tool_name, "allowed_tool"); + assert_eq!(cached[0].connector_id.as_deref(), Some("calendar")); + } + + #[test] + fn codex_apps_tools_cache_is_ignored_when_schema_version_mismatches() { + let codex_home = tempdir().expect("tempdir"); + let cache_context = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let cache_path = cache_context.cache_path(); + if let Some(parent) = cache_path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + let bytes = serde_json::to_vec_pretty(&serde_json::json!({ + "schema_version": CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION + 1, + "tools": [create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "one")], + })) + .expect("serialize"); + std::fs::write(cache_path, bytes).expect("write"); + + assert!(read_cached_codex_apps_tools(&cache_context).is_none()); + } + + #[test] + fn codex_apps_tools_cache_is_ignored_when_json_is_invalid() { + let codex_home = tempdir().expect("tempdir"); + let cache_context = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let cache_path = cache_context.cache_path(); + if let Some(parent) = cache_path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(cache_path, b"{not json").expect("write"); + + assert!(read_cached_codex_apps_tools(&cache_context).is_none()); + } + + #[test] + fn startup_cached_codex_apps_tools_loads_from_disk_cache() { + let codex_home = tempdir().expect("tempdir"); + let cache_context = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let cached_tools = vec![create_test_tool( + CODEX_APPS_MCP_SERVER_NAME, + "calendar_search", + )]; + write_cached_codex_apps_tools(&cache_context, &cached_tools); + + let startup_snapshot = load_startup_cached_codex_apps_tools_snapshot( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + ); + let startup_tools = startup_snapshot.expect("expected startup snapshot to load from cache"); + + assert_eq!(startup_tools.len(), 1); + assert_eq!(startup_tools[0].server_name, CODEX_APPS_MCP_SERVER_NAME); + assert_eq!(startup_tools[0].tool_name, "calendar_search"); + } + + #[tokio::test] + async fn list_all_tools_uses_startup_snapshot_while_client_is_pending() { + let startup_tools = vec![create_test_tool( + CODEX_APPS_MCP_SERVER_NAME, + "calendar_create_event", + )]; + let pending_client = + futures::future::pending::>() + .boxed() + .shared(); + let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); + let mut manager = McpConnectionManager::new_uninitialized(&approval_policy); + manager.clients.insert( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + AsyncManagedClient { + client: pending_client, + startup_snapshot: Some(startup_tools), + startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), + }, + ); + + let tools = manager.list_all_tools().await; + let tool = tools + .get("mcp__codex_apps__calendar_create_event") + .expect("tool from startup cache"); + assert_eq!(tool.server_name, CODEX_APPS_MCP_SERVER_NAME); + assert_eq!(tool.tool_name, "calendar_create_event"); + } + + #[tokio::test] + async fn list_all_tools_blocks_while_client_is_pending_without_startup_snapshot() { + let pending_client = + futures::future::pending::>() + .boxed() + .shared(); + let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); + let mut manager = McpConnectionManager::new_uninitialized(&approval_policy); + manager.clients.insert( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + AsyncManagedClient { + client: pending_client, + startup_snapshot: None, + startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), + }, + ); + + let timeout_result = + tokio::time::timeout(Duration::from_millis(10), manager.list_all_tools()).await; + assert!(timeout_result.is_err()); + } + + #[tokio::test] + async fn list_all_tools_does_not_block_when_startup_snapshot_cache_hit_is_empty() { + let pending_client = + futures::future::pending::>() + .boxed() + .shared(); + let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); + let mut manager = McpConnectionManager::new_uninitialized(&approval_policy); + manager.clients.insert( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + AsyncManagedClient { + client: pending_client, + startup_snapshot: Some(Vec::new()), + startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), + }, + ); + + let timeout_result = + tokio::time::timeout(Duration::from_millis(10), manager.list_all_tools()).await; + let tools = timeout_result.expect("cache-hit startup snapshot should not block"); + assert!(tools.is_empty()); + } + + #[tokio::test] + async fn list_all_tools_uses_startup_snapshot_when_client_startup_fails() { + let startup_tools = vec![create_test_tool( + CODEX_APPS_MCP_SERVER_NAME, + "calendar_create_event", + )]; + let failed_client = futures::future::ready::>( + Err(StartupOutcomeError::Failed { + error: "startup failed".to_string(), + }), + ) + .boxed() + .shared(); + let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); + let mut manager = McpConnectionManager::new_uninitialized(&approval_policy); + let startup_complete = Arc::new(std::sync::atomic::AtomicBool::new(true)); + manager.clients.insert( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + AsyncManagedClient { + client: failed_client, + startup_snapshot: Some(startup_tools), + startup_complete, + }, + ); + + let tools = manager.list_all_tools().await; + let tool = tools + .get("mcp__codex_apps__calendar_create_event") + .expect("tool from startup cache"); + assert_eq!(tool.server_name, CODEX_APPS_MCP_SERVER_NAME); + assert_eq!(tool.tool_name, "calendar_create_event"); } #[test] diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 9e746b4c57..7dcab8010a 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -539,6 +539,7 @@ pub(crate) struct ChatWidget { mcp_startup_status: Option>, connectors_cache: ConnectorsCacheState, connectors_prefetch_in_flight: bool, + connectors_force_refetch_pending: bool, // Queue of interruptive UI events deferred during an active write cycle interrupts: InterruptManager, // Accumulates the current reasoning block text to extract a header @@ -2650,6 +2651,7 @@ impl ChatWidget { mcp_startup_status: None, connectors_cache: ConnectorsCacheState::default(), connectors_prefetch_in_flight: false, + connectors_force_refetch_pending: false, interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), @@ -2813,6 +2815,7 @@ impl ChatWidget { mcp_startup_status: None, connectors_cache: ConnectorsCacheState::default(), connectors_prefetch_in_flight: false, + connectors_force_refetch_pending: false, interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), @@ -2965,6 +2968,7 @@ impl ChatWidget { mcp_startup_status: None, connectors_cache: ConnectorsCacheState::default(), connectors_prefetch_in_flight: false, + connectors_force_refetch_pending: false, interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), @@ -4601,7 +4605,13 @@ impl ChatWidget { } fn prefetch_connectors_with_options(&mut self, force_refetch: bool) { - if !self.connectors_enabled() || self.connectors_prefetch_in_flight { + if !self.connectors_enabled() { + return; + } + if self.connectors_prefetch_in_flight { + if force_refetch { + self.connectors_force_refetch_pending = true; + } return; } @@ -4613,8 +4623,8 @@ impl ChatWidget { let config = self.config.clone(); let app_event_tx = self.app_event_tx.clone(); tokio::spawn(async move { - let accessible_connectors = - match connectors::list_accessible_connectors_from_mcp_tools_with_options( + let accessible_result = + match connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status( &config, force_refetch, ) @@ -4629,6 +4639,9 @@ impl ChatWidget { return; } }; + let should_schedule_force_refetch = + !force_refetch && !accessible_result.codex_apps_ready; + let accessible_connectors = accessible_result.connectors; app_event_tx.send(AppEvent::ConnectorsLoaded { result: Ok(ConnectorsSnapshot { @@ -4638,7 +4651,8 @@ impl ChatWidget { }); let result: Result = async { - let all_connectors = connectors::list_all_connectors(&config).await?; + let all_connectors = + connectors::list_all_connectors_with_options(&config, force_refetch).await?; let connectors = connectors::merge_connectors_with_accessible( all_connectors, accessible_connectors, @@ -4653,6 +4667,12 @@ impl ChatWidget { result, is_final: true, }); + + if should_schedule_force_refetch { + app_event_tx.send(AppEvent::RefreshConnectors { + force_refetch: true, + }); + } }); } @@ -6821,8 +6841,13 @@ impl ChatWidget { result: Result, is_final: bool, ) { + let mut trigger_pending_force_refetch = false; if is_final { self.connectors_prefetch_in_flight = false; + if self.connectors_force_refetch_pending { + self.connectors_force_refetch_pending = false; + trigger_pending_force_refetch = true; + } } match result { @@ -6857,13 +6882,16 @@ impl ChatWidget { Err(err) => { if matches!(self.connectors_cache, ConnectorsCacheState::Ready(_)) { warn!("failed to refresh apps list; retaining current apps snapshot: {err}"); - return; + } else { + self.connectors_cache = ConnectorsCacheState::Failed(err); + self.bottom_pane.set_connectors_snapshot(None); } - - self.connectors_cache = ConnectorsCacheState::Failed(err); - self.bottom_pane.set_connectors_snapshot(None); } } + + if trigger_pending_force_refetch { + self.prefetch_connectors_with_options(true); + } } pub(crate) fn update_connector_enabled(&mut self, connector_id: &str, enabled: bool) { diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 829c39d0a0..d6d2ab1ad7 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -1627,6 +1627,7 @@ async fn make_chatwidget_manual( mcp_startup_status: None, connectors_cache: ConnectorsCacheState::default(), connectors_prefetch_in_flight: false, + connectors_force_refetch_pending: false, interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), @@ -4582,6 +4583,42 @@ async fn apps_refresh_failure_keeps_existing_full_snapshot() { ); } +#[tokio::test] +async fn apps_refresh_failure_with_cached_snapshot_triggers_pending_force_refetch() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.config.features.enable(Feature::Apps); + chat.bottom_pane.set_connectors_enabled(true); + chat.connectors_prefetch_in_flight = true; + chat.connectors_force_refetch_pending = true; + + let full_connectors = vec![codex_chatgpt::connectors::AppInfo { + id: "unit_test_apps_refresh_failure_pending_connector".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: true, + }]; + chat.connectors_cache = ConnectorsCacheState::Ready(ConnectorsSnapshot { + connectors: full_connectors.clone(), + }); + + chat.on_connectors_loaded(Err("failed to load apps".to_string()), true); + + assert!(chat.connectors_prefetch_in_flight); + assert!(!chat.connectors_force_refetch_pending); + assert_matches!( + &chat.connectors_cache, + ConnectorsCacheState::Ready(snapshot) if snapshot.connectors == full_connectors + ); +} + #[tokio::test] async fn apps_partial_refresh_uses_same_filtering_as_full_refresh() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; From e747a8eb745a2eaa8c9f3a181fc5b35bed809d2b Mon Sep 17 00:00:00 2001 From: zuxin-oai Date: Fri, 20 Feb 2026 01:13:35 -0800 Subject: [PATCH 003/385] memories: add rollout_summary_file header to raw memories and tune prompts (#12221) ## Summary - Add `rollout_summary_file: .md` to each thread header in `raw_memories.md` so Phase 2 can reliably reference the canonical rollout summary filename. - Update the memory prompts/templates (`stage_one_system`, `consolidation`, `read_path`) for the new task-oriented raw-memory / MEMORY.md schema and stronger consolidation guidance. ## Details - `codex-rs/core/src/memories/storage.rs` - Writes the generated `rollout_summary_file` path into the per-thread metadata header when rebuilding `raw_memories.md`. - `codex-rs/core/src/memories/tests.rs` - Verifies the canonical `rollout_summary_file` header is present and ordered after `updated_at`/`cwd` in `raw_memories.md`. - Verifies task-structured raw-memory content is preserved while the canonical header is added. - `codex-rs/core/templates/memories/*.md` - Updates the stage-1 raw-memory format to task-grouped sections (`task`, `task_group`, `task_outcome`). - Updates Phase 2 consolidation guidance around recency (`updated_at`), task-oriented `MEMORY.md` blocks, and richer evidence-backed consolidation. - Tweaks the quick memory pass wording to emphasize topics/workflows in addition to keywords. ## Testing - `cargo test -p codex-core memories` --- codex-rs/core/src/memories/storage.rs | 96 +------- codex-rs/core/src/memories/tests.rs | 45 +++- .../core/templates/memories/consolidation.md | 217 ++++++++++++++---- codex-rs/core/templates/memories/read_path.md | 4 +- .../templates/memories/stage_one_system.md | 89 ++++++- 5 files changed, 298 insertions(+), 153 deletions(-) diff --git a/codex-rs/core/src/memories/storage.rs b/codex-rs/core/src/memories/storage.rs index ea2b00acf5..1a07dbe9b8 100644 --- a/codex-rs/core/src/memories/storage.rs +++ b/codex-rs/core/src/memories/storage.rs @@ -82,11 +82,11 @@ async fn rebuild_raw_memories_file( ) .map_err(raw_memories_format_error)?; writeln!(body, "cwd: {}", memory.cwd.display()).map_err(raw_memories_format_error)?; - writeln!(body).map_err(raw_memories_format_error)?; let rollout_summary_file = format!("{}.md", rollout_summary_file_stem(memory)); - let raw_memory = - replace_rollout_summary_file_in_raw_memory(&memory.raw_memory, &rollout_summary_file); - body.push_str(raw_memory.trim()); + writeln!(body, "rollout_summary_file: {rollout_summary_file}") + .map_err(raw_memories_format_error)?; + writeln!(body).map_err(raw_memories_format_error)?; + body.push_str(memory.raw_memory.trim()); body.push_str("\n\n"); } @@ -161,26 +161,6 @@ fn rollout_summary_format_error(err: std::fmt::Error) -> std::io::Error { std::io::Error::other(format!("format rollout summary: {err}")) } -fn replace_rollout_summary_file_in_raw_memory( - raw_memory: &str, - rollout_summary_file: &str, -) -> String { - const ROLLOUT_SUMMARY_PREFIX: &str = "rollout_summary_file: "; - - let replacement = format!("rollout_summary_file: {rollout_summary_file}"); - raw_memory - .split('\n') - .map(|line| { - if line.starts_with(ROLLOUT_SUMMARY_PREFIX) { - replacement.as_str() - } else { - line - } - }) - .collect::>() - .join("\n") -} - pub(crate) fn rollout_summary_file_stem(memory: &Stage1Output) -> String { rollout_summary_file_stem_from_parts( memory.thread_id, @@ -270,7 +250,6 @@ pub(super) fn rollout_summary_file_stem_from_parts( #[cfg(test)] mod tests { - use super::replace_rollout_summary_file_in_raw_memory; use super::rollout_summary_file_stem; use super::rollout_summary_file_stem_from_parts; use chrono::TimeZone; @@ -339,71 +318,4 @@ mod tests { assert_eq!(rollout_summary_file_stem(&memory), FIXED_PREFIX); } - - #[test] - fn replace_rollout_summary_file_in_raw_memory_replaces_existing_value() { - let raw_memory = "\ ---- -rollout_summary_file: wrong.md -description: demo -keywords: one, two ---- -- body line"; - let normalized = replace_rollout_summary_file_in_raw_memory( - raw_memory, - "2025-01-01T00-00-00-abcd-demo.md", - ); - - assert_eq!( - normalized, - "\ ---- -rollout_summary_file: 2025-01-01T00-00-00-abcd-demo.md -description: demo -keywords: one, two ---- -- body line" - ); - } - - #[test] - fn replace_rollout_summary_file_in_raw_memory_replaces_placeholder() { - let raw_memory = "\ ---- -rollout_summary_file: -description: demo -keywords: one, two ---- -- body line"; - let normalized = replace_rollout_summary_file_in_raw_memory( - raw_memory, - "2025-01-01T00-00-00-abcd-demo.md", - ); - - assert_eq!( - normalized, - "\ ---- -rollout_summary_file: 2025-01-01T00-00-00-abcd-demo.md -description: demo -keywords: one, two ---- -- body line" - ); - } - - #[test] - fn replace_rollout_summary_file_in_raw_memory_leaves_text_without_field_unchanged() { - let raw_memory = "\ ---- -description: demo -keywords: one, two ---- -- body line"; - let normalized = replace_rollout_summary_file_in_raw_memory( - raw_memory, - "2025-01-01T00-00-00-abcd-demo.md", - ); - assert_eq!(normalized, raw_memory); - } } diff --git a/codex-rs/core/src/memories/tests.rs b/codex-rs/core/src/memories/tests.rs index 7d86f75c9d..b47e7f8aab 100644 --- a/codex-rs/core/src/memories/tests.rs +++ b/codex-rs/core/src/memories/tests.rs @@ -127,6 +127,7 @@ async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only } files.sort_unstable(); assert_eq!(files.len(), 1); + let canonical_rollout_summary_file = &files[0]; let raw_memories = tokio::fs::read_to_string(raw_memories_file(&root)) .await @@ -134,6 +135,30 @@ async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only assert!(raw_memories.contains("raw memory")); assert!(raw_memories.contains(&keep_id)); assert!(raw_memories.contains("cwd: /tmp/workspace")); + assert!(raw_memories.contains(&format!( + "rollout_summary_file: {canonical_rollout_summary_file}" + ))); + let thread_header = format!("## Thread `{keep_id}`"); + let thread_pos = raw_memories + .find(&thread_header) + .expect("thread header should exist"); + let updated_pos = raw_memories[thread_pos..] + .find("updated_at: ") + .map(|offset| thread_pos + offset) + .expect("updated_at should exist after thread header"); + let cwd_pos = raw_memories[thread_pos..] + .find("cwd: /tmp/workspace") + .map(|offset| thread_pos + offset) + .expect("cwd should exist after thread header"); + let file_pos = raw_memories[thread_pos..] + .find(&format!( + "rollout_summary_file: {canonical_rollout_summary_file}" + )) + .map(|offset| thread_pos + offset) + .expect("rollout_summary_file should exist after thread header"); + assert!(thread_pos < updated_pos); + assert!(updated_pos < cwd_pos); + assert!(cwd_pos < file_pos); } #[tokio::test] @@ -229,7 +254,7 @@ async fn sync_rollout_summaries_uses_timestamp_hash_and_sanitized_slug_filename( } #[tokio::test] -async fn rebuild_raw_memories_file_rewrites_rollout_summary_file_to_canonical_filename() { +async fn rebuild_raw_memories_file_adds_canonical_rollout_summary_file_header() { let dir = tempdir().expect("tempdir"); let root = dir.path().join("memory"); ensure_layout(&root).await.expect("ensure layout"); @@ -241,11 +266,20 @@ async fn rebuild_raw_memories_file_rewrites_rollout_summary_file_to_canonical_fi source_updated_at: Utc.timestamp_opt(200, 0).single().expect("timestamp"), raw_memory: "\ --- -rollout_summary_file: state_migration_uniqueness_test.md description: Added a migration test keywords: codex-state, migrations --- -- Kept details." +### Task 1: migration-test +task: add-migration-test +task_group: codex-state +task_outcome: success +- Added regression coverage for migration uniqueness. + +### Task 2: validate-migration +task: validate-migration-ordering +task_group: codex-state +task_outcome: success +- Confirmed no ordering regressions." .to_string(), rollout_summary: "short summary".to_string(), rollout_slug: Some("Unsafe Slug/With Spaces & Symbols + EXTRA_LONG_12345".to_string()), @@ -285,8 +319,11 @@ keywords: codex-state, migrations assert!(raw_memories.contains(&format!( "rollout_summary_file: {canonical_rollout_summary_file}" ))); - assert!(!raw_memories.contains("rollout_summary_file: state_migration_uniqueness_test.md")); assert!(raw_memories.contains("description: Added a migration test")); + assert!(raw_memories.contains("### Task 1: migration-test")); + assert!(raw_memories.contains("task: add-migration-test")); + assert!(raw_memories.contains("task_group: codex-state")); + assert!(raw_memories.contains("task_outcome: success")); } mod phase2 { diff --git a/codex-rs/core/templates/memories/consolidation.md b/codex-rs/core/templates/memories/consolidation.md index de0965082b..91096c1dd3 100644 --- a/codex-rs/core/templates/memories/consolidation.md +++ b/codex-rs/core/templates/memories/consolidation.md @@ -17,7 +17,8 @@ CONTEXT: MEMORY FOLDER STRUCTURE Folder structure (under {{ memory_root }}/): - memory_summary.md - - Always loaded into the system prompt. Must remain tiny and highly navigational. + - Always loaded into the system prompt. Must remain informative and highly navigational, + but still discriminative enough to guide retrieval. - MEMORY.md - Handbook entries. Used to grep for keywords; aggregated insights from rollouts; pointers to rollout summaries if certain past rollouts are very relevant. @@ -40,8 +41,10 @@ GLOBAL SAFETY, HYGIENE, AND NO-FILLER RULES (STRICT) - Evidence-based only: do not invent facts or claim verification that did not happen. - Redact secrets: never store tokens/keys/passwords; replace with [REDACTED_SECRET]. - Avoid copying large tool outputs. Prefer compact summaries + exact error snippets + pointers. -- **No-op is allowed and preferred** when there is no meaningful, reusable learning worth saving. - - If nothing is worth saving, make NO file changes. +- No-op content updates are allowed and preferred when there is no meaningful, reusable + learning worth saving. + - INIT mode: still create minimal required files (`MEMORY.md` and `memory_summary.md`). + - INCREMENTAL UPDATE mode: if nothing is worth saving, make no file changes. ============================================================ WHAT COUNTS AS HIGH-SIGNAL MEMORY @@ -97,7 +100,10 @@ Primary inputs (always read these, if exists): Under `{{ memory_root }}/`: - `raw_memories.md` - mechanical merge of `raw_memories` from Phase 1; - - source of rollout-level metadata needed for MEMORY.md header annotations; + - ordered latest-first; use this recency ordering as a major heuristic when choosing + what to promote, expand, or deprecate; + - source of rollout-level metadata needed for MEMORY.md `### rollout_summary_files` + annotations; you should be able to find `cwd` and `updated_at` there. - `MEMORY.md` - merged memories; produce a lightly clustered version if applicable @@ -123,45 +129,148 @@ Rules: - If there is no meaningful signal to add beyond what already exists, keep outputs minimal. - You should always make sure `MEMORY.md` and `memory_summary.md` exist and are up to date. - Follow the format and schema of the artifacts below. +- Do not target fixed counts (memory blocks, task groups, topics, or bullets). Let the + signal determine the granularity and depth. +- Quality objective: for high-signal task families, `MEMORY.md` should be materially more + useful than `raw_memories.md` while remaining easy to navigate. ============================================================ 1) `MEMORY.md` FORMAT (STRICT) ============================================================ -Clustered schema: ---- -rollout_summary_files: - - () - - () -description: brief description of the shared tasks/outcomes -keywords: k1, k2, k3, ... ---- +`MEMORY.md` is the durable, retrieval-oriented handbook. Each block should be easy to grep +and rich enough to reuse without reopening raw rollout logs. + +Each memory block MUST start with: + +# Task Group: + +scope: + +- `Task Group` is for retrieval. Choose granularity based on memory density: + repo / project / workflow / detail-task family. +- `scope:` is for scanning. Keep it short and operational. + +Body format (strict): + +- Use the task-grouped markdown structure below (headings + bullets). Do not use a flat + bullet dump. +- The header (`# Task Group: ...` + `scope: ...`) is the index. The body contains + task-level detail. +- Every `## Task ` section MUST include task-local rollout files, task-local keywords, + and task-specific learnings. +- Use `-` bullets for lists and learnings. Do not use `*`. +- No bolding text in the memory body. + +Required task-oriented body shape (strict): + +## Task 1: + +task: + +### rollout_summary_files + +- (cwd=, updated_at=, ) + +### keywords + +- + +### learnings + +- +- +- +- cause -> fix> +- +- + +## Task 2: + +task: + +### rollout_summary_files -- - ... -Schema rules (strict): -- Keep entries compact and retrieval-friendly. -- A single note block may correspond to multiple related tasks; aggregate when tasks and lessons align. -- In `rollout_summary_files`, each parenthesized annotation must include - `cwd=` and `updated_at=` copied from that rollout summary metadata. - If missing from an individual rollout summary, recover them from `raw_memories.md`. -- If you need to reference skills, do it in the BODY as bullets, not in the header - (e.g., "- Related skill: skills//SKILL.md"). -- Use lowercase, hyphenated skill folder names. -- Preserve provenance: include the relevant rollout_summary_file(s) for the block. +### keywords -What to write in memory entries: Extract the highest-signal takeaways from the rollout -summaries, especially from "User preferences", "Reusable knowledge", "References", and -"Things that did not work / things that can be improved". -Write what would most help a future agent doing a similar (or adjacent) task: decision -triggers, key steps, proven commands/paths, and failure shields (symptom -> cause -> fix), -plus any stable user preferences. -If a rollout summary contains stable user profile details or preferences that generalize, -capture them here so they're easy to find and can be reflected in memory_summary.md. -The goal of MEMORY.md is to support related-but-not-identical future tasks, so keep -insights slightly more general; when a future task is very similar, expect the agent to -use the rollout summary for full detail. +- ... + +### learnings + +- + +... More `## Task ` sections if needed + +## General Tips + +- [Task 1] +- [Task 1][Task 2] +- + +Schema rules (strict): +- A) Structure and consistency + - Exact block shape: `# Task Group`, `scope:`, one or more `## Task `, and + `## General Tips`. + - Keep all tasks and tips inside the task family implied by the block header. + - Keep entries retrieval-friendly, but not shallow. + - Do not emit placeholder values (`task: task`, `# Task Group: misc`, `scope: general`, etc.). +- B) Task boundaries and clustering + - Primary organization unit is the task (`## Task `), not the rollout file. + - Default mapping: one coherent rollout summary -> one MEMORY block -> one `## Task 1`. + - If a rollout contains multiple distinct tasks, split them into multiple `## Task ` + sections. If those tasks belong to different task families, split into separate + MEMORY blocks (`# Task Group`). + - A MEMORY block may include multiple rollouts only when they belong to the same + task group and the task intent, technical context, and outcome pattern align. + - A single `## Task ` section may cite multiple rollout summaries when they are + iterative attempts or follow-up runs for the same task. + - Do not cluster on keyword overlap alone. + - When in doubt, preserve boundaries (separate tasks/blocks) rather than over-cluster. +- C) Provenance and metadata + - Every `## Task ` section must include `### rollout_summary_files`, `### keywords`, + and `### learnings`. + - `### rollout_summary_files` must be task-local (not a block-wide catch-all list). + - Each rollout annotation must include `cwd=` and `updated_at=`. + If missing from a rollout summary, recover them from `raw_memories.md`. + - Major learnings should be traceable to rollout summaries listed in the same task section. + - Order rollout references by freshness and practical usefulness. +- D) Retrieval and references + - `task:` lines must be specific and searchable. + - `### keywords` should be discriminative and task-local (tool names, error strings, + repo concepts, APIs/contracts). + - Put task-specific detail in `## Task ` and only deduplicated cross-task guidance in + `## General Tips`. + - If you reference skills, do it in body bullets only (for example: + `- Related skill: skills//SKILL.md`). + - Use lowercase, hyphenated skill folder names. +- E) Ordering and conflict handling + - For grouped blocks, order `## Task ` sections by practical usefulness, then recency. + - Treat `updated_at` as a first-class signal: fresher validated evidence usually wins. + - If evidence conflicts and validation is unclear, preserve the uncertainty explicitly. + - In `## General Tips`, cite task references (`[Task 1]`, `[Task 2]`, etc.) when + merging, deduplicating, or resolving evidence. + +What to write: +- Extract the takeaways from rollout summaries and raw_memories, especially sections like + "User preferences", "Reusable knowledge", "References", and "Things that did not work". +- Optimize for future related tasks: decision triggers, validated commands/paths, + verification steps, and failure shields (symptom -> cause -> fix). +- Capture stable user preferences/details that generalize so they can also inform + `memory_summary.md`. +- `MEMORY.md` should support related-but-not-identical tasks: slightly more general than a + rollout summary, but still operational and concrete. +- Use `raw_memories.md` as the routing layer; deep-dive into `rollout_summaries/*.md` when: + - the task is high-value and needs richer detail, + - multiple rollouts overlap and need conflict/staleness resolution, + - raw memory wording is too terse/ambiguous to consolidate confidently, + - you need stronger evidence, validation context, or user feedback. +- Each block should be useful on its own and materially richer than `memory_summary.md`: + - include concrete triggers, commands/paths, and failure shields, + - include outcome-specific notes (what worked, what failed, what remains uncertain), + - include scope boundaries / anti-drift notes when they affect future task success, + - include stale/conflict notes when newer evidence changes prior guidance. ============================================================ 2) `memory_summary.md` FORMAT (STRICT) @@ -210,17 +319,23 @@ For example, include (when known): ## What's in Memory This is a compact index to help future agents quickly find details in `MEMORY.md`, `skills/`, and `rollout_summaries/`. -Organize by topic. Each bullet should include: topic, keywords (used to search over -memory files), and a brief description. +Organize by topic. Each bullet must include: topic, keywords, and a clear description. Ordered by utility - which is the most likely to be useful for a future agent. +Do not target a fixed topic count. Cover the real high-signal areas and omit low-signal noise. +Prefer grouping by task family / workflow intent, not by incidental tools alone. Recommended format: - : , , , ... - - desc: + - desc: Notes: - Do not include large snippets; push details into MEMORY.md and rollout summaries. - Prefer topics/keywords that help a future agent search MEMORY.md efficiently. +- Prefer clear topic taxonomy over verbose drill-down pointers. +- Keep descriptions explicit enough that a future model can decide which keyword cluster + to search first for a new user query. +- Topic descriptions should mention what is inside, when to use it, and what kind of + outcome/procedure depth is available (for example: runbook, diagnostics, reporting, recovery). ============================================================ 3) `skills/` FORMAT (optional) @@ -303,29 +418,41 @@ WORKFLOW - create initial `skills/*` (optional but highly recommended) - write `memory_summary.md` last (highest-signal file) - Use your best efforts to get the most high-quality memory files - - Do not be lazy at browsing files at the INIT phase + - Do not be lazy at browsing files in INIT mode; deep-dive high-value rollouts and + conflicting task families until MEMORY blocks are richer and more useful than raw memories 3) INCREMENTAL UPDATE behavior: - Treat `raw_memories.md` as the primary source of NEW signal. - Read existing memory files first for continuity. - Integrate new signal into existing artifacts by: + - scanning new raw memories in recency order and identifying which existing blocks they should update - updating existing knowledge with better/newer evidence - updating stale or contradicting guidance + - expanding terse old blocks when new summaries/raw memories make the task family clearer - doing light clustering and merging if needed - updating existing skills or adding new skills only when there is clear new reusable procedure - update `memory_summary.md` last to reflect the final state of the memory folder -4) For both modes, update `MEMORY.md` after skill updates: - - add clear **Related skills** pointers in the BODY of corresponding note blocks (do - not change the YAML header schema) +4) Evidence deep-dive rule (both modes): + - `raw_memories.md` is the routing layer, not always the final authority for detail. + - When a task family is important, ambiguous, or duplicated across multiple rollouts, + open the relevant `rollout_summaries/*.md` files and extract richer procedural detail, + validation signals, and user feedback before finalizing `MEMORY.md`. + - Use `updated_at` and validation strength together to resolve stale/conflicting notes. -5) Housekeeping (optional): +5) For both modes, update `MEMORY.md` after skill updates: + - add clear related-skill pointers as plain bullets in the BODY of corresponding task + sections (do not change the `# Task Group` / `scope:` block header format) + +6) Housekeeping (optional): - remove clearly redundant/low-signal rollout summaries - if multiple summaries overlap for the same thread, keep the best one -6) Final pass: +7) Final pass: - remove duplication in memory_summary, skills/, and MEMORY.md - ensure any referenced skills/summaries actually exist + - ensure MEMORY blocks and "What's in Memory" use a consistent task-oriented taxonomy + - ensure recent important task families are easy to find (description + keywords + topic wording) - if there is no net-new or higher-quality signal to add, keep changes minimal (no churn for its own sake). @@ -341,6 +468,6 @@ Use `rg` for fast retrieval while consolidating: - Search durable notes: `rg -n -i "" "{{ memory_root }}/MEMORY.md"` - Search across memory tree: - `rg -n -i "" "{{ memory_root }}" | head -n 50` + `rg -n -i "" "{{ memory_root }}" | head -n 100` - Locate rollout summary files: - `rg --files "{{ memory_root }}/rollout_summaries" | head -n 200` + `rg --files "{{ memory_root }}/rollout_summaries" | head -n 400` diff --git a/codex-rs/core/templates/memories/read_path.md b/codex-rs/core/templates/memories/read_path.md index 6ef09247b2..ec123fb551 100644 --- a/codex-rs/core/templates/memories/read_path.md +++ b/codex-rs/core/templates/memories/read_path.md @@ -25,8 +25,8 @@ again) - {{ base_path }}/rollout_summaries/ (per-rollout recaps + evidence snippets) Quick memory pass (when applicable): -1) Skim the MEMORY_SUMMARY included below and extract a few task-relevant -keywords (for example repo/module names, error strings, etc.). +1) Skim the MEMORY_SUMMARY included below and extract task-relevant topics and +keywords (for example repo/module names, workflows, error strings, etc.). 2) Search {{ base_path }}/MEMORY.md for those keywords, and for any referenced rollout summary files and skills. 3) If relevant rollout summary files and skills exist, open matching files diff --git a/codex-rs/core/templates/memories/stage_one_system.md b/codex-rs/core/templates/memories/stage_one_system.md index 38031e8d2f..692243c900 100644 --- a/codex-rs/core/templates/memories/stage_one_system.md +++ b/codex-rs/core/templates/memories/stage_one_system.md @@ -109,6 +109,16 @@ Typical real-world signals (use as examples when analyzing the rollout): 3) User keeps iterating on the same task: - Requests for fixes/revisions on the same artifact usually mean partial, not success. - Requesting a restart or pointing out contradictions often indicates fail. +4) Last task in the rollout: + - Treat the final task more conservatively than earlier tasks. + - If there is no explicit user feedback or environment validation for the final task, + prefer `uncertain` (or `partial` if there was obvious progress but no confirmation). + - For non-final tasks, switching to another task without unresolved blockers is a stronger + positive signal. + +Signal priority: +- Explicit user feedback and explicit environment/test/tool validation outrank all heuristics. +- If heuristic signals conflict with explicit feedback, follow explicit feedback. Fallback heuristics: - Success: explicit "done/works", tests pass, correct artifact produced, user @@ -152,6 +162,8 @@ This summary should be very comprehensive and detailed, because it will be furth distilled into MEMORY.md and memory_summary.md. There is no strict size limit, and you should feel free to list a lot of points here as long as they are helpful. +Do not target fixed counts (tasks, bullets, references, or topics). Let the rollout's +signal density decide how much to write. Instructional notes in angle brackets are guidance only; do not include them verbatim in the rollout summary. Template (items are flexible; include only what is useful): @@ -170,7 +182,7 @@ User preferences: -## Task : +## Task : Outcome: Key steps: @@ -188,9 +200,9 @@ Things that did not work / things that can be improved: user approval."> - ... -Reusable knowledge: +Reusable knowledge: - - : - [3] final verification evidence or explicit user feedback -## Task (if there are multiple tasks): +## Task (if there are multiple tasks): ... +Task section quality bar (strict): +- Each task section should be detailed enough that other agent can understand it without + reopening the raw rollout. +- For each task, cover the following when evidence exists (and state uncertainty when it + does not): + - what the user wanted / expected, + - what was attempted and what actually worked, + - what failed or remained uncertain and why, + - how the outcome was validated (user feedback, tests, tool output, or explicit lack of validation), + - reusable procedure/checklist and failure shields, + - concrete artifacts/commands/paths/error signatures that future agents can reuse. +- Do not be terse in task sections. Rich, evidence-backed task summaries are preferred + over compact summaries. + ============================================================ `raw_memory` FORMAT (STRICT) ============================================================ The schema is below. --- -rollout_summary_file: -description: brief description of the task and outcome +description: concise but information-dense description of the primary task(s), outcome, and highest-value takeaway +task: +task_group: +task_outcome: keywords: k1, k2, k3, ... --- -- + +Then write task-grouped body content (required): +### Task 1: +task: +task_group: +task_outcome: +- - ... +### Task 2: (if needed) +task: ... +task_group: ... +task_outcome: ... +- ... + +Preferred task-block body shape (strongly recommended): +- `### Task ` blocks should preserve task-specific retrieval signal and consolidation-ready detail. +- Within each task block, include bullets that explicitly cover (when applicable): + - user goal / expected outcome, + - what worked (key steps, commands, code paths, artifacts), + - what did not work or drifted (and what pivot worked), + - validation state (user confirmation, tests, runtime checks, or missing validation), + - reusable procedure/checklist and failure shields, + - high-signal evidence pointers (error strings, commands, files, IDs, URLs, etc.). +- Prefer labeled bullets when useful (for example: `- User goal: ...`, `- Validation: ...`, + `- Failure shield: ...`) so Phase 2 can retrieve and consolidate faster. + +Task grouping rules (strict): +- Every distinct user task in the thread must appear as its own `### Task ` block. +- Do not merge unrelated tasks into one block just because they happen in the same thread. +- If a thread contains only one task, keep exactly one task block. +- For each task block, keep the outcome tied to evidence relevant to that task. +- If a thread has partially related tasks, prefer splitting into separate task blocks and + linking them through shared keywords rather than merging. + What to write in memory entries: Extract useful takeaways from the rollout summaries, especially from "User preferences", "Reusable knowledge", "References", and "Things that did not work / things that can be improved". @@ -249,10 +309,17 @@ Write what would help a future agent doing a similar (or adjacent) task: decisio triggers, key steps, proven commands/paths, and failure shields (symptom -> cause -> fix), plus any stable user preferences. If a rollout summary contains stable user profile details or preferences that generalize, -capture them here so they're easy to find and can be reflected in memory_summary.md. +capture them here so they're easy to find without checking rollout summary. The goal is to support related-but-not-identical future tasks, so keep insights slightly more general; when a future task is very similar, expect the agent to use the rollout summary for full detail. +For each task block, include enough detail to be useful for future agent reference: +- what the user wanted and expected, +- what was attempted and what actually worked, +- what failed or remained uncertain and why, +- what evidence validates the outcome (user feedback, environment/test feedback, or lack of both), +- reusable procedures/checklists and failure shields that should survive future similar tasks, +- artifacts and retrieval handles (commands, file paths, error strings, IDs) that make the task easy to rediscover. ============================================================ @@ -264,4 +331,6 @@ WORKFLOW 1) Triage outcome using the common rules. 2) Read the rollout carefully (do not miss user messages/tool calls/outputs). 3) Return `rollout_summary`, `rollout_slug`, and `raw_memory`, valid JSON only. - No markdown wrapper, no prose outside JSON. \ No newline at end of file + No markdown wrapper, no prose outside JSON. + +- Do not be terse in task sections. Include validation signal, failure mode, and reusable procedure per task when available. From a7632f68a67c0a9bdd1d3e305012a6a708518544 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 09:25:35 +0000 Subject: [PATCH 004/385] Set memories phase reasoning effort constants (#12309) ## Summary - add reasoning effort constants for the memories phase one and phase two agents - wire the constants into phase1 request creation and phase2 agent configuration so the default efforts are always applied ## Testing - Not run (not requested) --- codex-rs/core/src/memories/mod.rs | 6 ++++++ codex-rs/core/src/memories/phase1.rs | 2 +- codex-rs/core/src/memories/phase2.rs | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/memories/mod.rs b/codex-rs/core/src/memories/mod.rs index cab19915df..1f892646ce 100644 --- a/codex-rs/core/src/memories/mod.rs +++ b/codex-rs/core/src/memories/mod.rs @@ -13,6 +13,8 @@ mod storage; mod tests; pub(crate) mod usage; +use codex_protocol::openai_models::ReasoningEffort; + /// Starts the memory startup pipeline for eligible root sessions. /// This is the single entrypoint that `codex` uses to trigger memory startup. /// @@ -28,6 +30,8 @@ mod artifacts { mod phase_one { /// Default model used for phase 1. pub(super) const MODEL: &str = "gpt-5.1-codex-mini"; + /// Default reasoning effort used for phase 1. + pub(super) const REASONING_EFFORT: super::ReasoningEffort = super::ReasoningEffort::Low; /// Prompt used for phase 1. pub(super) const PROMPT: &str = include_str!("../../templates/memories/stage_one_system.md"); /// Concurrency cap for startup memory extraction and consolidation scheduling. @@ -56,6 +60,8 @@ mod phase_one { mod phase_two { /// Default model used for phase 2. pub(super) const MODEL: &str = "gpt-5.3-codex"; + /// Default reasoning effort used for phase 2. + pub(super) const REASONING_EFFORT: super::ReasoningEffort = super::ReasoningEffort::Medium; /// Lease duration (seconds) for phase-2 consolidation job ownership. pub(super) const JOB_LEASE_SECONDS: i64 = 3_600; /// Backoff delay (seconds) before retrying a failed phase-2 consolidation diff --git a/codex-rs/core/src/memories/phase1.rs b/codex-rs/core/src/memories/phase1.rs index 36be849c14..b356f61b38 100644 --- a/codex-rs/core/src/memories/phase1.rs +++ b/codex-rs/core/src/memories/phase1.rs @@ -142,7 +142,7 @@ impl RequestContext { model_info, turn_metadata_header, otel_manager: turn_context.otel_manager.clone(), - reasoning_effort: turn_context.reasoning_effort, + reasoning_effort: Some(phase_one::REASONING_EFFORT), reasoning_summary: turn_context.reasoning_summary, } } diff --git a/codex-rs/core/src/memories/phase2.rs b/codex-rs/core/src/memories/phase2.rs index aa17cc1585..ec8c36249d 100644 --- a/codex-rs/core/src/memories/phase2.rs +++ b/codex-rs/core/src/memories/phase2.rs @@ -258,6 +258,7 @@ mod agent { .clone() .unwrap_or(phase_two::MODEL.to_string()), ); + agent_config.model_reasoning_effort = Some(phase_two::REASONING_EFFORT); Some(agent_config) } From 03ff04cd658bc34750ab74d2041e616d8aa6bb33 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 11:24:28 +0000 Subject: [PATCH 005/385] chore: nit explorer (#12315) --- codex-rs/core/src/agent/builtins/explorer.toml | 2 -- codex-rs/core/src/agent/role.rs | 6 +++--- codex-rs/core/src/tools/handlers/multi_agents.rs | 1 + 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/agent/builtins/explorer.toml b/codex-rs/core/src/agent/builtins/explorer.toml index 0b6def0323..e69de29bb2 100644 --- a/codex-rs/core/src/agent/builtins/explorer.toml +++ b/codex-rs/core/src/agent/builtins/explorer.toml @@ -1,2 +0,0 @@ -model = "gpt-5.1-codex-mini" -model_reasoning_effort = "medium" diff --git a/codex-rs/core/src/agent/role.rs b/codex-rs/core/src/agent/role.rs index 97cde2c8a3..16460fb7fd 100644 --- a/codex-rs/core/src/agent/role.rs +++ b/codex-rs/core/src/agent/role.rs @@ -162,11 +162,10 @@ mod built_in { ( "explorer".to_string(), AgentRoleConfig { - description: Some(r#"Use `explorer` for all codebase questions. + description: Some(r#"Use `explorer` for specific codebase questions. Explorers are fast and authoritative. -Always prefer them over manual search or file reading. +They must be used to ask specific, well-scoped questions on the codebase. Rules: -- Ask explorers first and precisely. - Do not re-read or re-search code they cover. - Trust explorer results without verification. - Run explorers in parallel when useful. @@ -268,6 +267,7 @@ mod tests { } #[tokio::test] + #[ignore = "No role requiring it for now"] async fn apply_explorer_role_sets_model_and_adds_session_flags_layer() { let (_home, mut config) = test_config_with_cli_overrides(Vec::new()).await; let before_layers = session_flags_layer_count(&config); diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 2180574cc5..38aa22b6c4 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -990,6 +990,7 @@ mod tests { } #[tokio::test] + #[ignore = "No role requiring it for now"] async fn spawn_agent_uses_explorer_role_and_sets_never_approval_policy() { #[derive(Debug, Deserialize)] struct SpawnAgentResult { From 0f9eed3a6f479395520fcd7aceb9fc5b2f3f3754 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 14:39:49 +0000 Subject: [PATCH 006/385] feat: add nick name to sub-agents (#12320) Adding random nick name to sub-agents. Used for UX At the same time, also storing and wiring the role of the sub-agent --- .../schema/json/ServerNotification.json | 28 ++ .../codex_app_server_protocol.schemas.json | 42 +++ .../v1/GetConversationSummaryResponse.json | 14 + .../json/v1/ListConversationsResponse.json | 14 + .../schema/json/v2/ThreadForkResponse.json | 28 ++ .../schema/json/v2/ThreadListResponse.json | 28 ++ .../schema/json/v2/ThreadReadResponse.json | 28 ++ .../schema/json/v2/ThreadResumeResponse.json | 28 ++ .../json/v2/ThreadRollbackResponse.json | 28 ++ .../schema/json/v2/ThreadStartResponse.json | 28 ++ .../json/v2/ThreadStartedNotification.json | 28 ++ .../json/v2/ThreadUnarchiveResponse.json | 28 ++ .../schema/typescript/SubAgentSource.ts | 2 +- .../schema/typescript/v2/Thread.ts | 8 + .../app-server-protocol/src/protocol/v2.rs | 4 + codex-rs/app-server/README.md | 5 +- .../app-server/src/codex_message_processor.rs | 86 +++++- codex-rs/app-server/src/filters.rs | 2 + codex-rs/app-server/src/thread_status.rs | 2 + codex-rs/app-server/tests/common/rollout.rs | 4 + .../app-server/tests/suite/v2/thread_list.rs | 4 + codex-rs/core/src/agent/agent_names.txt | 100 +++++++ codex-rs/core/src/agent/control.rs | 274 ++++++++++++++++-- codex-rs/core/src/agent/guards.rs | 182 +++++++++++- codex-rs/core/src/personality_migration.rs | 2 + codex-rs/core/src/rollout/list.rs | 14 +- codex-rs/core/src/rollout/metadata.rs | 6 + codex-rs/core/src/rollout/recorder.rs | 7 +- codex-rs/core/src/rollout/tests.rs | 26 ++ .../core/src/tools/handlers/multi_agents.rs | 52 ++-- .../core/tests/suite/personality_migration.rs | 4 + codex-rs/core/tests/suite/sqlite_state.rs | 2 + codex-rs/protocol/src/protocol.rs | 33 +++ .../0013_threads_agent_nickname.sql | 2 + codex-rs/state/src/extract.rs | 4 + codex-rs/state/src/model/thread_metadata.rs | 26 ++ codex-rs/state/src/runtime.rs | 14 +- codex-rs/state/src/runtime/memories.rs | 2 + codex-rs/tui/src/resume_picker.rs | 45 +-- 39 files changed, 1125 insertions(+), 109 deletions(-) create mode 100644 codex-rs/core/src/agent/agent_names.txt create mode 100644 codex-rs/state/migrations/0013_threads_agent_nickname.sql diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index f18531303e..128f4fa60d 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -6377,6 +6377,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -6524,6 +6538,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 39b21d0a54..ea4cd0bd3a 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -9431,6 +9431,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -15092,6 +15106,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -15218,6 +15246,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json b/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json index a54b7ddac1..13cdf0b0f8 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json @@ -123,6 +123,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" diff --git a/codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json index bb5a0f4861..2e3ab7e0dc 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json @@ -123,6 +123,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 2dfc446ac2..dad39a512a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -716,6 +716,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -777,6 +791,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index 2ab535625b..80a1d42a23 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -489,6 +489,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -550,6 +564,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index 8aa8b0c4fb..a4810d5850 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -489,6 +489,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -550,6 +564,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 2343766326..c4e1df8478 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -716,6 +716,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -777,6 +791,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index 4821029283..f8cdcd744c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -489,6 +489,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -550,6 +564,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 1b617a8508..099a65d219 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -716,6 +716,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -777,6 +791,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index 6f016b0c77..9927bb2f3c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -489,6 +489,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -550,6 +564,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index a49a3a8f95..011a97a34c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -489,6 +489,20 @@ "properties": { "thread_spawn": { "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, "depth": { "format": "int32", "type": "integer" @@ -550,6 +564,20 @@ }, "Thread": { "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, "cliVersion": { "description": "Version of the CLI that created the thread.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/typescript/SubAgentSource.ts b/codex-rs/app-server-protocol/schema/typescript/SubAgentSource.ts index 269a411be9..df261bf3ea 100644 --- a/codex-rs/app-server-protocol/schema/typescript/SubAgentSource.ts +++ b/codex-rs/app-server-protocol/schema/typescript/SubAgentSource.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ThreadId } from "./ThreadId"; -export type SubAgentSource = "review" | "compact" | { "thread_spawn": { parent_thread_id: ThreadId, depth: number, } } | "memory_consolidation" | { "other": string }; +export type SubAgentSource = "review" | "compact" | { "thread_spawn": { parent_thread_id: ThreadId, depth: number, agent_nickname: string | null, agent_role: string | null, } } | "memory_consolidation" | { "other": string }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts index 523a028583..5e7a6b7af4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts @@ -43,6 +43,14 @@ cliVersion: string, * Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.). */ source: SessionSource, +/** + * Optional random unique nickname assigned to an AgentControl-spawned sub-agent. + */ +agentNickname: string | null, +/** + * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + */ +agentRole: string | null, /** * Optional Git metadata captured when the thread was created. */ diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 6a1959bb25..fb2f86931e 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2206,6 +2206,10 @@ pub struct Thread { pub cli_version: String, /// Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.). pub source: SessionSource, + /// Optional random unique nickname assigned to an AgentControl-spawned sub-agent. + pub agent_nickname: Option, + /// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + pub agent_role: Option, /// Optional Git metadata captured when the thread was created. pub git_info: Option, /// Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index fcae5b3069..3d3cc18a9f 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -224,6 +224,7 @@ Experimental API: `thread/start`, `thread/resume`, and `thread/fork` accept `per - `sourceKinds` — restrict results to specific sources; omit or pass `[]` for interactive sessions only (`cli`, `vscode`). - `archived` — when `true`, list archived threads only. When `false` or `null`, list non-archived threads (default). - `cwd` — restrict results to threads whose session cwd exactly matches this path. +- Responses include `agentNickname` and `agentRole` for AgentControl-spawned thread sub-agents when available. Example: @@ -235,7 +236,7 @@ Example: } } { "id": 20, "result": { "data": [ - { "id": "thr_a", "preview": "Create a TUI", "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "status": { "type": "notLoaded" } }, + { "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" } } ], "nextCursor": "opaque-token-or-null" @@ -271,7 +272,7 @@ When `nextCursor` is `null`, you’ve reached the final page. ### Example: Read a thread -Use `thread/read` to fetch a stored thread by id without resuming it. Pass `includeTurns` when you want the rollout history loaded into `thread.turns`. +Use `thread/read` to fetch a stored thread by id without resuming it. Pass `includeTurns` when you want the rollout history loaded into `thread.turns`. The returned thread includes `agentNickname` and `agentRole` for AgentControl-spawned thread sub-agents when available. ```json { "method": "thread/read", "id": 22, "params": { "threadId": "thr_123" } } diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index ea2701d635..44444494df 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -6658,6 +6658,8 @@ async fn read_summary_from_state_db_context_by_thread_id( metadata.cwd, metadata.cli_version, metadata.source, + metadata.agent_nickname, + metadata.agent_role, metadata.git_sha, metadata.git_branch, metadata.git_origin_url, @@ -6678,9 +6680,12 @@ async fn summary_from_thread_list_item( .unwrap_or_else(|| fallback_provider.to_string()); let cwd = it.cwd?; let cli_version = it.cli_version.unwrap_or_default(); - let source = it - .source - .unwrap_or(codex_protocol::protocol::SessionSource::Unknown); + let source = with_thread_spawn_agent_metadata( + it.source + .unwrap_or(codex_protocol::protocol::SessionSource::Unknown), + it.agent_nickname.clone(), + it.agent_role.clone(), + ); return Some(ConversationSummary { conversation_id: thread_id, path: it.path, @@ -6735,13 +6740,17 @@ fn summary_from_state_db_metadata( cwd: PathBuf, cli_version: String, source: String, + agent_nickname: Option, + agent_role: Option, git_sha: Option, git_branch: Option, git_origin_url: Option, ) -> ConversationSummary { let preview = first_user_message.unwrap_or_default(); - let source = serde_json::from_value(serde_json::Value::String(source)) + let source = serde_json::from_str(&source) + .or_else(|_| serde_json::from_value(serde_json::Value::String(source.clone()))) .unwrap_or(codex_protocol::protocol::SessionSource::Unknown); + let source = with_thread_spawn_agent_metadata(source, agent_nickname, agent_role); let git_info = if git_sha.is_none() && git_branch.is_none() && git_origin_url.is_none() { None } else { @@ -6901,6 +6910,35 @@ fn map_git_info(git_info: &CoreGitInfo) -> ConversationGitInfo { } } +fn with_thread_spawn_agent_metadata( + source: codex_protocol::protocol::SessionSource, + agent_nickname: Option, + agent_role: Option, +) -> codex_protocol::protocol::SessionSource { + if agent_nickname.is_none() && agent_role.is_none() { + return source; + } + + match source { + codex_protocol::protocol::SessionSource::SubAgent( + codex_protocol::protocol::SubAgentSource::ThreadSpawn { + parent_thread_id, + depth, + agent_nickname: existing_agent_nickname, + agent_role: existing_agent_role, + }, + ) => codex_protocol::protocol::SessionSource::SubAgent( + codex_protocol::protocol::SubAgentSource::ThreadSpawn { + parent_thread_id, + depth, + agent_nickname: agent_nickname.or(existing_agent_nickname), + agent_role: agent_role.or(existing_agent_role), + }, + ), + _ => source, + } +} + fn parse_datetime(timestamp: Option<&str>) -> Option> { timestamp.and_then(|ts| { chrono::DateTime::parse_from_rfc3339(ts) @@ -6937,6 +6975,8 @@ fn build_thread_from_snapshot( path, cwd: config_snapshot.cwd.clone(), cli_version: env!("CARGO_PKG_VERSION").to_string(), + agent_nickname: config_snapshot.session_source.get_nickname(), + agent_role: config_snapshot.session_source.get_agent_role(), source: config_snapshot.session_source.clone().into(), git_info: None, turns: Vec::new(), @@ -6975,6 +7015,8 @@ pub(crate) fn summary_to_thread(summary: ConversationSummary) -> Thread { path: Some(path), cwd, cli_version, + agent_nickname: source.get_nickname(), + agent_role: source.get_agent_role(), source: source.into(), git_info, turns: Vec::new(), @@ -6986,6 +7028,7 @@ mod tests { use super::*; use anyhow::Result; use codex_protocol::protocol::SessionSource; + use codex_protocol::protocol::SubAgentSource; use pretty_assertions::assert_eq; use serde_json::json; use std::path::PathBuf; @@ -7131,6 +7174,41 @@ mod tests { Ok(()) } + #[test] + fn summary_from_state_db_metadata_preserves_agent_nickname() -> Result<()> { + let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; + let source = + serde_json::to_string(&SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?, + depth: 1, + agent_nickname: None, + agent_role: None, + }))?; + + let summary = summary_from_state_db_metadata( + conversation_id, + PathBuf::from("/tmp/rollout.jsonl"), + Some("hi".to_string()), + "2025-09-05T16:53:11Z".to_string(), + "2025-09-05T16:53:12Z".to_string(), + "test-provider".to_string(), + PathBuf::from("/"), + "0.0.0".to_string(), + source, + Some("atlas".to_string()), + Some("explorer".to_string()), + None, + None, + None, + ); + + let thread = summary_to_thread(summary); + + assert_eq!(thread.agent_nickname, Some("atlas".to_string())); + assert_eq!(thread.agent_role, Some("explorer".to_string())); + Ok(()) + } + #[tokio::test] async fn removing_one_listener_does_not_cancel_other_subscriptions_for_same_thread() -> Result<()> { diff --git a/codex-rs/app-server/src/filters.rs b/codex-rs/app-server/src/filters.rs index bd784c3dcc..a597509612 100644 --- a/codex-rs/app-server/src/filters.rs +++ b/codex-rs/app-server/src/filters.rs @@ -133,6 +133,8 @@ mod tests { let spawn = CoreSessionSource::SubAgent(CoreSubAgentSource::ThreadSpawn { parent_thread_id, depth: 1, + agent_nickname: None, + agent_role: None, }); assert!(source_kind_matches( diff --git a/codex-rs/app-server/src/thread_status.rs b/codex-rs/app-server/src/thread_status.rs index 7576791d37..301c4b1d07 100644 --- a/codex-rs/app-server/src/thread_status.rs +++ b/codex-rs/app-server/src/thread_status.rs @@ -622,6 +622,8 @@ mod tests { path: None, cwd: PathBuf::from("/tmp"), cli_version: "test".to_string(), + agent_nickname: None, + agent_role: None, source, git_info: None, turns: Vec::new(), diff --git a/codex-rs/app-server/tests/common/rollout.rs b/codex-rs/app-server/tests/common/rollout.rs index 14dce02c64..8122e7cd01 100644 --- a/codex-rs/app-server/tests/common/rollout.rs +++ b/codex-rs/app-server/tests/common/rollout.rs @@ -79,6 +79,8 @@ pub fn create_fake_rollout_with_source( originator: "codex".to_string(), cli_version: "0.0.0".to_string(), source, + agent_nickname: None, + agent_role: None, model_provider: model_provider.map(str::to_string), base_instructions: None, dynamic_tools: None, @@ -158,6 +160,8 @@ pub fn create_fake_rollout_with_text_elements( originator: "codex".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::Cli, + agent_nickname: None, + agent_role: None, model_provider: model_provider.map(str::to_string), base_instructions: None, dynamic_tools: None, diff --git a/codex-rs/app-server/tests/suite/v2/thread_list.rs b/codex-rs/app-server/tests/suite/v2/thread_list.rs index 46e1d170f6..1f6e0627eb 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_list.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_list.rs @@ -582,6 +582,8 @@ async fn thread_list_filters_by_source_kind_subagent_thread_spawn() -> Result<() CoreSessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, depth: 1, + agent_nickname: None, + agent_role: None, }), )?; @@ -643,6 +645,8 @@ async fn thread_list_filters_by_subagent_variant() -> Result<()> { CoreSessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, depth: 1, + agent_nickname: None, + agent_role: None, }), )?; let other_id = create_fake_rollout_with_source( diff --git a/codex-rs/core/src/agent/agent_names.txt b/codex-rs/core/src/agent/agent_names.txt new file mode 100644 index 0000000000..6b6846193a --- /dev/null +++ b/codex-rs/core/src/agent/agent_names.txt @@ -0,0 +1,100 @@ +Atlas +Nova +Orion +Iris +Milo +Juno +Mars +Vesta +Luna +Sol +Eros +Nyx +Zeus +Hera +Ares +Ajax +Echo +Leto +Rhea +Gaia +Hades +Apollo +Pallas +Circe +Nereus +Triton +Selene +Helios +Castor +Pollux +Astra +Aura +Thalia +Clio +Erato +Euterpe +Urania +Calliope +Minos +Linus +Cato +Brutus +Seneca +Ovid +Virgil +Horace +Remus +Romulus +Titus +Lucian +Felix +Maximus +Octavia +Claudia +Livia +Aelia +Aurel +Cassia +Sabina +Flavia +Numa +Ceres +Diana +Venus +Pluto +Pan +Ramius +Aether +Chaos +Logos +Ethos +Tethys +Chiron +Talos +Icarus +Daedalus +Hyacinth +Adonis +Perseus +Theseus +Argos +Lemnos +Delos +Sparta +Attica +Corinth +Thebes +Ephyra +Achaea +Cyrene +Sidon +Tyre +Ilium +Etrus +Vercos +Aurex +Novian +Helion +Casson +Aurelix \ No newline at end of file diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 847bb7f761..a9ddde6324 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -3,7 +3,9 @@ use crate::agent::guards::Guards; use crate::agent::status::is_final; use crate::error::CodexErr; use crate::error::Result as CodexResult; +use crate::find_thread_path_by_id_str; use crate::session_prefix::format_subagent_notification_message; +use crate::state_db; use crate::thread_manager::ThreadManagerState; use codex_protocol::ThreadId; use codex_protocol::protocol::Op; @@ -11,11 +13,20 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::TokenUsage; use codex_protocol::user_input::UserInput; -use std::path::PathBuf; use std::sync::Arc; use std::sync::Weak; use tokio::sync::watch; +const AGENT_NAMES: &str = include_str!("agent_names.txt"); + +fn agent_nickname_list() -> Vec<&'static str> { + AGENT_NAMES + .lines() + .map(str::trim) + .filter(|name| !name.is_empty()) + .collect() +} + /// Control-plane handle for multi-agent operations. /// `AgentControl` is held by each session (via `SessionServices`). It provides capability to /// spawn new agents and the inter-agent communication layer. @@ -48,7 +59,24 @@ impl AgentControl { session_source: Option, ) -> CodexResult { let state = self.upgrade()?; - let reservation = self.state.reserve_spawn_slot(config.agent_max_threads)?; + let mut reservation = self.state.reserve_spawn_slot(config.agent_max_threads)?; + let session_source = match session_source { + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth, + agent_role, + .. + })) => { + let agent_nickname = reservation.reserve_agent_nickname(&agent_nickname_list())?; + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth, + agent_nickname: Some(agent_nickname), + agent_role, + })) + } + other => other, + }; let notification_source = session_source.clone(); // The same `AgentControl` is sent to spawn the thread. @@ -77,12 +105,51 @@ impl AgentControl { pub(crate) async fn resume_agent_from_rollout( &self, config: crate::config::Config, - rollout_path: PathBuf, + thread_id: ThreadId, session_source: SessionSource, ) -> CodexResult { let state = self.upgrade()?; - let reservation = self.state.reserve_spawn_slot(config.agent_max_threads)?; + let mut reservation = self.state.reserve_spawn_slot(config.agent_max_threads)?; + let session_source = match session_source { + SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth, + .. + }) => { + // Collab resume callers rebuild a placeholder ThreadSpawn source. Rehydrate the + // stored nickname/role from sqlite when available; otherwise leave both unset. + let (resumed_agent_nickname, resumed_agent_role) = + if let Some(state_db_ctx) = state_db::get_state_db(&config, None).await { + match state_db_ctx.get_thread(thread_id).await { + Ok(Some(metadata)) => (metadata.agent_nickname, metadata.agent_role), + Ok(None) | Err(_) => (None, None), + } + } else { + (None, None) + }; + let reserved_agent_nickname = resumed_agent_nickname + .as_deref() + .map(|agent_nickname| { + reservation.reserve_agent_nickname_with_preference( + &agent_nickname_list(), + Some(agent_nickname), + ) + }) + .transpose()?; + SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth, + agent_nickname: reserved_agent_nickname, + agent_role: resumed_agent_role, + }) + } + other => other, + }; let notification_source = session_source.clone(); + let rollout_path = + find_thread_path_by_id_str(config.codex_home.as_path(), &thread_id.to_string()) + .await? + .ok_or_else(|| CodexErr::ThreadNotFound(thread_id))?; let resumed_thread = state .resume_thread_from_rollout_with_source( @@ -234,6 +301,8 @@ mod tests { use crate::agent::agent_status_from_event; use crate::config::Config; use crate::config::ConfigBuilder; + use crate::config_loader::LoaderOverrides; + use crate::features::Feature; use crate::session_prefix::SUBAGENT_NOTIFICATION_OPEN_TAG; use assert_matches::assert_matches; use codex_protocol::config_types::ModeKind; @@ -261,6 +330,12 @@ mod tests { let config = ConfigBuilder::default() .codex_home(home.path().to_path_buf()) .cli_overrides(cli_overrides) + .loader_overrides(LoaderOverrides { + #[cfg(target_os = "macos")] + managed_preferences_base64: Some(String::new()), + macos_managed_config_requirements_base64: Some(String::new()), + ..LoaderOverrides::default() + }) .build() .await .expect("load default test config"); @@ -441,11 +516,7 @@ mod tests { let control = AgentControl::default(); let (_home, config) = test_config().await; let err = control - .resume_agent_from_rollout( - config, - PathBuf::from("/tmp/missing-rollout.jsonl"), - SessionSource::Exec, - ) + .resume_agent_from_rollout(config, ThreadId::new(), SessionSource::Exec) .await .expect_err("resume_agent should fail without a manager"); assert_eq!( @@ -717,12 +788,6 @@ mod tests { .spawn_agent(config.clone(), text_input("hello"), None) .await .expect("spawn_agent should succeed"); - let rollout_path = manager - .get_thread(resumable_id) - .await - .expect("thread should exist") - .rollout_path() - .expect("rollout path should exist"); let _ = control .shutdown_agent(resumable_id) .await @@ -734,7 +799,7 @@ mod tests { .expect("spawn_agent should succeed for active slot"); let err = control - .resume_agent_from_rollout(config, rollout_path, SessionSource::Exec) + .resume_agent_from_rollout(config, resumable_id, SessionSource::Exec) .await .expect_err("resume should respect max threads"); let CodexErr::AgentLimitReached { @@ -766,9 +831,8 @@ mod tests { ); let control = manager.agent_control(); - let missing_rollout = config.codex_home.join("sessions/missing-rollout.jsonl"); let _ = control - .resume_agent_from_rollout(config.clone(), missing_rollout, SessionSource::Exec) + .resume_agent_from_rollout(config.clone(), ThreadId::new(), SessionSource::Exec) .await .expect_err("resume should fail for missing rollout path"); @@ -795,6 +859,8 @@ mod tests { Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, depth: 1, + agent_nickname: None, + agent_role: Some("explorer".to_string()), })), ) .await @@ -812,4 +878,176 @@ mod tests { assert_eq!(wait_for_subagent_notification(&parent_thread).await, true); } + + #[tokio::test] + async fn spawn_thread_subagent_gets_random_nickname_in_session_source() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, _parent_thread) = harness.start_thread().await; + + let child_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello child"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: Some("explorer".to_string()), + })), + ) + .await + .expect("child spawn should succeed"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + let snapshot = child_thread.config_snapshot().await; + + let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: seen_parent_thread_id, + depth, + agent_nickname, + agent_role, + }) = snapshot.session_source + else { + panic!("expected thread-spawn sub-agent source"); + }; + assert_eq!(seen_parent_thread_id, parent_thread_id); + assert_eq!(depth, 1); + assert!(agent_nickname.is_some()); + assert_eq!(agent_role, Some("explorer".to_string())); + } + + #[tokio::test] + async fn resume_thread_subagent_restores_stored_nickname_and_role() { + let (home, mut config) = test_config().await; + config.features.enable(Feature::Sqlite); + let manager = ThreadManager::with_models_provider_and_home_for_tests( + CodexAuth::from_api_key("dummy"), + config.model_provider.clone(), + config.codex_home.clone(), + ); + let control = manager.agent_control(); + let harness = AgentControlHarness { + _home: home, + config, + manager, + control, + }; + let (parent_thread_id, _parent_thread) = harness.start_thread().await; + + let child_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello child"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: Some("explorer".to_string()), + })), + ) + .await + .expect("child spawn should succeed"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should exist"); + let mut status_rx = harness + .control + .subscribe_status(child_thread_id) + .await + .expect("status subscription should succeed"); + if matches!(status_rx.borrow().clone(), AgentStatus::PendingInit) { + timeout(Duration::from_secs(5), async { + loop { + status_rx + .changed() + .await + .expect("child status should advance past pending init"); + if !matches!(status_rx.borrow().clone(), AgentStatus::PendingInit) { + break; + } + } + }) + .await + .expect("child should initialize before shutdown"); + } + let original_snapshot = child_thread.config_snapshot().await; + let original_nickname = original_snapshot + .session_source + .get_nickname() + .expect("spawned sub-agent should have a nickname"); + let state_db = child_thread + .state_db() + .expect("sqlite state db should be available for nickname resume test"); + timeout(Duration::from_secs(5), async { + loop { + if let Ok(Some(metadata)) = state_db.get_thread(child_thread_id).await + && metadata.agent_nickname.is_some() + && metadata.agent_role.as_deref() == Some("explorer") + { + break; + } + sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("child thread metadata should be persisted to sqlite before shutdown"); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + + let resumed_thread_id = harness + .control + .resume_agent_from_rollout( + harness.config.clone(), + child_thread_id, + SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + }), + ) + .await + .expect("resume should succeed"); + assert_eq!(resumed_thread_id, child_thread_id); + + let resumed_snapshot = harness + .manager + .get_thread(resumed_thread_id) + .await + .expect("resumed child thread should exist") + .config_snapshot() + .await; + let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: resumed_parent_thread_id, + depth: resumed_depth, + agent_nickname: resumed_nickname, + agent_role: resumed_role, + }) = resumed_snapshot.session_source + else { + panic!("expected thread-spawn sub-agent source"); + }; + assert_eq!(resumed_parent_thread_id, parent_thread_id); + assert_eq!(resumed_depth, 1); + assert_eq!(resumed_nickname, Some(original_nickname)); + assert_eq!(resumed_role, Some("explorer".to_string())); + + let _ = harness + .control + .shutdown_agent(resumed_thread_id) + .await + .expect("resumed child shutdown should submit"); + } } diff --git a/codex-rs/core/src/agent/guards.rs b/codex-rs/core/src/agent/guards.rs index 1964169cd7..223373c6df 100644 --- a/codex-rs/core/src/agent/guards.rs +++ b/codex-rs/core/src/agent/guards.rs @@ -3,6 +3,8 @@ use crate::error::Result; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; +use rand::prelude::IndexedRandom; +use std::collections::HashMap; use std::collections::HashSet; use std::sync::Arc; use std::sync::Mutex; @@ -17,10 +19,18 @@ use std::sync::atomic::Ordering; /// is). #[derive(Default)] pub(crate) struct Guards { - threads_set: Mutex>, + active_agents: Mutex, total_count: AtomicUsize, } +#[derive(Default)] +struct ActiveAgents { + threads_set: HashSet, + thread_agent_nicknames: HashMap, + used_agent_nicknames: HashSet, + nickname_reset_count: usize, +} + fn session_depth(session_source: &SessionSource) -> i32 { match session_source { SessionSource::SubAgent(SubAgentSource::ThreadSpawn { depth, .. }) => *depth, @@ -52,28 +62,69 @@ impl Guards { Ok(SpawnReservation { state: Arc::clone(self), active: true, + reserved_agent_nickname: None, }) } pub(crate) fn release_spawned_thread(&self, thread_id: ThreadId) { let removed = { - let mut threads = self - .threads_set + let mut active_agents = self + .active_agents .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - threads.remove(&thread_id) + let removed = active_agents.threads_set.remove(&thread_id); + active_agents.thread_agent_nicknames.remove(&thread_id); + removed }; if removed { self.total_count.fetch_sub(1, Ordering::AcqRel); } } - fn register_spawned_thread(&self, thread_id: ThreadId) { - let mut threads = self - .threads_set + fn register_spawned_thread(&self, thread_id: ThreadId, agent_nickname: Option) { + let mut active_agents = self + .active_agents .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - threads.insert(thread_id); + active_agents.threads_set.insert(thread_id); + if let Some(agent_nickname) = agent_nickname { + active_agents + .used_agent_nicknames + .insert(agent_nickname.clone()); + active_agents + .thread_agent_nicknames + .insert(thread_id, agent_nickname); + } + } + + fn reserve_agent_nickname(&self, names: &[&str], preferred: Option<&str>) -> Option { + let mut active_agents = self + .active_agents + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let agent_nickname = if let Some(preferred) = preferred { + preferred.to_string() + } else { + if names.is_empty() { + return None; + } + let available_names: Vec<&str> = names + .iter() + .copied() + .filter(|name| !active_agents.used_agent_nicknames.contains(*name)) + .collect(); + if let Some(name) = available_names.choose(&mut rand::rng()) { + (*name).to_string() + } else { + active_agents.used_agent_nicknames.clear(); + active_agents.nickname_reset_count += 1; + names.choose(&mut rand::rng())?.to_string() + } + }; + active_agents + .used_agent_nicknames + .insert(agent_nickname.clone()); + Some(agent_nickname) } fn try_increment_spawned(&self, max_threads: usize) -> bool { @@ -98,11 +149,41 @@ impl Guards { pub(crate) struct SpawnReservation { state: Arc, active: bool, + reserved_agent_nickname: Option, } impl SpawnReservation { - pub(crate) fn commit(mut self, thread_id: ThreadId) { - self.state.register_spawned_thread(thread_id); + pub(crate) fn reserve_agent_nickname(&mut self, names: &[&str]) -> Result { + self.reserve_agent_nickname_with_preference(names, None) + } + + pub(crate) fn reserve_agent_nickname_with_preference( + &mut self, + names: &[&str], + preferred: Option<&str>, + ) -> Result { + let agent_nickname = self + .state + .reserve_agent_nickname(names, preferred) + .ok_or_else(|| { + CodexErr::UnsupportedOperation("no available agent nicknames".to_string()) + })?; + self.reserved_agent_nickname = Some(agent_nickname.clone()); + Ok(agent_nickname) + } + + pub(crate) fn commit(self, thread_id: ThreadId) { + self.commit_with_agent_nickname(thread_id, None); + } + + pub(crate) fn commit_with_agent_nickname( + mut self, + thread_id: ThreadId, + agent_nickname: Option, + ) { + let agent_nickname = self.reserved_agent_nickname.take().or(agent_nickname); + self.state + .register_spawned_thread(thread_id, agent_nickname); self.active = false; } } @@ -130,6 +211,8 @@ mod tests { let session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id: ThreadId::new(), depth: 1, + agent_nickname: None, + agent_role: None, }); let child_depth = next_thread_spawn_depth(&session_source); assert_eq!(child_depth, 2); @@ -232,4 +315,83 @@ mod tests { .expect("slot released after second thread removal"); drop(reservation); } + + #[test] + fn failed_spawn_keeps_nickname_marked_used() { + let guards = Arc::new(Guards::default()); + let mut reservation = guards.reserve_spawn_slot(None).expect("reserve slot"); + let agent_nickname = reservation + .reserve_agent_nickname(&["alpha"]) + .expect("reserve agent name"); + assert_eq!(agent_nickname, "alpha"); + drop(reservation); + + let mut reservation = guards.reserve_spawn_slot(None).expect("reserve slot"); + let agent_nickname = reservation + .reserve_agent_nickname(&["alpha", "beta"]) + .expect("unused name should still be preferred"); + assert_eq!(agent_nickname, "beta"); + } + + #[test] + fn agent_nickname_resets_used_pool_when_exhausted() { + let guards = Arc::new(Guards::default()); + let mut first = guards.reserve_spawn_slot(None).expect("reserve first slot"); + let first_name = first + .reserve_agent_nickname(&["alpha"]) + .expect("reserve first agent name"); + let first_id = ThreadId::new(); + first.commit(first_id); + assert_eq!(first_name, "alpha"); + + let mut second = guards + .reserve_spawn_slot(None) + .expect("reserve second slot"); + let second_name = second + .reserve_agent_nickname(&["alpha"]) + .expect("name should be reused after pool reset"); + assert_eq!(second_name, "alpha"); + let active_agents = guards + .active_agents + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(active_agents.nickname_reset_count, 1); + } + + #[test] + fn released_nickname_stays_used_until_pool_reset() { + let guards = Arc::new(Guards::default()); + + let mut first = guards.reserve_spawn_slot(None).expect("reserve first slot"); + let first_name = first + .reserve_agent_nickname(&["alpha"]) + .expect("reserve first agent name"); + let first_id = ThreadId::new(); + first.commit(first_id); + assert_eq!(first_name, "alpha"); + + guards.release_spawned_thread(first_id); + + let mut second = guards + .reserve_spawn_slot(None) + .expect("reserve second slot"); + let second_name = second + .reserve_agent_nickname(&["alpha", "beta"]) + .expect("released name should still be marked used"); + assert_eq!(second_name, "beta"); + let second_id = ThreadId::new(); + second.commit(second_id); + guards.release_spawned_thread(second_id); + + let mut third = guards.reserve_spawn_slot(None).expect("reserve third slot"); + let third_name = third + .reserve_agent_nickname(&["alpha", "beta"]) + .expect("pool reset should permit a duplicate"); + assert!(third_name == "alpha" || third_name == "beta"); + let active_agents = guards + .active_agents + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(active_agents.nickname_reset_count, 1); + } } diff --git a/codex-rs/core/src/personality_migration.rs b/codex-rs/core/src/personality_migration.rs index 4ec78696b6..c207295e96 100644 --- a/codex-rs/core/src/personality_migration.rs +++ b/codex-rs/core/src/personality_migration.rs @@ -172,6 +172,8 @@ mod tests { originator: "test_originator".to_string(), cli_version: "test_version".to_string(), source: SessionSource::Cli, + agent_nickname: None, + agent_role: None, model_provider: None, base_instructions: None, dynamic_tools: None, diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index 9b2b00c78b..8c9ee7afec 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -39,7 +39,7 @@ pub struct ThreadsPage { } /// Summary information for a thread rollout file. -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Default)] pub struct ThreadItem { /// Absolute path to the rollout file. pub path: PathBuf, @@ -57,6 +57,10 @@ pub struct ThreadItem { pub git_origin_url: Option, /// Session source from session metadata. pub source: Option, + /// Random unique nickname from session metadata for AgentControl-spawned sub-agents. + pub agent_nickname: Option, + /// Role (agent_role) from session metadata for AgentControl-spawned sub-agents. + pub agent_role: Option, /// Model provider from session metadata. pub model_provider: Option, /// CLI version from session metadata. @@ -87,6 +91,8 @@ struct HeadTailSummary { git_sha: Option, git_origin_url: Option, source: Option, + agent_nickname: Option, + agent_role: Option, model_provider: Option, cli_version: Option, created_at: Option, @@ -715,6 +721,8 @@ async fn build_thread_item( git_sha, git_origin_url, source, + agent_nickname, + agent_role, model_provider, cli_version, created_at, @@ -733,6 +741,8 @@ async fn build_thread_item( git_sha, git_origin_url, source, + agent_nickname, + agent_role, model_provider, cli_version, created_at, @@ -1017,6 +1027,8 @@ async fn read_head_summary(path: &Path, head_limit: usize) -> io::Result { if !summary.saw_session_meta { summary.source = Some(session_meta_line.meta.source.clone()); + summary.agent_nickname = session_meta_line.meta.agent_nickname.clone(); + summary.agent_role = session_meta_line.meta.agent_role.clone(); summary.model_provider = session_meta_line.meta.model_provider.clone(); summary.thread_id = Some(session_meta_line.meta.id); summary.cwd = Some(session_meta_line.meta.cwd.clone()); diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs index 7298877751..9196931daf 100644 --- a/codex-rs/core/src/rollout/metadata.rs +++ b/codex-rs/core/src/rollout/metadata.rs @@ -47,6 +47,8 @@ pub(crate) fn builder_from_session_meta( session_meta.meta.source.clone(), ); builder.model_provider = session_meta.meta.model_provider.clone(); + builder.agent_nickname = session_meta.meta.agent_nickname.clone(); + builder.agent_role = session_meta.meta.agent_role.clone(); builder.cwd = session_meta.meta.cwd.clone(); builder.cli_version = Some(session_meta.meta.cli_version.clone()); builder.sandbox_policy = SandboxPolicy::new_read_only_policy(); @@ -512,6 +514,8 @@ mod tests { originator: "cli".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::default(), + agent_nickname: None, + agent_role: None, model_provider: Some("openai".to_string()), base_instructions: None, dynamic_tools: None, @@ -660,6 +664,8 @@ mod tests { originator: "cli".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::default(), + agent_nickname: None, + agent_role: None, model_provider: Some("test-provider".to_string()), base_instructions: None, dynamic_tools: None, diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index eab442743e..7e639e382e 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -391,6 +391,8 @@ impl RolloutRecorder { cwd: config.cwd.clone(), originator: originator().value, cli_version: env!("CARGO_PKG_VERSION").to_string(), + agent_nickname: source.get_nickname(), + agent_role: source.get_agent_role(), source, model_provider: Some(config.model_provider_id.clone()), base_instructions: Some(base_instructions), @@ -929,9 +931,12 @@ impl From for ThreadsPage { git_sha: item.git_sha, git_origin_url: item.git_origin_url, source: Some( - serde_json::from_value(Value::String(item.source)) + serde_json::from_str(item.source.as_str()) + .or_else(|_| serde_json::from_value(Value::String(item.source))) .unwrap_or(SessionSource::Unknown), ), + agent_nickname: item.agent_nickname, + agent_role: item.agent_role, model_provider: Some(item.model_provider), cli_version: Some(item.cli_version), created_at: Some(item.created_at.to_rfc3339_opts(SecondsFormat::Secs, true)), diff --git a/codex-rs/core/src/rollout/tests.rs b/codex-rs/core/src/rollout/tests.rs index b97edb0f66..0eabaee745 100644 --- a/codex-rs/core/src/rollout/tests.rs +++ b/codex-rs/core/src/rollout/tests.rs @@ -560,6 +560,8 @@ async fn test_list_conversations_latest_first() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-01-03T12-00-00".into()), @@ -574,6 +576,8 @@ async fn test_list_conversations_latest_first() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-01-02T12-00-00".into()), @@ -588,6 +592,8 @@ async fn test_list_conversations_latest_first() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-01-01T12-00-00".into()), @@ -695,6 +701,8 @@ async fn test_pagination_cursor() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-03-05T09-00-00".into()), @@ -709,6 +717,8 @@ async fn test_pagination_cursor() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-03-04T09-00-00".into()), @@ -759,6 +769,8 @@ async fn test_pagination_cursor() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-03-03T09-00-00".into()), @@ -773,6 +785,8 @@ async fn test_pagination_cursor() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-03-02T09-00-00".into()), @@ -814,6 +828,8 @@ async fn test_pagination_cursor() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some("2025-03-01T09-00-00".into()), @@ -894,6 +910,8 @@ async fn test_get_thread_contents() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some(ts.into()), @@ -1086,6 +1104,8 @@ async fn test_updated_at_uses_file_mtime() -> Result<()> { originator: "test_originator".into(), cli_version: "test_version".into(), source: SessionSource::VSCode, + agent_nickname: None, + agent_role: None, model_provider: Some("test-provider".into()), base_instructions: None, dynamic_tools: None, @@ -1203,6 +1223,8 @@ async fn test_stable_ordering_same_second_pagination() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some(ts.to_string()), @@ -1217,6 +1239,8 @@ async fn test_stable_ordering_same_second_pagination() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some(ts.to_string()), @@ -1258,6 +1282,8 @@ async fn test_stable_ordering_same_second_pagination() { git_sha: None, git_origin_url: None, source: Some(SessionSource::VSCode), + agent_nickname: None, + agent_role: None, model_provider: Some(TEST_PROVIDER.to_string()), cli_version: Some("test_version".to_string()), created_at: Some(ts.to_string()), diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 38aa22b6c4..dfc82ce52c 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -156,7 +156,11 @@ mod spawn { .spawn_agent( config, input_items, - Some(thread_spawn_source(session.conversation_id, child_depth)), + Some(thread_spawn_source( + session.conversation_id, + child_depth, + role_name, + )), ) .await .map_err(collab_spawn_error); @@ -284,7 +288,6 @@ mod send_input { mod resume_agent { use super::*; use crate::agent::next_thread_spawn_depth; - use crate::rollout::find_thread_path_by_id_str; use std::sync::Arc; #[derive(Debug, Deserialize)] @@ -331,15 +334,7 @@ mod resume_agent { .await; let error = if matches!(status, AgentStatus::NotFound) { // If the thread is no longer active, attempt to restore it from rollout. - match try_resume_closed_agent( - &session, - &turn, - receiver_thread_id, - &args.id, - child_depth, - ) - .await - { + match try_resume_closed_agent(&session, &turn, receiver_thread_id, child_depth).await { Ok(resumed_status) => { status = resumed_status; None @@ -388,33 +383,16 @@ mod resume_agent { session: &Arc, turn: &Arc, receiver_thread_id: ThreadId, - receiver_id: &str, child_depth: i32, ) -> Result { - let rollout_path = find_thread_path_by_id_str( - turn.config.codex_home.as_path(), - receiver_id, - ) - .await - .map_err(|err| { - FunctionCallError::RespondToModel(format!( - "tool failed: failed to locate rollout for agent {receiver_thread_id}: {err}" - )) - })? - .ok_or_else(|| { - FunctionCallError::RespondToModel(format!( - "agent with id {receiver_thread_id} not found" - )) - })?; - let config = build_agent_resume_config(turn.as_ref(), child_depth)?; let resumed_thread_id = session .services .agent_control .resume_agent_from_rollout( config, - rollout_path, - thread_spawn_source(session.conversation_id, child_depth), + receiver_thread_id, + thread_spawn_source(session.conversation_id, child_depth, None), ) .await .map_err(|err| collab_agent_error(receiver_thread_id, err))?; @@ -733,10 +711,16 @@ fn collab_agent_error(agent_id: ThreadId, err: CodexErr) -> FunctionCallError { } } -fn thread_spawn_source(parent_thread_id: ThreadId, depth: i32) -> SessionSource { +fn thread_spawn_source( + parent_thread_id: ThreadId, + depth: i32, + agent_role: Option<&str>, +) -> SessionSource { SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, depth, + agent_nickname: None, + agent_role: agent_role.map(str::to_string), }) } @@ -1068,6 +1052,8 @@ mod tests { turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id: session.conversation_id, depth: DEFAULT_AGENT_MAX_DEPTH, + agent_nickname: None, + agent_role: None, }); let invocation = invocation( @@ -1104,6 +1090,8 @@ mod tests { turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id: session.conversation_id, depth: DEFAULT_AGENT_MAX_DEPTH, + agent_nickname: None, + agent_role: None, }); let invocation = invocation( @@ -1487,6 +1475,8 @@ mod tests { turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id: session.conversation_id, depth: DEFAULT_AGENT_MAX_DEPTH, + agent_nickname: None, + agent_role: None, }); let invocation = invocation( diff --git a/codex-rs/core/tests/suite/personality_migration.rs b/codex-rs/core/tests/suite/personality_migration.rs index 2ca7aeeefd..dfff16ea03 100644 --- a/codex-rs/core/tests/suite/personality_migration.rs +++ b/codex-rs/core/tests/suite/personality_migration.rs @@ -66,6 +66,8 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R originator: "test_originator".to_string(), cli_version: "test_version".to_string(), source: SessionSource::Cli, + agent_nickname: None, + agent_role: None, model_provider: None, base_instructions: None, dynamic_tools: None, @@ -107,6 +109,8 @@ async fn write_rollout_with_meta_only(dir: &Path, thread_id: ThreadId) -> io::Re originator: "test_originator".to_string(), cli_version: "test_version".to_string(), source: SessionSource::Cli, + agent_nickname: None, + agent_role: None, model_provider: None, base_instructions: None, dynamic_tools: None, diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index b37683a430..8f0e5834e9 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -123,6 +123,8 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { originator: "test".to_string(), cli_version: "test".to_string(), source: SessionSource::default(), + agent_nickname: None, + agent_role: None, model_provider: None, base_instructions: None, dynamic_tools: Some(dynamic_tools_for_hook), diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 476f902085..a759f15129 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1861,6 +1861,10 @@ pub enum SubAgentSource { ThreadSpawn { parent_thread_id: ThreadId, depth: i32, + #[serde(default)] + agent_nickname: Option, + #[serde(default, alias = "agent_type")] + agent_role: Option, }, MemoryConsolidation, Other(String), @@ -1879,6 +1883,26 @@ impl fmt::Display for SessionSource { } } +impl SessionSource { + pub fn get_nickname(&self) -> Option { + match self { + SessionSource::SubAgent(SubAgentSource::ThreadSpawn { agent_nickname, .. }) => { + agent_nickname.clone() + } + _ => None, + } + } + + pub fn get_agent_role(&self) -> Option { + match self { + SessionSource::SubAgent(SubAgentSource::ThreadSpawn { agent_role, .. }) => { + agent_role.clone() + } + _ => None, + } + } +} + impl fmt::Display for SubAgentSource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -1888,6 +1912,7 @@ impl fmt::Display for SubAgentSource { SubAgentSource::ThreadSpawn { parent_thread_id, depth, + .. } => { write!(f, "thread_spawn_{parent_thread_id}_d{depth}") } @@ -1912,6 +1937,12 @@ pub struct SessionMeta { pub cli_version: String, #[serde(default)] pub source: SessionSource, + /// Optional random unique nickname assigned to an AgentControl-spawned sub-agent. + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_nickname: Option, + /// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + #[serde(default, alias = "agent_type", skip_serializing_if = "Option::is_none")] + pub agent_role: Option, pub model_provider: Option, /// base_instructions for the session. This *should* always be present when creating a new session, /// but may be missing for older sessions. If not present, fall back to rendering the base_instructions @@ -1931,6 +1962,8 @@ impl Default for SessionMeta { originator: String::new(), cli_version: String::new(), source: SessionSource::default(), + agent_nickname: None, + agent_role: None, model_provider: None, base_instructions: None, dynamic_tools: None, diff --git a/codex-rs/state/migrations/0013_threads_agent_nickname.sql b/codex-rs/state/migrations/0013_threads_agent_nickname.sql new file mode 100644 index 0000000000..80394c88b5 --- /dev/null +++ b/codex-rs/state/migrations/0013_threads_agent_nickname.sql @@ -0,0 +1,2 @@ +ALTER TABLE threads ADD COLUMN agent_nickname TEXT; +ALTER TABLE threads ADD COLUMN agent_role TEXT; diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index f8f9cb5251..0ba3df6790 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -37,6 +37,8 @@ fn apply_session_meta_from_item(metadata: &mut ThreadMetadata, meta_line: &Sessi } metadata.id = meta_line.meta.id; metadata.source = enum_to_string(&meta_line.meta.source); + metadata.agent_nickname = meta_line.meta.agent_nickname.clone(); + metadata.agent_role = meta_line.meta.agent_role.clone(); if let Some(provider) = meta_line.meta.model_provider.as_deref() { metadata.model_provider = provider.to_string(); } @@ -216,6 +218,8 @@ mod tests { created_at, updated_at: created_at, source: "cli".to_string(), + agent_nickname: None, + agent_role: None, model_provider: "openai".to_string(), cwd: PathBuf::from("/tmp"), cli_version: "0.0.0".to_string(), diff --git a/codex-rs/state/src/model/thread_metadata.rs b/codex-rs/state/src/model/thread_metadata.rs index d29bf07606..9533b8fede 100644 --- a/codex-rs/state/src/model/thread_metadata.rs +++ b/codex-rs/state/src/model/thread_metadata.rs @@ -62,6 +62,10 @@ pub struct ThreadMetadata { pub updated_at: DateTime, /// The session source (stringified enum). pub source: String, + /// Optional random unique nickname assigned to an AgentControl-spawned sub-agent. + pub agent_nickname: Option, + /// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + pub agent_role: Option, /// The model provider identifier. pub model_provider: String, /// The working directory for the thread. @@ -101,6 +105,10 @@ pub struct ThreadMetadataBuilder { pub updated_at: Option>, /// The session source. pub source: SessionSource, + /// Optional random unique nickname assigned to the session. + pub agent_nickname: Option, + /// Optional role (agent_role) assigned to the session. + pub agent_role: Option, /// The model provider identifier, if known. pub model_provider: Option, /// The working directory for the thread. @@ -135,6 +143,8 @@ impl ThreadMetadataBuilder { created_at, updated_at: None, source, + agent_nickname: None, + agent_role: None, model_provider: None, cwd: PathBuf::new(), cli_version: None, @@ -163,6 +173,8 @@ impl ThreadMetadataBuilder { created_at, updated_at, source, + agent_nickname: self.agent_nickname.clone(), + agent_role: self.agent_role.clone(), model_provider: self .model_provider .clone() @@ -201,6 +213,12 @@ impl ThreadMetadata { if self.source != other.source { diffs.push("source"); } + if self.agent_nickname != other.agent_nickname { + diffs.push("agent_nickname"); + } + if self.agent_role != other.agent_role { + diffs.push("agent_role"); + } if self.model_provider != other.model_provider { diffs.push("model_provider"); } @@ -252,6 +270,8 @@ pub(crate) struct ThreadRow { created_at: i64, updated_at: i64, source: String, + agent_nickname: Option, + agent_role: Option, model_provider: String, cwd: String, cli_version: String, @@ -274,6 +294,8 @@ impl ThreadRow { created_at: row.try_get("created_at")?, updated_at: row.try_get("updated_at")?, source: row.try_get("source")?, + agent_nickname: row.try_get("agent_nickname")?, + agent_role: row.try_get("agent_role")?, model_provider: row.try_get("model_provider")?, cwd: row.try_get("cwd")?, cli_version: row.try_get("cli_version")?, @@ -300,6 +322,8 @@ impl TryFrom for ThreadMetadata { created_at, updated_at, source, + agent_nickname, + agent_role, model_provider, cwd, cli_version, @@ -319,6 +343,8 @@ impl TryFrom for ThreadMetadata { created_at: epoch_seconds_to_datetime(created_at)?, updated_at: epoch_seconds_to_datetime(updated_at)?, source, + agent_nickname, + agent_role, model_provider, cwd: PathBuf::from(cwd), cli_version, diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index 4570532e69..3635bcb865 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -211,6 +211,8 @@ SELECT created_at, updated_at, source, + agent_nickname, + agent_role, model_provider, cwd, cli_version, @@ -310,6 +312,8 @@ SELECT created_at, updated_at, source, + agent_nickname, + agent_role, model_provider, cwd, cli_version, @@ -691,6 +695,8 @@ INSERT INTO threads ( created_at, updated_at, source, + agent_nickname, + agent_role, model_provider, cwd, cli_version, @@ -704,12 +710,14 @@ INSERT INTO threads ( git_sha, git_branch, git_origin_url -) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET rollout_path = excluded.rollout_path, created_at = excluded.created_at, updated_at = excluded.updated_at, source = excluded.source, + agent_nickname = excluded.agent_nickname, + agent_role = excluded.agent_role, model_provider = excluded.model_provider, cwd = excluded.cwd, cli_version = excluded.cli_version, @@ -730,6 +738,8 @@ ON CONFLICT(id) DO UPDATE SET .bind(datetime_to_epoch_seconds(metadata.created_at)) .bind(datetime_to_epoch_seconds(metadata.updated_at)) .bind(metadata.source.as_str()) + .bind(metadata.agent_nickname.as_deref()) + .bind(metadata.agent_role.as_deref()) .bind(metadata.model_provider.as_str()) .bind(metadata.cwd.display().to_string()) .bind(metadata.cli_version.as_str()) @@ -3092,6 +3102,8 @@ VALUES (?, ?, ?, ?, ?) created_at: now, updated_at: now, source: "cli".to_string(), + agent_nickname: None, + agent_role: None, model_provider: "test-provider".to_string(), cwd, cli_version: "0.0.0".to_string(), diff --git a/codex-rs/state/src/runtime/memories.rs b/codex-rs/state/src/runtime/memories.rs index c2a7f1fe91..f2a50e3c99 100644 --- a/codex-rs/state/src/runtime/memories.rs +++ b/codex-rs/state/src/runtime/memories.rs @@ -95,6 +95,8 @@ SELECT created_at, updated_at, source, + agent_nickname, + agent_role, model_provider, cwd, cli_version, diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index c9aa9aeced..6cb1387a4e 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -1327,17 +1327,10 @@ mod tests { fn make_item(path: &str, ts: &str, preview: &str) -> ThreadItem { ThreadItem { path: PathBuf::from(path), - thread_id: None, first_user_message: Some(preview.to_string()), - cwd: None, - git_branch: None, - git_sha: None, - git_origin_url: None, - source: None, - model_provider: None, - cli_version: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), + ..Default::default() } } @@ -1462,17 +1455,10 @@ mod tests { fn head_to_row_uses_first_user_message() { let item = ThreadItem { path: PathBuf::from("/tmp/a.jsonl"), - thread_id: None, first_user_message: Some("real question".to_string()), - cwd: None, - git_branch: None, - git_sha: None, - git_origin_url: None, - source: None, - model_provider: None, - cli_version: None, created_at: Some("2025-01-01T00:00:00Z".into()), updated_at: Some("2025-01-01T00:00:00Z".into()), + ..Default::default() }; let row = head_to_row(&item); assert_eq!(row.preview, "real question"); @@ -1483,31 +1469,17 @@ mod tests { // Construct two items with different timestamps and real user text. let a = ThreadItem { path: PathBuf::from("/tmp/a.jsonl"), - thread_id: None, first_user_message: Some("A".to_string()), - cwd: None, - git_branch: None, - git_sha: None, - git_origin_url: None, - source: None, - model_provider: None, - cli_version: None, created_at: Some("2025-01-01T00:00:00Z".into()), updated_at: Some("2025-01-01T00:00:00Z".into()), + ..Default::default() }; let b = ThreadItem { path: PathBuf::from("/tmp/b.jsonl"), - thread_id: None, first_user_message: Some("B".to_string()), - cwd: None, - git_branch: None, - git_sha: None, - git_origin_url: None, - source: None, - model_provider: None, - cli_version: None, created_at: Some("2025-01-02T00:00:00Z".into()), updated_at: Some("2025-01-02T00:00:00Z".into()), + ..Default::default() }; let rows = rows_from_items(vec![a, b]); assert_eq!(rows.len(), 2); @@ -1520,17 +1492,10 @@ mod tests { fn row_uses_tail_timestamp_for_updated_at() { let item = ThreadItem { path: PathBuf::from("/tmp/a.jsonl"), - thread_id: None, first_user_message: Some("Hello".to_string()), - cwd: None, - git_branch: None, - git_sha: None, - git_origin_url: None, - source: None, - model_provider: None, - cli_version: None, created_at: Some("2025-01-01T00:00:00Z".into()), updated_at: Some("2025-01-01T01:00:00Z".into()), + ..Default::default() }; let row = head_to_row(&item); From 595665de35a4c22fcda3c479063b709f0de4d7a2 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 14:51:09 +0000 Subject: [PATCH 007/385] chore: better agent names (#12328) --- codex-rs/core/src/agent/agent_names.txt | 185 +++++++++++------------- 1 file changed, 86 insertions(+), 99 deletions(-) diff --git a/codex-rs/core/src/agent/agent_names.txt b/codex-rs/core/src/agent/agent_names.txt index 6b6846193a..e5a712ff5c 100644 --- a/codex-rs/core/src/agent/agent_names.txt +++ b/codex-rs/core/src/agent/agent_names.txt @@ -1,100 +1,87 @@ -Atlas -Nova -Orion +Ash +Elm +Yew +Fir +Oak +Pine +Spruce +Cedar +Birch +Maple +Beech +Alder +Willow +Poplar +Aspen +Larch +Juniper +Cypress +Hemlock +Sequoia +Baobab +Acacia +Banyan +Teak +Olive +Cherry +Apple +Pear +Plum +Peach +Mango +Guava +Fig +Date +Palm +Holly +Ivy +Fern +Moss +Reed +Cane +Rush +Sage +Mint +Thyme +Basil +Dill +Fennel +Parsley +Laurel +Myrtle +Lotus +Tulip +Rose +Daisy +Lily Iris -Milo -Juno -Mars -Vesta -Luna -Sol -Eros -Nyx -Zeus -Hera -Ares -Ajax -Echo -Leto -Rhea -Gaia -Hades -Apollo -Pallas -Circe -Nereus -Triton -Selene -Helios -Castor -Pollux -Astra -Aura -Thalia -Clio -Erato -Euterpe -Urania -Calliope -Minos -Linus -Cato -Brutus -Seneca -Ovid -Virgil -Horace -Remus -Romulus -Titus -Lucian -Felix -Maximus -Octavia -Claudia -Livia -Aelia -Aurel -Cassia -Sabina -Flavia -Numa -Ceres -Diana -Venus -Pluto -Pan -Ramius -Aether -Chaos -Logos -Ethos -Tethys -Chiron -Talos -Icarus -Daedalus -Hyacinth -Adonis -Perseus -Theseus -Argos -Lemnos -Delos -Sparta -Attica -Corinth -Thebes -Ephyra -Achaea -Cyrene -Sidon -Tyre -Ilium -Etrus -Vercos -Aurex -Novian -Helion -Casson -Aurelix \ No newline at end of file +Poppy +Aster +Peony +Camellia +Azalea +Begonia +Petunia +Verbena +Marigold +Daffodil +Orchid +Violet +Clover +Bamboo +Eucalypt +Oleander +Yucca +Agave +Aloe +Cactus +Sedum +Boxwood +Hawthorn +Redwood +Ironwood +Sandal +Kapok +Mahonia +Spirea +Wisteria \ No newline at end of file From ede561b5d10a39463c68469c15a5d7c3034a988f Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 14:51:17 +0000 Subject: [PATCH 008/385] disable collab for phase 2 (#12326) --- codex-rs/core/src/memories/phase2.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/codex-rs/core/src/memories/phase2.rs b/codex-rs/core/src/memories/phase2.rs index ec8c36249d..6794a4574f 100644 --- a/codex-rs/core/src/memories/phase2.rs +++ b/codex-rs/core/src/memories/phase2.rs @@ -2,6 +2,7 @@ use crate::agent::AgentStatus; use crate::agent::status::is_final as is_final_agent_status; use crate::codex::Session; use crate::config::Config; +use crate::features::Feature; use crate::memories::memory_root; use crate::memories::metrics; use crate::memories::phase_two; @@ -227,6 +228,8 @@ mod agent { agent_config.cwd = root; // Approval policy agent_config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never); + // Consolidation runs as an internal sub-agent and must not recursively delegate. + agent_config.features.disable(Feature::Collab); // Sandbox policy let mut writable_roots = Vec::new(); From 2036a5f5e07c99eb1930f9e8ec207e8bf7e94afe Mon Sep 17 00:00:00 2001 From: colby-oai <228809017+colby-oai@users.noreply.github.com> Date: Fri, 20 Feb 2026 10:26:19 -0500 Subject: [PATCH 009/385] Add MCP server context to otel tool_result logs (#12267) Summary - capture the origin for each configured MCP server and expose it via the connection manager - plumb MCP server name/origin into tool logging and emit codex.tool_result events with those fields - add unit coverage for origin parsing and extend OTEL tests to assert empty MCP fields for non-MCP tools - currently not logging full urls or url paths to prevent logging potentially sensitive data Testing - Not run (not requested) --- codex-rs/core/src/mcp_connection_manager.rs | 50 ++++++++++++++++ codex-rs/core/src/tools/registry.rs | 21 +++++++ codex-rs/core/tests/suite/otel.rs | 62 ++++++++++++++++++++ codex-rs/otel/src/traces/otel_manager.rs | 13 ++++ codex-rs/otel/tests/suite/runtime_summary.rs | 2 + 5 files changed, 148 insertions(+) diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index c76e19809f..05ac2a9a9b 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -73,6 +73,7 @@ use tokio::task::JoinSet; use tokio_util::sync::CancellationToken; use tracing::instrument; use tracing::warn; +use url::Url; use crate::codex::INITIAL_SUBMIT_ID; use crate::config::types::McpServerConfig; @@ -507,6 +508,7 @@ pub struct SandboxState { /// A thin wrapper around a set of running [`RmcpClient`] instances. pub(crate) struct McpConnectionManager { clients: HashMap, + server_origins: HashMap, elicitation_requests: ElicitationRequestManager, } @@ -514,6 +516,7 @@ impl McpConnectionManager { pub(crate) fn new_uninitialized(approval_policy: &Constrained) -> Self { Self { clients: HashMap::new(), + server_origins: HashMap::new(), elicitation_requests: ElicitationRequestManager::new(approval_policy.value()), } } @@ -529,6 +532,10 @@ impl McpConnectionManager { !self.clients.is_empty() } + pub(crate) fn server_origin(&self, server_name: &str) -> Option<&str> { + self.server_origins.get(server_name).map(String::as_str) + } + pub fn set_approval_policy(&self, approval_policy: &Constrained) { if let Ok(mut policy) = self.elicitation_requests.approval_policy.lock() { *policy = approval_policy.value(); @@ -548,10 +555,14 @@ impl McpConnectionManager { ) -> (Self, CancellationToken) { let cancel_token = CancellationToken::new(); let mut clients = HashMap::new(); + let mut server_origins = HashMap::new(); let mut join_set = JoinSet::new(); let elicitation_requests = ElicitationRequestManager::new(approval_policy.value()); let mcp_servers = mcp_servers.clone(); for (server_name, cfg) in mcp_servers.into_iter().filter(|(_, cfg)| cfg.enabled) { + if let Some(origin) = transport_origin(&cfg.transport) { + server_origins.insert(server_name.clone(), origin); + } let cancel_token = cancel_token.child_token(); let _ = emit_update( &tx_event, @@ -624,6 +635,7 @@ impl McpConnectionManager { } let manager = Self { clients, + server_origins, elicitation_requests: elicitation_requests.clone(), }; tokio::spawn(async move { @@ -1448,6 +1460,16 @@ fn emit_duration(metric: &str, duration: Duration, tags: &[(&str, &str)]) { } } +fn transport_origin(transport: &McpServerTransportConfig) -> Option { + match transport { + McpServerTransportConfig::StreamableHttp { url, .. } => { + let parsed = Url::parse(url).ok()?; + Some(parsed.origin().ascii_serialization()) + } + McpServerTransportConfig::Stdio { .. } => Some("stdio".to_string()), + } +} + async fn list_tools_for_client_uncached( server_name: &str, client: &Arc, @@ -2164,4 +2186,32 @@ mod tests { display ); } + + #[test] + fn transport_origin_extracts_http_origin() { + let transport = McpServerTransportConfig::StreamableHttp { + url: "https://example.com:8443/path?query=1".to_string(), + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + }; + + assert_eq!( + transport_origin(&transport), + Some("https://example.com:8443".to_string()) + ); + } + + #[test] + fn transport_origin_is_stdio_for_stdio_transport() { + let transport = McpServerTransportConfig::Stdio { + command: "server".to_string(), + args: Vec::new(), + env: None, + env_vars: Vec::new(), + cwd: None, + }; + + assert_eq!(transport_origin(&transport), Some("stdio".to_string())); + } } diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 4ffb7ca107..7a0be68df3 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -102,6 +102,21 @@ impl ToolRegistry { sandbox_policy_tag(&invocation.turn.sandbox_policy), ), ]; + let (mcp_server, mcp_server_origin) = match &invocation.payload { + ToolPayload::Mcp { server, .. } => { + let manager = invocation + .session + .services + .mcp_connection_manager + .read() + .await; + let origin = manager.server_origin(server).map(str::to_owned); + (Some(server.clone()), origin) + } + _ => (None, None), + }; + let mcp_server_ref = mcp_server.as_deref(); + let mcp_server_origin_ref = mcp_server_origin.as_deref(); let handler = match self.handler(tool_name.as_ref()) { Some(handler) => handler, @@ -116,6 +131,8 @@ impl ToolRegistry { false, &message, &metric_tags, + mcp_server_ref, + mcp_server_origin_ref, ); return Err(FunctionCallError::RespondToModel(message)); } @@ -131,6 +148,8 @@ impl ToolRegistry { false, &message, &metric_tags, + mcp_server_ref, + mcp_server_origin_ref, ); return Err(FunctionCallError::Fatal(message)); } @@ -146,6 +165,8 @@ impl ToolRegistry { &call_id_owned, log_payload.as_ref(), &metric_tags, + mcp_server_ref, + mcp_server_origin_ref, || { let handler = handler.clone(); let output_cell = &output_cell; diff --git a/codex-rs/core/tests/suite/otel.rs b/codex-rs/core/tests/suite/otel.rs index fd3d1ca16c..03f87aec14 100644 --- a/codex-rs/core/tests/suite/otel.rs +++ b/codex-rs/core/tests/suite/otel.rs @@ -32,6 +32,64 @@ use tracing_test::traced_test; use tracing_subscriber::fmt::format::FmtSpan; use tracing_test::internal::MockWriter; +fn extract_log_field(line: &str, key: &str) -> Option { + let quoted_prefix = format!("{key}=\""); + if let Some(start) = line.find("ed_prefix) { + let value_start = start + quoted_prefix.len(); + if let Some(end_rel) = line[value_start..].find('"') { + return Some(line[value_start..value_start + end_rel].to_string()); + } + } + + let bare_prefix = format!("{key}="); + for token in line.split_whitespace() { + let trimmed = token.trim_end_matches(','); + if let Some(value) = trimmed.strip_prefix(&bare_prefix) { + return Some(value.to_string()); + } + } + + None +} + +fn assert_empty_mcp_tool_fields(line: &str) -> Result<(), String> { + let mcp_server = extract_log_field(line, "mcp_server") + .ok_or_else(|| "missing mcp_server field".to_string())?; + if !mcp_server.is_empty() { + return Err(format!("expected empty mcp_server, got {mcp_server}")); + } + + let mcp_server_origin = extract_log_field(line, "mcp_server_origin") + .ok_or_else(|| "missing mcp_server_origin field".to_string())?; + if !mcp_server_origin.is_empty() { + return Err(format!( + "expected empty mcp_server_origin, got {mcp_server_origin}" + )); + } + + Ok(()) +} + +#[test] +fn extract_log_field_handles_empty_bare_values() { + let line = "event.name=\"codex.tool_result\" mcp_server= mcp_server_origin="; + assert_eq!(extract_log_field(line, "mcp_server"), Some(String::new())); + assert_eq!( + extract_log_field(line, "mcp_server_origin"), + Some(String::new()) + ); +} + +#[test] +fn extract_log_field_does_not_confuse_similar_keys() { + let line = "event.name=\"codex.tool_result\" mcp_server_origin=stdio"; + assert_eq!(extract_log_field(line, "mcp_server"), None); + assert_eq!( + extract_log_field(line, "mcp_server_origin"), + Some("stdio".to_string()) + ); +} + #[tokio::test] #[traced_test] async fn responses_api_emits_api_request_event() { @@ -687,6 +745,7 @@ async fn handle_response_item_records_tool_result_for_custom_tool_call() { if !line.contains("success=false") { return Err("missing success field".to_string()); } + assert_empty_mcp_tool_fields(line)?; Ok(()) }); @@ -756,6 +815,7 @@ async fn handle_response_item_records_tool_result_for_function_call() { if !line.contains("success=false") { return Err("missing success field".to_string()); } + assert_empty_mcp_tool_fields(line)?; Ok(()) }); @@ -828,6 +888,7 @@ async fn handle_response_item_records_tool_result_for_local_shell_missing_ids() if !line.contains("success=false") { return Err("missing success field".to_string()); } + assert_empty_mcp_tool_fields(line)?; Ok(()) }); @@ -899,6 +960,7 @@ async fn handle_response_item_records_tool_result_for_local_shell_call() { if !line.contains("success=false") { return Err("missing success field".to_string()); } + assert_empty_mcp_tool_fields(line)?; Ok(()) }); diff --git a/codex-rs/otel/src/traces/otel_manager.rs b/codex-rs/otel/src/traces/otel_manager.rs index e3ba85eab1..9331801f9d 100644 --- a/codex-rs/otel/src/traces/otel_manager.rs +++ b/codex-rs/otel/src/traces/otel_manager.rs @@ -588,12 +588,15 @@ impl OtelManager { ); } + #[allow(clippy::too_many_arguments)] pub async fn log_tool_result_with_tags( &self, tool_name: &str, call_id: &str, arguments: &str, extra_tags: &[(&str, &str)], + mcp_server: Option<&str>, + mcp_server_origin: Option<&str>, f: F, ) -> Result<(String, bool), E> where @@ -618,6 +621,8 @@ impl OtelManager { success, output.as_ref(), extra_tags, + mcp_server, + mcp_server_origin, ); result @@ -641,6 +646,8 @@ impl OtelManager { duration_ms = %Duration::ZERO.as_millis(), success = %false, output = %error, + mcp_server = "", + mcp_server_origin = "", ); } @@ -654,6 +661,8 @@ impl OtelManager { success: bool, output: &str, extra_tags: &[(&str, &str)], + mcp_server: Option<&str>, + mcp_server_origin: Option<&str>, ) { let success_str = if success { "true" } else { "false" }; let mut tags = Vec::with_capacity(2 + extra_tags.len()); @@ -662,6 +671,8 @@ impl OtelManager { tags.extend_from_slice(extra_tags); self.counter(TOOL_CALL_COUNT_METRIC, 1, &tags); self.record_duration(TOOL_CALL_DURATION_METRIC, duration, &tags); + let mcp_server = mcp_server.unwrap_or(""); + let mcp_server_origin = mcp_server_origin.unwrap_or(""); tracing::event!( tracing::Level::INFO, event.name = "codex.tool_result", @@ -681,6 +692,8 @@ impl OtelManager { duration_ms = %duration.as_millis(), success = %success_str, output = %output, + mcp_server = %mcp_server, + mcp_server_origin = %mcp_server_origin, ); } diff --git a/codex-rs/otel/tests/suite/runtime_summary.rs b/codex-rs/otel/tests/suite/runtime_summary.rs index 0737e0797f..4020e70b45 100644 --- a/codex-rs/otel/tests/suite/runtime_summary.rs +++ b/codex-rs/otel/tests/suite/runtime_summary.rs @@ -44,6 +44,8 @@ fn runtime_metrics_summary_collects_tool_api_and_streaming_metrics() -> Result<( true, "ok", &[], + None, + None, ); manager.record_api_request(1, Some(200), None, Duration::from_millis(300)); manager.record_websocket_request(Duration::from_millis(400), None); From 4d60c803ba9c703b978e89a8f6f8a4ad1866582c Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 15:26:33 +0000 Subject: [PATCH 010/385] feat: cleaner TUI for sub-agents (#12327) Screenshot 2026-02-20 at 14 31 25 --- .../schema/json/EventMsg.json | 237 +++++++ .../schema/json/ServerNotification.json | 153 +++++ .../codex_app_server_protocol.schemas.json | 153 +++++ .../json/v1/ForkConversationResponse.json | 153 +++++ .../json/v1/ResumeConversationResponse.json | 153 +++++ .../v1/SessionConfiguredNotification.json | 153 +++++ .../CollabAgentInteractionEndEvent.ts | 8 + .../schema/typescript/CollabAgentRef.ts | 18 + .../typescript/CollabAgentSpawnEndEvent.ts | 8 + .../typescript/CollabAgentStatusEntry.ts | 23 + .../schema/typescript/CollabCloseEndEvent.ts | 8 + .../typescript/CollabResumeBeginEvent.ts | 10 +- .../schema/typescript/CollabResumeEndEvent.ts | 8 + .../typescript/CollabWaitingBeginEvent.ts | 5 + .../typescript/CollabWaitingEndEvent.ts | 5 + .../schema/typescript/index.ts | 2 + codex-rs/app-server-protocol/src/export.rs | 13 +- .../src/protocol/thread_history.rs | 2 + .../app-server/src/bespoke_event_handling.rs | 4 + codex-rs/core/src/agent/control.rs | 17 + .../core/src/tools/handlers/multi_agents.rs | 106 ++++ .../src/event_processor_with_human_output.rs | 5 + .../tests/event_processor_with_json_output.rs | 3 + codex-rs/protocol/src/protocol.rs | 62 ++ codex-rs/tui/src/multi_agents.rs | 585 ++++++++++++------ ...gents__tests__collab_agent_transcript.snap | 17 + 26 files changed, 1735 insertions(+), 176 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts create mode 100644 codex-rs/tui/src/snapshots/codex_tui__multi_agents__tests__collab_agent_transcript.snap diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index a85d02853b..33f58d18b1 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -296,6 +296,75 @@ } ] }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, "ContentItem": { "oneOf": [ { @@ -2548,6 +2617,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, "new_thread_id": { "anyOf": [ { @@ -2653,6 +2736,20 @@ "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2703,6 +2800,13 @@ "description": "ID of the waiting call.", "type": "string" }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, "receiver_thread_ids": { "description": "Thread ID of the receivers.", "items": { @@ -2738,6 +2842,13 @@ { "description": "Collab interaction: waiting end.", "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, "call_id": { "description": "ID of the waiting call.", "type": "string" @@ -2821,6 +2932,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2870,6 +2995,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2910,6 +3049,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -7528,6 +7681,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, "new_thread_id": { "anyOf": [ { @@ -7633,6 +7800,20 @@ "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -7683,6 +7864,13 @@ "description": "ID of the waiting call.", "type": "string" }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, "receiver_thread_ids": { "description": "Thread ID of the receivers.", "items": { @@ -7718,6 +7906,13 @@ { "description": "Collab interaction: waiting end.", "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, "call_id": { "description": "ID of the waiting call.", "type": "string" @@ -7801,6 +7996,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -7850,6 +8059,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -7890,6 +8113,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 128f4fa60d..6a6bf2d7c7 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -808,6 +808,36 @@ } ] }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, "CollabAgentState": { "properties": { "message": { @@ -836,6 +866,45 @@ ], "type": "string" }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, "CollabAgentTool": { "enum": [ "spawnAgent", @@ -3364,6 +3433,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, "new_thread_id": { "anyOf": [ { @@ -3469,6 +3552,20 @@ "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -3519,6 +3616,13 @@ "description": "ID of the waiting call.", "type": "string" }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, "receiver_thread_ids": { "description": "Thread ID of the receivers.", "items": { @@ -3554,6 +3658,13 @@ { "description": "Collab interaction: waiting end.", "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, "call_id": { "description": "ID of the waiting call.", "type": "string" @@ -3637,6 +3748,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -3686,6 +3811,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -3726,6 +3865,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index ea4cd0bd3a..df73bf2c46 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -2029,6 +2029,75 @@ } ] }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, "CommandExecutionApprovalDecision": { "oneOf": [ { @@ -4592,6 +4661,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, "new_thread_id": { "anyOf": [ { @@ -4697,6 +4780,20 @@ "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -4747,6 +4844,13 @@ "description": "ID of the waiting call.", "type": "string" }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, "receiver_thread_ids": { "description": "Thread ID of the receivers.", "items": { @@ -4782,6 +4886,13 @@ { "description": "Collab interaction: waiting end.", "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, "call_id": { "description": "ID of the waiting call.", "type": "string" @@ -4865,6 +4976,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -4914,6 +5039,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -4954,6 +5093,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json index d7f1e1d837..f88d5f741b 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json @@ -296,6 +296,75 @@ } ] }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, "ContentItem": { "oneOf": [ { @@ -2548,6 +2617,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, "new_thread_id": { "anyOf": [ { @@ -2653,6 +2736,20 @@ "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2703,6 +2800,13 @@ "description": "ID of the waiting call.", "type": "string" }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, "receiver_thread_ids": { "description": "Thread ID of the receivers.", "items": { @@ -2738,6 +2842,13 @@ { "description": "Collab interaction: waiting end.", "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, "call_id": { "description": "ID of the waiting call.", "type": "string" @@ -2821,6 +2932,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2870,6 +2995,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2910,6 +3049,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json index 9cbd492d99..e619dfe126 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json @@ -296,6 +296,75 @@ } ] }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, "ContentItem": { "oneOf": [ { @@ -2548,6 +2617,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, "new_thread_id": { "anyOf": [ { @@ -2653,6 +2736,20 @@ "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2703,6 +2800,13 @@ "description": "ID of the waiting call.", "type": "string" }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, "receiver_thread_ids": { "description": "Thread ID of the receivers.", "items": { @@ -2738,6 +2842,13 @@ { "description": "Collab interaction: waiting end.", "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, "call_id": { "description": "ID of the waiting call.", "type": "string" @@ -2821,6 +2932,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2870,6 +2995,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2910,6 +3049,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json b/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json index fd66f6060e..61887b4007 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json @@ -296,6 +296,75 @@ } ] }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, "ContentItem": { "oneOf": [ { @@ -2548,6 +2617,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, "new_thread_id": { "anyOf": [ { @@ -2653,6 +2736,20 @@ "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2703,6 +2800,13 @@ "description": "ID of the waiting call.", "type": "string" }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, "receiver_thread_ids": { "description": "Thread ID of the receivers.", "items": { @@ -2738,6 +2842,13 @@ { "description": "Collab interaction: waiting end.", "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, "call_id": { "description": "ID of the waiting call.", "type": "string" @@ -2821,6 +2932,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2870,6 +2995,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { @@ -2910,6 +3049,20 @@ "description": "Identifier for the collab tool call.", "type": "string" }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, "receiver_thread_id": { "allOf": [ { diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts index 0596300b35..5458e06dce 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts @@ -17,6 +17,14 @@ sender_thread_id: ThreadId, * Thread ID of the receiver. */ receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, /** * Prompt sent from the sender to the receiver. Can be empty to prevent CoT * leaking at the beginning. diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts new file mode 100644 index 0000000000..cae7bf88b8 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts @@ -0,0 +1,18 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentRef = { +/** + * Thread ID of the receiver/new agent. + */ +thread_id: ThreadId, +/** + * Optional nickname assigned to an AgentControl-spawned sub-agent. + */ +agent_nickname?: string | null, +/** + * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + */ +agent_role?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts index e880b5a401..34753c8e08 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts @@ -17,6 +17,14 @@ sender_thread_id: ThreadId, * Thread ID of the newly spawned agent, if it was created. */ new_thread_id: ThreadId | null, +/** + * Optional nickname assigned to the new agent. + */ +new_agent_nickname?: string | null, +/** + * Optional role assigned to the new agent. + */ +new_agent_role?: string | null, /** * Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the * beginning. diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts new file mode 100644 index 0000000000..286d19423d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts @@ -0,0 +1,23 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentStatus } from "./AgentStatus"; +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentStatusEntry = { +/** + * Thread ID of the receiver/new agent. + */ +thread_id: ThreadId, +/** + * Optional nickname assigned to an AgentControl-spawned sub-agent. + */ +agent_nickname?: string | null, +/** + * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + */ +agent_role?: string | null, +/** + * Last known status of the agent. + */ +status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts index 70343cbe4d..171886f1ef 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts @@ -17,6 +17,14 @@ sender_thread_id: ThreadId, * Thread ID of the receiver. */ receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, /** * Last known status of the receiver agent reported to the sender agent before * the close. diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts index b703666723..e6c1c3d5cd 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts @@ -15,4 +15,12 @@ sender_thread_id: ThreadId, /** * Thread ID of the receiver. */ -receiver_thread_id: ThreadId, }; +receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts index 9eed310360..caf970ec28 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts @@ -17,6 +17,14 @@ sender_thread_id: ThreadId, * Thread ID of the receiver. */ receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, /** * Last known status of the receiver agent reported to the sender agent after * resume. diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts index 0cbe04f62b..f2f07f87ea 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts @@ -1,6 +1,7 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CollabAgentRef } from "./CollabAgentRef"; import type { ThreadId } from "./ThreadId"; export type CollabWaitingBeginEvent = { @@ -12,6 +13,10 @@ sender_thread_id: ThreadId, * Thread ID of the receivers. */ receiver_thread_ids: Array, +/** + * Optional nicknames/roles for receivers. + */ +receiver_agents?: Array, /** * ID of the waiting call. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts index 57f914c134..929d59c611 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts @@ -2,6 +2,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AgentStatus } from "./AgentStatus"; +import type { CollabAgentStatusEntry } from "./CollabAgentStatusEntry"; import type { ThreadId } from "./ThreadId"; export type CollabWaitingEndEvent = { @@ -13,6 +14,10 @@ sender_thread_id: ThreadId, * ID of the waiting call. */ call_id: string, +/** + * Optional receiver metadata paired with final statuses. + */ +agent_statuses?: Array, /** * Last known status of the receiver agents reported to the sender agent. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index 79d8bdd98e..cda04def82 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -33,8 +33,10 @@ export type { ClientRequest } from "./ClientRequest"; export type { CodexErrorInfo } from "./CodexErrorInfo"; export type { CollabAgentInteractionBeginEvent } from "./CollabAgentInteractionBeginEvent"; export type { CollabAgentInteractionEndEvent } from "./CollabAgentInteractionEndEvent"; +export type { CollabAgentRef } from "./CollabAgentRef"; export type { CollabAgentSpawnBeginEvent } from "./CollabAgentSpawnBeginEvent"; export type { CollabAgentSpawnEndEvent } from "./CollabAgentSpawnEndEvent"; +export type { CollabAgentStatusEntry } from "./CollabAgentStatusEntry"; export type { CollabCloseBeginEvent } from "./CollabCloseBeginEvent"; export type { CollabCloseEndEvent } from "./CollabCloseEndEvent"; export type { CollabResumeBeginEvent } from "./CollabResumeBeginEvent"; diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 2cb3f9d1f1..ec51dd1585 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -1475,7 +1475,18 @@ mod tests { .file_stem() .and_then(|stem| stem.to_str()) .is_some_and(|stem| { - stem.ends_with("Params") || stem == "InitializeCapabilities" + stem.ends_with("Params") + || stem == "InitializeCapabilities" + || matches!( + stem, + "CollabAgentRef" + | "CollabAgentStatusEntry" + | "CollabAgentSpawnEndEvent" + | "CollabAgentInteractionEndEvent" + | "CollabCloseEndEvent" + | "CollabResumeBeginEvent" + | "CollabResumeEndEvent" + ) }); let contents = fs::read_to_string(&path)?; diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index 52850a67e4..fce6f4f263 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -2002,6 +2002,8 @@ mod tests { .expect("valid sender thread id"), receiver_thread_id: ThreadId::try_from("00000000-0000-0000-0000-000000000002") .expect("valid receiver thread id"), + receiver_agent_nickname: None, + receiver_agent_role: None, status: AgentStatus::Completed(None), }), ]; diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 2e87a16844..ea4fa691d5 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -2059,6 +2059,8 @@ mod tests { call_id: "call-1".to_string(), sender_thread_id: ThreadId::new(), receiver_thread_id: ThreadId::new(), + receiver_agent_nickname: None, + receiver_agent_role: None, }; let item = collab_resume_begin_item(event.clone()); @@ -2080,6 +2082,8 @@ mod tests { call_id: "call-2".to_string(), sender_thread_id: ThreadId::new(), receiver_thread_id: ThreadId::new(), + receiver_agent_nickname: None, + receiver_agent_role: None, status: codex_protocol::protocol::AgentStatus::NotFound, }; diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index a9ddde6324..7287d25283 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -218,6 +218,23 @@ impl AgentControl { thread.agent_status().await } + pub(crate) async fn get_agent_nickname_and_role( + &self, + agent_id: ThreadId, + ) -> Option<(Option, Option)> { + let Ok(state) = self.upgrade() else { + return None; + }; + let Ok(thread) = state.get_thread(agent_id).await else { + return None; + }; + let session_source = thread.config_snapshot().await.session_source; + Some(( + session_source.get_nickname(), + session_source.get_agent_role(), + )) + } + /// Subscribe to status updates for `agent_id`, yielding the latest value and changes. pub(crate) async fn subscribe_status( &self, diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index dfc82ce52c..b0c4cc4126 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -20,8 +20,10 @@ use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::CollabAgentInteractionBeginEvent; use codex_protocol::protocol::CollabAgentInteractionEndEvent; +use codex_protocol::protocol::CollabAgentRef; use codex_protocol::protocol::CollabAgentSpawnBeginEvent; use codex_protocol::protocol::CollabAgentSpawnEndEvent; +use codex_protocol::protocol::CollabAgentStatusEntry; use codex_protocol::protocol::CollabCloseBeginEvent; use codex_protocol::protocol::CollabCloseEndEvent; use codex_protocol::protocol::CollabResumeBeginEvent; @@ -33,6 +35,7 @@ use codex_protocol::protocol::SubAgentSource; use codex_protocol::user_input::UserInput; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; pub struct MultiAgentHandler; @@ -171,6 +174,15 @@ mod spawn { ), Err(_) => (None, AgentStatus::NotFound), }; + let (new_agent_nickname, new_agent_role) = match new_thread_id { + Some(thread_id) => session + .services + .agent_control + .get_agent_nickname_and_role(thread_id) + .await + .unwrap_or((None, None)), + None => (None, None), + }; session .send_event( &turn, @@ -178,6 +190,8 @@ mod spawn { call_id, sender_thread_id: session.conversation_id, new_thread_id, + new_agent_nickname, + new_agent_role, prompt, status, } @@ -228,6 +242,12 @@ mod send_input { let receiver_thread_id = agent_id(&args.id)?; let input_items = parse_collab_input(args.message, args.items)?; let prompt = input_preview(&input_items); + let (receiver_agent_nickname, receiver_agent_role) = session + .services + .agent_control + .get_agent_nickname_and_role(receiver_thread_id) + .await + .unwrap_or((None, None)); if args.interrupt { session .services @@ -266,6 +286,8 @@ mod send_input { call_id, sender_thread_id: session.conversation_id, receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, prompt, status, } @@ -308,6 +330,12 @@ mod resume_agent { ) -> Result { let args: ResumeAgentArgs = parse_arguments(&arguments)?; let receiver_thread_id = agent_id(&args.id)?; + let (receiver_agent_nickname, receiver_agent_role) = session + .services + .agent_control + .get_agent_nickname_and_role(receiver_thread_id) + .await + .unwrap_or((None, None)); let child_depth = next_thread_spawn_depth(&turn.session_source); if exceeds_thread_spawn_depth_limit(child_depth, turn.config.agent_max_depth) { return Err(FunctionCallError::RespondToModel( @@ -322,6 +350,8 @@ mod resume_agent { call_id: call_id.clone(), sender_thread_id: session.conversation_id, receiver_thread_id, + receiver_agent_nickname: receiver_agent_nickname.clone(), + receiver_agent_role: receiver_agent_role.clone(), } .into(), ) @@ -352,6 +382,12 @@ mod resume_agent { None }; + let (receiver_agent_nickname, receiver_agent_role) = session + .services + .agent_control + .get_agent_nickname_and_role(receiver_thread_id) + .await + .unwrap_or((receiver_agent_nickname, receiver_agent_role)); session .send_event( &turn, @@ -359,6 +395,8 @@ mod resume_agent { call_id, sender_thread_id: session.conversation_id, receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, status: status.clone(), } .into(), @@ -448,6 +486,20 @@ pub(crate) mod wait { .iter() .map(|id| agent_id(id)) .collect::, _>>()?; + let mut receiver_agents = Vec::with_capacity(receiver_thread_ids.len()); + for receiver_thread_id in &receiver_thread_ids { + let (agent_nickname, agent_role) = session + .services + .agent_control + .get_agent_nickname_and_role(*receiver_thread_id) + .await + .unwrap_or((None, None)); + receiver_agents.push(CollabAgentRef { + thread_id: *receiver_thread_id, + agent_nickname, + agent_role, + }); + } // Validate timeout. // Very short timeouts encourage busy-polling loops in the orchestrator prompt and can @@ -468,6 +520,7 @@ pub(crate) mod wait { CollabWaitingBeginEvent { sender_thread_id: session.conversation_id, receiver_thread_ids: receiver_thread_ids.clone(), + receiver_agents: receiver_agents.clone(), call_id: call_id.clone(), } .into(), @@ -497,6 +550,10 @@ pub(crate) mod wait { CollabWaitingEndEvent { sender_thread_id: session.conversation_id, call_id: call_id.clone(), + agent_statuses: build_wait_agent_statuses( + &statuses, + &receiver_agents, + ), statuses, } .into(), @@ -543,6 +600,7 @@ pub(crate) mod wait { // Convert payload. let statuses_map = statuses.clone().into_iter().collect::>(); + let agent_statuses = build_wait_agent_statuses(&statuses_map, &receiver_agents); let result = WaitResult { status: statuses_map.clone(), timed_out: statuses.is_empty(), @@ -555,6 +613,7 @@ pub(crate) mod wait { CollabWaitingEndEvent { sender_thread_id: session.conversation_id, call_id, + agent_statuses, statuses: statuses_map, } .into(), @@ -611,6 +670,12 @@ pub mod close_agent { ) -> Result { let args: CloseAgentArgs = parse_arguments(&arguments)?; let agent_id = agent_id(&args.id)?; + let (receiver_agent_nickname, receiver_agent_role) = session + .services + .agent_control + .get_agent_nickname_and_role(agent_id) + .await + .unwrap_or((None, None)); session .send_event( &turn, @@ -638,6 +703,8 @@ pub mod close_agent { call_id: call_id.clone(), sender_thread_id: session.conversation_id, receiver_thread_id: agent_id, + receiver_agent_nickname: receiver_agent_nickname.clone(), + receiver_agent_role: receiver_agent_role.clone(), status, } .into(), @@ -664,6 +731,8 @@ pub mod close_agent { call_id, sender_thread_id: session.conversation_id, receiver_thread_id: agent_id, + receiver_agent_nickname, + receiver_agent_role, status: status.clone(), } .into(), @@ -687,6 +756,43 @@ fn agent_id(id: &str) -> Result { .map_err(|e| FunctionCallError::RespondToModel(format!("invalid agent id {id}: {e:?}"))) } +fn build_wait_agent_statuses( + statuses: &HashMap, + receiver_agents: &[CollabAgentRef], +) -> Vec { + if statuses.is_empty() { + return Vec::new(); + } + + let mut entries = Vec::with_capacity(statuses.len()); + let mut seen = HashMap::with_capacity(receiver_agents.len()); + for receiver_agent in receiver_agents { + seen.insert(receiver_agent.thread_id, ()); + if let Some(status) = statuses.get(&receiver_agent.thread_id) { + entries.push(CollabAgentStatusEntry { + thread_id: receiver_agent.thread_id, + agent_nickname: receiver_agent.agent_nickname.clone(), + agent_role: receiver_agent.agent_role.clone(), + status: status.clone(), + }); + } + } + + let mut extras = statuses + .iter() + .filter(|(thread_id, _)| !seen.contains_key(thread_id)) + .map(|(thread_id, status)| CollabAgentStatusEntry { + thread_id: *thread_id, + agent_nickname: None, + agent_role: None, + status: status.clone(), + }) + .collect::>(); + extras.sort_by(|left, right| left.thread_id.to_string().cmp(&right.thread_id.to_string())); + entries.extend(extras); + entries +} + fn collab_spawn_error(err: CodexErr) -> FunctionCallError { match err { CodexErr::UnsupportedOperation(_) => { diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index f77a4ec16a..6583c19f9e 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -632,6 +632,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { new_thread_id, prompt, status, + .. }) => { let success = new_thread_id.is_some() && !is_collab_status_failure(&status); let title_style = if success { self.green } else { self.red }; @@ -669,6 +670,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { receiver_thread_id, prompt, status, + .. }) => { let success = !is_collab_status_failure(&status); let title_style = if success { self.green } else { self.red }; @@ -687,6 +689,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { sender_thread_id: _, receiver_thread_ids, call_id, + .. }) => { ts_msg!( self, @@ -703,6 +706,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { sender_thread_id: _, call_id, statuses, + .. }) => { if statuses.is_empty() { ts_msg!( @@ -755,6 +759,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { sender_thread_id: _, receiver_thread_id, status, + .. }) => { let success = !is_collab_status_failure(&status); let title_style = if success { self.green } else { self.red }; diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index 35cb962ee7..c04fcdb532 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -572,6 +572,8 @@ fn collab_spawn_begin_and_end_emit_item_events() { call_id: "call-10".to_string(), sender_thread_id, new_thread_id: Some(new_thread_id), + new_agent_nickname: None, + new_agent_role: None, prompt: prompt.clone(), status: AgentStatus::Running, }), @@ -623,6 +625,7 @@ fn collab_wait_end_without_begin_synthesizes_failed_item() { EventMsg::CollabWaitingEnd(CollabWaitingEndEvent { sender_thread_id, call_id: "call-11".to_string(), + agent_statuses: Vec::new(), statuses: statuses.clone(), }), ); diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index a759f15129..5b3d41888c 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -2747,6 +2747,32 @@ pub struct CollabAgentSpawnBeginEvent { pub prompt: String, } +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub struct CollabAgentRef { + /// Thread ID of the receiver/new agent. + pub thread_id: ThreadId, + /// Optional nickname assigned to an AgentControl-spawned sub-agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent_nickname: Option, + /// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + #[serde(default, alias = "agent_type", skip_serializing_if = "Option::is_none")] + pub agent_role: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub struct CollabAgentStatusEntry { + /// Thread ID of the receiver/new agent. + pub thread_id: ThreadId, + /// Optional nickname assigned to an AgentControl-spawned sub-agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent_nickname: Option, + /// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + #[serde(default, alias = "agent_type", skip_serializing_if = "Option::is_none")] + pub agent_role: Option, + /// Last known status of the agent. + pub status: AgentStatus, +} + #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] pub struct CollabAgentSpawnEndEvent { /// Identifier for the collab tool call. @@ -2755,6 +2781,12 @@ pub struct CollabAgentSpawnEndEvent { pub sender_thread_id: ThreadId, /// Thread ID of the newly spawned agent, if it was created. pub new_thread_id: Option, + /// Optional nickname assigned to the new agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub new_agent_nickname: Option, + /// Optional role assigned to the new agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub new_agent_role: Option, /// Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the /// beginning. pub prompt: String, @@ -2783,6 +2815,12 @@ pub struct CollabAgentInteractionEndEvent { pub sender_thread_id: ThreadId, /// Thread ID of the receiver. pub receiver_thread_id: ThreadId, + /// Optional nickname assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_nickname: Option, + /// Optional role assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_role: Option, /// Prompt sent from the sender to the receiver. Can be empty to prevent CoT /// leaking at the beginning. pub prompt: String, @@ -2796,6 +2834,9 @@ pub struct CollabWaitingBeginEvent { pub sender_thread_id: ThreadId, /// Thread ID of the receivers. pub receiver_thread_ids: Vec, + /// Optional nicknames/roles for receivers. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub receiver_agents: Vec, /// ID of the waiting call. pub call_id: String, } @@ -2806,6 +2847,9 @@ pub struct CollabWaitingEndEvent { pub sender_thread_id: ThreadId, /// ID of the waiting call. pub call_id: String, + /// Optional receiver metadata paired with final statuses. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub agent_statuses: Vec, /// Last known status of the receiver agents reported to the sender agent. pub statuses: HashMap, } @@ -2828,6 +2872,12 @@ pub struct CollabCloseEndEvent { pub sender_thread_id: ThreadId, /// Thread ID of the receiver. pub receiver_thread_id: ThreadId, + /// Optional nickname assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_nickname: Option, + /// Optional role assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_role: Option, /// Last known status of the receiver agent reported to the sender agent before /// the close. pub status: AgentStatus, @@ -2841,6 +2891,12 @@ pub struct CollabResumeBeginEvent { pub sender_thread_id: ThreadId, /// Thread ID of the receiver. pub receiver_thread_id: ThreadId, + /// Optional nickname assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_nickname: Option, + /// Optional role assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_role: Option, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] @@ -2851,6 +2907,12 @@ pub struct CollabResumeEndEvent { pub sender_thread_id: ThreadId, /// Thread ID of the receiver. pub receiver_thread_id: ThreadId, + /// Optional nickname assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_nickname: Option, + /// Optional role assigned to the receiver agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receiver_agent_role: Option, /// Last known status of the receiver agent reported to the sender agent after /// resume. pub status: AgentStatus, diff --git a/codex-rs/tui/src/multi_agents.rs b/codex-rs/tui/src/multi_agents.rs index e26bb8785a..57df8b8891 100644 --- a/codex-rs/tui/src/multi_agents.rs +++ b/codex-rs/tui/src/multi_agents.rs @@ -3,7 +3,9 @@ use crate::render::line_utils::prefix_lines; use crate::text_formatting::truncate_text; use codex_core::protocol::AgentStatus; use codex_core::protocol::CollabAgentInteractionEndEvent; +use codex_core::protocol::CollabAgentRef; use codex_core::protocol::CollabAgentSpawnEndEvent; +use codex_core::protocol::CollabAgentStatusEntry; use codex_core::protocol::CollabCloseEndEvent; use codex_core::protocol::CollabResumeBeginEvent; use codex_core::protocol::CollabResumeEndEvent; @@ -14,282 +16,517 @@ use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; use std::collections::HashMap; +use std::collections::HashSet; const COLLAB_PROMPT_PREVIEW_GRAPHEMES: usize = 160; const COLLAB_AGENT_ERROR_PREVIEW_GRAPHEMES: usize = 160; const COLLAB_AGENT_RESPONSE_PREVIEW_GRAPHEMES: usize = 240; +#[derive(Clone, Copy)] +struct AgentLabel<'a> { + thread_id: Option, + nickname: Option<&'a str>, + role: Option<&'a str>, +} + pub(crate) fn spawn_end(ev: CollabAgentSpawnEndEvent) -> PlainHistoryCell { let CollabAgentSpawnEndEvent { - call_id, + call_id: _, sender_thread_id: _, new_thread_id, + new_agent_nickname, + new_agent_role, prompt, - status, + status: _, } = ev; - let new_agent = new_thread_id - .map(|id| Span::from(id.to_string())) - .unwrap_or_else(|| Span::from("not created").dim()); - let mut details = vec![ - detail_line("call", call_id), - detail_line("agent", new_agent), - status_line(&status), - ]; + + let title = match new_thread_id { + Some(thread_id) => title_with_agent( + "Spawned", + AgentLabel { + thread_id: Some(thread_id), + nickname: new_agent_nickname.as_deref(), + role: new_agent_role.as_deref(), + }, + ), + None => title_text("Agent spawn failed"), + }; + + let mut details = Vec::new(); if let Some(line) = prompt_line(&prompt) { details.push(line); } - collab_event("Agent spawned", details) + collab_event(title, details) } pub(crate) fn interaction_end(ev: CollabAgentInteractionEndEvent) -> PlainHistoryCell { let CollabAgentInteractionEndEvent { - call_id, + call_id: _, sender_thread_id: _, receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, prompt, - status, + status: _, } = ev; - let mut details = vec![ - detail_line("call", call_id), - detail_line("receiver", receiver_thread_id.to_string()), - status_line(&status), - ]; + + let title = title_with_agent( + "Sent input to", + AgentLabel { + thread_id: Some(receiver_thread_id), + nickname: receiver_agent_nickname.as_deref(), + role: receiver_agent_role.as_deref(), + }, + ); + + let mut details = Vec::new(); if let Some(line) = prompt_line(&prompt) { details.push(line); } - collab_event("Input sent", details) + collab_event(title, details) } pub(crate) fn waiting_begin(ev: CollabWaitingBeginEvent) -> PlainHistoryCell { let CollabWaitingBeginEvent { - call_id, sender_thread_id: _, receiver_thread_ids, + receiver_agents, + call_id: _, } = ev; - let details = vec![ - detail_line("call", call_id), - detail_line("receivers", format_thread_ids(&receiver_thread_ids)), - ]; - collab_event("Waiting for agents", details) + let receiver_agents = merge_wait_receivers(&receiver_thread_ids, receiver_agents); + + let title = match receiver_agents.as_slice() { + [receiver] => title_with_agent("Waiting for", agent_label_from_ref(receiver)), + [] => title_text("Waiting for agents"), + _ => title_text(format!("Waiting for {} agents", receiver_agents.len())), + }; + + let details = if receiver_agents.len() > 1 { + receiver_agents + .iter() + .map(|receiver| agent_label_line(agent_label_from_ref(receiver))) + .collect() + } else { + Vec::new() + }; + + collab_event(title, details) } pub(crate) fn waiting_end(ev: CollabWaitingEndEvent) -> PlainHistoryCell { let CollabWaitingEndEvent { - call_id, + call_id: _, sender_thread_id: _, + agent_statuses, statuses, } = ev; - let mut details = vec![detail_line("call", call_id)]; - details.extend(wait_complete_lines(&statuses)); - collab_event("Wait complete", details) + let details = wait_complete_lines(&statuses, &agent_statuses); + collab_event(title_text("Finished waiting"), details) } pub(crate) fn close_end(ev: CollabCloseEndEvent) -> PlainHistoryCell { let CollabCloseEndEvent { - call_id, + call_id: _, sender_thread_id: _, receiver_thread_id, - status, + receiver_agent_nickname, + receiver_agent_role, + status: _, } = ev; - let details = vec![ - detail_line("call", call_id), - detail_line("receiver", receiver_thread_id.to_string()), - status_line(&status), - ]; - collab_event("Agent closed", details) + + collab_event( + title_with_agent( + "Closed", + AgentLabel { + thread_id: Some(receiver_thread_id), + nickname: receiver_agent_nickname.as_deref(), + role: receiver_agent_role.as_deref(), + }, + ), + Vec::new(), + ) } pub(crate) fn resume_begin(ev: CollabResumeBeginEvent) -> PlainHistoryCell { let CollabResumeBeginEvent { - call_id, + call_id: _, sender_thread_id: _, receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, } = ev; - let details = vec![ - detail_line("call", call_id), - detail_line("receiver", receiver_thread_id.to_string()), - ]; - collab_event("Resuming agent", details) + + collab_event( + title_with_agent( + "Resuming", + AgentLabel { + thread_id: Some(receiver_thread_id), + nickname: receiver_agent_nickname.as_deref(), + role: receiver_agent_role.as_deref(), + }, + ), + Vec::new(), + ) } pub(crate) fn resume_end(ev: CollabResumeEndEvent) -> PlainHistoryCell { let CollabResumeEndEvent { - call_id, + call_id: _, sender_thread_id: _, receiver_thread_id, + receiver_agent_nickname, + receiver_agent_role, status, } = ev; - let details = vec![ - detail_line("call", call_id), - detail_line("receiver", receiver_thread_id.to_string()), - status_line(&status), - ]; - collab_event("Agent resumed", details) + + collab_event( + title_with_agent( + "Resumed", + AgentLabel { + thread_id: Some(receiver_thread_id), + nickname: receiver_agent_nickname.as_deref(), + role: receiver_agent_role.as_deref(), + }, + ), + vec![status_summary_line(&status)], + ) } -fn collab_event(title: impl Into, details: Vec>) -> PlainHistoryCell { - let title = title.into(); - let mut lines: Vec> = - vec![vec![Span::from("• ").dim(), Span::from(title).bold()].into()]; +fn collab_event(title: Line<'static>, details: Vec>) -> PlainHistoryCell { + let mut lines: Vec> = vec![title]; if !details.is_empty() { lines.extend(prefix_lines(details, " └ ".dim(), " ".into())); } PlainHistoryCell::new(lines) } -fn detail_line(label: &str, value: impl Into>) -> Line<'static> { - vec![Span::from(format!("{label}: ")).dim(), value.into()].into() +fn title_text(title: impl Into) -> Line<'static> { + title_spans_line(vec![Span::from(title.into()).bold()]) } -fn status_line(status: &AgentStatus) -> Line<'static> { - detail_line("status", status_span(status)) +fn title_with_agent(prefix: &str, agent: AgentLabel<'_>) -> Line<'static> { + let mut spans = vec![Span::from(format!("{prefix} ")).bold()]; + spans.extend(agent_label_spans(agent)); + title_spans_line(spans) } -fn status_span(status: &AgentStatus) -> Span<'static> { - match status { - AgentStatus::PendingInit => Span::from("pending init").dim(), - AgentStatus::Running => Span::from("running").cyan().bold(), - AgentStatus::Completed(_) => Span::from("completed").green(), - AgentStatus::Errored(_) => Span::from("errored").red(), - AgentStatus::Shutdown => Span::from("shutdown").dim(), - AgentStatus::NotFound => Span::from("not found").red(), +fn title_spans_line(mut spans: Vec>) -> Line<'static> { + let mut title = Vec::with_capacity(spans.len() + 1); + title.push(Span::from("• ").dim()); + title.append(&mut spans); + title.into() +} + +fn agent_label_from_ref(agent: &CollabAgentRef) -> AgentLabel<'_> { + AgentLabel { + thread_id: Some(agent.thread_id), + nickname: agent.agent_nickname.as_deref(), + role: agent.agent_role.as_deref(), } } +fn agent_label_line(agent: AgentLabel<'_>) -> Line<'static> { + agent_label_spans(agent).into() +} + +fn agent_label_spans(agent: AgentLabel<'_>) -> Vec> { + let mut spans = Vec::new(); + let nickname = agent + .nickname + .map(str::trim) + .filter(|nickname| !nickname.is_empty()); + let role = agent.role.map(str::trim).filter(|role| !role.is_empty()); + + if let Some(nickname) = nickname { + spans.push(Span::from(nickname.to_string()).light_blue().bold()); + } else if let Some(thread_id) = agent.thread_id { + spans.push(Span::from(thread_id.to_string()).dim()); + } else { + spans.push(Span::from("agent").dim()); + } + + if let Some(role) = role { + spans.push(Span::from(" ").dim()); + spans.push(Span::from(format!("[{role}]")).dim()); + } + + spans +} + fn prompt_line(prompt: &str) -> Option> { let trimmed = prompt.trim(); if trimmed.is_empty() { None } else { - Some(detail_line( - "prompt", - Span::from(truncate_text(trimmed, COLLAB_PROMPT_PREVIEW_GRAPHEMES)).dim(), - )) + Some(Line::from(Span::from(truncate_text( + trimmed, + COLLAB_PROMPT_PREVIEW_GRAPHEMES, + )))) } } -fn format_thread_ids(ids: &[ThreadId]) -> Span<'static> { - if ids.is_empty() { - return Span::from("none").dim(); +fn merge_wait_receivers( + receiver_thread_ids: &[ThreadId], + mut receiver_agents: Vec, +) -> Vec { + if receiver_agents.is_empty() { + return receiver_thread_ids + .iter() + .map(|thread_id| CollabAgentRef { + thread_id: *thread_id, + agent_nickname: None, + agent_role: None, + }) + .collect(); } - let joined = ids + + let mut seen = receiver_agents .iter() - .map(ToString::to_string) - .collect::>() - .join(", "); - Span::from(joined) -} - -fn wait_complete_lines(statuses: &HashMap) -> Vec> { - if statuses.is_empty() { - return vec![detail_line("agents", Span::from("none").dim())]; - } - - let mut pending_init = 0usize; - let mut running = 0usize; - let mut completed = 0usize; - let mut errored = 0usize; - let mut shutdown = 0usize; - let mut not_found = 0usize; - for status in statuses.values() { - match status { - AgentStatus::PendingInit => pending_init += 1, - AgentStatus::Running => running += 1, - AgentStatus::Completed(_) => completed += 1, - AgentStatus::Errored(_) => errored += 1, - AgentStatus::Shutdown => shutdown += 1, - AgentStatus::NotFound => not_found += 1, + .map(|agent| agent.thread_id) + .collect::>(); + for thread_id in receiver_thread_ids { + if seen.insert(*thread_id) { + receiver_agents.push(CollabAgentRef { + thread_id: *thread_id, + agent_nickname: None, + agent_role: None, + }); } } + receiver_agents +} - let mut summary = vec![Span::from(format!("{} total", statuses.len())).dim()]; - push_status_count( - &mut summary, - pending_init, - "pending init", - ratatui::prelude::Stylize::dim, - ); - push_status_count(&mut summary, running, "running", |span| span.cyan().bold()); - push_status_count( - &mut summary, - completed, - "completed", - ratatui::prelude::Stylize::green, - ); - push_status_count( - &mut summary, - errored, - "errored", - ratatui::prelude::Stylize::red, - ); - push_status_count( - &mut summary, - shutdown, - "shutdown", - ratatui::prelude::Stylize::dim, - ); - push_status_count( - &mut summary, - not_found, - "not found", - ratatui::prelude::Stylize::red, - ); +fn wait_complete_lines( + statuses: &HashMap, + agent_statuses: &[CollabAgentStatusEntry], +) -> Vec> { + if statuses.is_empty() && agent_statuses.is_empty() { + return vec![Line::from(Span::from("No agents completed yet").dim())]; + } - let mut entries: Vec<(String, &AgentStatus)> = statuses - .iter() - .map(|(thread_id, status)| (thread_id.to_string(), status)) - .collect(); - entries.sort_by(|(left, _), (right, _)| left.cmp(right)); + let entries = if agent_statuses.is_empty() { + let mut entries = statuses + .iter() + .map(|(thread_id, status)| CollabAgentStatusEntry { + thread_id: *thread_id, + agent_nickname: None, + agent_role: None, + status: status.clone(), + }) + .collect::>(); + entries.sort_by(|left, right| left.thread_id.to_string().cmp(&right.thread_id.to_string())); + entries + } else { + let mut entries = agent_statuses.to_vec(); + let seen = entries + .iter() + .map(|entry| entry.thread_id) + .collect::>(); + let mut extras = statuses + .iter() + .filter(|(thread_id, _)| !seen.contains(thread_id)) + .map(|(thread_id, status)| CollabAgentStatusEntry { + thread_id: *thread_id, + agent_nickname: None, + agent_role: None, + status: status.clone(), + }) + .collect::>(); + extras.sort_by(|left, right| left.thread_id.to_string().cmp(&right.thread_id.to_string())); + entries.extend(extras); + entries + }; - let mut lines = Vec::with_capacity(entries.len() + 1); - lines.push(detail_line_spans("agents", summary)); - lines.extend(entries.into_iter().map(|(thread_id, status)| { - let mut spans = vec![ - Span::from(thread_id).dim(), - Span::from(" ").dim(), - status_span(status), - ]; - match status { - AgentStatus::Completed(Some(message)) => { + entries + .into_iter() + .map(|entry| { + let CollabAgentStatusEntry { + thread_id, + agent_nickname, + agent_role, + status, + } = entry; + let mut spans = agent_label_spans(AgentLabel { + thread_id: Some(thread_id), + nickname: agent_nickname.as_deref(), + role: agent_role.as_deref(), + }); + spans.push(Span::from(": ").dim()); + spans.extend(status_summary_spans(&status)); + spans.into() + }) + .collect() +} + +fn status_summary_line(status: &AgentStatus) -> Line<'static> { + status_summary_spans(status).into() +} + +fn status_summary_spans(status: &AgentStatus) -> Vec> { + match status { + AgentStatus::PendingInit => vec![Span::from("Pending init").dim()], + AgentStatus::Running => vec![Span::from("Running").cyan().bold()], + AgentStatus::Completed(message) => { + let mut spans = vec![Span::from("Completed").green()]; + if let Some(message) = message.as_ref() { let message_preview = truncate_text( &message.split_whitespace().collect::>().join(" "), COLLAB_AGENT_RESPONSE_PREVIEW_GRAPHEMES, ); - spans.push(Span::from(": ").dim()); - spans.push(Span::from(message_preview)); + if !message_preview.is_empty() { + spans.push(Span::from(" - ").dim()); + spans.push(Span::from(message_preview)); + } } - AgentStatus::Errored(error) => { - let error_preview = truncate_text( - &error.split_whitespace().collect::>().join(" "), - COLLAB_AGENT_ERROR_PREVIEW_GRAPHEMES, - ); - spans.push(Span::from(": ").dim()); + spans + } + AgentStatus::Errored(error) => { + let mut spans = vec![Span::from("Error").red()]; + let error_preview = truncate_text( + &error.split_whitespace().collect::>().join(" "), + COLLAB_AGENT_ERROR_PREVIEW_GRAPHEMES, + ); + if !error_preview.is_empty() { + spans.push(Span::from(" - ").dim()); spans.push(Span::from(error_preview).dim()); } - _ => {} + spans } - spans.into() - })); - lines + AgentStatus::Shutdown => vec![Span::from("Shutdown").dim()], + AgentStatus::NotFound => vec![Span::from("Not found").red()], + } } -fn push_status_count( - spans: &mut Vec>, - count: usize, - label: &'static str, - style: impl FnOnce(Span<'static>) -> Span<'static>, -) { - if count == 0 { - return; +#[cfg(test)] +mod tests { + use super::*; + use crate::history_cell::HistoryCell; + use insta::assert_snapshot; + use pretty_assertions::assert_eq; + use ratatui::style::Color; + use ratatui::style::Modifier; + + #[test] + fn collab_events_snapshot() { + let sender_thread_id = ThreadId::from_string("00000000-0000-0000-0000-000000000001") + .expect("valid sender thread id"); + let robie_id = ThreadId::from_string("00000000-0000-0000-0000-000000000002") + .expect("valid robie thread id"); + let bob_id = ThreadId::from_string("00000000-0000-0000-0000-000000000003") + .expect("valid bob thread id"); + + let spawn = spawn_end(CollabAgentSpawnEndEvent { + call_id: "call-spawn".to_string(), + sender_thread_id, + new_thread_id: Some(robie_id), + new_agent_nickname: Some("Robie".to_string()), + new_agent_role: Some("explorer".to_string()), + prompt: "Compute 11! and reply with just the integer result.".to_string(), + status: AgentStatus::PendingInit, + }); + + let send = interaction_end(CollabAgentInteractionEndEvent { + call_id: "call-send".to_string(), + sender_thread_id, + receiver_thread_id: robie_id, + receiver_agent_nickname: Some("Robie".to_string()), + receiver_agent_role: Some("explorer".to_string()), + prompt: "Please continue and return the answer only.".to_string(), + status: AgentStatus::Running, + }); + + let waiting = waiting_begin(CollabWaitingBeginEvent { + sender_thread_id, + receiver_thread_ids: vec![robie_id], + receiver_agents: vec![CollabAgentRef { + thread_id: robie_id, + agent_nickname: Some("Robie".to_string()), + agent_role: Some("explorer".to_string()), + }], + call_id: "call-wait".to_string(), + }); + + let mut statuses = HashMap::new(); + statuses.insert( + robie_id, + AgentStatus::Completed(Some("39916800".to_string())), + ); + statuses.insert(bob_id, AgentStatus::Errored("tool timeout".to_string())); + let finished = waiting_end(CollabWaitingEndEvent { + sender_thread_id, + call_id: "call-wait".to_string(), + agent_statuses: vec![ + CollabAgentStatusEntry { + thread_id: robie_id, + agent_nickname: Some("Robie".to_string()), + agent_role: Some("explorer".to_string()), + status: AgentStatus::Completed(Some("39916800".to_string())), + }, + CollabAgentStatusEntry { + thread_id: bob_id, + agent_nickname: Some("Bob".to_string()), + agent_role: Some("worker".to_string()), + status: AgentStatus::Errored("tool timeout".to_string()), + }, + ], + statuses, + }); + + let close = close_end(CollabCloseEndEvent { + call_id: "call-close".to_string(), + sender_thread_id, + receiver_thread_id: robie_id, + receiver_agent_nickname: Some("Robie".to_string()), + receiver_agent_role: Some("explorer".to_string()), + status: AgentStatus::Completed(Some("39916800".to_string())), + }); + + let snapshot = [spawn, send, waiting, finished, close] + .iter() + .map(cell_to_text) + .collect::>() + .join("\n\n"); + assert_snapshot!("collab_agent_transcript", snapshot); } - spans.push(Span::from(" · ").dim()); - spans.push(style(Span::from(format!("{count} {label}")))); -} + #[test] + fn title_styles_nickname_and_role() { + let sender_thread_id = ThreadId::from_string("00000000-0000-0000-0000-000000000001") + .expect("valid sender thread id"); + let robie_id = ThreadId::from_string("00000000-0000-0000-0000-000000000002") + .expect("valid robie thread id"); + let cell = spawn_end(CollabAgentSpawnEndEvent { + call_id: "call-spawn".to_string(), + sender_thread_id, + new_thread_id: Some(robie_id), + new_agent_nickname: Some("Robie".to_string()), + new_agent_role: Some("explorer".to_string()), + prompt: String::new(), + status: AgentStatus::PendingInit, + }); -fn detail_line_spans(label: &str, mut value: Vec>) -> Line<'static> { - let mut spans = Vec::with_capacity(value.len() + 1); - spans.push(Span::from(format!("{label}: ")).dim()); - spans.append(&mut value); - spans.into() + let lines = cell.display_lines(200); + let title = &lines[0]; + assert_eq!(title.spans[2].content.as_ref(), "Robie"); + assert_eq!(title.spans[2].style.fg, Some(Color::LightBlue)); + assert!(title.spans[2].style.add_modifier.contains(Modifier::BOLD)); + assert_eq!(title.spans[4].content.as_ref(), "[explorer]"); + assert!(title.spans[4].style.add_modifier.contains(Modifier::DIM)); + } + + fn cell_to_text(cell: &PlainHistoryCell) -> String { + cell.display_lines(200) + .iter() + .map(line_to_text) + .collect::>() + .join("\n") + } + + fn line_to_text(line: &Line<'static>) -> String { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::>() + .join("") + } } diff --git a/codex-rs/tui/src/snapshots/codex_tui__multi_agents__tests__collab_agent_transcript.snap b/codex-rs/tui/src/snapshots/codex_tui__multi_agents__tests__collab_agent_transcript.snap new file mode 100644 index 0000000000..19001a70df --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__multi_agents__tests__collab_agent_transcript.snap @@ -0,0 +1,17 @@ +--- +source: tui/src/multi_agents.rs +expression: snapshot +--- +• Spawned Robie [explorer] + └ Compute 11! and reply with just the integer result. + +• Sent input to Robie [explorer] + └ Please continue and return the answer only. + +• Waiting for Robie [explorer] + +• Finished waiting + └ Robie [explorer]: Completed - 39916800 + Bob [worker]: Error - tool timeout + +• Closed Robie [explorer] From 5a30cd3f92f28ba9a32b38c6d277b377493a253b Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 15:40:34 +0000 Subject: [PATCH 011/385] feat: better agent picker in TUI (#12332) Screenshot 2026-02-20 at 15 04 52 --- codex-rs/tui/src/app.rs | 94 +++++++++++++++++-- ...i__app__tests__agent_picker_item_name.snap | 9 ++ 2 files changed, 94 insertions(+), 9 deletions(-) create mode 100644 codex-rs/tui/src/snapshots/codex_tui__app__tests__agent_picker_item_name.snap diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index a46a927fbc..5898059644 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -808,38 +808,57 @@ impl App { async fn open_agent_picker(&mut self) { let thread_ids: Vec = self.thread_event_channels.keys().cloned().collect(); + let mut agent_threads = Vec::new(); for thread_id in thread_ids { - if self.server.get_thread(thread_id).await.is_err() { - self.thread_event_channels.remove(&thread_id); + match self.server.get_thread(thread_id).await { + Ok(thread) => { + let session_source = thread.config_snapshot().await.session_source; + agent_threads.push(( + thread_id, + session_source.get_nickname(), + session_source.get_agent_role(), + )); + } + Err(_) => { + self.thread_event_channels.remove(&thread_id); + } } } - if self.thread_event_channels.is_empty() { + if agent_threads.is_empty() { self.chat_widget .add_info_message("No agents available yet.".to_string(), None); return; } - let mut thread_ids: Vec = self.thread_event_channels.keys().cloned().collect(); - thread_ids.sort_by_key(ToString::to_string); + agent_threads.sort_by(|(left, ..), (right, ..)| left.to_string().cmp(&right.to_string())); let mut initial_selected_idx = None; - let items: Vec = thread_ids + let items: Vec = agent_threads .iter() .enumerate() - .map(|(idx, thread_id)| { + .map(|(idx, (thread_id, agent_nickname, agent_role))| { if self.active_thread_id == Some(*thread_id) { initial_selected_idx = Some(idx); } let id = *thread_id; + let is_primary = self.primary_thread_id == Some(*thread_id); + let name = format_agent_picker_item_name( + *thread_id, + agent_nickname.as_deref(), + agent_role.as_deref(), + is_primary, + ); + let uuid = thread_id.to_string(); SelectionItem { - name: thread_id.to_string(), + name: name.clone(), + description: Some(uuid.clone()), is_current: self.active_thread_id == Some(*thread_id), actions: vec![Box::new(move |tx| { tx.send(AppEvent::SelectAgentThread(id)); })], dismiss_on_select: true, - search_value: Some(thread_id.to_string()), + search_value: Some(format!("{name} {uuid}")), ..Default::default() } }) @@ -2892,6 +2911,28 @@ impl App { } } +fn format_agent_picker_item_name( + _thread_id: ThreadId, + agent_nickname: Option<&str>, + agent_role: Option<&str>, + is_primary: bool, +) -> String { + if is_primary { + return "Main [default]".to_string(); + } + + let agent_nickname = agent_nickname + .map(str::trim) + .filter(|nickname| !nickname.is_empty()); + let agent_role = agent_role.map(str::trim).filter(|role| !role.is_empty()); + match (agent_nickname, agent_role) { + (Some(agent_nickname), Some(agent_role)) => format!("{agent_nickname} [{agent_role}]"), + (Some(agent_nickname), None) => agent_nickname.to_string(), + (None, Some(agent_role)) => format!("[{agent_role}]"), + (None, None) => "Agent".to_string(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -3072,6 +3113,41 @@ mod tests { Ok(()) } + #[test] + fn agent_picker_item_name_snapshot() { + let thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("valid thread id"); + let snapshot = [ + format!( + "{} | {}", + format_agent_picker_item_name(thread_id, Some("Robie"), Some("explorer"), true), + thread_id + ), + format!( + "{} | {}", + format_agent_picker_item_name(thread_id, Some("Robie"), Some("explorer"), false), + thread_id + ), + format!( + "{} | {}", + format_agent_picker_item_name(thread_id, Some("Robie"), None, false), + thread_id + ), + format!( + "{} | {}", + format_agent_picker_item_name(thread_id, None, Some("explorer"), false), + thread_id + ), + format!( + "{} | {}", + format_agent_picker_item_name(thread_id, None, None, false), + thread_id + ), + ] + .join("\n"); + assert_snapshot!("agent_picker_item_name", snapshot); + } + #[tokio::test] async fn active_non_primary_shutdown_target_returns_none_for_non_shutdown_event() -> Result<()> { diff --git a/codex-rs/tui/src/snapshots/codex_tui__app__tests__agent_picker_item_name.snap b/codex-rs/tui/src/snapshots/codex_tui__app__tests__agent_picker_item_name.snap new file mode 100644 index 0000000000..0337f424a8 --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__app__tests__agent_picker_item_name.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/app.rs +expression: snapshot +--- +Main [default] | 00000000-0000-0000-0000-000000000123 +Robie [explorer] | 00000000-0000-0000-0000-000000000123 +Robie | 00000000-0000-0000-0000-000000000123 +[explorer] | 00000000-0000-0000-0000-000000000123 +Agent | 00000000-0000-0000-0000-000000000123 From fd67aba114f7f2248e7e563b25d0ee9de1359717 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 17:21:45 +0000 Subject: [PATCH 012/385] feat: do not enqueue phase 2 if not necessary (#12344) --- codex-rs/state/src/runtime.rs | 116 +++++++++++++++++++++++-- codex-rs/state/src/runtime/memories.rs | 11 ++- 2 files changed, 118 insertions(+), 9 deletions(-) diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index 3635bcb865..f027cac6e8 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -2069,7 +2069,7 @@ WHERE kind = 'memory_stage1' } #[tokio::test] - async fn mark_stage1_job_succeeded_no_output_tracks_watermark_without_persisting_output() { + async fn mark_stage1_job_succeeded_no_output_skips_phase2_when_output_was_already_absent() { let codex_home = unique_temp_dir(); let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) .await @@ -2122,23 +2122,129 @@ WHERE kind = 'memory_stage1' .expect("claim stage1 up-to-date"); assert_eq!(up_to_date, Stage1JobClaimOutcome::SkippedUpToDate); + let global_job_row_count = sqlx::query("SELECT COUNT(*) AS count FROM jobs WHERE kind = ?") + .bind("memory_consolidate_global") + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load phase2 job row count") + .try_get::("count") + .expect("phase2 job row count"); + assert_eq!( + global_job_row_count, 0, + "no-output without an existing stage1 output should not enqueue phase2" + ); + let claim_phase2 = runtime .try_claim_global_phase2_job(owner, 3600) .await .expect("claim phase2"); + assert_eq!( + claim_phase2, + Phase2JobClaimOutcome::SkippedNotDirty, + "phase2 should remain clean when no-output deleted nothing" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn mark_stage1_job_succeeded_no_output_enqueues_phase2_when_deleting_output() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let first_claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim initial stage1"); + let first_token = match first_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected initial stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded(thread_id, first_token.as_str(), 100, "raw", "sum", None) + .await + .expect("mark initial stage1 succeeded"), + "initial stage1 success should create stage1 output" + ); + + let phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2 after initial output"); + let (phase2_token, phase2_input_watermark) = match phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim after initial output: {other:?}"), + }; + assert_eq!(phase2_input_watermark, 100); + assert!( + runtime + .mark_global_phase2_job_succeeded(phase2_token.as_str(), phase2_input_watermark) + .await + .expect("mark initial phase2 succeeded"), + "initial phase2 success should clear global dirty state" + ); + + let no_output_claim = runtime + .try_claim_stage1_job(thread_id, owner_b, 101, 3600, 64) + .await + .expect("claim stage1 for no-output delete"); + let no_output_token = match no_output_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected no-output stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded_no_output(thread_id, no_output_token.as_str()) + .await + .expect("mark stage1 no-output after existing output"), + "no-output should succeed when deleting an existing stage1 output" + ); + + let output_row_count = + sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load stage1 output count after delete") + .try_get::("count") + .expect("stage1 output count"); + assert_eq!(output_row_count, 0); + + let claim_phase2 = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2 after no-output deletion"); let (phase2_token, phase2_input_watermark) = match claim_phase2 { Phase2JobClaimOutcome::Claimed { ownership_token, input_watermark, } => (ownership_token, input_watermark), - other => panic!("unexpected phase2 claim outcome after no-output success: {other:?}"), + other => panic!("unexpected phase2 claim after no-output deletion: {other:?}"), }; - assert_eq!(phase2_input_watermark, 100); + assert_eq!(phase2_input_watermark, 101); assert!( runtime - .mark_global_phase2_job_succeeded(phase2_token.as_str(), phase2_input_watermark,) + .mark_global_phase2_job_succeeded(phase2_token.as_str(), phase2_input_watermark) .await - .expect("mark phase2 succeeded after no-output") + .expect("mark phase2 succeeded after no-output delete") ); let _ = tokio::fs::remove_dir_all(codex_home).await; diff --git a/codex-rs/state/src/runtime/memories.rs b/codex-rs/state/src/runtime/memories.rs index f2a50e3c99..bad5679eac 100644 --- a/codex-rs/state/src/runtime/memories.rs +++ b/codex-rs/state/src/runtime/memories.rs @@ -498,7 +498,7 @@ WHERE excluded.source_updated_at >= stage1_outputs.source_updated_at /// - sets `status='done'` and `last_success_watermark = input_watermark` /// - deletes any existing `stage1_outputs` row for the thread /// - enqueues/advances the global phase-2 job watermark using the claimed - /// `input_watermark` + /// `input_watermark` only when deleting an existing `stage1_outputs` row pub async fn mark_stage1_job_succeeded_no_output( &self, thread_id: ThreadId, @@ -548,7 +548,7 @@ WHERE kind = ? AND job_key = ? AND ownership_token = ? .await? .try_get::("input_watermark")?; - sqlx::query( + let deleted_rows = sqlx::query( r#" DELETE FROM stage1_outputs WHERE thread_id = ? @@ -556,9 +556,12 @@ WHERE thread_id = ? ) .bind(thread_id.as_str()) .execute(&mut *tx) - .await?; + .await? + .rows_affected(); - enqueue_global_consolidation_with_executor(&mut *tx, source_updated_at).await?; + if deleted_rows > 0 { + enqueue_global_consolidation_with_executor(&mut *tx, source_updated_at).await?; + } tx.commit().await?; Ok(true) From 5b712460017b708334b8f4e85065dbeb70d7de9f Mon Sep 17 00:00:00 2001 From: Yaroslav Volovich Date: Fri, 20 Feb 2026 17:52:21 +0000 Subject: [PATCH 013/385] fix: simplify macOS sleep inhibitor FFI (#12340) Summary - simplify the macOS sleep inhibitor FFI by replacing `dlopen` / `dlsym` / `transmute` with normal IOKit extern calls and `SAFETY` comments - switch to cfg-selected platform implementations (`imp::SleepInhibitor`) instead of `Box` - check in minimal IOKit bindings generated with `bindgen` and include them from the macOS backend - enable direct IOKit linkage in Bazel macOS builds by registering `IOKit` in the Bazel `osx.framework(...)` toolchain extension list - update `Cargo.lock` and `MODULE.bazel.lock` after removing the build-time `bindgen` dependency path Testing - `just fmt` - `cargo clippy -p codex-utils-sleep-inhibitor --all-targets -- -D warnings` - `cargo test -p codex-utils-sleep-inhibitor` - `bazel test //codex-rs/utils/sleep-inhibitor:all --test_output=errors` - `just bazel-lock-update` - `just bazel-lock-check` Context - follow-up to #11711 addressing Ryan's review comments - `bindgen` is used to generate the checked-in bindings file, but not at build time --- MODULE.bazel | 1 + codex-rs/Cargo.lock | 21 +- codex-rs/utils/sleep-inhibitor/Cargo.toml | 1 - codex-rs/utils/sleep-inhibitor/src/dummy.rs | 12 +- .../sleep-inhibitor/src/iokit_bindings.rs | 27 +++ codex-rs/utils/sleep-inhibitor/src/lib.rs | 25 +-- codex-rs/utils/sleep-inhibitor/src/macos.rs | 107 ++++++++++ .../sleep-inhibitor/src/macos_inhibitor.rs | 192 ------------------ 8 files changed, 159 insertions(+), 227 deletions(-) create mode 100644 codex-rs/utils/sleep-inhibitor/src/iokit_bindings.rs create mode 100644 codex-rs/utils/sleep-inhibitor/src/macos.rs delete mode 100644 codex-rs/utils/sleep-inhibitor/src/macos_inhibitor.rs diff --git a/MODULE.bazel b/MODULE.bazel index 35dd575006..821e41878f 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -20,6 +20,7 @@ osx.framework(name = "CFNetwork") osx.framework(name = "FontServices") osx.framework(name = "Foundation") osx.framework(name = "ImageIO") +osx.framework(name = "IOKit") osx.framework(name = "Kernel") osx.framework(name = "OSLog") osx.framework(name = "Security") diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 20099b02eb..8d7edc4678 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -423,7 +423,7 @@ dependencies = [ "objc2-foundation", "parking_lot", "percent-encoding", - "windows-sys 0.52.0", + "windows-sys 0.60.2", "wl-clipboard-rs", "x11rb", ] @@ -2451,7 +2451,6 @@ name = "codex-utils-sleep-inhibitor" version = "0.0.0" dependencies = [ "core-foundation 0.9.4", - "libc", "tracing", ] @@ -3241,7 +3240,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.2", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3486,7 +3485,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4879,7 +4878,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5587,7 +5586,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6153,7 +6152,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.45.0", + "windows-sys 0.61.2", ] [[package]] @@ -6714,7 +6713,7 @@ dependencies = [ "once_cell", "socket2 0.6.2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -7540,7 +7539,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.11.0", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8917,7 +8916,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.3", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -10277,7 +10276,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/codex-rs/utils/sleep-inhibitor/Cargo.toml b/codex-rs/utils/sleep-inhibitor/Cargo.toml index 703433d819..f691b191e1 100644 --- a/codex-rs/utils/sleep-inhibitor/Cargo.toml +++ b/codex-rs/utils/sleep-inhibitor/Cargo.toml @@ -9,5 +9,4 @@ workspace = true [target.'cfg(target_os = "macos")'.dependencies] core-foundation = "0.9" -libc = { workspace = true } tracing = { workspace = true } diff --git a/codex-rs/utils/sleep-inhibitor/src/dummy.rs b/codex-rs/utils/sleep-inhibitor/src/dummy.rs index 767091ea93..a0be0dc650 100644 --- a/codex-rs/utils/sleep-inhibitor/src/dummy.rs +++ b/codex-rs/utils/sleep-inhibitor/src/dummy.rs @@ -1,16 +1,12 @@ -use crate::PlatformSleepInhibitor; - #[derive(Debug, Default)] -pub(crate) struct DummySleepInhibitor; +pub(crate) struct SleepInhibitor; -impl DummySleepInhibitor { +impl SleepInhibitor { pub(crate) fn new() -> Self { Self } -} -impl PlatformSleepInhibitor for DummySleepInhibitor { - fn acquire(&mut self) {} + pub(crate) fn acquire(&mut self) {} - fn release(&mut self) {} + pub(crate) fn release(&mut self) {} } diff --git a/codex-rs/utils/sleep-inhibitor/src/iokit_bindings.rs b/codex-rs/utils/sleep-inhibitor/src/iokit_bindings.rs new file mode 100644 index 0000000000..50fd7fe510 --- /dev/null +++ b/codex-rs/utils/sleep-inhibitor/src/iokit_bindings.rs @@ -0,0 +1,27 @@ +/* automatically generated by rust-bindgen 0.71.1 */ + +pub const kIOReturnSuccess: u32 = 0; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct __CFString { + _unused: [u8; 0], +} +pub type CFStringRef = *const __CFString; +pub type kern_return_t = ::std::os::raw::c_int; +pub type IOReturn = kern_return_t; +pub type IOPMAssertionID = u32; +pub type IOPMAssertionLevel = u32; +pub const kIOPMAssertionLevelOff: _bindgen_ty_36 = 0; +pub const kIOPMAssertionLevelOn: _bindgen_ty_36 = 255; +pub type _bindgen_ty_36 = ::std::os::raw::c_uint; +unsafe extern "C" { + pub fn IOPMAssertionRelease(AssertionID: IOPMAssertionID) -> IOReturn; +} +unsafe extern "C" { + pub fn IOPMAssertionCreateWithName( + AssertionType: CFStringRef, + AssertionLevel: IOPMAssertionLevel, + AssertionName: CFStringRef, + AssertionID: *mut IOPMAssertionID, + ) -> IOReturn; +} diff --git a/codex-rs/utils/sleep-inhibitor/src/lib.rs b/codex-rs/utils/sleep-inhibitor/src/lib.rs index 0f2f32df64..810fb170a2 100644 --- a/codex-rs/utils/sleep-inhibitor/src/lib.rs +++ b/codex-rs/utils/sleep-inhibitor/src/lib.rs @@ -6,31 +6,26 @@ #[cfg(not(target_os = "macos"))] mod dummy; #[cfg(target_os = "macos")] -mod macos_inhibitor; +mod macos; -use std::fmt::Debug; +#[cfg(not(target_os = "macos"))] +use dummy as imp; +#[cfg(target_os = "macos")] +use macos as imp; /// Keeps the machine awake while a turn is in progress when enabled. #[derive(Debug)] pub struct SleepInhibitor { enabled: bool, - platform: Box, -} - -pub(crate) trait PlatformSleepInhibitor: Debug { - fn acquire(&mut self); - fn release(&mut self); + platform: imp::SleepInhibitor, } impl SleepInhibitor { pub fn new(enabled: bool) -> Self { - #[cfg(target_os = "macos")] - let platform: Box = - Box::new(macos_inhibitor::MacOsSleepInhibitor::new()); - #[cfg(not(target_os = "macos"))] - let platform: Box = Box::new(dummy::DummySleepInhibitor::new()); - - Self { enabled, platform } + Self { + enabled, + platform: imp::SleepInhibitor::new(), + } } /// Update the active turn state; turns sleep prevention on/off as needed. diff --git a/codex-rs/utils/sleep-inhibitor/src/macos.rs b/codex-rs/utils/sleep-inhibitor/src/macos.rs new file mode 100644 index 0000000000..b8aaf29ab3 --- /dev/null +++ b/codex-rs/utils/sleep-inhibitor/src/macos.rs @@ -0,0 +1,107 @@ +use core_foundation::base::TCFType; +use core_foundation::string::CFString; +use tracing::warn; + +#[allow( + dead_code, + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + clippy::all +)] +mod iokit { + #[link(name = "IOKit", kind = "framework")] + unsafe extern "C" {} + + include!("iokit_bindings.rs"); +} + +type IOPMAssertionID = iokit::IOPMAssertionID; +type IOPMAssertionLevel = iokit::IOPMAssertionLevel; +type IOReturn = iokit::IOReturn; + +const ASSERTION_REASON: &str = "Codex is running an active turn"; +// Apple exposes this assertion type as a `CFSTR(...)` macro, so bindgen cannot generate a +// reusable `CFStringRef` constant for it. +const ASSERTION_TYPE_PREVENT_USER_IDLE_SYSTEM_SLEEP: &str = "PreventUserIdleSystemSleep"; + +#[derive(Debug, Default)] +pub(crate) struct SleepInhibitor { + assertion: Option, +} + +impl SleepInhibitor { + pub(crate) fn new() -> Self { + Self::default() + } + + pub(crate) fn acquire(&mut self) { + if self.assertion.is_some() { + return; + } + + match MacSleepAssertion::create(ASSERTION_REASON) { + Ok(assertion) => { + self.assertion = Some(assertion); + } + Err(error) => { + warn!( + iokit_error = error, + "Failed to create macOS sleep-prevention assertion" + ); + } + } + } + + pub(crate) fn release(&mut self) { + self.assertion = None; + } +} + +#[derive(Debug)] +struct MacSleepAssertion { + id: IOPMAssertionID, +} + +impl MacSleepAssertion { + fn create(name: &str) -> Result { + let assertion_type = CFString::new(ASSERTION_TYPE_PREVENT_USER_IDLE_SYSTEM_SLEEP); + let assertion_name = CFString::new(name); + let mut id: IOPMAssertionID = 0; + // `core-foundation` and the generated bindings each declare an opaque `__CFString` type, + // so we cast to the bindgen pointer aliases before crossing the FFI boundary. + let assertion_type_ref: iokit::CFStringRef = assertion_type.as_concrete_TypeRef().cast(); + let assertion_name_ref: iokit::CFStringRef = assertion_name.as_concrete_TypeRef().cast(); + let result = unsafe { + // SAFETY: `assertion_type_ref` and `assertion_name_ref` are valid `CFStringRef`s and + // `&mut id` is a valid out-pointer for `IOPMAssertionCreateWithName` to initialize. + iokit::IOPMAssertionCreateWithName( + assertion_type_ref, + iokit::kIOPMAssertionLevelOn as IOPMAssertionLevel, + assertion_name_ref, + &mut id, + ) + }; + if result == iokit::kIOReturnSuccess as IOReturn { + Ok(Self { id }) + } else { + Err(result) + } + } +} + +impl Drop for MacSleepAssertion { + fn drop(&mut self) { + let result = unsafe { + // SAFETY: `self.id` was returned by `IOPMAssertionCreateWithName` and this `Drop` + // implementation releases it exactly once when the owning assertion is dropped. + iokit::IOPMAssertionRelease(self.id) + }; + if result != iokit::kIOReturnSuccess as IOReturn { + warn!( + iokit_error = result, + "Failed to release macOS sleep-prevention assertion" + ); + } + } +} diff --git a/codex-rs/utils/sleep-inhibitor/src/macos_inhibitor.rs b/codex-rs/utils/sleep-inhibitor/src/macos_inhibitor.rs deleted file mode 100644 index e788705e1c..0000000000 --- a/codex-rs/utils/sleep-inhibitor/src/macos_inhibitor.rs +++ /dev/null @@ -1,192 +0,0 @@ -use crate::PlatformSleepInhibitor; -use core_foundation::base::TCFType; -use core_foundation::string::CFString; -use core_foundation::string::CFStringRef; -use std::fmt::Debug; -use std::sync::OnceLock; -use tracing::warn; - -const ASSERTION_REASON: &str = "Codex is running an active turn"; -const MACOS_IDLE_SLEEP_ASSERTION_TYPE: &str = "PreventUserIdleSystemSleep"; -const IOKIT_FRAMEWORK_BINARY: &[u8] = b"/System/Library/Frameworks/IOKit.framework/IOKit\0"; -const IOPM_ASSERTION_CREATE_WITH_NAME_SYMBOL: &[u8] = b"IOPMAssertionCreateWithName\0"; -const IOPM_ASSERTION_RELEASE_SYMBOL: &[u8] = b"IOPMAssertionRelease\0"; -const IOKIT_ASSERTION_API_UNAVAILABLE: &str = "IOKit power assertion APIs are unavailable"; - -type IOPMAssertionReleaseFn = unsafe extern "C" fn(assertion_id: IOPMAssertionID) -> IOReturn; -type IOPMAssertionID = u32; -type IOPMAssertionLevel = u32; -type IOReturn = i32; - -const K_IOPM_ASSERTION_LEVEL_ON: IOPMAssertionLevel = 255; -const K_IORETURN_SUCCESS: IOReturn = 0; - -#[derive(Debug, Default)] -pub(crate) struct MacOsSleepInhibitor { - assertion: Option, -} - -impl MacOsSleepInhibitor { - pub(crate) fn new() -> Self { - Self { - ..Default::default() - } - } -} - -impl PlatformSleepInhibitor for MacOsSleepInhibitor { - fn acquire(&mut self) { - if self.assertion.is_some() { - return; - } - - match MacSleepAssertion::create(ASSERTION_REASON) { - Ok(assertion) => { - self.assertion = Some(assertion); - } - Err(error) => match error { - MacSleepAssertionError::ApiUnavailable(reason) => { - warn!(reason, "Failed to create macOS sleep-prevention assertion"); - } - MacSleepAssertionError::Iokit(code) => { - warn!( - iokit_error = code, - "Failed to create macOS sleep-prevention assertion" - ); - } - }, - } - } - - fn release(&mut self) { - self.assertion = None; - } -} - -#[derive(Debug)] -struct MacSleepAssertion { - id: IOPMAssertionID, -} - -impl MacSleepAssertion { - fn create(name: &str) -> Result { - let Some(api) = MacSleepApi::get() else { - return Err(MacSleepAssertionError::ApiUnavailable( - IOKIT_ASSERTION_API_UNAVAILABLE, - )); - }; - - let assertion_type = CFString::new(MACOS_IDLE_SLEEP_ASSERTION_TYPE); - let assertion_name = CFString::new(name); - let mut id: IOPMAssertionID = 0; - let result = unsafe { - (api.create_with_name)( - assertion_type.as_concrete_TypeRef(), - K_IOPM_ASSERTION_LEVEL_ON, - assertion_name.as_concrete_TypeRef(), - &mut id, - ) - }; - if result == K_IORETURN_SUCCESS { - Ok(Self { id }) - } else { - Err(MacSleepAssertionError::Iokit(result)) - } - } -} - -impl Drop for MacSleepAssertion { - fn drop(&mut self) { - let Some(api) = MacSleepApi::get() else { - warn!( - reason = IOKIT_ASSERTION_API_UNAVAILABLE, - "Failed to release macOS sleep-prevention assertion" - ); - return; - }; - - let result = unsafe { (api.release)(self.id) }; - if result != K_IORETURN_SUCCESS { - warn!( - iokit_error = result, - "Failed to release macOS sleep-prevention assertion" - ); - } - } -} - -#[derive(Debug, Clone, Copy)] -enum MacSleepAssertionError { - ApiUnavailable(&'static str), - Iokit(IOReturn), -} - -type IOPMAssertionCreateWithNameFn = unsafe extern "C" fn( - assertion_type: CFStringRef, - assertion_level: IOPMAssertionLevel, - assertion_name: CFStringRef, - assertion_id: *mut IOPMAssertionID, -) -> IOReturn; - -struct MacSleepApi { - // Keep the dlopen handle alive for the lifetime of the loaded symbols. - // This prevents accidental dlclose while function pointers are in use. - _iokit_handle: usize, - create_with_name: IOPMAssertionCreateWithNameFn, - release: IOPMAssertionReleaseFn, -} - -impl MacSleepApi { - fn get() -> Option<&'static Self> { - static API: OnceLock> = OnceLock::new(); - API.get_or_init(Self::load).as_ref() - } - - fn load() -> Option { - let handle = unsafe { - libc::dlopen( - IOKIT_FRAMEWORK_BINARY.as_ptr().cast(), - libc::RTLD_LOCAL | libc::RTLD_LAZY, - ) - }; - if handle.is_null() { - warn!(framework = "IOKit", "Failed to open IOKit framework"); - return None; - } - - let create_with_name = unsafe { - libc::dlsym( - handle, - IOPM_ASSERTION_CREATE_WITH_NAME_SYMBOL.as_ptr().cast(), - ) - }; - if create_with_name.is_null() { - warn!( - symbol = "IOPMAssertionCreateWithName", - "Failed to load IOKit symbol" - ); - let _ = unsafe { libc::dlclose(handle) }; - return None; - } - - let release = unsafe { libc::dlsym(handle, IOPM_ASSERTION_RELEASE_SYMBOL.as_ptr().cast()) }; - if release.is_null() { - warn!( - symbol = "IOPMAssertionRelease", - "Failed to load IOKit symbol" - ); - let _ = unsafe { libc::dlclose(handle) }; - return None; - } - - let create_with_name: IOPMAssertionCreateWithNameFn = - unsafe { std::mem::transmute(create_with_name) }; - let release: IOPMAssertionReleaseFn = unsafe { std::mem::transmute(release) }; - - Some(Self { - _iokit_handle: handle as usize, - create_with_name, - release, - }) - } -} From 035c4c30bb0a9468ec35ad8a5ae693a0fee6ae46 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 20 Feb 2026 17:53:51 +0000 Subject: [PATCH 014/385] fix: nick name at thread/read (#12347) --- .../app-server/src/codex_message_processor.rs | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 44444494df..60c9c4638a 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -6798,6 +6798,12 @@ pub(crate) async fn read_summary_from_rollout( meta: session_meta, git, } = session_meta_line; + let mut session_meta = session_meta; + session_meta.source = with_thread_spawn_agent_metadata( + session_meta.source.clone(), + session_meta.agent_nickname.clone(), + session_meta.agent_role.clone(), + ); let created_at = if session_meta.timestamp.is_empty() { None @@ -7174,6 +7180,52 @@ mod tests { Ok(()) } + #[tokio::test] + async fn read_summary_from_rollout_preserves_agent_nickname() -> Result<()> { + use codex_protocol::protocol::RolloutItem; + use codex_protocol::protocol::RolloutLine; + use codex_protocol::protocol::SessionMetaLine; + use std::fs; + + let temp_dir = TempDir::new()?; + let path = temp_dir.path().join("rollout.jsonl"); + + let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; + let parent_thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; + let timestamp = "2025-09-05T16:53:11.850Z".to_string(); + + let session_meta = SessionMeta { + id: conversation_id, + timestamp: timestamp.clone(), + source: SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + }), + agent_nickname: Some("atlas".to_string()), + agent_role: Some("explorer".to_string()), + model_provider: Some("test-provider".to_string()), + ..SessionMeta::default() + }; + + let line = RolloutLine { + timestamp, + item: RolloutItem::SessionMeta(SessionMetaLine { + meta: session_meta, + git: None, + }), + }; + fs::write(&path, format!("{}\n", serde_json::to_string(&line)?))?; + + let summary = read_summary_from_rollout(path.as_path(), "fallback").await?; + let thread = summary_to_thread(summary); + + assert_eq!(thread.agent_nickname, Some("atlas".to_string())); + assert_eq!(thread.agent_role, Some("explorer".to_string())); + Ok(()) + } + #[test] fn summary_from_state_db_metadata_preserves_agent_nickname() -> Result<()> { let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; From 86803ca9bf00bc984d7f4a58342c053e3173db84 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Fri, 20 Feb 2026 10:09:46 -0800 Subject: [PATCH 015/385] Reuse connection between turns (#12294) Add a pool of one to the model client to reuse connections across turns. --- .../src/endpoint/responses_websocket.rs | 13 +++++++++ codex-rs/core/src/client.rs | 29 ++++++++++++++++++- .../core/tests/suite/client_websockets.rs | 28 ++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index aa559e9836..bdd32fbd5a 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -175,6 +175,19 @@ pub struct ResponsesWebsocketConnection { telemetry: Option>, } +impl std::fmt::Debug for ResponsesWebsocketConnection { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ResponsesWebsocketConnection") + .field("stream", &"") + .field("idle_timeout", &self.idle_timeout) + .field("server_reasoning_included", &self.server_reasoning_included) + .field("models_etag", &self.models_etag) + .field("server_model", &self.server_model) + .field("telemetry", &self.telemetry.as_ref().map(|_| "")) + .finish() + } +} + impl ResponsesWebsocketConnection { fn new( stream: WsStream, diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 658e212fa7..6f33910ce7 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -28,6 +28,7 @@ use std::collections::HashMap; use std::sync::Arc; +use std::sync::Mutex as StdMutex; use std::sync::OnceLock; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -123,6 +124,7 @@ struct ModelClientState { include_timing_metrics: bool, beta_features_header: Option, disable_websockets: AtomicBool, + cached_websocket_connection: StdMutex>, } /// Resolved API client setup for a single request attempt. @@ -228,6 +230,7 @@ impl ModelClient { include_timing_metrics, beta_features_header, disable_websockets: AtomicBool::new(false), + cached_websocket_connection: StdMutex::new(None), }), } } @@ -239,13 +242,29 @@ impl ModelClient { pub fn new_session(&self) -> ModelClientSession { ModelClientSession { client: self.clone(), - connection: None, + connection: self.take_cached_websocket_connection(), websocket_last_request: None, websocket_last_response_rx: None, turn_state: Arc::new(OnceLock::new()), } } + fn take_cached_websocket_connection(&self) -> Option { + self.state + .cached_websocket_connection + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + } + + fn store_cached_websocket_connection(&self, connection: ApiWebSocketConnection) { + *self + .state + .cached_websocket_connection + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(connection); + } + /// Compacts the current conversation history using the Compact endpoint. /// /// This is a unary call (no streaming) that returns a new list of @@ -452,6 +471,14 @@ impl ModelClient { } } +impl Drop for ModelClientSession { + fn drop(&mut self) { + if let Some(connection) = self.connection.take() { + self.client.store_cached_websocket_connection(connection); + } + } +} + impl ModelClientSession { fn activate_http_fallback(&self, websocket_enabled: bool) -> bool { websocket_enabled diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 1c7c578cae..736e5f50fe 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -118,6 +118,34 @@ async fn responses_websocket_preconnect_reuses_connection() { server.shutdown().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_websocket_reuses_connection_after_session_drop() { + skip_if_no_network!(); + + let server = start_websocket_server(vec![vec![ + vec![ev_response_created("resp-1"), ev_completed("resp-1")], + vec![ev_response_created("resp-2"), ev_completed("resp-2")], + ]]) + .await; + + let harness = websocket_harness(&server).await; + let prompt_one = prompt_with_input(vec![message_item("hello")]); + let prompt_two = prompt_with_input(vec![message_item("again")]); + + { + let mut client_session = harness.client.new_session(); + stream_until_complete(&mut client_session, &harness, &prompt_one).await; + } + + let mut client_session = harness.client.new_session(); + stream_until_complete(&mut client_session, &harness, &prompt_two).await; + + assert_eq!(server.handshakes().len(), 1); + assert_eq!(server.single_connection().len(), 2); + + server.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn responses_websocket_preconnect_is_reused_even_with_header_changes() { skip_if_no_network!(); From 41f15bf07bbc77a4f84b30f50ae1c7b28eb173cd Mon Sep 17 00:00:00 2001 From: Max Johnson <162359438+maxj-oai@users.noreply.github.com> Date: Fri, 20 Feb 2026 10:10:51 -0800 Subject: [PATCH 016/385] app-server: add JSON tracing logs (#12287) - add `LOG_FORMAT=json` support for app-server tracing logs via `tracing_subscriber`'s built-in JSON formatter - keep the default human-readable format unchanged and keep `RUST_LOG` filtering behavior - document the env var and update lockfile --- MODULE.bazel.lock | 1 + codex-rs/Cargo.lock | 13 +++++++ codex-rs/app-server/Cargo.toml | 2 +- codex-rs/app-server/README.md | 5 +++ codex-rs/app-server/src/lib.rs | 70 ++++++++++++++++++++++++++++++---- 5 files changed, 82 insertions(+), 9 deletions(-) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 03ad23ff77..008baf9393 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1332,6 +1332,7 @@ "tracing-error_0.2.1": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"default_features\":false,\"features\":[\"registry\",\"fmt\"],\"name\":\"tracing-subscriber\",\"req\":\"^0.3.0\"}],\"features\":{\"default\":[\"traced-error\"],\"traced-error\":[]}}", "tracing-log_0.2.0": "{\"dependencies\":[{\"name\":\"ahash\",\"optional\":true,\"req\":\"^0.7.6\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"name\":\"log\",\"req\":\"^0.4.17\"},{\"name\":\"lru\",\"optional\":true,\"req\":\"^0.7.7\"},{\"name\":\"once_cell\",\"req\":\"^1.13.0\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"name\":\"tracing-core\",\"req\":\"^0.1.28\"}],\"features\":{\"default\":[\"log-tracer\",\"std\"],\"interest-cache\":[\"lru\",\"ahash\"],\"log-tracer\":[],\"std\":[\"log/std\"]}}", "tracing-opentelemetry_0.32.1": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"name\":\"js-sys\",\"req\":\"^0.3.64\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(target_os = \\\"wasi\\\")))\"},{\"name\":\"lazy_static\",\"optional\":true,\"req\":\"^1.0.2\"},{\"default_features\":false,\"features\":[\"trace\"],\"name\":\"opentelemetry\",\"req\":\"^0.31.0\"},{\"features\":[\"trace\",\"metrics\"],\"kind\":\"dev\",\"name\":\"opentelemetry\",\"req\":\"^0.31.0\"},{\"features\":[\"metrics\",\"grpc-tonic\"],\"kind\":\"dev\",\"name\":\"opentelemetry-otlp\",\"req\":\"^0.31.0\"},{\"features\":[\"semconv_experimental\"],\"kind\":\"dev\",\"name\":\"opentelemetry-semantic-conventions\",\"req\":\"^0.31.0\"},{\"features\":[\"trace\",\"metrics\"],\"kind\":\"dev\",\"name\":\"opentelemetry-stdout\",\"req\":\"^0.31.0\"},{\"default_features\":false,\"features\":[\"trace\",\"experimental_metrics_custom_reader\",\"testing\"],\"kind\":\"dev\",\"name\":\"opentelemetry_sdk\",\"req\":\"^0.31.0\"},{\"features\":[\"flamegraph\",\"criterion\"],\"kind\":\"dev\",\"name\":\"pprof\",\"req\":\"^0.15.0\",\"target\":\"cfg(not(target_os = \\\"windows\\\"))\"},{\"name\":\"smallvec\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"default_features\":false,\"features\":[\"std\",\"attributes\"],\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"name\":\"tracing-core\",\"req\":\"^0.1.28\"},{\"kind\":\"dev\",\"name\":\"tracing-error\",\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"tracing-log\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"features\":[\"registry\",\"std\"],\"name\":\"tracing-subscriber\",\"req\":\"^0.3.22\"},{\"default_features\":false,\"features\":[\"registry\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3.0\"},{\"name\":\"web-time\",\"req\":\"^1.0.0\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(target_os = \\\"wasi\\\")))\"}],\"features\":{\"default\":[\"tracing-log\",\"metrics\"],\"metrics\":[\"opentelemetry/metrics\",\"smallvec\"]}}", + "tracing-serde_0.2.0": "{\"dependencies\":[{\"name\":\"serde\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"name\":\"tracing-core\",\"req\":\"^0.1.28\"},{\"default_features\":false,\"name\":\"valuable-serde\",\"optional\":true,\"req\":\"^0.1.0\",\"target\":\"cfg(tracing_unstable)\"},{\"default_features\":false,\"name\":\"valuable_crate\",\"optional\":true,\"package\":\"valuable\",\"req\":\"^0.1.0\",\"target\":\"cfg(tracing_unstable)\"}],\"features\":{\"valuable\":[\"valuable_crate\",\"valuable-serde\",\"tracing-core/valuable\"]}}", "tracing-subscriber_0.3.22": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"clock\",\"std\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.26\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"kind\":\"dev\",\"name\":\"log\",\"req\":\"^0.4.17\"},{\"name\":\"matchers\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"nu-ansi-term\",\"optional\":true,\"req\":\"^0.50.0\"},{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.13.0\"},{\"name\":\"parking_lot\",\"optional\":true,\"req\":\"^0.12.1\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"regex-automata\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.140\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.82\"},{\"name\":\"sharded-slab\",\"optional\":true,\"req\":\"^0.1.4\"},{\"name\":\"smallvec\",\"optional\":true,\"req\":\"^1.9.0\"},{\"name\":\"thread_local\",\"optional\":true,\"req\":\"^1.1.4\"},{\"features\":[\"formatting\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.2\"},{\"features\":[\"formatting\",\"macros\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.2\"},{\"features\":[\"rt\",\"rt-multi-thread\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.43\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.43\"},{\"default_features\":false,\"name\":\"tracing-core\",\"req\":\"^0.1.35\"},{\"default_features\":false,\"features\":[\"std-future\",\"std\"],\"kind\":\"dev\",\"name\":\"tracing-futures\",\"req\":\"^0.2.0\"},{\"default_features\":false,\"features\":[\"log-tracer\",\"std\"],\"name\":\"tracing-log\",\"optional\":true,\"req\":\"^0.2.0\"},{\"kind\":\"dev\",\"name\":\"tracing-log\",\"req\":\"^0.2.0\"},{\"name\":\"tracing-serde\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"valuable-serde\",\"optional\":true,\"req\":\"^0.1.0\",\"target\":\"cfg(tracing_unstable)\"},{\"default_features\":false,\"name\":\"valuable_crate\",\"optional\":true,\"package\":\"valuable\",\"req\":\"^0.1.0\",\"target\":\"cfg(tracing_unstable)\"}],\"features\":{\"alloc\":[],\"ansi\":[\"fmt\",\"nu-ansi-term\"],\"default\":[\"smallvec\",\"fmt\",\"ansi\",\"tracing-log\",\"std\"],\"env-filter\":[\"matchers\",\"once_cell\",\"tracing\",\"std\",\"thread_local\",\"dep:regex-automata\"],\"fmt\":[\"registry\",\"std\"],\"json\":[\"tracing-serde\",\"serde\",\"serde_json\"],\"local-time\":[\"time/local-offset\"],\"nu-ansi-term\":[\"dep:nu-ansi-term\"],\"regex\":[],\"registry\":[\"sharded-slab\",\"thread_local\",\"std\"],\"std\":[\"alloc\",\"tracing-core/std\"],\"valuable\":[\"tracing-core/valuable\",\"valuable_crate\",\"valuable-serde\",\"tracing-serde/valuable\"]}}", "tracing-test-macro_0.2.5": "{\"dependencies\":[{\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"no-env-filter\":[]}}", "tracing-test_0.2.5": "{\"dependencies\":[{\"features\":[\"rt-multi-thread\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1\"},{\"name\":\"tracing-core\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\"],\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"tracing-test-macro\",\"req\":\"^0.2.5\"}],\"features\":{\"no-env-filter\":[\"tracing-test-macro/no-env-filter\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 8d7edc4678..87f0e4cd41 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -9530,6 +9530,16 @@ dependencies = [ "web-time", ] +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.3.22" @@ -9540,12 +9550,15 @@ dependencies = [ "nu-ansi-term", "once_cell", "regex-automata", + "serde", + "serde_json", "sharded-slab", "smallvec", "thread_local", "tracing", "tracing-core", "tracing-log", + "tracing-serde", ] [[package]] diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 84ace4e38d..302a65d2f6 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -50,7 +50,7 @@ tokio = { workspace = true, features = [ ] } tokio-tungstenite = { workspace = true } tracing = { workspace = true, features = ["log"] } -tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"] } +tracing-subscriber = { workspace = true, features = ["env-filter", "fmt", "json"] } uuid = { workspace = true, features = ["serde", "v7"] } [dev-dependencies] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 3d3cc18a9f..3246bebd8c 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -28,6 +28,11 @@ Supported transports: Websocket transport is currently experimental and unsupported. Do not rely on it for production workloads. +Tracing/log output: + +- `RUST_LOG` controls log filtering/verbosity. +- Set `LOG_FORMAT=json` to emit app-server tracing logs to `stderr` as JSON (one event per line). + Backpressure behavior: - The server uses bounded queues between transport ingress, request processing, and outbound writes. diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 8e7e1455c4..6ff802c2a9 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -49,6 +49,7 @@ use tracing::warn; use tracing_subscriber::EnvFilter; use tracing_subscriber::Layer; use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::registry::Registry; use tracing_subscriber::util::SubscriberInitExt; mod bespoke_event_handling; @@ -67,6 +68,16 @@ mod transport; pub use crate::transport::AppServerTransport; +const LOG_FORMAT_ENV_VAR: &str = "LOG_FORMAT"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum LogFormat { + Default, + Json, +} + +type StderrLogLayer = Box + Send + Sync + 'static>; + /// Control-plane messages from the processor/transport side to the outbound router task. /// /// `run_main_with_transport` now uses two loops/tasks: @@ -198,6 +209,20 @@ fn project_config_warning(config: &Config) -> Option }) } +impl LogFormat { + fn from_env_value(value: Option<&str>) -> Self { + match value.map(str::trim).map(str::to_ascii_lowercase) { + Some(value) if value == "json" => Self::Json, + _ => Self::Default, + } + } +} + +fn log_format_from_env() -> LogFormat { + let value = std::env::var(LOG_FORMAT_ENV_VAR).ok(); + LogFormat::from_env_value(value.as_deref()) +} + pub async fn run_main( codex_linux_sandbox_exe: Option, cli_config_overrides: CliConfigOverrides, @@ -342,18 +367,26 @@ pub async fn run_main_with_transport( ) })?; - // Install a simple subscriber so `tracing` output is visible. Users can - // control the log level with `RUST_LOG`. - let stderr_fmt = tracing_subscriber::fmt::layer() - .with_writer(std::io::stderr) - .with_span_events(tracing_subscriber::fmt::format::FmtSpan::FULL) - .with_filter(EnvFilter::from_default_env()); + // Install a simple subscriber so `tracing` output is visible. Users can + // control the log level with `RUST_LOG` and switch to JSON logs with + // `LOG_FORMAT=json`. + let stderr_fmt: StderrLogLayer = match log_format_from_env() { + LogFormat::Json => tracing_subscriber::fmt::layer() + .json() + .with_writer(std::io::stderr) + .with_span_events(tracing_subscriber::fmt::format::FmtSpan::FULL) + .with_filter(EnvFilter::from_default_env()) + .boxed(), + LogFormat::Default => tracing_subscriber::fmt::layer() + .with_writer(std::io::stderr) + .with_span_events(tracing_subscriber::fmt::format::FmtSpan::FULL) + .with_filter(EnvFilter::from_default_env()) + .boxed(), + }; let feedback_layer = feedback.logger_layer(); let feedback_metadata_layer = feedback.metadata_layer(); - let otel_logger_layer = otel.as_ref().and_then(|o| o.logger_layer()); - let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); let _ = tracing_subscriber::registry() @@ -594,3 +627,24 @@ pub async fn run_main_with_transport( Ok(()) } + +#[cfg(test)] +mod tests { + use super::LogFormat; + use pretty_assertions::assert_eq; + + #[test] + fn log_format_from_env_value_matches_json_values_case_insensitively() { + assert_eq!(LogFormat::from_env_value(Some("json")), LogFormat::Json); + assert_eq!(LogFormat::from_env_value(Some("JSON")), LogFormat::Json); + assert_eq!(LogFormat::from_env_value(Some(" Json ")), LogFormat::Json); + } + + #[test] + fn log_format_from_env_value_defaults_for_non_json_values() { + assert_eq!(LogFormat::from_env_value(None), LogFormat::Default); + assert_eq!(LogFormat::from_env_value(Some("")), LogFormat::Default); + assert_eq!(LogFormat::from_env_value(Some("text")), LogFormat::Default); + assert_eq!(LogFormat::from_env_value(Some("jsonl")), LogFormat::Default); + } +} From e8afaed5029fdc16cee53c2007930b1d34401b79 Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Fri, 20 Feb 2026 10:39:55 -0800 Subject: [PATCH 017/385] Refactor network approvals to host/protocol/port scope (#12140) ## Summary Simplify network approvals by removing per-attempt proxy correlation and moving to session-level approval dedupe keyed by (host, protocol, port). Instead of encoding attempt IDs into proxy credentials/URLs, we now treat approvals as a destination policy decision. - Concurrent calls to the same destination share one approval prompt. - Different destinations (or same host on different ports) get separate prompts. - Allow once approves the current queued request group only. - Allow for session caches that (host, protocol, port) and auto-allows future matching requests. - Never policy continues to deny without prompting. Example: - 3 calls: - a.com (line 443) - b.com (line 443) - a.com (line 443) => 2 prompts total (a, b), second a waits on the first decision. - a.com:80 is treated separately from a.com line 443 ## Testing - `just fmt` (in `codex-rs`) - `cargo test -p codex-core tools::network_approval::tests` - `cargo test -p codex-core` (unit tests pass; existing integration-suite failures remain in this environment) --- codex-rs/Cargo.lock | 1 - ...CommandExecutionRequestApprovalParams.json | 35 + .../schema/json/ServerRequest.json | 35 + .../codex_app_server_protocol.schemas.json | 11 + .../CommandExecutionRequestApprovalParams.ts | 5 + .../typescript/v2/NetworkApprovalContext.ts | 6 + .../typescript/v2/NetworkApprovalProtocol.ts | 5 + .../schema/typescript/v2/index.ts | 2 + .../app-server-protocol/src/protocol/v2.rs | 32 + codex-rs/app-server-test-client/src/lib.rs | 4 + codex-rs/app-server/README.md | 2 +- .../app-server/src/bespoke_event_handling.rs | 62 +- .../app-server/src/codex_message_processor.rs | 1 - codex-rs/core/src/codex.rs | 2 - codex-rs/core/src/exec.rs | 24 +- codex-rs/core/src/network_policy_decision.rs | 2 - codex-rs/core/src/sandboxing/mod.rs | 2 - codex-rs/core/src/tasks/user_shell.rs | 1 - .../core/src/tools/handlers/apply_patch.rs | 2 - codex-rs/core/src/tools/handlers/shell.rs | 3 - codex-rs/core/src/tools/network_approval.rs | 761 ++++++++---------- codex-rs/core/src/tools/orchestrator.rs | 3 - codex-rs/core/src/tools/runtimes/shell.rs | 5 +- .../core/src/tools/runtimes/unified_exec.rs | 4 +- codex-rs/core/src/tools/sandboxing.rs | 1 - .../core/src/unified_exec/async_watcher.rs | 37 - codex-rs/core/src/unified_exec/mod.rs | 2 +- .../core/src/unified_exec/process_manager.rs | 64 +- codex-rs/core/tests/suite/exec.rs | 1 - .../exec-server/src/posix/escalate_server.rs | 1 - .../linux-sandbox/tests/suite/landlock.rs | 2 - codex-rs/network-proxy/Cargo.toml | 1 - codex-rs/network-proxy/src/http_proxy.rs | 50 -- codex-rs/network-proxy/src/lib.rs | 1 - codex-rs/network-proxy/src/metadata.rs | 50 -- codex-rs/network-proxy/src/network_policy.rs | 7 - codex-rs/network-proxy/src/proxy.rs | 36 +- codex-rs/network-proxy/src/runtime.rs | 14 +- codex-rs/network-proxy/src/socks5.rs | 8 - .../tui/src/bottom_pane/approval_overlay.rs | 24 +- 40 files changed, 570 insertions(+), 739 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalContext.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalProtocol.ts delete mode 100644 codex-rs/network-proxy/src/metadata.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 87f0e4cd41..ccdfddb3ac 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1986,7 +1986,6 @@ version = "0.0.0" dependencies = [ "anyhow", "async-trait", - "base64 0.22.1", "clap", "codex-utils-absolute-path", "codex-utils-rustls-provider", diff --git a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json index 1938701952..b7ad3fe315 100644 --- a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json @@ -110,6 +110,30 @@ "type": "object" } ] + }, + "NetworkApprovalContext": { + "properties": { + "host": { + "type": "string" + }, + "protocol": { + "$ref": "#/definitions/NetworkApprovalProtocol" + } + }, + "required": [ + "host", + "protocol" + ], + "type": "object" + }, + "NetworkApprovalProtocol": { + "enum": [ + "http", + "https", + "socks5Tcp", + "socks5Udp" + ], + "type": "string" } }, "properties": { @@ -147,6 +171,17 @@ "itemId": { "type": "string" }, + "networkApprovalContext": { + "anyOf": [ + { + "$ref": "#/definitions/NetworkApprovalContext" + }, + { + "type": "null" + } + ], + "description": "Optional context for managed-network approval prompts." + }, "proposedExecpolicyAmendment": { "description": "Optional proposed execpolicy amendment to allow similar commands without prompting.", "items": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index 6be3bebc5e..865912058e 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -213,6 +213,17 @@ "itemId": { "type": "string" }, + "networkApprovalContext": { + "anyOf": [ + { + "$ref": "#/definitions/NetworkApprovalContext" + }, + { + "type": "null" + } + ], + "description": "Optional context for managed-network approval prompts." + }, "proposedExecpolicyAmendment": { "description": "Optional proposed execpolicy amendment to allow similar commands without prompting.", "items": { @@ -419,6 +430,30 @@ ], "type": "object" }, + "NetworkApprovalContext": { + "properties": { + "host": { + "type": "string" + }, + "protocol": { + "$ref": "#/definitions/NetworkApprovalProtocol" + } + }, + "required": [ + "host", + "protocol" + ], + "type": "object" + }, + "NetworkApprovalProtocol": { + "enum": [ + "http", + "https", + "socks5Tcp", + "socks5Udp" + ], + "type": "string" + }, "ParsedCommand": { "oneOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index df73bf2c46..e1e0137b7f 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -2192,6 +2192,17 @@ "itemId": { "type": "string" }, + "networkApprovalContext": { + "anyOf": [ + { + "$ref": "#/definitions/NetworkApprovalContext" + }, + { + "type": "null" + } + ], + "description": "Optional context for managed-network approval prompts." + }, "proposedExecpolicyAmendment": { "description": "Optional proposed execpolicy amendment to allow similar commands without prompting.", "items": { diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts index 290ce5669c..4021e50a6a 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts @@ -3,6 +3,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { CommandAction } from "./CommandAction"; import type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; +import type { NetworkApprovalContext } from "./NetworkApprovalContext"; export type CommandExecutionRequestApprovalParams = { threadId: string, turnId: string, itemId: string, /** @@ -19,6 +20,10 @@ approvalId?: string | null, * Optional explanatory reason (e.g. request for network access). */ reason?: string | null, +/** + * Optional context for managed-network approval prompts. + */ +networkApprovalContext?: NetworkApprovalContext | null, /** * The command to be executed. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalContext.ts b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalContext.ts new file mode 100644 index 0000000000..b4b78e473c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalContext.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; + +export type NetworkApprovalContext = { host: string, protocol: NetworkApprovalProtocol, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalProtocol.ts b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalProtocol.ts new file mode 100644 index 0000000000..9dd4066fd1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkApprovalProtocol.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type NetworkApprovalProtocol = "http" | "https" | "socks5Tcp" | "socks5Udp"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index e595d0ce0b..db94051fa6 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -100,6 +100,8 @@ export type { ModelListResponse } from "./ModelListResponse"; export type { ModelRerouteReason } from "./ModelRerouteReason"; export type { ModelReroutedNotification } from "./ModelReroutedNotification"; export type { NetworkAccess } from "./NetworkAccess"; +export type { NetworkApprovalContext } from "./NetworkApprovalContext"; +export type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; export type { NetworkRequirements } from "./NetworkRequirements"; export type { OverriddenMetadata } from "./OverriddenMetadata"; export type { PatchApplyStatus } from "./PatchApplyStatus"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index fb2f86931e..dfb185b40a 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -5,6 +5,8 @@ use crate::protocol::common::AuthMode; use codex_experimental_api_macros::ExperimentalApi; use codex_protocol::account::PlanType; use codex_protocol::approvals::ExecPolicyAmendment as CoreExecPolicyAmendment; +use codex_protocol::approvals::NetworkApprovalContext as CoreNetworkApprovalContext; +use codex_protocol::approvals::NetworkApprovalProtocol as CoreNetworkApprovalProtocol; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::config_types::ForcedLoginMethod; @@ -650,6 +652,32 @@ pub enum CommandExecutionApprovalDecision { Cancel, } +v2_enum_from_core! { + pub enum NetworkApprovalProtocol from CoreNetworkApprovalProtocol { + Http, + Https, + Socks5Tcp, + Socks5Udp, + } +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct NetworkApprovalContext { + pub host: String, + pub protocol: NetworkApprovalProtocol, +} + +impl From for NetworkApprovalContext { + fn from(value: CoreNetworkApprovalContext) -> Self { + Self { + host: value.host, + protocol: value.protocol.into(), + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -3331,6 +3359,10 @@ pub struct CommandExecutionRequestApprovalParams { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional = nullable)] pub reason: Option, + /// Optional context for managed-network approval prompts. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub network_approval_context: Option, /// The command to be executed. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional = nullable)] diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index 7b846c80f1..a1d10be334 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -1491,6 +1491,7 @@ impl CodexClient { item_id, approval_id, reason, + network_approval_context, command, cwd, command_actions, @@ -1506,6 +1507,9 @@ impl CodexClient { if let Some(reason) = reason.as_deref() { println!("< reason: {reason}"); } + if let Some(network_approval_context) = network_approval_context.as_ref() { + println!("< network approval context: {network_approval_context:?}"); + } if let Some(command) = command.as_deref() { println!("< command: {command}"); } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 3246bebd8c..95ab4e43eb 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -667,7 +667,7 @@ Certain actions (shell commands or modifying files) may require explicit user ap Order of messages: 1. `item/started` — shows the pending `commandExecution` item with `command`, `cwd`, and other fields so you can render the proposed action. -2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), `reason`, plus `command`, `cwd`, and `commandActions` for friendly display. +2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. 3. Client response — `{ "decision": "accept", "acceptSettings": { "forSession": false } }` or `{ "decision": "decline" }`. 4. `item/completed` — final `commandExecution` item with `status: "completed" | "failed" | "declined"` and execution output. Render this as the authoritative result. diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index ea4fa691d5..fca2bcc1c1 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -44,6 +44,7 @@ use codex_app_server_protocol::McpToolCallError; use codex_app_server_protocol::McpToolCallResult; use codex_app_server_protocol::McpToolCallStatus; use codex_app_server_protocol::ModelReroutedNotification; +use codex_app_server_protocol::NetworkApprovalContext as V2NetworkApprovalContext; use codex_app_server_protocol::PatchApplyStatus; use codex_app_server_protocol::PlanDeltaNotification; use codex_app_server_protocol::RawResponseItemCompletedNotification; @@ -106,6 +107,17 @@ use tracing::error; type JsonValue = serde_json::Value; +enum CommandExecutionApprovalPresentation { + Network(V2NetworkApprovalContext), + Command(CommandExecutionCompletionItem), +} + +struct CommandExecutionCompletionItem { + command: String, + cwd: PathBuf, + command_actions: Vec, +} + #[allow(clippy::too_many_arguments)] pub(crate) async fn apply_bespoke_event_handling( event: Event, @@ -245,6 +257,7 @@ pub(crate) async fn apply_bespoke_event_handling( command, cwd, reason, + network_approval_context, proposed_execpolicy_amendment, parsed_cmd, .. @@ -280,7 +293,32 @@ pub(crate) async fn apply_bespoke_event_handling( .cloned() .map(V2ParsedCommand::from) .collect::>(); - let command_string = shlex_join(&command); + let presentation = if let Some(network_approval_context) = + network_approval_context.map(V2NetworkApprovalContext::from) + { + CommandExecutionApprovalPresentation::Network(network_approval_context) + } else { + let command_string = shlex_join(&command); + let completion_item = CommandExecutionCompletionItem { + command: command_string, + cwd: cwd.clone(), + command_actions: command_actions.clone(), + }; + CommandExecutionApprovalPresentation::Command(completion_item) + }; + let (network_approval_context, command, cwd, command_actions, completion_item) = + match presentation { + CommandExecutionApprovalPresentation::Network( + network_approval_context, + ) => (Some(network_approval_context), None, None, None, None), + CommandExecutionApprovalPresentation::Command(completion_item) => ( + None, + Some(completion_item.command.clone()), + Some(completion_item.cwd.clone()), + Some(completion_item.command_actions.clone()), + Some(completion_item), + ), + }; let proposed_execpolicy_amendment_v2 = proposed_execpolicy_amendment.map(V2ExecPolicyAmendment::from); @@ -290,9 +328,10 @@ pub(crate) async fn apply_bespoke_event_handling( item_id: call_id.clone(), approval_id: approval_id.clone(), reason, - command: Some(command_string.clone()), - cwd: Some(cwd.clone()), - command_actions: Some(command_actions.clone()), + network_approval_context, + command, + cwd, + command_actions, proposed_execpolicy_amendment: proposed_execpolicy_amendment_v2, }; let rx = outgoing @@ -306,9 +345,7 @@ pub(crate) async fn apply_bespoke_event_handling( conversation_id, approval_id, call_id, - command_string, - cwd, - command_actions, + completion_item, rx, conversation, outgoing, @@ -1790,9 +1827,7 @@ async fn on_command_execution_request_approval_response( conversation_id: ThreadId, approval_id: Option, item_id: String, - command: String, - cwd: PathBuf, - command_actions: Vec, + completion_item: Option, receiver: oneshot::Receiver, conversation: Arc, outgoing: ThreadScopedOutgoingMessageSender, @@ -1864,15 +1899,16 @@ async fn on_command_execution_request_approval_response( if let Some(status) = completion_status && !suppress_subcommand_completion_item + && let Some(completion_item) = completion_item { complete_command_execution_item( conversation_id, event_turn_id.clone(), item_id.clone(), - command.clone(), - cwd.clone(), + completion_item.command, + completion_item.cwd, None, - command_actions.clone(), + completion_item.command_actions, status, &outgoing, ) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 60c9c4638a..24c89edaf3 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1763,7 +1763,6 @@ impl CodexMessageProcessor { network: started_network_proxy .as_ref() .map(codex_core::config::StartedNetworkProxy::proxy), - network_attempt_id: None, sandbox_permissions: SandboxPermissions::UseDefault, windows_sandbox_level, justification: None, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index a384ffc00f..b5614cced5 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -8347,7 +8347,6 @@ mod tests { expiration: timeout_ms.into(), env: HashMap::new(), network: None, - network_attempt_id: None, sandbox_permissions, windows_sandbox_level: turn_context.windows_sandbox_level, justification: Some("test".to_string()), @@ -8361,7 +8360,6 @@ mod tests { expiration: timeout_ms.into(), env: HashMap::new(), network: None, - network_attempt_id: None, windows_sandbox_level: turn_context.windows_sandbox_level, justification: params.justification.clone(), arg0: None, diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 4e1220b87b..1e0e59d4e0 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -15,7 +15,6 @@ use tokio::io::AsyncReadExt; use tokio::io::BufReader; use tokio::process::Child; use tokio_util::sync::CancellationToken; -use uuid::Uuid; use crate::error::CodexErr; use crate::error::Result; @@ -67,7 +66,6 @@ pub struct ExecParams { pub expiration: ExecExpiration, pub env: HashMap, pub network: Option, - pub network_attempt_id: Option, pub sandbox_permissions: SandboxPermissions, pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, pub justification: Option, @@ -186,15 +184,13 @@ pub async fn process_exec_tool_call( mut env, expiration, network, - network_attempt_id, sandbox_permissions, windows_sandbox_level, justification, arg0: _, } = params; - let network_attempt_id = network_attempt_id.map(|attempt_id| attempt_id.to_string()); if let Some(network) = network.as_ref() { - network.apply_to_env_for_attempt(&mut env, network_attempt_id.as_deref()); + network.apply_to_env(&mut env); } let (program, args) = command.split_first().ok_or_else(|| { CodexErr::Io(io::Error::new( @@ -242,7 +238,6 @@ pub(crate) async fn execute_exec_env( cwd, env, network, - network_attempt_id, expiration, sandbox, windows_sandbox_level, @@ -251,18 +246,12 @@ pub(crate) async fn execute_exec_env( arg0, } = env; - let network_attempt_id = match network_attempt_id.as_deref() { - Some(attempt_id) => Uuid::parse_str(attempt_id).ok(), - None => network.as_ref().map(|_| Uuid::new_v4()), - }; - let params = ExecParams { command, cwd, expiration, env, network: network.clone(), - network_attempt_id, sandbox_permissions, windows_sandbox_level, justification, @@ -356,14 +345,12 @@ async fn exec_windows_sandbox( cwd, mut env, network, - network_attempt_id, expiration, windows_sandbox_level, .. } = params; - let network_attempt_id = network_attempt_id.map(|attempt_id| attempt_id.to_string()); if let Some(network) = network.as_ref() { - network.apply_to_env_for_attempt(&mut env, network_attempt_id.as_deref()); + network.apply_to_env(&mut env); } // TODO(iceweasel-oai): run_windows_sandbox_capture should support all @@ -717,16 +704,13 @@ async fn exec( cwd, mut env, network, - network_attempt_id, arg0, expiration, windows_sandbox_level: _, .. } = params; - let network_attempt_id = network_attempt_id.map(|attempt_id| attempt_id.to_string()); - if let Some(network) = network.as_ref() { - network.apply_to_env_for_attempt(&mut env, network_attempt_id.as_deref()); + network.apply_to_env(&mut env); } let (program, args) = command.split_first().ok_or_else(|| { @@ -1137,7 +1121,6 @@ mod tests { expiration: 500.into(), env, network: None, - network_attempt_id: None, sandbox_permissions: SandboxPermissions::UseDefault, windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled, justification: None, @@ -1191,7 +1174,6 @@ mod tests { expiration: ExecExpiration::Cancellation(cancel_token), env, network: None, - network_attempt_id: None, sandbox_permissions: SandboxPermissions::UseDefault, windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled, justification: None, diff --git a/codex-rs/core/src/network_policy_decision.rs b/codex-rs/core/src/network_policy_decision.rs index 3da6d34d6c..81ba7db82d 100644 --- a/codex-rs/core/src/network_policy_decision.rs +++ b/codex-rs/core/src/network_policy_decision.rs @@ -220,7 +220,6 @@ mod tests { method: Some("GET".to_string()), mode: None, protocol: "http".to_string(), - attempt_id: Some("attempt-1".to_string()), decision: Some("ask".to_string()), source: Some("decider".to_string()), port: Some(80), @@ -238,7 +237,6 @@ mod tests { method: Some("GET".to_string()), mode: None, protocol: "http".to_string(), - attempt_id: Some("attempt-1".to_string()), decision: Some("deny".to_string()), source: Some("baseline_policy".to_string()), port: Some(80), diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index 4bf8f66092..f9c3c171e7 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -46,7 +46,6 @@ pub struct ExecRequest { pub cwd: PathBuf, pub env: HashMap, pub network: Option, - pub network_attempt_id: Option, pub expiration: ExecExpiration, pub sandbox: SandboxType, pub windows_sandbox_level: WindowsSandboxLevel, @@ -222,7 +221,6 @@ impl SandboxManager { cwd: spec.cwd, env, network: network.cloned(), - network_attempt_id: None, expiration: spec.expiration, sandbox, windows_sandbox_level, diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 80112c61c7..d356193f58 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -151,7 +151,6 @@ pub(crate) async fn execute_user_shell_command( Some(session.conversation_id), ), network: turn_context.network.clone(), - network_attempt_id: None, // TODO(zhao-oai): Now that we have ExecExpiration::Cancellation, we // should use that instead of an "arbitrarily large" timeout here. expiration: USER_SHELL_TIMEOUT_MS.into(), diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 49c679e520..8f14fccedf 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -143,7 +143,6 @@ impl ToolHandler for ApplyPatchHandler { turn: turn.as_ref(), call_id: call_id.clone(), tool_name: tool_name.to_string(), - network_attempt_id: None, }; let out = orchestrator .run(&mut runtime, &req, &tool_ctx, &turn, turn.approval_policy) @@ -234,7 +233,6 @@ pub(crate) async fn intercept_apply_patch( turn, call_id: call_id.to_string(), tool_name: tool_name.to_string(), - network_attempt_id: None, }; let out = orchestrator .run(&mut runtime, &req, &tool_ctx, turn, turn.approval_policy) diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 31bf3f1294..8ca6de0d80 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -54,7 +54,6 @@ impl ShellHandler { expiration: params.timeout_ms.into(), env: create_env(&turn_context.shell_environment_policy, Some(thread_id)), network: turn_context.network.clone(), - network_attempt_id: None, sandbox_permissions: params.sandbox_permissions.unwrap_or_default(), windows_sandbox_level: turn_context.windows_sandbox_level, justification: params.justification.clone(), @@ -84,7 +83,6 @@ impl ShellCommandHandler { expiration: params.timeout_ms.into(), env: create_env(&turn_context.shell_environment_policy, Some(thread_id)), network: turn_context.network.clone(), - network_attempt_id: None, sandbox_permissions: params.sandbox_permissions.unwrap_or_default(), windows_sandbox_level: turn_context.windows_sandbox_level, justification: params.justification.clone(), @@ -327,7 +325,6 @@ impl ShellHandler { turn: turn.as_ref(), call_id: call_id.clone(), tool_name, - network_attempt_id: None, }; let out = orchestrator .run(&mut runtime, &req, &tool_ctx, &turn, turn.approval_policy) diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index d5643e4feb..4a893f74e9 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -10,12 +10,14 @@ use codex_network_proxy::NetworkProtocol; use codex_network_proxy::NetworkProxy; use codex_protocol::approvals::NetworkApprovalContext; use codex_protocol::approvals::NetworkApprovalProtocol; +use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::ReviewDecision; +use indexmap::IndexMap; use std::collections::HashMap; use std::collections::HashSet; -use std::path::PathBuf; use std::sync::Arc; use tokio::sync::Mutex; +use tokio::sync::Notify; use tokio::sync::RwLock; use uuid::Uuid; @@ -27,168 +29,207 @@ pub(crate) enum NetworkApprovalMode { #[derive(Clone, Debug)] pub(crate) struct NetworkApprovalSpec { - pub command: Vec, - pub cwd: PathBuf, pub network: Option, pub mode: NetworkApprovalMode, } #[derive(Clone, Debug)] pub(crate) struct DeferredNetworkApproval { - attempt_id: String, + registration_id: String, } impl DeferredNetworkApproval { - pub(crate) fn attempt_id(&self) -> &str { - &self.attempt_id + pub(crate) fn registration_id(&self) -> &str { + &self.registration_id } } #[derive(Debug)] pub(crate) struct ActiveNetworkApproval { - attempt_id: Option, + registration_id: Option, mode: NetworkApprovalMode, } impl ActiveNetworkApproval { - pub(crate) fn attempt_id(&self) -> Option<&str> { - self.attempt_id.as_deref() - } - pub(crate) fn mode(&self) -> NetworkApprovalMode { self.mode } pub(crate) fn into_deferred(self) -> Option { - match (self.mode, self.attempt_id) { - (NetworkApprovalMode::Deferred, Some(attempt_id)) => { - Some(DeferredNetworkApproval { attempt_id }) + match (self.mode, self.registration_id) { + (NetworkApprovalMode::Deferred, Some(registration_id)) => { + Some(DeferredNetworkApproval { registration_id }) } _ => None, } } } +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct HostApprovalKey { + host: String, + protocol: &'static str, + port: u16, +} + +impl HostApprovalKey { + fn from_request(request: &NetworkPolicyRequest, protocol: NetworkApprovalProtocol) -> Self { + Self { + host: request.host.to_ascii_lowercase(), + protocol: protocol_key_label(protocol), + port: request.port, + } + } +} + +fn protocol_key_label(protocol: NetworkApprovalProtocol) -> &'static str { + match protocol { + NetworkApprovalProtocol::Http => "http", + NetworkApprovalProtocol::Https => "https", + NetworkApprovalProtocol::Socks5Tcp => "socks5-tcp", + NetworkApprovalProtocol::Socks5Udp => "socks5-udp", + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum PendingApprovalDecision { + AllowOnce, + AllowForSession, + Deny, +} + #[derive(Clone, Debug, Eq, PartialEq)] -pub(crate) enum NetworkApprovalOutcome { +enum NetworkApprovalOutcome { DeniedByUser, DeniedByPolicy(String), } -struct NetworkApprovalAttempt { - turn_id: String, - call_id: String, - command: Vec, - cwd: PathBuf, - approved_hosts: Mutex>, - outcome: Mutex>, +fn allows_network_prompt(policy: AskForApproval) -> bool { + !matches!(policy, AskForApproval::Never) +} + +impl PendingApprovalDecision { + fn to_network_decision(self) -> NetworkDecision { + match self { + Self::AllowOnce | Self::AllowForSession => NetworkDecision::Allow, + Self::Deny => NetworkDecision::deny("not_allowed"), + } + } +} + +struct PendingHostApproval { + decision: Mutex>, + notify: Notify, +} + +impl PendingHostApproval { + fn new() -> Self { + Self { + decision: Mutex::new(None), + notify: Notify::new(), + } + } + + async fn wait_for_decision(&self) -> PendingApprovalDecision { + loop { + let notified = self.notify.notified(); + if let Some(decision) = *self.decision.lock().await { + return decision; + } + notified.await; + } + } + + async fn set_decision(&self, decision: PendingApprovalDecision) { + { + let mut current = self.decision.lock().await; + *current = Some(decision); + } + self.notify.notify_waiters(); + } +} + +struct ActiveNetworkApprovalCall { + registration_id: String, } pub(crate) struct NetworkApprovalService { - attempts: Mutex>>, - session_approved_hosts: Mutex>, + active_calls: Mutex>>, + call_outcomes: Mutex>, + pending_host_approvals: Mutex>>, + session_approved_hosts: Mutex>, } impl Default for NetworkApprovalService { fn default() -> Self { Self { - attempts: Mutex::new(HashMap::new()), + active_calls: Mutex::new(IndexMap::new()), + call_outcomes: Mutex::new(HashMap::new()), + pending_host_approvals: Mutex::new(HashMap::new()), session_approved_hosts: Mutex::new(HashSet::new()), } } } impl NetworkApprovalService { - pub(crate) async fn register_attempt( - &self, - attempt_id: String, - turn_id: String, - call_id: String, - command: Vec, - cwd: PathBuf, - ) { - let mut attempts = self.attempts.lock().await; - attempts.insert( - attempt_id, - Arc::new(NetworkApprovalAttempt { - turn_id, - call_id, - command, - cwd, - approved_hosts: Mutex::new(HashSet::new()), - outcome: Mutex::new(None), - }), - ); + async fn register_call(&self, registration_id: String) { + let mut active_calls = self.active_calls.lock().await; + let key = registration_id.clone(); + active_calls.insert(key, Arc::new(ActiveNetworkApprovalCall { registration_id })); } - pub(crate) async fn unregister_attempt(&self, attempt_id: &str) { - let mut attempts = self.attempts.lock().await; - attempts.remove(attempt_id); + pub(crate) async fn unregister_call(&self, registration_id: &str) { + let mut active_calls = self.active_calls.lock().await; + active_calls.shift_remove(registration_id); + let mut call_outcomes = self.call_outcomes.lock().await; + call_outcomes.remove(registration_id); } - pub(crate) async fn take_outcome(&self, attempt_id: &str) -> Option { - let attempt = { - let attempts = self.attempts.lock().await; - attempts.get(attempt_id).cloned() - }?; - let mut outcome = attempt.outcome.lock().await; - outcome.take() - } - - pub(crate) async fn take_user_denial_outcome(&self, attempt_id: &str) -> bool { - let attempt = { - let attempts = self.attempts.lock().await; - attempts.get(attempt_id).cloned() - }; - let Some(attempt) = attempt else { - return false; - }; - let mut outcome = attempt.outcome.lock().await; - if matches!(outcome.as_ref(), Some(NetworkApprovalOutcome::DeniedByUser)) { - outcome.take(); - return true; - } - false - } - - async fn resolve_attempt_for_request( - &self, - request: &NetworkPolicyRequest, - ) -> Option> { - let attempts = self.attempts.lock().await; - - if let Some(attempt_id) = request.attempt_id.as_deref() { - if let Some(attempt) = attempts.get(attempt_id).cloned() { - return Some(attempt); - } - return None; - } - - if attempts.len() == 1 { - return attempts.values().next().cloned(); + async fn resolve_single_active_call(&self) -> Option> { + let active_calls = self.active_calls.lock().await; + if active_calls.len() == 1 { + return active_calls.values().next().cloned(); } None } - async fn resolve_attempt_for_blocked_request( + async fn get_or_create_pending_approval( &self, - blocked: &BlockedRequest, - ) -> Option> { - let attempts = self.attempts.lock().await; - - if let Some(attempt_id) = blocked.attempt_id.as_deref() { - if let Some(attempt) = attempts.get(attempt_id).cloned() { - return Some(attempt); - } - return None; + key: HostApprovalKey, + ) -> (Arc, bool) { + let mut pending = self.pending_host_approvals.lock().await; + if let Some(existing) = pending.get(&key).cloned() { + return (existing, false); } - if attempts.len() == 1 { - return attempts.values().next().cloned(); - } + let created = Arc::new(PendingHostApproval::new()); + pending.insert(key, Arc::clone(&created)); + (created, true) + } - None + async fn record_outcome_for_single_active_call(&self, outcome: NetworkApprovalOutcome) { + let Some(owner_call) = self.resolve_single_active_call().await else { + return; + }; + self.record_call_outcome(&owner_call.registration_id, outcome) + .await; + } + + async fn take_call_outcome(&self, registration_id: &str) -> Option { + let mut call_outcomes = self.call_outcomes.lock().await; + call_outcomes.remove(registration_id) + } + + async fn record_call_outcome(&self, registration_id: &str, outcome: NetworkApprovalOutcome) { + let mut call_outcomes = self.call_outcomes.lock().await; + if matches!( + call_outcomes.get(registration_id), + Some(NetworkApprovalOutcome::DeniedByUser) + ) { + return; + } + call_outcomes.insert(registration_id.to_string(), outcome); } pub(crate) async fn record_blocked_request(&self, blocked: BlockedRequest) { @@ -196,15 +237,24 @@ impl NetworkApprovalService { return; }; - let Some(attempt) = self.resolve_attempt_for_blocked_request(&blocked).await else { - return; - }; + self.record_outcome_for_single_active_call(NetworkApprovalOutcome::DeniedByPolicy(message)) + .await; + } - let mut outcome = attempt.outcome.lock().await; - if matches!(outcome.as_ref(), Some(NetworkApprovalOutcome::DeniedByUser)) { - return; - } - *outcome = Some(NetworkApprovalOutcome::DeniedByPolicy(message)); + async fn active_turn_context(session: &Session) -> Option> { + let active_turn = session.active_turn.lock().await; + active_turn + .as_ref() + .and_then(|turn| turn.tasks.first()) + .map(|(_, task)| Arc::clone(&task.turn_context)) + } + + fn format_network_target(protocol: &str, host: &str, port: u16) -> String { + format!("{protocol}://{host}:{port}") + } + + fn approval_id_for_key(key: &HostApprovalKey) -> String { + format!("network#{}#{}#{}", key.protocol, key.host, key.port) } pub(crate) async fn handle_inline_policy_request( @@ -214,46 +264,63 @@ impl NetworkApprovalService { ) -> NetworkDecision { const REASON_NOT_ALLOWED: &str = "not_allowed"; - { - let approved_hosts = self.session_approved_hosts.lock().await; - if approved_hosts.contains(request.host.as_str()) { - return NetworkDecision::Allow; - } - } - - let Some(attempt) = self.resolve_attempt_for_request(&request).await else { - return NetworkDecision::deny(REASON_NOT_ALLOWED); - }; - - { - let approved_hosts = attempt.approved_hosts.lock().await; - if approved_hosts.contains(request.host.as_str()) { - return NetworkDecision::Allow; - } - } - let protocol = match request.protocol { NetworkProtocol::Http => NetworkApprovalProtocol::Http, NetworkProtocol::HttpsConnect => NetworkApprovalProtocol::Https, NetworkProtocol::Socks5Tcp => NetworkApprovalProtocol::Socks5Tcp, NetworkProtocol::Socks5Udp => NetworkApprovalProtocol::Socks5Udp, }; + let key = HostApprovalKey::from_request(&request, protocol); - let Some(turn_context) = session.turn_context_for_sub_id(&attempt.turn_id).await else { + { + let approved_hosts = self.session_approved_hosts.lock().await; + if approved_hosts.contains(&key) { + return NetworkDecision::Allow; + } + } + + let (pending, is_owner) = self.get_or_create_pending_approval(key.clone()).await; + if !is_owner { + return pending.wait_for_decision().await.to_network_decision(); + } + + let target = Self::format_network_target(key.protocol, request.host.as_str(), key.port); + let policy_denial_message = + format!("Network access to \"{target}\" was blocked by policy."); + let prompt_reason = format!("{} is not in the allowed_domains", request.host); + + let Some(turn_context) = Self::active_turn_context(session).await else { + pending.set_decision(PendingApprovalDecision::Deny).await; + let mut pending_approvals = self.pending_host_approvals.lock().await; + pending_approvals.remove(&key); + self.record_outcome_for_single_active_call(NetworkApprovalOutcome::DeniedByPolicy( + policy_denial_message, + )) + .await; return NetworkDecision::deny(REASON_NOT_ALLOWED); }; + if !allows_network_prompt(turn_context.approval_policy) { + pending.set_decision(PendingApprovalDecision::Deny).await; + let mut pending_approvals = self.pending_host_approvals.lock().await; + pending_approvals.remove(&key); + self.record_outcome_for_single_active_call(NetworkApprovalOutcome::DeniedByPolicy( + policy_denial_message, + )) + .await; + return NetworkDecision::deny(REASON_NOT_ALLOWED); + } + + let approval_id = Self::approval_id_for_key(&key); + let prompt_command = vec!["network-access".to_string(), target.clone()]; let approval_decision = session .request_command_approval( turn_context.as_ref(), - attempt.call_id.clone(), + approval_id, None, - attempt.command.clone(), - attempt.cwd.clone(), - Some(format!( - "Network access to \"{}\" is blocked by policy.", - request.host - )), + prompt_command, + turn_context.cwd.clone(), + Some(prompt_reason), Some(NetworkApprovalContext { host: request.host.clone(), protocol, @@ -262,23 +329,28 @@ impl NetworkApprovalService { ) .await; - match approval_decision { + let resolved = match approval_decision { ReviewDecision::Approved | ReviewDecision::ApprovedExecpolicyAmendment { .. } => { - let mut approved_hosts = attempt.approved_hosts.lock().await; - approved_hosts.insert(request.host); - NetworkDecision::Allow - } - ReviewDecision::ApprovedForSession => { - let mut approved_hosts = self.session_approved_hosts.lock().await; - approved_hosts.insert(request.host); - NetworkDecision::Allow + PendingApprovalDecision::AllowOnce } + ReviewDecision::ApprovedForSession => PendingApprovalDecision::AllowForSession, ReviewDecision::Denied | ReviewDecision::Abort => { - let mut outcome = attempt.outcome.lock().await; - *outcome = Some(NetworkApprovalOutcome::DeniedByUser); - NetworkDecision::deny(REASON_NOT_ALLOWED) + self.record_outcome_for_single_active_call(NetworkApprovalOutcome::DeniedByUser) + .await; + PendingApprovalDecision::Deny } + }; + + if matches!(resolved, PendingApprovalDecision::AllowForSession) { + let mut approved_hosts = self.session_approved_hosts.lock().await; + approved_hosts.insert(key.clone()); } + + pending.set_decision(resolved).await; + let mut pending_approvals = self.pending_host_approvals.lock().await; + pending_approvals.remove(&key); + + resolved.to_network_decision() } } @@ -313,8 +385,8 @@ pub(crate) fn build_network_policy_decider( pub(crate) async fn begin_network_approval( session: &Session, - turn_id: &str, - call_id: &str, + _turn_id: &str, + _call_id: &str, has_managed_network_requirements: bool, spec: Option, ) -> Option { @@ -323,21 +395,15 @@ pub(crate) async fn begin_network_approval( return None; } - let attempt_id = Uuid::new_v4().to_string(); + let registration_id = Uuid::new_v4().to_string(); session .services .network_approval - .register_attempt( - attempt_id.clone(), - turn_id.to_string(), - call_id.to_string(), - spec.command, - spec.cwd, - ) + .register_call(registration_id.clone()) .await; Some(ActiveNetworkApproval { - attempt_id: Some(attempt_id), + registration_id: Some(registration_id), mode: spec.mode, }) } @@ -346,20 +412,20 @@ pub(crate) async fn finish_immediate_network_approval( session: &Session, active: ActiveNetworkApproval, ) -> Result<(), ToolError> { - let Some(attempt_id) = active.attempt_id.as_deref() else { + let Some(registration_id) = active.registration_id.as_deref() else { return Ok(()); }; let approval_outcome = session .services .network_approval - .take_outcome(attempt_id) + .take_call_outcome(registration_id) .await; session .services .network_approval - .unregister_attempt(attempt_id) + .unregister_call(registration_id) .await; match approval_outcome { @@ -371,22 +437,6 @@ pub(crate) async fn finish_immediate_network_approval( } } -pub(crate) async fn deferred_rejection_message( - session: &Session, - deferred: &DeferredNetworkApproval, -) -> Option { - match session - .services - .network_approval - .take_outcome(deferred.attempt_id()) - .await - { - Some(NetworkApprovalOutcome::DeniedByUser) => Some("rejected by user".to_string()), - Some(NetworkApprovalOutcome::DeniedByPolicy(message)) => Some(message), - None => None, - } -} - pub(crate) async fn finish_deferred_network_approval( session: &Session, deferred: Option, @@ -397,7 +447,7 @@ pub(crate) async fn finish_deferred_network_approval( session .services .network_approval - .unregister_attempt(deferred.attempt_id()) + .unregister_call(deferred.registration_id()) .await; } @@ -405,272 +455,145 @@ pub(crate) async fn finish_deferred_network_approval( mod tests { use super::*; use codex_network_proxy::BlockedRequestArgs; - use codex_network_proxy::NetworkPolicyRequestArgs; + use codex_protocol::protocol::AskForApproval; use pretty_assertions::assert_eq; - fn http_request(host: &str, attempt_id: Option<&str>) -> NetworkPolicyRequest { - NetworkPolicyRequest::new(NetworkPolicyRequestArgs { - protocol: NetworkProtocol::Http, + #[tokio::test] + async fn pending_approvals_are_deduped_per_host_protocol_and_port() { + let service = NetworkApprovalService::default(); + let key = HostApprovalKey { + host: "example.com".to_string(), + protocol: "http", + port: 443, + }; + + let (first, first_is_owner) = service.get_or_create_pending_approval(key.clone()).await; + let (second, second_is_owner) = service.get_or_create_pending_approval(key).await; + + assert!(first_is_owner); + assert!(!second_is_owner); + assert!(Arc::ptr_eq(&first, &second)); + } + + #[tokio::test] + async fn pending_approvals_do_not_dedupe_across_ports() { + let service = NetworkApprovalService::default(); + let first_key = HostApprovalKey { + host: "example.com".to_string(), + protocol: "https", + port: 443, + }; + let second_key = HostApprovalKey { + host: "example.com".to_string(), + protocol: "https", + port: 8443, + }; + + let (first, first_is_owner) = service.get_or_create_pending_approval(first_key).await; + let (second, second_is_owner) = service.get_or_create_pending_approval(second_key).await; + + assert!(first_is_owner); + assert!(second_is_owner); + assert!(!Arc::ptr_eq(&first, &second)); + } + + #[tokio::test] + async fn pending_waiters_receive_owner_decision() { + let pending = Arc::new(PendingHostApproval::new()); + + let waiter = { + let pending = Arc::clone(&pending); + tokio::spawn(async move { pending.wait_for_decision().await }) + }; + + pending + .set_decision(PendingApprovalDecision::AllowOnce) + .await; + + let decision = waiter.await.expect("waiter should complete"); + assert_eq!(decision, PendingApprovalDecision::AllowOnce); + } + + #[test] + fn allow_once_and_allow_for_session_both_allow_network() { + assert_eq!( + PendingApprovalDecision::AllowOnce.to_network_decision(), + NetworkDecision::Allow + ); + assert_eq!( + PendingApprovalDecision::AllowForSession.to_network_decision(), + NetworkDecision::Allow + ); + } + + #[test] + fn never_policy_disables_network_prompts() { + assert!(!allows_network_prompt(AskForApproval::Never)); + assert!(allows_network_prompt(AskForApproval::OnRequest)); + assert!(allows_network_prompt(AskForApproval::OnFailure)); + assert!(allows_network_prompt(AskForApproval::UnlessTrusted)); + } + + fn denied_blocked_request(host: &str) -> BlockedRequest { + BlockedRequest::new(BlockedRequestArgs { host: host.to_string(), - port: 80, - client_addr: None, - method: Some("GET".to_string()), - command: None, - exec_policy_hint: None, - attempt_id: attempt_id.map(ToString::to_string), + reason: "not_allowed".to_string(), + client: None, + method: None, + mode: None, + protocol: "http".to_string(), + decision: Some("deny".to_string()), + source: Some("decider".to_string()), + port: Some(80), }) } #[tokio::test] - async fn resolve_attempt_for_request_falls_back_to_single_active_attempt() { + async fn record_blocked_request_sets_policy_outcome_for_owner_call() { let service = NetworkApprovalService::default(); + service.register_call("registration-1".to_string()).await; + service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) + .record_blocked_request(denied_blocked_request("example.com")) .await; - let resolved = service - .resolve_attempt_for_request(&http_request("example.com", None)) - .await - .expect("single active attempt should be used as fallback"); - assert_eq!(resolved.call_id, "call-1"); - } - - #[tokio::test] - async fn resolve_attempt_for_request_returns_exact_attempt_match() { - let service = NetworkApprovalService::default(); - service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) - .await; - service - .register_attempt( - "attempt-2".to_string(), - "turn-2".to_string(), - "call-2".to_string(), - vec!["curl".to_string(), "openai.com".to_string()], - std::env::temp_dir(), - ) - .await; - - let resolved = service - .resolve_attempt_for_request(&http_request("openai.com", Some("attempt-2"))) - .await - .expect("attempt-2 should resolve"); - assert_eq!(resolved.call_id, "call-2"); - } - - #[tokio::test] - async fn resolve_attempt_for_request_returns_none_for_unknown_attempt_id() { - let service = NetworkApprovalService::default(); - service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) - .await; - - let resolved = service - .resolve_attempt_for_request(&http_request("example.com", Some("attempt-unknown"))) - .await; - assert!(resolved.is_none()); - } - - #[tokio::test] - async fn resolve_attempt_for_request_returns_none_when_ambiguous() { - let service = NetworkApprovalService::default(); - service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) - .await; - service - .register_attempt( - "attempt-2".to_string(), - "turn-2".to_string(), - "call-2".to_string(), - vec!["curl".to_string(), "robinhood.com".to_string()], - std::env::temp_dir(), - ) - .await; - - let resolved = service - .resolve_attempt_for_request(&http_request("example.com", None)) - .await; - assert!(resolved.is_none()); - } - - #[tokio::test] - async fn take_outcome_clears_stored_value() { - let service = NetworkApprovalService::default(); - service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) - .await; - - let attempt = { - let attempts = service.attempts.lock().await; - attempts - .get("attempt-1") - .cloned() - .expect("attempt should exist") - }; - { - let mut outcome = attempt.outcome.lock().await; - *outcome = Some(NetworkApprovalOutcome::DeniedByUser); - } - assert_eq!( - service.take_outcome("attempt-1").await, - Some(NetworkApprovalOutcome::DeniedByUser) - ); - assert_eq!(service.take_outcome("attempt-1").await, None); - } - - #[tokio::test] - async fn take_user_denial_outcome_preserves_policy_denial() { - let service = NetworkApprovalService::default(); - service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) - .await; - - let attempt = { - let attempts = service.attempts.lock().await; - attempts - .get("attempt-1") - .cloned() - .expect("attempt should exist") - }; - { - let mut outcome = attempt.outcome.lock().await; - *outcome = Some(NetworkApprovalOutcome::DeniedByPolicy( - "policy denied".to_string(), - )); - } - - assert!(!service.take_user_denial_outcome("attempt-1").await); - assert_eq!( - service.take_outcome("attempt-1").await, + service.take_call_outcome("registration-1").await, Some(NetworkApprovalOutcome::DeniedByPolicy( - "policy denied".to_string(), + "Network access to \"example.com\" was blocked: domain is not on the allowlist for the current sandbox mode.".to_string() )) ); } #[tokio::test] - async fn record_blocked_request_stores_policy_denial_outcome() { + async fn blocked_request_policy_does_not_override_user_denial_outcome() { let service = NetworkApprovalService::default(); + service.register_call("registration-1".to_string()).await; + service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) + .record_call_outcome("registration-1", NetworkApprovalOutcome::DeniedByUser) .await; - service - .record_blocked_request(BlockedRequest::new(BlockedRequestArgs { - host: "example.com".to_string(), - reason: "denied".to_string(), - client: None, - method: Some("GET".to_string()), - mode: None, - protocol: "http".to_string(), - attempt_id: Some("attempt-1".to_string()), - decision: Some("deny".to_string()), - source: Some("baseline_policy".to_string()), - port: Some(80), - })) - .await; - - let outcome = service - .take_outcome("attempt-1") - .await - .expect("outcome should be recorded"); - match outcome { - NetworkApprovalOutcome::DeniedByPolicy(message) => { - assert_eq!( - message, - "Network access to \"example.com\" was blocked: domain is explicitly denied by policy and cannot be approved from this prompt.".to_string() - ); - } - NetworkApprovalOutcome::DeniedByUser => panic!("expected policy denial"), - } - } - - #[tokio::test] - async fn record_blocked_request_does_not_override_user_denial() { - let service = NetworkApprovalService::default(); - service - .register_attempt( - "attempt-1".to_string(), - "turn-1".to_string(), - "call-1".to_string(), - vec!["curl".to_string(), "example.com".to_string()], - std::env::temp_dir(), - ) - .await; - - let attempt = { - let attempts = service.attempts.lock().await; - attempts - .get("attempt-1") - .cloned() - .expect("attempt should exist") - }; - { - let mut outcome = attempt.outcome.lock().await; - *outcome = Some(NetworkApprovalOutcome::DeniedByUser); - } - - service - .record_blocked_request(BlockedRequest::new(BlockedRequestArgs { - host: "example.com".to_string(), - reason: "denied".to_string(), - client: None, - method: Some("GET".to_string()), - mode: None, - protocol: "http".to_string(), - attempt_id: Some("attempt-1".to_string()), - decision: Some("deny".to_string()), - source: Some("baseline_policy".to_string()), - port: Some(80), - })) + .record_blocked_request(denied_blocked_request("example.com")) .await; assert_eq!( - service.take_outcome("attempt-1").await, + service.take_call_outcome("registration-1").await, Some(NetworkApprovalOutcome::DeniedByUser) ); } + + #[tokio::test] + async fn record_blocked_request_ignores_ambiguous_unattributed_blocked_requests() { + let service = NetworkApprovalService::default(); + service.register_call("registration-1".to_string()).await; + service.register_call("registration-2".to_string()).await; + + service + .record_blocked_request(denied_blocked_request("example.com")) + .await; + + assert_eq!(service.take_call_outcome("registration-1").await, None); + assert_eq!(service.take_call_outcome("registration-2").await, None); + } } diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index cdbaac0254..afb24d4b3c 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -69,9 +69,6 @@ impl ToolOrchestrator { turn: tool_ctx.turn, call_id: tool_ctx.call_id.clone(), tool_name: tool_ctx.tool_name.clone(), - network_attempt_id: network_approval.as_ref().and_then(|network_approval| { - network_approval.attempt_id().map(ToString::to_string) - }), }; let run_result = tool.run(req, attempt, &attempt_tool_ctx).await; diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index 6f1e4b44af..bcbeafadfe 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -154,8 +154,6 @@ impl ToolRuntime for ShellRuntime { ) -> Option { req.network.as_ref()?; Some(NetworkApprovalSpec { - command: req.command.clone(), - cwd: req.cwd.clone(), network: req.network.clone(), mode: NetworkApprovalMode::Immediate, }) @@ -221,10 +219,9 @@ impl ToolRuntime for ShellRuntime { req.sandbox_permissions, req.justification.clone(), )?; - let mut env = attempt + let env = attempt .env_for(spec, req.network.as_ref()) .map_err(|err| ToolError::Codex(err.into()))?; - env.network_attempt_id = ctx.network_attempt_id.clone(); let out = execute_env(env, attempt.policy, Self::stdout_stream(ctx)) .await .map_err(ToolError::Codex)?; diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index be049d0934..201de7ad84 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -157,8 +157,6 @@ impl<'a> ToolRuntime for UnifiedExecRunt ) -> Option { req.network.as_ref()?; Some(NetworkApprovalSpec { - command: req.command.clone(), - cwd: req.cwd.clone(), network: req.network.clone(), mode: NetworkApprovalMode::Deferred, }) @@ -188,7 +186,7 @@ impl<'a> ToolRuntime for UnifiedExecRunt let mut env = req.env.clone(); if let Some(network) = req.network.as_ref() { - network.apply_to_env_for_attempt(&mut env, ctx.network_attempt_id.as_deref()); + network.apply_to_env(&mut env); } let spec = build_command_spec( &command, diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 89b4bc01ec..9721fed535 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -272,7 +272,6 @@ pub(crate) struct ToolCtx<'a> { pub turn: &'a TurnContext, pub call_id: String, pub tool_name: String, - pub network_attempt_id: Option, } #[derive(Debug)] diff --git a/codex-rs/core/src/unified_exec/async_watcher.rs b/codex-rs/core/src/unified_exec/async_watcher.rs index 772baab00b..1fbb1e8f6d 100644 --- a/codex-rs/core/src/unified_exec/async_watcher.rs +++ b/codex-rs/core/src/unified_exec/async_watcher.rs @@ -139,43 +139,6 @@ pub(crate) fn spawn_exit_watcher( }); } -pub(crate) fn spawn_network_denial_watcher( - process: Arc, - session: Arc, - process_id: String, - network_attempt_id: String, -) { - let exit_token = process.cancellation_token(); - tokio::spawn(async move { - let mut poll = tokio::time::interval(Duration::from_millis(100)); - poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - - loop { - tokio::select! { - _ = exit_token.cancelled() => { - break; - } - _ = poll.tick() => { - if session - .services - .network_approval - .take_user_denial_outcome(&network_attempt_id) - .await - { - process.terminate(); - session - .services - .unified_exec_manager - .release_process_id(&process_id) - .await; - break; - } - } - } - } - }); -} - async fn process_chunk( pending: &mut Vec, transcript: &Arc>, diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 4339d25ace..a586572dd1 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -155,7 +155,7 @@ struct ProcessEntry { process_id: String, command: Vec, tty: bool, - network_attempt_id: Option, + network_approval_id: Option, session: Weak, last_used: tokio::time::Instant, } diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index f2468583d2..6945316469 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -20,7 +20,6 @@ use crate::tools::events::ToolEmitter; use crate::tools::events::ToolEventCtx; use crate::tools::events::ToolEventStage; use crate::tools::network_approval::DeferredNetworkApproval; -use crate::tools::network_approval::deferred_rejection_message; use crate::tools::network_approval::finish_deferred_network_approval; use crate::tools::orchestrator::ToolOrchestrator; use crate::tools::runtimes::unified_exec::UnifiedExecRequest as UnifiedExecToolRequest; @@ -44,7 +43,6 @@ use crate::unified_exec::WARNING_UNIFIED_EXEC_PROCESSES; use crate::unified_exec::WriteStdinRequest; use crate::unified_exec::async_watcher::emit_exec_end_for_unified_exec; use crate::unified_exec::async_watcher::spawn_exit_watcher; -use crate::unified_exec::async_watcher::spawn_network_denial_watcher; use crate::unified_exec::async_watcher::start_streaming_output; use crate::unified_exec::clamp_yield_time; use crate::unified_exec::generate_chunk_id; @@ -140,18 +138,18 @@ impl UnifiedExecProcessManager { store.remove(process_id) }; if let Some(entry) = removed { - Self::unregister_network_attempt_for_entry(&entry).await; + Self::unregister_network_approval_for_entry(&entry).await; } } - async fn unregister_network_attempt_for_entry(entry: &ProcessEntry) { - if let Some(attempt_id) = entry.network_attempt_id.as_deref() + async fn unregister_network_approval_for_entry(entry: &ProcessEntry) { + if let Some(network_approval_id) = entry.network_approval_id.as_deref() && let Some(session) = entry.session.upgrade() { session .services .network_approval - .unregister_attempt(attempt_id) + .unregister_call(network_approval_id) .await; } } @@ -248,17 +246,6 @@ impl UnifiedExecProcessManager { .await; self.release_process_id(&request.process_id).await; - if let Some(deferred) = deferred_network_approval.as_ref() - && let Some(message) = - deferred_rejection_message(context.session.as_ref(), deferred).await - { - finish_deferred_network_approval( - context.session.as_ref(), - deferred_network_approval.take(), - ) - .await; - return Err(UnifiedExecError::create_process(message)); - } finish_deferred_network_approval( context.session.as_ref(), deferred_network_approval.take(), @@ -266,27 +253,13 @@ impl UnifiedExecProcessManager { .await; process.check_for_sandbox_denial_with_text(&text).await?; } else { - if let Some(deferred) = deferred_network_approval.as_ref() - && let Some(message) = - deferred_rejection_message(context.session.as_ref(), deferred).await - { - process.terminate(); - finish_deferred_network_approval( - context.session.as_ref(), - deferred_network_approval.take(), - ) - .await; - self.release_process_id(&request.process_id).await; - return Err(UnifiedExecError::create_process(message)); - } - // Long‑lived command: persist the process so write_stdin can reuse // it, and register a background watcher that will emit // ExecCommandEnd when the PTY eventually exits (even if no further // tool calls are made). - let network_attempt_id = deferred_network_approval + let network_approval_id = deferred_network_approval .as_ref() - .map(|deferred| deferred.attempt_id().to_string()); + .map(|deferred| deferred.registration_id().to_string()); self.store_process( Arc::clone(&process), context, @@ -295,7 +268,7 @@ impl UnifiedExecProcessManager { start, process_id, request.tty, - network_attempt_id, + network_approval_id, Arc::clone(&transcript), ) .await; @@ -443,7 +416,7 @@ impl UnifiedExecProcessManager { } }; if let ProcessStatus::Exited { entry, .. } = &status { - Self::unregister_network_attempt_for_entry(entry).await; + Self::unregister_network_approval_for_entry(entry).await; } status } @@ -502,17 +475,16 @@ impl UnifiedExecProcessManager { started_at: Instant, process_id: String, tty: bool, - network_attempt_id: Option, + network_approval_id: Option, transcript: Arc>, ) { - let network_attempt_id_for_watcher = network_attempt_id.clone(); let entry = ProcessEntry { process: Arc::clone(&process), call_id: context.call_id.clone(), process_id: process_id.clone(), command: command.to_vec(), tty, - network_attempt_id, + network_approval_id, session: Arc::downgrade(&context.session), last_used: started_at, }; @@ -525,7 +497,7 @@ impl UnifiedExecProcessManager { // prune_processes_if_needed runs while holding process_store; do async // network-approval cleanup only after dropping that lock. if let Some(pruned_entry) = pruned_entry { - Self::unregister_network_attempt_for_entry(&pruned_entry).await; + Self::unregister_network_approval_for_entry(&pruned_entry).await; pruned_entry.process.terminate(); } @@ -550,17 +522,6 @@ impl UnifiedExecProcessManager { transcript, started_at, ); - - if context.turn.config.managed_network_requirements_enabled() - && let Some(network_attempt_id) = network_attempt_id_for_watcher - { - spawn_network_denial_watcher( - Arc::clone(&process), - Arc::clone(&context.session), - process_id, - network_attempt_id, - ); - } } pub(crate) async fn open_session_with_exec_env( @@ -637,7 +598,6 @@ impl UnifiedExecProcessManager { turn: context.turn.as_ref(), call_id: context.call_id.clone(), tool_name: "exec_command".to_string(), - network_attempt_id: None, }; orchestrator .run( @@ -792,7 +752,7 @@ impl UnifiedExecProcessManager { }; for entry in entries { - Self::unregister_network_attempt_for_entry(&entry).await; + Self::unregister_network_approval_for_entry(&entry).await; entry.process.terminate(); } } diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index c857affd2b..c3cb15875b 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -37,7 +37,6 @@ async fn run_test_cmd(tmp: TempDir, cmd: Vec<&str>) -> Result(input: &T) -> Option { .map(|info| info.peer_addr().to_string()) } -fn request_network_attempt_id(req: &Request) -> Option { - // Some HTTP stacks normalize proxy credentials into `authorization`; accept both. - attempt_id_from_proxy_authorization(req.headers().get("proxy-authorization")) - .or_else(|| attempt_id_from_proxy_authorization(req.headers().get("authorization"))) -} - fn remove_hop_by_hop_request_headers(headers: &mut HeaderMap) { while let Some(raw_connection) = headers.get(header::CONNECTION).cloned() { headers.remove(header::CONNECTION); @@ -738,7 +721,6 @@ async fn proxy_disabled_response( method, mode: None, protocol: protocol.as_policy_protocol().to_string(), - attempt_id: None, decision: Some("deny".to_string()), source: Some("proxy_state".to_string()), port: Some(port), @@ -796,8 +778,6 @@ mod tests { use crate::config::NetworkMode; use crate::config::NetworkProxySettings; use crate::runtime::network_proxy_state_for_policy; - use base64::Engine; - use base64::engine::general_purpose::STANDARD; use pretty_assertions::assert_eq; use rama_http::Method; use rama_http::Request; @@ -873,36 +853,6 @@ mod tests { ); } - #[test] - fn request_network_attempt_id_reads_proxy_authorization_header() { - let encoded = STANDARD.encode("codex-net-attempt-attempt-1:"); - let req = Request::builder() - .method(Method::GET) - .uri("http://example.com") - .header("proxy-authorization", format!("Basic {encoded}")) - .body(Body::empty()) - .unwrap(); - assert_eq!( - request_network_attempt_id(&req), - Some("attempt-1".to_string()) - ); - } - - #[test] - fn request_network_attempt_id_reads_authorization_header_fallback() { - let encoded = STANDARD.encode("codex-net-attempt-attempt-2:"); - let req = Request::builder() - .method(Method::GET) - .uri("http://example.com") - .header("authorization", format!("Basic {encoded}")) - .body(Body::empty()) - .unwrap(); - assert_eq!( - request_network_attempt_id(&req), - Some("attempt-2".to_string()) - ); - } - #[test] fn remove_hop_by_hop_request_headers_keeps_forwarding_headers() { let mut headers = HeaderMap::new(); diff --git a/codex-rs/network-proxy/src/lib.rs b/codex-rs/network-proxy/src/lib.rs index 536dd4bf6f..f0cb3ae471 100644 --- a/codex-rs/network-proxy/src/lib.rs +++ b/codex-rs/network-proxy/src/lib.rs @@ -3,7 +3,6 @@ mod admin; mod config; mod http_proxy; -mod metadata; mod network_policy; mod policy; mod proxy; diff --git a/codex-rs/network-proxy/src/metadata.rs b/codex-rs/network-proxy/src/metadata.rs deleted file mode 100644 index 2542125c35..0000000000 --- a/codex-rs/network-proxy/src/metadata.rs +++ /dev/null @@ -1,50 +0,0 @@ -use base64::Engine; -use base64::engine::general_purpose::STANDARD; -use rama_http::HeaderValue; - -pub const NETWORK_ATTEMPT_USERNAME_PREFIX: &str = "codex-net-attempt-"; - -pub fn proxy_username_for_attempt_id(attempt_id: &str) -> String { - format!("{NETWORK_ATTEMPT_USERNAME_PREFIX}{attempt_id}") -} - -pub fn attempt_id_from_proxy_authorization(header: Option<&HeaderValue>) -> Option { - let header = header?; - let raw = header.to_str().ok()?; - let encoded = raw.strip_prefix("Basic ")?; - let decoded = STANDARD.decode(encoded.trim()).ok()?; - let decoded = String::from_utf8(decoded).ok()?; - let username = decoded - .split_once(':') - .map(|(user, _)| user) - .unwrap_or(decoded.as_str()); - let attempt_id = username.strip_prefix(NETWORK_ATTEMPT_USERNAME_PREFIX)?; - if attempt_id.is_empty() { - None - } else { - Some(attempt_id.to_string()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use base64::engine::general_purpose::STANDARD; - - #[test] - fn parses_attempt_id_from_proxy_authorization_header() { - let encoded = STANDARD.encode(format!("{NETWORK_ATTEMPT_USERNAME_PREFIX}abc123:")); - let header = HeaderValue::from_str(&format!("Basic {encoded}")).unwrap(); - assert_eq!( - attempt_id_from_proxy_authorization(Some(&header)), - Some("abc123".to_string()) - ); - } - - #[test] - fn ignores_non_attempt_proxy_authorization_header() { - let encoded = STANDARD.encode("normal-user:password"); - let header = HeaderValue::from_str(&format!("Basic {encoded}")).unwrap(); - assert_eq!(attempt_id_from_proxy_authorization(Some(&header)), None); - } -} diff --git a/codex-rs/network-proxy/src/network_policy.rs b/codex-rs/network-proxy/src/network_policy.rs index fdbbe92819..6d8ec48d91 100644 --- a/codex-rs/network-proxy/src/network_policy.rs +++ b/codex-rs/network-proxy/src/network_policy.rs @@ -71,7 +71,6 @@ pub struct NetworkPolicyRequest { pub method: Option, pub command: Option, pub exec_policy_hint: Option, - pub attempt_id: Option, } pub struct NetworkPolicyRequestArgs { @@ -82,7 +81,6 @@ pub struct NetworkPolicyRequestArgs { pub method: Option, pub command: Option, pub exec_policy_hint: Option, - pub attempt_id: Option, } impl NetworkPolicyRequest { @@ -95,7 +93,6 @@ impl NetworkPolicyRequest { method, command, exec_policy_hint, - attempt_id, } = args; Self { protocol, @@ -105,7 +102,6 @@ impl NetworkPolicyRequest { method, command, exec_policy_hint, - attempt_id, } } } @@ -258,7 +254,6 @@ mod tests { method: Some("GET".to_string()), command: None, exec_policy_hint: None, - attempt_id: None, }); let decision = evaluate_host_policy(&state, Some(&decider), &request) @@ -292,7 +287,6 @@ mod tests { method: Some("GET".to_string()), command: None, exec_policy_hint: None, - attempt_id: None, }); let decision = evaluate_host_policy(&state, Some(&decider), &request) @@ -333,7 +327,6 @@ mod tests { method: Some("GET".to_string()), command: None, exec_policy_hint: None, - attempt_id: None, }); let decision = evaluate_host_policy(&state, Some(&decider), &request) diff --git a/codex-rs/network-proxy/src/proxy.rs b/codex-rs/network-proxy/src/proxy.rs index 2e93fb7a1b..ba385dbba4 100644 --- a/codex-rs/network-proxy/src/proxy.rs +++ b/codex-rs/network-proxy/src/proxy.rs @@ -1,7 +1,6 @@ use crate::admin; use crate::config; use crate::http_proxy; -use crate::metadata::proxy_username_for_attempt_id; use crate::network_policy::NetworkPolicyDecider; use crate::runtime::BlockedRequestObserver; use crate::runtime::unix_socket_permissions_supported; @@ -338,12 +337,8 @@ fn apply_proxy_env_overrides( socks_addr: SocketAddr, socks_enabled: bool, allow_local_binding: bool, - network_attempt_id: Option<&str>, ) { - let http_proxy_url = network_attempt_id - .map(proxy_username_for_attempt_id) - .map(|username| format!("http://{username}@{http_addr}")) - .unwrap_or_else(|| format!("http://{http_addr}")); + let http_proxy_url = format!("http://{http_addr}"); let socks_proxy_url = format!("socks5h://{socks_addr}"); env.insert( ALLOW_LOCAL_BINDING_ENV_KEY.to_string(), @@ -390,9 +385,7 @@ fn apply_proxy_env_overrides( // Keep HTTP_PROXY/HTTPS_PROXY as HTTP endpoints. A lot of clients break if // those vars contain SOCKS URLs. We only switch ALL_PROXY here. // - // For attempt-scoped runs, point ALL_PROXY at the HTTP proxy URL so the - // attempt metadata survives in proxy credentials for correlation. - if socks_enabled && network_attempt_id.is_none() { + if socks_enabled { set_env_keys(env, ALL_PROXY_ENV_KEYS, &socks_proxy_url); set_env_keys(env, FTP_PROXY_ENV_KEYS, &socks_proxy_url); } else { @@ -427,14 +420,6 @@ impl NetworkProxy { } pub fn apply_to_env(&self, env: &mut HashMap) { - self.apply_to_env_for_attempt(env, None); - } - - pub fn apply_to_env_for_attempt( - &self, - env: &mut HashMap, - network_attempt_id: Option<&str>, - ) { // Enforce proxying for child processes. We intentionally override existing values so // command-level environment cannot bypass the managed proxy endpoint. apply_proxy_env_overrides( @@ -443,7 +428,6 @@ impl NetworkProxy { self.socks_addr, self.socks_enabled, self.allow_local_binding, - network_attempt_id, ); } @@ -751,7 +735,6 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081), true, false, - None, ); assert_eq!( @@ -802,7 +785,6 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081), false, true, - None, ); assert_eq!( @@ -813,7 +795,7 @@ mod tests { } #[test] - fn apply_proxy_env_overrides_embeds_attempt_id_in_http_proxy_url() { + fn apply_proxy_env_overrides_uses_plain_http_proxy_url() { let mut env = HashMap::new(); apply_proxy_env_overrides( &mut env, @@ -821,28 +803,27 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081), true, false, - Some("attempt-123"), ); assert_eq!( env.get("HTTP_PROXY"), - Some(&"http://codex-net-attempt-attempt-123@127.0.0.1:3128".to_string()) + Some(&"http://127.0.0.1:3128".to_string()) ); assert_eq!( env.get("HTTPS_PROXY"), - Some(&"http://codex-net-attempt-attempt-123@127.0.0.1:3128".to_string()) + Some(&"http://127.0.0.1:3128".to_string()) ); assert_eq!( env.get("WS_PROXY"), - Some(&"http://codex-net-attempt-attempt-123@127.0.0.1:3128".to_string()) + Some(&"http://127.0.0.1:3128".to_string()) ); assert_eq!( env.get("WSS_PROXY"), - Some(&"http://codex-net-attempt-attempt-123@127.0.0.1:3128".to_string()) + Some(&"http://127.0.0.1:3128".to_string()) ); assert_eq!( env.get("ALL_PROXY"), - Some(&"http://codex-net-attempt-attempt-123@127.0.0.1:3128".to_string()) + Some(&"socks5h://127.0.0.1:8081".to_string()) ); #[cfg(target_os = "macos")] assert_eq!( @@ -867,7 +848,6 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081), true, false, - None, ); assert_eq!( diff --git a/codex-rs/network-proxy/src/runtime.rs b/codex-rs/network-proxy/src/runtime.rs index 7917747a8f..238582a6a8 100644 --- a/codex-rs/network-proxy/src/runtime.rs +++ b/codex-rs/network-proxy/src/runtime.rs @@ -75,8 +75,6 @@ pub struct BlockedRequest { pub mode: Option, pub protocol: String, #[serde(skip_serializing_if = "Option::is_none")] - pub attempt_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub decision: Option, #[serde(skip_serializing_if = "Option::is_none")] pub source: Option, @@ -92,7 +90,6 @@ pub struct BlockedRequestArgs { pub method: Option, pub mode: Option, pub protocol: String, - pub attempt_id: Option, pub decision: Option, pub source: Option, pub port: Option, @@ -107,7 +104,6 @@ impl BlockedRequest { method, mode, protocol, - attempt_id, decision, source, port, @@ -119,7 +115,6 @@ impl BlockedRequest { method, mode, protocol, - attempt_id, decision, source, port, @@ -365,7 +360,6 @@ impl NetworkProxyState { let source = entry.source.clone(); let protocol = entry.protocol.clone(); let port = entry.port; - let attempt_id = entry.attempt_id.clone(); guard.blocked.push_back(entry); guard.blocked_total = guard.blocked_total.saturating_add(1); let total = guard.blocked_total; @@ -373,7 +367,7 @@ impl NetworkProxyState { guard.blocked.pop_front(); } debug!( - "recorded blocked request telemetry (total={}, host={}, reason={}, decision={:?}, source={:?}, protocol={}, port={:?}, attempt_id={:?}, buffered={})", + "recorded blocked request telemetry (total={}, host={}, reason={}, decision={:?}, source={:?}, protocol={}, port={:?}, buffered={})", total, host, reason, @@ -381,7 +375,6 @@ impl NetworkProxyState { source, protocol, port, - attempt_id, guard.blocked.len() ); debug!("{violation_line}"); @@ -700,7 +693,6 @@ mod tests { method: Some("GET".to_string()), mode: None, protocol: "http".to_string(), - attempt_id: None, decision: Some("ask".to_string()), source: Some("decider".to_string()), port: Some(80), @@ -741,7 +733,6 @@ mod tests { method: Some("GET".to_string()), mode: None, protocol: "http".to_string(), - attempt_id: None, decision: Some("ask".to_string()), source: Some("decider".to_string()), port: Some(80), @@ -764,7 +755,6 @@ mod tests { method: Some("GET".to_string()), mode: Some(NetworkMode::Full), protocol: "http".to_string(), - attempt_id: Some("attempt-1".to_string()), decision: Some("ask".to_string()), source: Some("decider".to_string()), port: Some(80), @@ -773,7 +763,7 @@ mod tests { assert_eq!( blocked_request_violation_log_line(&entry), - r#"CODEX_NETWORK_POLICY_VIOLATION {"host":"google.com","reason":"not_allowed","client":"127.0.0.1","method":"GET","mode":"full","protocol":"http","attempt_id":"attempt-1","decision":"ask","source":"decider","port":80,"timestamp":1735689600}"# + r#"CODEX_NETWORK_POLICY_VIOLATION {"host":"google.com","reason":"not_allowed","client":"127.0.0.1","method":"GET","mode":"full","protocol":"http","decision":"ask","source":"decider","port":80,"timestamp":1735689600}"# ); } diff --git a/codex-rs/network-proxy/src/socks5.rs b/codex-rs/network-proxy/src/socks5.rs index 176055a5d2..409bd82e37 100644 --- a/codex-rs/network-proxy/src/socks5.rs +++ b/codex-rs/network-proxy/src/socks5.rs @@ -168,7 +168,6 @@ async fn handle_socks5_tcp( method: None, mode: None, protocol: "socks5".to_string(), - attempt_id: None, decision: Some(details.decision.as_str().to_string()), source: Some(details.source.as_str().to_string()), port: Some(port), @@ -202,7 +201,6 @@ async fn handle_socks5_tcp( method: None, mode: Some(NetworkMode::Limited), protocol: "socks5".to_string(), - attempt_id: None, decision: Some(details.decision.as_str().to_string()), source: Some(details.source.as_str().to_string()), port: Some(port), @@ -229,7 +227,6 @@ async fn handle_socks5_tcp( method: None, command: None, exec_policy_hint: None, - attempt_id: None, }); match evaluate_host_policy(&app_state, policy_decider.as_ref(), &request).await { @@ -254,7 +251,6 @@ async fn handle_socks5_tcp( method: None, mode: None, protocol: "socks5".to_string(), - attempt_id: None, decision: Some(details.decision.as_str().to_string()), source: Some(details.source.as_str().to_string()), port: Some(port), @@ -318,7 +314,6 @@ async fn inspect_socks5_udp( method: None, mode: None, protocol: "socks5-udp".to_string(), - attempt_id: None, decision: Some(details.decision.as_str().to_string()), source: Some(details.source.as_str().to_string()), port: Some(port), @@ -352,7 +347,6 @@ async fn inspect_socks5_udp( method: None, mode: Some(NetworkMode::Limited), protocol: "socks5-udp".to_string(), - attempt_id: None, decision: Some(details.decision.as_str().to_string()), source: Some(details.source.as_str().to_string()), port: Some(port), @@ -375,7 +369,6 @@ async fn inspect_socks5_udp( method: None, command: None, exec_policy_hint: None, - attempt_id: None, }); match evaluate_host_policy(&state, policy_decider.as_ref(), &request).await { @@ -400,7 +393,6 @@ async fn inspect_socks5_udp( method: None, mode: None, protocol: "socks5-udp".to_string(), - attempt_id: None, decision: Some(details.decision.as_str().to_string()), source: Some(details.source.as_str().to_string()), port: Some(port), diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 567f18f332..169c8bdcc6 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -122,7 +122,7 @@ impl ApprovalOverlay { || "Would you like to run the following command?".to_string(), |network_approval_context| { format!( - "Do you want to approve access to \"{}\"?", + "Do you want to approve network access to \"{}\"?", network_approval_context.host ) }, @@ -364,12 +364,14 @@ impl From for ApprovalRequestState { header.push(Line::from(vec!["Reason: ".into(), reason.italic()])); header.push(Line::from("")); } - let full_cmd = strip_bash_lc_and_escape(&command); - let mut full_cmd_lines = highlight_bash_to_lines(&full_cmd); - if let Some(first) = full_cmd_lines.first_mut() { - first.spans.insert(0, Span::from("$ ")); + if network_approval_context.is_none() { + let full_cmd = strip_bash_lc_and_escape(&command); + let mut full_cmd_lines = highlight_bash_to_lines(&full_cmd); + if let Some(first) = full_cmd_lines.first_mut() { + first.spans.insert(0, Span::from("$ ")); + } + header.extend(full_cmd_lines); } - header.extend(full_cmd_lines); Self { variant: ApprovalVariant::Exec { id, @@ -738,11 +740,15 @@ mod tests { .collect(); assert!( - rendered - .iter() - .any(|line| line.contains("Do you want to approve access to \"example.com\"?")), + rendered.iter().any(|line| { + line.contains("Do you want to approve network access to \"example.com\"?") + }), "expected network title to include host, got {rendered:?}" ); + assert!( + !rendered.iter().any(|line| line.contains("$ curl")), + "network prompt should not show command line, got {rendered:?}" + ); assert!( !rendered.iter().any(|line| line.contains("don't ask again")), "network prompt should not show execpolicy option, got {rendered:?}" From 73fd93929699375e5231e4854083195588deae52 Mon Sep 17 00:00:00 2001 From: Curtis 'Fjord' Hawthorne Date: Fri, 20 Feb 2026 10:47:07 -0800 Subject: [PATCH 018/385] js_repl: block wrapped payload prefixes in grammar (#12300) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Tighten the `js_repl` freeform Lark grammar to block the most common malformed payload wrappers before they reach runtime validation. ## What Changed - Replaced the overly permissive `js_repl` freeform grammar (`start: /[\s\S]*/`) with a structured grammar that still supports: - plain JS source - optional first-line `// codex-js-repl:` pragma followed by JS source - Added grammar-level filtering for common bad payload shapes by rejecting inputs whose first significant token starts with: - `{` (JSON object wrapper like `{"code":"..."}`) - `"` (quoted code string) - `` ``` `` (markdown code fences) - Implemented the grammar without regex lookahead/lookbehind because the API-side Lark regex engine does not support look-around. - Added a unit test to validate the grammar shape and guard against reintroducing unsupported lookaround. ## Why `js_repl` is a freeform tool, but the model sometimes emits wrapped payloads (JSON, quoted strings, markdown fences) instead of raw JavaScript. We already reject those at runtime, but this change moves the constraint into the tool grammar so the model is less likely to generate invalid tool-call payloads in the first place. ## Testing - `cargo test -p codex-core js_repl_freeform_grammar_blocks_common_non_js_prefixes` - `cargo test -p codex-core parse_freeform_args_rejects_` ## Notes - This intentionally over-blocks a few uncommon valid JS starts (for example top-level `{ ... }` blocks or top-level quoted directives like `"use strict";`) in exchange for preventing the common wrapped-payload mistakes. #### [git stack](https://github.com/magus/git-stack-cli) - 👉 `1` https://github.com/openai/codex/pull/12300 - ⏳ `2` https://github.com/openai/codex/pull/12275 - ⏳ `3` https://github.com/openai/codex/pull/12205 - ⏳ `4` https://github.com/openai/codex/pull/12185 - ⏳ `5` https://github.com/openai/codex/pull/10673 --- codex-rs/core/src/tools/spec.rs | 34 ++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index b17a3a2850..fe9c7ee8a5 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -1068,7 +1068,24 @@ fn create_list_dir_tool() -> ToolSpec { } fn create_js_repl_tool() -> ToolSpec { - const JS_REPL_FREEFORM_GRAMMAR: &str = r#"start: /[\s\S]*/"#; + // Keep JS input freeform, but block the most common malformed payload shapes + // (JSON wrappers, quoted strings, and markdown fences) before they reach the + // runtime `reject_json_or_quoted_source` validation. The API's regex engine + // does not support look-around, so this uses a "first significant token" + // pattern rather than negative lookaheads. + const JS_REPL_FREEFORM_GRAMMAR: &str = r#" +start: pragma_source | plain_source + +pragma_source: PRAGMA_LINE NEWLINE js_source +plain_source: PLAIN_JS_SOURCE + +js_source: JS_SOURCE + +PRAGMA_LINE: /[ \t]*\/\/ codex-js-repl:[^\r\n]*/ +NEWLINE: /\r?\n/ +PLAIN_JS_SOURCE: /(?:\s*)(?:[^\s{\"`]|`[^`]|``[^`])[\s\S]*/ +JS_SOURCE: /(?:\s*)(?:[^\s{\"`]|`[^`]|``[^`])[\s\S]*/ +"#; ToolSpec::Freeform(FreeformTool { name: "js_repl".to_string(), @@ -1922,6 +1939,21 @@ mod tests { assert_contains_tool_names(&tools, &["js_repl", "js_repl_reset"]); } + #[test] + fn js_repl_freeform_grammar_blocks_common_non_js_prefixes() { + let ToolSpec::Freeform(FreeformTool { format, .. }) = create_js_repl_tool() else { + panic!("js_repl should use a freeform tool spec"); + }; + + assert_eq!(format.syntax, "lark"); + assert!(format.definition.contains("PRAGMA_LINE")); + assert!(format.definition.contains("`[^`]")); + assert!(format.definition.contains("``[^`]")); + assert!(format.definition.contains("PLAIN_JS_SOURCE")); + assert!(format.definition.contains("codex-js-repl:")); + assert!(!format.definition.contains("(?!")); + } + fn assert_model_tools( model_slug: &str, features: &Features, From 28c0089060b06bf73118ba906f198a1ca8630ad6 Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Fri, 20 Feb 2026 10:56:57 -0800 Subject: [PATCH 019/385] fix(network-proxy): add unix socket allow-all and update seatbelt rules (#11368) ## Summary Adds support for a Unix socket escape hatch so we can bypass socket allowlisting when explicitly enabled. ## Description * added a new flag, `network.dangerously_allow_all_unix_sockets` as an explicit escape hatch * In codex-network-proxy, enabling that flag now allows any absolute Unix socket path from x-unix-socket instead of requiring each path to be explicitly allowlisted. Relative paths are still rejected. * updated the macOS seatbelt path in core so it enforces the same Unix socket behavior: * allowlisted sockets generate explicit network* subpath rules * allow-all generates a broad network* (subpath "/") rule --------- Co-authored-by: Codex <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com> --- .../codex_app_server_protocol.schemas.json | 6 + .../v2/ConfigRequirementsReadResponse.json | 6 + .../typescript/v2/NetworkRequirements.ts | 2 +- .../app-server-protocol/src/protocol/v2.rs | 1 + codex-rs/app-server/src/config_api.rs | 3 + codex-rs/config/src/config_requirements.rs | 9 + codex-rs/core/config.schema.json | 3 + codex-rs/core/src/config/mod.rs | 1 + .../core/src/config/network_proxy_spec.rs | 7 + codex-rs/core/src/config/permissions.rs | 4 + codex-rs/core/src/network_proxy_loader.rs | 23 ++ codex-rs/core/src/seatbelt.rs | 233 +++++++++++++++++- codex-rs/network-proxy/README.md | 10 +- codex-rs/network-proxy/src/config.rs | 107 +++++++- codex-rs/network-proxy/src/http_proxy.rs | 4 +- codex-rs/network-proxy/src/proxy.rs | 22 +- codex-rs/network-proxy/src/runtime.rs | 103 +++++++- codex-rs/network-proxy/src/state.rs | 21 ++ codex-rs/tui/src/debug_config.rs | 6 + 19 files changed, 553 insertions(+), 18 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index e1e0137b7f..5a840f0bde 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -13466,6 +13466,12 @@ "null" ] }, + "dangerouslyAllowAllUnixSockets": { + "type": [ + "boolean", + "null" + ] + }, "dangerouslyAllowNonLoopbackAdmin": { "type": [ "boolean", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 4d8a967375..651e035e9c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -117,6 +117,12 @@ "null" ] }, + "dangerouslyAllowAllUnixSockets": { + "type": [ + "boolean", + "null" + ] + }, "dangerouslyAllowNonLoopbackAdmin": { "type": [ "boolean", diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/NetworkRequirements.ts b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkRequirements.ts index b7ac9d2f7a..6205de1f4b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/NetworkRequirements.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkRequirements.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type NetworkRequirements = { enabled: boolean | null, httpPort: number | null, socksPort: number | null, allowUpstreamProxy: boolean | null, dangerouslyAllowNonLoopbackProxy: boolean | null, dangerouslyAllowNonLoopbackAdmin: boolean | null, allowedDomains: Array | null, deniedDomains: Array | null, allowUnixSockets: Array | null, allowLocalBinding: boolean | null, }; +export type NetworkRequirements = { enabled: boolean | null, httpPort: number | null, socksPort: number | null, allowUpstreamProxy: boolean | null, dangerouslyAllowNonLoopbackProxy: boolean | null, dangerouslyAllowNonLoopbackAdmin: boolean | null, dangerouslyAllowAllUnixSockets: boolean | null, allowedDomains: Array | null, deniedDomains: Array | null, allowUnixSockets: Array | null, allowLocalBinding: boolean | null, }; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index dfb185b40a..2641d7c2a3 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -577,6 +577,7 @@ pub struct NetworkRequirements { pub allow_upstream_proxy: Option, pub dangerously_allow_non_loopback_proxy: Option, pub dangerously_allow_non_loopback_admin: Option, + pub dangerously_allow_all_unix_sockets: Option, pub allowed_domains: Option>, pub denied_domains: Option>, pub allow_unix_sockets: Option>, diff --git a/codex-rs/app-server/src/config_api.rs b/codex-rs/app-server/src/config_api.rs index e1531dce2f..c9317ac9f5 100644 --- a/codex-rs/app-server/src/config_api.rs +++ b/codex-rs/app-server/src/config_api.rs @@ -161,6 +161,7 @@ fn map_network_requirements_to_api( allow_upstream_proxy: network.allow_upstream_proxy, dangerously_allow_non_loopback_proxy: network.dangerously_allow_non_loopback_proxy, dangerously_allow_non_loopback_admin: network.dangerously_allow_non_loopback_admin, + dangerously_allow_all_unix_sockets: network.dangerously_allow_all_unix_sockets, allowed_domains: network.allowed_domains, denied_domains: network.denied_domains, allow_unix_sockets: network.allow_unix_sockets, @@ -221,6 +222,7 @@ mod tests { allow_upstream_proxy: Some(false), dangerously_allow_non_loopback_proxy: Some(false), dangerously_allow_non_loopback_admin: Some(false), + dangerously_allow_all_unix_sockets: Some(true), allowed_domains: Some(vec!["api.openai.com".to_string()]), denied_domains: Some(vec!["example.com".to_string()]), allow_unix_sockets: Some(vec!["/tmp/proxy.sock".to_string()]), @@ -258,6 +260,7 @@ mod tests { allow_upstream_proxy: Some(false), dangerously_allow_non_loopback_proxy: Some(false), dangerously_allow_non_loopback_admin: Some(false), + dangerously_allow_all_unix_sockets: Some(true), allowed_domains: Some(vec!["api.openai.com".to_string()]), denied_domains: Some(vec!["example.com".to_string()]), allow_unix_sockets: Some(vec!["/tmp/proxy.sock".to_string()]), diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index c6b63258f2..db81b45e35 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -135,6 +135,7 @@ pub struct NetworkRequirementsToml { pub allow_upstream_proxy: Option, pub dangerously_allow_non_loopback_proxy: Option, pub dangerously_allow_non_loopback_admin: Option, + pub dangerously_allow_all_unix_sockets: Option, pub allowed_domains: Option>, pub denied_domains: Option>, pub allow_unix_sockets: Option>, @@ -150,6 +151,7 @@ pub struct NetworkConstraints { pub allow_upstream_proxy: Option, pub dangerously_allow_non_loopback_proxy: Option, pub dangerously_allow_non_loopback_admin: Option, + pub dangerously_allow_all_unix_sockets: Option, pub allowed_domains: Option>, pub denied_domains: Option>, pub allow_unix_sockets: Option>, @@ -165,6 +167,7 @@ impl From for NetworkConstraints { allow_upstream_proxy, dangerously_allow_non_loopback_proxy, dangerously_allow_non_loopback_admin, + dangerously_allow_all_unix_sockets, allowed_domains, denied_domains, allow_unix_sockets, @@ -177,6 +180,7 @@ impl From for NetworkConstraints { allow_upstream_proxy, dangerously_allow_non_loopback_proxy, dangerously_allow_non_loopback_admin, + dangerously_allow_all_unix_sockets, allowed_domains, denied_domains, allow_unix_sockets, @@ -1040,6 +1044,7 @@ mod tests { [experimental_network] enabled = true allow_upstream_proxy = false + dangerously_allow_all_unix_sockets = true allowed_domains = ["api.example.com", "*.openai.com"] denied_domains = ["blocked.example.com"] allow_unix_sockets = ["/tmp/example.sock"] @@ -1058,6 +1063,10 @@ mod tests { assert_eq!(sourced_network.source, source); assert_eq!(sourced_network.value.enabled, Some(true)); assert_eq!(sourced_network.value.allow_upstream_proxy, Some(false)); + assert_eq!( + sourced_network.value.dangerously_allow_all_unix_sockets, + Some(true) + ); assert_eq!( sourced_network.value.allowed_domains.as_ref(), Some(&vec![ diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 5eab764fc3..732f9590f7 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -656,6 +656,9 @@ }, "type": "array" }, + "dangerously_allow_all_unix_sockets": { + "type": "boolean" + }, "dangerously_allow_non_loopback_admin": { "type": "boolean" }, diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index a27508d1a9..1675067c7a 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -2401,6 +2401,7 @@ allowed_domains = ["openai.com"] allow_upstream_proxy: Some(false), dangerously_allow_non_loopback_proxy: None, dangerously_allow_non_loopback_admin: None, + dangerously_allow_all_unix_sockets: None, mode: None, allowed_domains: Some(vec!["openai.com".to_string()]), denied_domains: None, diff --git a/codex-rs/core/src/config/network_proxy_spec.rs b/codex-rs/core/src/config/network_proxy_spec.rs index 1957455d6f..cd65a4dc41 100644 --- a/codex-rs/core/src/config/network_proxy_spec.rs +++ b/codex-rs/core/src/config/network_proxy_spec.rs @@ -178,6 +178,13 @@ impl NetworkProxySpec { constraints.dangerously_allow_non_loopback_admin = Some(dangerously_allow_non_loopback_admin); } + if let Some(dangerously_allow_all_unix_sockets) = + requirements.dangerously_allow_all_unix_sockets + { + config.network.dangerously_allow_all_unix_sockets = dangerously_allow_all_unix_sockets; + constraints.dangerously_allow_all_unix_sockets = + Some(dangerously_allow_all_unix_sockets); + } if let Some(allowed_domains) = requirements.allowed_domains.clone() { config.network.allowed_domains = allowed_domains.clone(); constraints.allowed_domains = Some(allowed_domains); diff --git a/codex-rs/core/src/config/permissions.rs b/codex-rs/core/src/config/permissions.rs index a03b5273da..dd242bd857 100644 --- a/codex-rs/core/src/config/permissions.rs +++ b/codex-rs/core/src/config/permissions.rs @@ -24,6 +24,7 @@ pub struct NetworkToml { pub allow_upstream_proxy: Option, pub dangerously_allow_non_loopback_proxy: Option, pub dangerously_allow_non_loopback_admin: Option, + pub dangerously_allow_all_unix_sockets: Option, #[schemars(with = "Option")] pub mode: Option, pub allowed_domains: Option>, @@ -74,6 +75,9 @@ impl NetworkToml { config.network.dangerously_allow_non_loopback_admin = dangerously_allow_non_loopback_admin; } + if let Some(dangerously_allow_all_unix_sockets) = self.dangerously_allow_all_unix_sockets { + config.network.dangerously_allow_all_unix_sockets = dangerously_allow_all_unix_sockets; + } if let Some(mode) = self.mode { config.network.mode = mode; } diff --git a/codex-rs/core/src/network_proxy_loader.rs b/codex-rs/core/src/network_proxy_loader.rs index 6fcf91f086..1af36b2acb 100644 --- a/codex-rs/core/src/network_proxy_loader.rs +++ b/codex-rs/core/src/network_proxy_loader.rs @@ -133,6 +133,9 @@ fn apply_network_constraints(network: NetworkToml, constraints: &mut NetworkProx constraints.dangerously_allow_non_loopback_admin = Some(dangerously_allow_non_loopback_admin); } + if let Some(dangerously_allow_all_unix_sockets) = network.dangerously_allow_all_unix_sockets { + constraints.dangerously_allow_all_unix_sockets = Some(dangerously_allow_all_unix_sockets); + } if let Some(allowed_domains) = network.allowed_domains { constraints.allowed_domains = Some(allowed_domains); } @@ -288,4 +291,24 @@ allowed_domains = ["higher.example.com"] assert_eq!(config.network.allowed_domains, vec!["higher.example.com"]); } + + #[test] + fn apply_network_constraints_includes_allow_all_unix_sockets_flag() { + let config: toml::Value = toml::from_str( + r#" +[network] +dangerously_allow_all_unix_sockets = true +"#, + ) + .expect("network table should parse"); + let network = network_tables_from_toml(&config) + .expect("network table should deserialize") + .network + .expect("network table should be present"); + + let mut constraints = NetworkProxyConstraints::default(); + apply_network_constraints(network, &mut constraints); + + assert_eq!(constraints.dangerously_allow_all_unix_sockets, Some(true)); + } } diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index 03cb45d918..e9d8879f85 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -1,16 +1,18 @@ #![cfg(target_os = "macos")] -use codex_network_proxy::ALLOW_LOCAL_BINDING_ENV_KEY; use codex_network_proxy::NetworkProxy; use codex_network_proxy::PROXY_URL_ENV_KEYS; use codex_network_proxy::has_proxy_url_env_vars; use codex_network_proxy::proxy_url_env_value; +use codex_utils_absolute_path::AbsolutePathBuf; +use std::collections::BTreeMap; use std::collections::BTreeSet; use std::collections::HashMap; use std::ffi::CStr; use std::path::Path; use std::path::PathBuf; use tokio::process::Child; +use tracing::warn; use url::Url; use crate::protocol::SandboxPolicy; @@ -110,34 +112,131 @@ fn proxy_loopback_ports_from_env(env: &HashMap) -> Vec { ports.into_iter().collect() } -fn local_binding_enabled(env: &HashMap) -> bool { - env.get(ALLOW_LOCAL_BINDING_ENV_KEY).is_some_and(|value| { - let trimmed = value.trim(); - trimmed == "1" || trimmed.eq_ignore_ascii_case("true") - }) -} - #[derive(Debug, Default)] struct ProxyPolicyInputs { ports: Vec, has_proxy_config: bool, allow_local_binding: bool, + unix_domain_socket_policy: UnixDomainSocketPolicy, +} + +#[derive(Debug, Clone)] +// Keep allow-all and allowlist modes disjoint so we don't carry ignored state. +enum UnixDomainSocketPolicy { + AllowAll, + Restricted { allowed: Vec }, +} + +impl Default for UnixDomainSocketPolicy { + fn default() -> Self { + Self::Restricted { allowed: vec![] } + } +} + +#[derive(Debug, Clone)] +struct UnixSocketPathParam { + key: String, + path: AbsolutePathBuf, } fn proxy_policy_inputs(network: Option<&NetworkProxy>) -> ProxyPolicyInputs { if let Some(network) = network { let mut env = HashMap::new(); network.apply_to_env(&mut env); + let unix_domain_socket_policy = if network.dangerously_allow_all_unix_sockets() { + UnixDomainSocketPolicy::AllowAll + } else { + let allowed = network + .allow_unix_sockets() + .iter() + .filter_map( + |socket_path| match normalize_path_for_sandbox(Path::new(socket_path)) { + Some(path) => Some((path.to_string_lossy().to_string(), path)), + None => { + warn!( + "ignoring network.allow_unix_sockets entry because it could not be normalized: {socket_path}" + ); + None + } + }, + ) + .collect::>() + .into_values() + .collect(); + UnixDomainSocketPolicy::Restricted { allowed } + }; return ProxyPolicyInputs { ports: proxy_loopback_ports_from_env(&env), has_proxy_config: has_proxy_url_env_vars(&env), - allow_local_binding: local_binding_enabled(&env), + allow_local_binding: network.allow_local_binding(), + unix_domain_socket_policy, }; } ProxyPolicyInputs::default() } +fn normalize_path_for_sandbox(path: &Path) -> Option { + // `AbsolutePathBuf::from_absolute_path()` normalizes relative paths against the current + // working directory, so keep the explicit check to avoid silently accepting relative entries. + if !path.is_absolute() { + return None; + } + + let absolute_path = AbsolutePathBuf::from_absolute_path(path).ok()?; + let normalized_path = absolute_path + .as_path() + .canonicalize() + .ok() + .and_then(|canonical_path| AbsolutePathBuf::from_absolute_path(canonical_path).ok()); + normalized_path.or(Some(absolute_path)) +} + +fn unix_socket_path_params(proxy: &ProxyPolicyInputs) -> Vec { + let mut deduped_paths: BTreeMap = BTreeMap::new(); + let UnixDomainSocketPolicy::Restricted { allowed } = &proxy.unix_domain_socket_policy else { + return vec![]; + }; + for path in allowed { + deduped_paths + .entry(path.to_string_lossy().to_string()) + .or_insert_with(|| path.clone()); + } + + deduped_paths + .into_values() + .enumerate() + .map(|(index, path)| UnixSocketPathParam { + key: format!("UNIX_SOCKET_PATH_{index}"), + path, + }) + .collect() +} + +fn unix_socket_dir_params(proxy: &ProxyPolicyInputs) -> Vec<(String, PathBuf)> { + unix_socket_path_params(proxy) + .into_iter() + .map(|param| (param.key, param.path.into_path_buf())) + .collect() +} + +/// Returns zero or more complete Seatbelt policy lines for unix socket rules. +/// When non-empty, the returned string is newline-terminated so callers can +/// append it directly to larger policy blocks. +fn unix_socket_policy(proxy: &ProxyPolicyInputs) -> String { + if matches!( + proxy.unix_domain_socket_policy, + UnixDomainSocketPolicy::AllowAll + ) { + return "(allow network* (subpath \"/\"))\n".to_string(); + } + + unix_socket_path_params(proxy) + .iter() + .map(|param| format!("(allow network* (subpath (param \"{}\")))\n", param.key)) + .collect() +} + fn dynamic_network_policy( sandbox_policy: &SandboxPolicy, enforce_managed_network: bool, @@ -157,6 +256,11 @@ fn dynamic_network_policy( "(allow network-outbound (remote ip \"localhost:{port}\"))\n" )); } + let unix_socket_policy = unix_socket_policy(proxy); + if !unix_socket_policy.is_empty() { + policy.push_str("; allow unix domain sockets for local IPC\n"); + policy.push_str(&unix_socket_policy); + } return format!("{policy}{MACOS_SEATBELT_NETWORK_POLICY}"); } @@ -339,6 +443,7 @@ pub(crate) fn create_seatbelt_command_args_with_extensions( file_write_dir_params, unix_socket_params, macos_dir_params(), + unix_socket_dir_params(&proxy), seatbelt_extensions.dir_params, ] .concat(); @@ -404,15 +509,20 @@ fn macos_dir_params() -> Vec<(String, PathBuf)> { mod tests { use super::MACOS_SEATBELT_BASE_POLICY; use super::ProxyPolicyInputs; + use super::UnixDomainSocketPolicy; use super::create_seatbelt_command_args; use super::create_seatbelt_command_args_with_extensions; use super::dynamic_network_policy; use super::macos_dir_params; + use super::normalize_path_for_sandbox; + use super::unix_socket_dir_params; + use super::unix_socket_policy; use crate::protocol::SandboxPolicy; use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE; use crate::seatbelt_permissions::MacOsAutomationPermission; use crate::seatbelt_permissions::MacOsPreferencesPermission; use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; + use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use std::fs; use std::path::Path; @@ -430,6 +540,10 @@ mod tests { ); } + fn absolute_path(path: &str) -> AbsolutePathBuf { + AbsolutePathBuf::from_absolute_path(Path::new(path)).expect("absolute path") + } + #[test] fn base_policy_allows_node_cpu_sysctls() { assert!( @@ -451,6 +565,7 @@ mod tests { ports: vec![43128, 48081], has_proxy_config: true, allow_local_binding: false, + ..ProxyPolicyInputs::default() }, ); @@ -574,6 +689,7 @@ mod tests { ports: vec![43128], has_proxy_config: true, allow_local_binding: true, + ..ProxyPolicyInputs::default() }, ); @@ -610,6 +726,7 @@ mod tests { ports: vec![], has_proxy_config: true, allow_local_binding: false, + ..ProxyPolicyInputs::default() }, ); @@ -638,12 +755,109 @@ mod tests { ports: vec![], has_proxy_config: false, allow_local_binding: false, + ..ProxyPolicyInputs::default() }, ); assert_eq!(policy, ""); } + #[test] + fn create_seatbelt_args_allowlists_unix_socket_paths() { + let policy = dynamic_network_policy( + &SandboxPolicy::new_read_only_policy(), + false, + &ProxyPolicyInputs { + ports: vec![43128], + has_proxy_config: true, + allow_local_binding: false, + unix_domain_socket_policy: UnixDomainSocketPolicy::Restricted { + allowed: vec![absolute_path("/tmp/example.sock")], + }, + }, + ); + + assert!( + policy.contains("(allow network* (subpath (param \"UNIX_SOCKET_PATH_0\")))"), + "policy should allow explicitly configured unix sockets:\n{policy}" + ); + } + + #[test] + fn unix_socket_policy_non_empty_output_is_newline_terminated() { + let allowlist_policy = unix_socket_policy(&ProxyPolicyInputs { + unix_domain_socket_policy: UnixDomainSocketPolicy::Restricted { + allowed: vec![absolute_path("/tmp/example.sock")], + }, + ..ProxyPolicyInputs::default() + }); + assert!( + allowlist_policy.ends_with('\n'), + "allowlist unix socket policy should end with a newline:\n{allowlist_policy}" + ); + + let allow_all_policy = unix_socket_policy(&ProxyPolicyInputs { + unix_domain_socket_policy: UnixDomainSocketPolicy::AllowAll, + ..ProxyPolicyInputs::default() + }); + assert!( + allow_all_policy.ends_with('\n'), + "allow-all unix socket policy should end with a newline:\n{allow_all_policy}" + ); + } + + #[test] + fn unix_socket_dir_params_use_stable_param_names() { + let params = unix_socket_dir_params(&ProxyPolicyInputs { + unix_domain_socket_policy: UnixDomainSocketPolicy::Restricted { + allowed: vec![ + absolute_path("/tmp/b.sock"), + absolute_path("/tmp/a.sock"), + absolute_path("/tmp/a.sock"), + ], + }, + ..ProxyPolicyInputs::default() + }); + + assert_eq!( + params, + vec![ + ( + "UNIX_SOCKET_PATH_0".to_string(), + PathBuf::from("/tmp/a.sock") + ), + ( + "UNIX_SOCKET_PATH_1".to_string(), + PathBuf::from("/tmp/b.sock") + ), + ] + ); + } + + #[test] + fn normalize_path_for_sandbox_rejects_relative_paths() { + assert_eq!(normalize_path_for_sandbox(Path::new("relative.sock")), None); + } + + #[test] + fn create_seatbelt_args_allows_all_unix_sockets_when_enabled() { + let policy = dynamic_network_policy( + &SandboxPolicy::new_read_only_policy(), + false, + &ProxyPolicyInputs { + ports: vec![43128], + has_proxy_config: true, + allow_local_binding: false, + unix_domain_socket_policy: UnixDomainSocketPolicy::AllowAll, + }, + ); + + assert!( + policy.contains("(allow network* (subpath \"/\"))"), + "policy should allow all unix sockets when flag is enabled:\n{policy}" + ); + } + #[test] fn create_seatbelt_args_full_network_with_proxy_is_still_proxy_only() { let policy = dynamic_network_policy( @@ -659,6 +873,7 @@ mod tests { ports: vec![43128], has_proxy_config: true, allow_local_binding: false, + ..ProxyPolicyInputs::default() }, ); diff --git a/codex-rs/network-proxy/README.md b/codex-rs/network-proxy/README.md index 925d7147bc..198dbbd617 100644 --- a/codex-rs/network-proxy/README.md +++ b/codex-rs/network-proxy/README.md @@ -47,6 +47,9 @@ allow_local_binding = true # macOS-only: allows proxying to a unix socket when request includes `x-unix-socket: /path`. allow_unix_sockets = ["/tmp/example.sock"] +# DANGEROUS (macOS-only): bypasses unix socket allowlisting and permits any +# absolute socket path from `x-unix-socket`. +dangerously_allow_all_unix_sockets = false ``` ### 2) Run the proxy @@ -116,8 +119,9 @@ let handle = proxy.run().await?; handle.shutdown().await?; ``` -When unix socket proxying is enabled, HTTP/admin bind overrides are still clamped to loopback -to avoid turning the proxy into a remote bridge to local daemons. +When unix socket proxying is enabled (`allow_unix_sockets` or +`dangerously_allow_all_unix_sockets`), HTTP/admin bind overrides are still clamped to loopback to +avoid turning the proxy into a remote bridge to local daemons. ### Policy hook (exec-policy mapping) @@ -176,6 +180,8 @@ what it can reasonably guarantee. `dangerously_allow_non_loopback_proxy` - when unix socket proxying is enabled, both listeners are forced to loopback to avoid turning the proxy into a remote bridge into local daemons. +- `dangerously_allow_all_unix_sockets = true` bypasses the unix socket allowlist entirely (still + macOS-only and absolute-path-only). Use only in tightly controlled environments. - `enabled` is enforced at runtime; when false the proxy no-ops and does not bind listeners. Limitations: diff --git a/codex-rs/network-proxy/src/config.rs b/codex-rs/network-proxy/src/config.rs index 31197a1c96..3284822232 100644 --- a/codex-rs/network-proxy/src/config.rs +++ b/codex-rs/network-proxy/src/config.rs @@ -1,10 +1,12 @@ use anyhow::Context; use anyhow::Result; use anyhow::bail; +use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; use serde::Serialize; use std::net::IpAddr; use std::net::SocketAddr; +use std::path::Path; use tracing::warn; use url::Url; @@ -33,6 +35,8 @@ pub struct NetworkProxySettings { #[serde(default)] pub dangerously_allow_non_loopback_admin: bool, #[serde(default)] + pub dangerously_allow_all_unix_sockets: bool, + #[serde(default)] pub mode: NetworkMode, #[serde(default)] pub allowed_domains: Vec, @@ -55,6 +59,7 @@ impl Default for NetworkProxySettings { allow_upstream_proxy: true, dangerously_allow_non_loopback_proxy: false, dangerously_allow_non_loopback_admin: false, + dangerously_allow_all_unix_sockets: false, mode: NetworkMode::default(), allowed_domains: Vec::new(), denied_domains: Vec::new(), @@ -136,7 +141,7 @@ pub(crate) fn clamp_bind_addrs( cfg.dangerously_allow_non_loopback_admin, "admin API", ); - if cfg.allow_unix_sockets.is_empty() { + if cfg.allow_unix_sockets.is_empty() && !cfg.dangerously_allow_all_unix_sockets { return (http_addr, socks_addr, admin_addr); } @@ -172,7 +177,49 @@ pub struct RuntimeConfig { pub admin_addr: SocketAddr, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct UnixStyleAbsolutePath(String); + +impl UnixStyleAbsolutePath { + fn parse(value: &str) -> Option { + value.starts_with('/').then(|| Self(value.to_string())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ValidatedUnixSocketPath { + Native(AbsolutePathBuf), + UnixStyleAbsolute(UnixStyleAbsolutePath), +} + +impl ValidatedUnixSocketPath { + pub(crate) fn parse(socket_path: &str) -> Result { + let path = Path::new(socket_path); + if path.is_absolute() { + let path = AbsolutePathBuf::from_absolute_path(path) + .with_context(|| format!("failed to normalize unix socket path {socket_path:?}"))?; + return Ok(Self::Native(path)); + } + + if let Some(path) = UnixStyleAbsolutePath::parse(socket_path) { + return Ok(Self::UnixStyleAbsolute(path)); + } + + bail!("expected an absolute path, got {socket_path:?}"); + } +} + +pub(crate) fn validate_unix_socket_allowlist_paths(cfg: &NetworkProxyConfig) -> Result<()> { + for (index, socket_path) in cfg.network.allow_unix_sockets.iter().enumerate() { + ValidatedUnixSocketPath::parse(socket_path) + .with_context(|| format!("invalid network.allow_unix_sockets[{index}]"))?; + } + Ok(()) +} + pub fn resolve_runtime(cfg: &NetworkProxyConfig) -> Result { + validate_unix_socket_allowlist_paths(cfg)?; + let http_addr = resolve_addr(&cfg.network.proxy_url, 3128) .with_context(|| format!("invalid network.proxy_url: {}", cfg.network.proxy_url))?; let socks_addr = resolve_addr(&cfg.network.socks_url, 8081) @@ -340,6 +387,7 @@ mod tests { allow_upstream_proxy: true, dangerously_allow_non_loopback_proxy: false, dangerously_allow_non_loopback_admin: false, + dangerously_allow_all_unix_sockets: false, mode: NetworkMode::Full, allowed_domains: Vec::new(), denied_domains: Vec::new(), @@ -526,4 +574,61 @@ mod tests { assert_eq!(socks_addr, "127.0.0.1:8081".parse::().unwrap()); assert_eq!(admin_addr, "127.0.0.1:8080".parse::().unwrap()); } + + #[test] + fn clamp_bind_addrs_forces_loopback_when_all_unix_sockets_enabled() { + let cfg = NetworkProxySettings { + dangerously_allow_non_loopback_proxy: true, + dangerously_allow_non_loopback_admin: true, + dangerously_allow_all_unix_sockets: true, + ..Default::default() + }; + let http_addr = "0.0.0.0:3128".parse::().unwrap(); + let socks_addr = "0.0.0.0:8081".parse::().unwrap(); + let admin_addr = "0.0.0.0:8080".parse::().unwrap(); + + let (http_addr, socks_addr, admin_addr) = + clamp_bind_addrs(http_addr, socks_addr, admin_addr, &cfg); + + assert_eq!(http_addr, "127.0.0.1:3128".parse::().unwrap()); + assert_eq!(socks_addr, "127.0.0.1:8081".parse::().unwrap()); + assert_eq!(admin_addr, "127.0.0.1:8080".parse::().unwrap()); + } + + #[test] + fn resolve_runtime_rejects_relative_allow_unix_sockets_entries() { + let cfg = NetworkProxyConfig { + network: NetworkProxySettings { + allow_unix_sockets: vec!["relative.sock".to_string()], + ..NetworkProxySettings::default() + }, + }; + + let err = match resolve_runtime(&cfg) { + Ok(runtime) => panic!( + "relative allow_unix_sockets should fail, but resolve_runtime succeeded: {:?}", + runtime.http_addr + ), + Err(err) => err, + }; + assert!( + err.to_string().contains("network.allow_unix_sockets[0]"), + "error should point at the invalid allow_unix_sockets entry: {err:#}" + ); + } + + #[test] + fn resolve_runtime_accepts_unix_style_absolute_allow_unix_sockets_entries() { + let cfg = NetworkProxyConfig { + network: NetworkProxySettings { + allow_unix_sockets: vec!["/private/tmp/example.sock".to_string()], + ..NetworkProxySettings::default() + }, + }; + + assert!( + resolve_runtime(&cfg).is_ok(), + "unix-style absolute allow_unix_sockets entry should be accepted" + ); + } } diff --git a/codex-rs/network-proxy/src/http_proxy.rs b/codex-rs/network-proxy/src/http_proxy.rs index d02e02bcff..7ea88ba34c 100644 --- a/codex-rs/network-proxy/src/http_proxy.rs +++ b/codex-rs/network-proxy/src/http_proxy.rs @@ -378,8 +378,8 @@ async fn http_plain_proxy( }; // `x-unix-socket` is an escape hatch for talking to local daemons. We keep it tightly scoped: - // macOS-only + explicit allowlist, to avoid turning the proxy into a general local capability - // escalation mechanism. + // macOS-only + explicit allowlist by default, to avoid turning the proxy into a general local + // capability escalation mechanism. if let Some(unix_socket_header) = req.headers().get("x-unix-socket") { let socket_path = match unix_socket_header.to_str() { Ok(value) => value.to_string(), diff --git a/codex-rs/network-proxy/src/proxy.rs b/codex-rs/network-proxy/src/proxy.rs index ba385dbba4..f30006958f 100644 --- a/codex-rs/network-proxy/src/proxy.rs +++ b/codex-rs/network-proxy/src/proxy.rs @@ -206,6 +206,10 @@ impl NetworkProxyBuilder { socks_addr, socks_enabled: current_cfg.network.enable_socks5, allow_local_binding: current_cfg.network.allow_local_binding, + allow_unix_sockets: current_cfg.network.allow_unix_sockets.clone(), + dangerously_allow_all_unix_sockets: current_cfg + .network + .dangerously_allow_all_unix_sockets, admin_addr, reserved_listeners, policy_decider: self.policy_decider, @@ -240,6 +244,8 @@ pub struct NetworkProxy { socks_addr: SocketAddr, socks_enabled: bool, allow_local_binding: bool, + allow_unix_sockets: Vec, + dangerously_allow_all_unix_sockets: bool, admin_addr: SocketAddr, reserved_listeners: Option>, policy_decider: Option>, @@ -419,6 +425,18 @@ impl NetworkProxy { self.admin_addr } + pub fn allow_local_binding(&self) -> bool { + self.allow_local_binding + } + + pub fn allow_unix_sockets(&self) -> &[String] { + &self.allow_unix_sockets + } + + pub fn dangerously_allow_all_unix_sockets(&self) -> bool { + self.dangerously_allow_all_unix_sockets + } + pub fn apply_to_env(&self, env: &mut HashMap) { // Enforce proxying for child processes. We intentionally override existing values so // command-level environment cannot bypass the managed proxy endpoint. @@ -441,7 +459,9 @@ impl NetworkProxy { ensure_rustls_crypto_provider(); if !unix_socket_permissions_supported() { - warn!("allowUnixSockets is macOS-only; requests will be rejected on this platform"); + warn!( + "allowUnixSockets and dangerouslyAllowAllUnixSockets are macOS-only; requests will be rejected on this platform" + ); } let reserved_listeners = self.reserved_listeners.as_ref(); diff --git a/codex-rs/network-proxy/src/runtime.rs b/codex-rs/network-proxy/src/runtime.rs index 238582a6a8..583ecd7eda 100644 --- a/codex-rs/network-proxy/src/runtime.rs +++ b/codex-rs/network-proxy/src/runtime.rs @@ -1,5 +1,6 @@ use crate::config::NetworkMode; use crate::config::NetworkProxyConfig; +use crate::config::ValidatedUnixSocketPath; use crate::policy::Host; use crate::policy::is_loopback_host; use crate::policy::is_non_public_ip; @@ -418,6 +419,10 @@ impl NetworkProxyState { } let guard = self.state.read().await; + if guard.config.network.dangerously_allow_all_unix_sockets { + return Ok(true); + } + // Normalize the path while keeping the absolute-path requirement explicit. let requested_abs = match AbsolutePathBuf::from_absolute_path(requested_path) { Ok(path) => path, @@ -425,7 +430,16 @@ impl NetworkProxyState { }; let requested_canonical = std::fs::canonicalize(requested_abs.as_path()).ok(); for allowed in &guard.config.network.allow_unix_sockets { - if allowed == path { + let allowed_path = match ValidatedUnixSocketPath::parse(allowed) { + Ok(ValidatedUnixSocketPath::Native(path)) => path, + Ok(ValidatedUnixSocketPath::UnixStyleAbsolute(_)) => continue, + Err(err) => { + warn!("ignoring invalid network.allow_unix_sockets entry at runtime: {err:#}"); + continue; + } + }; + + if allowed_path.as_path() == requested_abs.as_path() { return Ok(true); } @@ -434,7 +448,7 @@ impl NetworkProxyState { let Some(requested_canonical) = &requested_canonical else { continue; }; - if let Ok(allowed_canonical) = std::fs::canonicalize(allowed) + if let Ok(allowed_canonical) = std::fs::canonicalize(allowed_path.as_path()) && &allowed_canonical == requested_canonical { return Ok(true); @@ -1075,6 +1089,77 @@ mod tests { assert!(validate_policy_against_constraints(&config, &constraints).is_ok()); } + #[test] + fn validate_policy_against_constraints_disallows_allow_all_unix_sockets_without_managed_opt_in() + { + let constraints = NetworkProxyConstraints { + dangerously_allow_all_unix_sockets: Some(false), + ..NetworkProxyConstraints::default() + }; + + let config = NetworkProxyConfig { + network: NetworkProxySettings { + enabled: true, + dangerously_allow_all_unix_sockets: true, + ..NetworkProxySettings::default() + }, + }; + + assert!(validate_policy_against_constraints(&config, &constraints).is_err()); + } + + #[test] + fn validate_policy_against_constraints_disallows_allow_all_unix_sockets_when_allowlist_is_managed() + { + let constraints = NetworkProxyConstraints { + allow_unix_sockets: Some(vec!["/tmp/allowed.sock".to_string()]), + ..NetworkProxyConstraints::default() + }; + + let config = NetworkProxyConfig { + network: NetworkProxySettings { + enabled: true, + dangerously_allow_all_unix_sockets: true, + ..NetworkProxySettings::default() + }, + }; + + assert!(validate_policy_against_constraints(&config, &constraints).is_err()); + } + + #[test] + fn validate_policy_against_constraints_allows_allow_all_unix_sockets_with_managed_opt_in() { + let constraints = NetworkProxyConstraints { + dangerously_allow_all_unix_sockets: Some(true), + ..NetworkProxyConstraints::default() + }; + + let config = NetworkProxyConfig { + network: NetworkProxySettings { + enabled: true, + dangerously_allow_all_unix_sockets: true, + ..NetworkProxySettings::default() + }, + }; + + assert!(validate_policy_against_constraints(&config, &constraints).is_ok()); + } + + #[test] + fn validate_policy_against_constraints_allows_allow_all_unix_sockets_when_unmanaged() { + let constraints = NetworkProxyConstraints::default(); + + let config = NetworkProxyConfig { + network: NetworkProxySettings { + enabled: true, + dangerously_allow_all_unix_sockets: true, + ..NetworkProxySettings::default() + }, + }; + + assert!(validate_policy_against_constraints(&config, &constraints).is_ok()); + } + #[test] fn compile_globset_is_case_insensitive() { let patterns = vec!["ExAmPle.CoM".to_string()]; @@ -1172,6 +1257,19 @@ mod tests { assert!(state.is_unix_socket_allowed(&link_s).await.unwrap()); } + #[cfg(target_os = "macos")] + #[tokio::test] + async fn unix_socket_allow_all_flag_bypasses_allowlist() { + let state = network_proxy_state_for_policy(NetworkProxySettings { + allowed_domains: vec!["example.com".to_string()], + dangerously_allow_all_unix_sockets: true, + ..NetworkProxySettings::default() + }); + + assert!(state.is_unix_socket_allowed("/tmp/any.sock").await.unwrap()); + assert!(!state.is_unix_socket_allowed("relative.sock").await.unwrap()); + } + #[cfg(not(target_os = "macos"))] #[tokio::test] async fn unix_socket_allowlist_is_rejected_on_non_macos() { @@ -1179,6 +1277,7 @@ mod tests { let state = network_proxy_state_for_policy(NetworkProxySettings { allowed_domains: vec!["example.com".to_string()], allow_unix_sockets: vec![socket_path.clone()], + dangerously_allow_all_unix_sockets: true, ..NetworkProxySettings::default() }); diff --git a/codex-rs/network-proxy/src/state.rs b/codex-rs/network-proxy/src/state.rs index 97dfcc4b5d..d7dc705ac4 100644 --- a/codex-rs/network-proxy/src/state.rs +++ b/codex-rs/network-proxy/src/state.rs @@ -19,6 +19,7 @@ pub struct NetworkProxyConstraints { pub allow_upstream_proxy: Option, pub dangerously_allow_non_loopback_proxy: Option, pub dangerously_allow_non_loopback_admin: Option, + pub dangerously_allow_all_unix_sockets: Option, pub allowed_domains: Option>, pub denied_domains: Option>, pub allow_unix_sockets: Option>, @@ -38,6 +39,7 @@ pub struct PartialNetworkConfig { pub allow_upstream_proxy: Option, pub dangerously_allow_non_loopback_proxy: Option, pub dangerously_allow_non_loopback_admin: Option, + pub dangerously_allow_all_unix_sockets: Option, #[serde(default)] pub allowed_domains: Option>, #[serde(default)] @@ -52,6 +54,7 @@ pub fn build_config_state( config: NetworkProxyConfig, constraints: NetworkProxyConstraints, ) -> anyhow::Result { + crate::config::validate_unix_socket_allowlist_paths(&config)?; let deny_set = compile_globset(&config.network.denied_domains)?; let allow_set = compile_globset(&config.network.allowed_domains)?; Ok(ConfigState { @@ -173,6 +176,24 @@ pub fn validate_policy_against_constraints( }, )?; + let allow_all_unix_sockets = constraints + .dangerously_allow_all_unix_sockets + .unwrap_or(constraints.allow_unix_sockets.is_none()); + validate( + config.network.dangerously_allow_all_unix_sockets, + move |candidate| { + if *candidate && !allow_all_unix_sockets { + Err(invalid_value( + "network.dangerously_allow_all_unix_sockets", + "true", + "false (disabled by managed config)", + )) + } else { + Ok(()) + } + }, + )?; + if let Some(allow_local_binding) = constraints.allow_local_binding { validate(config.network.allow_local_binding, move |candidate| { if *candidate && !allow_local_binding { diff --git a/codex-rs/tui/src/debug_config.rs b/codex-rs/tui/src/debug_config.rs index a3f32d298d..38faf2d35b 100644 --- a/codex-rs/tui/src/debug_config.rs +++ b/codex-rs/tui/src/debug_config.rs @@ -332,6 +332,7 @@ fn format_network_constraints(network: &NetworkConstraints) -> String { allow_upstream_proxy, dangerously_allow_non_loopback_proxy, dangerously_allow_non_loopback_admin, + dangerously_allow_all_unix_sockets, allowed_domains, denied_domains, allow_unix_sockets, @@ -360,6 +361,11 @@ fn format_network_constraints(network: &NetworkConstraints) -> String { "dangerously_allow_non_loopback_admin={dangerously_allow_non_loopback_admin}" )); } + if let Some(dangerously_allow_all_unix_sockets) = dangerously_allow_all_unix_sockets { + parts.push(format!( + "dangerously_allow_all_unix_sockets={dangerously_allow_all_unix_sockets}" + )); + } if let Some(allowed_domains) = allowed_domains { parts.push(format!("allowed_domains=[{}]", allowed_domains.join(", "))); } From 097620218d2cc7ca310a8df21cf59243ddf32d0a Mon Sep 17 00:00:00 2001 From: Curtis 'Fjord' Hawthorne Date: Fri, 20 Feb 2026 11:20:45 -0800 Subject: [PATCH 020/385] js_repl: remove codex.state helper references (#12275) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary This PR removes `codex.state` from the `js_repl` helper surface and removes all corresponding documentation/instruction references. ## Motivation Top-level bindings in `js_repl` now persist across cells, so the extra `codex.state` helper is redundant and adds unnecessary API/docs surface. ## Changes - Removed the long-lived `state` object from the Node kernel helper wiring. - Stopped exposing `codex.state` (and `context.state`) during `js_repl` execution. - Updated user-facing `js_repl` docs to remove `codex.state`. - Updated generated instruction text and related test expectations to list only: - `codex.tmpDir` - `codex.tool(name, args?)` #### [git stack](https://github.com/magus/git-stack-cli) - ✅ `1` https://github.com/openai/codex/pull/12300 - 👉 `2` https://github.com/openai/codex/pull/12275 - ⏳ `3` https://github.com/openai/codex/pull/12205 - ⏳ `4` https://github.com/openai/codex/pull/12185 - ⏳ `5` https://github.com/openai/codex/pull/10673 --- codex-rs/core/src/project_doc.rs | 10 ++++++---- codex-rs/core/src/tools/js_repl/kernel.js | 6 +----- docs/js_repl.md | 1 - 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 3d2b55ab5b..0147a766fe 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -40,9 +40,11 @@ fn render_js_repl_instructions(config: &Config) -> Option { } let mut section = String::from("## JavaScript REPL (Node)\n"); - section.push_str("- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel. `codex.state` persists for the session (best effort) and is cleared by `js_repl_reset`.\n"); + section.push_str( + "- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n", + ); section.push_str("- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n"); - section.push_str("- Helpers: `codex.state`, `codex.tmpDir`, and `codex.tool(name, args?)`.\n"); + section.push_str("- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n"); section.push_str("- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n"); section.push_str("- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n"); section.push_str("- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n"); @@ -415,7 +417,7 @@ mod tests { let res = get_user_instructions(&cfg, None) .await .expect("js_repl instructions expected"); - let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel. `codex.state` persists for the session (best effort) and is cleared by `js_repl_reset`.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.state`, `codex.tmpDir`, and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; + let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; assert_eq!(res, expected); } @@ -430,7 +432,7 @@ mod tests { let res = get_user_instructions(&cfg, None) .await .expect("js_repl instructions expected"); - let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel. `codex.state` persists for the session (best effort) and is cleared by `js_repl_reset`.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.state`, `codex.tmpDir`, and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Do not call tools directly; use `js_repl` + `codex.tool(...)` for all tool calls, including shell commands.\n- MCP tools (if any) can also be called by name via `codex.tool(...)`.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; + let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Do not call tools directly; use `js_repl` + `codex.tool(...)` for all tool calls, including shell commands.\n- MCP tools (if any) can also be called by name via `codex.tool(...)`.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; assert_eq!(res, expected); } diff --git a/codex-rs/core/src/tools/js_repl/kernel.js b/codex-rs/core/src/tools/js_repl/kernel.js index 67a1f23a8b..283a9f4516 100644 --- a/codex-rs/core/src/tools/js_repl/kernel.js +++ b/codex-rs/core/src/tools/js_repl/kernel.js @@ -115,9 +115,6 @@ function isDeniedBuiltin(specifier) { const pendingTool = new Map(); let toolCounter = 0; const tmpDir = process.env.CODEX_JS_TMP_DIR || process.cwd(); -// Explicit long-lived mutable store exposed as `codex.state`. This is useful -// when callers want shared state without relying on lexical binding carry-over. -const state = {}; const nodeModuleDirEnv = process.env.CODEX_JS_REPL_NODE_MODULE_DIRS ?? ""; const moduleSearchBases = (() => { const bases = []; @@ -470,8 +467,7 @@ async function handleExec(message) { const { source, nextBindings } = await buildModuleSource(code); let output = ""; - context.state = state; - context.codex = { state, tmpDir, tool }; + context.codex = { tmpDir, tool }; context.tmpDir = tmpDir; await withCapturedConsole(context, async (logs) => { diff --git a/docs/js_repl.md b/docs/js_repl.md index a9b8b7228e..eb0ea84ffd 100644 --- a/docs/js_repl.md +++ b/docs/js_repl.md @@ -63,7 +63,6 @@ For `CODEX_JS_REPL_NODE_MODULE_DIRS` and `js_repl_node_module_dirs`, module reso `js_repl` exposes these globals: -- `codex.state`: mutable object persisted for the current kernel session. - `codex.tmpDir`: per-session scratch directory path. - `codex.tool(name, args?)`: executes a normal Codex tool call from inside `js_repl` (including shell tools like `shell` / `shell_command` when available). - To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool("view_image", { path: "/absolute/path" })`, then delete the file. From f08cf8d65f552d06c48eb7935acf9b6dfe17fb4c Mon Sep 17 00:00:00 2001 From: daniel-oai Date: Fri, 20 Feb 2026 11:35:28 -0800 Subject: [PATCH 021/385] CODEX-4927: Surface local login entitlement denials in browser (#12289) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem Users without Codex access can hit a confusing local login loop. In the denial case, the callback could fall through to generic behavior (including a plain "Missing authorization code" page) instead of clearly explaining that access was denied. Screenshot 2026-02-19 at 11 43 45 PM Screenshot 2026-02-19 at 11 44 53 PM ## Scope This PR improves local login error clarity only. It does not change entitlement policy, RBAC rules, or who is allowed to use Codex. ## What Changed - The local OAuth callback handler now parses `error` and `error_description` on `/auth/callback` and exits the callback loop with a real failure. - Callback failures render a branded local Codex error page instead of a generic/plain page. - `access_denied` + `missing_codex_entitlement` is now mapped to an explicit user-facing message telling the user Codex is not enabled for their workspace and to contact their workspace administrator for access. - Unknown OAuth callback errors continue to use a generic error page while preserving the OAuth error code/details for debugging. - Added the login error page template to Bazel assets so the local binary can render it in Bazel builds. ## Non-goals - No TUI onboarding/toast changes in this PR. - No backend entitlement or policy changes. ## Tests - Added an end-to-end `codex-login` test for `access_denied` + `missing_codex_entitlement` and verified the page shows the actionable admin guidance. - Added an end-to-end `codex-login` test for a generic `access_denied` reason to verify we keep a generic fallback page/message. --- codex-rs/login/BUILD.bazel | 5 +- codex-rs/login/src/assets/error.html | 122 +++++++++++ codex-rs/login/src/server.rs | 201 ++++++++++++++++-- .../login/tests/suite/login_server_e2e.rs | 146 +++++++++++++ 4 files changed, 450 insertions(+), 24 deletions(-) create mode 100644 codex-rs/login/src/assets/error.html diff --git a/codex-rs/login/BUILD.bazel b/codex-rs/login/BUILD.bazel index 127cd60fd9..fe5866577f 100644 --- a/codex-rs/login/BUILD.bazel +++ b/codex-rs/login/BUILD.bazel @@ -3,5 +3,8 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "login", crate_name = "codex_login", - compile_data = ["src/assets/success.html"], + compile_data = [ + "src/assets/error.html", + "src/assets/success.html", + ], ) diff --git a/codex-rs/login/src/assets/error.html b/codex-rs/login/src/assets/error.html new file mode 100644 index 0000000000..96c1eb303c --- /dev/null +++ b/codex-rs/login/src/assets/error.html @@ -0,0 +1,122 @@ + + + + + Codex Sign-in Error + + + + +
+
+
+ +
Codex login
+
+ +

__ERROR_TITLE__

+

__ERROR_MESSAGE__

+ +
+
+ Error code + __ERROR_CODE__ +
+
+ Details + __ERROR_DESCRIPTION__ +
+
+ +

__ERROR_HELP__

+
+
+ + diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index d97de008e6..53b4ad3601 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -1,3 +1,6 @@ +//! Local OAuth callback server for CLI login. +//! +//! This module runs the short-lived localhost server used by interactive sign-in. use std::io::Cursor; use std::io::Read; use std::io::Write; @@ -32,6 +35,7 @@ use tiny_http::StatusCode; const DEFAULT_ISSUER: &str = "https://auth.openai.com"; const DEFAULT_PORT: u16 = 1455; +/// Options for launching the local login callback server. #[derive(Debug, Clone)] pub struct ServerOptions { pub codex_home: PathBuf, @@ -45,6 +49,7 @@ pub struct ServerOptions { } impl ServerOptions { + /// Creates a server configuration with the default issuer and port. pub fn new( codex_home: PathBuf, client_id: String, @@ -64,6 +69,7 @@ impl ServerOptions { } } +/// Handle for a running login callback server. pub struct LoginServer { pub auth_url: String, pub actual_port: u16, @@ -72,32 +78,38 @@ pub struct LoginServer { } impl LoginServer { + /// Waits for the login callback loop to finish. pub async fn block_until_done(self) -> io::Result<()> { self.server_handle .await .map_err(|err| io::Error::other(format!("login server thread panicked: {err:?}")))? } + /// Requests shutdown of the callback server. pub fn cancel(&self) { self.shutdown_handle.shutdown(); } + /// Returns a cloneable cancel handle for the running server. pub fn cancel_handle(&self) -> ShutdownHandle { self.shutdown_handle.clone() } } +/// Handle used to signal the login server loop to exit. #[derive(Clone, Debug)] pub struct ShutdownHandle { shutdown_notify: Arc, } impl ShutdownHandle { + /// Signals the login loop to terminate. pub fn shutdown(&self) { self.shutdown_notify.notify_waiters(); } } +/// Starts a local callback server and returns the browser auth URL. pub fn run_login_server(opts: ServerOptions) -> io::Result { let pkce = generate_pkce(); let state = opts.force_state.clone().unwrap_or_else(generate_state); @@ -207,6 +219,7 @@ pub fn run_login_server(opts: ServerOptions) -> io::Result { }) } +/// Internal callback handling outcome. enum HandledRequest { Response(Response>>), RedirectWithHeader(Header), @@ -245,11 +258,25 @@ async fn process_request( Response::from_string("State mismatch").with_status_code(400), ); } + if let Some(error_code) = params.get("error") { + let error_description = params.get("error_description").map(String::as_str); + let message = oauth_callback_error_message(error_code, error_description); + eprintln!("OAuth callback error: {message}"); + return login_error_response( + &message, + io::ErrorKind::PermissionDenied, + Some(error_code), + error_description, + ); + } let code = match params.get("code") { Some(c) if !c.is_empty() => c.clone(), _ => { - return HandledRequest::Response( - Response::from_string("Missing authorization code").with_status_code(400), + return login_error_response( + "Missing authorization code. Sign-in could not be completed.", + io::ErrorKind::InvalidData, + Some("missing_authorization_code"), + None, ); } }; @@ -263,7 +290,12 @@ async fn process_request( &tokens.id_token, ) { eprintln!("Workspace restriction error: {message}"); - return login_error_response(&message); + return login_error_response( + &message, + io::ErrorKind::PermissionDenied, + Some("workspace_restriction"), + None, + ); } // Obtain API key via token-exchange and persist let api_key = obtain_api_key(&opts.issuer, &opts.client_id, &tokens.id_token) @@ -280,9 +312,11 @@ async fn process_request( .await { eprintln!("Persist error: {err}"); - return HandledRequest::Response( - Response::from_string(format!("Unable to persist auth file: {err}")) - .with_status_code(500), + return login_error_response( + "Sign-in completed but credentials could not be saved locally.", + io::ErrorKind::Other, + Some("persist_failed"), + Some(&err.to_string()), ); } @@ -294,16 +328,21 @@ async fn process_request( ); match tiny_http::Header::from_bytes(&b"Location"[..], success_url.as_bytes()) { Ok(header) => HandledRequest::RedirectWithHeader(header), - Err(_) => HandledRequest::Response( - Response::from_string("Internal Server Error").with_status_code(500), + Err(_) => login_error_response( + "Sign-in completed but redirecting back to Codex failed.", + io::ErrorKind::Other, + Some("redirect_failed"), + None, ), } } Err(err) => { eprintln!("Token exchange error: {err}"); - HandledRequest::Response( - Response::from_string(format!("Token exchange failed: {err}")) - .with_status_code(500), + login_error_response( + &format!("Token exchange failed: {err}"), + io::ErrorKind::Other, + Some("token_exchange_failed"), + None, ) } } @@ -486,12 +525,14 @@ fn bind_server(port: u16) -> io::Result { } } +/// Tokens returned by the OAuth authorization-code exchange. pub(crate) struct ExchangedTokens { pub id_token: String, pub access_token: String, pub refresh_token: String, } +/// Exchanges an authorization code for tokens. pub(crate) async fn exchange_code_for_tokens( issuer: &str, client_id: &str, @@ -521,10 +562,12 @@ pub(crate) async fn exchange_code_for_tokens( .await .map_err(io::Error::other)?; - if !resp.status().is_success() { + let status = resp.status(); + if !status.is_success() { + let body = resp.text().await.map_err(io::Error::other)?; + let detail = parse_token_endpoint_error(&body); return Err(io::Error::other(format!( - "token endpoint returned status {}", - resp.status() + "token endpoint returned status {status}: {detail}" ))); } @@ -536,6 +579,7 @@ pub(crate) async fn exchange_code_for_tokens( }) } +/// Persists exchanged credentials using the configured local auth store. pub(crate) async fn persist_tokens_async( codex_home: &Path, api_key: Option, @@ -650,6 +694,7 @@ fn jwt_auth_claims(jwt: &str) -> serde_json::Map { serde_json::Map::new() } +/// Validates the ID token against an optional workspace restriction. pub(crate) fn ensure_workspace_allowed( expected: Option<&str>, id_token: &str, @@ -670,23 +715,133 @@ pub(crate) fn ensure_workspace_allowed( } } -// Respond to the oauth server with an error so the code becomes unusable by anybody else. -fn login_error_response(message: &str) -> HandledRequest { +/// Builds a terminal callback response for login failures. +fn login_error_response( + message: &str, + kind: io::ErrorKind, + error_code: Option<&str>, + error_description: Option<&str>, +) -> HandledRequest { let mut headers = Vec::new(); - if let Ok(header) = Header::from_bytes(&b"Content-Type"[..], &b"text/plain; charset=utf-8"[..]) - { + if let Ok(header) = Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]) { headers.push(header); } + let body = render_login_error_page(message, error_code, error_description); HandledRequest::ResponseAndExit { headers, - body: message.as_bytes().to_vec(), - result: Err(io::Error::new( - io::ErrorKind::PermissionDenied, - message.to_string(), - )), + body, + result: Err(io::Error::new(kind, message.to_string())), } } +/// Returns true when the OAuth callback represents a missing Codex entitlement. +fn is_missing_codex_entitlement_error(error_code: &str, error_description: Option<&str>) -> bool { + error_code == "access_denied" + && error_description.is_some_and(|description| { + description + .to_ascii_lowercase() + .contains("missing_codex_entitlement") + }) +} + +/// Converts OAuth callback errors into a user-facing message. +fn oauth_callback_error_message(error_code: &str, error_description: Option<&str>) -> String { + if is_missing_codex_entitlement_error(error_code, error_description) { + return "Codex is not enabled for your workspace. Contact your workspace administrator to request access to Codex.".to_string(); + } + + if let Some(description) = error_description + && !description.trim().is_empty() + { + return format!("Sign-in failed: {description}"); + } + + format!("Sign-in failed: {error_code}") +} + +/// Extracts a readable error from token endpoint responses. +fn parse_token_endpoint_error(body: &str) -> String { + let trimmed = body.trim(); + if trimmed.is_empty() { + return "unknown error".to_string(); + } + + let parsed = serde_json::from_str::(trimmed).ok(); + if let Some(json) = parsed { + if let Some(description) = json.get("error_description").and_then(JsonValue::as_str) + && !description.trim().is_empty() + { + return description.to_string(); + } + if let Some(error_obj) = json.get("error") + && let Some(message) = error_obj.get("message").and_then(JsonValue::as_str) + && !message.trim().is_empty() + { + return message.to_string(); + } + if let Some(error_code) = json.get("error").and_then(JsonValue::as_str) + && !error_code.trim().is_empty() + { + return error_code.to_string(); + } + } + + trimmed.to_string() +} + +/// Renders the branded error page used by callback failures. +fn render_login_error_page( + message: &str, + error_code: Option<&str>, + error_description: Option<&str>, +) -> Vec { + let template = include_str!("assets/error.html"); + let code = error_code.unwrap_or("unknown_error"); + let (title, display_message, display_description, help_text) = + if is_missing_codex_entitlement_error(code, error_description) { + ( + "You do not have access to Codex".to_string(), + "This account is not currently authorized to use Codex in this workspace." + .to_string(), + "Contact your workspace administrator to request access to Codex.".to_string(), + "Contact your workspace administrator to get access to Codex, then return to Codex and try again." + .to_string(), + ) + } else { + ( + "Sign-in could not be completed".to_string(), + message.to_string(), + error_description.unwrap_or(message).to_string(), + "Return to Codex to retry, switch accounts, or contact your workspace admin if access is restricted." + .to_string(), + ) + }; + template + .replace("__ERROR_TITLE__", &html_escape(&title)) + .replace("__ERROR_MESSAGE__", &html_escape(&display_message)) + .replace("__ERROR_CODE__", &html_escape(code)) + .replace("__ERROR_DESCRIPTION__", &html_escape(&display_description)) + .replace("__ERROR_HELP__", &html_escape(&help_text)) + .into_bytes() +} + +/// Escapes error strings before inserting them into HTML. +fn html_escape(input: &str) -> String { + let mut escaped = String::with_capacity(input.len()); + for ch in input.chars() { + match ch { + '&' => escaped.push_str("&"), + '<' => escaped.push_str("<"), + '>' => escaped.push_str(">"), + '"' => escaped.push_str("""), + '\'' => escaped.push_str("'"), + _ => escaped.push(ch), + } + } + escaped +} + +/// Exchanges an authenticated ID token for an API-key style access token. pub(crate) async fn obtain_api_key( issuer: &str, client_id: &str, diff --git a/codex-rs/login/tests/suite/login_server_e2e.rs b/codex-rs/login/tests/suite/login_server_e2e.rs index 73cb8bd420..cdd4019f77 100644 --- a/codex-rs/login/tests/suite/login_server_e2e.rs +++ b/codex-rs/login/tests/suite/login_server_e2e.rs @@ -255,6 +255,152 @@ async fn forced_chatgpt_workspace_id_mismatch_blocks_login() -> Result<()> { Ok(()) } +#[tokio::test] +async fn oauth_access_denied_missing_entitlement_blocks_login_with_clear_error() -> Result<()> { + skip_if_no_network!(Ok(())); + + let (issuer_addr, _issuer_handle) = start_mock_issuer("org-123"); + let issuer = format!("http://{}:{}", issuer_addr.ip(), issuer_addr.port()); + + let tmp = tempdir()?; + let codex_home = tmp.path().to_path_buf(); + let state = "state-entitlement".to_string(); + + let opts = ServerOptions { + codex_home: codex_home.clone(), + cli_auth_credentials_store_mode: AuthCredentialsStoreMode::File, + client_id: codex_login::CLIENT_ID.to_string(), + issuer, + port: 0, + open_browser: false, + force_state: Some(state.clone()), + forced_chatgpt_workspace_id: None, + }; + let server = run_login_server(opts)?; + let login_port = server.actual_port; + + let client = reqwest::Client::new(); + let url = format!( + "http://127.0.0.1:{login_port}/auth/callback?state={state}&error=access_denied&error_description=missing_codex_entitlement" + ); + let resp = client.get(&url).send().await?; + assert!(resp.status().is_success()); + let body = resp.text().await?; + assert!( + body.contains("You do not have access to Codex"), + "error body should clearly explain the Codex access denial" + ); + assert!( + body.contains("Contact your workspace administrator"), + "error body should tell the user how to get access" + ); + assert!( + body.contains("access_denied"), + "error body should still include the oauth error code" + ); + assert!( + !body.contains("missing_codex_entitlement"), + "known entitlement errors should be mapped to user-facing copy" + ); + + let result = server.block_until_done().await; + assert!(result.is_err(), "login should fail for access_denied"); + let err = result.unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + assert!( + err.to_string() + .contains("Contact your workspace administrator"), + "terminal error should also tell the user what to do next" + ); + + let auth_path = codex_home.join("auth.json"); + assert!( + !auth_path.exists(), + "auth.json should not be written when oauth callback is denied" + ); + + Ok(()) +} + +#[tokio::test] +async fn oauth_access_denied_unknown_reason_uses_generic_error_page() -> Result<()> { + skip_if_no_network!(Ok(())); + + let (issuer_addr, _issuer_handle) = start_mock_issuer("org-123"); + let issuer = format!("http://{}:{}", issuer_addr.ip(), issuer_addr.port()); + + let tmp = tempdir()?; + let codex_home = tmp.path().to_path_buf(); + let state = "state-generic-denial".to_string(); + + let opts = ServerOptions { + codex_home: codex_home.clone(), + cli_auth_credentials_store_mode: AuthCredentialsStoreMode::File, + client_id: codex_login::CLIENT_ID.to_string(), + issuer, + port: 0, + open_browser: false, + force_state: Some(state.clone()), + forced_chatgpt_workspace_id: None, + }; + let server = run_login_server(opts)?; + let login_port = server.actual_port; + + let client = reqwest::Client::new(); + let url = format!( + "http://127.0.0.1:{login_port}/auth/callback?state={state}&error=access_denied&error_description=some_other_reason" + ); + let resp = client.get(&url).send().await?; + assert!(resp.status().is_success()); + let body = resp.text().await?; + assert!( + body.contains("Sign-in could not be completed"), + "generic oauth denial should use the generic error page title" + ); + assert!( + body.contains("Sign-in failed: some_other_reason"), + "generic oauth denial should preserve the oauth error details" + ); + assert!( + body.contains("Return to Codex to retry"), + "generic oauth denial should keep the generic help text" + ); + assert!( + body.contains("access_denied"), + "generic oauth denial should include the oauth error code" + ); + assert!( + body.contains("some_other_reason"), + "generic oauth denial should include the oauth error description" + ); + assert!( + !body.contains("You do not have access to Codex"), + "generic oauth denial should not show the entitlement-specific title" + ); + assert!( + !body.contains("get access to Codex"), + "generic oauth denial should not show the entitlement-specific admin guidance" + ); + + let result = server.block_until_done().await; + assert!(result.is_err(), "login should fail for access_denied"); + let err = result.unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + assert!( + err.to_string() + .contains("Sign-in failed: some_other_reason"), + "terminal error should preserve generic oauth details" + ); + + let auth_path = codex_home.join("auth.json"); + assert!( + !auth_path.exists(), + "auth.json should not be written when oauth callback is denied" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn cancels_previous_login_server_when_port_is_in_use() -> Result<()> { skip_if_no_network!(Ok(())); From 67e802e26b7526d9aeceebb5faf748c04f13388d Mon Sep 17 00:00:00 2001 From: Curtis 'Fjord' Hawthorne Date: Fri, 20 Feb 2026 11:51:17 -0800 Subject: [PATCH 022/385] ci(bazel): install Node from node-version.txt in remote image (#12205) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Install Node in the Bazel remote execution image using the version pinned in `codex-rs/node-version.txt`. ## Why `js_repl` tests run under Bazel remote execution and require a modern Node runtime. Runner-level `setup-node` does not guarantee Node is available (or recent enough) inside the remote worker container. ## What changed - Updated `.github/workflows/Dockerfile.bazel` to install Node from official tarballs at image build time. - Added `xz-utils` for extracting `.tar.xz` archives. - Copied `codex-rs/node-version.txt` into the image build context and used it as the single source of truth for Node version. - Added architecture mapping for multi-arch builds: - `amd64 -> x64` - `arm64 -> arm64` - Verified install during image build with: - `node --version` - `npm --version` ## Impact - Bazel remote workers should now have the required Node version available for `js_repl` tests. - Keeps Node version synchronized with repo policy via `codex-rs/node-version.txt`. ## Testing - Verified Dockerfile changes and build steps locally (build-time commands are deterministic and fail fast on unsupported arch/version fetch issues). ## Follow-up - Rebuild and publish the Bazel runner image for both `linux/amd64` and `linux/arm64`. - Update image digests in `rbe.bzl` to roll out this runtime update in CI. #### [git stack](https://github.com/magus/git-stack-cli) - ✅ `1` https://github.com/openai/codex/pull/12300 - ✅ `2` https://github.com/openai/codex/pull/12275 - 👉 `3` https://github.com/openai/codex/pull/12205 - ⏳ `4` https://github.com/openai/codex/pull/12185 - ⏳ `5` https://github.com/openai/codex/pull/10673 --- .github/workflows/Dockerfile.bazel | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/workflows/Dockerfile.bazel b/.github/workflows/Dockerfile.bazel index 51c199dcc3..4f85409f94 100644 --- a/.github/workflows/Dockerfile.bazel +++ b/.github/workflows/Dockerfile.bazel @@ -8,9 +8,25 @@ FROM ubuntu:24.04 RUN apt-get update && \ apt-get install -y --no-install-recommends \ - curl git python3 ca-certificates && \ + curl git python3 ca-certificates xz-utils && \ rm -rf /var/lib/apt/lists/* +COPY codex-rs/node-version.txt /tmp/node-version.txt + +RUN set -eux; \ + node_arch="$(dpkg --print-architecture)"; \ + case "${node_arch}" in \ + amd64) node_dist_arch="x64" ;; \ + arm64) node_dist_arch="arm64" ;; \ + *) echo "unsupported architecture: ${node_arch}"; exit 1 ;; \ + esac; \ + node_version="$(tr -d '[:space:]' Date: Fri, 20 Feb 2026 20:02:24 +0000 Subject: [PATCH 023/385] feat: add config `allow_login_shell` (#12312) --- codex-rs/core/config.schema.json | 4 + codex-rs/core/src/codex.rs | 3 + codex-rs/core/src/config/mod.rs | 46 ++++++++++ codex-rs/core/src/memories/usage.rs | 22 +++-- codex-rs/core/src/skills/loader.rs | 4 + codex-rs/core/src/skills/permissions.rs | 4 + codex-rs/core/src/tools/handlers/shell.rs | 87 ++++++++++++++++--- .../core/src/tools/handlers/unified_exec.rs | 69 ++++++++++++--- codex-rs/core/src/tools/spec.rs | 61 ++++++++----- 9 files changed, 244 insertions(+), 56 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 732f9590f7..97ce03cadf 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1392,6 +1392,10 @@ ], "description": "Agent-related settings (thread limits, etc.)." }, + "allow_login_shell": { + "description": "Whether the model may request a login shell for shell-based tools. Default to `true`\n\nIf `true`, the model may request a login shell (`login = true`), and omitting `login` defaults to using a login shell. If `false`, the model can never use a login shell: `login = true` requests are rejected, and omitting `login` defaults to a non-login shell.", + "type": "boolean" + }, "analytics": { "allOf": [ { diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index b5614cced5..2d5d283d6a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -609,6 +609,7 @@ impl TurnContext { features: &features, web_search_mode: self.tools_config.web_search_mode, }) + .with_allow_login_shell(self.tools_config.allow_login_shell) .with_agent_roles(config.agent_roles.clone()); Self { @@ -941,6 +942,7 @@ impl Session { features: &per_turn_config.features, web_search_mode: Some(per_turn_config.web_search_mode.value()), }) + .with_allow_login_shell(per_turn_config.permissions.allow_login_shell) .with_agent_roles(per_turn_config.agent_roles.clone()); let cwd = session_configuration.cwd.clone(); @@ -4122,6 +4124,7 @@ async fn spawn_review_thread( features: &review_features, web_search_mode: Some(review_web_search_mode), }) + .with_allow_login_shell(config.permissions.allow_login_shell) .with_agent_roles(config.agent_roles.clone()); let review_prompt = resolved.prompt.clone(); diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 1675067c7a..3b8e0382e8 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -139,6 +139,15 @@ pub struct Permissions { pub sandbox_policy: Constrained, /// Effective network configuration applied to all spawned processes. pub network: Option, + /// Whether the model may request a login shell for shell-based tools. + /// Default to `true` + /// + /// If `true`, the model may request a login shell (`login = true`), and + /// omitting `login` defaults to using a login shell. + /// If `false`, the model can never use a login shell: `login = true` + /// requests are rejected, and omitting `login` defaults to a non-login + /// shell. + pub allow_login_shell: bool, /// Policy used to build process environments for shell/unified exec. pub shell_environment_policy: ShellEnvironmentPolicy, /// Effective Windows sandbox mode derived from `[windows].sandbox` or @@ -952,6 +961,16 @@ pub struct ConfigToml { #[serde(default)] pub shell_environment_policy: ShellEnvironmentPolicyToml, + /// Whether the model may request a login shell for shell-based tools. + /// Default to `true` + /// + /// If `true`, the model may request a login shell (`login = true`), and + /// omitting `login` defaults to using a login shell. + /// If `false`, the model can never use a login shell: `login = true` + /// requests are rejected, and omitting `login` defaults to a non-login + /// shell. + pub allow_login_shell: Option, + /// Sandbox mode to use. pub sandbox_mode: Option, @@ -1710,6 +1729,7 @@ impl Config { .clone(); let shell_environment_policy = cfg.shell_environment_policy.into(); + let allow_login_shell = cfg.allow_login_shell.unwrap_or(true); let history = cfg.history.unwrap_or_default(); @@ -1950,6 +1970,7 @@ impl Config { approval_policy: constrained_approval_policy.value, sandbox_policy: constrained_sandbox_policy.value, network, + allow_login_shell, shell_environment_policy, windows_sandbox_mode, macos_seatbelt_profile_extensions: None, @@ -4519,6 +4540,7 @@ model_verbosity = "high" approval_policy: Constrained::allow_any(AskForApproval::Never), sandbox_policy: Constrained::allow_any(SandboxPolicy::new_read_only_policy()), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions: None, @@ -4637,6 +4659,7 @@ model_verbosity = "high" approval_policy: Constrained::allow_any(AskForApproval::UnlessTrusted), sandbox_policy: Constrained::allow_any(SandboxPolicy::new_read_only_policy()), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions: None, @@ -4753,6 +4776,7 @@ model_verbosity = "high" approval_policy: Constrained::allow_any(AskForApproval::OnFailure), sandbox_policy: Constrained::allow_any(SandboxPolicy::new_read_only_policy()), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions: None, @@ -4855,6 +4879,7 @@ model_verbosity = "high" approval_policy: Constrained::allow_any(AskForApproval::OnFailure), sandbox_policy: Constrained::allow_any(SandboxPolicy::new_read_only_policy()), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions: None, @@ -5429,6 +5454,27 @@ mcp_oauth_callback_port = 5678 Ok(()) } + #[test] + fn config_loads_allow_login_shell_from_toml() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg: ConfigToml = toml::from_str( + r#" +model = "gpt-5.1" +allow_login_shell = false +"#, + ) + .expect("TOML deserialization should succeed for allow_login_shell"); + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert!(!config.permissions.allow_login_shell); + Ok(()) + } + #[test] fn config_loads_mcp_oauth_callback_url_from_toml() -> std::io::Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/core/src/memories/usage.rs b/codex-rs/core/src/memories/usage.rs index dbdcd25735..ff82d6e164 100644 --- a/codex-rs/core/src/memories/usage.rs +++ b/codex-rs/core/src/memories/usage.rs @@ -84,22 +84,28 @@ fn shell_command_for_invocation(invocation: &ToolInvocation) -> Option<(Vec serde_json::from_str::(arguments) .ok() .map(|params| { + if !invocation.turn.tools_config.allow_login_shell && params.login == Some(true) { + return (Vec::new(), invocation.turn.resolve_path(params.workdir)); + } + let use_login_shell = params + .login + .unwrap_or(invocation.turn.tools_config.allow_login_shell); let command = invocation .session .user_shell() - .derive_exec_args(¶ms.command, params.login.unwrap_or(true)); + .derive_exec_args(¶ms.command, use_login_shell); (command, invocation.turn.resolve_path(params.workdir)) }), "exec_command" => serde_json::from_str::(arguments) .ok() - .map(|params| { - ( - crate::tools::handlers::unified_exec::get_command( - ¶ms, - invocation.session.user_shell(), - ), - invocation.turn.resolve_path(params.workdir), + .and_then(|params| { + let command = crate::tools::handlers::unified_exec::get_command( + ¶ms, + invocation.session.user_shell(), + invocation.turn.tools_config.allow_login_shell, ) + .ok()?; + Some((command, invocation.turn.resolve_path(params.workdir))) }), _ => None, } diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index e00bd42976..3c497bfcf8 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -1372,6 +1372,7 @@ permissions: } ), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions, @@ -1408,6 +1409,7 @@ permissions: {} crate::protocol::SandboxPolicy::new_read_only_policy(), ), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions: Some( @@ -1421,6 +1423,7 @@ permissions: {} crate::protocol::SandboxPolicy::new_read_only_policy(), ), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions: None, @@ -1515,6 +1518,7 @@ permissions: crate::protocol::SandboxPolicy::new_read_only_policy(), ), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions: None, diff --git a/codex-rs/core/src/skills/permissions.rs b/codex-rs/core/src/skills/permissions.rs index 1cf18e1052..24f3c9444c 100644 --- a/codex-rs/core/src/skills/permissions.rs +++ b/codex-rs/core/src/skills/permissions.rs @@ -112,6 +112,7 @@ pub(crate) fn compile_permission_profile( approval_policy: Constrained::allow_any(AskForApproval::Never), sandbox_policy: Constrained::allow_any(sandbox_policy), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, macos_seatbelt_profile_extensions, @@ -347,6 +348,7 @@ mod tests { exclude_slash_tmp: false, }), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, #[cfg(target_os = "macos")] @@ -391,6 +393,7 @@ mod tests { approval_policy: Constrained::allow_any(AskForApproval::Never), sandbox_policy: Constrained::allow_any(SandboxPolicy::new_read_only_policy()), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, #[cfg(target_os = "macos")] @@ -439,6 +442,7 @@ mod tests { }, }), network: None, + allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), windows_sandbox_mode: None, #[cfg(target_os = "macos")] diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 8ca6de0d80..f040b4ba64 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -63,8 +63,20 @@ impl ShellHandler { } impl ShellCommandHandler { - fn base_command(shell: &Shell, command: &str, login: Option) -> Vec { - let use_login_shell = login.unwrap_or(true); + fn resolve_use_login_shell( + login: Option, + allow_login_shell: bool, + ) -> Result { + if !allow_login_shell && login == Some(true) { + return Err(FunctionCallError::RespondToModel( + "login shell is disabled by config; omit `login` or set it to false.".to_string(), + )); + } + + Ok(login.unwrap_or(allow_login_shell)) + } + + fn base_command(shell: &Shell, command: &str, use_login_shell: bool) -> Vec { shell.derive_exec_args(command, use_login_shell) } @@ -73,11 +85,13 @@ impl ShellCommandHandler { session: &crate::codex::Session, turn_context: &TurnContext, thread_id: ThreadId, - ) -> ExecParams { + allow_login_shell: bool, + ) -> Result { let shell = session.user_shell(); - let command = Self::base_command(shell.as_ref(), ¶ms.command, params.login); + let use_login_shell = Self::resolve_use_login_shell(params.login, allow_login_shell)?; + let command = Self::base_command(shell.as_ref(), ¶ms.command, use_login_shell); - ExecParams { + Ok(ExecParams { command, cwd: turn_context.resolve_path(params.workdir.clone()), expiration: params.timeout_ms.into(), @@ -87,7 +101,7 @@ impl ShellCommandHandler { windows_sandbox_level: turn_context.windows_sandbox_level, justification: params.justification.clone(), arg0: None, - } + }) } } @@ -183,8 +197,15 @@ impl ToolHandler for ShellCommandHandler { serde_json::from_str::(arguments) .map(|params| { + let use_login_shell = match Self::resolve_use_login_shell( + params.login, + invocation.turn.tools_config.allow_login_shell, + ) { + Ok(use_login_shell) => use_login_shell, + Err(_) => return true, + }; let shell = invocation.session.user_shell(); - let command = Self::base_command(shell.as_ref(), ¶ms.command, params.login); + let command = Self::base_command(shell.as_ref(), ¶ms.command, use_login_shell); !is_known_safe_command(&command) }) .unwrap_or(true) @@ -213,7 +234,8 @@ impl ToolHandler for ShellCommandHandler { session.as_ref(), turn.as_ref(), session.conversation_id, - ); + turn.tools_config.allow_login_shell, + )?; ShellHandler::run_exec_like(RunExecLikeArgs { tool_name, exec_params, @@ -439,7 +461,9 @@ mod tests { &session, &turn_context, session.conversation_id, - ); + true, + ) + .expect("login shells should be allowed"); // ExecParams cannot derive Eq due to the CancellationToken field, so we manually compare the fields. assert_eq!(exec_params.command, expected_command); @@ -464,18 +488,57 @@ mod tests { shell_snapshot, }; - let login_command = - ShellCommandHandler::base_command(&shell, "echo login shell", Some(true)); + let login_command = ShellCommandHandler::base_command(&shell, "echo login shell", true); assert_eq!( login_command, shell.derive_exec_args("echo login shell", true) ); let non_login_command = - ShellCommandHandler::base_command(&shell, "echo non login shell", Some(false)); + ShellCommandHandler::base_command(&shell, "echo non login shell", false); assert_eq!( non_login_command, shell.derive_exec_args("echo non login shell", false) ); } + + #[tokio::test] + async fn shell_command_handler_defaults_to_non_login_when_disallowed() { + let (session, turn_context) = make_session_and_context().await; + let params = ShellCommandToolCallParams { + command: "echo hello".to_string(), + workdir: None, + login: None, + timeout_ms: None, + sandbox_permissions: None, + prefix_rule: None, + justification: None, + }; + + let exec_params = ShellCommandHandler::to_exec_params( + ¶ms, + &session, + &turn_context, + session.conversation_id, + false, + ) + .expect("non-login shells should still be allowed"); + + assert_eq!( + exec_params.command, + session.user_shell().derive_exec_args("echo hello", false) + ); + } + + #[test] + fn shell_command_handler_rejects_login_when_disallowed() { + let err = ShellCommandHandler::resolve_use_login_shell(Some(true), false) + .expect_err("explicit login should be rejected"); + + assert!( + err.to_string() + .contains("login shell is disabled by config"), + "unexpected error: {err}" + ); + } } diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 1bad6fa638..62da64a877 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -32,8 +32,8 @@ pub(crate) struct ExecCommandArgs { pub(crate) workdir: Option, #[serde(default)] shell: Option, - #[serde(default = "default_login")] - login: bool, + #[serde(default)] + login: Option, #[serde(default = "default_tty")] tty: bool, #[serde(default = "default_exec_yield_time_ms")] @@ -68,10 +68,6 @@ fn default_write_stdin_yield_time_ms() -> u64 { 250 } -fn default_login() -> bool { - true -} - fn default_tty() -> bool { false } @@ -98,7 +94,14 @@ impl ToolHandler for UnifiedExecHandler { let Ok(params) = serde_json::from_str::(arguments) else { return true; }; - let command = get_command(¶ms, invocation.session.user_shell()); + let command = match get_command( + ¶ms, + invocation.session.user_shell(), + invocation.turn.tools_config.allow_login_shell, + ) { + Ok(command) => command, + Err(_) => return true, + }; !is_known_safe_command(&command) } @@ -129,7 +132,12 @@ impl ToolHandler for UnifiedExecHandler { "exec_command" => { let args: ExecCommandArgs = parse_arguments(&arguments)?; let process_id = manager.allocate_process_id().await; - let command = get_command(&args, session.user_shell()); + let command = get_command( + &args, + session.user_shell(), + turn.tools_config.allow_login_shell, + ) + .map_err(FunctionCallError::RespondToModel)?; let ExecCommandArgs { workdir, @@ -238,7 +246,11 @@ impl ToolHandler for UnifiedExecHandler { } } -pub(crate) fn get_command(args: &ExecCommandArgs, session_shell: Arc) -> Vec { +pub(crate) fn get_command( + args: &ExecCommandArgs, + session_shell: Arc, + allow_login_shell: bool, +) -> Result, String> { let model_shell = args.shell.as_ref().map(|shell_str| { let mut shell = get_shell_by_model_provided_path(&PathBuf::from(shell_str)); shell.shell_snapshot = crate::shell::empty_shell_snapshot_receiver(); @@ -246,8 +258,17 @@ pub(crate) fn get_command(args: &ExecCommandArgs, session_shell: Arc) -> }); let shell = model_shell.as_ref().unwrap_or(session_shell.as_ref()); + let use_login_shell = match args.login { + Some(true) if !allow_login_shell => { + return Err( + "login shell is disabled by config; omit `login` or set it to false.".to_string(), + ); + } + Some(use_login_shell) => use_login_shell, + None => allow_login_shell, + }; - shell.derive_exec_args(&args.cmd, args.login) + Ok(shell.derive_exec_args(&args.cmd, use_login_shell)) } fn format_response(response: &UnifiedExecResponse) -> String { @@ -283,6 +304,7 @@ fn format_response(response: &UnifiedExecResponse) -> String { mod tests { use super::*; use crate::shell::default_user_shell; + use pretty_assertions::assert_eq; use std::sync::Arc; #[test] @@ -293,7 +315,8 @@ mod tests { assert!(args.shell.is_none()); - let command = get_command(&args, Arc::new(default_user_shell())); + let command = + get_command(&args, Arc::new(default_user_shell()), true).map_err(anyhow::Error::msg)?; assert_eq!(command.len(), 3); assert_eq!(command[2], "echo hello"); @@ -308,7 +331,8 @@ mod tests { assert_eq!(args.shell.as_deref(), Some("/bin/bash")); - let command = get_command(&args, Arc::new(default_user_shell())); + let command = + get_command(&args, Arc::new(default_user_shell()), true).map_err(anyhow::Error::msg)?; assert_eq!(command.last(), Some(&"echo hello".to_string())); if command @@ -328,7 +352,8 @@ mod tests { assert_eq!(args.shell.as_deref(), Some("powershell")); - let command = get_command(&args, Arc::new(default_user_shell())); + let command = + get_command(&args, Arc::new(default_user_shell()), true).map_err(anyhow::Error::msg)?; assert_eq!(command[2], "echo hello"); Ok(()) @@ -342,9 +367,25 @@ mod tests { assert_eq!(args.shell.as_deref(), Some("cmd")); - let command = get_command(&args, Arc::new(default_user_shell())); + let command = + get_command(&args, Arc::new(default_user_shell()), true).map_err(anyhow::Error::msg)?; assert_eq!(command[2], "echo hello"); Ok(()) } + + #[test] + fn test_get_command_rejects_explicit_login_when_disallowed() -> anyhow::Result<()> { + let json = r#"{"cmd": "echo hello", "login": true}"#; + + let args: ExecCommandArgs = parse_arguments(json)?; + let err = get_command(&args, Arc::new(default_user_shell()), false) + .expect_err("explicit login should be rejected"); + + assert!( + err.contains("login shell is disabled by config"), + "unexpected error: {err}" + ); + Ok(()) + } } diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index fe9c7ee8a5..7bd1fc9788 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -35,6 +35,7 @@ const SEARCH_TOOL_BM25_DESCRIPTION_TEMPLATE: &str = #[derive(Debug, Clone)] pub(crate) struct ToolsConfig { pub shell_type: ConfigShellToolType, + pub allow_login_shell: bool, pub apply_patch_tool_type: Option, pub web_search_mode: Option, pub agent_roles: BTreeMap, @@ -96,6 +97,7 @@ impl ToolsConfig { Self { shell_type, + allow_login_shell: true, apply_patch_tool_type, web_search_mode: *web_search_mode, agent_roles: BTreeMap::new(), @@ -112,6 +114,11 @@ impl ToolsConfig { self.agent_roles = agent_roles; self } + + pub fn with_allow_login_shell(mut self, allow_login_shell: bool) -> Self { + self.allow_login_shell = allow_login_shell; + self + } } /// Generic JSON‑Schema subset needed for our tool definitions @@ -211,7 +218,7 @@ fn create_approval_parameters() -> BTreeMap { properties } -fn create_exec_command_tool() -> ToolSpec { +fn create_exec_command_tool(allow_login_shell: bool) -> ToolSpec { let mut properties = BTreeMap::from([ ( "cmd".to_string(), @@ -234,14 +241,6 @@ fn create_exec_command_tool() -> ToolSpec { description: Some("Shell binary to launch. Defaults to the user's default shell.".to_string()), }, ), - ( - "login".to_string(), - JsonSchema::Boolean { - description: Some( - "Whether to run the shell with -l/-i semantics. Defaults to true.".to_string(), - ), - }, - ), ( "tty".to_string(), JsonSchema::Boolean { @@ -269,6 +268,16 @@ fn create_exec_command_tool() -> ToolSpec { }, ), ]); + if allow_login_shell { + properties.insert( + "login".to_string(), + JsonSchema::Boolean { + description: Some( + "Whether to run the shell with -l/-i semantics. Defaults to true.".to_string(), + ), + }, + ); + } properties.extend(create_approval_parameters()); ToolSpec::Function(ResponsesApiTool { @@ -385,7 +394,7 @@ Examples of valid command strings: }) } -fn create_shell_command_tool() -> ToolSpec { +fn create_shell_command_tool(allow_login_shell: bool) -> ToolSpec { let mut properties = BTreeMap::from([ ( "command".to_string(), @@ -402,6 +411,14 @@ fn create_shell_command_tool() -> ToolSpec { }, ), ( + "timeout_ms".to_string(), + JsonSchema::Number { + description: Some("The timeout for the command in milliseconds".to_string()), + }, + ), + ]); + if allow_login_shell { + properties.insert( "login".to_string(), JsonSchema::Boolean { description: Some( @@ -409,14 +426,8 @@ fn create_shell_command_tool() -> ToolSpec { .to_string(), ), }, - ), - ( - "timeout_ms".to_string(), - JsonSchema::Number { - description: Some("The timeout for the command in milliseconds".to_string()), - }, - ), - ]); + ); + } properties.extend(create_approval_parameters()); let description = if cfg!(windows) { @@ -1462,7 +1473,10 @@ pub(crate) fn build_specs( builder.push_spec_with_parallel_support(ToolSpec::LocalShell {}, true); } ConfigShellToolType::UnifiedExec => { - builder.push_spec_with_parallel_support(create_exec_command_tool(), true); + builder.push_spec_with_parallel_support( + create_exec_command_tool(config.allow_login_shell), + true, + ); builder.push_spec(create_write_stdin_tool()); builder.register_handler("exec_command", unified_exec_handler.clone()); builder.register_handler("write_stdin", unified_exec_handler); @@ -1471,7 +1485,10 @@ pub(crate) fn build_specs( // Do nothing. } ConfigShellToolType::ShellCommand => { - builder.push_spec_with_parallel_support(create_shell_command_tool(), true); + builder.push_spec_with_parallel_support( + create_shell_command_tool(config.allow_login_shell), + true, + ); } } @@ -1816,7 +1833,7 @@ mod tests { // Build expected from the same helpers used by the builder. let mut expected: BTreeMap = BTreeMap::from([]); for spec in [ - create_exec_command_tool(), + create_exec_command_tool(true), create_write_stdin_tool(), PLAN_TOOL.clone(), create_request_user_input_tool(), @@ -2790,7 +2807,7 @@ Examples of valid command strings: #[test] fn test_shell_command_tool() { - let tool = super::create_shell_command_tool(); + let tool = super::create_shell_command_tool(true); let ToolSpec::Function(ResponsesApiTool { description, name, .. }) = &tool From aa121a115e257cff4ace1075e1a0411d48f22a59 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Fri, 20 Feb 2026 12:05:21 -0800 Subject: [PATCH 024/385] [apps] Implement apps configs. (#12086) - [x] Implement apps configs. --- .../codex_app_server_protocol.schemas.json | 101 +++- .../schema/json/v2/ConfigReadResponse.json | 103 +++- ...ppDisabledReason.ts => AppToolApproval.ts} | 2 +- .../schema/typescript/v2/AppToolsConfig.ts | 6 + .../schema/typescript/v2/AppsConfig.ts | 6 +- .../schema/typescript/v2/AppsDefaultConfig.ts | 5 + .../schema/typescript/v2/index.ts | 4 +- .../app-server-protocol/src/protocol/v2.rs | 44 +- .../app-server/tests/suite/v2/config_rpc.rs | 23 +- codex-rs/core/config.schema.json | 89 +++- codex-rs/core/src/codex.rs | 19 +- codex-rs/core/src/config/service.rs | 15 +- codex-rs/core/src/config/types.rs | 84 ++- codex-rs/core/src/connectors.rs | 488 +++++++++++++++++- codex-rs/core/src/mcp_tool_call.rs | 159 ++++-- .../src/tools/handlers/search_tool_bm25.rs | 1 + 16 files changed, 1043 insertions(+), 106 deletions(-) rename codex-rs/app-server-protocol/schema/typescript/v2/{AppDisabledReason.ts => AppToolApproval.ts} (71%) create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/AppToolsConfig.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/AppsDefaultConfig.ts diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 5a840f0bde..7a01b04b51 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -10665,30 +10665,51 @@ }, "AppConfig": { "properties": { - "disabled_reason": { + "default_tools_approval_mode": { "anyOf": [ { - "$ref": "#/definitions/v2/AppDisabledReason" + "$ref": "#/definitions/v2/AppToolApproval" }, { "type": "null" } ] }, + "default_tools_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "destructive_enabled": { + "type": [ + "boolean", + "null" + ] + }, "enabled": { "default": true, "type": "boolean" + }, + "open_world_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "tools": { + "anyOf": [ + { + "$ref": "#/definitions/v2/AppToolsConfig" + }, + { + "type": "null" + } + ] } }, "type": "object" }, - "AppDisabledReason": { - "enum": [ - "unknown", - "user" - ], - "type": "string" - }, "AppInfo": { "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", "properties": { @@ -10914,7 +10935,69 @@ ], "type": "object" }, + "AppToolApproval": { + "enum": [ + "auto", + "prompt", + "approve" + ], + "type": "string" + }, + "AppToolConfig": { + "properties": { + "approval_mode": { + "anyOf": [ + { + "$ref": "#/definitions/v2/AppToolApproval" + }, + { + "type": "null" + } + ] + }, + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "AppToolsConfig": { + "type": "object" + }, "AppsConfig": { + "properties": { + "_default": { + "anyOf": [ + { + "$ref": "#/definitions/v2/AppsDefaultConfig" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "AppsDefaultConfig": { + "properties": { + "destructive_enabled": { + "default": true, + "type": "boolean" + }, + "enabled": { + "default": true, + "type": "boolean" + }, + "open_world_enabled": { + "default": true, + "type": "boolean" + } + }, "type": "object" }, "AppsListParams": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json index 293fe7dc31..4511515d17 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -19,10 +19,65 @@ }, "AppConfig": { "properties": { - "disabled_reason": { + "default_tools_approval_mode": { "anyOf": [ { - "$ref": "#/definitions/AppDisabledReason" + "$ref": "#/definitions/AppToolApproval" + }, + { + "type": "null" + } + ] + }, + "default_tools_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "destructive_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "enabled": { + "default": true, + "type": "boolean" + }, + "open_world_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "tools": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolsConfig" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "AppToolApproval": { + "enum": [ + "auto", + "prompt", + "approve" + ], + "type": "string" + }, + "AppToolConfig": { + "properties": { + "approval_mode": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolApproval" }, { "type": "null" @@ -30,20 +85,48 @@ ] }, "enabled": { - "default": true, - "type": "boolean" + "type": [ + "boolean", + "null" + ] } }, "type": "object" }, - "AppDisabledReason": { - "enum": [ - "unknown", - "user" - ], - "type": "string" + "AppToolsConfig": { + "type": "object" }, "AppsConfig": { + "properties": { + "_default": { + "anyOf": [ + { + "$ref": "#/definitions/AppsDefaultConfig" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "AppsDefaultConfig": { + "properties": { + "destructive_enabled": { + "default": true, + "type": "boolean" + }, + "enabled": { + "default": true, + "type": "boolean" + }, + "open_world_enabled": { + "default": true, + "type": "boolean" + } + }, "type": "object" }, "AskForApproval": { diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AppDisabledReason.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts similarity index 71% rename from codex-rs/app-server-protocol/schema/typescript/v2/AppDisabledReason.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts index bc44835a76..e92cd8e28b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AppDisabledReason.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type AppDisabledReason = "unknown" | "user"; +export type AppToolApproval = "auto" | "prompt" | "approve"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AppToolsConfig.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolsConfig.ts new file mode 100644 index 0000000000..16a1c22c6d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolsConfig.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AppToolApproval } from "./AppToolApproval"; + +export type AppToolsConfig = { [key in string]?: { enabled: boolean | null, approval_mode: AppToolApproval | null, } }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AppsConfig.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AppsConfig.ts index ae3e455201..b22997de97 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AppsConfig.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AppsConfig.ts @@ -1,6 +1,8 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AppDisabledReason } from "./AppDisabledReason"; +import type { AppToolApproval } from "./AppToolApproval"; +import type { AppToolsConfig } from "./AppToolsConfig"; +import type { AppsDefaultConfig } from "./AppsDefaultConfig"; -export type AppsConfig = { [key in string]?: { enabled: boolean, disabled_reason: AppDisabledReason | null, } }; +export type AppsConfig = { _default: AppsDefaultConfig | null, } & ({ [key in string]?: { enabled: boolean, destructive_enabled: boolean | null, open_world_enabled: boolean | null, default_tools_approval_mode: AppToolApproval | null, default_tools_enabled: boolean | null, tools: AppToolsConfig | null, } }); diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AppsDefaultConfig.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AppsDefaultConfig.ts new file mode 100644 index 0000000000..e73386027e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AppsDefaultConfig.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AppsDefaultConfig = { enabled: boolean, destructive_enabled: boolean, open_world_enabled: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index db94051fa6..c2f8494785 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -7,13 +7,15 @@ export type { AccountUpdatedNotification } from "./AccountUpdatedNotification"; export type { AgentMessageDeltaNotification } from "./AgentMessageDeltaNotification"; export type { AnalyticsConfig } from "./AnalyticsConfig"; export type { AppBranding } from "./AppBranding"; -export type { AppDisabledReason } from "./AppDisabledReason"; export type { AppInfo } from "./AppInfo"; export type { AppListUpdatedNotification } from "./AppListUpdatedNotification"; export type { AppMetadata } from "./AppMetadata"; export type { AppReview } from "./AppReview"; export type { AppScreenshot } from "./AppScreenshot"; +export type { AppToolApproval } from "./AppToolApproval"; +export type { AppToolsConfig } from "./AppToolsConfig"; export type { AppsConfig } from "./AppsConfig"; +export type { AppsDefaultConfig } from "./AppsDefaultConfig"; export type { AppsListParams } from "./AppsListParams"; export type { AppsListResponse } from "./AppsListResponse"; export type { AskForApproval } from "./AskForApproval"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 2641d7c2a3..103b5f56a0 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -398,12 +398,41 @@ pub struct AnalyticsConfig { pub additional: HashMap, } +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export_to = "v2/")] +pub enum AppToolApproval { + Auto, + Prompt, + Approve, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "snake_case")] #[ts(export_to = "v2/")] -pub enum AppDisabledReason { - Unknown, - User, +pub struct AppsDefaultConfig { + #[serde(default = "default_enabled")] + pub enabled: bool, + #[serde(default = "default_enabled")] + pub destructive_enabled: bool, + #[serde(default = "default_enabled")] + pub open_world_enabled: bool, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export_to = "v2/")] +pub struct AppToolConfig { + pub enabled: Option, + pub approval_mode: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export_to = "v2/")] +pub struct AppToolsConfig { + #[serde(default, flatten)] + pub tools: HashMap, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -412,15 +441,20 @@ pub enum AppDisabledReason { pub struct AppConfig { #[serde(default = "default_enabled")] pub enabled: bool, - pub disabled_reason: Option, + pub destructive_enabled: Option, + pub open_world_enabled: Option, + pub default_tools_approval_mode: Option, + pub default_tools_enabled: Option, + pub tools: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "snake_case")] #[ts(export_to = "v2/")] pub struct AppsConfig { + #[serde(default, rename = "_default")] + pub default: Option, #[serde(default, flatten)] - #[schemars(with = "HashMap")] pub apps: HashMap, } diff --git a/codex-rs/app-server/tests/suite/v2/config_rpc.rs b/codex-rs/app-server/tests/suite/v2/config_rpc.rs index de4c51cde4..cd74710876 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -4,7 +4,7 @@ use app_test_support::test_path_buf_with_windows; use app_test_support::test_tmp_path_buf; use app_test_support::to_response; use codex_app_server_protocol::AppConfig; -use codex_app_server_protocol::AppDisabledReason; +use codex_app_server_protocol::AppToolApproval; use codex_app_server_protocol::AppsConfig; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::ConfigBatchWriteParams; @@ -156,7 +156,8 @@ async fn config_read_includes_apps() -> Result<()> { r#" [apps.app1] enabled = false -disabled_reason = "user" +destructive_enabled = false +default_tools_approval_mode = "prompt" "#, )?; let codex_home_path = codex_home.path().canonicalize()?; @@ -185,11 +186,16 @@ disabled_reason = "user" assert_eq!( config.apps, Some(AppsConfig { + default: None, apps: std::collections::HashMap::from([( "app1".to_string(), AppConfig { enabled: false, - disabled_reason: Some(AppDisabledReason::User), + destructive_enabled: Some(false), + open_world_enabled: None, + default_tools_approval_mode: Some(AppToolApproval::Prompt), + default_tools_enabled: None, + tools: None, }, )]), }) @@ -202,7 +208,16 @@ disabled_reason = "user" ); assert_eq!( origins - .get("apps.app1.disabled_reason") + .get("apps.app1.destructive_enabled") + .expect("origin") + .name, + ConfigLayerSource::User { + file: user_file.clone(), + } + ); + assert_eq!( + origins + .get("apps.app1.default_tools_approval_mode") .expect("origin") .name, ConfigLayerSource::User { diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 97ce03cadf..e73a71bb30 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -85,34 +85,111 @@ "additionalProperties": false, "description": "Config values for a single app/connector.", "properties": { - "disabled_reason": { + "default_tools_approval_mode": { "allOf": [ { - "$ref": "#/definitions/AppDisabledReason" + "$ref": "#/definitions/AppToolApproval" } ], - "description": "Reason this app was disabled." + "description": "Approval mode for tools in this app unless a tool override exists." + }, + "default_tools_enabled": { + "description": "Whether tools are enabled by default for this app.", + "type": "boolean" + }, + "destructive_enabled": { + "description": "Whether tools with `destructive_hint = true` are allowed for this app.", + "type": "boolean" }, "enabled": { "default": true, "description": "When `false`, Codex does not surface this app.", "type": "boolean" + }, + "open_world_enabled": { + "description": "Whether tools with `open_world_hint = true` are allowed for this app.", + "type": "boolean" + }, + "tools": { + "allOf": [ + { + "$ref": "#/definitions/AppToolsConfig" + } + ], + "description": "Per-tool settings for this app." } }, "type": "object" }, - "AppDisabledReason": { + "AppToolApproval": { "enum": [ - "unknown", - "user" + "auto", + "prompt", + "approve" ], "type": "string" }, + "AppToolConfig": { + "additionalProperties": false, + "description": "Per-tool settings for a single app tool.", + "properties": { + "approval_mode": { + "allOf": [ + { + "$ref": "#/definitions/AppToolApproval" + } + ], + "description": "Approval mode for this tool." + }, + "enabled": { + "description": "Whether this tool is enabled. `Some(true)` explicitly allows this tool.", + "type": "boolean" + } + }, + "type": "object" + }, + "AppToolsConfig": { + "additionalProperties": { + "$ref": "#/definitions/AppToolConfig" + }, + "description": "Tool settings for a single app.", + "type": "object" + }, "AppsConfigToml": { "additionalProperties": { "$ref": "#/definitions/AppConfig" }, "description": "App/connector settings loaded from `config.toml`.", + "properties": { + "_default": { + "allOf": [ + { + "$ref": "#/definitions/AppsDefaultConfig" + } + ], + "description": "Default settings for all apps." + } + }, + "type": "object" + }, + "AppsDefaultConfig": { + "additionalProperties": false, + "description": "Default settings that apply to all apps.", + "properties": { + "destructive_enabled": { + "description": "Whether tools with `destructive_hint = true` are allowed by default.", + "type": "boolean" + }, + "enabled": { + "default": true, + "description": "When `false`, apps are disabled unless overridden by per-app settings.", + "type": "boolean" + }, + "open_world_enabled": { + "description": "Whether tools with `open_world_hint = true` are allowed by default.", + "type": "boolean" + } + }, "type": "object" }, "AskForApproval": { diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 2d5d283d6a..fcddf4e83e 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -4834,6 +4834,7 @@ fn connector_inserted_in_messages( fn filter_codex_apps_mcp_tools( mcp_tools: &HashMap, connectors: &[connectors::AppInfo], + config: &Config, ) -> HashMap { let allowed: HashSet<&str> = connectors .iter() @@ -4849,7 +4850,7 @@ fn filter_codex_apps_mcp_tools( let Some(connector_id) = codex_apps_connector_id(tool) else { return false; }; - allowed.contains(connector_id) + allowed.contains(connector_id) && connectors::codex_app_tool_is_enabled(config, tool) }) .map(|(name, tool)| (name.clone(), tool.clone())) .collect() @@ -5023,9 +5024,9 @@ async fn built_tools( None }; - let app_tools = connectors - .as_ref() - .map(|connectors| filter_codex_apps_mcp_tools(&mcp_tools, connectors)); + let app_tools = connectors.as_ref().map(|connectors| { + filter_codex_apps_mcp_tools(&mcp_tools, connectors, &turn_context.config) + }); if let Some(connectors) = connectors.as_ref() { let skill_name_counts_lower = skills_outcome.map_or_else(HashMap::new, |outcome| { @@ -5050,7 +5051,8 @@ async fn built_tools( explicitly_enabled.as_ref(), )); - mcp_tools = selected_mcp_tools; + mcp_tools = + connectors::filter_codex_apps_tools_by_policy(selected_mcp_tools, &turn_context.config); } Ok(Arc::new(ToolRouter::from_config( @@ -6001,7 +6003,7 @@ mod tests { let config_toml_path = codex_home.join(CONFIG_TOML_FILE); std::fs::write( &config_toml_path, - "[apps.calendar]\nenabled = false\ndisabled_reason = \"user\"\n", + "[apps.calendar]\nenabled = false\ndestructive_enabled = false\n", ) .expect("write user config"); @@ -6023,10 +6025,7 @@ mod tests { .expect("calendar app config exists"); assert!(!app.enabled); - assert_eq!( - app.disabled_reason, - Some(crate::config::types::AppDisabledReason::User) - ); + assert_eq!(app.destructive_enabled, Some(false)); } #[test] diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/core/src/config/service.rs index 02a9da23fd..1033db728d 100644 --- a/codex-rs/core/src/config/service.rs +++ b/codex-rs/core/src/config/service.rs @@ -701,7 +701,7 @@ mod tests { use super::*; use anyhow::Result; use codex_app_server_protocol::AppConfig; - use codex_app_server_protocol::AppDisabledReason; + use codex_app_server_protocol::AppToolApproval; use codex_app_server_protocol::AppsConfig; use codex_app_server_protocol::AskForApproval; use codex_utils_absolute_path::AbsolutePathBuf; @@ -827,13 +827,13 @@ personality = true service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), - key_path: "apps.app1.disabled_reason".to_string(), - value: serde_json::json!("user"), + key_path: "apps.app1.default_tools_approval_mode".to_string(), + value: serde_json::json!("prompt"), merge_strategy: MergeStrategy::Replace, expected_version: None, }) .await - .expect("write apps.app1.disabled_reason succeeds"); + .expect("write apps.app1.default_tools_approval_mode succeeds"); let read = service .read(ConfigReadParams { @@ -846,11 +846,16 @@ personality = true assert_eq!( read.config.apps, Some(AppsConfig { + default: None, apps: std::collections::HashMap::from([( "app1".to_string(), AppConfig { enabled: false, - disabled_reason: Some(AppDisabledReason::User), + destructive_enabled: None, + open_world_enabled: None, + default_tools_approval_mode: Some(AppToolApproval::Prompt), + default_tools_enabled: None, + tools: None, }, )]), }) diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index ca90414c27..2e3573f770 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -425,20 +425,58 @@ impl From for MemoriesConfig { } } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, JsonSchema)] #[serde(rename_all = "snake_case")] -pub enum AppDisabledReason { - Unknown, - User, +pub enum AppToolApproval { + #[default] + Auto, + Prompt, + Approve, } -impl fmt::Display for AppDisabledReason { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - AppDisabledReason::Unknown => write!(f, "unknown"), - AppDisabledReason::User => write!(f, "user"), - } - } +/// Default settings that apply to all apps. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppsDefaultConfig { + /// When `false`, apps are disabled unless overridden by per-app settings. + #[serde(default = "default_enabled")] + pub enabled: bool, + + /// Whether tools with `destructive_hint = true` are allowed by default. + #[serde( + default = "default_enabled", + skip_serializing_if = "std::clone::Clone::clone" + )] + pub destructive_enabled: bool, + + /// Whether tools with `open_world_hint = true` are allowed by default. + #[serde( + default = "default_enabled", + skip_serializing_if = "std::clone::Clone::clone" + )] + pub open_world_enabled: bool, +} + +/// Per-tool settings for a single app tool. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppToolConfig { + /// Whether this tool is enabled. `Some(true)` explicitly allows this tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enabled: Option, + + /// Approval mode for this tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub approval_mode: Option, +} + +/// Tool settings for a single app. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppToolsConfig { + /// Per-tool overrides keyed by tool name (for example `repos/list`). + #[serde(default, flatten)] + pub tools: HashMap, } /// Config values for a single app/connector. @@ -449,15 +487,35 @@ pub struct AppConfig { #[serde(default = "default_enabled")] pub enabled: bool, - /// Reason this app was disabled. + /// Whether tools with `destructive_hint = true` are allowed for this app. #[serde(default, skip_serializing_if = "Option::is_none")] - pub disabled_reason: Option, + pub destructive_enabled: Option, + + /// Whether tools with `open_world_hint = true` are allowed for this app. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub open_world_enabled: Option, + + /// Approval mode for tools in this app unless a tool override exists. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_tools_approval_mode: Option, + + /// Whether tools are enabled by default for this app. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_tools_enabled: Option, + + /// Per-tool settings for this app. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tools: Option, } /// App/connector settings loaded from `config.toml`. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct AppsConfigToml { + /// Default settings for all apps. + #[serde(default, rename = "_default", skip_serializing_if = "Option::is_none")] + pub default: Option, + /// Per-app settings keyed by app ID (for example `[apps.google_drive]`). #[serde(default, flatten)] pub apps: HashMap, diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index a34477850d..33b003770e 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -11,6 +11,7 @@ pub use codex_app_server_protocol::AppBranding; pub use codex_app_server_protocol::AppInfo; pub use codex_app_server_protocol::AppMetadata; use codex_protocol::protocol::SandboxPolicy; +use rmcp::model::ToolAnnotations; use serde::Deserialize; use tracing::warn; @@ -18,6 +19,7 @@ use crate::AuthManager; use crate::CodexAuth; use crate::SandboxState; use crate::config::Config; +use crate::config::types::AppToolApproval; use crate::config::types::AppsConfigToml; use crate::default_client::is_first_party_chat_originator; use crate::default_client::originator; @@ -32,6 +34,21 @@ use crate::token_data::TokenData; pub const CONNECTORS_CACHE_TTL: Duration = Duration::from_secs(3600); const CONNECTORS_READY_TIMEOUT_ON_EMPTY_TOOLS: Duration = Duration::from_secs(30); +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct AppToolPolicy { + pub enabled: bool, + pub approval: AppToolApproval, +} + +impl Default for AppToolPolicy { + fn default() -> Self { + Self { + enabled: true, + approval: AppToolApproval::Auto, + } + } +} + #[derive(Clone, PartialEq, Eq)] struct AccessibleConnectorsCacheKey { chatgpt_base_url: String, @@ -337,15 +354,58 @@ pub fn merge_connectors( } pub fn with_app_enabled_state(mut connectors: Vec, config: &Config) -> Vec { - let apps = read_apps_config(config).map(|apps_config| apps_config.apps); - for connector in &mut connectors { - if let Some(app) = apps.as_ref().and_then(|apps| apps.get(&connector.id)) { - connector.is_enabled = app.enabled; + let apps_config = read_apps_config(config); + if let Some(apps_config) = apps_config.as_ref() { + for connector in &mut connectors { + connector.is_enabled = app_is_enabled(apps_config, Some(connector.id.as_str())); } } connectors } +pub(crate) fn app_tool_policy( + config: &Config, + connector_id: Option<&str>, + tool_name: &str, + tool_title: Option<&str>, + annotations: Option<&ToolAnnotations>, +) -> AppToolPolicy { + let apps_config = read_apps_config(config); + app_tool_policy_from_apps_config( + apps_config.as_ref(), + connector_id, + tool_name, + tool_title, + annotations, + ) +} + +pub(crate) fn codex_app_tool_is_enabled( + config: &Config, + tool_info: &crate::mcp_connection_manager::ToolInfo, +) -> bool { + if tool_info.server_name != CODEX_APPS_MCP_SERVER_NAME { + return true; + } + + app_tool_policy( + config, + tool_info.connector_id.as_deref(), + &tool_info.tool_name, + tool_info.tool.title.as_deref(), + tool_info.tool.annotations.as_ref(), + ) + .enabled +} + +pub(crate) fn filter_codex_apps_tools_by_policy( + mut mcp_tools: HashMap, + config: &Config, +) -> HashMap { + mcp_tools.retain(|_, tool_info| codex_app_tool_is_enabled(config, tool_info)); + mcp_tools +} + const DISALLOWED_CONNECTOR_IDS: &[&str] = &[ "asdk_app_6938a94a61d881918ef32cb999ff937c", "connector_2b0a9009c9c64bf9933a3dae3f2b1254", @@ -394,6 +454,85 @@ fn read_apps_config(config: &Config) -> Option { AppsConfigToml::deserialize(apps_config).ok() } +fn app_is_enabled(apps_config: &AppsConfigToml, connector_id: Option<&str>) -> bool { + let default_enabled = apps_config + .default + .as_ref() + .map(|defaults| defaults.enabled) + .unwrap_or(true); + + connector_id + .and_then(|connector_id| apps_config.apps.get(connector_id)) + .map(|app| app.enabled) + .unwrap_or(default_enabled) +} + +fn app_tool_policy_from_apps_config( + apps_config: Option<&AppsConfigToml>, + connector_id: Option<&str>, + tool_name: &str, + tool_title: Option<&str>, + annotations: Option<&ToolAnnotations>, +) -> AppToolPolicy { + let Some(apps_config) = apps_config else { + return AppToolPolicy::default(); + }; + + let app = connector_id.and_then(|connector_id| apps_config.apps.get(connector_id)); + let tools = app.and_then(|app| app.tools.as_ref()); + let tool_config = tools.and_then(|tools| { + tools + .tools + .get(tool_name) + .or_else(|| tool_title.and_then(|title| tools.tools.get(title))) + }); + let approval = tool_config + .and_then(|tool| tool.approval_mode) + .or_else(|| app.and_then(|app| app.default_tools_approval_mode)) + .unwrap_or(AppToolApproval::Auto); + + if !app_is_enabled(apps_config, connector_id) { + return AppToolPolicy { + enabled: false, + approval, + }; + } + + if let Some(enabled) = tool_config.and_then(|tool| tool.enabled) { + return AppToolPolicy { enabled, approval }; + } + + if let Some(enabled) = app.and_then(|app| app.default_tools_enabled) { + return AppToolPolicy { enabled, approval }; + } + + let app_defaults = apps_config.default.as_ref(); + let destructive_enabled = app + .and_then(|app| app.destructive_enabled) + .unwrap_or_else(|| { + app_defaults + .map(|defaults| defaults.destructive_enabled) + .unwrap_or(true) + }); + let open_world_enabled = app + .and_then(|app| app.open_world_enabled) + .unwrap_or_else(|| { + app_defaults + .map(|defaults| defaults.open_world_enabled) + .unwrap_or(true) + }); + let destructive_hint = annotations + .and_then(|annotations| annotations.destructive_hint) + .unwrap_or(false); + let open_world_hint = annotations + .and_then(|annotations| annotations.open_world_hint) + .unwrap_or(false); + let enabled = + (destructive_enabled || !destructive_hint) && (open_world_enabled || !open_world_hint); + + AppToolPolicy { enabled, approval } +} + fn collect_accessible_connectors(tools: I) -> Vec where I: IntoIterator)>, @@ -472,8 +611,25 @@ fn format_connector_label(name: &str, _id: &str) -> String { #[cfg(test)] mod tests { use super::*; + use crate::config::types::AppConfig; + use crate::config::types::AppToolConfig; + use crate::config::types::AppToolsConfig; + use crate::config::types::AppsDefaultConfig; use pretty_assertions::assert_eq; + fn annotations( + destructive_hint: Option, + open_world_hint: Option, + ) -> ToolAnnotations { + ToolAnnotations { + destructive_hint, + idempotent_hint: None, + open_world_hint, + read_only_hint: None, + title: None, + } + } + fn app(id: &str) -> AppInfo { AppInfo { id: id.to_string(), @@ -491,6 +647,328 @@ mod tests { } } + #[test] + fn app_tool_policy_uses_global_defaults_for_destructive_hints() { + let apps_config = AppsConfigToml { + default: Some(AppsDefaultConfig { + enabled: true, + destructive_enabled: false, + open_world_enabled: true, + }), + apps: HashMap::new(), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "events/create", + None, + Some(&annotations(Some(true), None)), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: false, + approval: AppToolApproval::Auto, + } + ); + } + + #[test] + fn app_is_enabled_uses_default_for_unconfigured_apps() { + let apps_config = AppsConfigToml { + default: Some(AppsDefaultConfig { + enabled: false, + destructive_enabled: true, + open_world_enabled: true, + }), + apps: HashMap::new(), + }; + + assert!(!app_is_enabled(&apps_config, Some("calendar"))); + assert!(!app_is_enabled(&apps_config, None)); + } + + #[test] + fn app_is_enabled_prefers_per_app_override_over_default() { + let apps_config = AppsConfigToml { + default: Some(AppsDefaultConfig { + enabled: false, + destructive_enabled: true, + open_world_enabled: true, + }), + apps: HashMap::from([( + "calendar".to_string(), + AppConfig { + enabled: true, + destructive_enabled: None, + open_world_enabled: None, + default_tools_approval_mode: None, + default_tools_enabled: None, + tools: None, + }, + )]), + }; + + assert!(app_is_enabled(&apps_config, Some("calendar"))); + assert!(!app_is_enabled(&apps_config, Some("drive"))); + } + + #[test] + fn app_tool_policy_honors_default_app_enabled_false() { + let apps_config = AppsConfigToml { + default: Some(AppsDefaultConfig { + enabled: false, + destructive_enabled: true, + open_world_enabled: true, + }), + apps: HashMap::new(), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "events/list", + None, + Some(&annotations(None, None)), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: false, + approval: AppToolApproval::Auto, + } + ); + } + + #[test] + fn app_tool_policy_allows_per_app_enable_when_default_is_disabled() { + let apps_config = AppsConfigToml { + default: Some(AppsDefaultConfig { + enabled: false, + destructive_enabled: true, + open_world_enabled: true, + }), + apps: HashMap::from([( + "calendar".to_string(), + AppConfig { + enabled: true, + destructive_enabled: None, + open_world_enabled: None, + default_tools_approval_mode: None, + default_tools_enabled: None, + tools: None, + }, + )]), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "events/list", + None, + Some(&annotations(None, None)), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: true, + approval: AppToolApproval::Auto, + } + ); + } + + #[test] + fn app_tool_policy_per_tool_enabled_true_overrides_app_level_disable_flags() { + let apps_config = AppsConfigToml { + default: None, + apps: HashMap::from([( + "calendar".to_string(), + AppConfig { + enabled: true, + destructive_enabled: Some(false), + open_world_enabled: Some(false), + default_tools_approval_mode: None, + default_tools_enabled: None, + tools: Some(AppToolsConfig { + tools: HashMap::from([( + "events/create".to_string(), + AppToolConfig { + enabled: Some(true), + approval_mode: None, + }, + )]), + }), + }, + )]), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "events/create", + None, + Some(&annotations(Some(true), Some(true))), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: true, + approval: AppToolApproval::Auto, + } + ); + } + + #[test] + fn app_tool_policy_default_tools_enabled_true_overrides_app_level_tool_hints() { + let apps_config = AppsConfigToml { + default: None, + apps: HashMap::from([( + "calendar".to_string(), + AppConfig { + enabled: true, + destructive_enabled: Some(false), + open_world_enabled: Some(false), + default_tools_approval_mode: None, + default_tools_enabled: Some(true), + tools: None, + }, + )]), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "events/create", + None, + Some(&annotations(Some(true), Some(true))), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: true, + approval: AppToolApproval::Auto, + } + ); + } + + #[test] + fn app_tool_policy_default_tools_enabled_false_overrides_app_level_tool_hints() { + let apps_config = AppsConfigToml { + default: None, + apps: HashMap::from([( + "calendar".to_string(), + AppConfig { + enabled: true, + destructive_enabled: Some(true), + open_world_enabled: Some(true), + default_tools_approval_mode: Some(AppToolApproval::Approve), + default_tools_enabled: Some(false), + tools: None, + }, + )]), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "events/list", + None, + Some(&annotations(None, None)), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: false, + approval: AppToolApproval::Approve, + } + ); + } + + #[test] + fn app_tool_policy_uses_default_tools_approval_mode() { + let apps_config = AppsConfigToml { + default: None, + apps: HashMap::from([( + "calendar".to_string(), + AppConfig { + enabled: true, + destructive_enabled: None, + open_world_enabled: None, + default_tools_approval_mode: Some(AppToolApproval::Prompt), + default_tools_enabled: None, + tools: Some(AppToolsConfig { + tools: HashMap::new(), + }), + }, + )]), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "events/list", + None, + Some(&annotations(None, None)), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: true, + approval: AppToolApproval::Prompt, + } + ); + } + + #[test] + fn app_tool_policy_matches_prefix_stripped_tool_name_for_tool_config() { + let apps_config = AppsConfigToml { + default: None, + apps: HashMap::from([( + "calendar".to_string(), + AppConfig { + enabled: true, + destructive_enabled: Some(false), + open_world_enabled: Some(false), + default_tools_approval_mode: Some(AppToolApproval::Auto), + default_tools_enabled: Some(false), + tools: Some(AppToolsConfig { + tools: HashMap::from([( + "events/create".to_string(), + AppToolConfig { + enabled: Some(true), + approval_mode: Some(AppToolApproval::Approve), + }, + )]), + }), + }, + )]), + }; + + let policy = app_tool_policy_from_apps_config( + Some(&apps_config), + Some("calendar"), + "calendar_events/create", + Some("events/create"), + Some(&annotations(Some(true), Some(true))), + ); + + assert_eq!( + policy, + AppToolPolicy { + enabled: true, + approval: AppToolApproval::Approve, + } + ); + } + #[test] fn filter_disallowed_connectors_allows_non_disallowed_connectors() { let filtered = filter_disallowed_connectors(vec![app("asdk_app_hidden"), app("alpha")]); @@ -528,7 +1006,7 @@ mod tests { ); assert_eq!( filtered, - vec![app("asdk_app_6938a94a61d881918ef32cb999ff937c"),] + vec![app("asdk_app_6938a94a61d881918ef32cb999ff937c")] ); } } diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 5f7734118c..00327386b5 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -7,6 +7,8 @@ use crate::analytics_client::AppInvocation; use crate::analytics_client::build_track_events_context; use crate::codex::Session; use crate::codex::TurnContext; +use crate::config::types::AppToolApproval; +use crate::connectors; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::protocol::EventMsg; use crate::protocol::McpInvocation; @@ -64,9 +66,51 @@ pub(crate) async fn handle_mcp_tool_call( arguments: arguments_value.clone(), }; - if let Some(decision) = - maybe_request_mcp_tool_approval(sess.as_ref(), turn_context, &call_id, &server, &tool_name) - .await + let metadata = lookup_mcp_tool_metadata(sess.as_ref(), &server, &tool_name).await; + let app_tool_policy = if server == CODEX_APPS_MCP_SERVER_NAME { + connectors::app_tool_policy( + &turn_context.config, + metadata + .as_ref() + .and_then(|metadata| metadata.connector_id.as_deref()), + &tool_name, + metadata + .as_ref() + .and_then(|metadata| metadata.tool_title.as_deref()), + metadata + .as_ref() + .and_then(|metadata| metadata.annotations.as_ref()), + ) + } else { + connectors::AppToolPolicy::default() + }; + + if server == CODEX_APPS_MCP_SERVER_NAME && !app_tool_policy.enabled { + let result = notify_mcp_tool_call_skip( + sess.as_ref(), + turn_context, + &call_id, + invocation, + "MCP tool call blocked by app configuration".to_string(), + ) + .await; + let status = if result.is_ok() { "ok" } else { "error" }; + turn_context + .otel_manager + .counter("codex.mcp.call", 1, &[("status", status)]); + return ResponseInputItem::McpToolCallOutput { call_id, result }; + } + + if let Some(decision) = maybe_request_mcp_tool_approval( + sess.as_ref(), + turn_context, + &call_id, + &server, + &tool_name, + metadata.as_ref(), + app_tool_policy.approval, + ) + .await { let result = match decision { McpToolApprovalDecision::Accept | McpToolApprovalDecision::AcceptAndRemember => { @@ -267,7 +311,7 @@ enum McpToolApprovalDecision { } struct McpToolApprovalMetadata { - annotations: ToolAnnotations, + annotations: Option, connector_id: Option, connector_name: Option, tool_title: Option, @@ -292,21 +336,39 @@ async fn maybe_request_mcp_tool_approval( call_id: &str, server: &str, tool_name: &str, + metadata: Option<&McpToolApprovalMetadata>, + approval_mode: AppToolApproval, ) -> Option { - if is_full_access_mode(turn_context) { + if approval_mode == AppToolApproval::Approve { return None; } + let annotations = metadata.and_then(|metadata| metadata.annotations.as_ref()); + if approval_mode == AppToolApproval::Auto { + if is_full_access_mode(turn_context) { + return None; + } + if !annotations.is_some_and(requires_mcp_tool_approval) { + return None; + } + } - let metadata = lookup_mcp_tool_metadata(sess, server, tool_name).await?; - if !requires_mcp_tool_approval(&metadata.annotations) { - return None; - } - let approval_key = McpToolApprovalKey { - server: server.to_string(), - connector_id: metadata.connector_id.clone(), - tool_name: tool_name.to_string(), + let approval_key = if approval_mode == AppToolApproval::Auto { + let connector_id = metadata.and_then(|metadata| metadata.connector_id.clone()); + if server == CODEX_APPS_MCP_SERVER_NAME && connector_id.is_none() { + None + } else { + Some(McpToolApprovalKey { + server: server.to_string(), + connector_id, + tool_name: tool_name.to_string(), + }) + } + } else { + None }; - if mcp_tool_approval_is_remembered(sess, &approval_key).await { + if let Some(key) = approval_key.as_ref() + && mcp_tool_approval_is_remembered(sess, key).await + { return Some(McpToolApprovalDecision::Accept); } @@ -315,10 +377,10 @@ async fn maybe_request_mcp_tool_approval( question_id.clone(), server, tool_name, - metadata.tool_title.as_deref(), - metadata.connector_name.as_deref(), - &metadata.annotations, - true, + metadata.and_then(|metadata| metadata.tool_title.as_deref()), + metadata.and_then(|metadata| metadata.connector_name.as_deref()), + annotations, + approval_key.is_some(), ); let args = RequestUserInputArgs { questions: vec![question], @@ -326,9 +388,14 @@ async fn maybe_request_mcp_tool_approval( let response = sess .request_user_input(turn_context, call_id.to_string(), args) .await; - let decision = parse_mcp_tool_approval_response(response, &question_id); - if matches!(decision, McpToolApprovalDecision::AcceptAndRemember) { - remember_mcp_tool_approval(sess, approval_key).await; + let decision = normalize_approval_decision_for_mode( + parse_mcp_tool_approval_response(response, &question_id), + approval_mode, + ); + if matches!(decision, McpToolApprovalDecision::AcceptAndRemember) + && let Some(key) = approval_key + { + remember_mcp_tool_approval(sess, key).await; } Some(decision) } @@ -356,15 +423,12 @@ async fn lookup_mcp_tool_metadata( tools.into_values().find_map(|tool_info| { if tool_info.server_name == server && tool_info.tool_name == tool_name { - tool_info - .tool - .annotations - .map(|annotations| McpToolApprovalMetadata { - annotations, - connector_id: tool_info.connector_id, - connector_name: tool_info.connector_name, - tool_title: tool_info.tool.title, - }) + Some(McpToolApprovalMetadata { + annotations: tool_info.tool.annotations, + connector_id: tool_info.connector_id, + connector_name: tool_info.connector_name, + tool_title: tool_info.tool.title, + }) } else { None } @@ -402,11 +466,12 @@ fn build_mcp_tool_approval_question( tool_name: &str, tool_title: Option<&str>, connector_name: Option<&str>, - annotations: &ToolAnnotations, + annotations: Option<&ToolAnnotations>, allow_remember_option: bool, ) -> RequestUserInputQuestion { - let destructive = annotations.destructive_hint == Some(true); - let open_world = annotations.open_world_hint == Some(true); + let destructive = + annotations.and_then(|annotations| annotations.destructive_hint) == Some(true); + let open_world = annotations.and_then(|annotations| annotations.open_world_hint) == Some(true); let reason = match (destructive, open_world) { (true, true) => "may modify data and access external systems", (true, false) => "may modify or delete data", @@ -493,6 +558,19 @@ fn parse_mcp_tool_approval_response( } } +fn normalize_approval_decision_for_mode( + decision: McpToolApprovalDecision, + approval_mode: AppToolApproval, +) -> McpToolApprovalDecision { + if approval_mode == AppToolApproval::Prompt + && decision == McpToolApprovalDecision::AcceptAndRemember + { + McpToolApprovalDecision::Accept + } else { + decision + } +} + async fn mcp_tool_approval_is_remembered(sess: &Session, key: &McpToolApprovalKey) -> bool { let store = sess.services.tool_approvals.lock().await; matches!(store.get(key), Some(ReviewDecision::ApprovedForSession)) @@ -568,6 +646,17 @@ mod tests { assert_eq!(requires_mcp_tool_approval(&annotations), false); } + #[test] + fn prompt_mode_does_not_allow_session_remember() { + assert_eq!( + normalize_approval_decision_for_mode( + McpToolApprovalDecision::AcceptAndRemember, + AppToolApproval::Prompt, + ), + McpToolApprovalDecision::Accept + ); + } + #[test] fn custom_mcp_tool_question_mentions_server_name() { let question = build_mcp_tool_approval_question( @@ -576,7 +665,7 @@ mod tests { "run_action", Some("Run Action"), None, - &annotations(Some(false), Some(true), None), + Some(&annotations(Some(false), Some(true), None)), true, ); @@ -603,7 +692,7 @@ mod tests { "run_action", Some("Run Action"), None, - &annotations(Some(false), Some(true), None), + Some(&annotations(Some(false), Some(true), None)), true, ); diff --git a/codex-rs/core/src/tools/handlers/search_tool_bm25.rs b/codex-rs/core/src/tools/handlers/search_tool_bm25.rs index c5e267cb49..a4878b73a6 100644 --- a/codex-rs/core/src/tools/handlers/search_tool_bm25.rs +++ b/codex-rs/core/src/tools/handlers/search_tool_bm25.rs @@ -124,6 +124,7 @@ impl ToolHandler for SearchToolBm25Handler { &turn.config, ); let mcp_tools = filter_codex_apps_mcp_tools(mcp_tools, &connectors); + let mcp_tools = connectors::filter_codex_apps_tools_by_policy(mcp_tools, &turn.config); let mut entries: Vec = mcp_tools .into_iter() From d3cf8bd0fa6880b9a14ad8f9afb5a176adbc7291 Mon Sep 17 00:00:00 2001 From: colby-oai <228809017+colby-oai@users.noreply.github.com> Date: Fri, 20 Feb 2026 15:12:16 -0500 Subject: [PATCH 025/385] fix(core): require approval for destructive MCP tool calls (#12353) Summary - ensure destructive tool annotations short-circuit to require approval - simplify approval logic to only require read/write + open-world when destructive is false - update the unit test to cover the new destructive behavior Testing - Not run (not requested) --- codex-rs/core/src/mcp_tool_call.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 00327386b5..f194ee79a6 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -582,8 +582,11 @@ async fn remember_mcp_tool_approval(sess: &Session, key: McpToolApprovalKey) { } fn requires_mcp_tool_approval(annotations: &ToolAnnotations) -> bool { - annotations.read_only_hint == Some(false) - && (annotations.destructive_hint == Some(true) || annotations.open_world_hint == Some(true)) + if annotations.destructive_hint == Some(true) { + return true; + } + + annotations.read_only_hint == Some(false) && annotations.open_world_hint == Some(true) } async fn notify_mcp_tool_call_skip( @@ -641,9 +644,9 @@ mod tests { } #[test] - fn approval_not_required_when_read_only_true() { + fn approval_required_when_destructive_even_if_read_only_true() { let annotations = annotations(Some(true), Some(true), Some(true)); - assert_eq!(requires_mcp_tool_approval(&annotations), false); + assert_eq!(requires_mcp_tool_approval(&annotations), true); } #[test] From 6b1091fc92b7bac7cd25bc4772081eff7ad8f9ac Mon Sep 17 00:00:00 2001 From: Max Johnson <162359438+maxj-oai@users.noreply.github.com> Date: Fri, 20 Feb 2026 12:35:16 -0800 Subject: [PATCH 026/385] app-server: harden disconnect cleanup paths (#12218) Hardens codex-rs/app-server connection lifecycle and outbound routing for websocket clients. Fixes some FUD I was having - Added per-connection disconnect signaling (CancellationToken) for websocket transports. - Split websocket handling into independent inbound/outbound tasks coordinated by cancellation. - Changed outbound routing so websocket connections use non-blocking try_send; slow/full websocket writers are disconnected instead of stalling broadcast delivery. - Kept stdio behavior blocking-on-send (no forced disconnect) so local stdio clients are not dropped when queues are temporarily full. - Simplified outbound router flow by removing deferred pending_closed_connections handling. - Added guards to drop incoming response/notification/error messages from unknown connections. - Fixed listener teardown race in thread listener tasks using a listener_generation check so stale tasks do not clear newer listeners. Fixes https://linear.app/openai/issue/CODEX-4966/multiclient-handle-slow-notification-consumers ## Tests Added/updated transport tests covering: - broadcast does not block on a slow/full websocket connection - stdio connection waits instead of disconnecting on full queue I (maxj) have tested manually and will retest before landing --- codex-rs/Cargo.lock | 1 + codex-rs/app-server/Cargo.toml | 1 + .../app-server/src/codex_message_processor.rs | 7 +- codex-rs/app-server/src/lib.rs | 100 ++--- codex-rs/app-server/src/thread_state.rs | 6 +- codex-rs/app-server/src/transport.rs | 344 ++++++++++++++++-- 6 files changed, 372 insertions(+), 87 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index ccdfddb3ac..7818b253cf 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1327,6 +1327,7 @@ dependencies = [ "time", "tokio", "tokio-tungstenite", + "tokio-util", "toml 0.9.11+spec-1.1.0", "tracing", "tracing-subscriber", diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 302a65d2f6..7b90affe69 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -48,6 +48,7 @@ tokio = { workspace = true, features = [ "rt-multi-thread", "signal", ] } +tokio-util = { workspace = true } tokio-tungstenite = { workspace = true } tracing = { workspace = true, features = ["log"] } tracing-subscriber = { workspace = true, features = ["env-filter", "fmt", "json"] } diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 24c89edaf3..29d8acdbc1 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -5811,7 +5811,7 @@ impl CodexMessageProcessor { api_version: ApiVersion, ) { let (cancel_tx, mut cancel_rx) = oneshot::channel(); - let mut listener_command_rx = { + let (mut listener_command_rx, listener_generation) = { let mut thread_state = thread_state.lock().await; if thread_state.listener_matches(&conversation) { return; @@ -5927,6 +5927,11 @@ impl CodexMessageProcessor { } } } + + let mut thread_state = thread_state.lock().await; + if thread_state.listener_generation == listener_generation { + thread_state.clear_listener(); + } }); } async fn git_diff_to_origin(&self, request_id: ConnectionRequestId, cwd: PathBuf) { diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 6ff802c2a9..1bdbf97a13 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -10,7 +10,6 @@ use codex_core::config_loader::LoaderOverrides; use codex_utils_cli::CliConfigOverrides; use std::collections::HashMap; use std::collections::HashSet; -use std::collections::VecDeque; use std::io::ErrorKind; use std::io::Result as IoResult; use std::path::PathBuf; @@ -42,6 +41,7 @@ use codex_core::config_loader::TextRange as CoreTextRange; use codex_feedback::CodexFeedback; use tokio::sync::mpsc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use toml::Value as TomlValue; use tracing::error; use tracing::info; @@ -92,6 +92,7 @@ enum OutboundControlEvent { Opened { connection_id: ConnectionId, writer: mpsc::Sender, + disconnect_sender: Option, initialized: Arc, opted_out_notification_methods: Arc>>, }, @@ -403,61 +404,43 @@ pub async fn run_main_with_transport( } } - let transport_event_tx_for_outbound = transport_event_tx.clone(); let outbound_handle = tokio::spawn(async move { let mut outbound_connections = HashMap::::new(); - let mut pending_closed_connections = VecDeque::::new(); loop { tokio::select! { - biased; - event = outbound_control_rx.recv() => { - let Some(event) = event else { - break; - }; - match event { - OutboundControlEvent::Opened { - connection_id, - writer, - initialized, - opted_out_notification_methods, - } => { - outbound_connections.insert( + biased; + event = outbound_control_rx.recv() => { + let Some(event) = event else { + break; + }; + match event { + OutboundControlEvent::Opened { connection_id, - OutboundConnectionState::new( - writer, - initialized, - opted_out_notification_methods, - ), - ); - } - OutboundControlEvent::Closed { connection_id } => { - outbound_connections.remove(&connection_id); + writer, + disconnect_sender, + initialized, + opted_out_notification_methods, + } => { + outbound_connections.insert( + connection_id, + OutboundConnectionState::new( + writer, + initialized, + opted_out_notification_methods, + disconnect_sender, + ), + ); + } + OutboundControlEvent::Closed { connection_id } => { + outbound_connections.remove(&connection_id); + } } } - } - envelope = outgoing_rx.recv() => { + envelope = outgoing_rx.recv() => { let Some(envelope) = envelope else { break; }; - let disconnected_connections = - route_outgoing_envelope(&mut outbound_connections, envelope).await; - pending_closed_connections.extend(disconnected_connections); - } - } - - while let Some(connection_id) = pending_closed_connections.front().copied() { - match transport_event_tx_for_outbound - .try_send(TransportEvent::ConnectionClosed { connection_id }) - { - Ok(()) => { - pending_closed_connections.pop_front(); - } - Err(mpsc::error::TrySendError::Full(_)) => { - break; - } - Err(mpsc::error::TrySendError::Closed(_)) => { - return; - } + route_outgoing_envelope(&mut outbound_connections, envelope).await; } } } @@ -491,7 +474,11 @@ pub async fn run_main_with_transport( break; }; match event { - TransportEvent::ConnectionOpened { connection_id, writer } => { + TransportEvent::ConnectionOpened { + connection_id, + writer, + disconnect_sender, + } => { let outbound_initialized = Arc::new(AtomicBool::new(false)); let outbound_opted_out_notification_methods = Arc::new(RwLock::new(HashSet::new())); @@ -499,6 +486,7 @@ pub async fn run_main_with_transport( .send(OutboundControlEvent::Opened { connection_id, writer, + disconnect_sender, initialized: Arc::clone(&outbound_initialized), opted_out_notification_methods: Arc::clone( &outbound_opted_out_notification_methods, @@ -518,6 +506,9 @@ pub async fn run_main_with_transport( ); } TransportEvent::ConnectionClosed { connection_id } => { + if connections.remove(&connection_id).is_none() { + continue; + } if outbound_control_tx .send(OutboundControlEvent::Closed { connection_id }) .await @@ -526,7 +517,6 @@ pub async fn run_main_with_transport( break; } processor.connection_closed(connection_id).await; - connections.remove(&connection_id); if shutdown_when_no_connections && connections.is_empty() { break; } @@ -535,7 +525,7 @@ pub async fn run_main_with_transport( match message { JSONRPCMessage::Request(request) => { let Some(connection_state) = connections.get_mut(&connection_id) else { - warn!("dropping request from unknown connection: {:?}", connection_id); + warn!("dropping request from unknown connection: {connection_id:?}"); continue; }; let was_initialized = connection_state.session.initialized; @@ -565,12 +555,24 @@ pub async fn run_main_with_transport( } } JSONRPCMessage::Response(response) => { + if !connections.contains_key(&connection_id) { + warn!("dropping response from unknown connection: {connection_id:?}"); + continue; + } processor.process_response(response).await; } JSONRPCMessage::Notification(notification) => { + if !connections.contains_key(&connection_id) { + warn!("dropping notification from unknown connection: {connection_id:?}"); + continue; + } processor.process_notification(notification).await; } JSONRPCMessage::Error(err) => { + if !connections.contains_key(&connection_id) { + warn!("dropping error from unknown connection: {connection_id:?}"); + continue; + } processor.process_error(err).await; } } diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index 264c9a39d6..a9d35e0b7c 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -47,6 +47,7 @@ pub(crate) struct ThreadState { pub(crate) turn_summary: TurnSummary, pub(crate) cancel_tx: Option>, pub(crate) experimental_raw_events: bool, + pub(crate) listener_generation: u64, listener_command_tx: Option>, current_turn_history: ThreadHistoryBuilder, listener_thread: Option>, @@ -65,14 +66,15 @@ impl ThreadState { &mut self, cancel_tx: oneshot::Sender<()>, conversation: &Arc, - ) -> mpsc::UnboundedReceiver { + ) -> (mpsc::UnboundedReceiver, u64) { if let Some(previous) = self.cancel_tx.replace(cancel_tx) { let _ = previous.send(()); } + self.listener_generation = self.listener_generation.wrapping_add(1); let (listener_command_tx, listener_command_rx) = mpsc::unbounded_channel(); self.listener_command_tx = Some(listener_command_tx); self.listener_thread = Some(Arc::downgrade(conversation)); - listener_command_rx + (listener_command_rx, self.listener_generation) } pub(crate) fn clear_listener(&mut self) { diff --git a/codex-rs/app-server/src/transport.rs b/codex-rs/app-server/src/transport.rs index 558d786137..80768620bb 100644 --- a/codex-rs/app-server/src/transport.rs +++ b/codex-rs/app-server/src/transport.rs @@ -32,6 +32,7 @@ use tokio::sync::mpsc; use tokio::task::JoinHandle; use tokio_tungstenite::accept_async; use tokio_tungstenite::tungstenite::Message as WebSocketMessage; +use tokio_util::sync::CancellationToken; use tracing::debug; use tracing::error; use tracing::info; @@ -135,6 +136,7 @@ pub(crate) enum TransportEvent { ConnectionOpened { connection_id: ConnectionId, writer: mpsc::Sender, + disconnect_sender: Option, }, ConnectionClosed { connection_id: ConnectionId, @@ -168,6 +170,7 @@ pub(crate) struct OutboundConnectionState { pub(crate) initialized: Arc, pub(crate) opted_out_notification_methods: Arc>>, pub(crate) writer: mpsc::Sender, + disconnect_sender: Option, } impl OutboundConnectionState { @@ -175,11 +178,23 @@ impl OutboundConnectionState { writer: mpsc::Sender, initialized: Arc, opted_out_notification_methods: Arc>>, + disconnect_sender: Option, ) -> Self { Self { initialized, opted_out_notification_methods, writer, + disconnect_sender, + } + } + + fn can_disconnect(&self) -> bool { + self.disconnect_sender.is_some() + } + + fn request_disconnect(&self) { + if let Some(disconnect_sender) = &self.disconnect_sender { + disconnect_sender.cancel(); } } } @@ -195,6 +210,7 @@ pub(crate) async fn start_stdio_connection( .send(TransportEvent::ConnectionOpened { connection_id, writer: writer_tx, + disconnect_sender: None, }) .await .map_err(|_| std::io::Error::new(ErrorKind::BrokenPipe, "processor unavailable"))?; @@ -299,12 +315,14 @@ async fn run_websocket_connection( } }; - let (writer_tx, mut writer_rx) = mpsc::channel::(CHANNEL_CAPACITY); + let (writer_tx, writer_rx) = mpsc::channel::(CHANNEL_CAPACITY); let writer_tx_for_reader = writer_tx.clone(); + let disconnect_token = CancellationToken::new(); if transport_event_tx .send(TransportEvent::ConnectionOpened { connection_id, writer: writer_tx, + disconnect_sender: Some(disconnect_token.clone()), }) .await .is_err() @@ -312,9 +330,62 @@ async fn run_websocket_connection( return; } - let (mut websocket_writer, mut websocket_reader) = websocket_stream.split(); + let (websocket_writer, websocket_reader) = websocket_stream.split(); + let (writer_control_tx, writer_control_rx) = + mpsc::channel::(CHANNEL_CAPACITY); + let mut outbound_task = tokio::spawn(run_websocket_outbound_loop( + websocket_writer, + writer_rx, + writer_control_rx, + disconnect_token.clone(), + )); + let mut inbound_task = tokio::spawn(run_websocket_inbound_loop( + websocket_reader, + transport_event_tx.clone(), + writer_tx_for_reader, + writer_control_tx, + connection_id, + disconnect_token.clone(), + )); + + tokio::select! { + _ = &mut outbound_task => { + disconnect_token.cancel(); + inbound_task.abort(); + } + _ = &mut inbound_task => { + disconnect_token.cancel(); + outbound_task.abort(); + } + } + + let _ = transport_event_tx + .send(TransportEvent::ConnectionClosed { connection_id }) + .await; +} + +async fn run_websocket_outbound_loop( + mut websocket_writer: futures::stream::SplitSink< + tokio_tungstenite::WebSocketStream, + WebSocketMessage, + >, + mut writer_rx: mpsc::Receiver, + mut writer_control_rx: mpsc::Receiver, + disconnect_token: CancellationToken, +) { loop { tokio::select! { + _ = disconnect_token.cancelled() => { + break; + } + message = writer_control_rx.recv() => { + let Some(message) = message else { + break; + }; + if websocket_writer.send(message).await.is_err() { + break; + } + } outgoing_message = writer_rx.recv() => { let Some(outgoing_message) = outgoing_message else { break; @@ -326,6 +397,25 @@ async fn run_websocket_connection( break; } } + } + } +} + +async fn run_websocket_inbound_loop( + mut websocket_reader: futures::stream::SplitStream< + tokio_tungstenite::WebSocketStream, + >, + transport_event_tx: mpsc::Sender, + writer_tx_for_reader: mpsc::Sender, + writer_control_tx: mpsc::Sender, + connection_id: ConnectionId, + disconnect_token: CancellationToken, +) { + loop { + tokio::select! { + _ = disconnect_token.cancelled() => { + break; + } incoming_message = websocket_reader.next() => { match incoming_message { Some(Ok(WebSocketMessage::Text(text))) => { @@ -341,8 +431,13 @@ async fn run_websocket_connection( } } Some(Ok(WebSocketMessage::Ping(payload))) => { - if websocket_writer.send(WebSocketMessage::Pong(payload)).await.is_err() { - break; + match writer_control_tx.try_send(WebSocketMessage::Pong(payload)) { + Ok(()) => {} + Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => break, + Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => { + warn!("websocket control queue full while replying to ping; closing connection"); + break; + } } } Some(Ok(WebSocketMessage::Pong(_))) => {} @@ -359,10 +454,6 @@ async fn run_websocket_connection( } } } - - let _ = transport_event_tx - .send(TransportEvent::ConnectionClosed { connection_id }) - .await; } async fn forward_incoming_message( @@ -461,30 +552,61 @@ fn should_skip_notification_for_connection( } } +fn disconnect_connection( + connections: &mut HashMap, + connection_id: ConnectionId, +) -> bool { + if let Some(connection_state) = connections.remove(&connection_id) { + connection_state.request_disconnect(); + return true; + } + false +} + +async fn send_message_to_connection( + connections: &mut HashMap, + connection_id: ConnectionId, + message: OutgoingMessage, +) -> bool { + let Some(connection_state) = connections.get(&connection_id) else { + warn!("dropping message for disconnected connection: {connection_id:?}"); + return false; + }; + if should_skip_notification_for_connection(connection_state, &message) { + return false; + } + + let writer = connection_state.writer.clone(); + if connection_state.can_disconnect() { + match writer.try_send(message) { + Ok(()) => false, + Err(mpsc::error::TrySendError::Full(_)) => { + warn!( + "disconnecting slow connection after outbound queue filled: {connection_id:?}" + ); + disconnect_connection(connections, connection_id) + } + Err(mpsc::error::TrySendError::Closed(_)) => { + disconnect_connection(connections, connection_id) + } + } + } else if writer.send(message).await.is_err() { + disconnect_connection(connections, connection_id) + } else { + false + } +} + pub(crate) async fn route_outgoing_envelope( connections: &mut HashMap, envelope: OutgoingEnvelope, -) -> Vec { - let mut disconnected = Vec::new(); +) { match envelope { OutgoingEnvelope::ToConnection { connection_id, message, } => { - let Some(connection_state) = connections.get(&connection_id) else { - warn!( - "dropping message for disconnected connection: {:?}", - connection_id - ); - return disconnected; - }; - if should_skip_notification_for_connection(connection_state, &message) { - return disconnected; - } - if connection_state.writer.send(message).await.is_err() { - connections.remove(&connection_id); - disconnected.push(connection_id); - } + let _ = send_message_to_connection(connections, connection_id, message).await; } OutgoingEnvelope::Broadcast { message } => { let target_connections: Vec = connections @@ -501,17 +623,11 @@ pub(crate) async fn route_outgoing_envelope( .collect(); for connection_id in target_connections { - let Some(connection_state) = connections.get(&connection_id) else { - continue; - }; - if connection_state.writer.send(message.clone()).await.is_err() { - connections.remove(&connection_id); - disconnected.push(connection_id); - } + let _ = + send_message_to_connection(connections, connection_id, message.clone()).await; } } } - disconnected } #[cfg(test)] @@ -520,6 +636,8 @@ mod tests { use crate::error_code::OVERLOADED_ERROR_CODE; use pretty_assertions::assert_eq; use serde_json::json; + use tokio::time::Duration; + use tokio::time::timeout; #[test] fn app_server_transport_parses_stdio_listen_url() { @@ -754,10 +872,15 @@ mod tests { let mut connections = HashMap::new(); connections.insert( connection_id, - OutboundConnectionState::new(writer_tx, initialized, opted_out_notification_methods), + OutboundConnectionState::new( + writer_tx, + initialized, + opted_out_notification_methods, + None, + ), ); - let disconnected = route_outgoing_envelope( + route_outgoing_envelope( &mut connections, OutgoingEnvelope::ToConnection { connection_id, @@ -771,10 +894,161 @@ mod tests { ) .await; - assert_eq!(disconnected, Vec::::new()); assert!( writer_rx.try_recv().is_err(), "opted-out notification should be dropped" ); } + + #[tokio::test] + async fn broadcast_does_not_block_on_slow_connection() { + let fast_connection_id = ConnectionId(1); + let slow_connection_id = ConnectionId(2); + + let (fast_writer_tx, mut fast_writer_rx) = mpsc::channel(1); + let (slow_writer_tx, mut slow_writer_rx) = mpsc::channel(1); + let fast_disconnect_token = CancellationToken::new(); + let slow_disconnect_token = CancellationToken::new(); + + let mut connections = HashMap::new(); + connections.insert( + fast_connection_id, + OutboundConnectionState::new( + fast_writer_tx, + Arc::new(AtomicBool::new(true)), + Arc::new(RwLock::new(HashSet::new())), + Some(fast_disconnect_token.clone()), + ), + ); + connections.insert( + slow_connection_id, + OutboundConnectionState::new( + slow_writer_tx.clone(), + Arc::new(AtomicBool::new(true)), + Arc::new(RwLock::new(HashSet::new())), + Some(slow_disconnect_token.clone()), + ), + ); + + let queued_message = + OutgoingMessage::Notification(crate::outgoing_message::OutgoingNotification { + method: "codex/event/already-buffered".to_string(), + params: None, + }); + slow_writer_tx + .try_send(queued_message) + .expect("channel should have room"); + + let broadcast_message = + OutgoingMessage::Notification(crate::outgoing_message::OutgoingNotification { + method: "codex/event/test".to_string(), + params: None, + }); + timeout( + Duration::from_millis(100), + route_outgoing_envelope( + &mut connections, + OutgoingEnvelope::Broadcast { + message: broadcast_message, + }, + ), + ) + .await + .expect("broadcast should not block on a full writer"); + assert!(!connections.contains_key(&slow_connection_id)); + assert!(slow_disconnect_token.is_cancelled()); + assert!(!fast_disconnect_token.is_cancelled()); + let fast_message = fast_writer_rx + .try_recv() + .expect("fast connection should receive broadcast"); + assert!(matches!( + fast_message, + OutgoingMessage::Notification(crate::outgoing_message::OutgoingNotification { + method, + params: None, + }) if method == "codex/event/test" + )); + + let slow_message = slow_writer_rx + .try_recv() + .expect("slow connection should retain its original buffered message"); + assert!(matches!( + slow_message, + OutgoingMessage::Notification(crate::outgoing_message::OutgoingNotification { + method, + params: None, + }) if method == "codex/event/already-buffered" + )); + } + + #[tokio::test] + async fn to_connection_stdio_waits_instead_of_disconnecting_when_writer_queue_is_full() { + let connection_id = ConnectionId(3); + let (writer_tx, mut writer_rx) = mpsc::channel(1); + writer_tx + .send(OutgoingMessage::Notification( + crate::outgoing_message::OutgoingNotification { + method: "queued".to_string(), + params: None, + }, + )) + .await + .expect("channel should accept the first queued message"); + + let mut connections = HashMap::new(); + connections.insert( + connection_id, + OutboundConnectionState::new( + writer_tx, + Arc::new(AtomicBool::new(true)), + Arc::new(RwLock::new(HashSet::new())), + None, + ), + ); + + let route_task = tokio::spawn(async move { + route_outgoing_envelope( + &mut connections, + OutgoingEnvelope::ToConnection { + connection_id, + message: OutgoingMessage::Notification( + crate::outgoing_message::OutgoingNotification { + method: "second".to_string(), + params: None, + }, + ), + }, + ) + .await + }); + + let first = timeout(Duration::from_millis(100), writer_rx.recv()) + .await + .expect("first queued message should be readable") + .expect("first queued message should exist"); + let second = timeout(Duration::from_millis(100), writer_rx.recv()) + .await + .expect("second message should eventually be delivered") + .expect("second message should exist"); + + timeout(Duration::from_millis(100), route_task) + .await + .expect("routing should finish after writer drains") + .expect("routing task should succeed"); + + assert!(matches!( + first, + OutgoingMessage::Notification(crate::outgoing_message::OutgoingNotification { + method, + params: None, + }) if method == "queued" + )); + assert!(matches!( + second, + OutgoingMessage::Notification(crate::outgoing_message::OutgoingNotification { + method, + params: None, + }) if method == "second" + )); + } } From 60c2b7beca5929346311388d50b1bdeb59673077 Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Fri, 20 Feb 2026 12:50:12 -0800 Subject: [PATCH 027/385] core tests: use hermetic mock server in review suite (#12291) ## Summary - switch the review test SSE mock helper to use the shared hermetic mock server setup - ensure review tests always have a default `/v1/models` stub during Codex session bootstrap - remove the race that caused intermittent `/v1/models` connection failures and flaky ETag refresh assertions ## Testing - `just fmt` - `cargo test -p codex-core --test all refresh_models_on_models_etag_mismatch_and_avoid_duplicate_models_fetch` - `cargo test -p codex-core --test all review_uses_custom_review_model_from_config` - repeated both targeted tests 5x in a loop - `cargo clippy -p codex-core --tests -- -D warnings` --- codex-rs/core/tests/suite/review.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index 1c9c3adf7b..113776b81f 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -20,6 +20,7 @@ use codex_protocol::user_input::UserInput; use core_test_support::load_sse_fixture_with_id_from_str; use core_test_support::responses::ResponseMock; use core_test_support::responses::mount_sse_sequence; +use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; @@ -872,7 +873,7 @@ async fn start_responses_server_with_sse( sse_raw: &str, expected_requests: usize, ) -> (MockServer, ResponseMock) { - let server = MockServer::start().await; + let server = start_mock_server().await; let sse = load_sse_fixture_with_id_from_str(sse_raw, &Uuid::new_v4().to_string()); let responses = vec![sse; expected_requests]; let request_log = mount_sse_sequence(&server, responses).await; From 354e7fedd25576d51220ee277bab5d4ca4f4f716 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Fri, 20 Feb 2026 14:05:55 -0800 Subject: [PATCH 028/385] [apps] Enforce simple logo url format. (#12374) - [x] Enforce simple logo url format when loading apps directory to save bandwidth. --- codex-rs/app-server/tests/suite/v2/app_list.rs | 13 ++++++++++--- codex-rs/chatgpt/src/connectors.rs | 8 +++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/codex-rs/app-server/tests/suite/v2/app_list.rs b/codex-rs/app-server/tests/suite/v2/app_list.rs index 3a2064d4cb..a9bc14e932 100644 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ b/codex-rs/app-server/tests/suite/v2/app_list.rs @@ -15,6 +15,7 @@ use axum::Router; use axum::extract::State; use axum::http::HeaderMap; use axum::http::StatusCode; +use axum::http::Uri; use axum::http::header::AUTHORIZATION; use axum::routing::get; use codex_app_server_protocol::AppBranding; @@ -1215,6 +1216,7 @@ async fn start_apps_server_with_delays_and_control( async fn list_directory_connectors( State(state): State>, headers: HeaderMap, + uri: Uri, ) -> Result { if state.directory_delay > Duration::ZERO { tokio::time::sleep(state.directory_delay).await; @@ -1228,16 +1230,21 @@ async fn list_directory_connectors( .get("chatgpt-account-id") .and_then(|value| value.to_str().ok()) .is_some_and(|value| value == state.expected_account_id); + let external_logos_ok = uri + .query() + .is_some_and(|query| query.split('&').any(|pair| pair == "external_logos=true")); - if bearer_ok && account_ok { + if !bearer_ok || !account_ok { + Err(StatusCode::UNAUTHORIZED) + } else if !external_logos_ok { + Err(StatusCode::BAD_REQUEST) + } else { let response = state .response .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone(); Ok(Json(response)) - } else { - Err(StatusCode::UNAUTHORIZED) } } diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index 27f2f1de94..a3470ff1b9 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -220,9 +220,11 @@ async fn list_directory_connectors(config: &Config) -> anyhow::Result { let encoded_token = urlencoding::encode(token); - format!("/connectors/directory/list?tier=categorized&token={encoded_token}") + format!( + "/connectors/directory/list?tier=categorized&token={encoded_token}&external_logos=true" + ) } - None => "/connectors/directory/list?tier=categorized".to_string(), + None => "/connectors/directory/list?tier=categorized&external_logos=true".to_string(), }; let response: DirectoryListResponse = chatgpt_get_request_with_timeout(config, path, Some(DIRECTORY_CONNECTORS_TIMEOUT)) @@ -247,7 +249,7 @@ async fn list_directory_connectors(config: &Config) -> anyhow::Result anyhow::Result> { let response: anyhow::Result = chatgpt_get_request_with_timeout( config, - "/connectors/directory/list_workspace".to_string(), + "/connectors/directory/list_workspace?external_logos=true".to_string(), Some(DIRECTORY_CONNECTORS_TIMEOUT), ) .await; From 9176f09cb8300e90af322ed3850219ec9ab8da01 Mon Sep 17 00:00:00 2001 From: derekf-oai Date: Fri, 20 Feb 2026 14:12:13 -0800 Subject: [PATCH 029/385] docs: use --locked when installing cargo-nextest (#12377) ## What Updates the optional `cargo-nextest` install command in `docs/install.md`: - `cargo install cargo-nextest` -> `cargo install --locked cargo-nextest` ## Why The current docs command can fail during source install because recent `cargo-nextest` releases intentionally require `--locked`. Repro (macOS, but likely not platform-specific): - `cargo install cargo-nextest` - Fails with a compile error from `locked-tripwire` indicating: - `Nextest does not support being installed without --locked` - suggests `cargo install --locked cargo-nextest` Using the locked command succeeds: - `cargo install --locked cargo-nextest` ## How Single-line docs change in `docs/install.md` to match current `cargo-nextest` install requirements. ## Validation - Reproduced failure locally using a temporary `CARGO_HOME` directory (clean Cargo home) - Example command used: `CARGO_HOME=/tmp/cargo-home-test cargo install cargo-nextest` - Confirmed success with `cargo install --locked cargo-nextest` --- docs/install.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/install.md b/docs/install.md index ef14f5d840..16892c82fe 100644 --- a/docs/install.md +++ b/docs/install.md @@ -27,7 +27,7 @@ rustup component add clippy # Install helper tools used by the workspace justfile: cargo install just # Optional: install nextest for the `just test` helper -cargo install cargo-nextest +cargo install --locked cargo-nextest # Build Codex. cargo build From 1bb7989b20b25ff7e4017fc0f9d9e2de5ee4834b Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Fri, 20 Feb 2026 14:26:14 -0800 Subject: [PATCH 030/385] Add ability to attach extra files to feedback (#12370) Allow clients to provide extra files. --- .../schema/json/ClientRequest.json | 9 +++++++++ .../json/codex_app_server_protocol.schemas.json | 9 +++++++++ .../schema/json/v2/FeedbackUploadParams.json | 9 +++++++++ .../typescript/v2/FeedbackUploadParams.ts | 2 +- codex-rs/app-server-protocol/src/protocol/v2.rs | 2 ++ codex-rs/app-server/README.md | 2 +- .../app-server/src/codex_message_processor.rs | 9 +++++++-- codex-rs/feedback/src/lib.rs | 17 ++++++++++++++--- codex-rs/tui/src/bottom_pane/feedback_view.rs | 12 ++++++------ 9 files changed, 58 insertions(+), 13 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 9fc2a99141..76ba36735c 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -507,6 +507,15 @@ "classification": { "type": "string" }, + "extraLogFiles": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "includeLogs": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 7a01b04b51..313c3e62b3 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -12549,6 +12549,15 @@ "classification": { "type": "string" }, + "extraLogFiles": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "includeLogs": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadParams.json b/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadParams.json index e4171b27f4..47b752b868 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/FeedbackUploadParams.json @@ -4,6 +4,15 @@ "classification": { "type": "string" }, + "extraLogFiles": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "includeLogs": { "type": "boolean" }, diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FeedbackUploadParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FeedbackUploadParams.ts index 3066e65406..ebbe3b32d4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FeedbackUploadParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/FeedbackUploadParams.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type FeedbackUploadParams = { classification: string, reason?: string | null, threadId?: string | null, includeLogs: boolean, }; +export type FeedbackUploadParams = { classification: string, reason?: string | null, threadId?: string | null, includeLogs: boolean, extraLogFiles?: Array | null, }; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 103b5f56a0..833e628214 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1506,6 +1506,8 @@ pub struct FeedbackUploadParams { #[ts(optional = nullable)] pub thread_id: Option, pub include_logs: bool, + #[ts(optional = nullable)] + pub extra_log_files: Option>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 95ab4e43eb..8ee15688c6 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -150,7 +150,7 @@ Example with notification opt-out: - `config/mcpServer/reload` — reload MCP server config from disk and queue a refresh for loaded threads (applied on each thread's next active turn); returns `{}`. Use this after editing `config.toml` without restarting the server. - `mcpServerStatus/list` — enumerate configured MCP servers with their tools, resources, resource templates, and auth status; supports cursor+limit pagination. - `windowsSandbox/setupStart` — start Windows sandbox setup for the selected mode (`elevated` or `unelevated`); returns `{ started: true }` immediately and later emits `windowsSandbox/setupCompleted`. -- `feedback/upload` — submit a feedback report (classification + optional reason/logs and conversation_id); returns the tracking thread id. +- `feedback/upload` — submit a feedback report (classification + optional reason/logs, conversation_id, and optional `extraLogFiles` attachments array); returns the tracking thread id. - `command/exec` — run a single command under the server sandbox without starting a thread/turn (handy for utilities and validation). - `config/read` — fetch the effective config on disk after resolving config layering. - `config/value/write` — write a single config key/value to the user's config.toml on disk. diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 29d8acdbc1..65b7f1ecb7 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -6098,6 +6098,7 @@ impl CodexMessageProcessor { reason, thread_id, include_logs, + extra_log_files, } = params; let conversation_id = match thread_id.as_deref() { @@ -6127,15 +6128,19 @@ impl CodexMessageProcessor { } else { None }; + let mut attachment_paths = validated_rollout_path.into_iter().collect::>(); + if let Some(extra_log_files) = extra_log_files { + attachment_paths.extend(extra_log_files); + } + let session_source = self.thread_manager.session_source(); let upload_result = tokio::task::spawn_blocking(move || { - let rollout_path_ref = validated_rollout_path.as_deref(); snapshot.upload_feedback( &classification, reason.as_deref(), include_logs, - rollout_path_ref, + &attachment_paths, Some(session_source), ) }) diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index adda7173a1..a4fe6cc185 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -224,7 +224,7 @@ impl CodexLogSnapshot { classification: &str, reason: Option<&str>, include_logs: bool, - rollout_path: Option<&std::path::Path>, + extra_log_files: &[PathBuf], session_source: Option, ) -> Result<()> { use std::collections::BTreeMap; @@ -317,11 +317,22 @@ impl CodexLogSnapshot { })); } - if let Some((path, data)) = rollout_path.and_then(|p| fs::read(p).ok().map(|d| (p, d))) { + for path in extra_log_files { + let data = match fs::read(path) { + Ok(data) => data, + Err(err) => { + tracing::warn!( + path = %path.display(), + error = %err, + "failed to read log attachment; skipping" + ); + continue; + } + }; let fname = path .file_name() .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_else(|| "rollout.jsonl".to_string()); + .unwrap_or_else(|| "extra-log.log".to_string()); let content_type = "text/plain".to_string(); envelope.add_item(EnvelopeItem::Attachment(Attachment { buffer: data, diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index 6cbfbdb9e5..eeca6aef18 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -87,7 +87,11 @@ impl FeedbackNoteView { } else { Some(note.as_str()) }; - let rollout_path_ref = self.rollout_path.as_deref(); + let log_file_paths = if self.include_logs { + self.rollout_path.iter().cloned().collect::>() + } else { + Vec::new() + }; let classification = feedback_classification(self.category); let mut thread_id = self.snapshot.thread_id.clone(); @@ -96,11 +100,7 @@ impl FeedbackNoteView { classification, reason_opt, self.include_logs, - if self.include_logs { - rollout_path_ref - } else { - None - }, + &log_file_paths, Some(SessionSource::Cli), ); From 64f3827d109c923759ca60c58751a0cd686c446a Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Fri, 20 Feb 2026 14:47:54 -0800 Subject: [PATCH 031/385] Move sanitizer into codex-secrets (#12306) ## Summary - move the sanitizer implementation into `codex-secrets` (`secrets/src/sanitizer.rs`) and re-export `redact_secrets` - switch `codex-core` to depend on/import `codex-secrets` for sanitizer usage - remove the old `utils/sanitizer` crate wiring and refresh lockfiles ## Testing - `just fmt` - `cargo test -p codex-secrets` - `cargo test -p codex-core --no-run` - `cargo clippy -p codex-secrets -p codex-core --all-targets --all-features -- -D warnings` - `just bazel-lock-update` - `just bazel-lock-check` ## Notes - not run: `cargo test --all-features` (full workspace suite) --- codex-rs/Cargo.lock | 10 ++-------- codex-rs/Cargo.toml | 2 -- codex-rs/core/Cargo.toml | 2 +- codex-rs/core/src/memories/phase1.rs | 2 +- codex-rs/secrets/BUILD.bazel | 6 ++++++ codex-rs/secrets/Cargo.toml | 1 + codex-rs/secrets/src/lib.rs | 2 ++ .../sanitizer/src/lib.rs => secrets/src/sanitizer.rs} | 0 codex-rs/utils/sanitizer/BUILD.bazel | 6 ------ codex-rs/utils/sanitizer/Cargo.toml | 11 ----------- 10 files changed, 13 insertions(+), 29 deletions(-) create mode 100644 codex-rs/secrets/BUILD.bazel rename codex-rs/{utils/sanitizer/src/lib.rs => secrets/src/sanitizer.rs} (100%) delete mode 100644 codex-rs/utils/sanitizer/BUILD.bazel delete mode 100644 codex-rs/utils/sanitizer/Cargo.toml diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 7818b253cf..f05879a243 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1637,6 +1637,7 @@ dependencies = [ "codex-otel", "codex-protocol", "codex-rmcp-client", + "codex-secrets", "codex-shell-command", "codex-state", "codex-utils-absolute-path", @@ -1644,7 +1645,6 @@ dependencies = [ "codex-utils-home-dir", "codex-utils-pty", "codex-utils-readiness", - "codex-utils-sanitizer", "codex-utils-string", "codex-windows-sandbox", "core-foundation 0.9.4", @@ -2151,6 +2151,7 @@ dependencies = [ "keyring", "pretty_assertions", "rand 0.9.2", + "regex", "schemars 0.8.22", "serde", "serde_json", @@ -2439,13 +2440,6 @@ dependencies = [ "pretty_assertions", ] -[[package]] -name = "codex-utils-sanitizer" -version = "0.0.0" -dependencies = [ - "regex", -] - [[package]] name = "codex-utils-sleep-inhibitor" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index e27b08b7f4..8ff0c456b8 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -53,7 +53,6 @@ members = [ "utils/cli", "utils/elapsed", "utils/sandbox-summary", - "utils/sanitizer", "utils/sleep-inhibitor", "utils/approval-presets", "utils/oss", @@ -131,7 +130,6 @@ codex-utils-pty = { path = "utils/pty" } codex-utils-readiness = { path = "utils/readiness" } codex-utils-rustls-provider = { path = "utils/rustls-provider" } codex-utils-sandbox-summary = { path = "utils/sandbox-summary" } -codex-utils-sanitizer = { path = "utils/sanitizer" } codex-utils-sleep-inhibitor = { path = "utils/sleep-inhibitor" } codex-utils-string = { path = "utils/string" } codex-windows-sandbox = { path = "windows-sandbox-rs" } diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index fe7c2b5aa9..2b62d96254 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -48,7 +48,7 @@ codex-utils-absolute-path = { workspace = true } codex-utils-home-dir = { workspace = true } codex-utils-pty = { workspace = true } codex-utils-readiness = { workspace = true } -codex-utils-sanitizer = { workspace = true } +codex-secrets = { workspace = true } codex-utils-string = { workspace = true } codex-windows-sandbox = { package = "codex-windows-sandbox", path = "../windows-sandbox-rs" } dirs = { workspace = true } diff --git a/codex-rs/core/src/memories/phase1.rs b/codex-rs/core/src/memories/phase1.rs index b356f61b38..d2fb6d11f4 100644 --- a/codex-rs/core/src/memories/phase1.rs +++ b/codex-rs/core/src/memories/phase1.rs @@ -20,7 +20,7 @@ use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::TokenUsage; -use codex_utils_sanitizer::redact_secrets; +use codex_secrets::redact_secrets; use futures::StreamExt; use serde::Deserialize; use serde_json::Value; diff --git a/codex-rs/secrets/BUILD.bazel b/codex-rs/secrets/BUILD.bazel new file mode 100644 index 0000000000..1b69e7c7e0 --- /dev/null +++ b/codex-rs/secrets/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "secrets", + crate_name = "codex_secrets", +) diff --git a/codex-rs/secrets/Cargo.toml b/codex-rs/secrets/Cargo.toml index de45af50a1..eae8f9005e 100644 --- a/codex-rs/secrets/Cargo.toml +++ b/codex-rs/secrets/Cargo.toml @@ -13,6 +13,7 @@ anyhow = { workspace = true } base64 = { workspace = true } codex-keyring-store = { workspace = true } rand = { workspace = true } +regex = { workspace = true } schemars = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/codex-rs/secrets/src/lib.rs b/codex-rs/secrets/src/lib.rs index a45860d8b5..1ec925fd4f 100644 --- a/codex-rs/secrets/src/lib.rs +++ b/codex-rs/secrets/src/lib.rs @@ -13,8 +13,10 @@ use sha2::Digest; use sha2::Sha256; mod local; +mod sanitizer; pub use local::LocalSecretsBackend; +pub use sanitizer::redact_secrets; const KEYRING_SERVICE: &str = "codex"; diff --git a/codex-rs/utils/sanitizer/src/lib.rs b/codex-rs/secrets/src/sanitizer.rs similarity index 100% rename from codex-rs/utils/sanitizer/src/lib.rs rename to codex-rs/secrets/src/sanitizer.rs diff --git a/codex-rs/utils/sanitizer/BUILD.bazel b/codex-rs/utils/sanitizer/BUILD.bazel deleted file mode 100644 index 3cc7465bd7..0000000000 --- a/codex-rs/utils/sanitizer/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "sanitizer", - crate_name = "codex_utils_sanitizer", -) diff --git a/codex-rs/utils/sanitizer/Cargo.toml b/codex-rs/utils/sanitizer/Cargo.toml deleted file mode 100644 index 6f96cc891c..0000000000 --- a/codex-rs/utils/sanitizer/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "codex-utils-sanitizer" -version.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -regex = "1.12.3" - -[lints] -workspace = true From 65b9fe8f30c5889afc433181c3fb25a315633d79 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Fri, 20 Feb 2026 15:04:36 -0800 Subject: [PATCH 032/385] clarify model_catalog_json only applied on startup (#12379) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. --- codex-rs/core/config.schema.json | 2 +- codex-rs/core/src/config/mod.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index e73a71bb30..4de4da6e48 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1807,7 +1807,7 @@ "$ref": "#/definitions/AbsolutePathBuf" } ], - "description": "Optional path to a JSON file containing a complete model catalog. When set, this replaces the bundled catalog for this process." + "description": "Optional path to a JSON model catalog (applied on startup only). Per-thread `config` overrides are accepted but do not reapply this (no-ops)." }, "model_context_window": { "description": "Size of the context window for the model, in tokens.", diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 3b8e0382e8..76ba2fcb2d 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1109,8 +1109,8 @@ pub struct ConfigToml { /// Override to force-enable reasoning summaries for the configured model. pub model_supports_reasoning_summaries: Option, - /// Optional path to a JSON file containing a complete model catalog. - /// When set, this replaces the bundled catalog for this process. + /// Optional path to a JSON model catalog (applied on startup only). + /// Per-thread `config` overrides are accepted but do not reapply this (no-ops). pub model_catalog_json: Option, /// Optionally specify a personality for the model From 021e39b3031de7661245eff61ed9bbe11ffca531 Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Fri, 20 Feb 2026 15:22:10 -0800 Subject: [PATCH 033/385] Show model/reasoning hint when switching modes (#12307) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - show an info message when switching collaboration modes changes the effective model or reasoning - include the target mode in the message (for example `... for Plan mode.`) - add TUI tests for model-change and reasoning-only change notifications on mode switch Screenshot 2026-02-20 at 2 01 40 PM --- codex-rs/tui/src/chatwidget.rs | 27 +++++++++++ codex-rs/tui/src/chatwidget/tests.rs | 67 +++++++++++++++++++++++++++- 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 7dcab8010a..ca5aa7c620 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -6343,9 +6343,36 @@ impl ChatWidget { if !self.collaboration_modes_enabled() { return; } + let previous_mode = self.active_mode_kind(); + let previous_model = self.current_model().to_string(); + let previous_effort = self.effective_reasoning_effort(); self.active_collaboration_mask = Some(mask); self.update_collaboration_mode_indicator(); self.refresh_model_display(); + let next_mode = self.active_mode_kind(); + let next_model = self.current_model(); + let next_effort = self.effective_reasoning_effort(); + if previous_mode != next_mode + && (previous_model != next_model || previous_effort != next_effort) + { + let mut message = format!("Model changed to {next_model}"); + if !next_model.starts_with("codex-auto-") { + let reasoning_label = match next_effort { + Some(ReasoningEffortConfig::Minimal) => "minimal", + Some(ReasoningEffortConfig::Low) => "low", + Some(ReasoningEffortConfig::Medium) => "medium", + Some(ReasoningEffortConfig::High) => "high", + Some(ReasoningEffortConfig::XHigh) => "xhigh", + None | Some(ReasoningEffortConfig::None) => "default", + }; + message.push(' '); + message.push_str(reasoning_label); + } + message.push_str(" for "); + message.push_str(next_mode.display_name()); + message.push_str(" mode."); + self.add_info_message(message, None); + } self.request_redraw(); } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index d6d2ab1ad7..edf0e01681 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -3584,6 +3584,66 @@ async fn collab_mode_shift_tab_cycles_only_when_enabled_and_idle() { assert_eq!(chat.active_collaboration_mode_kind(), before); } +#[tokio::test] +async fn mode_switch_surfaces_model_change_notification_when_effective_model_changes() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await; + chat.set_feature_enabled(Feature::CollaborationModes, true); + let default_model = chat.current_model().to_string(); + + let mut plan_mask = + collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan) + .expect("expected plan collaboration mode"); + plan_mask.model = Some("gpt-5.1-codex-mini".to_string()); + chat.set_collaboration_mask(plan_mask); + + let plan_messages = drain_insert_history(&mut rx) + .iter() + .map(|lines| lines_to_single_string(lines)) + .collect::>() + .join("\n"); + assert!( + plan_messages.contains("Model changed to gpt-5.1-codex-mini medium for Plan mode."), + "expected Plan-mode model switch notice, got: {plan_messages:?}" + ); + + let default_mask = collaboration_modes::default_mask(chat.models_manager.as_ref()) + .expect("expected default collaboration mode"); + chat.set_collaboration_mask(default_mask); + + let default_messages = drain_insert_history(&mut rx) + .iter() + .map(|lines| lines_to_single_string(lines)) + .collect::>() + .join("\n"); + let expected_default_message = + format!("Model changed to {default_model} default for Default mode."); + assert!( + default_messages.contains(&expected_default_message), + "expected Default-mode model switch notice, got: {default_messages:?}" + ); +} + +#[tokio::test] +async fn mode_switch_surfaces_reasoning_change_notification_when_model_stays_same() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.3-codex")).await; + chat.set_feature_enabled(Feature::CollaborationModes, true); + chat.set_reasoning_effort(Some(ReasoningEffortConfig::High)); + + let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref()) + .expect("expected plan collaboration mode"); + chat.set_collaboration_mask(plan_mask); + + let plan_messages = drain_insert_history(&mut rx) + .iter() + .map(|lines| lines_to_single_string(lines)) + .collect::>() + .join("\n"); + assert!( + plan_messages.contains("Model changed to gpt-5.3-codex medium for Plan mode."), + "expected reasoning-change notice in Plan mode, got: {plan_messages:?}" + ); +} + #[tokio::test] async fn collab_slash_command_opens_picker_and_updates_mode() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; @@ -3649,7 +3709,12 @@ async fn plan_slash_command_switches_to_plan_mode() { chat.dispatch_command(SlashCommand::Plan); - assert!(rx.try_recv().is_err(), "plan should not emit an app event"); + while let Ok(event) = rx.try_recv() { + assert!( + matches!(event, AppEvent::InsertHistoryCell(_)), + "plan should not emit a non-history app event: {event:?}" + ); + } assert_eq!(chat.active_collaboration_mode_kind(), ModeKind::Plan); assert_eq!(chat.current_collaboration_mode(), &initial); } From 4ebdddaa3497e7fbd4cd80434015f016b9bdf119 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Fri, 20 Feb 2026 16:47:15 -0800 Subject: [PATCH 034/385] [apps] Fix gateway url. (#12403) - [x] Fix connectors gateway url. --- codex-rs/core/src/mcp/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index f2c2557514..3abe4e9233 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -31,7 +31,7 @@ const MCP_TOOL_NAME_DELIMITER: &str = "__"; pub(crate) const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps"; const CODEX_CONNECTORS_TOKEN_ENV_VAR: &str = "CODEX_CONNECTORS_TOKEN"; const OPENAI_CONNECTORS_MCP_BASE_URL: &str = "https://api.openai.com"; -const OPENAI_CONNECTORS_MCP_PATH: &str = "/v1/connectors/mcp/"; +const OPENAI_CONNECTORS_MCP_PATH: &str = "/v1/connectors/gateways/flat/mcp"; // Legacy vs new MCP gateway #[derive(Debug, Clone, Copy, PartialEq, Eq)] From a5d0757ed15b4b53c216510c5bcfa4ecf3ca196e Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Fri, 20 Feb 2026 21:56:41 -0300 Subject: [PATCH 035/385] fix(tui): queued-message edit shortcut unreachable in some terminals (#12240) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem The TUI's "edit queued message" shortcut (Alt+Up) is either silently swallowed or recognized as another key combination by Apple Terminal, Warp, and VSCode's integrated terminal on macOS. Users in those environments see the hint but pressing the keys does nothing. ## Mental model When a model turn is in progress the user can still type follow-up messages. These are queued and displayed below the composer with a hint line showing how to pop the most recent one back into the editor. The hint text and the actual key handler must agree on which shortcut is used, and that shortcut must actually reach the TUI—i.e. it must not be intercepted by the host terminal. Three terminals are known to intercept Alt+Up: Apple Terminal (remaps it to cursor movement), Warp (consumes it for its own command palette), and VSCode (maps it to "move line up"). For these we use Shift+Left instead.

image

| macOS Native Terminal | Warp | VSCode Terminal | |---|---|---| | SCR-20260219-kigi | SCR-20260219-krrf | SCR-20260219-ksbz | ## Non-goals - Making the binding user-configurable at runtime (deferred to a broader keybinding-config effort). - Remapping any other shortcuts that might be terminal-specific. ## Tradeoffs - **Exhaustive match instead of a wildcard default.** The `queued_message_edit_binding_for_terminal` function explicitly lists every `TerminalName` variant. This is intentional: adding a new terminal to the enum will produce a compile error, forcing the author to decide which binding that terminal should use. - **Binding lives on `ChatWidget`, hint lives on `QueuedUserMessages`.** The key event handler that actually acts on the press is in `ChatWidget`, but the rendered hint text is inside `QueuedUserMessages`. These are kept in sync by `ChatWidget` calling `bottom_pane.set_queued_message_edit_binding(self.queued_message_edit_binding)` during construction. A mismatch would show the wrong hint but would not lose data. ## Architecture ```mermaid graph TD TI["terminal_info().name"] --> FN["queued_message_edit_binding_for_terminal(name)"] FN --> KB["KeyBinding"] KB --> CW["ChatWidget.queued_message_edit_binding
key event matching"] KB --> BP["BottomPane.set_queued_message_edit_binding()"] BP --> QUM["QueuedUserMessages.edit_binding
rendered in hint line"] subgraph "Special terminals (Shift+Left)" AT["Apple Terminal"] WT["Warp"] VS["VSCode"] end subgraph "Default (Alt+Up)" GH["Ghostty"] IT["iTerm2"] OT["Others…"] end AT --> FN WT --> FN VS --> FN GH --> FN IT --> FN OT --> FN ``` No new crates or public API surface. The only cross-crate dependency added is `codex_core::terminal::{TerminalName, terminal_info}`, which already existed for telemetry. ## Observability No new logging. Terminal detection already emits a `tracing::debug!` log line at startup with the detected terminal name, which is sufficient to diagnose binding mismatches. ## Tests - Existing `alt_up_edits_most_recent_queued_message` test is preserved and explicitly sets the Alt+Up binding to isolate from the host terminal. - New parameterized async tests verify Shift+Left works for Apple Terminal, Warp, and VSCode. - A sync unit test asserts the mapping table covers the three special terminals (Shift+Left) and that iTerm2 still gets Alt+Up. Fixes #4490 --- codex-rs/tui/src/bottom_pane/mod.rs | 7 ++ .../src/bottom_pane/queued_user_messages.rs | 18 ++++- codex-rs/tui/src/chatwidget.rs | 78 +++++++++++++++---- codex-rs/tui/src/chatwidget/tests.rs | 76 ++++++++++++++++++ 4 files changed, 165 insertions(+), 14 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 43aecb4940..46917dd9fa 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -287,6 +287,13 @@ impl BottomPane { self.request_redraw(); } + /// Update the key hint shown next to queued messages so it matches the + /// binding that `ChatWidget` actually listens for. + pub(crate) fn set_queued_message_edit_binding(&mut self, binding: KeyBinding) { + self.queued_user_messages.set_edit_binding(binding); + self.request_redraw(); + } + pub fn status_widget(&self) -> Option<&StatusIndicatorWidget> { self.status.as_ref() } diff --git a/codex-rs/tui/src/bottom_pane/queued_user_messages.rs b/codex-rs/tui/src/bottom_pane/queued_user_messages.rs index ae33aeada4..010b88111c 100644 --- a/codex-rs/tui/src/bottom_pane/queued_user_messages.rs +++ b/codex-rs/tui/src/bottom_pane/queued_user_messages.rs @@ -11,17 +11,33 @@ use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_lines; /// Widget that displays a list of user messages queued while a turn is in progress. +/// +/// The widget shows a key hint at the bottom (e.g. "⌥ + ↑ edit") telling the +/// user how to pop the most recent queued message back into the composer. +/// Because some terminals intercept certain modifier-key combinations, the +/// displayed binding is configurable via [`set_edit_binding`](Self::set_edit_binding). pub(crate) struct QueuedUserMessages { pub messages: Vec, + /// Key combination rendered in the hint line. Defaults to Alt+Up but may + /// be overridden for terminals where that chord is unavailable. + edit_binding: key_hint::KeyBinding, } impl QueuedUserMessages { pub(crate) fn new() -> Self { Self { messages: Vec::new(), + edit_binding: key_hint::alt(KeyCode::Up), } } + /// Replace the keybinding shown in the hint line at the bottom of the + /// queued-messages list. The caller is responsible for also wiring the + /// corresponding key event handler. + pub(crate) fn set_edit_binding(&mut self, binding: key_hint::KeyBinding) { + self.edit_binding = binding; + } + fn as_renderable(&self, width: u16) -> Box { if self.messages.is_empty() || width < 4 { return Box::new(()); @@ -48,7 +64,7 @@ impl QueuedUserMessages { lines.push( Line::from(vec![ " ".into(), - key_hint::alt(KeyCode::Up).into(), + self.edit_binding.into(), " edit".into(), ]) .dim(), diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index ca5aa7c620..afc894b22b 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -110,6 +110,8 @@ use codex_core::protocol::WarningEvent; use codex_core::protocol::WebSearchBeginEvent; use codex_core::protocol::WebSearchEndEvent; use codex_core::skills::model::SkillMetadata; +use codex_core::terminal::TerminalName; +use codex_core::terminal::terminal_info; #[cfg(target_os = "windows")] use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_otel::OtelManager; @@ -158,6 +160,34 @@ const PLAN_IMPLEMENTATION_NO: &str = "No, stay in Plan mode"; const PLAN_IMPLEMENTATION_CODING_MESSAGE: &str = "Implement the plan."; const CONNECTORS_SELECTION_VIEW_ID: &str = "connectors-selection"; +/// Choose the keybinding used to edit the most-recently queued message. +/// +/// Apple Terminal, Warp, and VSCode integrated terminals intercept or silently +/// swallow Alt+Up, so users in those environments would never be able to trigger +/// the edit action. We fall back to Shift+Left for those terminals while +/// keeping the more discoverable Alt+Up everywhere else. +/// +/// The match is exhaustive so that adding a new `TerminalName` variant forces +/// an explicit decision about which binding that terminal should use. +fn queued_message_edit_binding_for_terminal(terminal_name: TerminalName) -> KeyBinding { + match terminal_name { + TerminalName::AppleTerminal | TerminalName::WarpTerminal | TerminalName::VsCode => { + key_hint::shift(KeyCode::Left) + } + TerminalName::Ghostty + | TerminalName::Iterm2 + | TerminalName::WezTerm + | TerminalName::Kitty + | TerminalName::Alacritty + | TerminalName::Konsole + | TerminalName::GnomeTerminal + | TerminalName::Vte + | TerminalName::WindowsTerminal + | TerminalName::Dumb + | TerminalName::Unknown => key_hint::alt(KeyCode::Up), + } +} + use crate::app_event::AppEvent; use crate::app_event::ConnectorsSnapshot; use crate::app_event::ExitMode; @@ -563,6 +593,11 @@ pub(crate) struct ChatWidget { suppress_session_configured_redraw: bool, // User messages queued while a turn is in progress queued_user_messages: VecDeque, + /// Terminal-appropriate keybinding for popping the most-recently queued + /// message back into the composer. Determined once at construction time via + /// [`queued_message_edit_binding_for_terminal`] and propagated to + /// `BottomPane` so the hint text matches the actual shortcut. + queued_message_edit_binding: KeyBinding, // Pending notification to show when unfocused on next Draw pending_notification: Option, /// When `Some`, the user has pressed a quit shortcut and the second press @@ -2605,6 +2640,8 @@ impl ChatWidget { let active_cell = Some(Self::placeholder_session_header_cell(&config)); let current_cwd = Some(config.cwd.clone()); + let queued_message_edit_binding = + queued_message_edit_binding_for_terminal(terminal_info().name); let mut widget = Self { app_event_tx: app_event_tx.clone(), frame_requester: frame_requester.clone(), @@ -2662,6 +2699,7 @@ impl ChatWidget { thread_name: None, forked_from: None, queued_user_messages: VecDeque::new(), + queued_message_edit_binding, show_welcome_banner: is_first_run, suppress_session_configured_redraw: false, pending_notification: None, @@ -2702,6 +2740,9 @@ impl ChatWidget { widget.config.features.enabled(Feature::CollaborationModes), ); widget.sync_personality_command_enabled(); + widget + .bottom_pane + .set_queued_message_edit_binding(widget.queued_message_edit_binding); #[cfg(target_os = "windows")] widget.bottom_pane.set_windows_degraded_sandbox_active( codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED @@ -2769,6 +2810,8 @@ impl ChatWidget { let active_cell = Some(Self::placeholder_session_header_cell(&config)); let current_cwd = Some(config.cwd.clone()); + let queued_message_edit_binding = + queued_message_edit_binding_for_terminal(terminal_info().name); let mut widget = Self { app_event_tx: app_event_tx.clone(), frame_requester: frame_requester.clone(), @@ -2830,6 +2873,7 @@ impl ChatWidget { plan_delta_buffer: String::new(), plan_item_active: false, queued_user_messages: VecDeque::new(), + queued_message_edit_binding, show_welcome_banner: is_first_run, suppress_session_configured_redraw: false, pending_notification: None, @@ -2866,6 +2910,9 @@ impl ChatWidget { widget.config.features.enabled(Feature::CollaborationModes), ); widget.sync_personality_command_enabled(); + widget + .bottom_pane + .set_queued_message_edit_binding(widget.queued_message_edit_binding); widget } @@ -2922,6 +2969,8 @@ impl ChatWidget { settings: fallback_default, }; + let queued_message_edit_binding = + queued_message_edit_binding_for_terminal(terminal_info().name); let mut widget = Self { app_event_tx: app_event_tx.clone(), frame_requester: frame_requester.clone(), @@ -2979,6 +3028,7 @@ impl ChatWidget { thread_name: None, forked_from: None, queued_user_messages: VecDeque::new(), + queued_message_edit_binding, show_welcome_banner: false, suppress_session_configured_redraw: true, pending_notification: None, @@ -3019,6 +3069,9 @@ impl ChatWidget { widget.config.features.enabled(Feature::CollaborationModes), ); widget.sync_personality_command_enabled(); + widget + .bottom_pane + .set_queued_message_edit_binding(widget.queued_message_edit_binding); #[cfg(target_os = "windows")] widget.bottom_pane.set_windows_degraded_sandbox_active( codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED @@ -3091,6 +3144,18 @@ impl ChatWidget { _ => {} } + if key_event.kind == KeyEventKind::Press + && self.queued_message_edit_binding.is_press(key_event) + && !self.queued_user_messages.is_empty() + { + if let Some(user_message) = self.queued_user_messages.pop_back() { + self.restore_user_message_to_composer(user_message); + self.refresh_queued_user_messages(); + self.request_redraw(); + } + return; + } + match key_event { KeyEvent { code: KeyCode::BackTab, @@ -3102,19 +3167,6 @@ impl ChatWidget { { self.cycle_collaboration_mode(); } - KeyEvent { - code: KeyCode::Up, - modifiers: KeyModifiers::ALT, - kind: KeyEventKind::Press, - .. - } if !self.queued_user_messages.is_empty() => { - // Prefer the most recently queued item. - if let Some(user_message) = self.queued_user_messages.pop_back() { - self.restore_user_message_to_composer(user_message); - self.refresh_queued_user_messages(); - self.request_redraw(); - } - } _ => match self.bottom_pane.handle_key_event(key_event) { InputResult::Submitted { text, diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index edf0e01681..8646033284 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -67,6 +67,7 @@ use codex_core::protocol::UndoStartedEvent; use codex_core::protocol::ViewImageToolCallEvent; use codex_core::protocol::WarningEvent; use codex_core::skills::model::SkillMetadata; +use codex_core::terminal::TerminalName; use codex_otel::OtelManager; use codex_otel::RuntimeMetricsSummary; use codex_protocol::ThreadId; @@ -1640,6 +1641,7 @@ async fn make_chatwidget_manual( frame_requester: FrameRequester::test_dummy(), show_welcome_banner: true, queued_user_messages: VecDeque::new(), + queued_message_edit_binding: crate::key_hint::alt(KeyCode::Up), suppress_session_configured_redraw: false, pending_notification: None, quit_shortcut_expires_at: None, @@ -2781,6 +2783,9 @@ async fn empty_enter_during_task_does_not_queue() { #[tokio::test] async fn alt_up_edits_most_recent_queued_message() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.queued_message_edit_binding = crate::key_hint::alt(KeyCode::Up); + chat.bottom_pane + .set_queued_message_edit_binding(crate::key_hint::alt(KeyCode::Up)); // Simulate a running task so messages would normally be queued. chat.bottom_pane.set_task_running(true); @@ -2808,6 +2813,77 @@ async fn alt_up_edits_most_recent_queued_message() { ); } +async fn assert_shift_left_edits_most_recent_queued_message_for_terminal( + terminal_name: TerminalName, +) { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.queued_message_edit_binding = queued_message_edit_binding_for_terminal(terminal_name); + chat.bottom_pane + .set_queued_message_edit_binding(chat.queued_message_edit_binding); + + // Simulate a running task so messages would normally be queued. + chat.bottom_pane.set_task_running(true); + + // Seed two queued messages. + chat.queued_user_messages + .push_back(UserMessage::from("first queued".to_string())); + chat.queued_user_messages + .push_back(UserMessage::from("second queued".to_string())); + chat.refresh_queued_user_messages(); + + // Press Shift+Left to edit the most recent (last) queued message. + chat.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); + + // Composer should now contain the last queued message. + assert_eq!( + chat.bottom_pane.composer_text(), + "second queued".to_string() + ); + // And the queue should now contain only the remaining (older) item. + assert_eq!(chat.queued_user_messages.len(), 1); + assert_eq!( + chat.queued_user_messages.front().unwrap().text, + "first queued" + ); +} + +#[tokio::test] +async fn shift_left_edits_most_recent_queued_message_in_apple_terminal() { + assert_shift_left_edits_most_recent_queued_message_for_terminal(TerminalName::AppleTerminal) + .await; +} + +#[tokio::test] +async fn shift_left_edits_most_recent_queued_message_in_warp_terminal() { + assert_shift_left_edits_most_recent_queued_message_for_terminal(TerminalName::WarpTerminal) + .await; +} + +#[tokio::test] +async fn shift_left_edits_most_recent_queued_message_in_vscode_terminal() { + assert_shift_left_edits_most_recent_queued_message_for_terminal(TerminalName::VsCode).await; +} + +#[test] +fn queued_message_edit_binding_mapping_covers_special_terminals() { + assert_eq!( + queued_message_edit_binding_for_terminal(TerminalName::AppleTerminal), + crate::key_hint::shift(KeyCode::Left) + ); + assert_eq!( + queued_message_edit_binding_for_terminal(TerminalName::WarpTerminal), + crate::key_hint::shift(KeyCode::Left) + ); + assert_eq!( + queued_message_edit_binding_for_terminal(TerminalName::VsCode), + crate::key_hint::shift(KeyCode::Left) + ); + assert_eq!( + queued_message_edit_binding_for_terminal(TerminalName::Iterm2), + crate::key_hint::alt(KeyCode::Up) + ); +} + /// Pressing Up to recall the most recent history entry and immediately queuing /// it while a task is running should always enqueue the same text, even when it /// is queued repeatedly. From 36a2a9fdbb11b07504a69c4f2fa90e63c1cbeb67 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Fri, 20 Feb 2026 17:35:07 -0800 Subject: [PATCH 036/385] [apps] Bump MCP tool call timeout. (#12405) - [x] Bump MCP tool call timeout. --- codex-rs/core/src/mcp_connection_manager.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 05ac2a9a9b..12e3d325d3 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -92,7 +92,7 @@ const MAX_TOOL_NAME_LENGTH: usize = 64; pub const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(10); /// Default timeout for individual tool calls. -const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(60); +const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(120); const CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION: u8 = 1; const CODEX_APPS_TOOLS_CACHE_DIR: &str = "cache/codex_apps_tools"; From 53bcfaf42d996d4e93e66c86f41a55b7ff3b56fc Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 20 Feb 2026 17:51:53 -0800 Subject: [PATCH 037/385] fix: explicitly list name collisions in JSON schema generation (#12406) ## Why JSON schema codegen was silently resolving naming collisions by appending numeric suffixes (for example `...2`, `...3`). That makes the generated schema names unstable: removing an earlier colliding type can cause a later type to be renumbered, which is a breaking change for consumers that referenced the old generated name. This PR makes those collisions explicit and reviewable. Though note that once we remove `v1` from the codegen, we will no longer support naming collisions. Or rather, naming collisions will have to be handled explicitly rather than the numeric suffix approach. ## What Changed - In `codex-rs/app-server-protocol/src/export.rs`, replaced implicit numeric suffix collision handling for generated variant titles with explicit special-case maps. - Added a panic when a collision occurs without an entry in the map, so new collisions fail loudly instead of silently renaming generated schema types. - Added the currently required special cases so existing generated names remain stable. - Extended the same approach to numbered `definitions` / `$defs` collisions (for example `MessagePhase2`-style names) so those are also explicitly tracked. ## Verification - Ran targeted generator-path test: - `cargo test -p codex-app-server-protocol generate_json_filters_experimental_fields_and_methods -- --nocapture` --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/12406). * #12408 * __->__ #12406 --- codex-rs/app-server-protocol/src/export.rs | 239 ++++++++++++++++++++- 1 file changed, 235 insertions(+), 4 deletions(-) diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index ec51dd1585..1a4edfdf57 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -32,10 +32,93 @@ use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::process::Command; +use std::sync::LazyLock; use ts_rs::TS; const HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n"; const IGNORED_DEFINITIONS: &[&str] = &["Option<()>"]; +static VARIANT_TITLE_COLLISION_OVERRIDES: LazyLock> = + LazyLock::new(|| { + HashMap::from([ + ( + "base=McpStartupStatus|generated=StateMcpStartupStatus|literal:state=ready|only_property=state|required_only=state", + "StateMcpStartupStatus2", + ), + ( + "base=McpStartupStatus|generated=StateMcpStartupStatus|literal:state=cancelled|only_property=state|required_only=state", + "StateMcpStartupStatus3", + ), + ]) + }); +static NUMBERED_DEFINITION_COLLISION_OVERRIDES: LazyLock> = + LazyLock::new(|| { + HashMap::from([ + ( + "schema=ClientRequest|container=definitions|generated=AskForApproval2|base=AskForApproval", + "AskForApproval2", + ), + ( + "schema=ClientRequest|container=definitions|generated=NetworkAccess2|base=NetworkAccess", + "NetworkAccess2", + ), + ( + "schema=ClientRequest|container=definitions|generated=ReadOnlyAccess2|base=ReadOnlyAccess", + "ReadOnlyAccess2", + ), + ( + "schema=ClientRequest|container=definitions|generated=SandboxMode2|base=SandboxMode", + "SandboxMode2", + ), + ( + "schema=ClientRequest|container=definitions|generated=SandboxPolicy2|base=SandboxPolicy", + "SandboxPolicy2", + ), + ( + "schema=ServerNotification|container=definitions|generated=ByteRange2|base=ByteRange", + "ByteRange2", + ), + ( + "schema=ServerNotification|container=definitions|generated=CodexErrorInfo2|base=CodexErrorInfo", + "CodexErrorInfo2", + ), + ( + "schema=ServerNotification|container=definitions|generated=CreditsSnapshot2|base=CreditsSnapshot", + "CreditsSnapshot2", + ), + ( + "schema=ServerNotification|container=definitions|generated=MessagePhase2|base=MessagePhase", + "MessagePhase2", + ), + ( + "schema=ServerNotification|container=definitions|generated=ModelRerouteReason2|base=ModelRerouteReason", + "ModelRerouteReason2", + ), + ( + "schema=ServerNotification|container=definitions|generated=PatchApplyStatus2|base=PatchApplyStatus", + "PatchApplyStatus2", + ), + ( + "schema=ServerNotification|container=definitions|generated=RateLimitSnapshot2|base=RateLimitSnapshot", + "RateLimitSnapshot2", + ), + ( + "schema=ServerNotification|container=definitions|generated=RateLimitWindow2|base=RateLimitWindow", + "RateLimitWindow2", + ), + ( + "schema=ServerNotification|container=definitions|generated=TextElement2|base=TextElement", + "TextElement2", + ), + ( + "schema=ServerNotification|container=definitions|generated=UserInput2|base=UserInput", + "UserInput2", + ), + ( + "schema=ServerNotification|container=definitions|generated=WebSearchAction2|base=WebSearchAction", + "WebSearchAction2", + ), + ]) + }); #[derive(Clone)] pub struct GeneratedSchema { @@ -950,6 +1033,7 @@ where let file_stem = name.trim(); let schema = schema_for!(T); let mut schema_value = serde_json::to_value(schema)?; + enforce_numbered_definition_collision_overrides(file_stem, &mut schema_value); annotate_schema(&mut schema_value, Some(file_stem)); // If the name looks like a namespaced path (e.g., "v2::Type"), mirror // the TypeScript layout and write to out_dir/v2/Type.json. Otherwise @@ -980,6 +1064,101 @@ where }) } +fn enforce_numbered_definition_collision_overrides(schema_name: &str, schema: &mut Value) { + for defs_key in ["definitions", "$defs"] { + let renames = { + let Some(defs) = schema.get(defs_key).and_then(Value::as_object) else { + continue; + }; + collect_numbered_definition_collision_renames(schema_name, defs_key, defs) + }; + + if renames.is_empty() { + continue; + } + + #[expect(clippy::expect_used)] + let defs = schema + .get_mut(defs_key) + .and_then(Value::as_object_mut) + .expect("definition map should still be present"); + for (old_name, new_name, collision_key) in &renames { + if old_name == new_name { + continue; + } + assert!( + !defs.contains_key(new_name), + "Numbered definition collision override produced duplicate definition {new_name} for {collision_key}", + ); + let schema_value = defs.remove(old_name).unwrap_or_else(|| { + panic!("Missing generated numbered definition {old_name} for {collision_key}") + }); + defs.insert(new_name.clone(), schema_value); + } + + for (old_name, new_name, _) in renames { + if old_name != new_name { + rewrite_named_local_ref(schema, defs_key, &old_name, &new_name); + } + } + } +} + +fn collect_numbered_definition_collision_renames( + schema_name: &str, + defs_key: &str, + defs: &Map, +) -> Vec<(String, String, String)> { + let mut renames = Vec::new(); + + for generated_name in defs.keys() { + let base_name = generated_name.trim_end_matches(|c: char| c.is_ascii_digit()); + if base_name == generated_name || !defs.contains_key(base_name) { + continue; + } + + let collision_key = format!( + "schema={schema_name}|container={defs_key}|generated={generated_name}|base={base_name}" + ); + let replacement = NUMBERED_DEFINITION_COLLISION_OVERRIDES + .get(collision_key.as_str()) + .map(|value| (*value).to_string()) + .unwrap_or_else(|| { + panic!("Missing numbered definition collision override for {collision_key}") + }); + renames.push((generated_name.clone(), replacement, collision_key)); + } + + renames +} + +fn rewrite_named_local_ref(value: &mut Value, defs_key: &str, old_name: &str, new_name: &str) { + let direct = format!("#/{defs_key}/{old_name}"); + let prefixed = format!("{direct}/"); + let replacement = format!("#/{defs_key}/{new_name}"); + let replacement_prefixed = format!("{replacement}/"); + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get_mut("$ref") { + if reference == &direct { + *reference = replacement; + } else if let Some(rest) = reference.strip_prefix(&prefixed) { + *reference = format!("{replacement_prefixed}{rest}"); + } + } + for child in obj.values_mut() { + rewrite_named_local_ref(child, defs_key, old_name, new_name); + } + } + Value::Array(items) => { + for child in items { + rewrite_named_local_ref(child, defs_key, old_name, new_name); + } + } + _ => {} + } +} + pub(crate) fn write_json_schema(out_dir: &Path, name: &str) -> Result where T: JsonSchema, @@ -1198,10 +1377,20 @@ fn annotate_variant_list(variants: &mut [Value], base: Option<&str>) { && let Some(name) = variant_definition_name(base_name, variant) { let mut candidate = name.clone(); - let mut index = 2; - while seen.contains(&candidate) { - candidate = format!("{name}{index}"); - index += 1; + if seen.contains(&candidate) { + let collision_key = variant_title_collision_key(base_name, &name, variant); + candidate = VARIANT_TITLE_COLLISION_OVERRIDES + .get(collision_key.as_str()) + .map(|value| (*value).to_string()) + .unwrap_or_else(|| { + panic!( + "Missing variant title collision override for {collision_key} (generated name: {name})" + ) + }); + assert!( + !seen.contains(&candidate), + "Variant title collision override produced duplicate title {candidate} for {collision_key}", + ); } if let Some(obj) = variant.as_object_mut() { obj.insert("title".into(), Value::String(candidate.clone())); @@ -1221,6 +1410,48 @@ fn annotate_variant_list(variants: &mut [Value], base: Option<&str>) { } } +fn variant_title_collision_key(base: &str, generated_name: &str, variant: &Value) -> String { + let mut parts = vec![ + format!("base={base}"), + format!("generated={generated_name}"), + ]; + + if let Some(props) = variant.get("properties").and_then(Value::as_object) { + for key in DISCRIMINATOR_KEYS { + if let Some(value) = literal_from_property(props, key) { + parts.push(format!("{key}={value}")); + } + } + for (key, value) in props { + if DISCRIMINATOR_KEYS.contains(&key.as_str()) { + continue; + } + if let Some(literal) = string_literal(value) { + parts.push(format!("literal:{key}={literal}")); + } + } + + if props.len() == 1 + && let Some(key) = props.keys().next() + { + parts.push(format!("only_property={key}")); + } + } + + if let Some(required) = variant.get("required").and_then(Value::as_array) + && required.len() == 1 + && let Some(key) = required[0].as_str() + { + parts.push(format!("required_only={key}")); + } + + if parts.len() == 2 { + parts.push(format!("variant={variant}")); + } + + parts.join("|") +} + const DISCRIMINATOR_KEYS: &[&str] = &["type", "method", "mode", "status", "role", "reason"]; fn set_discriminator_titles(props: &mut Map, owner: &str) { From 936e744c939071367d1c5e89cb8a7a211cc6c18c Mon Sep 17 00:00:00 2001 From: natea-oai Date: Fri, 20 Feb 2026 18:26:57 -0800 Subject: [PATCH 038/385] Add field to Thread object for the latest rename set for a given thread (#12301) Exposes through the app server updated names set for a thread. This enables other surfaces to use the core as the source of truth for thread naming. `threadName` is gathered using the helper functions used to interact with `session_index.jsonl`, and is hydrated in: - `thread/list` - `thread/read` - `thread/resume` - `thread/unarchive` - `thread/rollback` We don't do this for `thread/start` and `thread/fork`. --- .../schema/json/ServerNotification.json | 7 + .../codex_app_server_protocol.schemas.json | 7 + .../schema/json/v2/ThreadForkResponse.json | 7 + .../schema/json/v2/ThreadListResponse.json | 7 + .../schema/json/v2/ThreadReadResponse.json | 7 + .../schema/json/v2/ThreadResumeResponse.json | 7 + .../json/v2/ThreadRollbackResponse.json | 7 + .../schema/json/v2/ThreadStartResponse.json | 7 + .../json/v2/ThreadStartedNotification.json | 7 + .../json/v2/ThreadUnarchiveResponse.json | 7 + .../schema/typescript/v2/Thread.ts | 4 + .../app-server-protocol/src/protocol/v2.rs | 2 + .../app-server/src/bespoke_event_handling.rs | 14 ++ .../app-server/src/codex_message_processor.rs | 60 ++++++- codex-rs/app-server/src/thread_status.rs | 1 + .../app-server/tests/common/mcp_process.rs | 10 ++ .../app-server/tests/suite/v2/thread_fork.rs | 24 +++ .../app-server/tests/suite/v2/thread_read.rs | 156 ++++++++++++++++++ .../tests/suite/v2/thread_rollback.rs | 14 ++ .../app-server/tests/suite/v2/thread_start.rs | 24 +++ .../tests/suite/v2/thread_unarchive.rs | 14 ++ 21 files changed, 386 insertions(+), 7 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 6a6bf2d7c7..1df0a8b05c 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -6736,6 +6736,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 313c3e62b3..4b1728512e 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -15553,6 +15553,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index dad39a512a..55480c5bc7 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -836,6 +836,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index 80a1d42a23..9e4e4d63b4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -609,6 +609,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index a4810d5850..acb80dd56f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -609,6 +609,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index c4e1df8478..884930d4d6 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -836,6 +836,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index f8cdcd744c..555083baf2 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -609,6 +609,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 099a65d219..2acd4da8fb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -836,6 +836,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index 9927bb2f3c..a39ec5151c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -609,6 +609,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index 011a97a34c..e18582f069 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -609,6 +609,13 @@ "description": "Model provider used for this thread (for example, 'openai').", "type": "string" }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, "path": { "description": "[UNSTABLE] Path to the thread on disk.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts index 5e7a6b7af4..ee07081dca 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts @@ -55,6 +55,10 @@ agentRole: string | null, * Optional Git metadata captured when the thread was created. */ gitInfo: GitInfo | null, +/** + * Optional user-facing thread title. + */ +name: string | null, /** * Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` * (when `includeTurns` is true) responses. diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 833e628214..4b3ffaf02f 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2277,6 +2277,8 @@ pub struct Thread { pub agent_role: Option, /// Optional Git metadata captured when the thread was created. pub git_info: Option, + /// Optional user-facing thread title. + pub name: Option, /// Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` /// (when `includeTurns` is true) responses. /// For all other responses and notifications returning a Thread, diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index fca2bcc1c1..f53b10b843 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -75,6 +75,7 @@ use codex_app_server_protocol::build_turns_from_rollout_items; use codex_app_server_protocol::convert_patch_changes; use codex_core::CodexThread; use codex_core::ThreadManager; +use codex_core::find_thread_name_by_id; use codex_core::parse_command::shlex_join; use codex_core::protocol::ApplyPatchApprovalRequestEvent; use codex_core::protocol::CodexErrorInfo as CoreCodexErrorInfo; @@ -99,11 +100,13 @@ use codex_protocol::request_user_input::RequestUserInputAnswer as CoreRequestUse use codex_protocol::request_user_input::RequestUserInputResponse as CoreRequestUserInputResponse; use std::collections::HashMap; use std::convert::TryFrom; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use tokio::sync::Mutex; use tokio::sync::oneshot; use tracing::error; +use tracing::warn; type JsonValue = serde_json::Value; @@ -129,6 +132,7 @@ pub(crate) async fn apply_bespoke_event_handling( thread_watch_manager: ThreadWatchManager, api_version: ApiVersion, fallback_model_provider: String, + codex_home: &Path, ) { let Event { id: event_turn_id, @@ -1224,6 +1228,16 @@ pub(crate) async fn apply_bespoke_event_handling( thread.status = thread_watch_manager .loaded_status_for_thread(&thread.id) .await; + match find_thread_name_by_id(codex_home, &conversation_id).await { + Ok(name) => { + thread.name = name; + } + Err(err) => { + warn!( + "Failed to read thread name for {conversation_id}: {err}" + ); + } + } ThreadRollbackResponse { thread } } Err(err) => { diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 65b7f1ecb7..72dc7eaea2 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -202,6 +202,8 @@ use codex_core::features::FEATURES; use codex_core::features::Feature; use codex_core::features::Stage; use codex_core::find_archived_thread_path_by_id_str; +use codex_core::find_thread_name_by_id; +use codex_core::find_thread_names_by_ids; use codex_core::find_thread_path_by_id_str; use codex_core::git_info::git_diff_to_remote; use codex_core::mcp::collect_mcp_snapshot; @@ -2374,6 +2376,7 @@ impl CodexMessageProcessor { .thread_watch_manager .loaded_status_for_thread(&thread.id) .await; + self.attach_thread_name(thread_id, &mut thread).await; let thread_id = thread.id.clone(); let response = ThreadUnarchiveResponse { thread }; self.outgoing.send_response(request_id, response).await; @@ -2544,18 +2547,36 @@ impl CodexMessageProcessor { return; } }; + let mut threads = Vec::with_capacity(summaries.len()); + let mut thread_ids = HashSet::with_capacity(summaries.len()); + let mut status_ids = Vec::with_capacity(summaries.len()); + + for summary in summaries { + let conversation_id = summary.conversation_id; + thread_ids.insert(conversation_id); + + let thread = summary_to_thread(summary); + status_ids.push(thread.id.clone()); + threads.push((conversation_id, thread)); + } + + let names = match find_thread_names_by_ids(&self.config.codex_home, &thread_ids).await { + Ok(names) => names, + Err(err) => { + warn!("Failed to read thread names: {err}"); + HashMap::new() + } + }; - let data = summaries - .into_iter() - .map(summary_to_thread) - .collect::>(); let statuses = self .thread_watch_manager - .loaded_statuses_for_threads(data.iter().map(|thread| thread.id.clone()).collect()) + .loaded_statuses_for_threads(status_ids) .await; - let data = data + + let data = threads .into_iter() - .map(|mut thread| { + .map(|(conversation_id, mut thread)| { + thread.name = names.get(&conversation_id).cloned(); if let Some(status) = statuses.get(&thread.id) { thread.status = status.clone(); } @@ -2717,6 +2738,7 @@ impl CodexMessageProcessor { } build_thread_from_snapshot(thread_uuid, &config_snapshot, loaded_rollout_path) }; + self.attach_thread_name(thread_uuid, &mut thread).await; if include_turns && let Some(rollout_path) = rollout_path.as_ref() { match read_rollout_items_from_rollout(rollout_path).await { @@ -3206,6 +3228,7 @@ impl CodexMessageProcessor { match read_rollout_items_from_rollout(rollout_path).await { Ok(items) => { thread.turns = build_turns_from_rollout_items(&items); + self.attach_thread_name(thread_id, &mut thread).await; Some(thread) } Err(err) => { @@ -3222,6 +3245,17 @@ impl CodexMessageProcessor { } } + async fn attach_thread_name(&self, thread_id: ThreadId, thread: &mut Thread) { + match find_thread_name_by_id(&self.config.codex_home, &thread_id).await { + Ok(name) => { + thread.name = name; + } + Err(err) => { + warn!("Failed to read thread name for {thread_id}: {err}"); + } + } + } + async fn thread_fork(&mut self, request_id: ConnectionRequestId, params: ThreadForkParams) { let ThreadForkParams { thread_id, @@ -3419,6 +3453,7 @@ impl CodexMessageProcessor { return; } }; + // forked thread names do not inherit the source thread name match read_rollout_items_from_rollout(rollout_path.as_path()).await { Ok(items) => { thread.turns = build_turns_from_rollout_items(&items); @@ -5823,6 +5858,7 @@ impl CodexMessageProcessor { let thread_watch_manager = self.thread_watch_manager.clone(); let fallback_model_provider = self.config.model_provider_id.clone(); let single_client_mode = self.single_client_mode; + let codex_home = self.config.codex_home.clone(); tokio::spawn(async move { loop { tokio::select! { @@ -5903,6 +5939,7 @@ impl CodexMessageProcessor { thread_watch_manager.clone(), api_version, fallback_model_provider.clone(), + codex_home.as_path(), ) .await; } @@ -5916,6 +5953,7 @@ impl CodexMessageProcessor { ) => { handle_pending_thread_resume_request( conversation_id, + codex_home.as_path(), &thread_state, &thread_watch_manager, &outgoing_for_task, @@ -6235,6 +6273,7 @@ impl CodexMessageProcessor { async fn handle_pending_thread_resume_request( conversation_id: ThreadId, + codex_home: &Path, thread_state: &Arc>, thread_watch_manager: &ThreadWatchManager, outgoing: &Arc, @@ -6274,6 +6313,11 @@ async fn handle_pending_thread_resume_request( .loaded_status_for_thread(&thread.id) .await; + match find_thread_name_by_id(codex_home, &conversation_id).await { + Ok(thread_name) => thread.name = thread_name, + Err(err) => warn!("Failed to read thread name for {conversation_id}: {err}"), + } + let ThreadConfigSnapshot { model, model_provider_id, @@ -6994,6 +7038,7 @@ fn build_thread_from_snapshot( agent_role: config_snapshot.session_source.get_agent_role(), source: config_snapshot.session_source.clone().into(), git_info: None, + name: None, turns: Vec::new(), } } @@ -7034,6 +7079,7 @@ pub(crate) fn summary_to_thread(summary: ConversationSummary) -> Thread { agent_role: source.get_agent_role(), source: source.into(), git_info, + name: None, turns: Vec::new(), } } diff --git a/codex-rs/app-server/src/thread_status.rs b/codex-rs/app-server/src/thread_status.rs index 301c4b1d07..48e3d9ab08 100644 --- a/codex-rs/app-server/src/thread_status.rs +++ b/codex-rs/app-server/src/thread_status.rs @@ -626,6 +626,7 @@ mod tests { agent_role: None, source, git_info: None, + name: None, turns: Vec::new(), } } diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index 249a280213..4e48f909b3 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -59,6 +59,7 @@ use codex_app_server_protocol::ThreadLoadedListParams; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadResumeParams; use codex_app_server_protocol::ThreadRollbackParams; +use codex_app_server_protocol::ThreadSetNameParams; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadUnarchiveParams; use codex_app_server_protocol::TurnCompletedNotification; @@ -418,6 +419,15 @@ impl McpProcess { self.send_request("thread/archive", params).await } + /// Send a `thread/name/set` JSON-RPC request. + pub async fn send_thread_set_name_request( + &mut self, + params: ThreadSetNameParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("thread/name/set", params).await + } + /// Send a `thread/unarchive` JSON-RPC request. pub async fn send_thread_unarchive_request( &mut self, diff --git a/codex-rs/app-server/tests/suite/v2/thread_fork.rs b/codex-rs/app-server/tests/suite/v2/thread_fork.rs index 7047622a44..a6f9942171 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -18,6 +18,7 @@ use codex_app_server_protocol::ThreadStatus; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput; use pretty_assertions::assert_eq; +use serde_json::Value; use std::path::Path; use tempfile::TempDir; use tokio::time::timeout; @@ -70,8 +71,20 @@ async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> { mcp.read_stream_until_response_message(RequestId::Integer(fork_id)), ) .await??; + let fork_result = fork_resp.result.clone(); let ThreadForkResponse { thread, .. } = to_response::(fork_resp)?; + // Wire contract: thread title field is `name`, serialized as null when unset. + let thread_json = fork_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/fork result.thread must be an object"); + assert_eq!( + thread_json.get("name"), + Some(&Value::Null), + "forked threads do not inherit a name; expected `name: null`" + ); + let after_contents = std::fs::read_to_string(&original_path)?; assert_eq!( after_contents, original_contents, @@ -87,6 +100,7 @@ async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> { assert_ne!(thread_path, original_path); assert!(thread.cwd.is_absolute()); assert_eq!(thread.source, SessionSource::VsCode); + assert_eq!(thread.name, None); assert_eq!( thread.turns.len(), @@ -115,6 +129,16 @@ async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> { mcp.read_stream_until_notification_message("thread/started"), ) .await??; + let started_params = notif.params.clone().expect("params must be present"); + let started_thread_json = started_params + .get("thread") + .and_then(Value::as_object) + .expect("thread/started params.thread must be an object"); + assert_eq!( + started_thread_json.get("name"), + Some(&Value::Null), + "thread/started must serialize `name: null` when unset" + ); let started: ThreadStartedNotification = serde_json::from_value(notif.params.expect("params must be present"))?; assert_eq!(started.thread, thread); diff --git a/codex-rs/app-server/tests/suite/v2/thread_read.rs b/codex-rs/app-server/tests/suite/v2/thread_read.rs index 5a6925bcb8..384aad6c86 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_read.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_read.rs @@ -8,8 +8,14 @@ use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SessionSource; use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadListParams; +use codex_app_server_protocol::ThreadListResponse; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadReadResponse; +use codex_app_server_protocol::ThreadResumeParams; +use codex_app_server_protocol::ThreadResumeResponse; +use codex_app_server_protocol::ThreadSetNameParams; +use codex_app_server_protocol::ThreadSetNameResponse; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::ThreadStatus; @@ -21,6 +27,7 @@ use codex_protocol::user_input::ByteRange; use codex_protocol::user_input::TextElement; use core_test_support::responses; use pretty_assertions::assert_eq; +use serde_json::Value; use std::path::Path; use std::path::PathBuf; use tempfile::TempDir; @@ -192,6 +199,155 @@ async fn thread_read_loaded_thread_returns_precomputed_path_before_materializati Ok(()) } +#[tokio::test] +async fn thread_name_set_is_reflected_in_read_list_and_resume() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let preview = "Saved user message"; + let conversation_id = create_fake_rollout_with_text_elements( + codex_home.path(), + "2025-01-05T12-00-00", + "2025-01-05T12:00:00Z", + preview, + vec![], + Some("mock_provider"), + None, + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + // `thread/name/set` operates on loaded threads (via ThreadManager). A rollout existing on disk + // is not enough; we must `thread/resume` first to load it into the running server. + let pre_resume_id = mcp + .send_thread_resume_request(ThreadResumeParams { + thread_id: conversation_id.clone(), + ..Default::default() + }) + .await?; + let pre_resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(pre_resume_id)), + ) + .await??; + let ThreadResumeResponse { + thread: pre_resumed, + .. + } = to_response::(pre_resume_resp)?; + assert_eq!(pre_resumed.id, conversation_id); + + // Set a user-facing thread title. + let new_name = "My renamed thread"; + let set_id = mcp + .send_thread_set_name_request(ThreadSetNameParams { + thread_id: conversation_id.clone(), + name: new_name.to_string(), + }) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let _: ThreadSetNameResponse = to_response::(set_resp)?; + + // Read should now surface `thread.name`, and the wire payload must include `name`. + let read_id = mcp + .send_thread_read_request(ThreadReadParams { + thread_id: conversation_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 read_result = read_resp.result.clone(); + let ThreadReadResponse { thread } = to_response::(read_resp)?; + assert_eq!(thread.id, conversation_id); + assert_eq!(thread.name.as_deref(), Some(new_name)); + let thread_json = read_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/read result.thread must be an object"); + assert_eq!( + thread_json.get("name").and_then(Value::as_str), + Some(new_name), + "thread/read must serialize `thread.name` on the wire" + ); + + // List should also surface the name. + let list_id = mcp + .send_thread_list_request(ThreadListParams { + cursor: None, + limit: Some(50), + sort_key: None, + model_providers: Some(vec!["mock_provider".to_string()]), + source_kinds: None, + archived: None, + cwd: None, + }) + .await?; + let list_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(list_id)), + ) + .await??; + let list_result = list_resp.result.clone(); + let ThreadListResponse { data, .. } = to_response::(list_resp)?; + let listed = data + .iter() + .find(|t| t.id == conversation_id) + .expect("thread/list should include the created thread"); + assert_eq!(listed.name.as_deref(), Some(new_name)); + let listed_json = list_result + .get("data") + .and_then(Value::as_array) + .expect("thread/list result.data must be an array") + .iter() + .find(|t| t.get("id").and_then(Value::as_str) == Some(&conversation_id)) + .and_then(Value::as_object) + .expect("thread/list should include the created thread as an object"); + assert_eq!( + listed_json.get("name").and_then(Value::as_str), + Some(new_name), + "thread/list must serialize `thread.name` on the wire" + ); + + // Resume should also surface the name. + let resume_id = mcp + .send_thread_resume_request(ThreadResumeParams { + thread_id: conversation_id.clone(), + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let resume_result = resume_resp.result.clone(); + let ThreadResumeResponse { + thread: resumed, .. + } = to_response::(resume_resp)?; + assert_eq!(resumed.id, conversation_id); + assert_eq!(resumed.name.as_deref(), Some(new_name)); + let resumed_json = resume_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/resume result.thread must be an object"); + assert_eq!( + resumed_json.get("name").and_then(Value::as_str), + Some(new_name), + "thread/resume must serialize `thread.name` on the wire" + ); + + Ok(()) +} + #[tokio::test] async fn thread_read_include_turns_rejects_unmaterialized_loaded_thread() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; diff --git a/codex-rs/app-server/tests/suite/v2/thread_rollback.rs b/codex-rs/app-server/tests/suite/v2/thread_rollback.rs index 47a3587281..3487b9e36a 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_rollback.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_rollback.rs @@ -16,6 +16,7 @@ use codex_app_server_protocol::ThreadStatus; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::UserInput as V2UserInput; use pretty_assertions::assert_eq; +use serde_json::Value; use tempfile::TempDir; use tokio::time::timeout; @@ -107,10 +108,23 @@ async fn thread_rollback_drops_last_turns_and_persists_to_rollout() -> Result<() mcp.read_stream_until_response_message(RequestId::Integer(rollback_id)), ) .await??; + let rollback_result = rollback_resp.result.clone(); let ThreadRollbackResponse { thread: rolled_back_thread, } = to_response::(rollback_resp)?; + // Wire contract: thread title field is `name`, serialized as null when unset. + let thread_json = rollback_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/rollback result.thread must be an object"); + assert_eq!(rolled_back_thread.name, None); + assert_eq!( + thread_json.get("name"), + Some(&Value::Null), + "thread/rollback must serialize `name: null` when unset" + ); + assert_eq!(rolled_back_thread.turns.len(), 1); assert_eq!(rolled_back_thread.status, ThreadStatus::Idle); assert_eq!(rolled_back_thread.turns[0].items.len(), 2); diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index bcee63df95..4e63d4c546 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -13,6 +13,7 @@ use codex_app_server_protocol::ThreadStatus; use codex_core::config::set_project_trust_level; use codex_protocol::config_types::TrustLevel; use codex_protocol::openai_models::ReasoningEffort; +use serde_json::Value; use std::path::Path; use tempfile::TempDir; use tokio::time::timeout; @@ -45,6 +46,7 @@ async fn thread_start_creates_thread_and_emits_started() -> Result<()> { mcp.read_stream_until_response_message(RequestId::Integer(req_id)), ) .await??; + let resp_result = resp.result.clone(); let ThreadStartResponse { thread, model_provider, @@ -68,12 +70,34 @@ async fn thread_start_creates_thread_and_emits_started() -> Result<()> { "fresh thread rollout should not be materialized until first user message" ); + // Wire contract: thread title field is `name`, serialized as null when unset. + let thread_json = resp_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/start result.thread must be an object"); + assert_eq!( + thread_json.get("name"), + Some(&Value::Null), + "new threads should serialize `name: null`" + ); + assert_eq!(thread.name, None); + // A corresponding thread/started notification should arrive. let notif: JSONRPCNotification = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("thread/started"), ) .await??; + let started_params = notif.params.clone().expect("params must be present"); + let started_thread_json = started_params + .get("thread") + .and_then(Value::as_object) + .expect("thread/started params.thread must be an object"); + assert_eq!( + started_thread_json.get("name"), + Some(&Value::Null), + "thread/started should serialize `name: null` for new threads" + ); let started: ThreadStartedNotification = serde_json::from_value(notif.params.expect("params must be present"))?; assert_eq!(started.thread, thread); diff --git a/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs b/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs index 35de7eee91..b2ae60ae35 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs @@ -18,6 +18,7 @@ use codex_app_server_protocol::UserInput; use codex_core::find_archived_thread_path_by_id_str; use codex_core::find_thread_path_by_id_str; use pretty_assertions::assert_eq; +use serde_json::Value; use std::fs::FileTimes; use std::fs::OpenOptions; use std::path::Path; @@ -120,6 +121,7 @@ async fn thread_unarchive_moves_rollout_back_into_sessions_directory() -> Result mcp.read_stream_until_response_message(RequestId::Integer(unarchive_id)), ) .await??; + let unarchive_result = unarchive_resp.result.clone(); let ThreadUnarchiveResponse { thread: unarchived_thread, } = to_response::(unarchive_resp)?; @@ -140,6 +142,18 @@ async fn thread_unarchive_moves_rollout_back_into_sessions_directory() -> Result ); assert_eq!(unarchived_thread.status, ThreadStatus::NotLoaded); + // Wire contract: thread title field is `name`, serialized as null when unset. + let thread_json = unarchive_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/unarchive result.thread must be an object"); + assert_eq!(unarchived_thread.name, None); + assert_eq!( + thread_json.get("name"), + Some(&Value::Null), + "thread/unarchive must serialize `name: null` when unset" + ); + let rollout_path_display = rollout_path.display(); assert!( rollout_path.exists(), From 6817f0be8aaa6e7215a044ca9462eb6eeece6c53 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 20 Feb 2026 19:06:35 -0800 Subject: [PATCH 039/385] Wire realtime api to core (#12268) - Introduce `RealtimeConversationManager` for realtime API management - Add `op::conversation` to start conversation, insert audio, insert text, and close conversation. - emit conversation lifecycle and realtime events. - Move shared realtime payload types into codex-protocol and add core e2e websocket tests for start/replace/transport-close paths. Things to consider: - Should we use the same `op::` and `Events` channel to carry audio? I think we should try this simple approach and later we can create separate one if the channels got congested. - Sending text updates to the client: we can start simple and later restrict that. - Provider auth isn't wired for now intentionally --- .../schema/json/EventMsg.json | 248 ++++++++++++ .../schema/json/ServerNotification.json | 181 +++++++++ .../codex_app_server_protocol.schemas.json | 181 +++++++++ .../json/v1/ForkConversationResponse.json | 181 +++++++++ .../json/v1/ResumeConversationResponse.json | 181 +++++++++ .../v1/SessionConfiguredNotification.json | 181 +++++++++ .../schema/typescript/EventMsg.ts | 5 +- .../schema/typescript/RealtimeAudioFrame.ts | 5 + .../RealtimeConversationClosedEvent.ts | 5 + .../RealtimeConversationRealtimeEvent.ts | 6 + .../RealtimeConversationStartedEvent.ts | 5 + .../schema/typescript/RealtimeEvent.ts | 7 + .../schema/typescript/index.ts | 5 + .../endpoint/realtime_websocket/methods.rs | 9 +- .../src/endpoint/realtime_websocket/mod.rs | 4 +- .../endpoint/realtime_websocket/protocol.rs | 22 +- codex-rs/codex-api/src/lib.rs | 4 +- .../codex-api/tests/realtime_websocket_e2e.rs | 16 +- codex-rs/core/src/codex.rs | 43 ++- codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/realtime_conversation.rs | 354 +++++++++++++++++ codex-rs/core/src/rollout/policy.rs | 3 + codex-rs/core/tests/suite/mod.rs | 1 + .../core/tests/suite/realtime_conversation.rs | 360 ++++++++++++++++++ .../src/event_processor_with_human_output.rs | 3 + codex-rs/mcp-server/src/codex_tool_runner.rs | 3 + codex-rs/protocol/src/protocol.rs | 127 ++++++ codex-rs/tui/src/chatwidget.rs | 3 + 28 files changed, 2102 insertions(+), 42 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts create mode 100644 codex-rs/core/src/realtime_conversation.rs create mode 100644 codex-rs/core/tests/suite/realtime_conversation.rs diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index 33f58d18b1..518d650208 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -556,6 +556,73 @@ "title": "WarningEventMsg", "type": "object" }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, { "description": "Model routing changed from the requested model to a different model.", "properties": { @@ -3856,6 +3923,120 @@ } ] }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionCreated": { + "properties": { + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionCreated" + ], + "title": "SessionCreatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "backend_prompt": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ @@ -5620,6 +5801,73 @@ "title": "WarningEventMsg", "type": "object" }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, { "description": "Model routing changed from the requested model to a different model.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 1df0a8b05c..51c445bf14 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1372,6 +1372,73 @@ "title": "WarningEventMsg", "type": "object" }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, { "description": "Model routing changed from the requested model to a different model.", "properties": { @@ -5176,6 +5243,120 @@ } ] }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionCreated": { + "properties": { + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionCreated" + ], + "title": "SessionCreatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "backend_prompt": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 4b1728512e..2c1eb40316 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -2611,6 +2611,73 @@ "title": "WarningEventMsg", "type": "object" }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, { "description": "Model routing changed from the requested model to a different model.", "properties": { @@ -7027,6 +7094,120 @@ } ] }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionCreated": { + "properties": { + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionCreated" + ], + "title": "SessionCreatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "backend_prompt": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json index f88d5f741b..70521ec729 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json @@ -556,6 +556,73 @@ "title": "WarningEventMsg", "type": "object" }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, { "description": "Model routing changed from the requested model to a different model.", "properties": { @@ -3856,6 +3923,120 @@ } ] }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionCreated": { + "properties": { + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionCreated" + ], + "title": "SessionCreatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "backend_prompt": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json index e619dfe126..3ce7593460 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json @@ -556,6 +556,73 @@ "title": "WarningEventMsg", "type": "object" }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, { "description": "Model routing changed from the requested model to a different model.", "properties": { @@ -3856,6 +3923,120 @@ } ] }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionCreated": { + "properties": { + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionCreated" + ], + "title": "SessionCreatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "backend_prompt": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json b/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json index 61887b4007..a3010337bb 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json @@ -556,6 +556,73 @@ "title": "WarningEventMsg", "type": "object" }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, { "description": "Model routing changed from the requested model to a different model.", "properties": { @@ -3856,6 +3923,120 @@ } ] }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionCreated": { + "properties": { + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionCreated" + ], + "title": "SessionCreatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "backend_prompt": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ diff --git a/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts b/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts index 5ed3ca2529..3aa06058e0 100644 --- a/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts +++ b/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts @@ -47,6 +47,9 @@ import type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent"; import type { PatchApplyEndEvent } from "./PatchApplyEndEvent"; import type { PlanDeltaEvent } from "./PlanDeltaEvent"; import type { RawResponseItemEvent } from "./RawResponseItemEvent"; +import type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent"; +import type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent"; +import type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent"; import type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent"; import type { ReasoningRawContentDeltaEvent } from "./ReasoningRawContentDeltaEvent"; import type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent"; @@ -75,4 +78,4 @@ import type { WebSearchEndEvent } from "./WebSearchEndEvent"; * Response event from the agent * NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen. */ -export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent; +export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "realtime_conversation_started" } & RealtimeConversationStartedEvent | { "type": "realtime_conversation_realtime" } & RealtimeConversationRealtimeEvent | { "type": "realtime_conversation_closed" } & RealtimeConversationClosedEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts new file mode 100644 index 0000000000..99c0c1063c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RealtimeAudioFrame = { data: string, sample_rate: number, num_channels: number, samples_per_channel: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts new file mode 100644 index 0000000000..c73e6833ae --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RealtimeConversationClosedEvent = { reason: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts new file mode 100644 index 0000000000..4ff24a8281 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RealtimeEvent } from "./RealtimeEvent"; + +export type RealtimeConversationRealtimeEvent = { payload: RealtimeEvent, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts new file mode 100644 index 0000000000..f2894fcb1e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RealtimeConversationStartedEvent = { session_id: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts new file mode 100644 index 0000000000..6297beebef --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RealtimeAudioFrame } from "./RealtimeAudioFrame"; +import type { JsonValue } from "./serde_json/JsonValue"; + +export type RealtimeEvent = { "SessionCreated": { session_id: string, } } | { "SessionUpdated": { backend_prompt: string | null, } } | { "AudioOut": RealtimeAudioFrame } | { "ConversationItemAdded": JsonValue } | { "Error": string }; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index cda04def82..30197f8922 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -148,6 +148,11 @@ export type { RateLimitSnapshot } from "./RateLimitSnapshot"; export type { RateLimitWindow } from "./RateLimitWindow"; export type { RawResponseItemEvent } from "./RawResponseItemEvent"; export type { ReadOnlyAccess } from "./ReadOnlyAccess"; +export type { RealtimeAudioFrame } from "./RealtimeAudioFrame"; +export type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent"; +export type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent"; +export type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent"; +export type { RealtimeEvent } from "./RealtimeEvent"; export type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent"; export type { ReasoningEffort } from "./ReasoningEffort"; export type { ReasoningItem } from "./ReasoningItem"; diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs index e9a297de07..48cc1d7002 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs @@ -372,7 +372,8 @@ impl RealtimeWebsocketClient { default_headers: HeaderMap, ) -> Result { ensure_rustls_crypto_provider(); - let ws_url = websocket_url_from_api_url(config.api_url.as_str())?; + // Keep provider base_url semantics aligned with HTTP clients; derive the ws endpoint here. + let ws_url = websocket_url_from_api_url(self.provider.base_url.as_str())?; let mut request = ws_url .as_str() @@ -638,7 +639,7 @@ mod tests { let provider = Provider { name: "test".to_string(), - base_url: "http://localhost".to_string(), + base_url: format!("http://{addr}"), query_params: Some(HashMap::new()), headers: HeaderMap::new(), retry: crate::provider::RetryConfig { @@ -654,7 +655,6 @@ mod tests { let connection = client .connect( RealtimeSessionConfig { - api_url: format!("ws://{addr}"), prompt: "backend prompt".to_string(), session_id: Some("conv_1".to_string()), }, @@ -765,7 +765,7 @@ mod tests { let provider = Provider { name: "test".to_string(), - base_url: "http://localhost".to_string(), + base_url: format!("http://{addr}"), query_params: Some(HashMap::new()), headers: HeaderMap::new(), retry: crate::provider::RetryConfig { @@ -781,7 +781,6 @@ mod tests { let connection = client .connect( RealtimeSessionConfig { - api_url: format!("ws://{addr}"), prompt: "backend prompt".to_string(), session_id: Some("conv_1".to_string()), }, diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs index 469fea8dcf..a89dbd3e77 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/mod.rs @@ -1,10 +1,10 @@ pub mod methods; pub mod protocol; +pub use codex_protocol::protocol::RealtimeAudioFrame; +pub use codex_protocol::protocol::RealtimeEvent; pub use methods::RealtimeWebsocketClient; pub use methods::RealtimeWebsocketConnection; pub use methods::RealtimeWebsocketEvents; pub use methods::RealtimeWebsocketWriter; -pub use protocol::RealtimeAudioFrame; -pub use protocol::RealtimeEvent; pub use protocol::RealtimeSessionConfig; diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs index db63f51795..f2f0616fc6 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs @@ -1,33 +1,15 @@ -use serde::Deserialize; +pub use codex_protocol::protocol::RealtimeAudioFrame; +pub use codex_protocol::protocol::RealtimeEvent; use serde::Serialize; use serde_json::Value; use tracing::debug; #[derive(Debug, Clone, PartialEq, Eq)] pub struct RealtimeSessionConfig { - pub api_url: String, pub prompt: String, pub session_id: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct RealtimeAudioFrame { - pub data: String, - pub sample_rate: u32, - pub num_channels: u16, - #[serde(skip_serializing_if = "Option::is_none")] - pub samples_per_channel: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum RealtimeEvent { - SessionCreated { session_id: String }, - SessionUpdated { backend_prompt: Option }, - AudioOut(RealtimeAudioFrame), - ConversationItemAdded(Value), - Error(String), -} - #[derive(Debug, Clone, Serialize)] #[serde(tag = "type")] pub(super) enum RealtimeOutboundMessage { diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs index ff8953c034..23c08d7e2b 100644 --- a/codex-rs/codex-api/src/lib.rs +++ b/codex-rs/codex-api/src/lib.rs @@ -29,8 +29,6 @@ pub use crate::endpoint::aggregate::AggregateStreamExt; pub use crate::endpoint::compact::CompactClient; pub use crate::endpoint::memories::MemoriesClient; pub use crate::endpoint::models::ModelsClient; -pub use crate::endpoint::realtime_websocket::RealtimeAudioFrame; -pub use crate::endpoint::realtime_websocket::RealtimeEvent; pub use crate::endpoint::realtime_websocket::RealtimeSessionConfig; pub use crate::endpoint::realtime_websocket::RealtimeWebsocketClient; pub use crate::endpoint::realtime_websocket::RealtimeWebsocketConnection; @@ -44,3 +42,5 @@ pub use crate::provider::is_azure_responses_wire_base_url; pub use crate::sse::stream_from_fixture; pub use crate::telemetry::SseTelemetry; pub use crate::telemetry::WebsocketTelemetry; +pub use codex_protocol::protocol::RealtimeAudioFrame; +pub use codex_protocol::protocol::RealtimeEvent; diff --git a/codex-rs/codex-api/tests/realtime_websocket_e2e.rs b/codex-rs/codex-api/tests/realtime_websocket_e2e.rs index 08d93b9145..ae8b082b93 100644 --- a/codex-rs/codex-api/tests/realtime_websocket_e2e.rs +++ b/codex-rs/codex-api/tests/realtime_websocket_e2e.rs @@ -50,10 +50,10 @@ where (addr, server) } -fn test_provider() -> Provider { +fn test_provider(base_url: String) -> Provider { Provider { name: "test".to_string(), - base_url: "http://localhost".to_string(), + base_url, query_params: Some(HashMap::new()), headers: HeaderMap::new(), retry: RetryConfig { @@ -124,11 +124,10 @@ async fn realtime_ws_e2e_session_create_and_event_flow() { }) .await; - let client = RealtimeWebsocketClient::new(test_provider()); + let client = RealtimeWebsocketClient::new(test_provider(format!("http://{addr}"))); let connection = client .connect( RealtimeSessionConfig { - api_url: format!("ws://{addr}"), prompt: "backend prompt".to_string(), session_id: Some("conv_123".to_string()), }, @@ -215,11 +214,10 @@ async fn realtime_ws_e2e_send_while_next_event_waits() { }) .await; - let client = RealtimeWebsocketClient::new(test_provider()); + let client = RealtimeWebsocketClient::new(test_provider(format!("http://{addr}"))); let connection = client .connect( RealtimeSessionConfig { - api_url: format!("ws://{addr}"), prompt: "backend prompt".to_string(), session_id: Some("conv_123".to_string()), }, @@ -277,11 +275,10 @@ async fn realtime_ws_e2e_disconnected_emitted_once() { }) .await; - let client = RealtimeWebsocketClient::new(test_provider()); + let client = RealtimeWebsocketClient::new(test_provider(format!("http://{addr}"))); let connection = client .connect( RealtimeSessionConfig { - api_url: format!("ws://{addr}"), prompt: "backend prompt".to_string(), session_id: Some("conv_123".to_string()), }, @@ -337,11 +334,10 @@ async fn realtime_ws_e2e_ignores_unknown_text_events() { }) .await; - let client = RealtimeWebsocketClient::new(test_provider()); + let client = RealtimeWebsocketClient::new(test_provider(format!("http://{addr}"))); let connection = client .connect( RealtimeSessionConfig { - api_url: format!("ws://{addr}"), prompt: "backend prompt".to_string(), session_id: Some("conv_123".to_string()), }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index fcddf4e83e..88e6fef893 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -30,6 +30,11 @@ use crate::features::maybe_push_unstable_features_warning; use crate::models_manager::manager::ModelsManager; use crate::parse_command::parse_command; use crate::parse_turn_item; +use crate::realtime_conversation::RealtimeConversationManager; +use crate::realtime_conversation::handle_audio as handle_realtime_conversation_audio; +use crate::realtime_conversation::handle_close as handle_realtime_conversation_close; +use crate::realtime_conversation::handle_start as handle_realtime_conversation_start; +use crate::realtime_conversation::handle_text as handle_realtime_conversation_text; use crate::rollout::session_index; use crate::stream_events_utils::HandleOutputCtx; use crate::stream_events_utils::handle_non_tool_response_item; @@ -282,7 +287,7 @@ pub struct CodexSpawnOk { } pub(crate) const INITIAL_SUBMIT_ID: &str = ""; -pub(crate) const SUBMISSION_CHANNEL_CAPACITY: usize = 64; +pub(crate) const SUBMISSION_CHANNEL_CAPACITY: usize = 512; const CYBER_VERIFY_URL: &str = "https://chatgpt.com/cyber"; const CYBER_SAFETY_URL: &str = "https://developers.openai.com/codex/concepts/cyber-safety"; @@ -523,11 +528,13 @@ pub(crate) struct Session { /// session. features: Features, pending_mcp_server_refresh_config: Mutex>, + pub(crate) conversation: Arc, pub(crate) active_turn: Mutex>, pub(crate) services: SessionServices, js_repl: Arc, next_internal_sub_id: AtomicU64, } + /// The context needed for a single turn of the thread. #[derive(Debug)] pub(crate) struct TurnContext { @@ -1357,6 +1364,7 @@ impl Session { state: Mutex::new(state), features: config.features.clone(), pending_mcp_server_refresh_config: Mutex::new(None), + conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), services, js_repl, @@ -1961,7 +1969,7 @@ impl Session { state.take_startup_regular_task() } - async fn get_config(&self) -> std::sync::Arc { + pub(crate) async fn get_config(&self) -> std::sync::Arc { let state = self.state.lock().await; state .session_configuration @@ -1969,6 +1977,11 @@ impl Session { .clone() } + pub(crate) async fn provider(&self) -> ModelProviderInfo { + let state = self.state.lock().await; + state.session_configuration.provider.clone() + } + pub(crate) async fn reload_user_config_layer(&self) { let config_toml_path = { let state = self.state.lock().await; @@ -3170,6 +3183,29 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv Op::CleanBackgroundTerminals => { handlers::clean_background_terminals(&sess).await; } + Op::RealtimeConversationStart(params) => { + if let Err(err) = + handle_realtime_conversation_start(&sess, sub.id.clone(), params).await + { + sess.send_event_raw(Event { + id: sub.id.clone(), + msg: EventMsg::Error(ErrorEvent { + message: err.to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + }), + }) + .await; + } + } + Op::RealtimeConversationAudio(params) => { + handle_realtime_conversation_audio(&sess, sub.id.clone(), params).await; + } + Op::RealtimeConversationText(params) => { + handle_realtime_conversation_text(&sess, sub.id.clone(), params).await; + } + Op::RealtimeConversationClose => { + handle_realtime_conversation_close(&sess, sub.id.clone()).await; + } Op::OverrideTurnContext { cwd, approval_policy, @@ -4015,6 +4051,7 @@ mod handlers { pub async fn shutdown(sess: &Arc, sub_id: String) -> bool { sess.abort_all_tasks(TurnAbortReason::Interrupted).await; + let _ = sess.conversation.shutdown().await; sess.services .unified_exec_manager .terminate_all_processes() @@ -7467,6 +7504,7 @@ mod tests { state: Mutex::new(state), features: config.features.clone(), pending_mcp_server_refresh_config: Mutex::new(None), + conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), services, js_repl, @@ -7623,6 +7661,7 @@ mod tests { state: Mutex::new(state), features: config.features.clone(), pending_mcp_server_refresh_config: Mutex::new(None), + conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), services, js_repl, diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index ccfd340dfe..4dc2a607c6 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -13,6 +13,7 @@ pub mod auth; mod client; mod client_common; pub mod codex; +mod realtime_conversation; pub use codex::SteerInputError; mod codex_thread; mod compact_remote; diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs new file mode 100644 index 0000000000..dfaddd97bd --- /dev/null +++ b/codex-rs/core/src/realtime_conversation.rs @@ -0,0 +1,354 @@ +use crate::CodexAuth; +use crate::api_bridge::map_api_error; +use crate::codex::Session; +use crate::default_client::default_headers; +use crate::error::CodexErr; +use crate::error::Result as CodexResult; +use async_channel::Receiver; +use async_channel::Sender; +use async_channel::TrySendError; +use codex_api::Provider as ApiProvider; +use codex_api::RealtimeAudioFrame; +use codex_api::RealtimeEvent; +use codex_api::RealtimeSessionConfig; +use codex_api::RealtimeWebsocketClient; +use codex_api::endpoint::realtime_websocket::RealtimeWebsocketEvents; +use codex_api::endpoint::realtime_websocket::RealtimeWebsocketWriter; +use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::ConversationAudioParams; +use codex_protocol::protocol::ConversationStartParams; +use codex_protocol::protocol::ConversationTextParams; +use codex_protocol::protocol::ErrorEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RealtimeConversationClosedEvent; +use codex_protocol::protocol::RealtimeConversationRealtimeEvent; +use codex_protocol::protocol::RealtimeConversationStartedEvent; +use http::HeaderMap; +use std::sync::Arc; +use tokio::sync::Mutex; +use tokio::task::JoinHandle; +use tracing::error; +use tracing::warn; + +const AUDIO_IN_QUEUE_CAPACITY: usize = 256; +const TEXT_IN_QUEUE_CAPACITY: usize = 64; +const OUTPUT_EVENTS_QUEUE_CAPACITY: usize = 256; + +pub(crate) struct RealtimeConversationManager { + state: Mutex>, +} + +#[allow(dead_code)] +struct ConversationState { + audio_tx: Sender, + text_tx: Sender, + task: JoinHandle<()>, +} + +#[allow(dead_code)] +impl RealtimeConversationManager { + pub(crate) fn new() -> Self { + Self { + state: Mutex::new(None), + } + } + + pub(crate) async fn running_state(&self) -> Option<()> { + let state = self.state.lock().await; + state.as_ref().map(|_| ()) + } + + pub(crate) async fn start( + &self, + api_provider: ApiProvider, + extra_headers: Option, + prompt: String, + session_id: Option, + ) -> CodexResult> { + let previous_state = { + let mut guard = self.state.lock().await; + guard.take() + }; + if let Some(state) = previous_state { + state.task.abort(); + let _ = state.task.await; + } + + let session_config = RealtimeSessionConfig { prompt, session_id }; + let client = RealtimeWebsocketClient::new(api_provider); + let connection = client + .connect( + session_config, + extra_headers.unwrap_or_default(), + default_headers(), + ) + .await + .map_err(map_api_error)?; + + let writer = connection.writer(); + let events = connection.events(); + let (audio_tx, audio_rx) = + async_channel::bounded::(AUDIO_IN_QUEUE_CAPACITY); + let (text_tx, text_rx) = async_channel::bounded::(TEXT_IN_QUEUE_CAPACITY); + let (events_tx, events_rx) = + async_channel::bounded::(OUTPUT_EVENTS_QUEUE_CAPACITY); + + let task = spawn_realtime_input_task(writer, events, text_rx, audio_rx, events_tx); + + let mut guard = self.state.lock().await; + *guard = Some(ConversationState { + audio_tx, + text_tx, + task, + }); + Ok(events_rx) + } + + pub(crate) async fn audio_in(&self, frame: RealtimeAudioFrame) -> CodexResult<()> { + let sender = { + let guard = self.state.lock().await; + guard.as_ref().map(|state| state.audio_tx.clone()) + }; + + let Some(sender) = sender else { + return Err(CodexErr::InvalidRequest( + "conversation is not running".to_string(), + )); + }; + + match sender.try_send(frame) { + Ok(()) => Ok(()), + Err(TrySendError::Full(_)) => { + warn!("dropping input audio frame due to full queue"); + Ok(()) + } + Err(TrySendError::Closed(_)) => Err(CodexErr::InvalidRequest( + "conversation is not running".to_string(), + )), + } + } + + pub(crate) async fn text_in(&self, text: String) -> CodexResult<()> { + let sender = { + let guard = self.state.lock().await; + guard.as_ref().map(|state| state.text_tx.clone()) + }; + + let Some(sender) = sender else { + return Err(CodexErr::InvalidRequest( + "conversation is not running".to_string(), + )); + }; + + sender + .send(text) + .await + .map_err(|_| CodexErr::InvalidRequest("conversation is not running".to_string()))?; + Ok(()) + } + + pub(crate) async fn shutdown(&self) -> CodexResult<()> { + let state = { + let mut guard = self.state.lock().await; + guard.take() + }; + + if let Some(state) = state { + state.task.abort(); + let _ = state.task.await; + } + Ok(()) + } +} + +pub(crate) async fn handle_start( + sess: &Arc, + sub_id: String, + params: ConversationStartParams, +) -> CodexResult<()> { + let provider = sess.provider().await; + let auth = sess.services.auth_manager.auth().await; + let api_provider = provider.to_api_provider(auth.as_ref().map(CodexAuth::auth_mode))?; + + let requested_session_id = params + .session_id + .or_else(|| Some(sess.conversation_id.to_string())); + let events_rx = match sess + .conversation + .start( + api_provider, + None, + params.prompt, + requested_session_id.clone(), + ) + .await + { + Ok(events_rx) => events_rx, + Err(err) => { + send_conversation_error(sess, sub_id, err.to_string(), CodexErrorInfo::Other).await; + return Ok(()); + } + }; + + sess.send_event_raw(Event { + id: sub_id.clone(), + msg: EventMsg::RealtimeConversationStarted(RealtimeConversationStartedEvent { + session_id: requested_session_id, + }), + }) + .await; + + let sess_clone = Arc::clone(sess); + tokio::spawn(async move { + let ev = |msg| Event { + id: sub_id.clone(), + msg, + }; + while let Ok(event) = events_rx.recv().await { + sess_clone + .send_event_raw(ev(EventMsg::RealtimeConversationRealtime( + RealtimeConversationRealtimeEvent { payload: event }, + ))) + .await; + } + if let Some(()) = sess_clone.conversation.running_state().await { + sess_clone + .send_event_raw(ev(EventMsg::RealtimeConversationClosed( + RealtimeConversationClosedEvent { + reason: Some("transport_closed".to_string()), + }, + ))) + .await; + } + }); + + Ok(()) +} + +pub(crate) async fn handle_audio( + sess: &Arc, + sub_id: String, + params: ConversationAudioParams, +) { + if let Err(err) = sess.conversation.audio_in(params.frame).await { + send_conversation_error(sess, sub_id, err.to_string(), CodexErrorInfo::BadRequest).await; + } +} + +pub(crate) async fn handle_text( + sess: &Arc, + sub_id: String, + params: ConversationTextParams, +) { + if let Err(err) = sess.conversation.text_in(params.text).await { + send_conversation_error(sess, sub_id, err.to_string(), CodexErrorInfo::BadRequest).await; + } +} + +pub(crate) async fn handle_close(sess: &Arc, sub_id: String) { + match sess.conversation.shutdown().await { + Ok(()) => { + sess.send_event_raw(Event { + id: sub_id, + msg: EventMsg::RealtimeConversationClosed(RealtimeConversationClosedEvent { + reason: Some("requested".to_string()), + }), + }) + .await; + } + Err(err) => { + send_conversation_error(sess, sub_id, err.to_string(), CodexErrorInfo::Other).await; + } + } +} + +fn spawn_realtime_input_task( + writer: RealtimeWebsocketWriter, + events: RealtimeWebsocketEvents, + text_rx: Receiver, + audio_rx: Receiver, + events_tx: Sender, +) -> JoinHandle<()> { + tokio::spawn(async move { + loop { + tokio::select! { + biased; + text = text_rx.recv() => { + match text { + Ok(text) => { + if let Err(err) = writer.send_conversation_item_create(text).await { + let mapped_error = map_api_error(err); + warn!("failed to send input text: {mapped_error}"); + break; + } + } + Err(_) => break, + } + } + event = events.next_event() => { + match event { + Ok(Some(event)) => { + let should_stop = matches!(&event, RealtimeEvent::Error(_)); + if events_tx.send(event).await.is_err() { + break; + } + if should_stop { + error!("realtime stream error event received"); + break; + } + } + Ok(None) => { + let _ = events_tx + .send(RealtimeEvent::Error( + "realtime websocket connection is closed".to_string(), + )) + .await; + break; + } + Err(err) => { + let mapped_error = map_api_error(err); + if events_tx + .send(RealtimeEvent::Error(mapped_error.to_string())) + .await + .is_err() + { + break; + } + error!("realtime stream closed: {mapped_error}"); + break; + } + } + } + frame = audio_rx.recv() => { + match frame { + Ok(frame) => { + if let Err(err) = writer.send_audio_frame(frame).await { + let mapped_error = map_api_error(err); + error!("failed to send input audio: {mapped_error}"); + break; + } + } + Err(_) => break, + } + } + } + } + }) +} + +async fn send_conversation_error( + sess: &Arc, + sub_id: String, + message: String, + codex_error_info: CodexErrorInfo, +) { + sess.send_event_raw(Event { + id: sub_id, + msg: EventMsg::Error(ErrorEvent { + message, + codex_error_info: Some(codex_error_info), + }), + }) + .await; +} diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index f83433efb2..7899f0e83d 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -122,6 +122,9 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option { | EventMsg::CollabCloseEnd(_) | EventMsg::CollabResumeEnd(_) => Some(EventPersistenceMode::Extended), EventMsg::Warning(_) + | EventMsg::RealtimeConversationStarted(_) + | EventMsg::RealtimeConversationRealtime(_) + | EventMsg::RealtimeConversationClosed(_) | EventMsg::ModelReroute(_) | EventMsg::AgentMessageDelta(_) | EventMsg::AgentReasoningDelta(_) diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index 5e3d657996..7d73e46683 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -96,6 +96,7 @@ mod personality_migration; mod prompt_caching; mod quota_exceeded; mod read_file; +mod realtime_conversation; mod remote_models; mod request_compression; mod request_user_input; diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs new file mode 100644 index 0000000000..a6eccc969b --- /dev/null +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -0,0 +1,360 @@ +use anyhow::Result; +use codex_core::protocol::CodexErrorInfo; +use codex_core::protocol::ConversationAudioParams; +use codex_core::protocol::ConversationStartParams; +use codex_core::protocol::ConversationTextParams; +use codex_core::protocol::ErrorEvent; +use codex_core::protocol::EventMsg; +use codex_core::protocol::Op; +use codex_core::protocol::RealtimeAudioFrame; +use codex_core::protocol::RealtimeConversationRealtimeEvent; +use codex_core::protocol::RealtimeEvent; +use core_test_support::responses::start_websocket_server; +use core_test_support::skip_if_no_network; +use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event_match; +use pretty_assertions::assert_eq; +use serde_json::json; +use std::time::Duration; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_start_audio_text_close_round_trip() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![ + vec![], + vec![ + vec![json!({ + "type": "session.created", + "session": { "id": "sess_1" } + })], + vec![], + vec![ + json!({ + "type": "response.output_audio.delta", + "delta": "AQID", + "sample_rate": 24000, + "num_channels": 1 + }), + json!({ + "type": "conversation.item.added", + "item": { + "type": "message", + "role": "assistant", + "content": [{"type": "text", "text": "hi"}] + } + }), + ], + ], + ]) + .await; + + let mut builder = test_codex(); + let test = builder.build_with_websocket_server(&server).await?; + assert!(server.wait_for_handshakes(1, Duration::from_secs(2)).await); + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + let started = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationStarted(started) => Some(Ok(started.clone())), + EventMsg::Error(err) => Some(Err(err.clone())), + _ => None, + }) + .await + .unwrap_or_else(|err: ErrorEvent| panic!("conversation start failed: {err:?}")); + assert!(started.session_id.is_some()); + + let session_created = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + assert_eq!(session_created, "sess_1"); + + test.codex + .submit(Op::RealtimeConversationAudio(ConversationAudioParams { + frame: RealtimeAudioFrame { + data: "AQID".to_string(), + sample_rate: 24000, + num_channels: 1, + samples_per_channel: Some(480), + }, + })) + .await?; + test.codex + .submit(Op::RealtimeConversationText(ConversationTextParams { + text: "hello".to_string(), + })) + .await?; + + let audio_out = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::AudioOut(frame), + }) => Some(frame.clone()), + _ => None, + }) + .await; + assert_eq!(audio_out.data, "AQID"); + + let connections = server.connections(); + assert_eq!(connections.len(), 2); + let connection = &connections[1]; + assert_eq!(connection.len(), 3); + assert_eq!( + connection[0].body_json()["type"].as_str(), + Some("session.create") + ); + assert_eq!( + connection[0].body_json()["session"]["conversation_id"] + .as_str() + .expect("session.create conversation_id"), + started + .session_id + .as_deref() + .expect("started session id should be present") + ); + let request_types = [ + connection[1].body_json()["type"] + .as_str() + .expect("request type") + .to_string(), + connection[2].body_json()["type"] + .as_str() + .expect("request type") + .to_string(), + ]; + assert_eq!( + request_types, + [ + "conversation.item.create".to_string(), + "response.input_audio.delta".to_string(), + ] + ); + + test.codex.submit(Op::RealtimeConversationClose).await?; + let closed = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationClosed(closed) => Some(closed.clone()), + _ => None, + }) + .await; + assert!(matches!( + closed.reason.as_deref(), + Some("requested" | "transport_closed") + )); + + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_transport_close_emits_closed_event() -> Result<()> { + skip_if_no_network!(Ok(())); + + let session_created = vec![json!({ + "type": "session.created", + "session": { "id": "sess_1" } + })]; + let server = start_websocket_server(vec![vec![], vec![session_created]]).await; + + let mut builder = test_codex(); + let test = builder.build_with_websocket_server(&server).await?; + assert!(server.wait_for_handshakes(1, Duration::from_secs(2)).await); + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + let started = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationStarted(started) => Some(Ok(started.clone())), + EventMsg::Error(err) => Some(Err(err.clone())), + _ => None, + }) + .await + .unwrap_or_else(|err: ErrorEvent| panic!("conversation start failed: {err:?}")); + assert!(started.session_id.is_some()); + + let session_created = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + assert_eq!(session_created, "sess_1"); + + let closed = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationClosed(closed) => Some(closed.clone()), + _ => None, + }) + .await; + assert_eq!(closed.reason.as_deref(), Some("transport_closed")); + + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_audio_before_start_emits_error() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![]).await; + let mut builder = test_codex(); + let test = builder.build_with_websocket_server(&server).await?; + + test.codex + .submit(Op::RealtimeConversationAudio(ConversationAudioParams { + frame: RealtimeAudioFrame { + data: "AQID".to_string(), + sample_rate: 24000, + num_channels: 1, + samples_per_channel: Some(480), + }, + })) + .await?; + + let err = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::Error(err) => Some(err.clone()), + _ => None, + }) + .await; + assert_eq!(err.codex_error_info, Some(CodexErrorInfo::BadRequest)); + assert_eq!(err.message, "conversation is not running"); + + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_text_before_start_emits_error() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![]).await; + let mut builder = test_codex(); + let test = builder.build_with_websocket_server(&server).await?; + + test.codex + .submit(Op::RealtimeConversationText(ConversationTextParams { + text: "hello".to_string(), + })) + .await?; + + let err = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::Error(err) => Some(err.clone()), + _ => None, + }) + .await; + assert_eq!(err.codex_error_info, Some(CodexErrorInfo::BadRequest)); + assert_eq!(err.message, "conversation is not running"); + + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_second_start_replaces_runtime() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![ + vec![], + vec![vec![json!({ + "type": "session.created", + "session": { "id": "sess_old" } + })]], + vec![ + vec![json!({ + "type": "session.created", + "session": { "id": "sess_new" } + })], + vec![json!({ + "type": "response.output_audio.delta", + "delta": "AQID", + "sample_rate": 24000, + "num_channels": 1 + })], + ], + ]) + .await; + let mut builder = test_codex(); + let test = builder.build_with_websocket_server(&server).await?; + assert!(server.wait_for_handshakes(1, Duration::from_secs(2)).await); + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "old".to_string(), + session_id: Some("conv_old".to_string()), + })) + .await?; + wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) if session_id == "sess_old" => Some(Ok(())), + EventMsg::Error(err) => Some(Err(err.clone())), + _ => None, + }) + .await + .unwrap_or_else(|err: ErrorEvent| panic!("first conversation start failed: {err:?}")); + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "new".to_string(), + session_id: Some("conv_new".to_string()), + })) + .await?; + wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) if session_id == "sess_new" => Some(Ok(())), + EventMsg::Error(err) => Some(Err(err.clone())), + _ => None, + }) + .await + .unwrap_or_else(|err: ErrorEvent| panic!("second conversation start failed: {err:?}")); + + test.codex + .submit(Op::RealtimeConversationAudio(ConversationAudioParams { + frame: RealtimeAudioFrame { + data: "AQID".to_string(), + sample_rate: 24000, + num_channels: 1, + samples_per_channel: Some(480), + }, + })) + .await?; + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::AudioOut(frame), + }) if frame.data == "AQID" => Some(()), + _ => None, + }) + .await; + + let connections = server.connections(); + assert_eq!(connections.len(), 3); + assert_eq!(connections[1].len(), 1); + assert_eq!( + connections[1][0].body_json()["session"]["conversation_id"].as_str(), + Some("conv_old") + ); + assert_eq!(connections[2].len(), 2); + assert_eq!( + connections[2][0].body_json()["session"]["conversation_id"].as_str(), + Some("conv_new") + ); + assert_eq!( + connections[2][1].body_json()["type"].as_str(), + Some("response.input_audio.delta") + ); + + server.shutdown().await; + Ok(()) +} diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 6583c19f9e..1e2a1b9e6d 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -806,6 +806,9 @@ impl EventProcessor for EventProcessorWithHumanOutput { | EventMsg::RequestUserInput(_) | EventMsg::CollabResumeBegin(_) | EventMsg::CollabResumeEnd(_) + | EventMsg::RealtimeConversationStarted(_) + | EventMsg::RealtimeConversationRealtime(_) + | EventMsg::RealtimeConversationClosed(_) | EventMsg::DynamicToolCallRequest(_) => {} } CodexStatus::Running diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index c20c877c41..762052ccf4 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -374,6 +374,9 @@ async fn run_codex_tool_session_inner( | EventMsg::CollabCloseEnd(_) | EventMsg::CollabResumeBegin(_) | EventMsg::CollabResumeEnd(_) + | EventMsg::RealtimeConversationStarted(_) + | EventMsg::RealtimeConversationRealtime(_) + | EventMsg::RealtimeConversationClosed(_) | EventMsg::DeprecationNotice(_) => { // For now, we do not do anything extra for these // events. Note that diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 5b3d41888c..86a1248657 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -85,6 +85,41 @@ pub struct McpServerRefreshConfig { pub mcp_oauth_credentials_store_mode: Value, } +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] +pub struct ConversationStartParams { + pub prompt: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub struct RealtimeAudioFrame { + pub data: String, + pub sample_rate: u32, + pub num_channels: u16, + #[serde(skip_serializing_if = "Option::is_none")] + pub samples_per_channel: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub enum RealtimeEvent { + SessionCreated { session_id: String }, + SessionUpdated { backend_prompt: Option }, + AudioOut(RealtimeAudioFrame), + ConversationItemAdded(Value), + Error(String), +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] +pub struct ConversationAudioParams { + pub frame: RealtimeAudioFrame, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] +pub struct ConversationTextParams { + pub text: String, +} + /// Submission operation #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema)] #[serde(tag = "type", rename_all = "snake_case")] @@ -98,6 +133,18 @@ pub enum Op { /// Terminate all running background terminal processes for this thread. CleanBackgroundTerminals, + /// Start a realtime conversation stream. + RealtimeConversationStart(ConversationStartParams), + + /// Send audio input to the running realtime conversation stream. + RealtimeConversationAudio(ConversationAudioParams), + + /// Send text input to the running realtime conversation stream. + RealtimeConversationText(ConversationTextParams), + + /// Close the running realtime conversation stream. + RealtimeConversationClose, + /// Legacy user input. /// /// Prefer [`Op::UserTurn`] so the caller provides full turn context @@ -899,6 +946,15 @@ pub enum EventMsg { /// indicates the turn continued but the user should still be notified. Warning(WarningEvent), + /// Realtime conversation lifecycle start event. + RealtimeConversationStarted(RealtimeConversationStartedEvent), + + /// Realtime conversation streaming payload event. + RealtimeConversationRealtime(RealtimeConversationRealtimeEvent), + + /// Realtime conversation lifecycle close event. + RealtimeConversationClosed(RealtimeConversationClosedEvent), + /// Model routing changed from the requested model to a different model. ModelReroute(ModelRerouteEvent), @@ -1078,6 +1134,22 @@ pub enum EventMsg { CollabResumeEnd(CollabResumeEndEvent), } +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] +pub struct RealtimeConversationStartedEvent { + pub session_id: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] +pub struct RealtimeConversationRealtimeEvent { + pub payload: RealtimeEvent, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] +pub struct RealtimeConversationClosedEvent { + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + impl From for EventMsg { fn from(event: CollabAgentSpawnBeginEvent) -> Self { EventMsg::CollabAgentSpawnBegin(event) @@ -3047,6 +3119,61 @@ mod tests { assert!(event.affects_turn_status()); } + #[test] + fn conversation_op_serializes_as_unnested_variants() { + let audio = Op::RealtimeConversationAudio(ConversationAudioParams { + frame: RealtimeAudioFrame { + data: "AQID".to_string(), + sample_rate: 24_000, + num_channels: 1, + samples_per_channel: Some(480), + }, + }); + let start = Op::RealtimeConversationStart(ConversationStartParams { + prompt: "be helpful".to_string(), + session_id: Some("conv_1".to_string()), + }); + let text = Op::RealtimeConversationText(ConversationTextParams { + text: "hello".to_string(), + }); + let close = Op::RealtimeConversationClose; + + assert_eq!( + serde_json::to_value(&start).unwrap(), + json!({ + "type": "realtime_conversation_start", + "prompt": "be helpful", + "session_id": "conv_1" + }) + ); + assert_eq!( + serde_json::to_value(&audio).unwrap(), + json!({ + "type": "realtime_conversation_audio", + "frame": { + "data": "AQID", + "sample_rate": 24000, + "num_channels": 1, + "samples_per_channel": 480 + } + }) + ); + assert_eq!( + serde_json::from_value::(serde_json::to_value(&text).unwrap()).unwrap(), + text + ); + assert_eq!( + serde_json::to_value(&close).unwrap(), + json!({ + "type": "realtime_conversation_close" + }) + ); + assert_eq!( + serde_json::from_value::(serde_json::to_value(&close).unwrap()).unwrap(), + close + ); + } + #[test] fn user_input_serialization_omits_final_output_json_schema_when_none() -> Result<()> { let op = Op::UserInput { diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index afc894b22b..8850cc8b73 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -4186,6 +4186,9 @@ impl ChatWidget { | EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) + | EventMsg::RealtimeConversationStarted(_) + | EventMsg::RealtimeConversationRealtime(_) + | EventMsg::RealtimeConversationClosed(_) | EventMsg::DynamicToolCallRequest(_) => {} EventMsg::ItemCompleted(event) => { let item = event.item; From 0644ba7b7e00dfe308794b3bb3adff6ec717707d Mon Sep 17 00:00:00 2001 From: Rohan Godha Date: Fri, 20 Feb 2026 22:32:15 -0500 Subject: [PATCH 040/385] fix(nix): include libcap dependency on linux builds (#12415) commit 923f9311215df350248e4a314e8931bfb9033bcd introduced a dependency on `libcap`. This PR fixes the nix build by including `libcap` in nix's build inputs issue number: #12102. @etraut-openai gave me permission to open pr Testing: running `nix run .#codex-rs` works on both macos (aarch64) and nixos (x86-64) --- codex-rs/default.nix | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/codex-rs/default.nix b/codex-rs/default.nix index fc7dd978ef..80896689f9 100644 --- a/codex-rs/default.nix +++ b/codex-rs/default.nix @@ -2,16 +2,18 @@ cmake, llvmPackages, openssl, + libcap ? null, rustPlatform, pkg-config, lib, + stdenv, version ? "0.0.0", ... }: rustPlatform.buildRustPackage (_: { - env = { - PKG_CONFIG_PATH = "${openssl.dev}/lib/pkgconfig:$PKG_CONFIG_PATH"; - }; + env.PKG_CONFIG_PATH = lib.makeSearchPathOutput "dev" "lib/pkgconfig" ( + [ openssl ] ++ lib.optionals stdenv.isLinux [ libcap ] + ); pname = "codex-rs"; inherit version; cargoLock.lockFile = ./Cargo.lock; @@ -31,6 +33,8 @@ rustPlatform.buildRustPackage (_: { llvmPackages.libclang.lib openssl pkg-config + ] ++ lib.optionals stdenv.isLinux [ + libcap ]; cargoLock.outputHashes = { @@ -47,5 +51,6 @@ rustPlatform.buildRustPackage (_: { description = "OpenAI Codex command‑line interface rust implementation"; license = licenses.asl20; homepage = "https://github.com/openai/codex"; + mainProgram = "codex"; }; }) From 7ae5d8801655fe3ecc66d0f14442e45b0bfe196f Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 20 Feb 2026 19:51:20 -0800 Subject: [PATCH 041/385] Add experimental realtime websocket URL override (#12416) - add top-level `experimental_realtime_ws_base_url` config key (experimental / do not use) and include it in config schema - apply the override only to `Op::RealtimeConversation` websocket transport, with config + realtime tests --- codex-rs/core/config.schema.json | 4 ++ codex-rs/core/src/config/mod.rs | 43 +++++++++++++++ codex-rs/core/src/realtime_conversation.rs | 6 +- .../core/tests/suite/realtime_conversation.rs | 55 +++++++++++++++++++ 4 files changed, 107 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 4de4da6e48..9096455fae 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1541,6 +1541,10 @@ "experimental_compact_prompt_file": { "$ref": "#/definitions/AbsolutePathBuf" }, + "experimental_realtime_ws_base_url": { + "description": "Experimental / do not use. Overrides only the realtime conversation websocket transport base URL (the `Op::RealtimeConversation` `/ws` connection) without changing normal provider HTTP requests.", + "type": "string" + }, "experimental_use_freeform_apply_patch": { "type": "boolean" }, diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 76ba2fcb2d..68bc623e0a 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -394,6 +394,11 @@ pub struct Config { /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: String, + /// Experimental / do not use. Overrides only the realtime conversation + /// websocket transport base URL (the `Op::RealtimeConversation` `/ws` + /// connection) without changing normal provider HTTP requests. + pub experimental_realtime_ws_base_url: Option, + /// When set, restricts ChatGPT login to a specific workspace identifier. pub forced_chatgpt_workspace_id: Option, @@ -1119,6 +1124,11 @@ pub struct ConfigToml { /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: Option, + /// Experimental / do not use. Overrides only the realtime conversation + /// websocket transport base URL (the `Op::RealtimeConversation` `/ws` + /// connection) without changing normal provider HTTP requests. + pub experimental_realtime_ws_base_url: Option, + pub projects: Option>, /// Controls the web search tool mode: disabled, cached, or live. @@ -2043,6 +2053,7 @@ impl Config { .chatgpt_base_url .or(cfg.chatgpt_base_url) .unwrap_or("https://chatgpt.com/backend-api/".to_string()), + experimental_realtime_ws_base_url: cfg.experimental_realtime_ws_base_url, forced_chatgpt_workspace_id, forced_login_method, include_apply_patch_tool: include_apply_patch_tool_flag, @@ -4583,6 +4594,7 @@ model_verbosity = "high" model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + experimental_realtime_ws_base_url: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -4702,6 +4714,7 @@ model_verbosity = "high" model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + experimental_realtime_ws_base_url: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -4819,6 +4832,7 @@ model_verbosity = "high" model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + experimental_realtime_ws_base_url: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -4922,6 +4936,7 @@ model_verbosity = "high" model_verbosity: Some(Verbosity::High), personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + experimental_realtime_ws_base_url: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -5708,6 +5723,34 @@ trust_level = "untrusted" ); Ok(()) } + + #[test] + fn experimental_realtime_ws_base_url_loads_from_config_toml() -> std::io::Result<()> { + let cfg: ConfigToml = toml::from_str( + r#" +experimental_realtime_ws_base_url = "http://127.0.0.1:8011" +"#, + ) + .expect("TOML deserialization should succeed"); + + assert_eq!( + cfg.experimental_realtime_ws_base_url.as_deref(), + Some("http://127.0.0.1:8011") + ); + + let codex_home = TempDir::new()?; + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!( + config.experimental_realtime_ws_base_url.as_deref(), + Some("http://127.0.0.1:8011") + ); + Ok(()) + } } #[cfg(test)] diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index dfaddd97bd..b41b4bd0d4 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -169,7 +169,11 @@ pub(crate) async fn handle_start( ) -> CodexResult<()> { let provider = sess.provider().await; let auth = sess.services.auth_manager.auth().await; - let api_provider = provider.to_api_provider(auth.as_ref().map(CodexAuth::auth_mode))?; + let mut api_provider = provider.to_api_provider(auth.as_ref().map(CodexAuth::auth_mode))?; + let config = sess.get_config().await; + if let Some(realtime_ws_base_url) = &config.experimental_realtime_ws_base_url { + api_provider.base_url = realtime_ws_base_url.clone(); + } let requested_session_id = params .session_id diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index a6eccc969b..ddc63385de 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -358,3 +358,58 @@ async fn conversation_second_start_replaces_runtime() -> Result<()> { server.shutdown().await; Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_uses_experimental_realtime_ws_base_url_override() -> Result<()> { + skip_if_no_network!(Ok(())); + + let startup_server = start_websocket_server(vec![vec![]]).await; + let realtime_server = start_websocket_server(vec![vec![vec![json!({ + "type": "session.created", + "session": { "id": "sess_override" } + })]]]) + .await; + + let mut builder = test_codex().with_config({ + let realtime_base_url = realtime_server.uri().to_string(); + move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + } + }); + let test = builder.build_with_websocket_server(&startup_server).await?; + assert!( + startup_server + .wait_for_handshakes(1, Duration::from_secs(2)) + .await + ); + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + let session_created = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + assert_eq!(session_created, "sess_override"); + + let startup_connections = startup_server.connections(); + assert_eq!(startup_connections.len(), 1); + + let realtime_connections = realtime_server.connections(); + assert_eq!(realtime_connections.len(), 1); + assert_eq!( + realtime_connections[0][0].body_json()["type"].as_str(), + Some("session.create") + ); + + startup_server.shutdown().await; + realtime_server.shutdown().await; + Ok(()) +} From 4c1744afb22383ae61bebf7feb19a24eedc970df Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Fri, 20 Feb 2026 20:08:56 -0800 Subject: [PATCH 042/385] Improve Plan mode reasoning selection flow (#12303) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses https://github.com/openai/codex/issues/11013 ## Summary - add a Plan implementation path in the TUI that lets users choose reasoning before switching to Default mode and implementing - add Plan-mode reasoning scope handling (Plan-only override vs all-modes default), including config/schema/docs plumbing for `plan_mode_reasoning_effort` - remove the hardcoded Plan preset medium default and make the reasoning popup reflect the active Plan override as `(current)` - split the collaboration-mode switch notification UI hint into #12307 to keep this diff focused If I have `plan_mode_reasoning_effort = "medium"` set in my `config.toml`: Screenshot 2026-02-20 at 6 59 37 PM If I don't have `plan_mode_reasoning_effort` set in my `config.toml`: Screenshot 2026-02-20 at 7 01 51 PM ## Codex author `codex resume 019c78a2-726b-7fe3-adac-3fa4523dcc2a` --- codex-rs/core/config.schema.json | 6 + codex-rs/core/src/config/mod.rs | 15 + codex-rs/core/src/config/profile.rs | 1 + .../collaboration_mode_presets.rs | 4 + codex-rs/tui/src/app.rs | 52 ++++ codex-rs/tui/src/app_event.rs | 12 + codex-rs/tui/src/chatwidget.rs | 252 +++++++++++++---- ...ng_selection_popup_extra_high_warning.snap | 1 - codex-rs/tui/src/chatwidget/tests.rs | 261 +++++++++++++++++- docs/config.md | 9 + 10 files changed, 558 insertions(+), 55 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 9096455fae..cda5b8eaba 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -467,6 +467,9 @@ "personality": { "$ref": "#/definitions/Personality" }, + "plan_mode_reasoning_effort": { + "$ref": "#/definitions/ReasoningEffort" + }, "sandbox_mode": { "$ref": "#/definitions/SandboxMode" }, @@ -1901,6 +1904,9 @@ ], "description": "Optionally specify a personality for the model" }, + "plan_mode_reasoning_effort": { + "$ref": "#/definitions/ReasoningEffort" + }, "profile": { "description": "Profile to use from the `profiles` map.", "type": "string" diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 68bc623e0a..168633194e 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -376,6 +376,13 @@ pub struct Config { /// Value to use for `reasoning.effort` when making a request using the /// Responses API. pub model_reasoning_effort: Option, + /// Optional Plan-mode-specific reasoning effort override used by the TUI. + /// + /// When unset, Plan mode uses the built-in Plan preset default (currently + /// `medium`). When explicitly set (including `none`), this overrides the + /// Plan preset. The `none` value means "no reasoning" (not "inherit the + /// global default"). + pub plan_mode_reasoning_effort: Option, /// If not "none", the value to use for `reasoning.summary` when making a /// request using the Responses API. @@ -1107,6 +1114,7 @@ pub struct ConfigToml { pub show_raw_agent_reasoning: Option, pub model_reasoning_effort: Option, + pub plan_mode_reasoning_effort: Option, pub model_reasoning_summary: Option, /// Optional verbosity control for GPT-5 models (Responses API `text.verbosity`). pub model_verbosity: Option, @@ -2042,6 +2050,9 @@ impl Config { model_reasoning_effort: config_profile .model_reasoning_effort .or(cfg.model_reasoning_effort), + plan_mode_reasoning_effort: config_profile + .plan_mode_reasoning_effort + .or(cfg.plan_mode_reasoning_effort), model_reasoning_summary: config_profile .model_reasoning_summary .or(cfg.model_reasoning_summary) @@ -4588,6 +4599,7 @@ model_verbosity = "high" hide_agent_reasoning: false, show_raw_agent_reasoning: false, model_reasoning_effort: Some(ReasoningEffort::High), + plan_mode_reasoning_effort: None, model_reasoning_summary: ReasoningSummary::Detailed, model_supports_reasoning_summaries: None, model_catalog: None, @@ -4708,6 +4720,7 @@ model_verbosity = "high" hide_agent_reasoning: false, show_raw_agent_reasoning: false, model_reasoning_effort: None, + plan_mode_reasoning_effort: None, model_reasoning_summary: ReasoningSummary::default(), model_supports_reasoning_summaries: None, model_catalog: None, @@ -4826,6 +4839,7 @@ model_verbosity = "high" hide_agent_reasoning: false, show_raw_agent_reasoning: false, model_reasoning_effort: None, + plan_mode_reasoning_effort: None, model_reasoning_summary: ReasoningSummary::default(), model_supports_reasoning_summaries: None, model_catalog: None, @@ -4930,6 +4944,7 @@ model_verbosity = "high" hide_agent_reasoning: false, show_raw_agent_reasoning: false, model_reasoning_effort: Some(ReasoningEffort::High), + plan_mode_reasoning_effort: None, model_reasoning_summary: ReasoningSummary::Detailed, model_supports_reasoning_summaries: None, model_catalog: None, diff --git a/codex-rs/core/src/config/profile.rs b/codex-rs/core/src/config/profile.rs index d8b7ab1baf..3c7d575cdc 100644 --- a/codex-rs/core/src/config/profile.rs +++ b/codex-rs/core/src/config/profile.rs @@ -24,6 +24,7 @@ pub struct ConfigProfile { pub approval_policy: Option, pub sandbox_mode: Option, pub model_reasoning_effort: Option, + pub plan_mode_reasoning_effort: Option, pub model_reasoning_summary: Option, pub model_verbosity: Option, pub personality: Option, diff --git a/codex-rs/core/src/models_manager/collaboration_mode_presets.rs b/codex-rs/core/src/models_manager/collaboration_mode_presets.rs index 25f083cb81..7b900609b3 100644 --- a/codex-rs/core/src/models_manager/collaboration_mode_presets.rs +++ b/codex-rs/core/src/models_manager/collaboration_mode_presets.rs @@ -75,6 +75,10 @@ mod tests { fn preset_names_use_mode_display_names() { assert_eq!(plan_preset().name, ModeKind::Plan.display_name()); assert_eq!(default_preset().name, ModeKind::Default.display_name()); + assert_eq!( + plan_preset().reasoning_effort, + Some(Some(ReasoningEffort::Medium)) + ); } #[test] diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 5898059644..0090ef5e9b 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1764,6 +1764,10 @@ impl App { AppEvent::OpenReasoningPopup { model } => { self.chat_widget.open_reasoning_popup(model); } + AppEvent::OpenPlanReasoningScopePrompt { model, effort } => { + self.chat_widget + .open_plan_reasoning_scope_prompt(model, effort); + } AppEvent::OpenAllModelsPopup { models } => { self.chat_widget.open_all_models_popup(models); } @@ -2115,6 +2119,10 @@ impl App { .await { Ok(()) => { + let effort_label = effort + .map(|selected_effort| selected_effort.to_string()) + .unwrap_or_else(|| "default".to_string()); + tracing::info!("Selected model: {model}, Selected effort: {effort_label}"); let mut message = format!("Model changed to {model}"); if let Some(label) = Self::reasoning_label_for(&model, effort) { message.push(' '); @@ -2315,6 +2323,11 @@ impl App { AppEvent::UpdateRateLimitSwitchPromptHidden(hidden) => { self.chat_widget.set_rate_limit_switch_prompt_hidden(hidden); } + AppEvent::UpdatePlanModeReasoningEffort(effort) => { + self.config.plan_mode_reasoning_effort = effort; + self.chat_widget.set_plan_mode_reasoning_effort(effort); + self.refresh_status_line(); + } AppEvent::PersistFullAccessWarningAcknowledged => { if let Err(err) = ConfigEditsBuilder::new(&self.config.codex_home) .set_hide_full_access_warning(true) @@ -2360,6 +2373,45 @@ impl App { )); } } + AppEvent::PersistPlanModeReasoningEffort(effort) => { + let profile = self.active_profile.as_deref(); + let segments = if let Some(profile) = profile { + vec![ + "profiles".to_string(), + profile.to_string(), + "plan_mode_reasoning_effort".to_string(), + ] + } else { + vec!["plan_mode_reasoning_effort".to_string()] + }; + let edit = if let Some(effort) = effort { + ConfigEdit::SetPath { + segments, + value: effort.to_string().into(), + } + } else { + ConfigEdit::ClearPath { segments } + }; + if let Err(err) = ConfigEditsBuilder::new(&self.config.codex_home) + .with_edits([edit]) + .apply() + .await + { + tracing::error!( + error = %err, + "failed to persist plan mode reasoning effort" + ); + if let Some(profile) = profile { + self.chat_widget.add_error_message(format!( + "Failed to save Plan mode reasoning effort for profile `{profile}`: {err}" + )); + } else { + self.chat_widget.add_error_message(format!( + "Failed to save Plan mode reasoning effort: {err}" + )); + } + } + } AppEvent::PersistModelMigrationPromptAcknowledged { from_model, to_model, diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 1c9e8ce88e..17ce9f14b4 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -164,6 +164,12 @@ pub(crate) enum AppEvent { model: ModelPreset, }, + /// Open the Plan-mode reasoning scope prompt for the selected model/effort. + OpenPlanReasoningScopePrompt { + model: String, + effort: Option, + }, + /// Open the full model picker (non-auto models). OpenAllModelsPopup { models: Vec, @@ -258,6 +264,9 @@ pub(crate) enum AppEvent { /// Update whether the rate limit switch prompt has been acknowledged for the session. UpdateRateLimitSwitchPromptHidden(bool), + /// Update the Plan-mode-specific reasoning effort in memory. + UpdatePlanModeReasoningEffort(Option), + /// Persist the acknowledgement flag for the full access warning prompt. PersistFullAccessWarningAcknowledged, @@ -268,6 +277,9 @@ pub(crate) enum AppEvent { /// Persist the acknowledgement flag for the rate limit switch prompt. PersistRateLimitSwitchPromptHidden, + /// Persist the Plan-mode-specific reasoning effort. + PersistPlanModeReasoningEffort(Option), + /// Persist the acknowledgement flag for the model migration prompt. PersistModelMigrationPromptAcknowledged { from_model: String, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 8850cc8b73..1cd3b3e14f 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -158,6 +158,9 @@ const PLAN_IMPLEMENTATION_TITLE: &str = "Implement this plan?"; const PLAN_IMPLEMENTATION_YES: &str = "Yes, implement this plan"; const PLAN_IMPLEMENTATION_NO: &str = "No, stay in Plan mode"; const PLAN_IMPLEMENTATION_CODING_MESSAGE: &str = "Implement the plan."; +const PLAN_MODE_REASONING_SCOPE_TITLE: &str = "Apply reasoning change"; +const PLAN_MODE_REASONING_SCOPE_PLAN_ONLY: &str = "Apply to Plan mode override"; +const PLAN_MODE_REASONING_SCOPE_ALL_MODES: &str = "Apply to global default and Plan mode override"; const CONNECTORS_SELECTION_VIEW_ID: &str = "connectors-selection"; /// Choose the keybinding used to edit the most-recently queued message. @@ -1452,7 +1455,6 @@ impl ChatWidget { } None => (Vec::new(), Some("Default mode unavailable".to_string())), }; - let items = vec![ SelectionItem { name: PLAN_IMPLEMENTATION_YES.to_string(), @@ -5031,16 +5033,20 @@ impl ChatWidget { } auto_presets.sort_by_key(|preset| Self::auto_model_order(&preset.model)); - let mut items: Vec = auto_presets .into_iter() .map(|preset| { let description = (!preset.description.is_empty()).then_some(preset.description.clone()); let model = preset.model.clone(); + let should_prompt_plan_mode_scope = self.should_prompt_plan_mode_reasoning_scope( + model.as_str(), + Some(preset.default_reasoning_effort), + ); let actions = Self::model_selection_actions( model.clone(), Some(preset.default_reasoning_effort), + should_prompt_plan_mode_scope, ); SelectionItem { name: model.clone(), @@ -5195,40 +5201,135 @@ impl ChatWidget { fn model_selection_actions( model_for_action: String, effort_for_action: Option, + should_prompt_plan_mode_scope: bool, ) -> Vec { vec![Box::new(move |tx| { - let effort_label = effort_for_action - .map(|effort| effort.to_string()) - .unwrap_or_else(|| "default".to_string()); - tx.send(AppEvent::CodexOp(Op::OverrideTurnContext { - cwd: None, - approval_policy: None, - sandbox_policy: None, - windows_sandbox_level: None, - model: Some(model_for_action.clone()), - effort: Some(effort_for_action), - summary: None, - collaboration_mode: None, - personality: None, - })); + if should_prompt_plan_mode_scope { + tx.send(AppEvent::OpenPlanReasoningScopePrompt { + model: model_for_action.clone(), + effort: effort_for_action, + }); + return; + } + tx.send(AppEvent::UpdateModel(model_for_action.clone())); tx.send(AppEvent::UpdateReasoningEffort(effort_for_action)); tx.send(AppEvent::PersistModelSelection { model: model_for_action.clone(), effort: effort_for_action, }); - tracing::info!( - "Selected model: {}, Selected effort: {}", - model_for_action, - effort_label - ); })] } + fn should_prompt_plan_mode_reasoning_scope( + &self, + selected_model: &str, + selected_effort: Option, + ) -> bool { + if !self.collaboration_modes_enabled() + || self.active_mode_kind() != ModeKind::Plan + || selected_model != self.current_model() + { + return false; + } + + // Prompt whenever the selection is not a true no-op for both: + // 1) the active Plan-mode effective reasoning, and + // 2) the stored global defaults that would be updated by the fallback path. + selected_effort != self.effective_reasoning_effort() + || selected_model != self.current_collaboration_mode.model() + || selected_effort != self.current_collaboration_mode.reasoning_effort() + } + + pub(crate) fn open_plan_reasoning_scope_prompt( + &mut self, + model: String, + effort: Option, + ) { + let reasoning_phrase = match effort { + Some(ReasoningEffortConfig::None) => "no reasoning".to_string(), + Some(selected_effort) => { + format!( + "{} reasoning", + Self::reasoning_effort_label(selected_effort).to_lowercase() + ) + } + None => "the selected reasoning".to_string(), + }; + let plan_only_description = format!("Always use {reasoning_phrase} in Plan mode."); + let plan_reasoning_source = if let Some(plan_override) = + self.config.plan_mode_reasoning_effort + { + format!( + "user-chosen Plan override ({})", + Self::reasoning_effort_label(plan_override).to_lowercase() + ) + } else if let Some(plan_mask) = collaboration_modes::plan_mask(self.models_manager.as_ref()) + { + match plan_mask.reasoning_effort.flatten() { + Some(plan_effort) => format!( + "built-in Plan default ({})", + Self::reasoning_effort_label(plan_effort).to_lowercase() + ), + None => "built-in Plan default (no reasoning)".to_string(), + } + } else { + "built-in Plan default".to_string() + }; + let all_modes_description = format!( + "Set the global default reasoning level and the Plan mode override. This replaces the current {plan_reasoning_source}." + ); + let subtitle = format!("Choose where to apply {reasoning_phrase}."); + + let plan_only_actions: Vec = vec![Box::new({ + let model = model.clone(); + move |tx| { + tx.send(AppEvent::UpdateModel(model.clone())); + tx.send(AppEvent::UpdatePlanModeReasoningEffort(effort)); + tx.send(AppEvent::PersistPlanModeReasoningEffort(effort)); + } + })]; + let all_modes_actions: Vec = vec![Box::new(move |tx| { + tx.send(AppEvent::UpdateModel(model.clone())); + tx.send(AppEvent::UpdateReasoningEffort(effort)); + tx.send(AppEvent::UpdatePlanModeReasoningEffort(effort)); + tx.send(AppEvent::PersistPlanModeReasoningEffort(effort)); + tx.send(AppEvent::PersistModelSelection { + model: model.clone(), + effort, + }); + })]; + + self.bottom_pane.show_selection_view(SelectionViewParams { + title: Some(PLAN_MODE_REASONING_SCOPE_TITLE.to_string()), + subtitle: Some(subtitle), + footer_hint: Some(standard_popup_hint_line()), + items: vec![ + SelectionItem { + name: PLAN_MODE_REASONING_SCOPE_PLAN_ONLY.to_string(), + description: Some(plan_only_description), + actions: plan_only_actions, + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: PLAN_MODE_REASONING_SCOPE_ALL_MODES.to_string(), + description: Some(all_modes_description), + actions: all_modes_actions, + dismiss_on_select: true, + ..Default::default() + }, + ], + ..Default::default() + }); + } + /// Open a popup to choose the reasoning effort (stage 2) for the given model. pub(crate) fn open_reasoning_popup(&mut self, preset: ModelPreset) { let default_effort: ReasoningEffortConfig = preset.default_reasoning_effort; let supported = preset.supported_reasoning_efforts; + let in_plan_mode = + self.collaboration_modes_enabled() && self.active_mode_kind() == ModeKind::Plan; let warn_effort = if supported .iter() @@ -5272,10 +5373,16 @@ impl ChatWidget { } if choices.len() == 1 { - if let Some(effort) = choices.first().and_then(|c| c.stored) { - self.apply_model_and_effort(preset.model, Some(effort)); + let selected_effort = choices.first().and_then(|c| c.stored); + let selected_model = preset.model; + if self.should_prompt_plan_mode_reasoning_scope(&selected_model, selected_effort) { + self.app_event_tx + .send(AppEvent::OpenPlanReasoningScopePrompt { + model: selected_model, + effort: selected_effort, + }); } else { - self.apply_model_and_effort(preset.model, None); + self.apply_model_and_effort(selected_model, selected_effort); } return; } @@ -5291,7 +5398,13 @@ impl ChatWidget { let model_slug = preset.model.to_string(); let is_current_model = self.current_model() == preset.model.as_str(); let highlight_choice = if is_current_model { - self.effective_reasoning_effort() + if in_plan_mode { + self.config + .plan_mode_reasoning_effort + .or(self.effective_reasoning_effort()) + } else { + self.effective_reasoning_effort() + } } else { default_choice }; @@ -5334,7 +5447,24 @@ impl ChatWidget { }; let model_for_action = model_slug.clone(); - let actions = Self::model_selection_actions(model_for_action, choice.stored); + let choice_effort = choice.stored; + let should_prompt_plan_mode_scope = + self.should_prompt_plan_mode_reasoning_scope(model_slug.as_str(), choice_effort); + let actions: Vec = vec![Box::new(move |tx| { + if should_prompt_plan_mode_scope { + tx.send(AppEvent::OpenPlanReasoningScopePrompt { + model: model_for_action.clone(), + effort: choice_effort, + }); + } else { + tx.send(AppEvent::UpdateModel(model_for_action.clone())); + tx.send(AppEvent::UpdateReasoningEffort(choice_effort)); + tx.send(AppEvent::PersistModelSelection { + model: model_for_action.clone(), + effort: choice_effort, + }); + } + })]; items.push(SelectionItem { name: effort_label, @@ -5372,33 +5502,20 @@ impl ChatWidget { } } - fn apply_model_and_effort(&self, model: String, effort: Option) { - self.app_event_tx - .send(AppEvent::CodexOp(Op::OverrideTurnContext { - cwd: None, - approval_policy: None, - sandbox_policy: None, - windows_sandbox_level: None, - model: Some(model.clone()), - effort: Some(effort), - summary: None, - collaboration_mode: None, - personality: None, - })); - self.app_event_tx.send(AppEvent::UpdateModel(model.clone())); + fn apply_model_and_effort_without_persist( + &self, + model: String, + effort: Option, + ) { + self.app_event_tx.send(AppEvent::UpdateModel(model)); self.app_event_tx .send(AppEvent::UpdateReasoningEffort(effort)); - self.app_event_tx.send(AppEvent::PersistModelSelection { - model: model.clone(), - effort, - }); - tracing::info!( - "Selected model: {}, Selected effort: {}", - model, - effort - .map(|e| e.to_string()) - .unwrap_or_else(|| "default".to_string()) - ); + } + + fn apply_model_and_effort(&self, model: String, effort: Option) { + self.apply_model_and_effort_without_persist(model.clone(), effort); + self.app_event_tx + .send(AppEvent::PersistModelSelection { model, effort }); } /// Open the permissions popup (alias for /permissions). @@ -6163,6 +6280,22 @@ impl ChatWidget { .unwrap_or(false) } + pub(crate) fn set_plan_mode_reasoning_effort(&mut self, effort: Option) { + self.config.plan_mode_reasoning_effort = effort; + if self.collaboration_modes_enabled() + && let Some(mask) = self.active_collaboration_mask.as_mut() + && mask.mode == Some(ModeKind::Plan) + { + if let Some(effort) = effort { + mask.reasoning_effort = Some(Some(effort)); + } else if let Some(plan_mask) = + collaboration_modes::plan_mask(self.models_manager.as_ref()) + { + mask.reasoning_effort = plan_mask.reasoning_effort; + } + } + } + /// Set the reasoning effort in the stored collaboration mode. pub(crate) fn set_reasoning_effort(&mut self, effort: Option) { self.current_collaboration_mode = @@ -6170,7 +6303,10 @@ impl ChatWidget { .with_updates(None, Some(effort), None); if self.collaboration_modes_enabled() && let Some(mask) = self.active_collaboration_mask.as_mut() + && mask.mode != Some(ModeKind::Plan) { + // Generic "global default" updates should not mutate the active Plan mask. + // Plan reasoning is controlled by the Plan preset and Plan-only override updates. mask.reasoning_effort = Some(effort); } } @@ -6394,13 +6530,18 @@ impl ChatWidget { /// /// When collaboration modes are enabled and a preset is selected, /// the current mode is attached to submissions as `Op::UserTurn { collaboration_mode: Some(...) }`. - pub(crate) fn set_collaboration_mask(&mut self, mask: CollaborationModeMask) { + pub(crate) fn set_collaboration_mask(&mut self, mut mask: CollaborationModeMask) { if !self.collaboration_modes_enabled() { return; } let previous_mode = self.active_mode_kind(); let previous_model = self.current_model().to_string(); let previous_effort = self.effective_reasoning_effort(); + if mask.mode == Some(ModeKind::Plan) + && let Some(effort) = self.config.plan_mode_reasoning_effort + { + mask.reasoning_effort = Some(Some(effort)); + } self.active_collaboration_mask = Some(mask); self.update_collaboration_mode_indicator(); self.refresh_model_display(); @@ -6817,8 +6958,13 @@ impl ChatWidget { pub(crate) fn submit_user_message_with_mode( &mut self, text: String, - collaboration_mode: CollaborationModeMask, + mut collaboration_mode: CollaborationModeMask, ) { + if collaboration_mode.mode == Some(ModeKind::Plan) + && let Some(effort) = self.config.plan_mode_reasoning_effort + { + collaboration_mode.reasoning_effort = Some(Some(effort)); + } if self.agent_turn_running && self.active_collaboration_mask.as_ref() != Some(&collaboration_mode) { diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap index 3eb172c101..2404dced5d 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap @@ -1,6 +1,5 @@ --- source: tui/src/chatwidget/tests.rs -assertion_line: 1548 expression: popup --- Select Reasoning Level for gpt-5.1-codex-max diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 8646033284..f04d02f658 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -2177,6 +2177,243 @@ async fn submit_user_message_with_mode_sets_coding_collaboration_mode() { } } +#[tokio::test] +async fn reasoning_selection_in_plan_mode_opens_scope_prompt_event() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.thread_id = Some(ThreadId::new()); + chat.set_feature_enabled(Feature::CollaborationModes, true); + let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref()) + .expect("expected plan collaboration mode"); + chat.set_collaboration_mask(plan_mask); + let _ = drain_insert_history(&mut rx); + set_chatgpt_auth(&mut chat); + chat.set_reasoning_effort(Some(ReasoningEffortConfig::High)); + + let preset = get_available_model(&chat, "gpt-5.1-codex-max"); + chat.open_reasoning_popup(preset); + chat.handle_key_event(KeyEvent::from(KeyCode::Down)); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let event = rx.try_recv().expect("expected AppEvent"); + assert_matches!( + event, + AppEvent::OpenPlanReasoningScopePrompt { + model, + effort: Some(_) + } if model == "gpt-5.1-codex-max" + ); +} + +#[tokio::test] +async fn reasoning_selection_in_plan_mode_without_effort_change_does_not_open_scope_prompt_event() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.thread_id = Some(ThreadId::new()); + chat.set_feature_enabled(Feature::CollaborationModes, true); + let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref()) + .expect("expected plan collaboration mode"); + chat.set_collaboration_mask(plan_mask); + let _ = drain_insert_history(&mut rx); + set_chatgpt_auth(&mut chat); + + let current_preset = get_available_model(&chat, "gpt-5.1-codex-max"); + chat.set_reasoning_effort(Some(current_preset.default_reasoning_effort)); + + let preset = get_available_model(&chat, "gpt-5.1-codex-max"); + chat.open_reasoning_popup(preset); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let events = std::iter::from_fn(|| rx.try_recv().ok()).collect::>(); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::UpdateModel(model) if model == "gpt-5.1-codex-max" + )), + "expected model update event; events: {events:?}" + ); + assert!( + events + .iter() + .any(|event| matches!(event, AppEvent::UpdateReasoningEffort(Some(_)))), + "expected reasoning update event; events: {events:?}" + ); +} + +#[tokio::test] +async fn reasoning_selection_in_plan_mode_matching_plan_effort_but_different_global_opens_scope_prompt() + { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.thread_id = Some(ThreadId::new()); + chat.set_feature_enabled(Feature::CollaborationModes, true); + let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref()) + .expect("expected plan collaboration mode"); + chat.set_collaboration_mask(plan_mask); + let _ = drain_insert_history(&mut rx); + set_chatgpt_auth(&mut chat); + + // Reproduce: Plan effective reasoning remains the preset (medium), but the + // global default differs (high). Pressing Enter on the current Plan choice + // should open the scope prompt rather than silently rewriting the global default. + chat.set_reasoning_effort(Some(ReasoningEffortConfig::High)); + + let preset = get_available_model(&chat, "gpt-5.1-codex-max"); + chat.open_reasoning_popup(preset); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let event = rx.try_recv().expect("expected AppEvent"); + assert_matches!( + event, + AppEvent::OpenPlanReasoningScopePrompt { + model, + effort: Some(ReasoningEffortConfig::Medium) + } if model == "gpt-5.1-codex-max" + ); +} + +#[tokio::test] +async fn plan_mode_reasoning_override_is_marked_current_in_reasoning_popup() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.set_feature_enabled(Feature::CollaborationModes, true); + set_chatgpt_auth(&mut chat); + chat.set_reasoning_effort(Some(ReasoningEffortConfig::High)); + chat.set_plan_mode_reasoning_effort(Some(ReasoningEffortConfig::Low)); + + let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref()) + .expect("expected plan collaboration mode"); + chat.set_collaboration_mask(plan_mask); + + let preset = get_available_model(&chat, "gpt-5.1-codex-max"); + chat.open_reasoning_popup(preset); + + let popup = render_bottom_popup(&chat, 100); + assert!(popup.contains("Low (current)")); + assert!( + !popup.contains("High (current)"), + "expected Plan override to drive current reasoning label, got: {popup}" + ); +} + +#[tokio::test] +async fn reasoning_selection_in_plan_mode_model_switch_does_not_open_scope_prompt_event() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.thread_id = Some(ThreadId::new()); + chat.set_feature_enabled(Feature::CollaborationModes, true); + let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref()) + .expect("expected plan collaboration mode"); + chat.set_collaboration_mask(plan_mask); + let _ = drain_insert_history(&mut rx); + set_chatgpt_auth(&mut chat); + + let preset = get_available_model(&chat, "gpt-5"); + chat.open_reasoning_popup(preset); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let events = std::iter::from_fn(|| rx.try_recv().ok()).collect::>(); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::UpdateModel(model) if model == "gpt-5" + )), + "expected model update event; events: {events:?}" + ); + assert!( + events + .iter() + .any(|event| matches!(event, AppEvent::UpdateReasoningEffort(Some(_)))), + "expected reasoning update event; events: {events:?}" + ); +} + +#[tokio::test] +async fn plan_reasoning_scope_popup_all_modes_persists_global_and_plan_override() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.open_plan_reasoning_scope_prompt( + "gpt-5.1-codex-max".to_string(), + Some(ReasoningEffortConfig::High), + ); + + chat.handle_key_event(KeyEvent::from(KeyCode::Down)); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let events = std::iter::from_fn(|| rx.try_recv().ok()).collect::>(); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::UpdatePlanModeReasoningEffort(Some(ReasoningEffortConfig::High)) + )), + "expected plan override to be updated; events: {events:?}" + ); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::PersistPlanModeReasoningEffort(Some(ReasoningEffortConfig::High)) + )), + "expected updated plan override to be persisted; events: {events:?}" + ); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::PersistModelSelection { model, effort: Some(ReasoningEffortConfig::High) } + if model == "gpt-5.1-codex-max" + )), + "expected global model reasoning selection persistence; events: {events:?}" + ); +} + +#[tokio::test] +async fn plan_reasoning_scope_popup_mentions_selected_reasoning() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.set_plan_mode_reasoning_effort(Some(ReasoningEffortConfig::Low)); + chat.open_plan_reasoning_scope_prompt( + "gpt-5.1-codex-max".to_string(), + Some(ReasoningEffortConfig::Medium), + ); + + let popup = render_bottom_popup(&chat, 100); + assert!(popup.contains("Choose where to apply medium reasoning.")); + assert!(popup.contains("Always use medium reasoning in Plan mode.")); + assert!(popup.contains("Apply to Plan mode override")); + assert!(popup.contains("Apply to global default and Plan mode override")); + assert!(popup.contains("user-chosen Plan override (low)")); +} + +#[tokio::test] +async fn plan_reasoning_scope_popup_mentions_built_in_plan_default_when_no_override() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.open_plan_reasoning_scope_prompt( + "gpt-5.1-codex-max".to_string(), + Some(ReasoningEffortConfig::Medium), + ); + + let popup = render_bottom_popup(&chat, 100); + assert!(popup.contains("built-in Plan default (medium)")); +} + +#[tokio::test] +async fn plan_reasoning_scope_popup_plan_only_does_not_update_all_modes_reasoning() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.open_plan_reasoning_scope_prompt( + "gpt-5.1-codex-max".to_string(), + Some(ReasoningEffortConfig::High), + ); + + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let events = std::iter::from_fn(|| rx.try_recv().ok()).collect::>(); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::UpdatePlanModeReasoningEffort(Some(ReasoningEffortConfig::High)) + )), + "expected plan-only reasoning update; events: {events:?}" + ); + assert!( + events + .iter() + .all(|event| !matches!(event, AppEvent::UpdateReasoningEffort(_))), + "did not expect all-modes reasoning update; events: {events:?}" + ); +} + #[tokio::test] async fn submit_user_message_with_mode_errors_when_mode_changes_during_running_turn() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await; @@ -3958,7 +4195,29 @@ async fn set_reasoning_effort_updates_active_collaboration_mask() { chat.set_reasoning_effort(None); - assert_eq!(chat.current_reasoning_effort(), None); + assert_eq!( + chat.current_reasoning_effort(), + Some(ReasoningEffortConfig::Medium) + ); + assert_eq!(chat.active_collaboration_mode_kind(), ModeKind::Plan); +} + +#[tokio::test] +async fn set_reasoning_effort_does_not_override_active_plan_override() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1")).await; + chat.set_feature_enabled(Feature::CollaborationModes, true); + chat.set_plan_mode_reasoning_effort(Some(ReasoningEffortConfig::High)); + let plan_mask = + collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan) + .expect("expected plan collaboration mask"); + chat.set_collaboration_mask(plan_mask); + + chat.set_reasoning_effort(Some(ReasoningEffortConfig::Low)); + + assert_eq!( + chat.current_reasoning_effort(), + Some(ReasoningEffortConfig::High) + ); assert_eq!(chat.active_collaboration_mode_kind(), ModeKind::Plan); } diff --git a/docs/config.md b/docs/config.md index 9d53538cae..ed80e559c1 100644 --- a/docs/config.md +++ b/docs/config.md @@ -32,4 +32,13 @@ The generated JSON Schema for `config.toml` lives at `codex-rs/core/config.schem Codex stores "do not show again" flags for some UI prompts under the `[notice]` table. +## Plan mode defaults + +`plan_mode_reasoning_effort` lets you set a Plan-mode-specific default reasoning +effort override. When unset, Plan mode uses the built-in Plan preset default +(currently `medium`). When explicitly set (including `none`), it overrides the +Plan preset. The string value `none` means "no reasoning" (an explicit Plan +override), not "inherit the global default". There is currently no separate +config value for "follow the global default in Plan mode". + Ctrl+C/Ctrl+D quitting uses a ~1 second double-press hint (`ctrl + c again to quit`). From b237f7cbb124563faf6485b70db13886653869b3 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 20 Feb 2026 20:10:51 -0800 Subject: [PATCH 043/385] Add experimental realtime websocket backend prompt override (#12418) - add top-level `experimental_realtime_ws_backend_prompt` config key (experimental / do not use) and include it in config schema - apply the override only to `Op::RealtimeConversation` websocket `backend_prompt`, with config + realtime tests --- codex-rs/core/config.schema.json | 4 ++ codex-rs/core/src/config/mod.rs | 44 +++++++++++++++-- codex-rs/core/src/realtime_conversation.rs | 11 ++--- .../core/tests/suite/realtime_conversation.rs | 47 ++++++++++++++++++- 4 files changed, 96 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index cda5b8eaba..23963196a1 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1544,6 +1544,10 @@ "experimental_compact_prompt_file": { "$ref": "#/definitions/AbsolutePathBuf" }, + "experimental_realtime_ws_backend_prompt": { + "description": "Experimental / do not use. Overrides only the realtime conversation websocket transport backend prompt (the `Op::RealtimeConversation` `/ws` session.create backend_prompt) without changing normal prompts.", + "type": "string" + }, "experimental_realtime_ws_base_url": { "description": "Experimental / do not use. Overrides only the realtime conversation websocket transport base URL (the `Op::RealtimeConversation` `/ws` connection) without changing normal provider HTTP requests.", "type": "string" diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 168633194e..edaabed1fa 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -405,7 +405,10 @@ pub struct Config { /// websocket transport base URL (the `Op::RealtimeConversation` `/ws` /// connection) without changing normal provider HTTP requests. pub experimental_realtime_ws_base_url: Option, - + /// Experimental / do not use. Overrides only the realtime conversation + /// websocket transport backend prompt (the `Op::RealtimeConversation` + /// `/ws` session.create backend_prompt) without changing normal prompts. + pub experimental_realtime_ws_backend_prompt: Option, /// When set, restricts ChatGPT login to a specific workspace identifier. pub forced_chatgpt_workspace_id: Option, @@ -1136,7 +1139,10 @@ pub struct ConfigToml { /// websocket transport base URL (the `Op::RealtimeConversation` `/ws` /// connection) without changing normal provider HTTP requests. pub experimental_realtime_ws_base_url: Option, - + /// Experimental / do not use. Overrides only the realtime conversation + /// websocket transport backend prompt (the `Op::RealtimeConversation` + /// `/ws` session.create backend_prompt) without changing normal prompts. + pub experimental_realtime_ws_backend_prompt: Option, pub projects: Option>, /// Controls the web search tool mode: disabled, cached, or live. @@ -2065,6 +2071,7 @@ impl Config { .or(cfg.chatgpt_base_url) .unwrap_or("https://chatgpt.com/backend-api/".to_string()), experimental_realtime_ws_base_url: cfg.experimental_realtime_ws_base_url, + experimental_realtime_ws_backend_prompt: cfg.experimental_realtime_ws_backend_prompt, forced_chatgpt_workspace_id, forced_login_method, include_apply_patch_tool: include_apply_patch_tool_flag, @@ -4607,6 +4614,7 @@ model_verbosity = "high" personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -4728,6 +4736,7 @@ model_verbosity = "high" personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -4847,6 +4856,7 @@ model_verbosity = "high" personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -4952,6 +4962,7 @@ model_verbosity = "high" personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, compact_prompt: None, @@ -5738,7 +5749,6 @@ trust_level = "untrusted" ); Ok(()) } - #[test] fn experimental_realtime_ws_base_url_loads_from_config_toml() -> std::io::Result<()> { let cfg: ConfigToml = toml::from_str( @@ -5766,6 +5776,34 @@ experimental_realtime_ws_base_url = "http://127.0.0.1:8011" ); Ok(()) } + + #[test] + fn experimental_realtime_ws_backend_prompt_loads_from_config_toml() -> std::io::Result<()> { + let cfg: ConfigToml = toml::from_str( + r#" +experimental_realtime_ws_backend_prompt = "prompt from config" +"#, + ) + .expect("TOML deserialization should succeed"); + + assert_eq!( + cfg.experimental_realtime_ws_backend_prompt.as_deref(), + Some("prompt from config") + ); + + let codex_home = TempDir::new()?; + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!( + config.experimental_realtime_ws_backend_prompt.as_deref(), + Some("prompt from config") + ); + Ok(()) + } } #[cfg(test)] diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index b41b4bd0d4..b67874593f 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -174,18 +174,17 @@ pub(crate) async fn handle_start( if let Some(realtime_ws_base_url) = &config.experimental_realtime_ws_base_url { api_provider.base_url = realtime_ws_base_url.clone(); } + let prompt = config + .experimental_realtime_ws_backend_prompt + .clone() + .unwrap_or(params.prompt); let requested_session_id = params .session_id .or_else(|| Some(sess.conversation_id.to_string())); let events_rx = match sess .conversation - .start( - api_provider, - None, - params.prompt, - requested_session_id.clone(), - ) + .start(api_provider, None, prompt, requested_session_id.clone()) .await { Ok(events_rx) => events_rx, diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index ddc63385de..3d94ccf533 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -358,7 +358,6 @@ async fn conversation_second_start_replaces_runtime() -> Result<()> { server.shutdown().await; Ok(()) } - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn conversation_uses_experimental_realtime_ws_base_url_override() -> Result<()> { skip_if_no_network!(Ok(())); @@ -413,3 +412,49 @@ async fn conversation_uses_experimental_realtime_ws_base_url_override() -> Resul realtime_server.shutdown().await; Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_uses_experimental_realtime_ws_backend_prompt_override() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![ + vec![], + vec![vec![json!({ + "type": "session.created", + "session": { "id": "sess_override" } + })]], + ]) + .await; + + let mut builder = test_codex().with_config(|config| { + config.experimental_realtime_ws_backend_prompt = Some("prompt from config".to_string()); + }); + let test = builder.build_with_websocket_server(&server).await?; + assert!(server.wait_for_handshakes(1, Duration::from_secs(2)).await); + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "prompt from op".to_string(), + session_id: None, + })) + .await?; + + let session_created = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + assert_eq!(session_created, "sess_override"); + + let connections = server.connections(); + assert_eq!(connections.len(), 2); + assert_eq!( + connections[1][0].body_json()["session"]["backend_prompt"].as_str(), + Some("prompt from config") + ); + + server.shutdown().await; + Ok(()) +} From a73efab8dd6ca8371dc637ae67d4de991d69fb2e Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 20 Feb 2026 20:36:04 -0800 Subject: [PATCH 044/385] fix: address flakiness in thread_resume_rejoins_running_thread_even_with_override_mismatch (#12381) ## Why `thread/resume` responses for already-running threads can be reported as `Idle` even while a turn is still in progress. This is caused by a timing window where the runtime watch state has not yet observed the running-thread transition, so API clients can receive stale status information at resume time. Possibly related: https://github.com/openai/codex/pull/11786 ## What - Add a shared status normalization helper, `resolve_thread_status`, in `codex-rs/app-server/src/thread_status.rs` that resolves `Idle`/`NotLoaded` to `Active { active_flags: [] }` when an in-progress turn is known. - Reuse this helper across thread response paths in `codex-rs/app-server/src/codex_message_processor.rs` (including `thread/start`, `thread/unarchive`, `thread/read`, `thread/resume`, `thread/fork`, and review/thread-started notification responses). - In `handle_pending_thread_resume_request`, use both the in-memory `active_turn_snapshot` and the resumed rollout turns to decide whether a turn is in progress before resolving thread status for the response. - Extend `thread_status` tests to validate the new status-resolution behavior directly. ## Verification - `cargo test -p codex-app-server suite::v2::thread_resume::thread_resume_rejoins_running_thread_even_with_override_mismatch` --- .../app-server/src/codex_message_processor.rs | 81 ++++++++++++------- codex-rs/app-server/src/thread_status.rs | 47 +++++++++++ 2 files changed, 101 insertions(+), 27 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 72dc7eaea2..17a67fa4dc 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -11,6 +11,7 @@ use crate::outgoing_message::OutgoingMessageSender; use crate::outgoing_message::OutgoingNotification; use crate::outgoing_message::ThreadScopedOutgoingMessageSender; use crate::thread_status::ThreadWatchManager; +use crate::thread_status::resolve_thread_status; use chrono::DateTime; use chrono::SecondsFormat; use chrono::Utc; @@ -2053,10 +2054,12 @@ impl CodexMessageProcessor { .upsert_thread(thread.clone()) .await; - thread.status = self - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + false, + ); let response = ThreadStartResponse { thread: thread.clone(), @@ -2372,10 +2375,12 @@ impl CodexMessageProcessor { match result { Ok(mut thread) => { - thread.status = self - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + false, + ); self.attach_thread_name(thread_id, &mut thread).await; let thread_id = thread.id.clone(); let response = ThreadUnarchiveResponse { thread }; @@ -2769,10 +2774,12 @@ impl CodexMessageProcessor { } } - thread.status = self - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + false, + ); let response = ThreadReadResponse { thread }; self.outgoing.send_response(request_id, response).await; } @@ -2949,10 +2956,12 @@ impl CodexMessageProcessor { .upsert_thread(thread.clone()) .await; - thread.status = self - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + false, + ); let response = ThreadResumeResponse { thread, @@ -3475,10 +3484,12 @@ impl CodexMessageProcessor { .upsert_thread(thread.clone()) .await; - thread.status = self - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + false, + ); let response = ThreadForkResponse { thread: thread.clone(), @@ -5616,10 +5627,12 @@ impl CodexMessageProcessor { self.thread_watch_manager .upsert_thread(thread.clone()) .await; - thread.status = self - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + false, + ); let notif = ThreadStartedNotification { thread }; self.outgoing .send_server_notification(ServerNotification::ThreadStarted(notif)) @@ -6283,6 +6296,9 @@ async fn handle_pending_thread_resume_request( let state = thread_state.lock().await; state.active_turn_snapshot() }; + let mut has_in_progress_turn = active_turn + .as_ref() + .is_some_and(|turn| matches!(turn.status, TurnStatus::InProgress)); let request_id = pending.request_id; let connection_id = request_id.connection_id; @@ -6309,9 +6325,20 @@ async fn handle_pending_thread_resume_request( return; } }; - thread.status = thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await; + + has_in_progress_turn = has_in_progress_turn + || thread + .turns + .iter() + .any(|turn| matches!(turn.status, TurnStatus::InProgress)); + + let status = resolve_thread_status( + thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + has_in_progress_turn, + ); + thread.status = status; match find_thread_name_by_id(codex_home, &conversation_id).await { Ok(thread_name) => thread.name = thread_name, diff --git a/codex-rs/app-server/src/thread_status.rs b/codex-rs/app-server/src/thread_status.rs index 48e3d9ab08..5693631111 100644 --- a/codex-rs/app-server/src/thread_status.rs +++ b/codex-rs/app-server/src/thread_status.rs @@ -239,6 +239,22 @@ impl ThreadWatchManager { } } +pub(crate) fn resolve_thread_status( + status: ThreadStatus, + has_in_progress_turn: bool, +) -> ThreadStatus { + // Running-turn events can arrive before the watch runtime state is observed by + // the listener loop. In that window we prefer to reflect a real active turn as + // `Active` instead of `Idle`/`NotLoaded`. + if has_in_progress_turn && matches!(status, ThreadStatus::Idle | ThreadStatus::NotLoaded) { + return ThreadStatus::Active { + active_flags: Vec::new(), + }; + } + + status +} + #[derive(Default)] struct ThreadWatchState { runtime_by_thread_id: HashMap, @@ -459,6 +475,37 @@ mod tests { ); } + #[test] + fn resolves_in_progress_turn_to_active_status() { + let status = resolve_thread_status(ThreadStatus::Idle, true); + assert_eq!( + status, + ThreadStatus::Active { + active_flags: Vec::new(), + } + ); + + let status = resolve_thread_status(ThreadStatus::NotLoaded, true); + assert_eq!( + status, + ThreadStatus::Active { + active_flags: Vec::new(), + } + ); + } + + #[test] + fn keeps_status_when_no_in_progress_turn() { + assert_eq!( + resolve_thread_status(ThreadStatus::Idle, false), + ThreadStatus::Idle + ); + assert_eq!( + resolve_thread_status(ThreadStatus::SystemError, false), + ThreadStatus::SystemError + ); + } + #[tokio::test] async fn system_error_sets_idle_flag_until_next_turn() { let manager = ThreadWatchManager::new(); From 48af93399e1e5105fe7a770e61e572b070dc3cf9 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 20 Feb 2026 20:43:36 -0800 Subject: [PATCH 045/385] feat: use OAI Responses API MessagePhase type directly in App Server v2 (#12422) https://github.com/openai/codex/pull/10455 introduced the `phase` field, and then https://github.com/openai/codex/pull/12072 introduced a `MessagePhase` type in `v2.rs` that paralleled the `MessagePhase` type in `codex-rs/protocol/src/models.rs`. The app server protocol prefers `camelCase` while the Responses API uses `snake_case`, so this meant we had two versions of `MessagePhase` with different serialization rules. When the app server protocol refers to types from the Responses API, we use the wire format of the the Responses API even though it is inconsistent with the app server API. This PR deletes `MessagePhase` from `v2.rs` and consolidates on the Responses API version to eliminate confusion. --- .../schema/json/ServerNotification.json | 13 +++------- .../json/v2/ItemCompletedNotification.json | 22 ++++++++++++---- .../json/v2/ItemStartedNotification.json | 22 ++++++++++++---- .../schema/json/v2/ReviewStartResponse.json | 22 ++++++++++++---- .../schema/json/v2/ThreadForkResponse.json | 22 ++++++++++++---- .../schema/json/v2/ThreadListResponse.json | 22 ++++++++++++---- .../schema/json/v2/ThreadReadResponse.json | 22 ++++++++++++---- .../schema/json/v2/ThreadResumeResponse.json | 22 ++++++++++++---- .../json/v2/ThreadRollbackResponse.json | 22 ++++++++++++---- .../schema/json/v2/ThreadStartResponse.json | 22 ++++++++++++---- .../json/v2/ThreadStartedNotification.json | 22 ++++++++++++---- .../json/v2/ThreadUnarchiveResponse.json | 22 ++++++++++++---- .../json/v2/TurnCompletedNotification.json | 22 ++++++++++++---- .../schema/json/v2/TurnStartResponse.json | 22 ++++++++++++---- .../json/v2/TurnStartedNotification.json | 22 ++++++++++++---- .../schema/typescript/v2/MessagePhase.ts | 5 ---- .../schema/typescript/v2/ThreadItem.ts | 2 +- .../schema/typescript/v2/index.ts | 1 - .../src/protocol/thread_history.rs | 14 +++++------ .../app-server-protocol/src/protocol/v2.rs | 25 +++---------------- 20 files changed, 251 insertions(+), 117 deletions(-) delete mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/MessagePhase.ts diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 51c445bf14..bcdbdb33ed 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1618,7 +1618,7 @@ "phase": { "anyOf": [ { - "$ref": "#/definitions/MessagePhase2" + "$ref": "#/definitions/MessagePhase" }, { "type": "null" @@ -4660,13 +4660,6 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" - }, - "MessagePhase2": { "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", "oneOf": [ { @@ -5732,7 +5725,7 @@ "phase": { "anyOf": [ { - "$ref": "#/definitions/MessagePhase2" + "$ref": "#/definitions/MessagePhase" }, { "type": "null" @@ -7923,7 +7916,7 @@ "phase": { "anyOf": [ { - "$ref": "#/definitions/MessagePhase2" + "$ref": "#/definitions/MessagePhase" }, { "type": "null" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json index 1a0ef630a1..98d8a631e9 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json @@ -237,11 +237,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json index 50e7e1e664..ee10e470e0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json @@ -237,11 +237,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json index e71ebbdc7f..760477095f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json @@ -351,11 +351,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 55480c5bc7..71f9da2f3b 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -420,11 +420,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "NetworkAccess": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index 9e4e4d63b4..5907d13cea 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -374,11 +374,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index acb80dd56f..9944457c3e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -374,11 +374,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 884930d4d6..7778773a16 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -420,11 +420,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "NetworkAccess": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index 555083baf2..c4bcdf7092 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -374,11 +374,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 2acd4da8fb..6b3d2ebc58 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -420,11 +420,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "NetworkAccess": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index a39ec5151c..2fbd9538f3 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -374,11 +374,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index e18582f069..df3e7beee5 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -374,11 +374,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json index e20e71be29..2c8eec7f90 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json @@ -351,11 +351,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json index 4fb088a13e..5585cd455a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json @@ -351,11 +351,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json index 4e7f82f4e5..4462c314d2 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json @@ -351,11 +351,23 @@ "type": "string" }, "MessagePhase": { - "enum": [ - "commentary", - "finalAnswer" - ], - "type": "string" + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] }, "PatchApplyStatus": { "enum": [ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/MessagePhase.ts b/codex-rs/app-server-protocol/schema/typescript/v2/MessagePhase.ts deleted file mode 100644 index 80d7236e74..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/MessagePhase.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type MessagePhase = "commentary" | "finalAnswer"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts index cbdad0bf2b..dee39cd5db 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts @@ -1,6 +1,7 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { MessagePhase } from "../MessagePhase"; import type { JsonValue } from "../serde_json/JsonValue"; import type { CollabAgentState } from "./CollabAgentState"; import type { CollabAgentTool } from "./CollabAgentTool"; @@ -11,7 +12,6 @@ import type { FileUpdateChange } from "./FileUpdateChange"; import type { McpToolCallError } from "./McpToolCallError"; import type { McpToolCallResult } from "./McpToolCallResult"; import type { McpToolCallStatus } from "./McpToolCallStatus"; -import type { MessagePhase } from "./MessagePhase"; import type { PatchApplyStatus } from "./PatchApplyStatus"; import type { UserInput } from "./UserInput"; import type { WebSearchAction } from "./WebSearchAction"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index c2f8494785..ce2289c382 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -95,7 +95,6 @@ export type { McpToolCallProgressNotification } from "./McpToolCallProgressNotif export type { McpToolCallResult } from "./McpToolCallResult"; export type { McpToolCallStatus } from "./McpToolCallStatus"; export type { MergeStrategy } from "./MergeStrategy"; -export type { MessagePhase } from "./MessagePhase"; export type { Model } from "./Model"; export type { ModelListParams } from "./ModelListParams"; export type { ModelListResponse } from "./ModelListResponse"; diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index fce6f4f263..c6d0cc00fe 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -16,7 +16,7 @@ use crate::protocol::v2::TurnError; use crate::protocol::v2::TurnStatus; use crate::protocol::v2::UserInput; use crate::protocol::v2::WebSearchAction; -use codex_protocol::models::MessagePhase as CoreMessagePhase; +use codex_protocol::models::MessagePhase; use codex_protocol::protocol::AgentReasoningEvent; use codex_protocol::protocol::AgentReasoningRawContentEvent; use codex_protocol::protocol::AgentStatus; @@ -190,17 +190,15 @@ impl ThreadHistoryBuilder { self.current_turn = Some(turn); } - fn handle_agent_message(&mut self, text: String, phase: Option) { + fn handle_agent_message(&mut self, text: String, phase: Option) { if text.is_empty() { return; } let id = self.next_item_id(); - self.ensure_turn().items.push(ThreadItem::AgentMessage { - id, - text, - phase: phase.map(Into::into), - }); + self.ensure_turn() + .items + .push(ThreadItem::AgentMessage { id, text, phase }); } fn handle_agent_reasoning(&mut self, payload: &AgentReasoningEvent) { @@ -1196,7 +1194,7 @@ mod tests { ThreadItem::AgentMessage { id: "item-1".into(), text: "Final reply".into(), - phase: Some(crate::protocol::v2::MessagePhase::FinalAnswer), + phase: Some(MessagePhase::FinalAnswer), } ); } diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 4b3ffaf02f..43038d351c 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -20,7 +20,7 @@ use codex_protocol::items::TurnItem as CoreTurnItem; use codex_protocol::mcp::Resource as McpResource; use codex_protocol::mcp::ResourceTemplate as McpResourceTemplate; use codex_protocol::mcp::Tool as McpTool; -use codex_protocol::models::MessagePhase as CoreMessagePhase; +use codex_protocol::models::MessagePhase; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ReasoningEffort; @@ -2666,24 +2666,6 @@ impl From for UserInput { } } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -#[ts(rename_all = "camelCase")] -#[ts(export_to = "v2/")] -pub enum MessagePhase { - Commentary, - FinalAnswer, -} - -impl From for MessagePhase { - fn from(value: CoreMessagePhase) -> Self { - match value { - CoreMessagePhase::Commentary => Self::Commentary, - CoreMessagePhase::FinalAnswer => Self::FinalAnswer, - } - } -} - #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "camelCase")] #[ts(tag = "type")] @@ -2873,7 +2855,7 @@ impl From for ThreadItem { ThreadItem::AgentMessage { id: agent.id, text, - phase: agent.phase.map(Into::into), + phase: agent.phase, } } CoreTurnItem::Plan(plan) => ThreadItem::Plan { @@ -3692,7 +3674,6 @@ mod tests { use codex_protocol::items::TurnItem; use codex_protocol::items::UserMessageItem; use codex_protocol::items::WebSearchItem; - use codex_protocol::models::MessagePhase as CoreMessagePhase; use codex_protocol::models::WebSearchAction as CoreWebSearchAction; use codex_protocol::protocol::NetworkAccess as CoreNetworkAccess; use codex_protocol::protocol::ReadOnlyAccess as CoreReadOnlyAccess; @@ -3902,7 +3883,7 @@ mod tests { content: vec![AgentMessageContent::Text { text: "final".to_string(), }], - phase: Some(CoreMessagePhase::FinalAnswer), + phase: Some(MessagePhase::FinalAnswer), }); assert_eq!( From dca9c40dd5f9b4ad8cca7b67c01ea055feecc2bf Mon Sep 17 00:00:00 2001 From: Yaroslav Volovich Date: Sat, 21 Feb 2026 05:15:21 +0000 Subject: [PATCH 046/385] test(app-server): wait for turn/completed in turn_start tests (#12376) ## Summary - switch a few app-server `turn_start` tests from `codex/event/task_complete` waits to `turn/completed` waits - avoid matching unrelated/background `task_complete` events - keep this flaky test fix separate from the /title feature PR ## Why On Windows ARM CI, these tests can return early after observing a generic `codex/event/task_complete` notification from another task. That can leave the mock Responses server with fewer calls than expected and fail the test with a wiremock verification mismatch. Using `turn/completed` matches the app-server turn lifecycle notification the tests actually care about. ## Validation - `cargo test -p codex-app-server turn_start_updates_sandbox_and_cwd_between_turns_v2 -- --nocapture` - `cargo test -p codex-app-server turn_start_exec_approval_ -- --nocapture` - `just fmt` --- codex-rs/app-server/tests/suite/v2/turn_start.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index d2d850176d..8d6db34731 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -847,7 +847,9 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> { // Approve and wait for task completion mcp.send_response( request_id, - serde_json::json!({ "decision": codex_core::protocol::ReviewDecision::Approved }), + serde_json::to_value(CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::Accept, + })?, ) .await?; timeout( @@ -1035,7 +1037,7 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> { timeout( DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), + mcp.read_stream_until_notification_message("turn/completed"), ) .await??; @@ -1129,7 +1131,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { .await??; timeout( DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), + mcp.read_stream_until_notification_message("turn/completed"), ) .await??; mcp.clear_message_buffer(); From 1779feb6a7b5937a81e5134379e3a729416948ff Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 20 Feb 2026 21:36:12 -0800 Subject: [PATCH 047/385] ignore v1 in JSON schema codegen (#12408) ## Why The generated unnamespaced JSON envelope schemas (`ClientRequest` and `ServerNotification`) still contained both v1 and v2 variants, which pulled legacy v1/core types and v2 types into the same `definitions` graph. That caused `schemars` to produce numeric suffix names (for example `AskForApproval2`, `ByteRange2`, `MessagePhase2`). This PR moves JSON codegen toward v2-only output while preserving the unnamespaced envelope artifacts, and avoids reintroducing numeric-suffix tolerance by removing the v1/internal-only variants that caused the collisions in those envelope schemas. ## What Changed - In `codex-rs/app-server-protocol/src/export.rs`, JSON generation now excludes v1 schema artifacts (`v1/*`) while continuing to emit unnamespaced/root JSON schemas and the JSON bundle. - Added a narrow JSON v1 allowlist (`JSON_V1_ALLOWLIST`) so `InitializeParams` and `InitializeResponse` are still emitted. - Added JSON-only post-processing for the mixed envelope schemas before collision checks run: - `ClientRequest`: strips v1 request variants from the generated `oneOf` using the temporary `V1_CLIENT_REQUEST_METHODS` list - `ServerNotification`: strips v1 notifications plus the internal-only `rawResponseItem/completed` notification using the temporary `EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON` list - Added a temporary local-definition pruning pass for those envelope schemas so now-unreferenced v1/core definitions are removed from `definitions` after method filtering. - Updated the variant-title naming heuristic for single-property literal object variants to use the literal value (when available), avoiding collisions like multiple `state`-only variants all deriving the same title. - Collision handling remains fail-fast (no numeric suffix fallback map in this PR path). ## Verification - `just write-app-server-schema` --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/12408). * __->__ #12408 * #12406 --- .../schema/json/ClientRequest.json | 1365 ---- .../schema/json/EventMsg.json | 6 +- .../schema/json/ServerNotification.json | 5898 ----------------- .../codex_app_server_protocol.schemas.json | 3996 +---------- .../v1/AddConversationListenerParams.json | 22 - .../AddConversationSubscriptionResponse.json | 13 - .../json/v1/ArchiveConversationParams.json | 22 - .../json/v1/ArchiveConversationResponse.json | 5 - .../json/v1/AuthStatusChangeNotification.json | 46 - .../json/v1/CancelLoginChatGptParams.json | 13 - .../json/v1/CancelLoginChatGptResponse.json | 5 - .../json/v1/ExecOneOffCommandParams.json | 225 - .../json/v1/ExecOneOffCommandResponse.json | 22 - .../json/v1/ForkConversationParams.json | 195 - .../json/v1/ForkConversationResponse.json | 5776 ---------------- .../schema/json/v1/GetAuthStatusParams.json | 19 - .../schema/json/v1/GetAuthStatusResponse.json | 57 - .../json/v1/GetConversationSummaryParams.json | 35 - .../v1/GetConversationSummaryResponse.json | 190 - .../schema/json/v1/GetUserAgentResponse.json | 13 - .../json/v1/GetUserSavedConfigResponse.json | 366 - .../schema/json/v1/GitDiffToRemoteParams.json | 13 - .../json/v1/GitDiffToRemoteResponse.json | 22 - .../json/v1/InterruptConversationParams.json | 18 - .../v1/InterruptConversationResponse.json | 23 - .../json/v1/ListConversationsParams.json | 30 - .../json/v1/ListConversationsResponse.json | 199 - .../schema/json/v1/LoginApiKeyParams.json | 13 - .../schema/json/v1/LoginApiKeyResponse.json | 5 - .../v1/LoginChatGptCompleteNotification.json | 24 - .../schema/json/v1/LoginChatGptResponse.json | 17 - .../schema/json/v1/LogoutChatGptResponse.json | 5 - .../schema/json/v1/NewConversationParams.json | 161 - .../json/v1/NewConversationResponse.json | 48 - .../v1/RemoveConversationListenerParams.json | 13 - ...emoveConversationSubscriptionResponse.json | 5 - .../json/v1/ResumeConversationParams.json | 984 --- .../json/v1/ResumeConversationResponse.json | 5776 ---------------- .../schema/json/v1/SendUserMessageParams.json | 165 - .../json/v1/SendUserMessageResponse.json | 5 - .../schema/json/v1/SendUserTurnParams.json | 482 -- .../schema/json/v1/SendUserTurnResponse.json | 5 - .../v1/SessionConfiguredNotification.json | 5798 ---------------- .../schema/json/v1/SetDefaultModelParams.json | 37 - .../json/v1/SetDefaultModelResponse.json | 5 - .../schema/json/v1/UserInfoResponse.json | 13 - codex-rs/app-server-protocol/src/export.rs | 372 +- 47 files changed, 204 insertions(+), 32323 deletions(-) delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/AddConversationListenerParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/AddConversationSubscriptionResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/AuthStatusChangeNotification.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ForkConversationParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GetUserAgentResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GetUserSavedConfigResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/InterruptConversationParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/InterruptConversationResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ListConversationsParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/LoginChatGptCompleteNotification.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/LoginChatGptResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/LogoutChatGptResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/NewConversationParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/NewConversationResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/RemoveConversationListenerParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/RemoveConversationSubscriptionResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ResumeConversationParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/SendUserMessageParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/SendUserMessageResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/SendUserTurnParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/SendUserTurnResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelParams.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelResponse.json delete mode 100644 codex-rs/app-server-protocol/schema/json/v1/UserInfoResponse.json diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 76ba36735c..cee6e6d04b 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -5,21 +5,6 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, - "AddConversationListenerParams": { - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "experimentalRawEvents": { - "default": false, - "type": "boolean" - } - }, - "required": [ - "conversationId" - ], - "type": "object" - }, "AppsListParams": { "description": "EXPERIMENTAL - list available apps/connectors.", "properties": { @@ -53,21 +38,6 @@ }, "type": "object" }, - "ArchiveConversationParams": { - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "rolloutPath" - ], - "type": "object" - }, "AskForApproval": { "oneOf": [ { @@ -110,53 +80,6 @@ } ] }, - "AskForApproval2": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval2", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, "ByteRange": { "properties": { "end": { @@ -187,17 +110,6 @@ ], "type": "object" }, - "CancelLoginChatGptParams": { - "properties": { - "loginId": { - "type": "string" - } - }, - "required": [ - "loginId" - ], - "type": "object" - }, "ClientInfo": { "properties": { "name": { @@ -443,44 +355,6 @@ ], "type": "object" }, - "ExecOneOffCommandParams": { - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "sandboxPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxPolicy2" - }, - { - "type": "null" - } - ] - }, - "timeoutMs": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "command" - ], - "type": "object" - }, "ExperimentalFeatureListParams": { "properties": { "cursor": { @@ -538,37 +412,6 @@ ], "type": "object" }, - "ForkConversationParams": { - "properties": { - "conversationId": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "overrides": { - "anyOf": [ - { - "$ref": "#/definitions/NewConversationParams" - }, - { - "type": "null" - } - ] - }, - "path": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, "FunctionCallOutputBody": { "anyOf": [ { @@ -679,51 +522,6 @@ }, "type": "object" }, - "GetAuthStatusParams": { - "properties": { - "includeToken": { - "type": [ - "boolean", - "null" - ] - }, - "refreshToken": { - "type": [ - "boolean", - "null" - ] - } - }, - "type": "object" - }, - "GetConversationSummaryParams": { - "anyOf": [ - { - "properties": { - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "rolloutPath" - ], - "title": "RolloutPathGetConversationSummaryParams", - "type": "object" - }, - { - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "conversationId" - ], - "title": "ConversationIdGetConversationSummaryParams", - "type": "object" - } - ] - }, "GhostCommit": { "description": "Details of a ghost commit created from a repository state.", "properties": { @@ -756,17 +554,6 @@ ], "type": "object" }, - "GitDiffToRemoteParams": { - "properties": { - "cwd": { - "type": "string" - } - }, - "required": [ - "cwd" - ], - "type": "object" - }, "HazelnutScope": { "enum": [ "example", @@ -818,141 +605,6 @@ ], "type": "object" }, - "InputItem": { - "oneOf": [ - { - "properties": { - "data": { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/V1TextElement" - }, - "type": "array" - } - }, - "required": [ - "text" - ], - "type": "object" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "TextInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "image_url": { - "type": "string" - } - }, - "required": [ - "image_url" - ], - "type": "object" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "ImageInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "path": { - "type": "string" - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "type": { - "enum": [ - "localImage" - ], - "title": "LocalImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "LocalImageInputItem", - "type": "object" - } - ] - }, - "InterruptConversationParams": { - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "conversationId" - ], - "type": "object" - }, - "ListConversationsParams": { - "properties": { - "cursor": { - "type": [ - "string", - "null" - ] - }, - "modelProviders": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "pageSize": { - "format": "uint", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - }, "ListMcpServerStatusParams": { "properties": { "cursor": { @@ -1112,17 +764,6 @@ } ] }, - "LoginApiKeyParams": { - "properties": { - "apiKey": { - "type": "string" - } - }, - "required": [ - "apiKey" - ], - "type": "object" - }, "McpServerOauthLoginParams": { "properties": { "name": { @@ -1219,94 +860,6 @@ ], "type": "string" }, - "NetworkAccess2": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, - "NewConversationParams": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval2" - }, - { - "type": "null" - } - ] - }, - "baseInstructions": { - "type": [ - "string", - "null" - ] - }, - "compactPrompt": { - "type": [ - "string", - "null" - ] - }, - "config": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "developerInstructions": { - "type": [ - "string", - "null" - ] - }, - "includeApplyPatchTool": { - "type": [ - "boolean", - "null" - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelProvider": { - "type": [ - "string", - "null" - ] - }, - "profile": { - "type": [ - "string", - "null" - ] - }, - "sandbox": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxMode2" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, "Personality": { "enum": [ "none", @@ -1371,57 +924,6 @@ } ] }, - "ReadOnlyAccess2": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccess2Type", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess2", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccess2Type", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess2", - "type": "object" - } - ] - }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ @@ -1522,39 +1024,6 @@ } ] }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "RemoveConversationListenerParams": { - "properties": { - "subscriptionId": { - "type": "string" - } - }, - "required": [ - "subscriptionId" - ], - "type": "object" - }, "RequestId": { "anyOf": [ { @@ -1922,46 +1391,6 @@ } ] }, - "ResumeConversationParams": { - "properties": { - "conversationId": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "history": { - "items": { - "$ref": "#/definitions/ResponseItem" - }, - "type": [ - "array", - "null" - ] - }, - "overrides": { - "anyOf": [ - { - "$ref": "#/definitions/NewConversationParams" - }, - { - "type": "null" - } - ] - }, - "path": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, "ReviewDelivery": { "enum": [ "inline", @@ -2095,14 +1524,6 @@ ], "type": "string" }, - "SandboxMode2": { - "enum": [ - "read-only", - "workspace-write", - "danger-full-access" - ], - "type": "string" - }, "SandboxPolicy": { "oneOf": [ { @@ -2218,216 +1639,6 @@ } ] }, - "SandboxPolicy2": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicy2Type", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy2", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess2" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicy2Type", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy2", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess2" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicy2Type", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy2", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess2" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicy2Type", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy2", - "type": "object" - } - ] - }, - "SendUserMessageParams": { - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "items": { - "items": { - "$ref": "#/definitions/InputItem" - }, - "type": "array" - } - }, - "required": [ - "conversationId", - "items" - ], - "type": "object" - }, - "SendUserTurnParams": { - "properties": { - "approvalPolicy": { - "$ref": "#/definitions/AskForApproval2" - }, - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "cwd": { - "type": "string" - }, - "effort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "items": { - "items": { - "$ref": "#/definitions/InputItem" - }, - "type": "array" - }, - "model": { - "type": "string" - }, - "outputSchema": { - "description": "Optional JSON Schema used to constrain the final assistant message for this turn." - }, - "sandboxPolicy": { - "$ref": "#/definitions/SandboxPolicy2" - }, - "summary": { - "$ref": "#/definitions/ReasoningSummary" - } - }, - "required": [ - "approvalPolicy", - "conversationId", - "cwd", - "items", - "model", - "sandboxPolicy", - "summary" - ], - "type": "object" - }, - "SetDefaultModelParams": { - "properties": { - "model": { - "type": [ - "string", - "null" - ] - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, "Settings": { "description": "Settings for a collaboration mode.", "properties": { @@ -2667,9 +1878,6 @@ ], "type": "object" }, - "ThreadId": { - "type": "string" - }, "ThreadListParams": { "properties": { "archived": { @@ -3245,50 +2453,6 @@ } ] }, - "V1ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "V1TextElement": { - "properties": { - "byteRange": { - "allOf": [ - { - "$ref": "#/definitions/V1ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byteRange" - ], - "type": "object" - }, "WebSearchAction": { "oneOf": [ { @@ -4321,510 +3485,6 @@ "title": "Account/readRequest", "type": "object" }, - { - "description": "DEPRECATED APIs below", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "newConversation" - ], - "title": "NewConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/NewConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "NewConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getConversationSummary" - ], - "title": "GetConversationSummaryRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/GetConversationSummaryParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "GetConversationSummaryRequest", - "type": "object" - }, - { - "description": "List recorded Codex conversations (rollouts) with optional pagination and search.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "listConversations" - ], - "title": "ListConversationsRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ListConversationsParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ListConversationsRequest", - "type": "object" - }, - { - "description": "Resume a recorded Codex conversation from a rollout file.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "resumeConversation" - ], - "title": "ResumeConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ResumeConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ResumeConversationRequest", - "type": "object" - }, - { - "description": "Fork a recorded Codex conversation into a new session.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "forkConversation" - ], - "title": "ForkConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ForkConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ForkConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "archiveConversation" - ], - "title": "ArchiveConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ArchiveConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ArchiveConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "sendUserMessage" - ], - "title": "SendUserMessageRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SendUserMessageParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "SendUserMessageRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "sendUserTurn" - ], - "title": "SendUserTurnRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SendUserTurnParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "SendUserTurnRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "interruptConversation" - ], - "title": "InterruptConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/InterruptConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "InterruptConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "addConversationListener" - ], - "title": "AddConversationListenerRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/AddConversationListenerParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "AddConversationListenerRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "removeConversationListener" - ], - "title": "RemoveConversationListenerRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/RemoveConversationListenerParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "RemoveConversationListenerRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "gitDiffToRemote" - ], - "title": "GitDiffToRemoteRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/GitDiffToRemoteParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "GitDiffToRemoteRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "loginApiKey" - ], - "title": "LoginApiKeyRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/LoginApiKeyParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "LoginApiKeyRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "loginChatGpt" - ], - "title": "LoginChatGptRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "LoginChatGptRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "cancelLoginChatGpt" - ], - "title": "CancelLoginChatGptRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/CancelLoginChatGptParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "CancelLoginChatGptRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "logoutChatGpt" - ], - "title": "LogoutChatGptRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "LogoutChatGptRequest", - "type": "object" - }, - { - "description": "DEPRECATED in favor of GetAccount", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getAuthStatus" - ], - "title": "GetAuthStatusRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/GetAuthStatusParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "GetAuthStatusRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getUserSavedConfig" - ], - "title": "GetUserSavedConfigRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "GetUserSavedConfigRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "setDefaultModel" - ], - "title": "SetDefaultModelRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SetDefaultModelParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "SetDefaultModelRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getUserAgent" - ], - "title": "GetUserAgentRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "GetUserAgentRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "userInfo" - ], - "title": "UserInfoRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "UserInfoRequest", - "type": "object" - }, { "properties": { "id": { @@ -4848,31 +3508,6 @@ ], "title": "FuzzyFileSearchRequest", "type": "object" - }, - { - "description": "Execute a command (argv vector) under the server's sandbox.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "execOneOffCommand" - ], - "title": "ExecOneOffCommandRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ExecOneOffCommandParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ExecOneOffCommandRequest", - "type": "object" } ], "title": "ClientRequest" diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index 518d650208..81140db5e9 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -3519,7 +3519,7 @@ "required": [ "state" ], - "title": "StateMcpStartupStatus", + "title": "StartingMcpStartupStatus", "type": "object" }, { @@ -3534,7 +3534,7 @@ "required": [ "state" ], - "title": "StateMcpStartupStatus2", + "title": "ReadyMcpStartupStatus", "type": "object" }, { @@ -3567,7 +3567,7 @@ "required": [ "state" ], - "title": "StateMcpStartupStatus3", + "title": "CancelledMcpStartupStatus", "type": "object" } ] diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index bcdbdb33ed..b2dc4c3c3e 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1,10 +1,6 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, "AccountLoginCompletedNotification": { "properties": { "error": { @@ -54,30 +50,6 @@ }, "type": "object" }, - "AgentMessageContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Text" - ], - "title": "TextAgentMessageContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextAgentMessageContent", - "type": "object" - } - ] - }, "AgentMessageDeltaNotification": { "properties": { "delta": { @@ -101,70 +73,6 @@ ], "type": "object" }, - "AgentStatus": { - "description": "Agent lifecycle status, derived from emitted events.", - "oneOf": [ - { - "description": "Agent is waiting for initialization.", - "enum": [ - "pending_init" - ], - "type": "string" - }, - { - "description": "Agent is currently running.", - "enum": [ - "running" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Agent is done. Contains the final assistant message.", - "properties": { - "completed": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "completed" - ], - "title": "CompletedAgentStatus", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Agent encountered an error.", - "properties": { - "errored": { - "type": "string" - } - }, - "required": [ - "errored" - ], - "title": "ErroredAgentStatus", - "type": "object" - }, - { - "description": "Agent has been shutdown.", - "enum": [ - "shutdown" - ], - "type": "string" - }, - { - "description": "Agent is not found.", - "enum": [ - "not_found" - ], - "type": "string" - } - ] - }, "AppBranding": { "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", "properties": { @@ -430,53 +338,6 @@ ], "type": "object" }, - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, "AuthMode": { "description": "Authentication mode for OpenAI-backed providers.", "oneOf": [ @@ -503,22 +364,6 @@ } ] }, - "AuthStatusChangeNotification": { - "description": "Deprecated notification. Use AccountUpdatedNotification instead.", - "properties": { - "authMethod": { - "anyOf": [ - { - "$ref": "#/definitions/AuthMode" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, "ByteRange": { "properties": { "end": { @@ -538,48 +383,6 @@ ], "type": "object" }, - "ByteRange2": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "CallToolResult": { - "description": "The server's response to a tool call.", - "properties": { - "_meta": true, - "content": { - "items": true, - "type": "array" - }, - "isError": { - "type": [ - "boolean", - "null" - ] - }, - "structuredContent": true - }, - "required": [ - "content" - ], - "type": "object" - }, "CodexErrorInfo": { "description": "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", "oneOf": [ @@ -694,150 +497,6 @@ } ] }, - "CodexErrorInfo2": { - "description": "Codex errors that we expose to clients.", - "oneOf": [ - { - "enum": [ - "context_window_exceeded", - "usage_limit_exceeded", - "server_overloaded", - "internal_server_error", - "unauthorized", - "bad_request", - "sandbox_error", - "thread_rollback_failed", - "other" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "http_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "http_connection_failed" - ], - "title": "HttpConnectionFailedCodexErrorInfo2", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Failed to connect to the response SSE stream.", - "properties": { - "response_stream_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_connection_failed" - ], - "title": "ResponseStreamConnectionFailedCodexErrorInfo2", - "type": "object" - }, - { - "additionalProperties": false, - "description": "The response SSE stream disconnected in the middle of a turnbefore completion.", - "properties": { - "response_stream_disconnected": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_disconnected" - ], - "title": "ResponseStreamDisconnectedCodexErrorInfo2", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Reached the retry limit for responses.", - "properties": { - "response_too_many_failed_attempts": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_too_many_failed_attempts" - ], - "title": "ResponseTooManyFailedAttemptsCodexErrorInfo2", - "type": "object" - } - ] - }, - "CollabAgentRef": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "thread_id" - ], - "type": "object" - }, "CollabAgentState": { "properties": { "message": { @@ -866,45 +525,6 @@ ], "type": "string" }, - "CollabAgentStatusEntry": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the agent." - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "status", - "thread_id" - ], - "type": "object" - }, "CollabAgentTool": { "enum": [ "spawnAgent", @@ -1102,70 +722,6 @@ ], "type": "object" }, - "ContentItem": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageContentItem", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "output_text" - ], - "title": "OutputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "OutputTextContentItem", - "type": "object" - } - ] - }, "ContextCompactedNotification": { "description": "Deprecated: Use `ContextCompaction` item type instead.", "properties": { @@ -1203,58 +759,6 @@ ], "type": "object" }, - "CreditsSnapshot2": { - "properties": { - "balance": { - "type": [ - "string", - "null" - ] - }, - "has_credits": { - "type": "boolean" - }, - "unlimited": { - "type": "boolean" - } - }, - "required": [ - "has_credits", - "unlimited" - ], - "type": "object" - }, - "CustomPrompt": { - "properties": { - "argument_hint": { - "type": [ - "string", - "null" - ] - }, - "content": { - "type": "string" - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "content", - "name", - "path" - ], - "type": "object" - }, "DeprecationNoticeNotification": { "properties": { "details": { @@ -1274,25 +778,6 @@ ], "type": "object" }, - "Duration": { - "properties": { - "nanos": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "secs": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "nanos", - "secs" - ], - "type": "object" - }, "ErrorNotification": { "properties": { "error": { @@ -1316,2774 +801,6 @@ ], "type": "object" }, - "EventMsg": { - "description": "Response event from the agent NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.", - "oneOf": [ - { - "description": "Error while executing a submission", - "properties": { - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo2" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "error" - ], - "title": "ErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "ErrorEventMsg", - "type": "object" - }, - { - "description": "Warning issued while processing a submission. Unlike `Error`, this indicates the turn continued but the user should still be notified.", - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "warning" - ], - "title": "WarningEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "WarningEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle start event.", - "properties": { - "session_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_started" - ], - "title": "RealtimeConversationStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationStartedEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation streaming payload event.", - "properties": { - "payload": { - "$ref": "#/definitions/RealtimeEvent" - }, - "type": { - "enum": [ - "realtime_conversation_realtime" - ], - "title": "RealtimeConversationRealtimeEventMsgType", - "type": "string" - } - }, - "required": [ - "payload", - "type" - ], - "title": "RealtimeConversationRealtimeEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle close event.", - "properties": { - "reason": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_closed" - ], - "title": "RealtimeConversationClosedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationClosedEventMsg", - "type": "object" - }, - { - "description": "Model routing changed from the requested model to a different model.", - "properties": { - "from_model": { - "type": "string" - }, - "reason": { - "$ref": "#/definitions/ModelRerouteReason2" - }, - "to_model": { - "type": "string" - }, - "type": { - "enum": [ - "model_reroute" - ], - "title": "ModelRerouteEventMsgType", - "type": "string" - } - }, - "required": [ - "from_model", - "reason", - "to_model", - "type" - ], - "title": "ModelRerouteEventMsg", - "type": "object" - }, - { - "description": "Conversation history was compacted (either automatically or manually).", - "properties": { - "type": { - "enum": [ - "context_compacted" - ], - "title": "ContextCompactedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ContextCompactedEventMsg", - "type": "object" - }, - { - "description": "Conversation history was rolled back by dropping the last N user turns.", - "properties": { - "num_turns": { - "description": "Number of user turns that were removed from context.", - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "thread_rolled_back" - ], - "title": "ThreadRolledBackEventMsgType", - "type": "string" - } - }, - "required": [ - "num_turns", - "type" - ], - "title": "ThreadRolledBackEventMsg", - "type": "object" - }, - { - "description": "Agent has started a turn. v1 wire format uses `task_started`; accept `turn_started` for v2 interop.", - "properties": { - "collaboration_mode_kind": { - "allOf": [ - { - "$ref": "#/definitions/ModeKind" - } - ], - "default": "default" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_started" - ], - "title": "TaskStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskStartedEventMsg", - "type": "object" - }, - { - "description": "Agent has completed all actions. v1 wire format uses `task_complete`; accept `turn_complete` for v2 interop.", - "properties": { - "last_agent_message": { - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_complete" - ], - "title": "TaskCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskCompleteEventMsg", - "type": "object" - }, - { - "description": "Usage update for the current session, including totals and last turn. Optional means unknown — UIs should not display when `None`.", - "properties": { - "info": { - "anyOf": [ - { - "$ref": "#/definitions/TokenUsageInfo" - }, - { - "type": "null" - } - ] - }, - "rate_limits": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitSnapshot2" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "token_count" - ], - "title": "TokenCountEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "TokenCountEventMsg", - "type": "object" - }, - { - "description": "Agent text output message", - "properties": { - "message": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "default": null - }, - "type": { - "enum": [ - "agent_message" - ], - "title": "AgentMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "AgentMessageEventMsg", - "type": "object" - }, - { - "description": "User/system input message (what was sent to the model)", - "properties": { - "images": { - "description": "Image URLs sourced from `UserInput::Image`. These are safe to replay in legacy UI history events and correspond to images sent to the model.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "local_images": { - "default": [], - "description": "Local file paths sourced from `UserInput::LocalImage`. These are kept so the UI can reattach images when editing history, and should not be sent to the model or treated as API-ready URLs.", - "items": { - "type": "string" - }, - "type": "array" - }, - "message": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `message` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/TextElement2" - }, - "type": "array" - }, - "type": { - "enum": [ - "user_message" - ], - "title": "UserMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "UserMessageEventMsg", - "type": "object" - }, - { - "description": "Agent text output delta message", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_delta" - ], - "title": "AgentMessageDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentMessageDeltaEventMsg", - "type": "object" - }, - { - "description": "Reasoning event from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning" - ], - "title": "AgentReasoningEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_delta" - ], - "title": "AgentReasoningDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningDeltaEventMsg", - "type": "object" - }, - { - "description": "Raw chain-of-thought from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content" - ], - "title": "AgentReasoningRawContentEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningRawContentEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning content delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content_delta" - ], - "title": "AgentReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Signaled when the model begins a new reasoning summary section (e.g., a new titled block).", - "properties": { - "item_id": { - "default": "", - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "type": { - "enum": [ - "agent_reasoning_section_break" - ], - "title": "AgentReasoningSectionBreakEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "AgentReasoningSectionBreakEventMsg", - "type": "object" - }, - { - "description": "Ack the client's configure message.", - "properties": { - "approval_policy": { - "allOf": [ - { - "$ref": "#/definitions/AskForApproval" - } - ], - "description": "When to escalate for approval for execution" - }, - "cwd": { - "description": "Working directory that should be treated as the *root* of the session.", - "type": "string" - }, - "forked_from_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "history_entry_count": { - "description": "Current number of entries in the history log.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "history_log_id": { - "description": "Identifier of the history log file (inode on Unix, 0 otherwise).", - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "initial_messages": { - "description": "Optional initial messages (as events) for resumed sessions. When present, UIs can use these to seed the history.", - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "description": "Tell the client what model is being queried.", - "type": "string" - }, - "model_provider_id": { - "type": "string" - }, - "network_proxy": { - "anyOf": [ - { - "$ref": "#/definitions/SessionNetworkProxyRuntime" - }, - { - "type": "null" - } - ], - "description": "Runtime proxy bind addresses, when the managed proxy was started for this session." - }, - "reasoning_effort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ], - "description": "The effort the model is putting into reasoning about the user's request." - }, - "rollout_path": { - "description": "Path in which the rollout is stored. Can be `None` for ephemeral threads", - "type": [ - "string", - "null" - ] - }, - "sandbox_policy": { - "allOf": [ - { - "$ref": "#/definitions/SandboxPolicy" - } - ], - "description": "How to sandbox commands executed in the system" - }, - "session_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "description": "Optional user-facing thread name (may be unset).", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "session_configured" - ], - "title": "SessionConfiguredEventMsgType", - "type": "string" - } - }, - "required": [ - "approval_policy", - "cwd", - "history_entry_count", - "history_log_id", - "model", - "model_provider_id", - "sandbox_policy", - "session_id", - "type" - ], - "title": "SessionConfiguredEventMsg", - "type": "object" - }, - { - "description": "Updated session metadata (e.g., thread name changes).", - "properties": { - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "thread_name_updated" - ], - "title": "ThreadNameUpdatedEventMsgType", - "type": "string" - } - }, - "required": [ - "thread_id", - "type" - ], - "title": "ThreadNameUpdatedEventMsg", - "type": "object" - }, - { - "description": "Incremental MCP startup progress updates.", - "properties": { - "server": { - "description": "Server name being started.", - "type": "string" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/McpStartupStatus" - } - ], - "description": "Current startup status." - }, - "type": { - "enum": [ - "mcp_startup_update" - ], - "title": "McpStartupUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "server", - "status", - "type" - ], - "title": "McpStartupUpdateEventMsg", - "type": "object" - }, - { - "description": "Aggregate MCP startup completion summary.", - "properties": { - "cancelled": { - "items": { - "type": "string" - }, - "type": "array" - }, - "failed": { - "items": { - "$ref": "#/definitions/McpStartupFailure" - }, - "type": "array" - }, - "ready": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "mcp_startup_complete" - ], - "title": "McpStartupCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "cancelled", - "failed", - "ready", - "type" - ], - "title": "McpStartupCompleteEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the McpToolCallEnd event.", - "type": "string" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "type": { - "enum": [ - "mcp_tool_call_begin" - ], - "title": "McpToolCallBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "invocation", - "type" - ], - "title": "McpToolCallBeginEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier for the corresponding McpToolCallBegin that finished.", - "type": "string" - }, - "duration": { - "$ref": "#/definitions/Duration" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "result": { - "allOf": [ - { - "$ref": "#/definitions/Result_of_CallToolResult_or_String" - } - ], - "description": "Result of the tool call. Note this could be an error." - }, - "type": { - "enum": [ - "mcp_tool_call_end" - ], - "title": "McpToolCallEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "duration", - "invocation", - "result", - "type" - ], - "title": "McpToolCallEndEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_begin" - ], - "title": "WebSearchBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "type" - ], - "title": "WebSearchBeginEventMsg", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction2" - }, - "call_id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_end" - ], - "title": "WebSearchEndEventMsgType", - "type": "string" - } - }, - "required": [ - "action", - "call_id", - "query", - "type" - ], - "title": "WebSearchEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the server is about to execute a command.", - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the ExecCommandEnd event.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_begin" - ], - "title": "ExecCommandBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "turn_id", - "type" - ], - "title": "ExecCommandBeginEventMsg", - "type": "object" - }, - { - "description": "Incremental chunk of output from a running command.", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "chunk": { - "description": "Raw bytes from the stream (may not be valid UTF-8).", - "type": "string" - }, - "stream": { - "allOf": [ - { - "$ref": "#/definitions/ExecOutputStream" - } - ], - "description": "Which stream produced this chunk." - }, - "type": { - "enum": [ - "exec_command_output_delta" - ], - "title": "ExecCommandOutputDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "chunk", - "stream", - "type" - ], - "title": "ExecCommandOutputDeltaEventMsg", - "type": "object" - }, - { - "description": "Terminal interaction for an in-progress command (stdin sent and stdout observed).", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "process_id": { - "description": "Process id associated with the running command.", - "type": "string" - }, - "stdin": { - "description": "Stdin sent to the running session.", - "type": "string" - }, - "type": { - "enum": [ - "terminal_interaction" - ], - "title": "TerminalInteractionEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "process_id", - "stdin", - "type" - ], - "title": "TerminalInteractionEventMsg", - "type": "object" - }, - { - "properties": { - "aggregated_output": { - "default": "", - "description": "Captured aggregated output", - "type": "string" - }, - "call_id": { - "description": "Identifier for the ExecCommandBegin that finished.", - "type": "string" - }, - "command": { - "description": "The command that was executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "duration": { - "allOf": [ - { - "$ref": "#/definitions/Duration" - } - ], - "description": "The duration of the command execution." - }, - "exit_code": { - "description": "The command's exit code.", - "format": "int32", - "type": "integer" - }, - "formatted_output": { - "description": "Formatted output from the command, as seen by the model.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandStatus" - } - ], - "description": "Completion status for this command execution." - }, - "stderr": { - "description": "Captured stderr", - "type": "string" - }, - "stdout": { - "description": "Captured stdout", - "type": "string" - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_end" - ], - "title": "ExecCommandEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "duration", - "exit_code", - "formatted_output", - "parsed_cmd", - "status", - "stderr", - "stdout", - "turn_id", - "type" - ], - "title": "ExecCommandEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent attached a local image via the view_image tool.", - "properties": { - "call_id": { - "description": "Identifier for the originating tool call.", - "type": "string" - }, - "path": { - "description": "Local filesystem path provided to the tool.", - "type": "string" - }, - "type": { - "enum": [ - "view_image_tool_call" - ], - "title": "ViewImageToolCallEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "path", - "type" - ], - "title": "ViewImageToolCallEventMsg", - "type": "object" - }, - { - "properties": { - "approval_id": { - "description": "Identifier for this specific approval callback.\n\nWhen absent, the approval is for the command item itself (`call_id`). This is present for subcommand approvals (via execve intercept).", - "type": [ - "string", - "null" - ] - }, - "call_id": { - "description": "Identifier for the associated command execution item.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory.", - "type": "string" - }, - "network_approval_context": { - "anyOf": [ - { - "$ref": "#/definitions/NetworkApprovalContext" - }, - { - "type": "null" - } - ], - "description": "Optional network context for a blocked request that can be approved." - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "proposed_execpolicy_amendment": { - "description": "Proposed execpolicy amendment that can be applied to allow future runs.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "reason": { - "description": "Optional human-readable reason for the approval (e.g. retry without sandbox).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this command belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "exec_approval_request" - ], - "title": "ExecApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "type" - ], - "title": "ExecApprovalRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated tool call, if available.", - "type": "string" - }, - "questions": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestion" - }, - "type": "array" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this request belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "request_user_input" - ], - "title": "RequestUserInputEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "questions", - "type" - ], - "title": "RequestUserInputEventMsg", - "type": "object" - }, - { - "properties": { - "arguments": true, - "callId": { - "type": "string" - }, - "tool": { - "type": "string" - }, - "turnId": { - "type": "string" - }, - "type": { - "enum": [ - "dynamic_tool_call_request" - ], - "title": "DynamicToolCallRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "arguments", - "callId", - "tool", - "turnId", - "type" - ], - "title": "DynamicToolCallRequestEventMsg", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "message": { - "type": "string" - }, - "server_name": { - "type": "string" - }, - "type": { - "enum": [ - "elicitation_request" - ], - "title": "ElicitationRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "message", - "server_name", - "type" - ], - "title": "ElicitationRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated patch apply call, if available.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "type": "object" - }, - "grant_root": { - "description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session.", - "type": [ - "string", - "null" - ] - }, - "reason": { - "description": "Optional explanatory reason (e.g. request for extra write access).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility with older senders.", - "type": "string" - }, - "type": { - "enum": [ - "apply_patch_approval_request" - ], - "title": "ApplyPatchApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "changes", - "type" - ], - "title": "ApplyPatchApprovalRequestEventMsg", - "type": "object" - }, - { - "description": "Notification advising the user that something they are using has been deprecated and should be phased out.", - "properties": { - "details": { - "description": "Optional extra guidance, such as migration steps or rationale.", - "type": [ - "string", - "null" - ] - }, - "summary": { - "description": "Concise summary of what is deprecated.", - "type": "string" - }, - "type": { - "enum": [ - "deprecation_notice" - ], - "title": "DeprecationNoticeEventMsgType", - "type": "string" - } - }, - "required": [ - "summary", - "type" - ], - "title": "DeprecationNoticeEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "background_event" - ], - "title": "BackgroundEventEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "BackgroundEventEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "undo_started" - ], - "title": "UndoStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UndoStartedEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "success": { - "type": "boolean" - }, - "type": { - "enum": [ - "undo_completed" - ], - "title": "UndoCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "success", - "type" - ], - "title": "UndoCompletedEventMsg", - "type": "object" - }, - { - "description": "Notification that a model stream experienced an error or disconnect and the system is handling it (e.g., retrying with backoff).", - "properties": { - "additional_details": { - "default": null, - "description": "Optional details about the underlying stream failure (often the same human-readable message that is surfaced as the terminal error if retries are exhausted).", - "type": [ - "string", - "null" - ] - }, - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo2" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "stream_error" - ], - "title": "StreamErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "StreamErrorEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is about to apply a code patch. Mirrors `ExecCommandBegin` so front‑ends can show progress indicators.", - "properties": { - "auto_approved": { - "description": "If true, there was no ApplyPatchApprovalRequest for this patch.", - "type": "boolean" - }, - "call_id": { - "description": "Identifier so this can be paired with the PatchApplyEnd event.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "description": "The changes to be applied.", - "type": "object" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_begin" - ], - "title": "PatchApplyBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "auto_approved", - "call_id", - "changes", - "type" - ], - "title": "PatchApplyBeginEventMsg", - "type": "object" - }, - { - "description": "Notification that a patch application has finished.", - "properties": { - "call_id": { - "description": "Identifier for the PatchApplyBegin that finished.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "default": {}, - "description": "The changes that were applied (mirrors PatchApplyBeginEvent::changes).", - "type": "object" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/PatchApplyStatus2" - } - ], - "description": "Completion status for this patch application." - }, - "stderr": { - "description": "Captured stderr (parser errors, IO failures, etc.).", - "type": "string" - }, - "stdout": { - "description": "Captured stdout (summary printed by apply_patch).", - "type": "string" - }, - "success": { - "description": "Whether the patch was applied successfully.", - "type": "boolean" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_end" - ], - "title": "PatchApplyEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "status", - "stderr", - "stdout", - "success", - "type" - ], - "title": "PatchApplyEndEventMsg", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "turn_diff" - ], - "title": "TurnDiffEventMsgType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "TurnDiffEventMsg", - "type": "object" - }, - { - "description": "Response to GetHistoryEntryRequest.", - "properties": { - "entry": { - "anyOf": [ - { - "$ref": "#/definitions/HistoryEntry" - }, - { - "type": "null" - } - ], - "description": "The entry at the requested offset, if available and parseable." - }, - "log_id": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "offset": { - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "get_history_entry_response" - ], - "title": "GetHistoryEntryResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "log_id", - "offset", - "type" - ], - "title": "GetHistoryEntryResponseEventMsg", - "type": "object" - }, - { - "description": "List of MCP tools available to the agent.", - "properties": { - "auth_statuses": { - "additionalProperties": { - "$ref": "#/definitions/McpAuthStatus" - }, - "description": "Authentication status for each configured MCP server.", - "type": "object" - }, - "resource_templates": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/ResourceTemplate" - }, - "type": "array" - }, - "description": "Known resource templates grouped by server name.", - "type": "object" - }, - "resources": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/Resource" - }, - "type": "array" - }, - "description": "Known resources grouped by server name.", - "type": "object" - }, - "tools": { - "additionalProperties": { - "$ref": "#/definitions/Tool" - }, - "description": "Fully qualified tool name -> tool definition.", - "type": "object" - }, - "type": { - "enum": [ - "mcp_list_tools_response" - ], - "title": "McpListToolsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "auth_statuses", - "resource_templates", - "resources", - "tools", - "type" - ], - "title": "McpListToolsResponseEventMsg", - "type": "object" - }, - { - "description": "List of custom prompts available to the agent.", - "properties": { - "custom_prompts": { - "items": { - "$ref": "#/definitions/CustomPrompt" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_custom_prompts_response" - ], - "title": "ListCustomPromptsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "custom_prompts", - "type" - ], - "title": "ListCustomPromptsResponseEventMsg", - "type": "object" - }, - { - "description": "List of skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/SkillsListEntry" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_skills_response" - ], - "title": "ListSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "List of remote skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/RemoteSkillSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_remote_skills_response" - ], - "title": "ListRemoteSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListRemoteSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "Remote skill downloaded to local cache.", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "remote_skill_downloaded" - ], - "title": "RemoteSkillDownloadedEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "name", - "path", - "type" - ], - "title": "RemoteSkillDownloadedEventMsg", - "type": "object" - }, - { - "description": "Notification that skill data may have been updated and clients may want to reload.", - "properties": { - "type": { - "enum": [ - "skills_update_available" - ], - "title": "SkillsUpdateAvailableEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SkillsUpdateAvailableEventMsg", - "type": "object" - }, - { - "properties": { - "explanation": { - "default": null, - "description": "Arguments for the `update_plan` todo/checklist tool (not plan mode).", - "type": [ - "string", - "null" - ] - }, - "plan": { - "items": { - "$ref": "#/definitions/PlanItemArg" - }, - "type": "array" - }, - "type": { - "enum": [ - "plan_update" - ], - "title": "PlanUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "plan", - "type" - ], - "title": "PlanUpdateEventMsg", - "type": "object" - }, - { - "properties": { - "reason": { - "$ref": "#/definitions/TurnAbortReason" - }, - "turn_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "turn_aborted" - ], - "title": "TurnAbortedEventMsgType", - "type": "string" - } - }, - "required": [ - "reason", - "type" - ], - "title": "TurnAbortedEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is shutting down.", - "properties": { - "type": { - "enum": [ - "shutdown_complete" - ], - "title": "ShutdownCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ShutdownCompleteEventMsg", - "type": "object" - }, - { - "description": "Entered review mode.", - "properties": { - "target": { - "$ref": "#/definitions/ReviewTarget" - }, - "type": { - "enum": [ - "entered_review_mode" - ], - "title": "EnteredReviewModeEventMsgType", - "type": "string" - }, - "user_facing_hint": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "target", - "type" - ], - "title": "EnteredReviewModeEventMsg", - "type": "object" - }, - { - "description": "Exited review mode with an optional final result to apply.", - "properties": { - "review_output": { - "anyOf": [ - { - "$ref": "#/definitions/ReviewOutputEvent" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "exited_review_mode" - ], - "title": "ExitedReviewModeEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExitedReviewModeEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/ResponseItem" - }, - "type": { - "enum": [ - "raw_response_item" - ], - "title": "RawResponseItemEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "type" - ], - "title": "RawResponseItemEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_started" - ], - "title": "ItemStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemStartedEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_completed" - ], - "title": "ItemCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemCompletedEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_content_delta" - ], - "title": "AgentMessageContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "AgentMessageContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "plan_delta" - ], - "title": "PlanDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "PlanDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_content_delta" - ], - "title": "ReasoningContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "content_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_raw_content_delta" - ], - "title": "ReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_spawn_begin" - ], - "title": "CollabAgentSpawnBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "type" - ], - "title": "CollabAgentSpawnBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "new_agent_nickname": { - "description": "Optional nickname assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_agent_role": { - "description": "Optional role assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_thread_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ], - "description": "Thread ID of the newly spawned agent, if it was created." - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the new agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_spawn_end" - ], - "title": "CollabAgentSpawnEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentSpawnEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_interaction_begin" - ], - "title": "CollabAgentInteractionBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabAgentInteractionBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_interaction_end" - ], - "title": "CollabAgentInteractionEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentInteractionEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting begin.", - "properties": { - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "receiver_agents": { - "description": "Optional nicknames/roles for receivers.", - "items": { - "$ref": "#/definitions/CollabAgentRef" - }, - "type": "array" - }, - "receiver_thread_ids": { - "description": "Thread ID of the receivers.", - "items": { - "$ref": "#/definitions/ThreadId" - }, - "type": "array" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_waiting_begin" - ], - "title": "CollabWaitingBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_ids", - "sender_thread_id", - "type" - ], - "title": "CollabWaitingBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting end.", - "properties": { - "agent_statuses": { - "description": "Optional receiver metadata paired with final statuses.", - "items": { - "$ref": "#/definitions/CollabAgentStatusEntry" - }, - "type": "array" - }, - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "statuses": { - "additionalProperties": { - "$ref": "#/definitions/AgentStatus" - }, - "description": "Last known status of the receiver agents reported to the sender agent.", - "type": "object" - }, - "type": { - "enum": [ - "collab_waiting_end" - ], - "title": "CollabWaitingEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "sender_thread_id", - "statuses", - "type" - ], - "title": "CollabWaitingEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_close_begin" - ], - "title": "CollabCloseBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabCloseBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent before the close." - }, - "type": { - "enum": [ - "collab_close_end" - ], - "title": "CollabCloseEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabCloseEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_resume_begin" - ], - "title": "CollabResumeBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabResumeBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent after resume." - }, - "type": { - "enum": [ - "collab_resume_end" - ], - "title": "CollabResumeEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabResumeEndEventMsg", - "type": "object" - } - ] - }, - "ExecCommandSource": { - "enum": [ - "agent", - "user_shell", - "unified_exec_startup", - "unified_exec_interaction" - ], - "type": "string" - }, - "ExecCommandStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, - "ExecOutputStream": { - "enum": [ - "stdout", - "stderr" - ], - "type": "string" - }, - "FileChange": { - "oneOf": [ - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "add" - ], - "title": "AddFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "AddFileChange", - "type": "object" - }, - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "delete" - ], - "title": "DeleteFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "DeleteFileChange", - "type": "object" - }, - { - "properties": { - "move_path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "update" - ], - "title": "UpdateFileChangeType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "UpdateFileChange", - "type": "object" - } - ] - }, "FileChangeOutputDeltaNotification": { "properties": { "delta": { @@ -4126,82 +843,6 @@ ], "type": "object" }, - "FunctionCallOutputBody": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "$ref": "#/definitions/FunctionCallOutputContentItem" - }, - "type": "array" - } - ] - }, - "FunctionCallOutputContentItem": { - "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextFunctionCallOutputContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageFunctionCallOutputContentItem", - "type": "object" - } - ] - }, - "FunctionCallOutputPayload": { - "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", - "properties": { - "body": { - "$ref": "#/definitions/FunctionCallOutputBody" - }, - "success": { - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "body" - ], - "type": "object" - }, "FuzzyFileSearchResult": { "description": "Superset of [`codex_file_search::FileMatch`]", "properties": { @@ -4272,38 +913,6 @@ ], "type": "object" }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, "GitInfo": { "properties": { "branch": { @@ -4327,27 +936,6 @@ }, "type": "object" }, - "HistoryEntry": { - "properties": { - "conversation_id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "ts": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "conversation_id", - "text", - "ts" - ], - "type": "object" - }, "ItemCompletedNotification": { "properties": { "item": { @@ -4386,121 +974,6 @@ ], "type": "object" }, - "LocalShellAction": { - "oneOf": [ - { - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "timeout_ms": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - }, - "type": { - "enum": [ - "exec" - ], - "title": "ExecLocalShellActionType", - "type": "string" - }, - "user": { - "type": [ - "string", - "null" - ] - }, - "working_directory": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "command", - "type" - ], - "title": "ExecLocalShellAction", - "type": "object" - } - ] - }, - "LocalShellStatus": { - "enum": [ - "completed", - "in_progress", - "incomplete" - ], - "type": "string" - }, - "LoginChatGptCompleteNotification": { - "description": "Deprecated in favor of AccountLoginCompletedNotification.", - "properties": { - "error": { - "type": [ - "string", - "null" - ] - }, - "loginId": { - "type": "string" - }, - "success": { - "type": "boolean" - } - }, - "required": [ - "loginId", - "success" - ], - "type": "object" - }, - "McpAuthStatus": { - "enum": [ - "unsupported", - "not_logged_in", - "bearer_token", - "o_auth" - ], - "type": "string" - }, - "McpInvocation": { - "properties": { - "arguments": { - "description": "Arguments to the tool call." - }, - "server": { - "description": "Name of the MCP server as defined in the config.", - "type": "string" - }, - "tool": { - "description": "Name of the tool as given by the MCP server.", - "type": "string" - } - }, - "required": [ - "server", - "tool" - ], - "type": "object" - }, "McpServerOauthLoginCompletedNotification": { "properties": { "error": { @@ -4522,88 +995,6 @@ ], "type": "object" }, - "McpStartupFailure": { - "properties": { - "error": { - "type": "string" - }, - "server": { - "type": "string" - } - }, - "required": [ - "error", - "server" - ], - "type": "object" - }, - "McpStartupStatus": { - "oneOf": [ - { - "properties": { - "state": { - "enum": [ - "starting" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus", - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "ready" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus2", - "type": "object" - }, - { - "properties": { - "error": { - "type": "string" - }, - "state": { - "enum": [ - "failed" - ], - "type": "string" - } - }, - "required": [ - "error", - "state" - ], - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "cancelled" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus3", - "type": "object" - } - ] - }, "McpToolCallError": { "properties": { "message": { @@ -4678,26 +1069,12 @@ } ] }, - "ModeKind": { - "description": "Initial collaboration mode to use when the TUI starts.", - "enum": [ - "plan", - "default" - ], - "type": "string" - }, "ModelRerouteReason": { "enum": [ "highRiskCyberActivity" ], "type": "string" }, - "ModelRerouteReason2": { - "enum": [ - "high_risk_cyber_activity" - ], - "type": "string" - }, "ModelReroutedNotification": { "properties": { "fromModel": { @@ -4725,149 +1102,6 @@ ], "type": "object" }, - "NetworkAccess": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, - "NetworkApprovalContext": { - "properties": { - "host": { - "type": "string" - }, - "protocol": { - "$ref": "#/definitions/NetworkApprovalProtocol" - } - }, - "required": [ - "host", - "protocol" - ], - "type": "object" - }, - "NetworkApprovalProtocol": { - "enum": [ - "http", - "https", - "socks5_tcp", - "socks5_udp" - ], - "type": "string" - }, - "ParsedCommand": { - "oneOf": [ - { - "properties": { - "cmd": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", - "type": "string" - }, - "type": { - "enum": [ - "read" - ], - "title": "ReadParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "name", - "path", - "type" - ], - "title": "ReadParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "list_files" - ], - "title": "ListFilesParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "ListFilesParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "SearchParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "type": { - "enum": [ - "unknown" - ], - "title": "UnknownParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "UnknownParsedCommand", - "type": "object" - } - ] - }, "PatchApplyStatus": { "enum": [ "inProgress", @@ -4877,14 +1111,6 @@ ], "type": "string" }, - "PatchApplyStatus2": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, "PatchChangeKind": { "oneOf": [ { @@ -4967,22 +1193,6 @@ ], "type": "object" }, - "PlanItemArg": { - "additionalProperties": false, - "properties": { - "status": { - "$ref": "#/definitions/StepStatus" - }, - "step": { - "type": "string" - } - }, - "required": [ - "status", - "step" - ], - "type": "object" - }, "PlanType": { "enum": [ "free", @@ -5054,63 +1264,6 @@ }, "type": "object" }, - "RateLimitSnapshot2": { - "properties": { - "credits": { - "anyOf": [ - { - "$ref": "#/definitions/CreditsSnapshot2" - }, - { - "type": "null" - } - ] - }, - "limit_id": { - "type": [ - "string", - "null" - ] - }, - "limit_name": { - "type": [ - "string", - "null" - ] - }, - "plan_type": { - "anyOf": [ - { - "$ref": "#/definitions/PlanType" - }, - { - "type": "null" - } - ] - }, - "primary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow2" - }, - { - "type": "null" - } - ] - }, - "secondary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow2" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, "RateLimitWindow": { "properties": { "resetsAt": { @@ -5137,299 +1290,6 @@ ], "type": "object" }, - "RateLimitWindow2": { - "properties": { - "resets_at": { - "description": "Unix timestamp (seconds since epoch) when the window resets.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "used_percent": { - "description": "Percentage (0-100) of the window that has been consumed.", - "format": "double", - "type": "number" - }, - "window_minutes": { - "description": "Rolling window duration, in minutes.", - "format": "int64", - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "used_percent" - ], - "type": "object" - }, - "RawResponseItemCompletedNotification": { - "properties": { - "item": { - "$ref": "#/definitions/ResponseItem" - }, - "threadId": { - "type": "string" - }, - "turnId": { - "type": "string" - } - }, - "required": [ - "item", - "threadId", - "turnId" - ], - "type": "object" - }, - "ReadOnlyAccess": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess", - "type": "object" - } - ] - }, - "RealtimeAudioFrame": { - "properties": { - "data": { - "type": "string" - }, - "num_channels": { - "format": "uint16", - "minimum": 0.0, - "type": "integer" - }, - "sample_rate": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "samples_per_channel": { - "format": "uint32", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "data", - "num_channels", - "sample_rate" - ], - "type": "object" - }, - "RealtimeEvent": { - "oneOf": [ - { - "additionalProperties": false, - "properties": { - "SessionCreated": { - "properties": { - "session_id": { - "type": "string" - } - }, - "required": [ - "session_id" - ], - "type": "object" - } - }, - "required": [ - "SessionCreated" - ], - "title": "SessionCreatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "SessionUpdated": { - "properties": { - "backend_prompt": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "SessionUpdated" - ], - "title": "SessionUpdatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "AudioOut": { - "$ref": "#/definitions/RealtimeAudioFrame" - } - }, - "required": [ - "AudioOut" - ], - "title": "AudioOutRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "ConversationItemAdded": true - }, - "required": [ - "ConversationItemAdded" - ], - "title": "ConversationItemAddedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "Error": { - "type": "string" - } - }, - "required": [ - "Error" - ], - "title": "ErrorRealtimeEvent", - "type": "object" - } - ] - }, - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ReasoningItemContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_text" - ], - "title": "ReasoningTextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "ReasoningTextReasoningItemContent", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextReasoningItemContent", - "type": "object" - } - ] - }, - "ReasoningItemReasoningSummary": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "summary_text" - ], - "title": "SummaryTextReasoningItemReasoningSummaryType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "SummaryTextReasoningItemReasoningSummary", - "type": "object" - } - ] - }, "ReasoningSummaryPartAddedNotification": { "properties": { "itemId": { @@ -5510,953 +1370,6 @@ ], "type": "object" }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "RemoteSkillSummary": { - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "description", - "id", - "name" - ], - "type": "object" - }, - "RequestId": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "int64", - "type": "integer" - } - ], - "description": "ID of a request, which can be either a string or an integer." - }, - "RequestUserInputQuestion": { - "properties": { - "header": { - "type": "string" - }, - "id": { - "type": "string" - }, - "isOther": { - "default": false, - "type": "boolean" - }, - "isSecret": { - "default": false, - "type": "boolean" - }, - "options": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestionOption" - }, - "type": [ - "array", - "null" - ] - }, - "question": { - "type": "string" - } - }, - "required": [ - "header", - "id", - "question" - ], - "type": "object" - }, - "RequestUserInputQuestionOption": { - "properties": { - "description": { - "type": "string" - }, - "label": { - "type": "string" - } - }, - "required": [ - "description", - "label" - ], - "type": "object" - }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "size": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uri": { - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uriTemplate": { - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResponseItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/ContentItem" - }, - "type": "array" - }, - "end_turn": { - "type": [ - "boolean", - "null" - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ] - }, - "role": { - "type": "string" - }, - "type": { - "enum": [ - "message" - ], - "title": "MessageResponseItemType", - "type": "string" - } - }, - "required": [ - "content", - "role", - "type" - ], - "title": "MessageResponseItem", - "type": "object" - }, - { - "properties": { - "content": { - "default": null, - "items": { - "$ref": "#/definitions/ReasoningItemContent" - }, - "type": [ - "array", - "null" - ] - }, - "encrypted_content": { - "type": [ - "string", - "null" - ] - }, - "id": { - "type": "string", - "writeOnly": true - }, - "summary": { - "items": { - "$ref": "#/definitions/ReasoningItemReasoningSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "reasoning" - ], - "title": "ReasoningResponseItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary", - "type" - ], - "title": "ReasoningResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/LocalShellAction" - }, - "call_id": { - "description": "Set when using the Responses API.", - "type": [ - "string", - "null" - ] - }, - "id": { - "description": "Legacy id field retained for compatibility with older payloads.", - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "$ref": "#/definitions/LocalShellStatus" - }, - "type": { - "enum": [ - "local_shell_call" - ], - "title": "LocalShellCallResponseItemType", - "type": "string" - } - }, - "required": [ - "action", - "status", - "type" - ], - "title": "LocalShellCallResponseItem", - "type": "object" - }, - { - "properties": { - "arguments": { - "type": "string" - }, - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "name": { - "type": "string" - }, - "type": { - "enum": [ - "function_call" - ], - "title": "FunctionCallResponseItemType", - "type": "string" - } - }, - "required": [ - "arguments", - "call_id", - "name", - "type" - ], - "title": "FunctionCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "$ref": "#/definitions/FunctionCallOutputPayload" - }, - "type": { - "enum": [ - "function_call_output" - ], - "title": "FunctionCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "FunctionCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "input": { - "type": "string" - }, - "name": { - "type": "string" - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "custom_tool_call" - ], - "title": "CustomToolCallResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "input", - "name", - "type" - ], - "title": "CustomToolCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "type": "string" - }, - "type": { - "enum": [ - "custom_tool_call_output" - ], - "title": "CustomToolCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "CustomToolCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "anyOf": [ - { - "$ref": "#/definitions/WebSearchAction2" - }, - { - "type": "null" - } - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "web_search_call" - ], - "title": "WebSearchCallResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "WebSearchCallResponseItem", - "type": "object" - }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, - { - "properties": { - "encrypted_content": { - "type": "string" - }, - "type": { - "enum": [ - "compaction" - ], - "title": "CompactionResponseItemType", - "type": "string" - } - }, - "required": [ - "encrypted_content", - "type" - ], - "title": "CompactionResponseItem", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherResponseItem", - "type": "object" - } - ] - }, - "Result_of_CallToolResult_or_String": { - "oneOf": [ - { - "properties": { - "Ok": { - "$ref": "#/definitions/CallToolResult" - } - }, - "required": [ - "Ok" - ], - "title": "OkResult_of_CallToolResult_or_String", - "type": "object" - }, - { - "properties": { - "Err": { - "type": "string" - } - }, - "required": [ - "Err" - ], - "title": "ErrResult_of_CallToolResult_or_String", - "type": "object" - } - ] - }, - "ReviewCodeLocation": { - "description": "Location of the code related to a review finding.", - "properties": { - "absolute_file_path": { - "type": "string" - }, - "line_range": { - "$ref": "#/definitions/ReviewLineRange" - } - }, - "required": [ - "absolute_file_path", - "line_range" - ], - "type": "object" - }, - "ReviewFinding": { - "description": "A single review finding describing an observed issue or recommendation.", - "properties": { - "body": { - "type": "string" - }, - "code_location": { - "$ref": "#/definitions/ReviewCodeLocation" - }, - "confidence_score": { - "format": "float", - "type": "number" - }, - "priority": { - "format": "int32", - "type": "integer" - }, - "title": { - "type": "string" - } - }, - "required": [ - "body", - "code_location", - "confidence_score", - "priority", - "title" - ], - "type": "object" - }, - "ReviewLineRange": { - "description": "Inclusive line range in a file associated with the finding.", - "properties": { - "end": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "ReviewOutputEvent": { - "description": "Structured review result produced by a child review session.", - "properties": { - "findings": { - "items": { - "$ref": "#/definitions/ReviewFinding" - }, - "type": "array" - }, - "overall_confidence_score": { - "format": "float", - "type": "number" - }, - "overall_correctness": { - "type": "string" - }, - "overall_explanation": { - "type": "string" - } - }, - "required": [ - "findings", - "overall_confidence_score", - "overall_correctness", - "overall_explanation" - ], - "type": "object" - }, - "ReviewTarget": { - "oneOf": [ - { - "description": "Review the working tree: staged, unstaged, and untracked files.", - "properties": { - "type": { - "enum": [ - "uncommittedChanges" - ], - "title": "UncommittedChangesReviewTargetType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UncommittedChangesReviewTarget", - "type": "object" - }, - { - "description": "Review changes between the current branch and the given base branch.", - "properties": { - "branch": { - "type": "string" - }, - "type": { - "enum": [ - "baseBranch" - ], - "title": "BaseBranchReviewTargetType", - "type": "string" - } - }, - "required": [ - "branch", - "type" - ], - "title": "BaseBranchReviewTarget", - "type": "object" - }, - { - "description": "Review the changes introduced by a specific commit.", - "properties": { - "sha": { - "type": "string" - }, - "title": { - "description": "Optional human-readable label (e.g., commit subject) for UIs.", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "commit" - ], - "title": "CommitReviewTargetType", - "type": "string" - } - }, - "required": [ - "sha", - "type" - ], - "title": "CommitReviewTarget", - "type": "object" - }, - { - "description": "Arbitrary instructions provided by the user.", - "properties": { - "instructions": { - "type": "string" - }, - "type": { - "enum": [ - "custom" - ], - "title": "CustomReviewTargetType", - "type": "string" - } - }, - "required": [ - "instructions", - "type" - ], - "title": "CustomReviewTarget", - "type": "object" - } - ] - }, - "SandboxPolicy": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicyType", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy", - "type": "object" - } - ] - }, - "SessionConfiguredNotification": { - "properties": { - "historyEntryCount": { - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "historyLogId": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "initialMessages": { - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "type": "string" - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "rolloutPath": { - "type": "string" - }, - "sessionId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "historyEntryCount", - "historyLogId", - "model", - "rolloutPath", - "sessionId" - ], - "type": "object" - }, - "SessionNetworkProxyRuntime": { - "properties": { - "admin_addr": { - "type": "string" - }, - "http_addr": { - "type": "string" - }, - "socks_addr": { - "type": "string" - } - }, - "required": [ - "admin_addr", - "http_addr", - "socks_addr" - ], - "type": "object" - }, "SessionSource": { "oneOf": [ { @@ -6484,211 +1397,6 @@ } ] }, - "SkillDependencies": { - "properties": { - "tools": { - "items": { - "$ref": "#/definitions/SkillToolDependency" - }, - "type": "array" - } - }, - "required": [ - "tools" - ], - "type": "object" - }, - "SkillErrorInfo": { - "properties": { - "message": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "message", - "path" - ], - "type": "object" - }, - "SkillInterface": { - "properties": { - "brand_color": { - "type": [ - "string", - "null" - ] - }, - "default_prompt": { - "type": [ - "string", - "null" - ] - }, - "display_name": { - "type": [ - "string", - "null" - ] - }, - "icon_large": { - "type": [ - "string", - "null" - ] - }, - "icon_small": { - "type": [ - "string", - "null" - ] - }, - "short_description": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "SkillMetadata": { - "properties": { - "dependencies": { - "anyOf": [ - { - "$ref": "#/definitions/SkillDependencies" - }, - { - "type": "null" - } - ] - }, - "description": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "interface": { - "anyOf": [ - { - "$ref": "#/definitions/SkillInterface" - }, - { - "type": "null" - } - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "scope": { - "$ref": "#/definitions/SkillScope" - }, - "short_description": { - "description": "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "description", - "enabled", - "name", - "path", - "scope" - ], - "type": "object" - }, - "SkillScope": { - "enum": [ - "user", - "repo", - "system", - "admin" - ], - "type": "string" - }, - "SkillToolDependency": { - "properties": { - "command": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "transport": { - "type": [ - "string", - "null" - ] - }, - "type": { - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - }, - "value": { - "type": "string" - } - }, - "required": [ - "type", - "value" - ], - "type": "object" - }, - "SkillsListEntry": { - "properties": { - "cwd": { - "type": "string" - }, - "errors": { - "items": { - "$ref": "#/definitions/SkillErrorInfo" - }, - "type": "array" - }, - "skills": { - "items": { - "$ref": "#/definitions/SkillMetadata" - }, - "type": "array" - } - }, - "required": [ - "cwd", - "errors", - "skills" - ], - "type": "object" - }, - "StepStatus": { - "enum": [ - "pending", - "in_progress", - "completed" - ], - "type": "string" - }, "SubAgentSource": { "oneOf": [ { @@ -6804,29 +1512,6 @@ ], "type": "object" }, - "TextElement2": { - "properties": { - "byte_range": { - "allOf": [ - { - "$ref": "#/definitions/ByteRange2" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byte_range" - ], - "type": "object" - }, "TextPosition": { "properties": { "column": { @@ -7645,38 +2330,6 @@ ], "type": "object" }, - "TokenUsage": { - "properties": { - "cached_input_tokens": { - "format": "int64", - "type": "integer" - }, - "input_tokens": { - "format": "int64", - "type": "integer" - }, - "output_tokens": { - "format": "int64", - "type": "integer" - }, - "reasoning_output_tokens": { - "format": "int64", - "type": "integer" - }, - "total_tokens": { - "format": "int64", - "type": "integer" - } - }, - "required": [ - "cached_input_tokens", - "input_tokens", - "output_tokens", - "reasoning_output_tokens", - "total_tokens" - ], - "type": "object" - }, "TokenUsageBreakdown": { "properties": { "cachedInputTokens": { @@ -7709,64 +2362,6 @@ ], "type": "object" }, - "TokenUsageInfo": { - "properties": { - "last_token_usage": { - "$ref": "#/definitions/TokenUsage" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "total_token_usage": { - "$ref": "#/definitions/TokenUsage" - } - }, - "required": [ - "last_token_usage", - "total_token_usage" - ], - "type": "object" - }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "inputSchema": true, - "name": { - "type": "string" - }, - "outputSchema": true, - "title": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, "Turn": { "properties": { "error": { @@ -7801,14 +2396,6 @@ ], "type": "object" }, - "TurnAbortReason": { - "enum": [ - "interrupted", - "replaced", - "review_ended" - ], - "type": "string" - }, "TurnCompletedNotification": { "properties": { "threadId": { @@ -7872,182 +2459,6 @@ ], "type": "object" }, - "TurnItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/UserInput2" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "type": { - "enum": [ - "UserMessage" - ], - "title": "UserMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "UserMessageTurnItem", - "type": "object" - }, - { - "description": "Assistant-authored message payload used in turn-item streams.\n\n`phase` is optional because not all providers/models emit it. Consumers should use it when present, but retain legacy completion semantics when it is `None`.", - "properties": { - "content": { - "items": { - "$ref": "#/definitions/AgentMessageContent" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "description": "Optional phase metadata carried through from `ResponseItem::Message`.\n\nThis is currently used by TUI rendering to distinguish mid-turn commentary from a final answer and avoid status-indicator jitter." - }, - "type": { - "enum": [ - "AgentMessage" - ], - "title": "AgentMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "AgentMessageTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Plan" - ], - "title": "PlanTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "text", - "type" - ], - "title": "PlanTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "raw_content": { - "default": [], - "items": { - "type": "string" - }, - "type": "array" - }, - "summary_text": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "Reasoning" - ], - "title": "ReasoningTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary_text", - "type" - ], - "title": "ReasoningTurnItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction2" - }, - "id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "WebSearch" - ], - "title": "WebSearchTurnItemType", - "type": "string" - } - }, - "required": [ - "action", - "id", - "query", - "type" - ], - "title": "WebSearchTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "type": { - "enum": [ - "ContextCompaction" - ], - "title": "ContextCompactionTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "type" - ], - "title": "ContextCompactionTurnItem", - "type": "object" - } - ] - }, "TurnPlanStep": { "properties": { "status": { @@ -8243,131 +2654,6 @@ } ] }, - "UserInput2": { - "description": "User input", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` that should be treated as special elements. These are byte ranges into the UTF-8 `text` buffer and are used to render or persist rich input markers (e.g., image placeholders) across history and resume without mutating the literal text.", - "items": { - "$ref": "#/definitions/TextElement2" - }, - "type": "array" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextUserInput2Type", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextUserInput2", - "type": "object" - }, - { - "description": "Pre‑encoded data: URI image.", - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageUserInput2Type", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "ImageUserInput2", - "type": "object" - }, - { - "description": "Local image path provided by the user. This will be converted to an `Image` variant (base64 data URL) during request serialization.", - "properties": { - "path": { - "type": "string" - }, - "type": { - "enum": [ - "local_image" - ], - "title": "LocalImageUserInput2Type", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "LocalImageUserInput2", - "type": "object" - }, - { - "description": "Skill selected by the user (name + path to SKILL.md).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "skill" - ], - "title": "SkillUserInput2Type", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "SkillUserInput2", - "type": "object" - }, - { - "description": "Explicit mention selected by the user (name + app://connector id).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "mention" - ], - "title": "MentionUserInput2Type", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "MentionUserInput2", - "type": "object" - } - ] - }, "WebSearchAction": { "oneOf": [ { @@ -8469,107 +2755,6 @@ } ] }, - "WebSearchAction2": { - "oneOf": [ - { - "properties": { - "queries": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchWebSearchAction2Type", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SearchWebSearchAction2", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "open_page" - ], - "title": "OpenPageWebSearchAction2Type", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "OpenPageWebSearchAction2", - "type": "object" - }, - { - "properties": { - "pattern": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "find_in_page" - ], - "title": "FindInPageWebSearchAction2Type", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "FindInPageWebSearchAction2", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherWebSearchAction2Type", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherWebSearchAction2", - "type": "object" - } - ] - }, "WindowsSandboxSetupCompletedNotification": { "properties": { "error": { @@ -8886,27 +3071,6 @@ "title": "Item/completedNotification", "type": "object" }, - { - "description": "This event is internal-only. Used by Codex Cloud.", - "properties": { - "method": { - "enum": [ - "rawResponseItem/completed" - ], - "title": "RawResponseItem/completedNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/RawResponseItemCompletedNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "RawResponseItem/completedNotification", - "type": "object" - }, { "properties": { "method": { @@ -9349,68 +3513,6 @@ ], "title": "Account/login/completedNotification", "type": "object" - }, - { - "description": "DEPRECATED NOTIFICATIONS below", - "properties": { - "method": { - "enum": [ - "authStatusChange" - ], - "title": "AuthStatusChangeNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/AuthStatusChangeNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "AuthStatusChangeNotification", - "type": "object" - }, - { - "description": "Deprecated: use `account/login/completed` instead.", - "properties": { - "method": { - "enum": [ - "loginChatGptComplete" - ], - "title": "LoginChatGptCompleteNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/LoginChatGptCompleteNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "LoginChatGptCompleteNotification", - "type": "object" - }, - { - "properties": { - "method": { - "enum": [ - "sessionConfigured" - ], - "title": "SessionConfiguredNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SessionConfiguredNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "SessionConfiguredNotification", - "type": "object" } ], "title": "ServerNotification" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 2c1eb40316..89f7dc34c3 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -1,40 +1,6 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, - "AddConversationListenerParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "experimentalRawEvents": { - "default": false, - "type": "boolean" - } - }, - "required": [ - "conversationId" - ], - "title": "AddConversationListenerParams", - "type": "object" - }, - "AddConversationSubscriptionResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "subscriptionId": { - "type": "string" - } - }, - "required": [ - "subscriptionId" - ], - "title": "AddConversationSubscriptionResponse", - "type": "object" - }, "AgentMessageContent": { "oneOf": [ { @@ -175,140 +141,6 @@ "title": "ApplyPatchApprovalResponse", "type": "object" }, - "ArchiveConversationParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "rolloutPath" - ], - "title": "ArchiveConversationParams", - "type": "object" - }, - "ArchiveConversationResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "ArchiveConversationResponse", - "type": "object" - }, - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "AuthMode": { - "description": "Authentication mode for OpenAI-backed providers.", - "oneOf": [ - { - "description": "OpenAI API key provided by the caller and stored by Codex.", - "enum": [ - "apikey" - ], - "type": "string" - }, - { - "description": "ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex).", - "enum": [ - "chatgpt" - ], - "type": "string" - }, - { - "description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.\n\nChatGPT auth tokens are supplied by an external host app and are only stored in memory. Token refresh must be handled by the external host app.", - "enum": [ - "chatgptAuthTokens" - ], - "type": "string" - } - ] - }, - "AuthStatusChangeNotification": { - "$schema": "http://json-schema.org/draft-07/schema#", - "description": "Deprecated notification. Use AccountUpdatedNotification instead.", - "properties": { - "authMethod": { - "anyOf": [ - { - "$ref": "#/definitions/AuthMode" - }, - { - "type": "null" - } - ] - } - }, - "title": "AuthStatusChangeNotification", - "type": "object" - }, - "ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, "CallToolResult": { "description": "The server's response to a tool call.", "properties": { @@ -330,24 +162,6 @@ ], "type": "object" }, - "CancelLoginChatGptParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "loginId": { - "type": "string" - } - }, - "required": [ - "loginId" - ], - "title": "CancelLoginChatGptParams", - "type": "object" - }, - "CancelLoginChatGptResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "CancelLoginChatGptResponse", - "type": "object" - }, "ChatgptAuthTokensRefreshParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -1359,510 +1173,6 @@ "title": "Account/readRequest", "type": "object" }, - { - "description": "DEPRECATED APIs below", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "newConversation" - ], - "title": "NewConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/NewConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "NewConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getConversationSummary" - ], - "title": "GetConversationSummaryRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/GetConversationSummaryParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "GetConversationSummaryRequest", - "type": "object" - }, - { - "description": "List recorded Codex conversations (rollouts) with optional pagination and search.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "listConversations" - ], - "title": "ListConversationsRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ListConversationsParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ListConversationsRequest", - "type": "object" - }, - { - "description": "Resume a recorded Codex conversation from a rollout file.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "resumeConversation" - ], - "title": "ResumeConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ResumeConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ResumeConversationRequest", - "type": "object" - }, - { - "description": "Fork a recorded Codex conversation into a new session.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "forkConversation" - ], - "title": "ForkConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ForkConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ForkConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "archiveConversation" - ], - "title": "ArchiveConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ArchiveConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ArchiveConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "sendUserMessage" - ], - "title": "SendUserMessageRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SendUserMessageParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "SendUserMessageRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "sendUserTurn" - ], - "title": "SendUserTurnRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SendUserTurnParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "SendUserTurnRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "interruptConversation" - ], - "title": "InterruptConversationRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/InterruptConversationParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "InterruptConversationRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "addConversationListener" - ], - "title": "AddConversationListenerRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/AddConversationListenerParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "AddConversationListenerRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "removeConversationListener" - ], - "title": "RemoveConversationListenerRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/RemoveConversationListenerParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "RemoveConversationListenerRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "gitDiffToRemote" - ], - "title": "GitDiffToRemoteRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/GitDiffToRemoteParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "GitDiffToRemoteRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "loginApiKey" - ], - "title": "LoginApiKeyRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/LoginApiKeyParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "LoginApiKeyRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "loginChatGpt" - ], - "title": "LoginChatGptRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "LoginChatGptRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "cancelLoginChatGpt" - ], - "title": "CancelLoginChatGptRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/CancelLoginChatGptParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "CancelLoginChatGptRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "logoutChatGpt" - ], - "title": "LogoutChatGptRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "LogoutChatGptRequest", - "type": "object" - }, - { - "description": "DEPRECATED in favor of GetAccount", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getAuthStatus" - ], - "title": "GetAuthStatusRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/GetAuthStatusParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "GetAuthStatusRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getUserSavedConfig" - ], - "title": "GetUserSavedConfigRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "GetUserSavedConfigRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "setDefaultModel" - ], - "title": "SetDefaultModelRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SetDefaultModelParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "SetDefaultModelRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "getUserAgent" - ], - "title": "GetUserAgentRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "GetUserAgentRequest", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "userInfo" - ], - "title": "UserInfoRequestMethod", - "type": "string" - }, - "params": { - "type": "null" - } - }, - "required": [ - "id", - "method" - ], - "title": "UserInfoRequest", - "type": "object" - }, { "properties": { "id": { @@ -1886,149 +1196,10 @@ ], "title": "FuzzyFileSearchRequest", "type": "object" - }, - { - "description": "Execute a command (argv vector) under the server's sandbox.", - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "execOneOffCommand" - ], - "title": "ExecOneOffCommandRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/ExecOneOffCommandParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "ExecOneOffCommandRequest", - "type": "object" } ], "title": "ClientRequest" }, - "CodexErrorInfo": { - "description": "Codex errors that we expose to clients.", - "oneOf": [ - { - "enum": [ - "context_window_exceeded", - "usage_limit_exceeded", - "server_overloaded", - "internal_server_error", - "unauthorized", - "bad_request", - "sandbox_error", - "thread_rollback_failed", - "other" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "http_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "http_connection_failed" - ], - "title": "HttpConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Failed to connect to the response SSE stream.", - "properties": { - "response_stream_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_connection_failed" - ], - "title": "ResponseStreamConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "The response SSE stream disconnected in the middle of a turnbefore completion.", - "properties": { - "response_stream_disconnected": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_disconnected" - ], - "title": "ResponseStreamDisconnectedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Reached the retry limit for responses.", - "properties": { - "response_too_many_failed_attempts": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_too_many_failed_attempts" - ], - "title": "ResponseTooManyFailedAttemptsCodexErrorInfo", - "type": "object" - } - ] - }, "CollabAgentRef": { "properties": { "agent_nickname": { @@ -2248,171 +1419,6 @@ "title": "CommandExecutionRequestApprovalResponse", "type": "object" }, - "ContentItem": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageContentItem", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "output_text" - ], - "title": "OutputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "OutputTextContentItem", - "type": "object" - } - ] - }, - "ConversationGitInfo": { - "properties": { - "branch": { - "type": [ - "string", - "null" - ] - }, - "origin_url": { - "type": [ - "string", - "null" - ] - }, - "sha": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "ConversationSummary": { - "properties": { - "cliVersion": { - "type": "string" - }, - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "cwd": { - "type": "string" - }, - "gitInfo": { - "anyOf": [ - { - "$ref": "#/definitions/ConversationGitInfo" - }, - { - "type": "null" - } - ] - }, - "modelProvider": { - "type": "string" - }, - "path": { - "type": "string" - }, - "preview": { - "type": "string" - }, - "source": { - "$ref": "#/definitions/SessionSource" - }, - "timestamp": { - "type": [ - "string", - "null" - ] - }, - "updatedAt": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "cliVersion", - "conversationId", - "cwd", - "modelProvider", - "path", - "preview", - "source" - ], - "type": "object" - }, - "CreditsSnapshot": { - "properties": { - "balance": { - "type": [ - "string", - "null" - ] - }, - "has_credits": { - "type": "boolean" - }, - "unlimited": { - "type": "boolean" - } - }, - "required": [ - "has_credits", - "unlimited" - ], - "type": "object" - }, "CustomPrompt": { "properties": { "argument_hint": { @@ -5309,68 +4315,6 @@ ], "type": "string" }, - "ExecOneOffCommandParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "sandboxPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxPolicy" - }, - { - "type": "null" - } - ] - }, - "timeoutMs": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "command" - ], - "title": "ExecOneOffCommandParams", - "type": "object" - }, - "ExecOneOffCommandResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "exitCode": { - "format": "int32", - "type": "integer" - }, - "stderr": { - "type": "string" - }, - "stdout": { - "type": "string" - } - }, - "required": [ - "exitCode", - "stderr", - "stdout" - ], - "title": "ExecOneOffCommandResponse", - "type": "object" - }, "ExecOutputStream": { "enum": [ "stdout", @@ -5528,152 +4472,6 @@ "title": "FileChangeRequestApprovalResponse", "type": "object" }, - "ForcedLoginMethod": { - "enum": [ - "chatgpt", - "api" - ], - "type": "string" - }, - "ForkConversationParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "overrides": { - "anyOf": [ - { - "$ref": "#/definitions/NewConversationParams" - }, - { - "type": "null" - } - ] - }, - "path": { - "type": [ - "string", - "null" - ] - } - }, - "title": "ForkConversationParams", - "type": "object" - }, - "ForkConversationResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "initialMessages": { - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "type": "string" - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "model", - "rolloutPath" - ], - "title": "ForkConversationResponse", - "type": "object" - }, - "FunctionCallOutputBody": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "$ref": "#/definitions/FunctionCallOutputContentItem" - }, - "type": "array" - } - ] - }, - "FunctionCallOutputContentItem": { - "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextFunctionCallOutputContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageFunctionCallOutputContentItem", - "type": "object" - } - ] - }, - "FunctionCallOutputPayload": { - "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", - "properties": { - "body": { - "$ref": "#/definitions/FunctionCallOutputBody" - }, - "success": { - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "body" - ], - "type": "object" - }, "FuzzyFileSearchParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -5790,188 +4588,6 @@ "title": "FuzzyFileSearchSessionUpdatedNotification", "type": "object" }, - "GetAuthStatusParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "includeToken": { - "type": [ - "boolean", - "null" - ] - }, - "refreshToken": { - "type": [ - "boolean", - "null" - ] - } - }, - "title": "GetAuthStatusParams", - "type": "object" - }, - "GetAuthStatusResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "authMethod": { - "anyOf": [ - { - "$ref": "#/definitions/AuthMode" - }, - { - "type": "null" - } - ] - }, - "authToken": { - "type": [ - "string", - "null" - ] - }, - "requiresOpenaiAuth": { - "type": [ - "boolean", - "null" - ] - } - }, - "title": "GetAuthStatusResponse", - "type": "object" - }, - "GetConversationSummaryParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "anyOf": [ - { - "properties": { - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "rolloutPath" - ], - "title": "RolloutPathv1::GetConversationSummaryParams", - "type": "object" - }, - { - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "conversationId" - ], - "title": "ConversationIdv1::GetConversationSummaryParams", - "type": "object" - } - ], - "title": "GetConversationSummaryParams" - }, - "GetConversationSummaryResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "summary": { - "$ref": "#/definitions/ConversationSummary" - } - }, - "required": [ - "summary" - ], - "title": "GetConversationSummaryResponse", - "type": "object" - }, - "GetUserAgentResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "userAgent": { - "type": "string" - } - }, - "required": [ - "userAgent" - ], - "title": "GetUserAgentResponse", - "type": "object" - }, - "GetUserSavedConfigResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "config": { - "$ref": "#/definitions/UserSavedConfig" - } - }, - "required": [ - "config" - ], - "title": "GetUserSavedConfigResponse", - "type": "object" - }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, - "GitDiffToRemoteParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "cwd": { - "type": "string" - } - }, - "required": [ - "cwd" - ], - "title": "GitDiffToRemoteParams", - "type": "object" - }, - "GitDiffToRemoteResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "diff": { - "type": "string" - }, - "sha": { - "$ref": "#/definitions/GitSha" - } - }, - "required": [ - "diff", - "sha" - ], - "title": "GitDiffToRemoteResponse", - "type": "object" - }, - "GitSha": { - "type": "string" - }, "HistoryEntry": { "properties": { "conversation_id": { @@ -6050,128 +4666,6 @@ "title": "InitializeResponse", "type": "object" }, - "InputItem": { - "oneOf": [ - { - "properties": { - "data": { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/V1TextElement" - }, - "type": "array" - } - }, - "required": [ - "text" - ], - "type": "object" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "TextInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "image_url": { - "type": "string" - } - }, - "required": [ - "image_url" - ], - "type": "object" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "ImageInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "path": { - "type": "string" - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "type": { - "enum": [ - "localImage" - ], - "title": "LocalImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "LocalImageInputItem", - "type": "object" - } - ] - }, - "InterruptConversationParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "conversationId" - ], - "title": "InterruptConversationParams", - "type": "object" - }, - "InterruptConversationResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "abortReason": { - "$ref": "#/definitions/TurnAbortReason" - } - }, - "required": [ - "abortReason" - ], - "title": "InterruptConversationResponse", - "type": "object" - }, "JSONRPCError": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "A response to a request that indicates an error occurred.", @@ -6278,195 +4772,6 @@ "title": "JSONRPCResponse", "type": "object" }, - "ListConversationsParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "cursor": { - "type": [ - "string", - "null" - ] - }, - "modelProviders": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "pageSize": { - "format": "uint", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "title": "ListConversationsParams", - "type": "object" - }, - "ListConversationsResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "items": { - "items": { - "$ref": "#/definitions/ConversationSummary" - }, - "type": "array" - }, - "nextCursor": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "items" - ], - "title": "ListConversationsResponse", - "type": "object" - }, - "LocalShellAction": { - "oneOf": [ - { - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "timeout_ms": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - }, - "type": { - "enum": [ - "exec" - ], - "title": "ExecLocalShellActionType", - "type": "string" - }, - "user": { - "type": [ - "string", - "null" - ] - }, - "working_directory": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "command", - "type" - ], - "title": "ExecLocalShellAction", - "type": "object" - } - ] - }, - "LocalShellStatus": { - "enum": [ - "completed", - "in_progress", - "incomplete" - ], - "type": "string" - }, - "LoginApiKeyParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "apiKey": { - "type": "string" - } - }, - "required": [ - "apiKey" - ], - "title": "LoginApiKeyParams", - "type": "object" - }, - "LoginApiKeyResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "LoginApiKeyResponse", - "type": "object" - }, - "LoginChatGptCompleteNotification": { - "$schema": "http://json-schema.org/draft-07/schema#", - "description": "Deprecated in favor of AccountLoginCompletedNotification.", - "properties": { - "error": { - "type": [ - "string", - "null" - ] - }, - "loginId": { - "type": "string" - }, - "success": { - "type": "boolean" - } - }, - "required": [ - "loginId", - "success" - ], - "title": "LoginChatGptCompleteNotification", - "type": "object" - }, - "LoginChatGptResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "authUrl": { - "type": "string" - }, - "loginId": { - "type": "string" - } - }, - "required": [ - "authUrl", - "loginId" - ], - "title": "LoginChatGptResponse", - "type": "object" - }, - "LogoutChatGptResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "LogoutChatGptResponse", - "type": "object" - }, - "McpAuthStatus": { - "enum": [ - "unsupported", - "not_logged_in", - "bearer_token", - "o_auth" - ], - "type": "string" - }, "McpInvocation": { "properties": { "arguments": { @@ -6516,7 +4821,7 @@ "required": [ "state" ], - "title": "StateMcpStartupStatus", + "title": "StartingMcpStartupStatus", "type": "object" }, { @@ -6531,7 +4836,7 @@ "required": [ "state" ], - "title": "StateMcpStartupStatus2", + "title": "ReadyMcpStartupStatus", "type": "object" }, { @@ -6564,52 +4869,11 @@ "required": [ "state" ], - "title": "StateMcpStartupStatus3", + "title": "CancelledMcpStartupStatus", "type": "object" } ] }, - "MessagePhase": { - "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", - "oneOf": [ - { - "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", - "enum": [ - "commentary" - ], - "type": "string" - }, - { - "description": "The assistant's terminal answer text for the current turn.", - "enum": [ - "final_answer" - ], - "type": "string" - } - ] - }, - "ModeKind": { - "description": "Initial collaboration mode to use when the TUI starts.", - "enum": [ - "plan", - "default" - ], - "type": "string" - }, - "ModelRerouteReason": { - "enum": [ - "high_risk_cyber_activity" - ], - "type": "string" - }, - "NetworkAccess": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, "NetworkApprovalContext": { "properties": { "host": { @@ -6629,122 +4893,11 @@ "enum": [ "http", "https", - "socks5_tcp", - "socks5_udp" + "socks5Tcp", + "socks5Udp" ], "type": "string" }, - "NewConversationParams": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "baseInstructions": { - "type": [ - "string", - "null" - ] - }, - "compactPrompt": { - "type": [ - "string", - "null" - ] - }, - "config": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "developerInstructions": { - "type": [ - "string", - "null" - ] - }, - "includeApplyPatchTool": { - "type": [ - "boolean", - "null" - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelProvider": { - "type": [ - "string", - "null" - ] - }, - "profile": { - "type": [ - "string", - "null" - ] - }, - "sandbox": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxMode" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "NewConversationResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "model": { - "type": "string" - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "model", - "rolloutPath" - ], - "title": "NewConversationResponse", - "type": "object" - }, "ParsedCommand": { "oneOf": [ { @@ -6856,14 +5009,6 @@ } ] }, - "PatchApplyStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, "PlanItemArg": { "additionalProperties": false, "properties": { @@ -6880,220 +5025,6 @@ ], "type": "object" }, - "PlanType": { - "enum": [ - "free", - "go", - "plus", - "pro", - "team", - "business", - "enterprise", - "edu", - "unknown" - ], - "type": "string" - }, - "Profile": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "chatgptBaseUrl": { - "type": [ - "string", - "null" - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelProvider": { - "type": [ - "string", - "null" - ] - }, - "modelReasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "modelReasoningSummary": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningSummary" - }, - { - "type": "null" - } - ] - }, - "modelVerbosity": { - "anyOf": [ - { - "$ref": "#/definitions/Verbosity" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "RateLimitSnapshot": { - "properties": { - "credits": { - "anyOf": [ - { - "$ref": "#/definitions/CreditsSnapshot" - }, - { - "type": "null" - } - ] - }, - "limit_id": { - "type": [ - "string", - "null" - ] - }, - "limit_name": { - "type": [ - "string", - "null" - ] - }, - "plan_type": { - "anyOf": [ - { - "$ref": "#/definitions/PlanType" - }, - { - "type": "null" - } - ] - }, - "primary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - }, - "secondary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "RateLimitWindow": { - "properties": { - "resets_at": { - "description": "Unix timestamp (seconds since epoch) when the window resets.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "used_percent": { - "description": "Percentage (0-100) of the window that has been consumed.", - "format": "double", - "type": "number" - }, - "window_minutes": { - "description": "Rolling window duration, in minutes.", - "format": "int64", - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "used_percent" - ], - "type": "object" - }, - "ReadOnlyAccess": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess", - "type": "object" - } - ] - }, "RealtimeAudioFrame": { "properties": { "data": { @@ -7208,106 +5139,6 @@ } ] }, - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ReasoningItemContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_text" - ], - "title": "ReasoningTextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "ReasoningTextReasoningItemContent", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextReasoningItemContent", - "type": "object" - } - ] - }, - "ReasoningItemReasoningSummary": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "summary_text" - ], - "title": "SummaryTextReasoningItemReasoningSummaryType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "SummaryTextReasoningItemReasoningSummary", - "type": "object" - } - ] - }, - "ReasoningSummary": { - "description": "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", - "oneOf": [ - { - "enum": [ - "auto", - "concise", - "detailed" - ], - "type": "string" - }, - { - "description": "Option to disable reasoning summaries.", - "enum": [ - "none" - ], - "type": "string" - } - ] - }, "RejectConfig": { "properties": { "mcp_elicitations": { @@ -7330,43 +5161,6 @@ ], "type": "object" }, - "RemoteSkillSummary": { - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "description", - "id", - "name" - ], - "type": "object" - }, - "RemoveConversationListenerParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "subscriptionId": { - "type": "string" - } - }, - "required": [ - "subscriptionId" - ], - "title": "RemoveConversationListenerParams", - "type": "object" - }, - "RemoveConversationSubscriptionResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "RemoveConversationSubscriptionResponse", - "type": "object" - }, "RequestId": { "anyOf": [ { @@ -7430,447 +5224,6 @@ ], "type": "object" }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "size": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uri": { - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uriTemplate": { - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResponseItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/ContentItem" - }, - "type": "array" - }, - "end_turn": { - "type": [ - "boolean", - "null" - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ] - }, - "role": { - "type": "string" - }, - "type": { - "enum": [ - "message" - ], - "title": "MessageResponseItemType", - "type": "string" - } - }, - "required": [ - "content", - "role", - "type" - ], - "title": "MessageResponseItem", - "type": "object" - }, - { - "properties": { - "content": { - "default": null, - "items": { - "$ref": "#/definitions/ReasoningItemContent" - }, - "type": [ - "array", - "null" - ] - }, - "encrypted_content": { - "type": [ - "string", - "null" - ] - }, - "id": { - "type": "string", - "writeOnly": true - }, - "summary": { - "items": { - "$ref": "#/definitions/ReasoningItemReasoningSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "reasoning" - ], - "title": "ReasoningResponseItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary", - "type" - ], - "title": "ReasoningResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/LocalShellAction" - }, - "call_id": { - "description": "Set when using the Responses API.", - "type": [ - "string", - "null" - ] - }, - "id": { - "description": "Legacy id field retained for compatibility with older payloads.", - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "$ref": "#/definitions/LocalShellStatus" - }, - "type": { - "enum": [ - "local_shell_call" - ], - "title": "LocalShellCallResponseItemType", - "type": "string" - } - }, - "required": [ - "action", - "status", - "type" - ], - "title": "LocalShellCallResponseItem", - "type": "object" - }, - { - "properties": { - "arguments": { - "type": "string" - }, - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "name": { - "type": "string" - }, - "type": { - "enum": [ - "function_call" - ], - "title": "FunctionCallResponseItemType", - "type": "string" - } - }, - "required": [ - "arguments", - "call_id", - "name", - "type" - ], - "title": "FunctionCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "$ref": "#/definitions/FunctionCallOutputPayload" - }, - "type": { - "enum": [ - "function_call_output" - ], - "title": "FunctionCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "FunctionCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "input": { - "type": "string" - }, - "name": { - "type": "string" - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "custom_tool_call" - ], - "title": "CustomToolCallResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "input", - "name", - "type" - ], - "title": "CustomToolCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "type": "string" - }, - "type": { - "enum": [ - "custom_tool_call_output" - ], - "title": "CustomToolCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "CustomToolCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "anyOf": [ - { - "$ref": "#/definitions/WebSearchAction" - }, - { - "type": "null" - } - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "web_search_call" - ], - "title": "WebSearchCallResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "WebSearchCallResponseItem", - "type": "object" - }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, - { - "properties": { - "encrypted_content": { - "type": "string" - }, - "type": { - "enum": [ - "compaction" - ], - "title": "CompactionResponseItemType", - "type": "string" - } - }, - "required": [ - "encrypted_content", - "type" - ], - "title": "CompactionResponseItem", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherResponseItem", - "type": "object" - } - ] - }, "Result_of_CallToolResult_or_String": { "oneOf": [ { @@ -7899,78 +5252,6 @@ } ] }, - "ResumeConversationParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "history": { - "items": { - "$ref": "#/definitions/ResponseItem" - }, - "type": [ - "array", - "null" - ] - }, - "overrides": { - "anyOf": [ - { - "$ref": "#/definitions/NewConversationParams" - }, - { - "type": "null" - } - ] - }, - "path": { - "type": [ - "string", - "null" - ] - } - }, - "title": "ResumeConversationParams", - "type": "object" - }, - "ResumeConversationResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "initialMessages": { - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "type": "string" - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "model", - "rolloutPath" - ], - "title": "ResumeConversationResponse", - "type": "object" - }, "ReviewCodeLocation": { "description": "Location of the code related to a review finding.", "properties": { @@ -8123,338 +5404,6 @@ ], "type": "object" }, - "ReviewTarget": { - "oneOf": [ - { - "description": "Review the working tree: staged, unstaged, and untracked files.", - "properties": { - "type": { - "enum": [ - "uncommittedChanges" - ], - "title": "UncommittedChangesReviewTargetType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UncommittedChangesReviewTarget", - "type": "object" - }, - { - "description": "Review changes between the current branch and the given base branch.", - "properties": { - "branch": { - "type": "string" - }, - "type": { - "enum": [ - "baseBranch" - ], - "title": "BaseBranchReviewTargetType", - "type": "string" - } - }, - "required": [ - "branch", - "type" - ], - "title": "BaseBranchReviewTarget", - "type": "object" - }, - { - "description": "Review the changes introduced by a specific commit.", - "properties": { - "sha": { - "type": "string" - }, - "title": { - "description": "Optional human-readable label (e.g., commit subject) for UIs.", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "commit" - ], - "title": "CommitReviewTargetType", - "type": "string" - } - }, - "required": [ - "sha", - "type" - ], - "title": "CommitReviewTarget", - "type": "object" - }, - { - "description": "Arbitrary instructions provided by the user.", - "properties": { - "instructions": { - "type": "string" - }, - "type": { - "enum": [ - "custom" - ], - "title": "CustomReviewTargetType", - "type": "string" - } - }, - "required": [ - "instructions", - "type" - ], - "title": "CustomReviewTarget", - "type": "object" - } - ] - }, - "SandboxMode": { - "enum": [ - "read-only", - "workspace-write", - "danger-full-access" - ], - "type": "string" - }, - "SandboxPolicy": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicyType", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy", - "type": "object" - } - ] - }, - "SandboxSettings": { - "properties": { - "excludeSlashTmp": { - "type": [ - "boolean", - "null" - ] - }, - "excludeTmpdirEnvVar": { - "type": [ - "boolean", - "null" - ] - }, - "networkAccess": { - "type": [ - "boolean", - "null" - ] - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "type": "object" - }, - "SendUserMessageParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "items": { - "items": { - "$ref": "#/definitions/InputItem" - }, - "type": "array" - } - }, - "required": [ - "conversationId", - "items" - ], - "title": "SendUserMessageParams", - "type": "object" - }, - "SendUserMessageResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "SendUserMessageResponse", - "type": "object" - }, - "SendUserTurnParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "approvalPolicy": { - "$ref": "#/definitions/AskForApproval" - }, - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "cwd": { - "type": "string" - }, - "effort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "items": { - "items": { - "$ref": "#/definitions/InputItem" - }, - "type": "array" - }, - "model": { - "type": "string" - }, - "outputSchema": { - "description": "Optional JSON Schema used to constrain the final assistant message for this turn." - }, - "sandboxPolicy": { - "$ref": "#/definitions/SandboxPolicy" - }, - "summary": { - "$ref": "#/definitions/ReasoningSummary" - } - }, - "required": [ - "approvalPolicy", - "conversationId", - "cwd", - "items", - "model", - "sandboxPolicy", - "summary" - ], - "title": "SendUserTurnParams", - "type": "object" - }, - "SendUserTurnResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "SendUserTurnResponse", - "type": "object" - }, "ServerNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "Notification sent from the server to the client.", @@ -8720,27 +5669,6 @@ "title": "Item/completedNotification", "type": "object" }, - { - "description": "This event is internal-only. Used by Codex Cloud.", - "properties": { - "method": { - "enum": [ - "rawResponseItem/completed" - ], - "title": "RawResponseItem/completedNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/v2/RawResponseItemCompletedNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "RawResponseItem/completedNotification", - "type": "object" - }, { "properties": { "method": { @@ -9183,68 +6111,6 @@ ], "title": "Account/login/completedNotification", "type": "object" - }, - { - "description": "DEPRECATED NOTIFICATIONS below", - "properties": { - "method": { - "enum": [ - "authStatusChange" - ], - "title": "AuthStatusChangeNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/AuthStatusChangeNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "AuthStatusChangeNotification", - "type": "object" - }, - { - "description": "Deprecated: use `account/login/completed` instead.", - "properties": { - "method": { - "enum": [ - "loginChatGptComplete" - ], - "title": "LoginChatGptCompleteNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/LoginChatGptCompleteNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "LoginChatGptCompleteNotification", - "type": "object" - }, - { - "properties": { - "method": { - "enum": [ - "sessionConfigured" - ], - "title": "SessionConfiguredNotificationMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SessionConfiguredNotification" - } - }, - "required": [ - "method", - "params" - ], - "title": "SessionConfiguredNotification", - "type": "object" } ], "title": "ServerNotification" @@ -9430,58 +6296,6 @@ ], "title": "ServerRequest" }, - "SessionConfiguredNotification": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "historyEntryCount": { - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "historyLogId": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "initialMessages": { - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "type": "string" - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "rolloutPath": { - "type": "string" - }, - "sessionId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "historyEntryCount", - "historyLogId", - "model", - "rolloutPath", - "sessionId" - ], - "title": "SessionConfiguredNotification", - "type": "object" - }, "SessionNetworkProxyRuntime": { "properties": { "admin_addr": { @@ -9501,258 +6315,6 @@ ], "type": "object" }, - "SessionSource": { - "oneOf": [ - { - "enum": [ - "cli", - "vscode", - "exec", - "mcp", - "unknown" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "subagent": { - "$ref": "#/definitions/SubAgentSource" - } - }, - "required": [ - "subagent" - ], - "title": "SubagentSessionSource", - "type": "object" - } - ] - }, - "SetDefaultModelParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "model": { - "type": [ - "string", - "null" - ] - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - } - }, - "title": "SetDefaultModelParams", - "type": "object" - }, - "SetDefaultModelResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "SetDefaultModelResponse", - "type": "object" - }, - "SkillDependencies": { - "properties": { - "tools": { - "items": { - "$ref": "#/definitions/SkillToolDependency" - }, - "type": "array" - } - }, - "required": [ - "tools" - ], - "type": "object" - }, - "SkillErrorInfo": { - "properties": { - "message": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "message", - "path" - ], - "type": "object" - }, - "SkillInterface": { - "properties": { - "brand_color": { - "type": [ - "string", - "null" - ] - }, - "default_prompt": { - "type": [ - "string", - "null" - ] - }, - "display_name": { - "type": [ - "string", - "null" - ] - }, - "icon_large": { - "type": [ - "string", - "null" - ] - }, - "icon_small": { - "type": [ - "string", - "null" - ] - }, - "short_description": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "SkillMetadata": { - "properties": { - "dependencies": { - "anyOf": [ - { - "$ref": "#/definitions/SkillDependencies" - }, - { - "type": "null" - } - ] - }, - "description": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "interface": { - "anyOf": [ - { - "$ref": "#/definitions/SkillInterface" - }, - { - "type": "null" - } - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "scope": { - "$ref": "#/definitions/SkillScope" - }, - "short_description": { - "description": "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "description", - "enabled", - "name", - "path", - "scope" - ], - "type": "object" - }, - "SkillScope": { - "enum": [ - "user", - "repo", - "system", - "admin" - ], - "type": "string" - }, - "SkillToolDependency": { - "properties": { - "command": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "transport": { - "type": [ - "string", - "null" - ] - }, - "type": { - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - }, - "value": { - "type": "string" - } - }, - "required": [ - "type", - "value" - ], - "type": "object" - }, - "SkillsListEntry": { - "properties": { - "cwd": { - "type": "string" - }, - "errors": { - "items": { - "$ref": "#/definitions/SkillErrorInfo" - }, - "type": "array" - }, - "skills": { - "items": { - "$ref": "#/definitions/SkillMetadata" - }, - "type": "array" - } - }, - "required": [ - "cwd", - "errors", - "skills" - ], - "type": "object" - }, "StepStatus": { "enum": [ "pending", @@ -9761,97 +6323,6 @@ ], "type": "string" }, - "SubAgentSource": { - "oneOf": [ - { - "enum": [ - "review", - "compact", - "memory_consolidation" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "thread_spawn": { - "properties": { - "agent_nickname": { - "default": null, - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "default": null, - "type": [ - "string", - "null" - ] - }, - "depth": { - "format": "int32", - "type": "integer" - }, - "parent_thread_id": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "depth", - "parent_thread_id" - ], - "type": "object" - } - }, - "required": [ - "thread_spawn" - ], - "title": "ThreadSpawnSubAgentSource", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "other": { - "type": "string" - } - }, - "required": [ - "other" - ], - "title": "OtherSubAgentSource", - "type": "object" - } - ] - }, - "TextElement": { - "properties": { - "byte_range": { - "allOf": [ - { - "$ref": "#/definitions/ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byte_range" - ], - "type": "object" - }, - "ThreadId": { - "type": "string" - }, "TokenUsage": { "properties": { "cached_input_tokens": { @@ -9906,42 +6377,6 @@ ], "type": "object" }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "inputSchema": true, - "name": { - "type": "string" - }, - "outputSchema": true, - "title": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, "ToolRequestUserInputAnswer": { "description": "EXPERIMENTAL. Captures a user's answer to a request_user_input question.", "properties": { @@ -10056,23 +6491,6 @@ "title": "ToolRequestUserInputResponse", "type": "object" }, - "Tools": { - "properties": { - "viewImage": { - "type": [ - "boolean", - "null" - ] - }, - "webSearch": { - "type": [ - "boolean", - "null" - ] - } - }, - "type": "object" - }, "TurnAbortReason": { "enum": [ "interrupted", @@ -10257,410 +6675,6 @@ } ] }, - "UserInfoResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "allegedUserEmail": { - "type": [ - "string", - "null" - ] - } - }, - "title": "UserInfoResponse", - "type": "object" - }, - "UserInput": { - "description": "User input", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` that should be treated as special elements. These are byte ranges into the UTF-8 `text` buffer and are used to render or persist rich input markers (e.g., image placeholders) across history and resume without mutating the literal text.", - "items": { - "$ref": "#/definitions/TextElement" - }, - "type": "array" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextUserInputType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextUserInput", - "type": "object" - }, - { - "description": "Pre‑encoded data: URI image.", - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageUserInputType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "ImageUserInput", - "type": "object" - }, - { - "description": "Local image path provided by the user. This will be converted to an `Image` variant (base64 data URL) during request serialization.", - "properties": { - "path": { - "type": "string" - }, - "type": { - "enum": [ - "local_image" - ], - "title": "LocalImageUserInputType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "LocalImageUserInput", - "type": "object" - }, - { - "description": "Skill selected by the user (name + path to SKILL.md).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "skill" - ], - "title": "SkillUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "SkillUserInput", - "type": "object" - }, - { - "description": "Explicit mention selected by the user (name + app://connector id).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "mention" - ], - "title": "MentionUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "MentionUserInput", - "type": "object" - } - ] - }, - "UserSavedConfig": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "forcedChatgptWorkspaceId": { - "type": [ - "string", - "null" - ] - }, - "forcedLoginMethod": { - "anyOf": [ - { - "$ref": "#/definitions/ForcedLoginMethod" - }, - { - "type": "null" - } - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelReasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "modelReasoningSummary": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningSummary" - }, - { - "type": "null" - } - ] - }, - "modelVerbosity": { - "anyOf": [ - { - "$ref": "#/definitions/Verbosity" - }, - { - "type": "null" - } - ] - }, - "profile": { - "type": [ - "string", - "null" - ] - }, - "profiles": { - "additionalProperties": { - "$ref": "#/definitions/Profile" - }, - "type": "object" - }, - "sandboxMode": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxMode" - }, - { - "type": "null" - } - ] - }, - "sandboxSettings": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxSettings" - }, - { - "type": "null" - } - ] - }, - "tools": { - "anyOf": [ - { - "$ref": "#/definitions/Tools" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "profiles" - ], - "type": "object" - }, - "V1ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "V1TextElement": { - "properties": { - "byteRange": { - "allOf": [ - { - "$ref": "#/definitions/V1ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byteRange" - ], - "type": "object" - }, - "Verbosity": { - "description": "Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.", - "enum": [ - "low", - "medium", - "high" - ], - "type": "string" - }, - "WebSearchAction": { - "oneOf": [ - { - "properties": { - "queries": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SearchWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "open_page" - ], - "title": "OpenPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "OpenPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "pattern": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "find_in_page" - ], - "title": "FindInPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "FindInPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherWebSearchAction", - "type": "object" - } - ] - }, "v2": { "AbsolutePathBuf": { "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", diff --git a/codex-rs/app-server-protocol/schema/json/v1/AddConversationListenerParams.json b/codex-rs/app-server-protocol/schema/json/v1/AddConversationListenerParams.json deleted file mode 100644 index 67b8bd7d81..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/AddConversationListenerParams.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "ThreadId": { - "type": "string" - } - }, - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "experimentalRawEvents": { - "default": false, - "type": "boolean" - } - }, - "required": [ - "conversationId" - ], - "title": "AddConversationListenerParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/AddConversationSubscriptionResponse.json b/codex-rs/app-server-protocol/schema/json/v1/AddConversationSubscriptionResponse.json deleted file mode 100644 index 8bd1bcf016..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/AddConversationSubscriptionResponse.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "subscriptionId": { - "type": "string" - } - }, - "required": [ - "subscriptionId" - ], - "title": "AddConversationSubscriptionResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationParams.json b/codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationParams.json deleted file mode 100644 index 7ee5b16b3b..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationParams.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "ThreadId": { - "type": "string" - } - }, - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "rolloutPath" - ], - "title": "ArchiveConversationParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationResponse.json deleted file mode 100644 index 253d15cc0d..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ArchiveConversationResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "ArchiveConversationResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/AuthStatusChangeNotification.json b/codex-rs/app-server-protocol/schema/json/v1/AuthStatusChangeNotification.json deleted file mode 100644 index 2aee28ba9c..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/AuthStatusChangeNotification.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AuthMode": { - "description": "Authentication mode for OpenAI-backed providers.", - "oneOf": [ - { - "description": "OpenAI API key provided by the caller and stored by Codex.", - "enum": [ - "apikey" - ], - "type": "string" - }, - { - "description": "ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex).", - "enum": [ - "chatgpt" - ], - "type": "string" - }, - { - "description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.\n\nChatGPT auth tokens are supplied by an external host app and are only stored in memory. Token refresh must be handled by the external host app.", - "enum": [ - "chatgptAuthTokens" - ], - "type": "string" - } - ] - } - }, - "description": "Deprecated notification. Use AccountUpdatedNotification instead.", - "properties": { - "authMethod": { - "anyOf": [ - { - "$ref": "#/definitions/AuthMode" - }, - { - "type": "null" - } - ] - } - }, - "title": "AuthStatusChangeNotification", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptParams.json b/codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptParams.json deleted file mode 100644 index 8367dac087..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptParams.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "loginId": { - "type": "string" - } - }, - "required": [ - "loginId" - ], - "title": "CancelLoginChatGptParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptResponse.json b/codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptResponse.json deleted file mode 100644 index a4e1c333c4..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/CancelLoginChatGptResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "CancelLoginChatGptResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandParams.json b/codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandParams.json deleted file mode 100644 index ec5b789352..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandParams.json +++ /dev/null @@ -1,225 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, - "NetworkAccess": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, - "ReadOnlyAccess": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess", - "type": "object" - } - ] - }, - "SandboxPolicy": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicyType", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy", - "type": "object" - } - ] - } - }, - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "sandboxPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxPolicy" - }, - { - "type": "null" - } - ] - }, - "timeoutMs": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "command" - ], - "title": "ExecOneOffCommandParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandResponse.json deleted file mode 100644 index 121ed648ff..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ExecOneOffCommandResponse.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "exitCode": { - "format": "int32", - "type": "integer" - }, - "stderr": { - "type": "string" - }, - "stdout": { - "type": "string" - } - }, - "required": [ - "exitCode", - "stderr", - "stdout" - ], - "title": "ExecOneOffCommandResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationParams.json b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationParams.json deleted file mode 100644 index b712352776..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationParams.json +++ /dev/null @@ -1,195 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "NewConversationParams": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "baseInstructions": { - "type": [ - "string", - "null" - ] - }, - "compactPrompt": { - "type": [ - "string", - "null" - ] - }, - "config": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "developerInstructions": { - "type": [ - "string", - "null" - ] - }, - "includeApplyPatchTool": { - "type": [ - "boolean", - "null" - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelProvider": { - "type": [ - "string", - "null" - ] - }, - "profile": { - "type": [ - "string", - "null" - ] - }, - "sandbox": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxMode" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "SandboxMode": { - "enum": [ - "read-only", - "workspace-write", - "danger-full-access" - ], - "type": "string" - }, - "ThreadId": { - "type": "string" - } - }, - "properties": { - "conversationId": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "overrides": { - "anyOf": [ - { - "$ref": "#/definitions/NewConversationParams" - }, - { - "type": "null" - } - ] - }, - "path": { - "type": [ - "string", - "null" - ] - } - }, - "title": "ForkConversationParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json deleted file mode 100644 index 70521ec729..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json +++ /dev/null @@ -1,5776 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, - "AgentMessageContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Text" - ], - "title": "TextAgentMessageContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextAgentMessageContent", - "type": "object" - } - ] - }, - "AgentStatus": { - "description": "Agent lifecycle status, derived from emitted events.", - "oneOf": [ - { - "description": "Agent is waiting for initialization.", - "enum": [ - "pending_init" - ], - "type": "string" - }, - { - "description": "Agent is currently running.", - "enum": [ - "running" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Agent is done. Contains the final assistant message.", - "properties": { - "completed": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "completed" - ], - "title": "CompletedAgentStatus", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Agent encountered an error.", - "properties": { - "errored": { - "type": "string" - } - }, - "required": [ - "errored" - ], - "title": "ErroredAgentStatus", - "type": "object" - }, - { - "description": "Agent has been shutdown.", - "enum": [ - "shutdown" - ], - "type": "string" - }, - { - "description": "Agent is not found.", - "enum": [ - "not_found" - ], - "type": "string" - } - ] - }, - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "CallToolResult": { - "description": "The server's response to a tool call.", - "properties": { - "_meta": true, - "content": { - "items": true, - "type": "array" - }, - "isError": { - "type": [ - "boolean", - "null" - ] - }, - "structuredContent": true - }, - "required": [ - "content" - ], - "type": "object" - }, - "CodexErrorInfo": { - "description": "Codex errors that we expose to clients.", - "oneOf": [ - { - "enum": [ - "context_window_exceeded", - "usage_limit_exceeded", - "server_overloaded", - "internal_server_error", - "unauthorized", - "bad_request", - "sandbox_error", - "thread_rollback_failed", - "other" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "http_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "http_connection_failed" - ], - "title": "HttpConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Failed to connect to the response SSE stream.", - "properties": { - "response_stream_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_connection_failed" - ], - "title": "ResponseStreamConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "The response SSE stream disconnected in the middle of a turnbefore completion.", - "properties": { - "response_stream_disconnected": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_disconnected" - ], - "title": "ResponseStreamDisconnectedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Reached the retry limit for responses.", - "properties": { - "response_too_many_failed_attempts": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_too_many_failed_attempts" - ], - "title": "ResponseTooManyFailedAttemptsCodexErrorInfo", - "type": "object" - } - ] - }, - "CollabAgentRef": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "thread_id" - ], - "type": "object" - }, - "CollabAgentStatusEntry": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the agent." - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "status", - "thread_id" - ], - "type": "object" - }, - "ContentItem": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageContentItem", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "output_text" - ], - "title": "OutputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "OutputTextContentItem", - "type": "object" - } - ] - }, - "CreditsSnapshot": { - "properties": { - "balance": { - "type": [ - "string", - "null" - ] - }, - "has_credits": { - "type": "boolean" - }, - "unlimited": { - "type": "boolean" - } - }, - "required": [ - "has_credits", - "unlimited" - ], - "type": "object" - }, - "CustomPrompt": { - "properties": { - "argument_hint": { - "type": [ - "string", - "null" - ] - }, - "content": { - "type": "string" - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "content", - "name", - "path" - ], - "type": "object" - }, - "Duration": { - "properties": { - "nanos": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "secs": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "nanos", - "secs" - ], - "type": "object" - }, - "EventMsg": { - "description": "Response event from the agent NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.", - "oneOf": [ - { - "description": "Error while executing a submission", - "properties": { - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "error" - ], - "title": "ErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "ErrorEventMsg", - "type": "object" - }, - { - "description": "Warning issued while processing a submission. Unlike `Error`, this indicates the turn continued but the user should still be notified.", - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "warning" - ], - "title": "WarningEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "WarningEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle start event.", - "properties": { - "session_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_started" - ], - "title": "RealtimeConversationStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationStartedEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation streaming payload event.", - "properties": { - "payload": { - "$ref": "#/definitions/RealtimeEvent" - }, - "type": { - "enum": [ - "realtime_conversation_realtime" - ], - "title": "RealtimeConversationRealtimeEventMsgType", - "type": "string" - } - }, - "required": [ - "payload", - "type" - ], - "title": "RealtimeConversationRealtimeEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle close event.", - "properties": { - "reason": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_closed" - ], - "title": "RealtimeConversationClosedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationClosedEventMsg", - "type": "object" - }, - { - "description": "Model routing changed from the requested model to a different model.", - "properties": { - "from_model": { - "type": "string" - }, - "reason": { - "$ref": "#/definitions/ModelRerouteReason" - }, - "to_model": { - "type": "string" - }, - "type": { - "enum": [ - "model_reroute" - ], - "title": "ModelRerouteEventMsgType", - "type": "string" - } - }, - "required": [ - "from_model", - "reason", - "to_model", - "type" - ], - "title": "ModelRerouteEventMsg", - "type": "object" - }, - { - "description": "Conversation history was compacted (either automatically or manually).", - "properties": { - "type": { - "enum": [ - "context_compacted" - ], - "title": "ContextCompactedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ContextCompactedEventMsg", - "type": "object" - }, - { - "description": "Conversation history was rolled back by dropping the last N user turns.", - "properties": { - "num_turns": { - "description": "Number of user turns that were removed from context.", - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "thread_rolled_back" - ], - "title": "ThreadRolledBackEventMsgType", - "type": "string" - } - }, - "required": [ - "num_turns", - "type" - ], - "title": "ThreadRolledBackEventMsg", - "type": "object" - }, - { - "description": "Agent has started a turn. v1 wire format uses `task_started`; accept `turn_started` for v2 interop.", - "properties": { - "collaboration_mode_kind": { - "allOf": [ - { - "$ref": "#/definitions/ModeKind" - } - ], - "default": "default" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_started" - ], - "title": "TaskStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskStartedEventMsg", - "type": "object" - }, - { - "description": "Agent has completed all actions. v1 wire format uses `task_complete`; accept `turn_complete` for v2 interop.", - "properties": { - "last_agent_message": { - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_complete" - ], - "title": "TaskCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskCompleteEventMsg", - "type": "object" - }, - { - "description": "Usage update for the current session, including totals and last turn. Optional means unknown — UIs should not display when `None`.", - "properties": { - "info": { - "anyOf": [ - { - "$ref": "#/definitions/TokenUsageInfo" - }, - { - "type": "null" - } - ] - }, - "rate_limits": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitSnapshot" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "token_count" - ], - "title": "TokenCountEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "TokenCountEventMsg", - "type": "object" - }, - { - "description": "Agent text output message", - "properties": { - "message": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "default": null - }, - "type": { - "enum": [ - "agent_message" - ], - "title": "AgentMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "AgentMessageEventMsg", - "type": "object" - }, - { - "description": "User/system input message (what was sent to the model)", - "properties": { - "images": { - "description": "Image URLs sourced from `UserInput::Image`. These are safe to replay in legacy UI history events and correspond to images sent to the model.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "local_images": { - "default": [], - "description": "Local file paths sourced from `UserInput::LocalImage`. These are kept so the UI can reattach images when editing history, and should not be sent to the model or treated as API-ready URLs.", - "items": { - "type": "string" - }, - "type": "array" - }, - "message": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `message` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/TextElement" - }, - "type": "array" - }, - "type": { - "enum": [ - "user_message" - ], - "title": "UserMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "UserMessageEventMsg", - "type": "object" - }, - { - "description": "Agent text output delta message", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_delta" - ], - "title": "AgentMessageDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentMessageDeltaEventMsg", - "type": "object" - }, - { - "description": "Reasoning event from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning" - ], - "title": "AgentReasoningEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_delta" - ], - "title": "AgentReasoningDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningDeltaEventMsg", - "type": "object" - }, - { - "description": "Raw chain-of-thought from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content" - ], - "title": "AgentReasoningRawContentEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningRawContentEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning content delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content_delta" - ], - "title": "AgentReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Signaled when the model begins a new reasoning summary section (e.g., a new titled block).", - "properties": { - "item_id": { - "default": "", - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "type": { - "enum": [ - "agent_reasoning_section_break" - ], - "title": "AgentReasoningSectionBreakEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "AgentReasoningSectionBreakEventMsg", - "type": "object" - }, - { - "description": "Ack the client's configure message.", - "properties": { - "approval_policy": { - "allOf": [ - { - "$ref": "#/definitions/AskForApproval" - } - ], - "description": "When to escalate for approval for execution" - }, - "cwd": { - "description": "Working directory that should be treated as the *root* of the session.", - "type": "string" - }, - "forked_from_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "history_entry_count": { - "description": "Current number of entries in the history log.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "history_log_id": { - "description": "Identifier of the history log file (inode on Unix, 0 otherwise).", - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "initial_messages": { - "description": "Optional initial messages (as events) for resumed sessions. When present, UIs can use these to seed the history.", - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "description": "Tell the client what model is being queried.", - "type": "string" - }, - "model_provider_id": { - "type": "string" - }, - "network_proxy": { - "anyOf": [ - { - "$ref": "#/definitions/SessionNetworkProxyRuntime" - }, - { - "type": "null" - } - ], - "description": "Runtime proxy bind addresses, when the managed proxy was started for this session." - }, - "reasoning_effort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ], - "description": "The effort the model is putting into reasoning about the user's request." - }, - "rollout_path": { - "description": "Path in which the rollout is stored. Can be `None` for ephemeral threads", - "type": [ - "string", - "null" - ] - }, - "sandbox_policy": { - "allOf": [ - { - "$ref": "#/definitions/SandboxPolicy" - } - ], - "description": "How to sandbox commands executed in the system" - }, - "session_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "description": "Optional user-facing thread name (may be unset).", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "session_configured" - ], - "title": "SessionConfiguredEventMsgType", - "type": "string" - } - }, - "required": [ - "approval_policy", - "cwd", - "history_entry_count", - "history_log_id", - "model", - "model_provider_id", - "sandbox_policy", - "session_id", - "type" - ], - "title": "SessionConfiguredEventMsg", - "type": "object" - }, - { - "description": "Updated session metadata (e.g., thread name changes).", - "properties": { - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "thread_name_updated" - ], - "title": "ThreadNameUpdatedEventMsgType", - "type": "string" - } - }, - "required": [ - "thread_id", - "type" - ], - "title": "ThreadNameUpdatedEventMsg", - "type": "object" - }, - { - "description": "Incremental MCP startup progress updates.", - "properties": { - "server": { - "description": "Server name being started.", - "type": "string" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/McpStartupStatus" - } - ], - "description": "Current startup status." - }, - "type": { - "enum": [ - "mcp_startup_update" - ], - "title": "McpStartupUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "server", - "status", - "type" - ], - "title": "McpStartupUpdateEventMsg", - "type": "object" - }, - { - "description": "Aggregate MCP startup completion summary.", - "properties": { - "cancelled": { - "items": { - "type": "string" - }, - "type": "array" - }, - "failed": { - "items": { - "$ref": "#/definitions/McpStartupFailure" - }, - "type": "array" - }, - "ready": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "mcp_startup_complete" - ], - "title": "McpStartupCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "cancelled", - "failed", - "ready", - "type" - ], - "title": "McpStartupCompleteEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the McpToolCallEnd event.", - "type": "string" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "type": { - "enum": [ - "mcp_tool_call_begin" - ], - "title": "McpToolCallBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "invocation", - "type" - ], - "title": "McpToolCallBeginEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier for the corresponding McpToolCallBegin that finished.", - "type": "string" - }, - "duration": { - "$ref": "#/definitions/Duration" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "result": { - "allOf": [ - { - "$ref": "#/definitions/Result_of_CallToolResult_or_String" - } - ], - "description": "Result of the tool call. Note this could be an error." - }, - "type": { - "enum": [ - "mcp_tool_call_end" - ], - "title": "McpToolCallEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "duration", - "invocation", - "result", - "type" - ], - "title": "McpToolCallEndEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_begin" - ], - "title": "WebSearchBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "type" - ], - "title": "WebSearchBeginEventMsg", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction" - }, - "call_id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_end" - ], - "title": "WebSearchEndEventMsgType", - "type": "string" - } - }, - "required": [ - "action", - "call_id", - "query", - "type" - ], - "title": "WebSearchEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the server is about to execute a command.", - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the ExecCommandEnd event.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_begin" - ], - "title": "ExecCommandBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "turn_id", - "type" - ], - "title": "ExecCommandBeginEventMsg", - "type": "object" - }, - { - "description": "Incremental chunk of output from a running command.", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "chunk": { - "description": "Raw bytes from the stream (may not be valid UTF-8).", - "type": "string" - }, - "stream": { - "allOf": [ - { - "$ref": "#/definitions/ExecOutputStream" - } - ], - "description": "Which stream produced this chunk." - }, - "type": { - "enum": [ - "exec_command_output_delta" - ], - "title": "ExecCommandOutputDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "chunk", - "stream", - "type" - ], - "title": "ExecCommandOutputDeltaEventMsg", - "type": "object" - }, - { - "description": "Terminal interaction for an in-progress command (stdin sent and stdout observed).", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "process_id": { - "description": "Process id associated with the running command.", - "type": "string" - }, - "stdin": { - "description": "Stdin sent to the running session.", - "type": "string" - }, - "type": { - "enum": [ - "terminal_interaction" - ], - "title": "TerminalInteractionEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "process_id", - "stdin", - "type" - ], - "title": "TerminalInteractionEventMsg", - "type": "object" - }, - { - "properties": { - "aggregated_output": { - "default": "", - "description": "Captured aggregated output", - "type": "string" - }, - "call_id": { - "description": "Identifier for the ExecCommandBegin that finished.", - "type": "string" - }, - "command": { - "description": "The command that was executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "duration": { - "allOf": [ - { - "$ref": "#/definitions/Duration" - } - ], - "description": "The duration of the command execution." - }, - "exit_code": { - "description": "The command's exit code.", - "format": "int32", - "type": "integer" - }, - "formatted_output": { - "description": "Formatted output from the command, as seen by the model.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandStatus" - } - ], - "description": "Completion status for this command execution." - }, - "stderr": { - "description": "Captured stderr", - "type": "string" - }, - "stdout": { - "description": "Captured stdout", - "type": "string" - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_end" - ], - "title": "ExecCommandEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "duration", - "exit_code", - "formatted_output", - "parsed_cmd", - "status", - "stderr", - "stdout", - "turn_id", - "type" - ], - "title": "ExecCommandEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent attached a local image via the view_image tool.", - "properties": { - "call_id": { - "description": "Identifier for the originating tool call.", - "type": "string" - }, - "path": { - "description": "Local filesystem path provided to the tool.", - "type": "string" - }, - "type": { - "enum": [ - "view_image_tool_call" - ], - "title": "ViewImageToolCallEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "path", - "type" - ], - "title": "ViewImageToolCallEventMsg", - "type": "object" - }, - { - "properties": { - "approval_id": { - "description": "Identifier for this specific approval callback.\n\nWhen absent, the approval is for the command item itself (`call_id`). This is present for subcommand approvals (via execve intercept).", - "type": [ - "string", - "null" - ] - }, - "call_id": { - "description": "Identifier for the associated command execution item.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory.", - "type": "string" - }, - "network_approval_context": { - "anyOf": [ - { - "$ref": "#/definitions/NetworkApprovalContext" - }, - { - "type": "null" - } - ], - "description": "Optional network context for a blocked request that can be approved." - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "proposed_execpolicy_amendment": { - "description": "Proposed execpolicy amendment that can be applied to allow future runs.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "reason": { - "description": "Optional human-readable reason for the approval (e.g. retry without sandbox).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this command belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "exec_approval_request" - ], - "title": "ExecApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "type" - ], - "title": "ExecApprovalRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated tool call, if available.", - "type": "string" - }, - "questions": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestion" - }, - "type": "array" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this request belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "request_user_input" - ], - "title": "RequestUserInputEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "questions", - "type" - ], - "title": "RequestUserInputEventMsg", - "type": "object" - }, - { - "properties": { - "arguments": true, - "callId": { - "type": "string" - }, - "tool": { - "type": "string" - }, - "turnId": { - "type": "string" - }, - "type": { - "enum": [ - "dynamic_tool_call_request" - ], - "title": "DynamicToolCallRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "arguments", - "callId", - "tool", - "turnId", - "type" - ], - "title": "DynamicToolCallRequestEventMsg", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "message": { - "type": "string" - }, - "server_name": { - "type": "string" - }, - "type": { - "enum": [ - "elicitation_request" - ], - "title": "ElicitationRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "message", - "server_name", - "type" - ], - "title": "ElicitationRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated patch apply call, if available.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "type": "object" - }, - "grant_root": { - "description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session.", - "type": [ - "string", - "null" - ] - }, - "reason": { - "description": "Optional explanatory reason (e.g. request for extra write access).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility with older senders.", - "type": "string" - }, - "type": { - "enum": [ - "apply_patch_approval_request" - ], - "title": "ApplyPatchApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "changes", - "type" - ], - "title": "ApplyPatchApprovalRequestEventMsg", - "type": "object" - }, - { - "description": "Notification advising the user that something they are using has been deprecated and should be phased out.", - "properties": { - "details": { - "description": "Optional extra guidance, such as migration steps or rationale.", - "type": [ - "string", - "null" - ] - }, - "summary": { - "description": "Concise summary of what is deprecated.", - "type": "string" - }, - "type": { - "enum": [ - "deprecation_notice" - ], - "title": "DeprecationNoticeEventMsgType", - "type": "string" - } - }, - "required": [ - "summary", - "type" - ], - "title": "DeprecationNoticeEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "background_event" - ], - "title": "BackgroundEventEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "BackgroundEventEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "undo_started" - ], - "title": "UndoStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UndoStartedEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "success": { - "type": "boolean" - }, - "type": { - "enum": [ - "undo_completed" - ], - "title": "UndoCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "success", - "type" - ], - "title": "UndoCompletedEventMsg", - "type": "object" - }, - { - "description": "Notification that a model stream experienced an error or disconnect and the system is handling it (e.g., retrying with backoff).", - "properties": { - "additional_details": { - "default": null, - "description": "Optional details about the underlying stream failure (often the same human-readable message that is surfaced as the terminal error if retries are exhausted).", - "type": [ - "string", - "null" - ] - }, - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "stream_error" - ], - "title": "StreamErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "StreamErrorEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is about to apply a code patch. Mirrors `ExecCommandBegin` so front‑ends can show progress indicators.", - "properties": { - "auto_approved": { - "description": "If true, there was no ApplyPatchApprovalRequest for this patch.", - "type": "boolean" - }, - "call_id": { - "description": "Identifier so this can be paired with the PatchApplyEnd event.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "description": "The changes to be applied.", - "type": "object" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_begin" - ], - "title": "PatchApplyBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "auto_approved", - "call_id", - "changes", - "type" - ], - "title": "PatchApplyBeginEventMsg", - "type": "object" - }, - { - "description": "Notification that a patch application has finished.", - "properties": { - "call_id": { - "description": "Identifier for the PatchApplyBegin that finished.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "default": {}, - "description": "The changes that were applied (mirrors PatchApplyBeginEvent::changes).", - "type": "object" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/PatchApplyStatus" - } - ], - "description": "Completion status for this patch application." - }, - "stderr": { - "description": "Captured stderr (parser errors, IO failures, etc.).", - "type": "string" - }, - "stdout": { - "description": "Captured stdout (summary printed by apply_patch).", - "type": "string" - }, - "success": { - "description": "Whether the patch was applied successfully.", - "type": "boolean" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_end" - ], - "title": "PatchApplyEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "status", - "stderr", - "stdout", - "success", - "type" - ], - "title": "PatchApplyEndEventMsg", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "turn_diff" - ], - "title": "TurnDiffEventMsgType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "TurnDiffEventMsg", - "type": "object" - }, - { - "description": "Response to GetHistoryEntryRequest.", - "properties": { - "entry": { - "anyOf": [ - { - "$ref": "#/definitions/HistoryEntry" - }, - { - "type": "null" - } - ], - "description": "The entry at the requested offset, if available and parseable." - }, - "log_id": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "offset": { - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "get_history_entry_response" - ], - "title": "GetHistoryEntryResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "log_id", - "offset", - "type" - ], - "title": "GetHistoryEntryResponseEventMsg", - "type": "object" - }, - { - "description": "List of MCP tools available to the agent.", - "properties": { - "auth_statuses": { - "additionalProperties": { - "$ref": "#/definitions/McpAuthStatus" - }, - "description": "Authentication status for each configured MCP server.", - "type": "object" - }, - "resource_templates": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/ResourceTemplate" - }, - "type": "array" - }, - "description": "Known resource templates grouped by server name.", - "type": "object" - }, - "resources": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/Resource" - }, - "type": "array" - }, - "description": "Known resources grouped by server name.", - "type": "object" - }, - "tools": { - "additionalProperties": { - "$ref": "#/definitions/Tool" - }, - "description": "Fully qualified tool name -> tool definition.", - "type": "object" - }, - "type": { - "enum": [ - "mcp_list_tools_response" - ], - "title": "McpListToolsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "auth_statuses", - "resource_templates", - "resources", - "tools", - "type" - ], - "title": "McpListToolsResponseEventMsg", - "type": "object" - }, - { - "description": "List of custom prompts available to the agent.", - "properties": { - "custom_prompts": { - "items": { - "$ref": "#/definitions/CustomPrompt" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_custom_prompts_response" - ], - "title": "ListCustomPromptsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "custom_prompts", - "type" - ], - "title": "ListCustomPromptsResponseEventMsg", - "type": "object" - }, - { - "description": "List of skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/SkillsListEntry" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_skills_response" - ], - "title": "ListSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "List of remote skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/RemoteSkillSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_remote_skills_response" - ], - "title": "ListRemoteSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListRemoteSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "Remote skill downloaded to local cache.", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "remote_skill_downloaded" - ], - "title": "RemoteSkillDownloadedEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "name", - "path", - "type" - ], - "title": "RemoteSkillDownloadedEventMsg", - "type": "object" - }, - { - "description": "Notification that skill data may have been updated and clients may want to reload.", - "properties": { - "type": { - "enum": [ - "skills_update_available" - ], - "title": "SkillsUpdateAvailableEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SkillsUpdateAvailableEventMsg", - "type": "object" - }, - { - "properties": { - "explanation": { - "default": null, - "description": "Arguments for the `update_plan` todo/checklist tool (not plan mode).", - "type": [ - "string", - "null" - ] - }, - "plan": { - "items": { - "$ref": "#/definitions/PlanItemArg" - }, - "type": "array" - }, - "type": { - "enum": [ - "plan_update" - ], - "title": "PlanUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "plan", - "type" - ], - "title": "PlanUpdateEventMsg", - "type": "object" - }, - { - "properties": { - "reason": { - "$ref": "#/definitions/TurnAbortReason" - }, - "turn_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "turn_aborted" - ], - "title": "TurnAbortedEventMsgType", - "type": "string" - } - }, - "required": [ - "reason", - "type" - ], - "title": "TurnAbortedEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is shutting down.", - "properties": { - "type": { - "enum": [ - "shutdown_complete" - ], - "title": "ShutdownCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ShutdownCompleteEventMsg", - "type": "object" - }, - { - "description": "Entered review mode.", - "properties": { - "target": { - "$ref": "#/definitions/ReviewTarget" - }, - "type": { - "enum": [ - "entered_review_mode" - ], - "title": "EnteredReviewModeEventMsgType", - "type": "string" - }, - "user_facing_hint": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "target", - "type" - ], - "title": "EnteredReviewModeEventMsg", - "type": "object" - }, - { - "description": "Exited review mode with an optional final result to apply.", - "properties": { - "review_output": { - "anyOf": [ - { - "$ref": "#/definitions/ReviewOutputEvent" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "exited_review_mode" - ], - "title": "ExitedReviewModeEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExitedReviewModeEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/ResponseItem" - }, - "type": { - "enum": [ - "raw_response_item" - ], - "title": "RawResponseItemEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "type" - ], - "title": "RawResponseItemEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_started" - ], - "title": "ItemStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemStartedEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_completed" - ], - "title": "ItemCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemCompletedEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_content_delta" - ], - "title": "AgentMessageContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "AgentMessageContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "plan_delta" - ], - "title": "PlanDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "PlanDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_content_delta" - ], - "title": "ReasoningContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "content_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_raw_content_delta" - ], - "title": "ReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_spawn_begin" - ], - "title": "CollabAgentSpawnBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "type" - ], - "title": "CollabAgentSpawnBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "new_agent_nickname": { - "description": "Optional nickname assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_agent_role": { - "description": "Optional role assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_thread_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ], - "description": "Thread ID of the newly spawned agent, if it was created." - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the new agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_spawn_end" - ], - "title": "CollabAgentSpawnEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentSpawnEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_interaction_begin" - ], - "title": "CollabAgentInteractionBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabAgentInteractionBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_interaction_end" - ], - "title": "CollabAgentInteractionEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentInteractionEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting begin.", - "properties": { - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "receiver_agents": { - "description": "Optional nicknames/roles for receivers.", - "items": { - "$ref": "#/definitions/CollabAgentRef" - }, - "type": "array" - }, - "receiver_thread_ids": { - "description": "Thread ID of the receivers.", - "items": { - "$ref": "#/definitions/ThreadId" - }, - "type": "array" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_waiting_begin" - ], - "title": "CollabWaitingBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_ids", - "sender_thread_id", - "type" - ], - "title": "CollabWaitingBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting end.", - "properties": { - "agent_statuses": { - "description": "Optional receiver metadata paired with final statuses.", - "items": { - "$ref": "#/definitions/CollabAgentStatusEntry" - }, - "type": "array" - }, - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "statuses": { - "additionalProperties": { - "$ref": "#/definitions/AgentStatus" - }, - "description": "Last known status of the receiver agents reported to the sender agent.", - "type": "object" - }, - "type": { - "enum": [ - "collab_waiting_end" - ], - "title": "CollabWaitingEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "sender_thread_id", - "statuses", - "type" - ], - "title": "CollabWaitingEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_close_begin" - ], - "title": "CollabCloseBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabCloseBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent before the close." - }, - "type": { - "enum": [ - "collab_close_end" - ], - "title": "CollabCloseEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabCloseEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_resume_begin" - ], - "title": "CollabResumeBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabResumeBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent after resume." - }, - "type": { - "enum": [ - "collab_resume_end" - ], - "title": "CollabResumeEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabResumeEndEventMsg", - "type": "object" - } - ] - }, - "ExecCommandSource": { - "enum": [ - "agent", - "user_shell", - "unified_exec_startup", - "unified_exec_interaction" - ], - "type": "string" - }, - "ExecCommandStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, - "ExecOutputStream": { - "enum": [ - "stdout", - "stderr" - ], - "type": "string" - }, - "FileChange": { - "oneOf": [ - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "add" - ], - "title": "AddFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "AddFileChange", - "type": "object" - }, - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "delete" - ], - "title": "DeleteFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "DeleteFileChange", - "type": "object" - }, - { - "properties": { - "move_path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "update" - ], - "title": "UpdateFileChangeType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "UpdateFileChange", - "type": "object" - } - ] - }, - "FunctionCallOutputBody": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "$ref": "#/definitions/FunctionCallOutputContentItem" - }, - "type": "array" - } - ] - }, - "FunctionCallOutputContentItem": { - "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextFunctionCallOutputContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageFunctionCallOutputContentItem", - "type": "object" - } - ] - }, - "FunctionCallOutputPayload": { - "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", - "properties": { - "body": { - "$ref": "#/definitions/FunctionCallOutputBody" - }, - "success": { - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "body" - ], - "type": "object" - }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, - "HistoryEntry": { - "properties": { - "conversation_id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "ts": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "conversation_id", - "text", - "ts" - ], - "type": "object" - }, - "LocalShellAction": { - "oneOf": [ - { - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "timeout_ms": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - }, - "type": { - "enum": [ - "exec" - ], - "title": "ExecLocalShellActionType", - "type": "string" - }, - "user": { - "type": [ - "string", - "null" - ] - }, - "working_directory": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "command", - "type" - ], - "title": "ExecLocalShellAction", - "type": "object" - } - ] - }, - "LocalShellStatus": { - "enum": [ - "completed", - "in_progress", - "incomplete" - ], - "type": "string" - }, - "McpAuthStatus": { - "enum": [ - "unsupported", - "not_logged_in", - "bearer_token", - "o_auth" - ], - "type": "string" - }, - "McpInvocation": { - "properties": { - "arguments": { - "description": "Arguments to the tool call." - }, - "server": { - "description": "Name of the MCP server as defined in the config.", - "type": "string" - }, - "tool": { - "description": "Name of the tool as given by the MCP server.", - "type": "string" - } - }, - "required": [ - "server", - "tool" - ], - "type": "object" - }, - "McpStartupFailure": { - "properties": { - "error": { - "type": "string" - }, - "server": { - "type": "string" - } - }, - "required": [ - "error", - "server" - ], - "type": "object" - }, - "McpStartupStatus": { - "oneOf": [ - { - "properties": { - "state": { - "enum": [ - "starting" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus", - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "ready" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus2", - "type": "object" - }, - { - "properties": { - "error": { - "type": "string" - }, - "state": { - "enum": [ - "failed" - ], - "type": "string" - } - }, - "required": [ - "error", - "state" - ], - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "cancelled" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus3", - "type": "object" - } - ] - }, - "MessagePhase": { - "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", - "oneOf": [ - { - "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", - "enum": [ - "commentary" - ], - "type": "string" - }, - { - "description": "The assistant's terminal answer text for the current turn.", - "enum": [ - "final_answer" - ], - "type": "string" - } - ] - }, - "ModeKind": { - "description": "Initial collaboration mode to use when the TUI starts.", - "enum": [ - "plan", - "default" - ], - "type": "string" - }, - "ModelRerouteReason": { - "enum": [ - "high_risk_cyber_activity" - ], - "type": "string" - }, - "NetworkAccess": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, - "NetworkApprovalContext": { - "properties": { - "host": { - "type": "string" - }, - "protocol": { - "$ref": "#/definitions/NetworkApprovalProtocol" - } - }, - "required": [ - "host", - "protocol" - ], - "type": "object" - }, - "NetworkApprovalProtocol": { - "enum": [ - "http", - "https", - "socks5_tcp", - "socks5_udp" - ], - "type": "string" - }, - "ParsedCommand": { - "oneOf": [ - { - "properties": { - "cmd": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", - "type": "string" - }, - "type": { - "enum": [ - "read" - ], - "title": "ReadParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "name", - "path", - "type" - ], - "title": "ReadParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "list_files" - ], - "title": "ListFilesParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "ListFilesParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "SearchParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "type": { - "enum": [ - "unknown" - ], - "title": "UnknownParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "UnknownParsedCommand", - "type": "object" - } - ] - }, - "PatchApplyStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, - "PlanItemArg": { - "additionalProperties": false, - "properties": { - "status": { - "$ref": "#/definitions/StepStatus" - }, - "step": { - "type": "string" - } - }, - "required": [ - "status", - "step" - ], - "type": "object" - }, - "PlanType": { - "enum": [ - "free", - "go", - "plus", - "pro", - "team", - "business", - "enterprise", - "edu", - "unknown" - ], - "type": "string" - }, - "RateLimitSnapshot": { - "properties": { - "credits": { - "anyOf": [ - { - "$ref": "#/definitions/CreditsSnapshot" - }, - { - "type": "null" - } - ] - }, - "limit_id": { - "type": [ - "string", - "null" - ] - }, - "limit_name": { - "type": [ - "string", - "null" - ] - }, - "plan_type": { - "anyOf": [ - { - "$ref": "#/definitions/PlanType" - }, - { - "type": "null" - } - ] - }, - "primary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - }, - "secondary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "RateLimitWindow": { - "properties": { - "resets_at": { - "description": "Unix timestamp (seconds since epoch) when the window resets.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "used_percent": { - "description": "Percentage (0-100) of the window that has been consumed.", - "format": "double", - "type": "number" - }, - "window_minutes": { - "description": "Rolling window duration, in minutes.", - "format": "int64", - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "used_percent" - ], - "type": "object" - }, - "ReadOnlyAccess": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess", - "type": "object" - } - ] - }, - "RealtimeAudioFrame": { - "properties": { - "data": { - "type": "string" - }, - "num_channels": { - "format": "uint16", - "minimum": 0.0, - "type": "integer" - }, - "sample_rate": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "samples_per_channel": { - "format": "uint32", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "data", - "num_channels", - "sample_rate" - ], - "type": "object" - }, - "RealtimeEvent": { - "oneOf": [ - { - "additionalProperties": false, - "properties": { - "SessionCreated": { - "properties": { - "session_id": { - "type": "string" - } - }, - "required": [ - "session_id" - ], - "type": "object" - } - }, - "required": [ - "SessionCreated" - ], - "title": "SessionCreatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "SessionUpdated": { - "properties": { - "backend_prompt": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "SessionUpdated" - ], - "title": "SessionUpdatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "AudioOut": { - "$ref": "#/definitions/RealtimeAudioFrame" - } - }, - "required": [ - "AudioOut" - ], - "title": "AudioOutRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "ConversationItemAdded": true - }, - "required": [ - "ConversationItemAdded" - ], - "title": "ConversationItemAddedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "Error": { - "type": "string" - } - }, - "required": [ - "Error" - ], - "title": "ErrorRealtimeEvent", - "type": "object" - } - ] - }, - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ReasoningItemContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_text" - ], - "title": "ReasoningTextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "ReasoningTextReasoningItemContent", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextReasoningItemContent", - "type": "object" - } - ] - }, - "ReasoningItemReasoningSummary": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "summary_text" - ], - "title": "SummaryTextReasoningItemReasoningSummaryType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "SummaryTextReasoningItemReasoningSummary", - "type": "object" - } - ] - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "RemoteSkillSummary": { - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "description", - "id", - "name" - ], - "type": "object" - }, - "RequestId": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "int64", - "type": "integer" - } - ], - "description": "ID of a request, which can be either a string or an integer." - }, - "RequestUserInputQuestion": { - "properties": { - "header": { - "type": "string" - }, - "id": { - "type": "string" - }, - "isOther": { - "default": false, - "type": "boolean" - }, - "isSecret": { - "default": false, - "type": "boolean" - }, - "options": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestionOption" - }, - "type": [ - "array", - "null" - ] - }, - "question": { - "type": "string" - } - }, - "required": [ - "header", - "id", - "question" - ], - "type": "object" - }, - "RequestUserInputQuestionOption": { - "properties": { - "description": { - "type": "string" - }, - "label": { - "type": "string" - } - }, - "required": [ - "description", - "label" - ], - "type": "object" - }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "size": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uri": { - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uriTemplate": { - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResponseItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/ContentItem" - }, - "type": "array" - }, - "end_turn": { - "type": [ - "boolean", - "null" - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ] - }, - "role": { - "type": "string" - }, - "type": { - "enum": [ - "message" - ], - "title": "MessageResponseItemType", - "type": "string" - } - }, - "required": [ - "content", - "role", - "type" - ], - "title": "MessageResponseItem", - "type": "object" - }, - { - "properties": { - "content": { - "default": null, - "items": { - "$ref": "#/definitions/ReasoningItemContent" - }, - "type": [ - "array", - "null" - ] - }, - "encrypted_content": { - "type": [ - "string", - "null" - ] - }, - "id": { - "type": "string", - "writeOnly": true - }, - "summary": { - "items": { - "$ref": "#/definitions/ReasoningItemReasoningSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "reasoning" - ], - "title": "ReasoningResponseItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary", - "type" - ], - "title": "ReasoningResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/LocalShellAction" - }, - "call_id": { - "description": "Set when using the Responses API.", - "type": [ - "string", - "null" - ] - }, - "id": { - "description": "Legacy id field retained for compatibility with older payloads.", - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "$ref": "#/definitions/LocalShellStatus" - }, - "type": { - "enum": [ - "local_shell_call" - ], - "title": "LocalShellCallResponseItemType", - "type": "string" - } - }, - "required": [ - "action", - "status", - "type" - ], - "title": "LocalShellCallResponseItem", - "type": "object" - }, - { - "properties": { - "arguments": { - "type": "string" - }, - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "name": { - "type": "string" - }, - "type": { - "enum": [ - "function_call" - ], - "title": "FunctionCallResponseItemType", - "type": "string" - } - }, - "required": [ - "arguments", - "call_id", - "name", - "type" - ], - "title": "FunctionCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "$ref": "#/definitions/FunctionCallOutputPayload" - }, - "type": { - "enum": [ - "function_call_output" - ], - "title": "FunctionCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "FunctionCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "input": { - "type": "string" - }, - "name": { - "type": "string" - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "custom_tool_call" - ], - "title": "CustomToolCallResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "input", - "name", - "type" - ], - "title": "CustomToolCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "type": "string" - }, - "type": { - "enum": [ - "custom_tool_call_output" - ], - "title": "CustomToolCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "CustomToolCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "anyOf": [ - { - "$ref": "#/definitions/WebSearchAction" - }, - { - "type": "null" - } - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "web_search_call" - ], - "title": "WebSearchCallResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "WebSearchCallResponseItem", - "type": "object" - }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, - { - "properties": { - "encrypted_content": { - "type": "string" - }, - "type": { - "enum": [ - "compaction" - ], - "title": "CompactionResponseItemType", - "type": "string" - } - }, - "required": [ - "encrypted_content", - "type" - ], - "title": "CompactionResponseItem", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherResponseItem", - "type": "object" - } - ] - }, - "Result_of_CallToolResult_or_String": { - "oneOf": [ - { - "properties": { - "Ok": { - "$ref": "#/definitions/CallToolResult" - } - }, - "required": [ - "Ok" - ], - "title": "OkResult_of_CallToolResult_or_String", - "type": "object" - }, - { - "properties": { - "Err": { - "type": "string" - } - }, - "required": [ - "Err" - ], - "title": "ErrResult_of_CallToolResult_or_String", - "type": "object" - } - ] - }, - "ReviewCodeLocation": { - "description": "Location of the code related to a review finding.", - "properties": { - "absolute_file_path": { - "type": "string" - }, - "line_range": { - "$ref": "#/definitions/ReviewLineRange" - } - }, - "required": [ - "absolute_file_path", - "line_range" - ], - "type": "object" - }, - "ReviewFinding": { - "description": "A single review finding describing an observed issue or recommendation.", - "properties": { - "body": { - "type": "string" - }, - "code_location": { - "$ref": "#/definitions/ReviewCodeLocation" - }, - "confidence_score": { - "format": "float", - "type": "number" - }, - "priority": { - "format": "int32", - "type": "integer" - }, - "title": { - "type": "string" - } - }, - "required": [ - "body", - "code_location", - "confidence_score", - "priority", - "title" - ], - "type": "object" - }, - "ReviewLineRange": { - "description": "Inclusive line range in a file associated with the finding.", - "properties": { - "end": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "ReviewOutputEvent": { - "description": "Structured review result produced by a child review session.", - "properties": { - "findings": { - "items": { - "$ref": "#/definitions/ReviewFinding" - }, - "type": "array" - }, - "overall_confidence_score": { - "format": "float", - "type": "number" - }, - "overall_correctness": { - "type": "string" - }, - "overall_explanation": { - "type": "string" - } - }, - "required": [ - "findings", - "overall_confidence_score", - "overall_correctness", - "overall_explanation" - ], - "type": "object" - }, - "ReviewTarget": { - "oneOf": [ - { - "description": "Review the working tree: staged, unstaged, and untracked files.", - "properties": { - "type": { - "enum": [ - "uncommittedChanges" - ], - "title": "UncommittedChangesReviewTargetType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UncommittedChangesReviewTarget", - "type": "object" - }, - { - "description": "Review changes between the current branch and the given base branch.", - "properties": { - "branch": { - "type": "string" - }, - "type": { - "enum": [ - "baseBranch" - ], - "title": "BaseBranchReviewTargetType", - "type": "string" - } - }, - "required": [ - "branch", - "type" - ], - "title": "BaseBranchReviewTarget", - "type": "object" - }, - { - "description": "Review the changes introduced by a specific commit.", - "properties": { - "sha": { - "type": "string" - }, - "title": { - "description": "Optional human-readable label (e.g., commit subject) for UIs.", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "commit" - ], - "title": "CommitReviewTargetType", - "type": "string" - } - }, - "required": [ - "sha", - "type" - ], - "title": "CommitReviewTarget", - "type": "object" - }, - { - "description": "Arbitrary instructions provided by the user.", - "properties": { - "instructions": { - "type": "string" - }, - "type": { - "enum": [ - "custom" - ], - "title": "CustomReviewTargetType", - "type": "string" - } - }, - "required": [ - "instructions", - "type" - ], - "title": "CustomReviewTarget", - "type": "object" - } - ] - }, - "SandboxPolicy": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicyType", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy", - "type": "object" - } - ] - }, - "SessionNetworkProxyRuntime": { - "properties": { - "admin_addr": { - "type": "string" - }, - "http_addr": { - "type": "string" - }, - "socks_addr": { - "type": "string" - } - }, - "required": [ - "admin_addr", - "http_addr", - "socks_addr" - ], - "type": "object" - }, - "SkillDependencies": { - "properties": { - "tools": { - "items": { - "$ref": "#/definitions/SkillToolDependency" - }, - "type": "array" - } - }, - "required": [ - "tools" - ], - "type": "object" - }, - "SkillErrorInfo": { - "properties": { - "message": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "message", - "path" - ], - "type": "object" - }, - "SkillInterface": { - "properties": { - "brand_color": { - "type": [ - "string", - "null" - ] - }, - "default_prompt": { - "type": [ - "string", - "null" - ] - }, - "display_name": { - "type": [ - "string", - "null" - ] - }, - "icon_large": { - "type": [ - "string", - "null" - ] - }, - "icon_small": { - "type": [ - "string", - "null" - ] - }, - "short_description": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "SkillMetadata": { - "properties": { - "dependencies": { - "anyOf": [ - { - "$ref": "#/definitions/SkillDependencies" - }, - { - "type": "null" - } - ] - }, - "description": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "interface": { - "anyOf": [ - { - "$ref": "#/definitions/SkillInterface" - }, - { - "type": "null" - } - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "scope": { - "$ref": "#/definitions/SkillScope" - }, - "short_description": { - "description": "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "description", - "enabled", - "name", - "path", - "scope" - ], - "type": "object" - }, - "SkillScope": { - "enum": [ - "user", - "repo", - "system", - "admin" - ], - "type": "string" - }, - "SkillToolDependency": { - "properties": { - "command": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "transport": { - "type": [ - "string", - "null" - ] - }, - "type": { - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - }, - "value": { - "type": "string" - } - }, - "required": [ - "type", - "value" - ], - "type": "object" - }, - "SkillsListEntry": { - "properties": { - "cwd": { - "type": "string" - }, - "errors": { - "items": { - "$ref": "#/definitions/SkillErrorInfo" - }, - "type": "array" - }, - "skills": { - "items": { - "$ref": "#/definitions/SkillMetadata" - }, - "type": "array" - } - }, - "required": [ - "cwd", - "errors", - "skills" - ], - "type": "object" - }, - "StepStatus": { - "enum": [ - "pending", - "in_progress", - "completed" - ], - "type": "string" - }, - "TextElement": { - "properties": { - "byte_range": { - "allOf": [ - { - "$ref": "#/definitions/ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byte_range" - ], - "type": "object" - }, - "ThreadId": { - "type": "string" - }, - "TokenUsage": { - "properties": { - "cached_input_tokens": { - "format": "int64", - "type": "integer" - }, - "input_tokens": { - "format": "int64", - "type": "integer" - }, - "output_tokens": { - "format": "int64", - "type": "integer" - }, - "reasoning_output_tokens": { - "format": "int64", - "type": "integer" - }, - "total_tokens": { - "format": "int64", - "type": "integer" - } - }, - "required": [ - "cached_input_tokens", - "input_tokens", - "output_tokens", - "reasoning_output_tokens", - "total_tokens" - ], - "type": "object" - }, - "TokenUsageInfo": { - "properties": { - "last_token_usage": { - "$ref": "#/definitions/TokenUsage" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "total_token_usage": { - "$ref": "#/definitions/TokenUsage" - } - }, - "required": [ - "last_token_usage", - "total_token_usage" - ], - "type": "object" - }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "inputSchema": true, - "name": { - "type": "string" - }, - "outputSchema": true, - "title": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, - "TurnAbortReason": { - "enum": [ - "interrupted", - "replaced", - "review_ended" - ], - "type": "string" - }, - "TurnItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/UserInput" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "type": { - "enum": [ - "UserMessage" - ], - "title": "UserMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "UserMessageTurnItem", - "type": "object" - }, - { - "description": "Assistant-authored message payload used in turn-item streams.\n\n`phase` is optional because not all providers/models emit it. Consumers should use it when present, but retain legacy completion semantics when it is `None`.", - "properties": { - "content": { - "items": { - "$ref": "#/definitions/AgentMessageContent" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "description": "Optional phase metadata carried through from `ResponseItem::Message`.\n\nThis is currently used by TUI rendering to distinguish mid-turn commentary from a final answer and avoid status-indicator jitter." - }, - "type": { - "enum": [ - "AgentMessage" - ], - "title": "AgentMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "AgentMessageTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Plan" - ], - "title": "PlanTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "text", - "type" - ], - "title": "PlanTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "raw_content": { - "default": [], - "items": { - "type": "string" - }, - "type": "array" - }, - "summary_text": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "Reasoning" - ], - "title": "ReasoningTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary_text", - "type" - ], - "title": "ReasoningTurnItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction" - }, - "id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "WebSearch" - ], - "title": "WebSearchTurnItemType", - "type": "string" - } - }, - "required": [ - "action", - "id", - "query", - "type" - ], - "title": "WebSearchTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "type": { - "enum": [ - "ContextCompaction" - ], - "title": "ContextCompactionTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "type" - ], - "title": "ContextCompactionTurnItem", - "type": "object" - } - ] - }, - "UserInput": { - "description": "User input", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` that should be treated as special elements. These are byte ranges into the UTF-8 `text` buffer and are used to render or persist rich input markers (e.g., image placeholders) across history and resume without mutating the literal text.", - "items": { - "$ref": "#/definitions/TextElement" - }, - "type": "array" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextUserInputType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextUserInput", - "type": "object" - }, - { - "description": "Pre‑encoded data: URI image.", - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageUserInputType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "ImageUserInput", - "type": "object" - }, - { - "description": "Local image path provided by the user. This will be converted to an `Image` variant (base64 data URL) during request serialization.", - "properties": { - "path": { - "type": "string" - }, - "type": { - "enum": [ - "local_image" - ], - "title": "LocalImageUserInputType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "LocalImageUserInput", - "type": "object" - }, - { - "description": "Skill selected by the user (name + path to SKILL.md).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "skill" - ], - "title": "SkillUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "SkillUserInput", - "type": "object" - }, - { - "description": "Explicit mention selected by the user (name + app://connector id).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "mention" - ], - "title": "MentionUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "MentionUserInput", - "type": "object" - } - ] - }, - "WebSearchAction": { - "oneOf": [ - { - "properties": { - "queries": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SearchWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "open_page" - ], - "title": "OpenPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "OpenPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "pattern": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "find_in_page" - ], - "title": "FindInPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "FindInPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherWebSearchAction", - "type": "object" - } - ] - } - }, - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "initialMessages": { - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "type": "string" - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "model", - "rolloutPath" - ], - "title": "ForkConversationResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusParams.json b/codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusParams.json deleted file mode 100644 index 0b21fd765d..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusParams.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "includeToken": { - "type": [ - "boolean", - "null" - ] - }, - "refreshToken": { - "type": [ - "boolean", - "null" - ] - } - }, - "title": "GetAuthStatusParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusResponse.json b/codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusResponse.json deleted file mode 100644 index 7a605453d4..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GetAuthStatusResponse.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AuthMode": { - "description": "Authentication mode for OpenAI-backed providers.", - "oneOf": [ - { - "description": "OpenAI API key provided by the caller and stored by Codex.", - "enum": [ - "apikey" - ], - "type": "string" - }, - { - "description": "ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex).", - "enum": [ - "chatgpt" - ], - "type": "string" - }, - { - "description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.\n\nChatGPT auth tokens are supplied by an external host app and are only stored in memory. Token refresh must be handled by the external host app.", - "enum": [ - "chatgptAuthTokens" - ], - "type": "string" - } - ] - } - }, - "properties": { - "authMethod": { - "anyOf": [ - { - "$ref": "#/definitions/AuthMode" - }, - { - "type": "null" - } - ] - }, - "authToken": { - "type": [ - "string", - "null" - ] - }, - "requiresOpenaiAuth": { - "type": [ - "boolean", - "null" - ] - } - }, - "title": "GetAuthStatusResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryParams.json b/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryParams.json deleted file mode 100644 index aa6726cded..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryParams.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "anyOf": [ - { - "properties": { - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "rolloutPath" - ], - "title": "RolloutPathv1::GetConversationSummaryParams", - "type": "object" - }, - { - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "conversationId" - ], - "title": "ConversationIdv1::GetConversationSummaryParams", - "type": "object" - } - ], - "definitions": { - "ThreadId": { - "type": "string" - } - }, - "title": "GetConversationSummaryParams" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json b/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json deleted file mode 100644 index 13cdf0b0f8..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GetConversationSummaryResponse.json +++ /dev/null @@ -1,190 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "ConversationGitInfo": { - "properties": { - "branch": { - "type": [ - "string", - "null" - ] - }, - "origin_url": { - "type": [ - "string", - "null" - ] - }, - "sha": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "ConversationSummary": { - "properties": { - "cliVersion": { - "type": "string" - }, - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "cwd": { - "type": "string" - }, - "gitInfo": { - "anyOf": [ - { - "$ref": "#/definitions/ConversationGitInfo" - }, - { - "type": "null" - } - ] - }, - "modelProvider": { - "type": "string" - }, - "path": { - "type": "string" - }, - "preview": { - "type": "string" - }, - "source": { - "$ref": "#/definitions/SessionSource" - }, - "timestamp": { - "type": [ - "string", - "null" - ] - }, - "updatedAt": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "cliVersion", - "conversationId", - "cwd", - "modelProvider", - "path", - "preview", - "source" - ], - "type": "object" - }, - "SessionSource": { - "oneOf": [ - { - "enum": [ - "cli", - "vscode", - "exec", - "mcp", - "unknown" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "subagent": { - "$ref": "#/definitions/SubAgentSource" - } - }, - "required": [ - "subagent" - ], - "title": "SubagentSessionSource", - "type": "object" - } - ] - }, - "SubAgentSource": { - "oneOf": [ - { - "enum": [ - "review", - "compact", - "memory_consolidation" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "thread_spawn": { - "properties": { - "agent_nickname": { - "default": null, - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "default": null, - "type": [ - "string", - "null" - ] - }, - "depth": { - "format": "int32", - "type": "integer" - }, - "parent_thread_id": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "depth", - "parent_thread_id" - ], - "type": "object" - } - }, - "required": [ - "thread_spawn" - ], - "title": "ThreadSpawnSubAgentSource", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "other": { - "type": "string" - } - }, - "required": [ - "other" - ], - "title": "OtherSubAgentSource", - "type": "object" - } - ] - }, - "ThreadId": { - "type": "string" - } - }, - "properties": { - "summary": { - "$ref": "#/definitions/ConversationSummary" - } - }, - "required": [ - "summary" - ], - "title": "GetConversationSummaryResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GetUserAgentResponse.json b/codex-rs/app-server-protocol/schema/json/v1/GetUserAgentResponse.json deleted file mode 100644 index c041282c8f..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GetUserAgentResponse.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "userAgent": { - "type": "string" - } - }, - "required": [ - "userAgent" - ], - "title": "GetUserAgentResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GetUserSavedConfigResponse.json b/codex-rs/app-server-protocol/schema/json/v1/GetUserSavedConfigResponse.json deleted file mode 100644 index 2f6d8b3b5f..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GetUserSavedConfigResponse.json +++ /dev/null @@ -1,366 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "ForcedLoginMethod": { - "enum": [ - "chatgpt", - "api" - ], - "type": "string" - }, - "Profile": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "chatgptBaseUrl": { - "type": [ - "string", - "null" - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelProvider": { - "type": [ - "string", - "null" - ] - }, - "modelReasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "modelReasoningSummary": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningSummary" - }, - { - "type": "null" - } - ] - }, - "modelVerbosity": { - "anyOf": [ - { - "$ref": "#/definitions/Verbosity" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ReasoningSummary": { - "description": "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", - "oneOf": [ - { - "enum": [ - "auto", - "concise", - "detailed" - ], - "type": "string" - }, - { - "description": "Option to disable reasoning summaries.", - "enum": [ - "none" - ], - "type": "string" - } - ] - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "SandboxMode": { - "enum": [ - "read-only", - "workspace-write", - "danger-full-access" - ], - "type": "string" - }, - "SandboxSettings": { - "properties": { - "excludeSlashTmp": { - "type": [ - "boolean", - "null" - ] - }, - "excludeTmpdirEnvVar": { - "type": [ - "boolean", - "null" - ] - }, - "networkAccess": { - "type": [ - "boolean", - "null" - ] - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "type": "object" - }, - "Tools": { - "properties": { - "viewImage": { - "type": [ - "boolean", - "null" - ] - }, - "webSearch": { - "type": [ - "boolean", - "null" - ] - } - }, - "type": "object" - }, - "UserSavedConfig": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "forcedChatgptWorkspaceId": { - "type": [ - "string", - "null" - ] - }, - "forcedLoginMethod": { - "anyOf": [ - { - "$ref": "#/definitions/ForcedLoginMethod" - }, - { - "type": "null" - } - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelReasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "modelReasoningSummary": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningSummary" - }, - { - "type": "null" - } - ] - }, - "modelVerbosity": { - "anyOf": [ - { - "$ref": "#/definitions/Verbosity" - }, - { - "type": "null" - } - ] - }, - "profile": { - "type": [ - "string", - "null" - ] - }, - "profiles": { - "additionalProperties": { - "$ref": "#/definitions/Profile" - }, - "type": "object" - }, - "sandboxMode": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxMode" - }, - { - "type": "null" - } - ] - }, - "sandboxSettings": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxSettings" - }, - { - "type": "null" - } - ] - }, - "tools": { - "anyOf": [ - { - "$ref": "#/definitions/Tools" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "profiles" - ], - "type": "object" - }, - "Verbosity": { - "description": "Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.", - "enum": [ - "low", - "medium", - "high" - ], - "type": "string" - } - }, - "properties": { - "config": { - "$ref": "#/definitions/UserSavedConfig" - } - }, - "required": [ - "config" - ], - "title": "GetUserSavedConfigResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteParams.json b/codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteParams.json deleted file mode 100644 index 51640965ca..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteParams.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "cwd": { - "type": "string" - } - }, - "required": [ - "cwd" - ], - "title": "GitDiffToRemoteParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteResponse.json b/codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteResponse.json deleted file mode 100644 index fd59b80e94..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/GitDiffToRemoteResponse.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "GitSha": { - "type": "string" - } - }, - "properties": { - "diff": { - "type": "string" - }, - "sha": { - "$ref": "#/definitions/GitSha" - } - }, - "required": [ - "diff", - "sha" - ], - "title": "GitDiffToRemoteResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/InterruptConversationParams.json b/codex-rs/app-server-protocol/schema/json/v1/InterruptConversationParams.json deleted file mode 100644 index 4fdd221fca..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/InterruptConversationParams.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "ThreadId": { - "type": "string" - } - }, - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "conversationId" - ], - "title": "InterruptConversationParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/InterruptConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/InterruptConversationResponse.json deleted file mode 100644 index 5d2ddf3e40..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/InterruptConversationResponse.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "TurnAbortReason": { - "enum": [ - "interrupted", - "replaced", - "review_ended" - ], - "type": "string" - } - }, - "properties": { - "abortReason": { - "$ref": "#/definitions/TurnAbortReason" - } - }, - "required": [ - "abortReason" - ], - "title": "InterruptConversationResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ListConversationsParams.json b/codex-rs/app-server-protocol/schema/json/v1/ListConversationsParams.json deleted file mode 100644 index 9ac05602c4..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ListConversationsParams.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "cursor": { - "type": [ - "string", - "null" - ] - }, - "modelProviders": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "pageSize": { - "format": "uint", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "title": "ListConversationsParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json deleted file mode 100644 index 2e3ab7e0dc..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ListConversationsResponse.json +++ /dev/null @@ -1,199 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "ConversationGitInfo": { - "properties": { - "branch": { - "type": [ - "string", - "null" - ] - }, - "origin_url": { - "type": [ - "string", - "null" - ] - }, - "sha": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "ConversationSummary": { - "properties": { - "cliVersion": { - "type": "string" - }, - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "cwd": { - "type": "string" - }, - "gitInfo": { - "anyOf": [ - { - "$ref": "#/definitions/ConversationGitInfo" - }, - { - "type": "null" - } - ] - }, - "modelProvider": { - "type": "string" - }, - "path": { - "type": "string" - }, - "preview": { - "type": "string" - }, - "source": { - "$ref": "#/definitions/SessionSource" - }, - "timestamp": { - "type": [ - "string", - "null" - ] - }, - "updatedAt": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "cliVersion", - "conversationId", - "cwd", - "modelProvider", - "path", - "preview", - "source" - ], - "type": "object" - }, - "SessionSource": { - "oneOf": [ - { - "enum": [ - "cli", - "vscode", - "exec", - "mcp", - "unknown" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "subagent": { - "$ref": "#/definitions/SubAgentSource" - } - }, - "required": [ - "subagent" - ], - "title": "SubagentSessionSource", - "type": "object" - } - ] - }, - "SubAgentSource": { - "oneOf": [ - { - "enum": [ - "review", - "compact", - "memory_consolidation" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "thread_spawn": { - "properties": { - "agent_nickname": { - "default": null, - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "default": null, - "type": [ - "string", - "null" - ] - }, - "depth": { - "format": "int32", - "type": "integer" - }, - "parent_thread_id": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "depth", - "parent_thread_id" - ], - "type": "object" - } - }, - "required": [ - "thread_spawn" - ], - "title": "ThreadSpawnSubAgentSource", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "other": { - "type": "string" - } - }, - "required": [ - "other" - ], - "title": "OtherSubAgentSource", - "type": "object" - } - ] - }, - "ThreadId": { - "type": "string" - } - }, - "properties": { - "items": { - "items": { - "$ref": "#/definitions/ConversationSummary" - }, - "type": "array" - }, - "nextCursor": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "items" - ], - "title": "ListConversationsResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyParams.json b/codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyParams.json deleted file mode 100644 index b23ce5548f..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyParams.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "apiKey": { - "type": "string" - } - }, - "required": [ - "apiKey" - ], - "title": "LoginApiKeyParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyResponse.json b/codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyResponse.json deleted file mode 100644 index cba1fe3c40..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/LoginApiKeyResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "LoginApiKeyResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/LoginChatGptCompleteNotification.json b/codex-rs/app-server-protocol/schema/json/v1/LoginChatGptCompleteNotification.json deleted file mode 100644 index ae34de2f42..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/LoginChatGptCompleteNotification.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "description": "Deprecated in favor of AccountLoginCompletedNotification.", - "properties": { - "error": { - "type": [ - "string", - "null" - ] - }, - "loginId": { - "type": "string" - }, - "success": { - "type": "boolean" - } - }, - "required": [ - "loginId", - "success" - ], - "title": "LoginChatGptCompleteNotification", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/LoginChatGptResponse.json b/codex-rs/app-server-protocol/schema/json/v1/LoginChatGptResponse.json deleted file mode 100644 index 9ecf3cdbb9..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/LoginChatGptResponse.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "authUrl": { - "type": "string" - }, - "loginId": { - "type": "string" - } - }, - "required": [ - "authUrl", - "loginId" - ], - "title": "LoginChatGptResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/LogoutChatGptResponse.json b/codex-rs/app-server-protocol/schema/json/v1/LogoutChatGptResponse.json deleted file mode 100644 index 449cfc5fab..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/LogoutChatGptResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "LogoutChatGptResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/NewConversationParams.json b/codex-rs/app-server-protocol/schema/json/v1/NewConversationParams.json deleted file mode 100644 index c9c8caaa26..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/NewConversationParams.json +++ /dev/null @@ -1,161 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "SandboxMode": { - "enum": [ - "read-only", - "workspace-write", - "danger-full-access" - ], - "type": "string" - } - }, - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "baseInstructions": { - "type": [ - "string", - "null" - ] - }, - "compactPrompt": { - "type": [ - "string", - "null" - ] - }, - "config": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "developerInstructions": { - "type": [ - "string", - "null" - ] - }, - "includeApplyPatchTool": { - "type": [ - "boolean", - "null" - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelProvider": { - "type": [ - "string", - "null" - ] - }, - "profile": { - "type": [ - "string", - "null" - ] - }, - "sandbox": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxMode" - }, - { - "type": "null" - } - ] - } - }, - "title": "NewConversationParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/NewConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/NewConversationResponse.json deleted file mode 100644 index 8030d8113f..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/NewConversationResponse.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ThreadId": { - "type": "string" - } - }, - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "model": { - "type": "string" - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "model", - "rolloutPath" - ], - "title": "NewConversationResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/RemoveConversationListenerParams.json b/codex-rs/app-server-protocol/schema/json/v1/RemoveConversationListenerParams.json deleted file mode 100644 index 990b8ff0c4..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/RemoveConversationListenerParams.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "subscriptionId": { - "type": "string" - } - }, - "required": [ - "subscriptionId" - ], - "title": "RemoveConversationListenerParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/RemoveConversationSubscriptionResponse.json b/codex-rs/app-server-protocol/schema/json/v1/RemoveConversationSubscriptionResponse.json deleted file mode 100644 index 8efe40d430..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/RemoveConversationSubscriptionResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "RemoveConversationSubscriptionResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationParams.json b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationParams.json deleted file mode 100644 index a45e1e60ee..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationParams.json +++ /dev/null @@ -1,984 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "ContentItem": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageContentItem", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "output_text" - ], - "title": "OutputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "OutputTextContentItem", - "type": "object" - } - ] - }, - "FunctionCallOutputBody": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "$ref": "#/definitions/FunctionCallOutputContentItem" - }, - "type": "array" - } - ] - }, - "FunctionCallOutputContentItem": { - "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextFunctionCallOutputContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageFunctionCallOutputContentItem", - "type": "object" - } - ] - }, - "FunctionCallOutputPayload": { - "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", - "properties": { - "body": { - "$ref": "#/definitions/FunctionCallOutputBody" - }, - "success": { - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "body" - ], - "type": "object" - }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, - "LocalShellAction": { - "oneOf": [ - { - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "timeout_ms": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - }, - "type": { - "enum": [ - "exec" - ], - "title": "ExecLocalShellActionType", - "type": "string" - }, - "user": { - "type": [ - "string", - "null" - ] - }, - "working_directory": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "command", - "type" - ], - "title": "ExecLocalShellAction", - "type": "object" - } - ] - }, - "LocalShellStatus": { - "enum": [ - "completed", - "in_progress", - "incomplete" - ], - "type": "string" - }, - "MessagePhase": { - "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", - "oneOf": [ - { - "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", - "enum": [ - "commentary" - ], - "type": "string" - }, - { - "description": "The assistant's terminal answer text for the current turn.", - "enum": [ - "final_answer" - ], - "type": "string" - } - ] - }, - "NewConversationParams": { - "properties": { - "approvalPolicy": { - "anyOf": [ - { - "$ref": "#/definitions/AskForApproval" - }, - { - "type": "null" - } - ] - }, - "baseInstructions": { - "type": [ - "string", - "null" - ] - }, - "compactPrompt": { - "type": [ - "string", - "null" - ] - }, - "config": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - }, - "cwd": { - "type": [ - "string", - "null" - ] - }, - "developerInstructions": { - "type": [ - "string", - "null" - ] - }, - "includeApplyPatchTool": { - "type": [ - "boolean", - "null" - ] - }, - "model": { - "type": [ - "string", - "null" - ] - }, - "modelProvider": { - "type": [ - "string", - "null" - ] - }, - "profile": { - "type": [ - "string", - "null" - ] - }, - "sandbox": { - "anyOf": [ - { - "$ref": "#/definitions/SandboxMode" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "ReasoningItemContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_text" - ], - "title": "ReasoningTextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "ReasoningTextReasoningItemContent", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextReasoningItemContent", - "type": "object" - } - ] - }, - "ReasoningItemReasoningSummary": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "summary_text" - ], - "title": "SummaryTextReasoningItemReasoningSummaryType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "SummaryTextReasoningItemReasoningSummary", - "type": "object" - } - ] - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "ResponseItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/ContentItem" - }, - "type": "array" - }, - "end_turn": { - "type": [ - "boolean", - "null" - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ] - }, - "role": { - "type": "string" - }, - "type": { - "enum": [ - "message" - ], - "title": "MessageResponseItemType", - "type": "string" - } - }, - "required": [ - "content", - "role", - "type" - ], - "title": "MessageResponseItem", - "type": "object" - }, - { - "properties": { - "content": { - "default": null, - "items": { - "$ref": "#/definitions/ReasoningItemContent" - }, - "type": [ - "array", - "null" - ] - }, - "encrypted_content": { - "type": [ - "string", - "null" - ] - }, - "id": { - "type": "string", - "writeOnly": true - }, - "summary": { - "items": { - "$ref": "#/definitions/ReasoningItemReasoningSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "reasoning" - ], - "title": "ReasoningResponseItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary", - "type" - ], - "title": "ReasoningResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/LocalShellAction" - }, - "call_id": { - "description": "Set when using the Responses API.", - "type": [ - "string", - "null" - ] - }, - "id": { - "description": "Legacy id field retained for compatibility with older payloads.", - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "$ref": "#/definitions/LocalShellStatus" - }, - "type": { - "enum": [ - "local_shell_call" - ], - "title": "LocalShellCallResponseItemType", - "type": "string" - } - }, - "required": [ - "action", - "status", - "type" - ], - "title": "LocalShellCallResponseItem", - "type": "object" - }, - { - "properties": { - "arguments": { - "type": "string" - }, - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "name": { - "type": "string" - }, - "type": { - "enum": [ - "function_call" - ], - "title": "FunctionCallResponseItemType", - "type": "string" - } - }, - "required": [ - "arguments", - "call_id", - "name", - "type" - ], - "title": "FunctionCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "$ref": "#/definitions/FunctionCallOutputPayload" - }, - "type": { - "enum": [ - "function_call_output" - ], - "title": "FunctionCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "FunctionCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "input": { - "type": "string" - }, - "name": { - "type": "string" - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "custom_tool_call" - ], - "title": "CustomToolCallResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "input", - "name", - "type" - ], - "title": "CustomToolCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "type": "string" - }, - "type": { - "enum": [ - "custom_tool_call_output" - ], - "title": "CustomToolCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "CustomToolCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "anyOf": [ - { - "$ref": "#/definitions/WebSearchAction" - }, - { - "type": "null" - } - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "web_search_call" - ], - "title": "WebSearchCallResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "WebSearchCallResponseItem", - "type": "object" - }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, - { - "properties": { - "encrypted_content": { - "type": "string" - }, - "type": { - "enum": [ - "compaction" - ], - "title": "CompactionResponseItemType", - "type": "string" - } - }, - "required": [ - "encrypted_content", - "type" - ], - "title": "CompactionResponseItem", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherResponseItem", - "type": "object" - } - ] - }, - "SandboxMode": { - "enum": [ - "read-only", - "workspace-write", - "danger-full-access" - ], - "type": "string" - }, - "ThreadId": { - "type": "string" - }, - "WebSearchAction": { - "oneOf": [ - { - "properties": { - "queries": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SearchWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "open_page" - ], - "title": "OpenPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "OpenPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "pattern": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "find_in_page" - ], - "title": "FindInPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "FindInPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherWebSearchAction", - "type": "object" - } - ] - } - }, - "properties": { - "conversationId": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "history": { - "items": { - "$ref": "#/definitions/ResponseItem" - }, - "type": [ - "array", - "null" - ] - }, - "overrides": { - "anyOf": [ - { - "$ref": "#/definitions/NewConversationParams" - }, - { - "type": "null" - } - ] - }, - "path": { - "type": [ - "string", - "null" - ] - } - }, - "title": "ResumeConversationParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json deleted file mode 100644 index 3ce7593460..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json +++ /dev/null @@ -1,5776 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, - "AgentMessageContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Text" - ], - "title": "TextAgentMessageContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextAgentMessageContent", - "type": "object" - } - ] - }, - "AgentStatus": { - "description": "Agent lifecycle status, derived from emitted events.", - "oneOf": [ - { - "description": "Agent is waiting for initialization.", - "enum": [ - "pending_init" - ], - "type": "string" - }, - { - "description": "Agent is currently running.", - "enum": [ - "running" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Agent is done. Contains the final assistant message.", - "properties": { - "completed": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "completed" - ], - "title": "CompletedAgentStatus", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Agent encountered an error.", - "properties": { - "errored": { - "type": "string" - } - }, - "required": [ - "errored" - ], - "title": "ErroredAgentStatus", - "type": "object" - }, - { - "description": "Agent has been shutdown.", - "enum": [ - "shutdown" - ], - "type": "string" - }, - { - "description": "Agent is not found.", - "enum": [ - "not_found" - ], - "type": "string" - } - ] - }, - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "CallToolResult": { - "description": "The server's response to a tool call.", - "properties": { - "_meta": true, - "content": { - "items": true, - "type": "array" - }, - "isError": { - "type": [ - "boolean", - "null" - ] - }, - "structuredContent": true - }, - "required": [ - "content" - ], - "type": "object" - }, - "CodexErrorInfo": { - "description": "Codex errors that we expose to clients.", - "oneOf": [ - { - "enum": [ - "context_window_exceeded", - "usage_limit_exceeded", - "server_overloaded", - "internal_server_error", - "unauthorized", - "bad_request", - "sandbox_error", - "thread_rollback_failed", - "other" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "http_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "http_connection_failed" - ], - "title": "HttpConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Failed to connect to the response SSE stream.", - "properties": { - "response_stream_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_connection_failed" - ], - "title": "ResponseStreamConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "The response SSE stream disconnected in the middle of a turnbefore completion.", - "properties": { - "response_stream_disconnected": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_disconnected" - ], - "title": "ResponseStreamDisconnectedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Reached the retry limit for responses.", - "properties": { - "response_too_many_failed_attempts": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_too_many_failed_attempts" - ], - "title": "ResponseTooManyFailedAttemptsCodexErrorInfo", - "type": "object" - } - ] - }, - "CollabAgentRef": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "thread_id" - ], - "type": "object" - }, - "CollabAgentStatusEntry": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the agent." - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "status", - "thread_id" - ], - "type": "object" - }, - "ContentItem": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageContentItem", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "output_text" - ], - "title": "OutputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "OutputTextContentItem", - "type": "object" - } - ] - }, - "CreditsSnapshot": { - "properties": { - "balance": { - "type": [ - "string", - "null" - ] - }, - "has_credits": { - "type": "boolean" - }, - "unlimited": { - "type": "boolean" - } - }, - "required": [ - "has_credits", - "unlimited" - ], - "type": "object" - }, - "CustomPrompt": { - "properties": { - "argument_hint": { - "type": [ - "string", - "null" - ] - }, - "content": { - "type": "string" - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "content", - "name", - "path" - ], - "type": "object" - }, - "Duration": { - "properties": { - "nanos": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "secs": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "nanos", - "secs" - ], - "type": "object" - }, - "EventMsg": { - "description": "Response event from the agent NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.", - "oneOf": [ - { - "description": "Error while executing a submission", - "properties": { - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "error" - ], - "title": "ErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "ErrorEventMsg", - "type": "object" - }, - { - "description": "Warning issued while processing a submission. Unlike `Error`, this indicates the turn continued but the user should still be notified.", - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "warning" - ], - "title": "WarningEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "WarningEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle start event.", - "properties": { - "session_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_started" - ], - "title": "RealtimeConversationStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationStartedEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation streaming payload event.", - "properties": { - "payload": { - "$ref": "#/definitions/RealtimeEvent" - }, - "type": { - "enum": [ - "realtime_conversation_realtime" - ], - "title": "RealtimeConversationRealtimeEventMsgType", - "type": "string" - } - }, - "required": [ - "payload", - "type" - ], - "title": "RealtimeConversationRealtimeEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle close event.", - "properties": { - "reason": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_closed" - ], - "title": "RealtimeConversationClosedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationClosedEventMsg", - "type": "object" - }, - { - "description": "Model routing changed from the requested model to a different model.", - "properties": { - "from_model": { - "type": "string" - }, - "reason": { - "$ref": "#/definitions/ModelRerouteReason" - }, - "to_model": { - "type": "string" - }, - "type": { - "enum": [ - "model_reroute" - ], - "title": "ModelRerouteEventMsgType", - "type": "string" - } - }, - "required": [ - "from_model", - "reason", - "to_model", - "type" - ], - "title": "ModelRerouteEventMsg", - "type": "object" - }, - { - "description": "Conversation history was compacted (either automatically or manually).", - "properties": { - "type": { - "enum": [ - "context_compacted" - ], - "title": "ContextCompactedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ContextCompactedEventMsg", - "type": "object" - }, - { - "description": "Conversation history was rolled back by dropping the last N user turns.", - "properties": { - "num_turns": { - "description": "Number of user turns that were removed from context.", - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "thread_rolled_back" - ], - "title": "ThreadRolledBackEventMsgType", - "type": "string" - } - }, - "required": [ - "num_turns", - "type" - ], - "title": "ThreadRolledBackEventMsg", - "type": "object" - }, - { - "description": "Agent has started a turn. v1 wire format uses `task_started`; accept `turn_started` for v2 interop.", - "properties": { - "collaboration_mode_kind": { - "allOf": [ - { - "$ref": "#/definitions/ModeKind" - } - ], - "default": "default" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_started" - ], - "title": "TaskStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskStartedEventMsg", - "type": "object" - }, - { - "description": "Agent has completed all actions. v1 wire format uses `task_complete`; accept `turn_complete` for v2 interop.", - "properties": { - "last_agent_message": { - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_complete" - ], - "title": "TaskCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskCompleteEventMsg", - "type": "object" - }, - { - "description": "Usage update for the current session, including totals and last turn. Optional means unknown — UIs should not display when `None`.", - "properties": { - "info": { - "anyOf": [ - { - "$ref": "#/definitions/TokenUsageInfo" - }, - { - "type": "null" - } - ] - }, - "rate_limits": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitSnapshot" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "token_count" - ], - "title": "TokenCountEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "TokenCountEventMsg", - "type": "object" - }, - { - "description": "Agent text output message", - "properties": { - "message": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "default": null - }, - "type": { - "enum": [ - "agent_message" - ], - "title": "AgentMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "AgentMessageEventMsg", - "type": "object" - }, - { - "description": "User/system input message (what was sent to the model)", - "properties": { - "images": { - "description": "Image URLs sourced from `UserInput::Image`. These are safe to replay in legacy UI history events and correspond to images sent to the model.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "local_images": { - "default": [], - "description": "Local file paths sourced from `UserInput::LocalImage`. These are kept so the UI can reattach images when editing history, and should not be sent to the model or treated as API-ready URLs.", - "items": { - "type": "string" - }, - "type": "array" - }, - "message": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `message` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/TextElement" - }, - "type": "array" - }, - "type": { - "enum": [ - "user_message" - ], - "title": "UserMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "UserMessageEventMsg", - "type": "object" - }, - { - "description": "Agent text output delta message", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_delta" - ], - "title": "AgentMessageDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentMessageDeltaEventMsg", - "type": "object" - }, - { - "description": "Reasoning event from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning" - ], - "title": "AgentReasoningEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_delta" - ], - "title": "AgentReasoningDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningDeltaEventMsg", - "type": "object" - }, - { - "description": "Raw chain-of-thought from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content" - ], - "title": "AgentReasoningRawContentEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningRawContentEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning content delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content_delta" - ], - "title": "AgentReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Signaled when the model begins a new reasoning summary section (e.g., a new titled block).", - "properties": { - "item_id": { - "default": "", - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "type": { - "enum": [ - "agent_reasoning_section_break" - ], - "title": "AgentReasoningSectionBreakEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "AgentReasoningSectionBreakEventMsg", - "type": "object" - }, - { - "description": "Ack the client's configure message.", - "properties": { - "approval_policy": { - "allOf": [ - { - "$ref": "#/definitions/AskForApproval" - } - ], - "description": "When to escalate for approval for execution" - }, - "cwd": { - "description": "Working directory that should be treated as the *root* of the session.", - "type": "string" - }, - "forked_from_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "history_entry_count": { - "description": "Current number of entries in the history log.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "history_log_id": { - "description": "Identifier of the history log file (inode on Unix, 0 otherwise).", - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "initial_messages": { - "description": "Optional initial messages (as events) for resumed sessions. When present, UIs can use these to seed the history.", - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "description": "Tell the client what model is being queried.", - "type": "string" - }, - "model_provider_id": { - "type": "string" - }, - "network_proxy": { - "anyOf": [ - { - "$ref": "#/definitions/SessionNetworkProxyRuntime" - }, - { - "type": "null" - } - ], - "description": "Runtime proxy bind addresses, when the managed proxy was started for this session." - }, - "reasoning_effort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ], - "description": "The effort the model is putting into reasoning about the user's request." - }, - "rollout_path": { - "description": "Path in which the rollout is stored. Can be `None` for ephemeral threads", - "type": [ - "string", - "null" - ] - }, - "sandbox_policy": { - "allOf": [ - { - "$ref": "#/definitions/SandboxPolicy" - } - ], - "description": "How to sandbox commands executed in the system" - }, - "session_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "description": "Optional user-facing thread name (may be unset).", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "session_configured" - ], - "title": "SessionConfiguredEventMsgType", - "type": "string" - } - }, - "required": [ - "approval_policy", - "cwd", - "history_entry_count", - "history_log_id", - "model", - "model_provider_id", - "sandbox_policy", - "session_id", - "type" - ], - "title": "SessionConfiguredEventMsg", - "type": "object" - }, - { - "description": "Updated session metadata (e.g., thread name changes).", - "properties": { - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "thread_name_updated" - ], - "title": "ThreadNameUpdatedEventMsgType", - "type": "string" - } - }, - "required": [ - "thread_id", - "type" - ], - "title": "ThreadNameUpdatedEventMsg", - "type": "object" - }, - { - "description": "Incremental MCP startup progress updates.", - "properties": { - "server": { - "description": "Server name being started.", - "type": "string" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/McpStartupStatus" - } - ], - "description": "Current startup status." - }, - "type": { - "enum": [ - "mcp_startup_update" - ], - "title": "McpStartupUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "server", - "status", - "type" - ], - "title": "McpStartupUpdateEventMsg", - "type": "object" - }, - { - "description": "Aggregate MCP startup completion summary.", - "properties": { - "cancelled": { - "items": { - "type": "string" - }, - "type": "array" - }, - "failed": { - "items": { - "$ref": "#/definitions/McpStartupFailure" - }, - "type": "array" - }, - "ready": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "mcp_startup_complete" - ], - "title": "McpStartupCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "cancelled", - "failed", - "ready", - "type" - ], - "title": "McpStartupCompleteEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the McpToolCallEnd event.", - "type": "string" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "type": { - "enum": [ - "mcp_tool_call_begin" - ], - "title": "McpToolCallBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "invocation", - "type" - ], - "title": "McpToolCallBeginEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier for the corresponding McpToolCallBegin that finished.", - "type": "string" - }, - "duration": { - "$ref": "#/definitions/Duration" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "result": { - "allOf": [ - { - "$ref": "#/definitions/Result_of_CallToolResult_or_String" - } - ], - "description": "Result of the tool call. Note this could be an error." - }, - "type": { - "enum": [ - "mcp_tool_call_end" - ], - "title": "McpToolCallEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "duration", - "invocation", - "result", - "type" - ], - "title": "McpToolCallEndEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_begin" - ], - "title": "WebSearchBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "type" - ], - "title": "WebSearchBeginEventMsg", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction" - }, - "call_id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_end" - ], - "title": "WebSearchEndEventMsgType", - "type": "string" - } - }, - "required": [ - "action", - "call_id", - "query", - "type" - ], - "title": "WebSearchEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the server is about to execute a command.", - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the ExecCommandEnd event.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_begin" - ], - "title": "ExecCommandBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "turn_id", - "type" - ], - "title": "ExecCommandBeginEventMsg", - "type": "object" - }, - { - "description": "Incremental chunk of output from a running command.", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "chunk": { - "description": "Raw bytes from the stream (may not be valid UTF-8).", - "type": "string" - }, - "stream": { - "allOf": [ - { - "$ref": "#/definitions/ExecOutputStream" - } - ], - "description": "Which stream produced this chunk." - }, - "type": { - "enum": [ - "exec_command_output_delta" - ], - "title": "ExecCommandOutputDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "chunk", - "stream", - "type" - ], - "title": "ExecCommandOutputDeltaEventMsg", - "type": "object" - }, - { - "description": "Terminal interaction for an in-progress command (stdin sent and stdout observed).", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "process_id": { - "description": "Process id associated with the running command.", - "type": "string" - }, - "stdin": { - "description": "Stdin sent to the running session.", - "type": "string" - }, - "type": { - "enum": [ - "terminal_interaction" - ], - "title": "TerminalInteractionEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "process_id", - "stdin", - "type" - ], - "title": "TerminalInteractionEventMsg", - "type": "object" - }, - { - "properties": { - "aggregated_output": { - "default": "", - "description": "Captured aggregated output", - "type": "string" - }, - "call_id": { - "description": "Identifier for the ExecCommandBegin that finished.", - "type": "string" - }, - "command": { - "description": "The command that was executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "duration": { - "allOf": [ - { - "$ref": "#/definitions/Duration" - } - ], - "description": "The duration of the command execution." - }, - "exit_code": { - "description": "The command's exit code.", - "format": "int32", - "type": "integer" - }, - "formatted_output": { - "description": "Formatted output from the command, as seen by the model.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandStatus" - } - ], - "description": "Completion status for this command execution." - }, - "stderr": { - "description": "Captured stderr", - "type": "string" - }, - "stdout": { - "description": "Captured stdout", - "type": "string" - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_end" - ], - "title": "ExecCommandEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "duration", - "exit_code", - "formatted_output", - "parsed_cmd", - "status", - "stderr", - "stdout", - "turn_id", - "type" - ], - "title": "ExecCommandEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent attached a local image via the view_image tool.", - "properties": { - "call_id": { - "description": "Identifier for the originating tool call.", - "type": "string" - }, - "path": { - "description": "Local filesystem path provided to the tool.", - "type": "string" - }, - "type": { - "enum": [ - "view_image_tool_call" - ], - "title": "ViewImageToolCallEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "path", - "type" - ], - "title": "ViewImageToolCallEventMsg", - "type": "object" - }, - { - "properties": { - "approval_id": { - "description": "Identifier for this specific approval callback.\n\nWhen absent, the approval is for the command item itself (`call_id`). This is present for subcommand approvals (via execve intercept).", - "type": [ - "string", - "null" - ] - }, - "call_id": { - "description": "Identifier for the associated command execution item.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory.", - "type": "string" - }, - "network_approval_context": { - "anyOf": [ - { - "$ref": "#/definitions/NetworkApprovalContext" - }, - { - "type": "null" - } - ], - "description": "Optional network context for a blocked request that can be approved." - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "proposed_execpolicy_amendment": { - "description": "Proposed execpolicy amendment that can be applied to allow future runs.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "reason": { - "description": "Optional human-readable reason for the approval (e.g. retry without sandbox).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this command belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "exec_approval_request" - ], - "title": "ExecApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "type" - ], - "title": "ExecApprovalRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated tool call, if available.", - "type": "string" - }, - "questions": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestion" - }, - "type": "array" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this request belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "request_user_input" - ], - "title": "RequestUserInputEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "questions", - "type" - ], - "title": "RequestUserInputEventMsg", - "type": "object" - }, - { - "properties": { - "arguments": true, - "callId": { - "type": "string" - }, - "tool": { - "type": "string" - }, - "turnId": { - "type": "string" - }, - "type": { - "enum": [ - "dynamic_tool_call_request" - ], - "title": "DynamicToolCallRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "arguments", - "callId", - "tool", - "turnId", - "type" - ], - "title": "DynamicToolCallRequestEventMsg", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "message": { - "type": "string" - }, - "server_name": { - "type": "string" - }, - "type": { - "enum": [ - "elicitation_request" - ], - "title": "ElicitationRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "message", - "server_name", - "type" - ], - "title": "ElicitationRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated patch apply call, if available.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "type": "object" - }, - "grant_root": { - "description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session.", - "type": [ - "string", - "null" - ] - }, - "reason": { - "description": "Optional explanatory reason (e.g. request for extra write access).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility with older senders.", - "type": "string" - }, - "type": { - "enum": [ - "apply_patch_approval_request" - ], - "title": "ApplyPatchApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "changes", - "type" - ], - "title": "ApplyPatchApprovalRequestEventMsg", - "type": "object" - }, - { - "description": "Notification advising the user that something they are using has been deprecated and should be phased out.", - "properties": { - "details": { - "description": "Optional extra guidance, such as migration steps or rationale.", - "type": [ - "string", - "null" - ] - }, - "summary": { - "description": "Concise summary of what is deprecated.", - "type": "string" - }, - "type": { - "enum": [ - "deprecation_notice" - ], - "title": "DeprecationNoticeEventMsgType", - "type": "string" - } - }, - "required": [ - "summary", - "type" - ], - "title": "DeprecationNoticeEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "background_event" - ], - "title": "BackgroundEventEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "BackgroundEventEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "undo_started" - ], - "title": "UndoStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UndoStartedEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "success": { - "type": "boolean" - }, - "type": { - "enum": [ - "undo_completed" - ], - "title": "UndoCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "success", - "type" - ], - "title": "UndoCompletedEventMsg", - "type": "object" - }, - { - "description": "Notification that a model stream experienced an error or disconnect and the system is handling it (e.g., retrying with backoff).", - "properties": { - "additional_details": { - "default": null, - "description": "Optional details about the underlying stream failure (often the same human-readable message that is surfaced as the terminal error if retries are exhausted).", - "type": [ - "string", - "null" - ] - }, - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "stream_error" - ], - "title": "StreamErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "StreamErrorEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is about to apply a code patch. Mirrors `ExecCommandBegin` so front‑ends can show progress indicators.", - "properties": { - "auto_approved": { - "description": "If true, there was no ApplyPatchApprovalRequest for this patch.", - "type": "boolean" - }, - "call_id": { - "description": "Identifier so this can be paired with the PatchApplyEnd event.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "description": "The changes to be applied.", - "type": "object" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_begin" - ], - "title": "PatchApplyBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "auto_approved", - "call_id", - "changes", - "type" - ], - "title": "PatchApplyBeginEventMsg", - "type": "object" - }, - { - "description": "Notification that a patch application has finished.", - "properties": { - "call_id": { - "description": "Identifier for the PatchApplyBegin that finished.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "default": {}, - "description": "The changes that were applied (mirrors PatchApplyBeginEvent::changes).", - "type": "object" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/PatchApplyStatus" - } - ], - "description": "Completion status for this patch application." - }, - "stderr": { - "description": "Captured stderr (parser errors, IO failures, etc.).", - "type": "string" - }, - "stdout": { - "description": "Captured stdout (summary printed by apply_patch).", - "type": "string" - }, - "success": { - "description": "Whether the patch was applied successfully.", - "type": "boolean" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_end" - ], - "title": "PatchApplyEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "status", - "stderr", - "stdout", - "success", - "type" - ], - "title": "PatchApplyEndEventMsg", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "turn_diff" - ], - "title": "TurnDiffEventMsgType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "TurnDiffEventMsg", - "type": "object" - }, - { - "description": "Response to GetHistoryEntryRequest.", - "properties": { - "entry": { - "anyOf": [ - { - "$ref": "#/definitions/HistoryEntry" - }, - { - "type": "null" - } - ], - "description": "The entry at the requested offset, if available and parseable." - }, - "log_id": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "offset": { - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "get_history_entry_response" - ], - "title": "GetHistoryEntryResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "log_id", - "offset", - "type" - ], - "title": "GetHistoryEntryResponseEventMsg", - "type": "object" - }, - { - "description": "List of MCP tools available to the agent.", - "properties": { - "auth_statuses": { - "additionalProperties": { - "$ref": "#/definitions/McpAuthStatus" - }, - "description": "Authentication status for each configured MCP server.", - "type": "object" - }, - "resource_templates": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/ResourceTemplate" - }, - "type": "array" - }, - "description": "Known resource templates grouped by server name.", - "type": "object" - }, - "resources": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/Resource" - }, - "type": "array" - }, - "description": "Known resources grouped by server name.", - "type": "object" - }, - "tools": { - "additionalProperties": { - "$ref": "#/definitions/Tool" - }, - "description": "Fully qualified tool name -> tool definition.", - "type": "object" - }, - "type": { - "enum": [ - "mcp_list_tools_response" - ], - "title": "McpListToolsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "auth_statuses", - "resource_templates", - "resources", - "tools", - "type" - ], - "title": "McpListToolsResponseEventMsg", - "type": "object" - }, - { - "description": "List of custom prompts available to the agent.", - "properties": { - "custom_prompts": { - "items": { - "$ref": "#/definitions/CustomPrompt" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_custom_prompts_response" - ], - "title": "ListCustomPromptsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "custom_prompts", - "type" - ], - "title": "ListCustomPromptsResponseEventMsg", - "type": "object" - }, - { - "description": "List of skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/SkillsListEntry" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_skills_response" - ], - "title": "ListSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "List of remote skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/RemoteSkillSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_remote_skills_response" - ], - "title": "ListRemoteSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListRemoteSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "Remote skill downloaded to local cache.", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "remote_skill_downloaded" - ], - "title": "RemoteSkillDownloadedEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "name", - "path", - "type" - ], - "title": "RemoteSkillDownloadedEventMsg", - "type": "object" - }, - { - "description": "Notification that skill data may have been updated and clients may want to reload.", - "properties": { - "type": { - "enum": [ - "skills_update_available" - ], - "title": "SkillsUpdateAvailableEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SkillsUpdateAvailableEventMsg", - "type": "object" - }, - { - "properties": { - "explanation": { - "default": null, - "description": "Arguments for the `update_plan` todo/checklist tool (not plan mode).", - "type": [ - "string", - "null" - ] - }, - "plan": { - "items": { - "$ref": "#/definitions/PlanItemArg" - }, - "type": "array" - }, - "type": { - "enum": [ - "plan_update" - ], - "title": "PlanUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "plan", - "type" - ], - "title": "PlanUpdateEventMsg", - "type": "object" - }, - { - "properties": { - "reason": { - "$ref": "#/definitions/TurnAbortReason" - }, - "turn_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "turn_aborted" - ], - "title": "TurnAbortedEventMsgType", - "type": "string" - } - }, - "required": [ - "reason", - "type" - ], - "title": "TurnAbortedEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is shutting down.", - "properties": { - "type": { - "enum": [ - "shutdown_complete" - ], - "title": "ShutdownCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ShutdownCompleteEventMsg", - "type": "object" - }, - { - "description": "Entered review mode.", - "properties": { - "target": { - "$ref": "#/definitions/ReviewTarget" - }, - "type": { - "enum": [ - "entered_review_mode" - ], - "title": "EnteredReviewModeEventMsgType", - "type": "string" - }, - "user_facing_hint": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "target", - "type" - ], - "title": "EnteredReviewModeEventMsg", - "type": "object" - }, - { - "description": "Exited review mode with an optional final result to apply.", - "properties": { - "review_output": { - "anyOf": [ - { - "$ref": "#/definitions/ReviewOutputEvent" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "exited_review_mode" - ], - "title": "ExitedReviewModeEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExitedReviewModeEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/ResponseItem" - }, - "type": { - "enum": [ - "raw_response_item" - ], - "title": "RawResponseItemEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "type" - ], - "title": "RawResponseItemEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_started" - ], - "title": "ItemStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemStartedEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_completed" - ], - "title": "ItemCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemCompletedEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_content_delta" - ], - "title": "AgentMessageContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "AgentMessageContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "plan_delta" - ], - "title": "PlanDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "PlanDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_content_delta" - ], - "title": "ReasoningContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "content_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_raw_content_delta" - ], - "title": "ReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_spawn_begin" - ], - "title": "CollabAgentSpawnBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "type" - ], - "title": "CollabAgentSpawnBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "new_agent_nickname": { - "description": "Optional nickname assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_agent_role": { - "description": "Optional role assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_thread_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ], - "description": "Thread ID of the newly spawned agent, if it was created." - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the new agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_spawn_end" - ], - "title": "CollabAgentSpawnEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentSpawnEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_interaction_begin" - ], - "title": "CollabAgentInteractionBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabAgentInteractionBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_interaction_end" - ], - "title": "CollabAgentInteractionEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentInteractionEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting begin.", - "properties": { - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "receiver_agents": { - "description": "Optional nicknames/roles for receivers.", - "items": { - "$ref": "#/definitions/CollabAgentRef" - }, - "type": "array" - }, - "receiver_thread_ids": { - "description": "Thread ID of the receivers.", - "items": { - "$ref": "#/definitions/ThreadId" - }, - "type": "array" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_waiting_begin" - ], - "title": "CollabWaitingBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_ids", - "sender_thread_id", - "type" - ], - "title": "CollabWaitingBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting end.", - "properties": { - "agent_statuses": { - "description": "Optional receiver metadata paired with final statuses.", - "items": { - "$ref": "#/definitions/CollabAgentStatusEntry" - }, - "type": "array" - }, - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "statuses": { - "additionalProperties": { - "$ref": "#/definitions/AgentStatus" - }, - "description": "Last known status of the receiver agents reported to the sender agent.", - "type": "object" - }, - "type": { - "enum": [ - "collab_waiting_end" - ], - "title": "CollabWaitingEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "sender_thread_id", - "statuses", - "type" - ], - "title": "CollabWaitingEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_close_begin" - ], - "title": "CollabCloseBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabCloseBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent before the close." - }, - "type": { - "enum": [ - "collab_close_end" - ], - "title": "CollabCloseEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabCloseEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_resume_begin" - ], - "title": "CollabResumeBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabResumeBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent after resume." - }, - "type": { - "enum": [ - "collab_resume_end" - ], - "title": "CollabResumeEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabResumeEndEventMsg", - "type": "object" - } - ] - }, - "ExecCommandSource": { - "enum": [ - "agent", - "user_shell", - "unified_exec_startup", - "unified_exec_interaction" - ], - "type": "string" - }, - "ExecCommandStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, - "ExecOutputStream": { - "enum": [ - "stdout", - "stderr" - ], - "type": "string" - }, - "FileChange": { - "oneOf": [ - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "add" - ], - "title": "AddFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "AddFileChange", - "type": "object" - }, - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "delete" - ], - "title": "DeleteFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "DeleteFileChange", - "type": "object" - }, - { - "properties": { - "move_path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "update" - ], - "title": "UpdateFileChangeType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "UpdateFileChange", - "type": "object" - } - ] - }, - "FunctionCallOutputBody": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "$ref": "#/definitions/FunctionCallOutputContentItem" - }, - "type": "array" - } - ] - }, - "FunctionCallOutputContentItem": { - "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextFunctionCallOutputContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageFunctionCallOutputContentItem", - "type": "object" - } - ] - }, - "FunctionCallOutputPayload": { - "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", - "properties": { - "body": { - "$ref": "#/definitions/FunctionCallOutputBody" - }, - "success": { - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "body" - ], - "type": "object" - }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, - "HistoryEntry": { - "properties": { - "conversation_id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "ts": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "conversation_id", - "text", - "ts" - ], - "type": "object" - }, - "LocalShellAction": { - "oneOf": [ - { - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "timeout_ms": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - }, - "type": { - "enum": [ - "exec" - ], - "title": "ExecLocalShellActionType", - "type": "string" - }, - "user": { - "type": [ - "string", - "null" - ] - }, - "working_directory": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "command", - "type" - ], - "title": "ExecLocalShellAction", - "type": "object" - } - ] - }, - "LocalShellStatus": { - "enum": [ - "completed", - "in_progress", - "incomplete" - ], - "type": "string" - }, - "McpAuthStatus": { - "enum": [ - "unsupported", - "not_logged_in", - "bearer_token", - "o_auth" - ], - "type": "string" - }, - "McpInvocation": { - "properties": { - "arguments": { - "description": "Arguments to the tool call." - }, - "server": { - "description": "Name of the MCP server as defined in the config.", - "type": "string" - }, - "tool": { - "description": "Name of the tool as given by the MCP server.", - "type": "string" - } - }, - "required": [ - "server", - "tool" - ], - "type": "object" - }, - "McpStartupFailure": { - "properties": { - "error": { - "type": "string" - }, - "server": { - "type": "string" - } - }, - "required": [ - "error", - "server" - ], - "type": "object" - }, - "McpStartupStatus": { - "oneOf": [ - { - "properties": { - "state": { - "enum": [ - "starting" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus", - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "ready" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus2", - "type": "object" - }, - { - "properties": { - "error": { - "type": "string" - }, - "state": { - "enum": [ - "failed" - ], - "type": "string" - } - }, - "required": [ - "error", - "state" - ], - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "cancelled" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus3", - "type": "object" - } - ] - }, - "MessagePhase": { - "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", - "oneOf": [ - { - "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", - "enum": [ - "commentary" - ], - "type": "string" - }, - { - "description": "The assistant's terminal answer text for the current turn.", - "enum": [ - "final_answer" - ], - "type": "string" - } - ] - }, - "ModeKind": { - "description": "Initial collaboration mode to use when the TUI starts.", - "enum": [ - "plan", - "default" - ], - "type": "string" - }, - "ModelRerouteReason": { - "enum": [ - "high_risk_cyber_activity" - ], - "type": "string" - }, - "NetworkAccess": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, - "NetworkApprovalContext": { - "properties": { - "host": { - "type": "string" - }, - "protocol": { - "$ref": "#/definitions/NetworkApprovalProtocol" - } - }, - "required": [ - "host", - "protocol" - ], - "type": "object" - }, - "NetworkApprovalProtocol": { - "enum": [ - "http", - "https", - "socks5_tcp", - "socks5_udp" - ], - "type": "string" - }, - "ParsedCommand": { - "oneOf": [ - { - "properties": { - "cmd": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", - "type": "string" - }, - "type": { - "enum": [ - "read" - ], - "title": "ReadParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "name", - "path", - "type" - ], - "title": "ReadParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "list_files" - ], - "title": "ListFilesParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "ListFilesParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "SearchParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "type": { - "enum": [ - "unknown" - ], - "title": "UnknownParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "UnknownParsedCommand", - "type": "object" - } - ] - }, - "PatchApplyStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, - "PlanItemArg": { - "additionalProperties": false, - "properties": { - "status": { - "$ref": "#/definitions/StepStatus" - }, - "step": { - "type": "string" - } - }, - "required": [ - "status", - "step" - ], - "type": "object" - }, - "PlanType": { - "enum": [ - "free", - "go", - "plus", - "pro", - "team", - "business", - "enterprise", - "edu", - "unknown" - ], - "type": "string" - }, - "RateLimitSnapshot": { - "properties": { - "credits": { - "anyOf": [ - { - "$ref": "#/definitions/CreditsSnapshot" - }, - { - "type": "null" - } - ] - }, - "limit_id": { - "type": [ - "string", - "null" - ] - }, - "limit_name": { - "type": [ - "string", - "null" - ] - }, - "plan_type": { - "anyOf": [ - { - "$ref": "#/definitions/PlanType" - }, - { - "type": "null" - } - ] - }, - "primary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - }, - "secondary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "RateLimitWindow": { - "properties": { - "resets_at": { - "description": "Unix timestamp (seconds since epoch) when the window resets.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "used_percent": { - "description": "Percentage (0-100) of the window that has been consumed.", - "format": "double", - "type": "number" - }, - "window_minutes": { - "description": "Rolling window duration, in minutes.", - "format": "int64", - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "used_percent" - ], - "type": "object" - }, - "ReadOnlyAccess": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess", - "type": "object" - } - ] - }, - "RealtimeAudioFrame": { - "properties": { - "data": { - "type": "string" - }, - "num_channels": { - "format": "uint16", - "minimum": 0.0, - "type": "integer" - }, - "sample_rate": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "samples_per_channel": { - "format": "uint32", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "data", - "num_channels", - "sample_rate" - ], - "type": "object" - }, - "RealtimeEvent": { - "oneOf": [ - { - "additionalProperties": false, - "properties": { - "SessionCreated": { - "properties": { - "session_id": { - "type": "string" - } - }, - "required": [ - "session_id" - ], - "type": "object" - } - }, - "required": [ - "SessionCreated" - ], - "title": "SessionCreatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "SessionUpdated": { - "properties": { - "backend_prompt": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "SessionUpdated" - ], - "title": "SessionUpdatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "AudioOut": { - "$ref": "#/definitions/RealtimeAudioFrame" - } - }, - "required": [ - "AudioOut" - ], - "title": "AudioOutRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "ConversationItemAdded": true - }, - "required": [ - "ConversationItemAdded" - ], - "title": "ConversationItemAddedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "Error": { - "type": "string" - } - }, - "required": [ - "Error" - ], - "title": "ErrorRealtimeEvent", - "type": "object" - } - ] - }, - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ReasoningItemContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_text" - ], - "title": "ReasoningTextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "ReasoningTextReasoningItemContent", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextReasoningItemContent", - "type": "object" - } - ] - }, - "ReasoningItemReasoningSummary": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "summary_text" - ], - "title": "SummaryTextReasoningItemReasoningSummaryType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "SummaryTextReasoningItemReasoningSummary", - "type": "object" - } - ] - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "RemoteSkillSummary": { - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "description", - "id", - "name" - ], - "type": "object" - }, - "RequestId": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "int64", - "type": "integer" - } - ], - "description": "ID of a request, which can be either a string or an integer." - }, - "RequestUserInputQuestion": { - "properties": { - "header": { - "type": "string" - }, - "id": { - "type": "string" - }, - "isOther": { - "default": false, - "type": "boolean" - }, - "isSecret": { - "default": false, - "type": "boolean" - }, - "options": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestionOption" - }, - "type": [ - "array", - "null" - ] - }, - "question": { - "type": "string" - } - }, - "required": [ - "header", - "id", - "question" - ], - "type": "object" - }, - "RequestUserInputQuestionOption": { - "properties": { - "description": { - "type": "string" - }, - "label": { - "type": "string" - } - }, - "required": [ - "description", - "label" - ], - "type": "object" - }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "size": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uri": { - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uriTemplate": { - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResponseItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/ContentItem" - }, - "type": "array" - }, - "end_turn": { - "type": [ - "boolean", - "null" - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ] - }, - "role": { - "type": "string" - }, - "type": { - "enum": [ - "message" - ], - "title": "MessageResponseItemType", - "type": "string" - } - }, - "required": [ - "content", - "role", - "type" - ], - "title": "MessageResponseItem", - "type": "object" - }, - { - "properties": { - "content": { - "default": null, - "items": { - "$ref": "#/definitions/ReasoningItemContent" - }, - "type": [ - "array", - "null" - ] - }, - "encrypted_content": { - "type": [ - "string", - "null" - ] - }, - "id": { - "type": "string", - "writeOnly": true - }, - "summary": { - "items": { - "$ref": "#/definitions/ReasoningItemReasoningSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "reasoning" - ], - "title": "ReasoningResponseItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary", - "type" - ], - "title": "ReasoningResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/LocalShellAction" - }, - "call_id": { - "description": "Set when using the Responses API.", - "type": [ - "string", - "null" - ] - }, - "id": { - "description": "Legacy id field retained for compatibility with older payloads.", - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "$ref": "#/definitions/LocalShellStatus" - }, - "type": { - "enum": [ - "local_shell_call" - ], - "title": "LocalShellCallResponseItemType", - "type": "string" - } - }, - "required": [ - "action", - "status", - "type" - ], - "title": "LocalShellCallResponseItem", - "type": "object" - }, - { - "properties": { - "arguments": { - "type": "string" - }, - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "name": { - "type": "string" - }, - "type": { - "enum": [ - "function_call" - ], - "title": "FunctionCallResponseItemType", - "type": "string" - } - }, - "required": [ - "arguments", - "call_id", - "name", - "type" - ], - "title": "FunctionCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "$ref": "#/definitions/FunctionCallOutputPayload" - }, - "type": { - "enum": [ - "function_call_output" - ], - "title": "FunctionCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "FunctionCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "input": { - "type": "string" - }, - "name": { - "type": "string" - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "custom_tool_call" - ], - "title": "CustomToolCallResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "input", - "name", - "type" - ], - "title": "CustomToolCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "type": "string" - }, - "type": { - "enum": [ - "custom_tool_call_output" - ], - "title": "CustomToolCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "CustomToolCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "anyOf": [ - { - "$ref": "#/definitions/WebSearchAction" - }, - { - "type": "null" - } - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "web_search_call" - ], - "title": "WebSearchCallResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "WebSearchCallResponseItem", - "type": "object" - }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, - { - "properties": { - "encrypted_content": { - "type": "string" - }, - "type": { - "enum": [ - "compaction" - ], - "title": "CompactionResponseItemType", - "type": "string" - } - }, - "required": [ - "encrypted_content", - "type" - ], - "title": "CompactionResponseItem", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherResponseItem", - "type": "object" - } - ] - }, - "Result_of_CallToolResult_or_String": { - "oneOf": [ - { - "properties": { - "Ok": { - "$ref": "#/definitions/CallToolResult" - } - }, - "required": [ - "Ok" - ], - "title": "OkResult_of_CallToolResult_or_String", - "type": "object" - }, - { - "properties": { - "Err": { - "type": "string" - } - }, - "required": [ - "Err" - ], - "title": "ErrResult_of_CallToolResult_or_String", - "type": "object" - } - ] - }, - "ReviewCodeLocation": { - "description": "Location of the code related to a review finding.", - "properties": { - "absolute_file_path": { - "type": "string" - }, - "line_range": { - "$ref": "#/definitions/ReviewLineRange" - } - }, - "required": [ - "absolute_file_path", - "line_range" - ], - "type": "object" - }, - "ReviewFinding": { - "description": "A single review finding describing an observed issue or recommendation.", - "properties": { - "body": { - "type": "string" - }, - "code_location": { - "$ref": "#/definitions/ReviewCodeLocation" - }, - "confidence_score": { - "format": "float", - "type": "number" - }, - "priority": { - "format": "int32", - "type": "integer" - }, - "title": { - "type": "string" - } - }, - "required": [ - "body", - "code_location", - "confidence_score", - "priority", - "title" - ], - "type": "object" - }, - "ReviewLineRange": { - "description": "Inclusive line range in a file associated with the finding.", - "properties": { - "end": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "ReviewOutputEvent": { - "description": "Structured review result produced by a child review session.", - "properties": { - "findings": { - "items": { - "$ref": "#/definitions/ReviewFinding" - }, - "type": "array" - }, - "overall_confidence_score": { - "format": "float", - "type": "number" - }, - "overall_correctness": { - "type": "string" - }, - "overall_explanation": { - "type": "string" - } - }, - "required": [ - "findings", - "overall_confidence_score", - "overall_correctness", - "overall_explanation" - ], - "type": "object" - }, - "ReviewTarget": { - "oneOf": [ - { - "description": "Review the working tree: staged, unstaged, and untracked files.", - "properties": { - "type": { - "enum": [ - "uncommittedChanges" - ], - "title": "UncommittedChangesReviewTargetType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UncommittedChangesReviewTarget", - "type": "object" - }, - { - "description": "Review changes between the current branch and the given base branch.", - "properties": { - "branch": { - "type": "string" - }, - "type": { - "enum": [ - "baseBranch" - ], - "title": "BaseBranchReviewTargetType", - "type": "string" - } - }, - "required": [ - "branch", - "type" - ], - "title": "BaseBranchReviewTarget", - "type": "object" - }, - { - "description": "Review the changes introduced by a specific commit.", - "properties": { - "sha": { - "type": "string" - }, - "title": { - "description": "Optional human-readable label (e.g., commit subject) for UIs.", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "commit" - ], - "title": "CommitReviewTargetType", - "type": "string" - } - }, - "required": [ - "sha", - "type" - ], - "title": "CommitReviewTarget", - "type": "object" - }, - { - "description": "Arbitrary instructions provided by the user.", - "properties": { - "instructions": { - "type": "string" - }, - "type": { - "enum": [ - "custom" - ], - "title": "CustomReviewTargetType", - "type": "string" - } - }, - "required": [ - "instructions", - "type" - ], - "title": "CustomReviewTarget", - "type": "object" - } - ] - }, - "SandboxPolicy": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicyType", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy", - "type": "object" - } - ] - }, - "SessionNetworkProxyRuntime": { - "properties": { - "admin_addr": { - "type": "string" - }, - "http_addr": { - "type": "string" - }, - "socks_addr": { - "type": "string" - } - }, - "required": [ - "admin_addr", - "http_addr", - "socks_addr" - ], - "type": "object" - }, - "SkillDependencies": { - "properties": { - "tools": { - "items": { - "$ref": "#/definitions/SkillToolDependency" - }, - "type": "array" - } - }, - "required": [ - "tools" - ], - "type": "object" - }, - "SkillErrorInfo": { - "properties": { - "message": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "message", - "path" - ], - "type": "object" - }, - "SkillInterface": { - "properties": { - "brand_color": { - "type": [ - "string", - "null" - ] - }, - "default_prompt": { - "type": [ - "string", - "null" - ] - }, - "display_name": { - "type": [ - "string", - "null" - ] - }, - "icon_large": { - "type": [ - "string", - "null" - ] - }, - "icon_small": { - "type": [ - "string", - "null" - ] - }, - "short_description": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "SkillMetadata": { - "properties": { - "dependencies": { - "anyOf": [ - { - "$ref": "#/definitions/SkillDependencies" - }, - { - "type": "null" - } - ] - }, - "description": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "interface": { - "anyOf": [ - { - "$ref": "#/definitions/SkillInterface" - }, - { - "type": "null" - } - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "scope": { - "$ref": "#/definitions/SkillScope" - }, - "short_description": { - "description": "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "description", - "enabled", - "name", - "path", - "scope" - ], - "type": "object" - }, - "SkillScope": { - "enum": [ - "user", - "repo", - "system", - "admin" - ], - "type": "string" - }, - "SkillToolDependency": { - "properties": { - "command": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "transport": { - "type": [ - "string", - "null" - ] - }, - "type": { - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - }, - "value": { - "type": "string" - } - }, - "required": [ - "type", - "value" - ], - "type": "object" - }, - "SkillsListEntry": { - "properties": { - "cwd": { - "type": "string" - }, - "errors": { - "items": { - "$ref": "#/definitions/SkillErrorInfo" - }, - "type": "array" - }, - "skills": { - "items": { - "$ref": "#/definitions/SkillMetadata" - }, - "type": "array" - } - }, - "required": [ - "cwd", - "errors", - "skills" - ], - "type": "object" - }, - "StepStatus": { - "enum": [ - "pending", - "in_progress", - "completed" - ], - "type": "string" - }, - "TextElement": { - "properties": { - "byte_range": { - "allOf": [ - { - "$ref": "#/definitions/ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byte_range" - ], - "type": "object" - }, - "ThreadId": { - "type": "string" - }, - "TokenUsage": { - "properties": { - "cached_input_tokens": { - "format": "int64", - "type": "integer" - }, - "input_tokens": { - "format": "int64", - "type": "integer" - }, - "output_tokens": { - "format": "int64", - "type": "integer" - }, - "reasoning_output_tokens": { - "format": "int64", - "type": "integer" - }, - "total_tokens": { - "format": "int64", - "type": "integer" - } - }, - "required": [ - "cached_input_tokens", - "input_tokens", - "output_tokens", - "reasoning_output_tokens", - "total_tokens" - ], - "type": "object" - }, - "TokenUsageInfo": { - "properties": { - "last_token_usage": { - "$ref": "#/definitions/TokenUsage" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "total_token_usage": { - "$ref": "#/definitions/TokenUsage" - } - }, - "required": [ - "last_token_usage", - "total_token_usage" - ], - "type": "object" - }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "inputSchema": true, - "name": { - "type": "string" - }, - "outputSchema": true, - "title": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, - "TurnAbortReason": { - "enum": [ - "interrupted", - "replaced", - "review_ended" - ], - "type": "string" - }, - "TurnItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/UserInput" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "type": { - "enum": [ - "UserMessage" - ], - "title": "UserMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "UserMessageTurnItem", - "type": "object" - }, - { - "description": "Assistant-authored message payload used in turn-item streams.\n\n`phase` is optional because not all providers/models emit it. Consumers should use it when present, but retain legacy completion semantics when it is `None`.", - "properties": { - "content": { - "items": { - "$ref": "#/definitions/AgentMessageContent" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "description": "Optional phase metadata carried through from `ResponseItem::Message`.\n\nThis is currently used by TUI rendering to distinguish mid-turn commentary from a final answer and avoid status-indicator jitter." - }, - "type": { - "enum": [ - "AgentMessage" - ], - "title": "AgentMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "AgentMessageTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Plan" - ], - "title": "PlanTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "text", - "type" - ], - "title": "PlanTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "raw_content": { - "default": [], - "items": { - "type": "string" - }, - "type": "array" - }, - "summary_text": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "Reasoning" - ], - "title": "ReasoningTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary_text", - "type" - ], - "title": "ReasoningTurnItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction" - }, - "id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "WebSearch" - ], - "title": "WebSearchTurnItemType", - "type": "string" - } - }, - "required": [ - "action", - "id", - "query", - "type" - ], - "title": "WebSearchTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "type": { - "enum": [ - "ContextCompaction" - ], - "title": "ContextCompactionTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "type" - ], - "title": "ContextCompactionTurnItem", - "type": "object" - } - ] - }, - "UserInput": { - "description": "User input", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` that should be treated as special elements. These are byte ranges into the UTF-8 `text` buffer and are used to render or persist rich input markers (e.g., image placeholders) across history and resume without mutating the literal text.", - "items": { - "$ref": "#/definitions/TextElement" - }, - "type": "array" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextUserInputType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextUserInput", - "type": "object" - }, - { - "description": "Pre‑encoded data: URI image.", - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageUserInputType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "ImageUserInput", - "type": "object" - }, - { - "description": "Local image path provided by the user. This will be converted to an `Image` variant (base64 data URL) during request serialization.", - "properties": { - "path": { - "type": "string" - }, - "type": { - "enum": [ - "local_image" - ], - "title": "LocalImageUserInputType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "LocalImageUserInput", - "type": "object" - }, - { - "description": "Skill selected by the user (name + path to SKILL.md).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "skill" - ], - "title": "SkillUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "SkillUserInput", - "type": "object" - }, - { - "description": "Explicit mention selected by the user (name + app://connector id).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "mention" - ], - "title": "MentionUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "MentionUserInput", - "type": "object" - } - ] - }, - "WebSearchAction": { - "oneOf": [ - { - "properties": { - "queries": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SearchWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "open_page" - ], - "title": "OpenPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "OpenPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "pattern": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "find_in_page" - ], - "title": "FindInPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "FindInPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherWebSearchAction", - "type": "object" - } - ] - } - }, - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "initialMessages": { - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "type": "string" - }, - "rolloutPath": { - "type": "string" - } - }, - "required": [ - "conversationId", - "model", - "rolloutPath" - ], - "title": "ResumeConversationResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/SendUserMessageParams.json b/codex-rs/app-server-protocol/schema/json/v1/SendUserMessageParams.json deleted file mode 100644 index 1f53acc006..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/SendUserMessageParams.json +++ /dev/null @@ -1,165 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "InputItem": { - "oneOf": [ - { - "properties": { - "data": { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/V1TextElement" - }, - "type": "array" - } - }, - "required": [ - "text" - ], - "type": "object" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "TextInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "image_url": { - "type": "string" - } - }, - "required": [ - "image_url" - ], - "type": "object" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "ImageInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "path": { - "type": "string" - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "type": { - "enum": [ - "localImage" - ], - "title": "LocalImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "LocalImageInputItem", - "type": "object" - } - ] - }, - "ThreadId": { - "type": "string" - }, - "V1ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "V1TextElement": { - "properties": { - "byteRange": { - "allOf": [ - { - "$ref": "#/definitions/V1ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byteRange" - ], - "type": "object" - } - }, - "properties": { - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "items": { - "items": { - "$ref": "#/definitions/InputItem" - }, - "type": "array" - } - }, - "required": [ - "conversationId", - "items" - ], - "title": "SendUserMessageParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/SendUserMessageResponse.json b/codex-rs/app-server-protocol/schema/json/v1/SendUserMessageResponse.json deleted file mode 100644 index df3df37c83..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/SendUserMessageResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "SendUserMessageResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/SendUserTurnParams.json b/codex-rs/app-server-protocol/schema/json/v1/SendUserTurnParams.json deleted file mode 100644 index a213f6077e..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/SendUserTurnParams.json +++ /dev/null @@ -1,482 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "InputItem": { - "oneOf": [ - { - "properties": { - "data": { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/V1TextElement" - }, - "type": "array" - } - }, - "required": [ - "text" - ], - "type": "object" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "TextInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "image_url": { - "type": "string" - } - }, - "required": [ - "image_url" - ], - "type": "object" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "ImageInputItem", - "type": "object" - }, - { - "properties": { - "data": { - "properties": { - "path": { - "type": "string" - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "type": { - "enum": [ - "localImage" - ], - "title": "LocalImageInputItemType", - "type": "string" - } - }, - "required": [ - "data", - "type" - ], - "title": "LocalImageInputItem", - "type": "object" - } - ] - }, - "NetworkAccess": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, - "ReadOnlyAccess": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess", - "type": "object" - } - ] - }, - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ReasoningSummary": { - "description": "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", - "oneOf": [ - { - "enum": [ - "auto", - "concise", - "detailed" - ], - "type": "string" - }, - { - "description": "Option to disable reasoning summaries.", - "enum": [ - "none" - ], - "type": "string" - } - ] - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "SandboxPolicy": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicyType", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy", - "type": "object" - } - ] - }, - "ThreadId": { - "type": "string" - }, - "V1ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "V1TextElement": { - "properties": { - "byteRange": { - "allOf": [ - { - "$ref": "#/definitions/V1ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byteRange" - ], - "type": "object" - } - }, - "properties": { - "approvalPolicy": { - "$ref": "#/definitions/AskForApproval" - }, - "conversationId": { - "$ref": "#/definitions/ThreadId" - }, - "cwd": { - "type": "string" - }, - "effort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "items": { - "items": { - "$ref": "#/definitions/InputItem" - }, - "type": "array" - }, - "model": { - "type": "string" - }, - "outputSchema": { - "description": "Optional JSON Schema used to constrain the final assistant message for this turn." - }, - "sandboxPolicy": { - "$ref": "#/definitions/SandboxPolicy" - }, - "summary": { - "$ref": "#/definitions/ReasoningSummary" - } - }, - "required": [ - "approvalPolicy", - "conversationId", - "cwd", - "items", - "model", - "sandboxPolicy", - "summary" - ], - "title": "SendUserTurnParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/SendUserTurnResponse.json b/codex-rs/app-server-protocol/schema/json/v1/SendUserTurnResponse.json deleted file mode 100644 index 5dc36098ff..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/SendUserTurnResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "SendUserTurnResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json b/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json deleted file mode 100644 index a3010337bb..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json +++ /dev/null @@ -1,5798 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "AbsolutePathBuf": { - "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", - "type": "string" - }, - "AgentMessageContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Text" - ], - "title": "TextAgentMessageContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextAgentMessageContent", - "type": "object" - } - ] - }, - "AgentStatus": { - "description": "Agent lifecycle status, derived from emitted events.", - "oneOf": [ - { - "description": "Agent is waiting for initialization.", - "enum": [ - "pending_init" - ], - "type": "string" - }, - { - "description": "Agent is currently running.", - "enum": [ - "running" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Agent is done. Contains the final assistant message.", - "properties": { - "completed": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "completed" - ], - "title": "CompletedAgentStatus", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Agent encountered an error.", - "properties": { - "errored": { - "type": "string" - } - }, - "required": [ - "errored" - ], - "title": "ErroredAgentStatus", - "type": "object" - }, - { - "description": "Agent has been shutdown.", - "enum": [ - "shutdown" - ], - "type": "string" - }, - { - "description": "Agent is not found.", - "enum": [ - "not_found" - ], - "type": "string" - } - ] - }, - "AskForApproval": { - "description": "Determines the conditions under which the user is consulted to approve running the command proposed by Codex.", - "oneOf": [ - { - "description": "Under this policy, only \"known safe\" commands—as determined by `is_safe_command()`—that **only read files** are auto‑approved. Everything else will ask the user to approve.", - "enum": [ - "untrusted" - ], - "type": "string" - }, - { - "description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.", - "enum": [ - "on-failure" - ], - "type": "string" - }, - { - "description": "The model decides when to ask the user for approval.", - "enum": [ - "on-request" - ], - "type": "string" - }, - { - "additionalProperties": false, - "description": "Fine-grained rejection controls for approval prompts.\n\nWhen a field is `true`, prompts of that category are automatically rejected instead of shown to the user.", - "properties": { - "reject": { - "$ref": "#/definitions/RejectConfig" - } - }, - "required": [ - "reject" - ], - "title": "RejectAskForApproval", - "type": "object" - }, - { - "description": "Never ask the user to approve commands. Failures are immediately returned to the model, and never escalated to the user for approval.", - "enum": [ - "never" - ], - "type": "string" - } - ] - }, - "ByteRange": { - "properties": { - "end": { - "description": "End byte offset (exclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "description": "Start byte offset (inclusive) within the UTF-8 text buffer.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "CallToolResult": { - "description": "The server's response to a tool call.", - "properties": { - "_meta": true, - "content": { - "items": true, - "type": "array" - }, - "isError": { - "type": [ - "boolean", - "null" - ] - }, - "structuredContent": true - }, - "required": [ - "content" - ], - "type": "object" - }, - "CodexErrorInfo": { - "description": "Codex errors that we expose to clients.", - "oneOf": [ - { - "enum": [ - "context_window_exceeded", - "usage_limit_exceeded", - "server_overloaded", - "internal_server_error", - "unauthorized", - "bad_request", - "sandbox_error", - "thread_rollback_failed", - "other" - ], - "type": "string" - }, - { - "additionalProperties": false, - "properties": { - "http_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "http_connection_failed" - ], - "title": "HttpConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Failed to connect to the response SSE stream.", - "properties": { - "response_stream_connection_failed": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_connection_failed" - ], - "title": "ResponseStreamConnectionFailedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "The response SSE stream disconnected in the middle of a turnbefore completion.", - "properties": { - "response_stream_disconnected": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_stream_disconnected" - ], - "title": "ResponseStreamDisconnectedCodexErrorInfo", - "type": "object" - }, - { - "additionalProperties": false, - "description": "Reached the retry limit for responses.", - "properties": { - "response_too_many_failed_attempts": { - "properties": { - "http_status_code": { - "format": "uint16", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "response_too_many_failed_attempts" - ], - "title": "ResponseTooManyFailedAttemptsCodexErrorInfo", - "type": "object" - } - ] - }, - "CollabAgentRef": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "thread_id" - ], - "type": "object" - }, - "CollabAgentStatusEntry": { - "properties": { - "agent_nickname": { - "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "agent_role": { - "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", - "type": [ - "string", - "null" - ] - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the agent." - }, - "thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver/new agent." - } - }, - "required": [ - "status", - "thread_id" - ], - "type": "object" - }, - "ContentItem": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageContentItem", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "output_text" - ], - "title": "OutputTextContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "OutputTextContentItem", - "type": "object" - } - ] - }, - "CreditsSnapshot": { - "properties": { - "balance": { - "type": [ - "string", - "null" - ] - }, - "has_credits": { - "type": "boolean" - }, - "unlimited": { - "type": "boolean" - } - }, - "required": [ - "has_credits", - "unlimited" - ], - "type": "object" - }, - "CustomPrompt": { - "properties": { - "argument_hint": { - "type": [ - "string", - "null" - ] - }, - "content": { - "type": "string" - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "content", - "name", - "path" - ], - "type": "object" - }, - "Duration": { - "properties": { - "nanos": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "secs": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "nanos", - "secs" - ], - "type": "object" - }, - "EventMsg": { - "description": "Response event from the agent NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.", - "oneOf": [ - { - "description": "Error while executing a submission", - "properties": { - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "error" - ], - "title": "ErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "ErrorEventMsg", - "type": "object" - }, - { - "description": "Warning issued while processing a submission. Unlike `Error`, this indicates the turn continued but the user should still be notified.", - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "warning" - ], - "title": "WarningEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "WarningEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle start event.", - "properties": { - "session_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_started" - ], - "title": "RealtimeConversationStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationStartedEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation streaming payload event.", - "properties": { - "payload": { - "$ref": "#/definitions/RealtimeEvent" - }, - "type": { - "enum": [ - "realtime_conversation_realtime" - ], - "title": "RealtimeConversationRealtimeEventMsgType", - "type": "string" - } - }, - "required": [ - "payload", - "type" - ], - "title": "RealtimeConversationRealtimeEventMsg", - "type": "object" - }, - { - "description": "Realtime conversation lifecycle close event.", - "properties": { - "reason": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "realtime_conversation_closed" - ], - "title": "RealtimeConversationClosedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RealtimeConversationClosedEventMsg", - "type": "object" - }, - { - "description": "Model routing changed from the requested model to a different model.", - "properties": { - "from_model": { - "type": "string" - }, - "reason": { - "$ref": "#/definitions/ModelRerouteReason" - }, - "to_model": { - "type": "string" - }, - "type": { - "enum": [ - "model_reroute" - ], - "title": "ModelRerouteEventMsgType", - "type": "string" - } - }, - "required": [ - "from_model", - "reason", - "to_model", - "type" - ], - "title": "ModelRerouteEventMsg", - "type": "object" - }, - { - "description": "Conversation history was compacted (either automatically or manually).", - "properties": { - "type": { - "enum": [ - "context_compacted" - ], - "title": "ContextCompactedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ContextCompactedEventMsg", - "type": "object" - }, - { - "description": "Conversation history was rolled back by dropping the last N user turns.", - "properties": { - "num_turns": { - "description": "Number of user turns that were removed from context.", - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "thread_rolled_back" - ], - "title": "ThreadRolledBackEventMsgType", - "type": "string" - } - }, - "required": [ - "num_turns", - "type" - ], - "title": "ThreadRolledBackEventMsg", - "type": "object" - }, - { - "description": "Agent has started a turn. v1 wire format uses `task_started`; accept `turn_started` for v2 interop.", - "properties": { - "collaboration_mode_kind": { - "allOf": [ - { - "$ref": "#/definitions/ModeKind" - } - ], - "default": "default" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_started" - ], - "title": "TaskStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskStartedEventMsg", - "type": "object" - }, - { - "description": "Agent has completed all actions. v1 wire format uses `task_complete`; accept `turn_complete` for v2 interop.", - "properties": { - "last_agent_message": { - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "task_complete" - ], - "title": "TaskCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "turn_id", - "type" - ], - "title": "TaskCompleteEventMsg", - "type": "object" - }, - { - "description": "Usage update for the current session, including totals and last turn. Optional means unknown — UIs should not display when `None`.", - "properties": { - "info": { - "anyOf": [ - { - "$ref": "#/definitions/TokenUsageInfo" - }, - { - "type": "null" - } - ] - }, - "rate_limits": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitSnapshot" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "token_count" - ], - "title": "TokenCountEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "TokenCountEventMsg", - "type": "object" - }, - { - "description": "Agent text output message", - "properties": { - "message": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "default": null - }, - "type": { - "enum": [ - "agent_message" - ], - "title": "AgentMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "AgentMessageEventMsg", - "type": "object" - }, - { - "description": "User/system input message (what was sent to the model)", - "properties": { - "images": { - "description": "Image URLs sourced from `UserInput::Image`. These are safe to replay in legacy UI history events and correspond to images sent to the model.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "local_images": { - "default": [], - "description": "Local file paths sourced from `UserInput::LocalImage`. These are kept so the UI can reattach images when editing history, and should not be sent to the model or treated as API-ready URLs.", - "items": { - "type": "string" - }, - "type": "array" - }, - "message": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `message` used to render or persist special elements.", - "items": { - "$ref": "#/definitions/TextElement" - }, - "type": "array" - }, - "type": { - "enum": [ - "user_message" - ], - "title": "UserMessageEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "UserMessageEventMsg", - "type": "object" - }, - { - "description": "Agent text output delta message", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_delta" - ], - "title": "AgentMessageDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentMessageDeltaEventMsg", - "type": "object" - }, - { - "description": "Reasoning event from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning" - ], - "title": "AgentReasoningEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_delta" - ], - "title": "AgentReasoningDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningDeltaEventMsg", - "type": "object" - }, - { - "description": "Raw chain-of-thought from agent.", - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content" - ], - "title": "AgentReasoningRawContentEventMsgType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "AgentReasoningRawContentEventMsg", - "type": "object" - }, - { - "description": "Agent reasoning content delta event from agent.", - "properties": { - "delta": { - "type": "string" - }, - "type": { - "enum": [ - "agent_reasoning_raw_content_delta" - ], - "title": "AgentReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "type" - ], - "title": "AgentReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Signaled when the model begins a new reasoning summary section (e.g., a new titled block).", - "properties": { - "item_id": { - "default": "", - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "type": { - "enum": [ - "agent_reasoning_section_break" - ], - "title": "AgentReasoningSectionBreakEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "AgentReasoningSectionBreakEventMsg", - "type": "object" - }, - { - "description": "Ack the client's configure message.", - "properties": { - "approval_policy": { - "allOf": [ - { - "$ref": "#/definitions/AskForApproval" - } - ], - "description": "When to escalate for approval for execution" - }, - "cwd": { - "description": "Working directory that should be treated as the *root* of the session.", - "type": "string" - }, - "forked_from_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ] - }, - "history_entry_count": { - "description": "Current number of entries in the history log.", - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "history_log_id": { - "description": "Identifier of the history log file (inode on Unix, 0 otherwise).", - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "initial_messages": { - "description": "Optional initial messages (as events) for resumed sessions. When present, UIs can use these to seed the history.", - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "description": "Tell the client what model is being queried.", - "type": "string" - }, - "model_provider_id": { - "type": "string" - }, - "network_proxy": { - "anyOf": [ - { - "$ref": "#/definitions/SessionNetworkProxyRuntime" - }, - { - "type": "null" - } - ], - "description": "Runtime proxy bind addresses, when the managed proxy was started for this session." - }, - "reasoning_effort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ], - "description": "The effort the model is putting into reasoning about the user's request." - }, - "rollout_path": { - "description": "Path in which the rollout is stored. Can be `None` for ephemeral threads", - "type": [ - "string", - "null" - ] - }, - "sandbox_policy": { - "allOf": [ - { - "$ref": "#/definitions/SandboxPolicy" - } - ], - "description": "How to sandbox commands executed in the system" - }, - "session_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "description": "Optional user-facing thread name (may be unset).", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "session_configured" - ], - "title": "SessionConfiguredEventMsgType", - "type": "string" - } - }, - "required": [ - "approval_policy", - "cwd", - "history_entry_count", - "history_log_id", - "model", - "model_provider_id", - "sandbox_policy", - "session_id", - "type" - ], - "title": "SessionConfiguredEventMsg", - "type": "object" - }, - { - "description": "Updated session metadata (e.g., thread name changes).", - "properties": { - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "thread_name": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "thread_name_updated" - ], - "title": "ThreadNameUpdatedEventMsgType", - "type": "string" - } - }, - "required": [ - "thread_id", - "type" - ], - "title": "ThreadNameUpdatedEventMsg", - "type": "object" - }, - { - "description": "Incremental MCP startup progress updates.", - "properties": { - "server": { - "description": "Server name being started.", - "type": "string" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/McpStartupStatus" - } - ], - "description": "Current startup status." - }, - "type": { - "enum": [ - "mcp_startup_update" - ], - "title": "McpStartupUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "server", - "status", - "type" - ], - "title": "McpStartupUpdateEventMsg", - "type": "object" - }, - { - "description": "Aggregate MCP startup completion summary.", - "properties": { - "cancelled": { - "items": { - "type": "string" - }, - "type": "array" - }, - "failed": { - "items": { - "$ref": "#/definitions/McpStartupFailure" - }, - "type": "array" - }, - "ready": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "mcp_startup_complete" - ], - "title": "McpStartupCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "cancelled", - "failed", - "ready", - "type" - ], - "title": "McpStartupCompleteEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the McpToolCallEnd event.", - "type": "string" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "type": { - "enum": [ - "mcp_tool_call_begin" - ], - "title": "McpToolCallBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "invocation", - "type" - ], - "title": "McpToolCallBeginEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Identifier for the corresponding McpToolCallBegin that finished.", - "type": "string" - }, - "duration": { - "$ref": "#/definitions/Duration" - }, - "invocation": { - "$ref": "#/definitions/McpInvocation" - }, - "result": { - "allOf": [ - { - "$ref": "#/definitions/Result_of_CallToolResult_or_String" - } - ], - "description": "Result of the tool call. Note this could be an error." - }, - "type": { - "enum": [ - "mcp_tool_call_end" - ], - "title": "McpToolCallEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "duration", - "invocation", - "result", - "type" - ], - "title": "McpToolCallEndEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_begin" - ], - "title": "WebSearchBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "type" - ], - "title": "WebSearchBeginEventMsg", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction" - }, - "call_id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "web_search_end" - ], - "title": "WebSearchEndEventMsgType", - "type": "string" - } - }, - "required": [ - "action", - "call_id", - "query", - "type" - ], - "title": "WebSearchEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the server is about to execute a command.", - "properties": { - "call_id": { - "description": "Identifier so this can be paired with the ExecCommandEnd event.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_begin" - ], - "title": "ExecCommandBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "turn_id", - "type" - ], - "title": "ExecCommandBeginEventMsg", - "type": "object" - }, - { - "description": "Incremental chunk of output from a running command.", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "chunk": { - "description": "Raw bytes from the stream (may not be valid UTF-8).", - "type": "string" - }, - "stream": { - "allOf": [ - { - "$ref": "#/definitions/ExecOutputStream" - } - ], - "description": "Which stream produced this chunk." - }, - "type": { - "enum": [ - "exec_command_output_delta" - ], - "title": "ExecCommandOutputDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "chunk", - "stream", - "type" - ], - "title": "ExecCommandOutputDeltaEventMsg", - "type": "object" - }, - { - "description": "Terminal interaction for an in-progress command (stdin sent and stdout observed).", - "properties": { - "call_id": { - "description": "Identifier for the ExecCommandBegin that produced this chunk.", - "type": "string" - }, - "process_id": { - "description": "Process id associated with the running command.", - "type": "string" - }, - "stdin": { - "description": "Stdin sent to the running session.", - "type": "string" - }, - "type": { - "enum": [ - "terminal_interaction" - ], - "title": "TerminalInteractionEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "process_id", - "stdin", - "type" - ], - "title": "TerminalInteractionEventMsg", - "type": "object" - }, - { - "properties": { - "aggregated_output": { - "default": "", - "description": "Captured aggregated output", - "type": "string" - }, - "call_id": { - "description": "Identifier for the ExecCommandBegin that finished.", - "type": "string" - }, - "command": { - "description": "The command that was executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory if not the default cwd for the agent.", - "type": "string" - }, - "duration": { - "allOf": [ - { - "$ref": "#/definitions/Duration" - } - ], - "description": "The duration of the command execution." - }, - "exit_code": { - "description": "The command's exit code.", - "format": "int32", - "type": "integer" - }, - "formatted_output": { - "description": "Formatted output from the command, as seen by the model.", - "type": "string" - }, - "interaction_input": { - "description": "Raw input sent to a unified exec session (if this is an interaction event).", - "type": [ - "string", - "null" - ] - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "process_id": { - "description": "Identifier for the underlying PTY process (when available).", - "type": [ - "string", - "null" - ] - }, - "source": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandSource" - } - ], - "default": "agent", - "description": "Where the command originated. Defaults to Agent for backward compatibility." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/ExecCommandStatus" - } - ], - "description": "Completion status for this command execution." - }, - "stderr": { - "description": "Captured stderr", - "type": "string" - }, - "stdout": { - "description": "Captured stdout", - "type": "string" - }, - "turn_id": { - "description": "Turn ID that this command belongs to.", - "type": "string" - }, - "type": { - "enum": [ - "exec_command_end" - ], - "title": "ExecCommandEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "duration", - "exit_code", - "formatted_output", - "parsed_cmd", - "status", - "stderr", - "stdout", - "turn_id", - "type" - ], - "title": "ExecCommandEndEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent attached a local image via the view_image tool.", - "properties": { - "call_id": { - "description": "Identifier for the originating tool call.", - "type": "string" - }, - "path": { - "description": "Local filesystem path provided to the tool.", - "type": "string" - }, - "type": { - "enum": [ - "view_image_tool_call" - ], - "title": "ViewImageToolCallEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "path", - "type" - ], - "title": "ViewImageToolCallEventMsg", - "type": "object" - }, - { - "properties": { - "approval_id": { - "description": "Identifier for this specific approval callback.\n\nWhen absent, the approval is for the command item itself (`call_id`). This is present for subcommand approvals (via execve intercept).", - "type": [ - "string", - "null" - ] - }, - "call_id": { - "description": "Identifier for the associated command execution item.", - "type": "string" - }, - "command": { - "description": "The command to be executed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "cwd": { - "description": "The command's working directory.", - "type": "string" - }, - "network_approval_context": { - "anyOf": [ - { - "$ref": "#/definitions/NetworkApprovalContext" - }, - { - "type": "null" - } - ], - "description": "Optional network context for a blocked request that can be approved." - }, - "parsed_cmd": { - "items": { - "$ref": "#/definitions/ParsedCommand" - }, - "type": "array" - }, - "proposed_execpolicy_amendment": { - "description": "Proposed execpolicy amendment that can be applied to allow future runs.", - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "reason": { - "description": "Optional human-readable reason for the approval (e.g. retry without sandbox).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this command belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "exec_approval_request" - ], - "title": "ExecApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "command", - "cwd", - "parsed_cmd", - "type" - ], - "title": "ExecApprovalRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated tool call, if available.", - "type": "string" - }, - "questions": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestion" - }, - "type": "array" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this request belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "request_user_input" - ], - "title": "RequestUserInputEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "questions", - "type" - ], - "title": "RequestUserInputEventMsg", - "type": "object" - }, - { - "properties": { - "arguments": true, - "callId": { - "type": "string" - }, - "tool": { - "type": "string" - }, - "turnId": { - "type": "string" - }, - "type": { - "enum": [ - "dynamic_tool_call_request" - ], - "title": "DynamicToolCallRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "arguments", - "callId", - "tool", - "turnId", - "type" - ], - "title": "DynamicToolCallRequestEventMsg", - "type": "object" - }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "message": { - "type": "string" - }, - "server_name": { - "type": "string" - }, - "type": { - "enum": [ - "elicitation_request" - ], - "title": "ElicitationRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "message", - "server_name", - "type" - ], - "title": "ElicitationRequestEventMsg", - "type": "object" - }, - { - "properties": { - "call_id": { - "description": "Responses API call id for the associated patch apply call, if available.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "type": "object" - }, - "grant_root": { - "description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session.", - "type": [ - "string", - "null" - ] - }, - "reason": { - "description": "Optional explanatory reason (e.g. request for extra write access).", - "type": [ - "string", - "null" - ] - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility with older senders.", - "type": "string" - }, - "type": { - "enum": [ - "apply_patch_approval_request" - ], - "title": "ApplyPatchApprovalRequestEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "changes", - "type" - ], - "title": "ApplyPatchApprovalRequestEventMsg", - "type": "object" - }, - { - "description": "Notification advising the user that something they are using has been deprecated and should be phased out.", - "properties": { - "details": { - "description": "Optional extra guidance, such as migration steps or rationale.", - "type": [ - "string", - "null" - ] - }, - "summary": { - "description": "Concise summary of what is deprecated.", - "type": "string" - }, - "type": { - "enum": [ - "deprecation_notice" - ], - "title": "DeprecationNoticeEventMsgType", - "type": "string" - } - }, - "required": [ - "summary", - "type" - ], - "title": "DeprecationNoticeEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": "string" - }, - "type": { - "enum": [ - "background_event" - ], - "title": "BackgroundEventEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "BackgroundEventEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "undo_started" - ], - "title": "UndoStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UndoStartedEventMsg", - "type": "object" - }, - { - "properties": { - "message": { - "type": [ - "string", - "null" - ] - }, - "success": { - "type": "boolean" - }, - "type": { - "enum": [ - "undo_completed" - ], - "title": "UndoCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "success", - "type" - ], - "title": "UndoCompletedEventMsg", - "type": "object" - }, - { - "description": "Notification that a model stream experienced an error or disconnect and the system is handling it (e.g., retrying with backoff).", - "properties": { - "additional_details": { - "default": null, - "description": "Optional details about the underlying stream failure (often the same human-readable message that is surfaced as the terminal error if retries are exhausted).", - "type": [ - "string", - "null" - ] - }, - "codex_error_info": { - "anyOf": [ - { - "$ref": "#/definitions/CodexErrorInfo" - }, - { - "type": "null" - } - ], - "default": null - }, - "message": { - "type": "string" - }, - "type": { - "enum": [ - "stream_error" - ], - "title": "StreamErrorEventMsgType", - "type": "string" - } - }, - "required": [ - "message", - "type" - ], - "title": "StreamErrorEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is about to apply a code patch. Mirrors `ExecCommandBegin` so front‑ends can show progress indicators.", - "properties": { - "auto_approved": { - "description": "If true, there was no ApplyPatchApprovalRequest for this patch.", - "type": "boolean" - }, - "call_id": { - "description": "Identifier so this can be paired with the PatchApplyEnd event.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "description": "The changes to be applied.", - "type": "object" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_begin" - ], - "title": "PatchApplyBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "auto_approved", - "call_id", - "changes", - "type" - ], - "title": "PatchApplyBeginEventMsg", - "type": "object" - }, - { - "description": "Notification that a patch application has finished.", - "properties": { - "call_id": { - "description": "Identifier for the PatchApplyBegin that finished.", - "type": "string" - }, - "changes": { - "additionalProperties": { - "$ref": "#/definitions/FileChange" - }, - "default": {}, - "description": "The changes that were applied (mirrors PatchApplyBeginEvent::changes).", - "type": "object" - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/PatchApplyStatus" - } - ], - "description": "Completion status for this patch application." - }, - "stderr": { - "description": "Captured stderr (parser errors, IO failures, etc.).", - "type": "string" - }, - "stdout": { - "description": "Captured stdout (summary printed by apply_patch).", - "type": "string" - }, - "success": { - "description": "Whether the patch was applied successfully.", - "type": "boolean" - }, - "turn_id": { - "default": "", - "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", - "type": "string" - }, - "type": { - "enum": [ - "patch_apply_end" - ], - "title": "PatchApplyEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "status", - "stderr", - "stdout", - "success", - "type" - ], - "title": "PatchApplyEndEventMsg", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "turn_diff" - ], - "title": "TurnDiffEventMsgType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "TurnDiffEventMsg", - "type": "object" - }, - { - "description": "Response to GetHistoryEntryRequest.", - "properties": { - "entry": { - "anyOf": [ - { - "$ref": "#/definitions/HistoryEntry" - }, - { - "type": "null" - } - ], - "description": "The entry at the requested offset, if available and parseable." - }, - "log_id": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "offset": { - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "type": { - "enum": [ - "get_history_entry_response" - ], - "title": "GetHistoryEntryResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "log_id", - "offset", - "type" - ], - "title": "GetHistoryEntryResponseEventMsg", - "type": "object" - }, - { - "description": "List of MCP tools available to the agent.", - "properties": { - "auth_statuses": { - "additionalProperties": { - "$ref": "#/definitions/McpAuthStatus" - }, - "description": "Authentication status for each configured MCP server.", - "type": "object" - }, - "resource_templates": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/ResourceTemplate" - }, - "type": "array" - }, - "description": "Known resource templates grouped by server name.", - "type": "object" - }, - "resources": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/Resource" - }, - "type": "array" - }, - "description": "Known resources grouped by server name.", - "type": "object" - }, - "tools": { - "additionalProperties": { - "$ref": "#/definitions/Tool" - }, - "description": "Fully qualified tool name -> tool definition.", - "type": "object" - }, - "type": { - "enum": [ - "mcp_list_tools_response" - ], - "title": "McpListToolsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "auth_statuses", - "resource_templates", - "resources", - "tools", - "type" - ], - "title": "McpListToolsResponseEventMsg", - "type": "object" - }, - { - "description": "List of custom prompts available to the agent.", - "properties": { - "custom_prompts": { - "items": { - "$ref": "#/definitions/CustomPrompt" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_custom_prompts_response" - ], - "title": "ListCustomPromptsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "custom_prompts", - "type" - ], - "title": "ListCustomPromptsResponseEventMsg", - "type": "object" - }, - { - "description": "List of skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/SkillsListEntry" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_skills_response" - ], - "title": "ListSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "List of remote skills available to the agent.", - "properties": { - "skills": { - "items": { - "$ref": "#/definitions/RemoteSkillSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "list_remote_skills_response" - ], - "title": "ListRemoteSkillsResponseEventMsgType", - "type": "string" - } - }, - "required": [ - "skills", - "type" - ], - "title": "ListRemoteSkillsResponseEventMsg", - "type": "object" - }, - { - "description": "Remote skill downloaded to local cache.", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "remote_skill_downloaded" - ], - "title": "RemoteSkillDownloadedEventMsgType", - "type": "string" - } - }, - "required": [ - "id", - "name", - "path", - "type" - ], - "title": "RemoteSkillDownloadedEventMsg", - "type": "object" - }, - { - "description": "Notification that skill data may have been updated and clients may want to reload.", - "properties": { - "type": { - "enum": [ - "skills_update_available" - ], - "title": "SkillsUpdateAvailableEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SkillsUpdateAvailableEventMsg", - "type": "object" - }, - { - "properties": { - "explanation": { - "default": null, - "description": "Arguments for the `update_plan` todo/checklist tool (not plan mode).", - "type": [ - "string", - "null" - ] - }, - "plan": { - "items": { - "$ref": "#/definitions/PlanItemArg" - }, - "type": "array" - }, - "type": { - "enum": [ - "plan_update" - ], - "title": "PlanUpdateEventMsgType", - "type": "string" - } - }, - "required": [ - "plan", - "type" - ], - "title": "PlanUpdateEventMsg", - "type": "object" - }, - { - "properties": { - "reason": { - "$ref": "#/definitions/TurnAbortReason" - }, - "turn_id": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "turn_aborted" - ], - "title": "TurnAbortedEventMsgType", - "type": "string" - } - }, - "required": [ - "reason", - "type" - ], - "title": "TurnAbortedEventMsg", - "type": "object" - }, - { - "description": "Notification that the agent is shutting down.", - "properties": { - "type": { - "enum": [ - "shutdown_complete" - ], - "title": "ShutdownCompleteEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ShutdownCompleteEventMsg", - "type": "object" - }, - { - "description": "Entered review mode.", - "properties": { - "target": { - "$ref": "#/definitions/ReviewTarget" - }, - "type": { - "enum": [ - "entered_review_mode" - ], - "title": "EnteredReviewModeEventMsgType", - "type": "string" - }, - "user_facing_hint": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "target", - "type" - ], - "title": "EnteredReviewModeEventMsg", - "type": "object" - }, - { - "description": "Exited review mode with an optional final result to apply.", - "properties": { - "review_output": { - "anyOf": [ - { - "$ref": "#/definitions/ReviewOutputEvent" - }, - { - "type": "null" - } - ] - }, - "type": { - "enum": [ - "exited_review_mode" - ], - "title": "ExitedReviewModeEventMsgType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExitedReviewModeEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/ResponseItem" - }, - "type": { - "enum": [ - "raw_response_item" - ], - "title": "RawResponseItemEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "type" - ], - "title": "RawResponseItemEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_started" - ], - "title": "ItemStartedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemStartedEventMsg", - "type": "object" - }, - { - "properties": { - "item": { - "$ref": "#/definitions/TurnItem" - }, - "thread_id": { - "$ref": "#/definitions/ThreadId" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "item_completed" - ], - "title": "ItemCompletedEventMsgType", - "type": "string" - } - }, - "required": [ - "item", - "thread_id", - "turn_id", - "type" - ], - "title": "ItemCompletedEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "agent_message_content_delta" - ], - "title": "AgentMessageContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "AgentMessageContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "plan_delta" - ], - "title": "PlanDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "PlanDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "summary_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_content_delta" - ], - "title": "ReasoningContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningContentDeltaEventMsg", - "type": "object" - }, - { - "properties": { - "content_index": { - "default": 0, - "format": "int64", - "type": "integer" - }, - "delta": { - "type": "string" - }, - "item_id": { - "type": "string" - }, - "thread_id": { - "type": "string" - }, - "turn_id": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_raw_content_delta" - ], - "title": "ReasoningRawContentDeltaEventMsgType", - "type": "string" - } - }, - "required": [ - "delta", - "item_id", - "thread_id", - "turn_id", - "type" - ], - "title": "ReasoningRawContentDeltaEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_spawn_begin" - ], - "title": "CollabAgentSpawnBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "type" - ], - "title": "CollabAgentSpawnBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent spawn end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "new_agent_nickname": { - "description": "Optional nickname assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_agent_role": { - "description": "Optional role assigned to the new agent.", - "type": [ - "string", - "null" - ] - }, - "new_thread_id": { - "anyOf": [ - { - "$ref": "#/definitions/ThreadId" - }, - { - "type": "null" - } - ], - "description": "Thread ID of the newly spawned agent, if it was created." - }, - "prompt": { - "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the new agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_spawn_end" - ], - "title": "CollabAgentSpawnEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentSpawnEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_agent_interaction_begin" - ], - "title": "CollabAgentInteractionBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabAgentInteractionBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: agent interaction end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "prompt": { - "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent." - }, - "type": { - "enum": [ - "collab_agent_interaction_end" - ], - "title": "CollabAgentInteractionEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "prompt", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabAgentInteractionEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting begin.", - "properties": { - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "receiver_agents": { - "description": "Optional nicknames/roles for receivers.", - "items": { - "$ref": "#/definitions/CollabAgentRef" - }, - "type": "array" - }, - "receiver_thread_ids": { - "description": "Thread ID of the receivers.", - "items": { - "$ref": "#/definitions/ThreadId" - }, - "type": "array" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_waiting_begin" - ], - "title": "CollabWaitingBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_ids", - "sender_thread_id", - "type" - ], - "title": "CollabWaitingBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: waiting end.", - "properties": { - "agent_statuses": { - "description": "Optional receiver metadata paired with final statuses.", - "items": { - "$ref": "#/definitions/CollabAgentStatusEntry" - }, - "type": "array" - }, - "call_id": { - "description": "ID of the waiting call.", - "type": "string" - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "statuses": { - "additionalProperties": { - "$ref": "#/definitions/AgentStatus" - }, - "description": "Last known status of the receiver agents reported to the sender agent.", - "type": "object" - }, - "type": { - "enum": [ - "collab_waiting_end" - ], - "title": "CollabWaitingEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "sender_thread_id", - "statuses", - "type" - ], - "title": "CollabWaitingEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_close_begin" - ], - "title": "CollabCloseBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabCloseBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: close end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent before the close." - }, - "type": { - "enum": [ - "collab_close_end" - ], - "title": "CollabCloseEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabCloseEndEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume begin.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "type": { - "enum": [ - "collab_resume_begin" - ], - "title": "CollabResumeBeginEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "type" - ], - "title": "CollabResumeBeginEventMsg", - "type": "object" - }, - { - "description": "Collab interaction: resume end.", - "properties": { - "call_id": { - "description": "Identifier for the collab tool call.", - "type": "string" - }, - "receiver_agent_nickname": { - "description": "Optional nickname assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_agent_role": { - "description": "Optional role assigned to the receiver agent.", - "type": [ - "string", - "null" - ] - }, - "receiver_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the receiver." - }, - "sender_thread_id": { - "allOf": [ - { - "$ref": "#/definitions/ThreadId" - } - ], - "description": "Thread ID of the sender." - }, - "status": { - "allOf": [ - { - "$ref": "#/definitions/AgentStatus" - } - ], - "description": "Last known status of the receiver agent reported to the sender agent after resume." - }, - "type": { - "enum": [ - "collab_resume_end" - ], - "title": "CollabResumeEndEventMsgType", - "type": "string" - } - }, - "required": [ - "call_id", - "receiver_thread_id", - "sender_thread_id", - "status", - "type" - ], - "title": "CollabResumeEndEventMsg", - "type": "object" - } - ] - }, - "ExecCommandSource": { - "enum": [ - "agent", - "user_shell", - "unified_exec_startup", - "unified_exec_interaction" - ], - "type": "string" - }, - "ExecCommandStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, - "ExecOutputStream": { - "enum": [ - "stdout", - "stderr" - ], - "type": "string" - }, - "FileChange": { - "oneOf": [ - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "add" - ], - "title": "AddFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "AddFileChange", - "type": "object" - }, - { - "properties": { - "content": { - "type": "string" - }, - "type": { - "enum": [ - "delete" - ], - "title": "DeleteFileChangeType", - "type": "string" - } - }, - "required": [ - "content", - "type" - ], - "title": "DeleteFileChange", - "type": "object" - }, - { - "properties": { - "move_path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "update" - ], - "title": "UpdateFileChangeType", - "type": "string" - }, - "unified_diff": { - "type": "string" - } - }, - "required": [ - "type", - "unified_diff" - ], - "title": "UpdateFileChange", - "type": "object" - } - ] - }, - "FunctionCallOutputBody": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "$ref": "#/definitions/FunctionCallOutputContentItem" - }, - "type": "array" - } - ] - }, - "FunctionCallOutputContentItem": { - "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "input_text" - ], - "title": "InputTextFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextFunctionCallOutputContentItem", - "type": "object" - }, - { - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "input_image" - ], - "title": "InputImageFunctionCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "InputImageFunctionCallOutputContentItem", - "type": "object" - } - ] - }, - "FunctionCallOutputPayload": { - "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", - "properties": { - "body": { - "$ref": "#/definitions/FunctionCallOutputBody" - }, - "success": { - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "body" - ], - "type": "object" - }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, - "HistoryEntry": { - "properties": { - "conversation_id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "ts": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "conversation_id", - "text", - "ts" - ], - "type": "object" - }, - "LocalShellAction": { - "oneOf": [ - { - "properties": { - "command": { - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "type": [ - "object", - "null" - ] - }, - "timeout_ms": { - "format": "uint64", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - }, - "type": { - "enum": [ - "exec" - ], - "title": "ExecLocalShellActionType", - "type": "string" - }, - "user": { - "type": [ - "string", - "null" - ] - }, - "working_directory": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "command", - "type" - ], - "title": "ExecLocalShellAction", - "type": "object" - } - ] - }, - "LocalShellStatus": { - "enum": [ - "completed", - "in_progress", - "incomplete" - ], - "type": "string" - }, - "McpAuthStatus": { - "enum": [ - "unsupported", - "not_logged_in", - "bearer_token", - "o_auth" - ], - "type": "string" - }, - "McpInvocation": { - "properties": { - "arguments": { - "description": "Arguments to the tool call." - }, - "server": { - "description": "Name of the MCP server as defined in the config.", - "type": "string" - }, - "tool": { - "description": "Name of the tool as given by the MCP server.", - "type": "string" - } - }, - "required": [ - "server", - "tool" - ], - "type": "object" - }, - "McpStartupFailure": { - "properties": { - "error": { - "type": "string" - }, - "server": { - "type": "string" - } - }, - "required": [ - "error", - "server" - ], - "type": "object" - }, - "McpStartupStatus": { - "oneOf": [ - { - "properties": { - "state": { - "enum": [ - "starting" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus", - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "ready" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus2", - "type": "object" - }, - { - "properties": { - "error": { - "type": "string" - }, - "state": { - "enum": [ - "failed" - ], - "type": "string" - } - }, - "required": [ - "error", - "state" - ], - "type": "object" - }, - { - "properties": { - "state": { - "enum": [ - "cancelled" - ], - "type": "string" - } - }, - "required": [ - "state" - ], - "title": "StateMcpStartupStatus3", - "type": "object" - } - ] - }, - "MessagePhase": { - "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", - "oneOf": [ - { - "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", - "enum": [ - "commentary" - ], - "type": "string" - }, - { - "description": "The assistant's terminal answer text for the current turn.", - "enum": [ - "final_answer" - ], - "type": "string" - } - ] - }, - "ModeKind": { - "description": "Initial collaboration mode to use when the TUI starts.", - "enum": [ - "plan", - "default" - ], - "type": "string" - }, - "ModelRerouteReason": { - "enum": [ - "high_risk_cyber_activity" - ], - "type": "string" - }, - "NetworkAccess": { - "description": "Represents whether outbound network access is available to the agent.", - "enum": [ - "restricted", - "enabled" - ], - "type": "string" - }, - "NetworkApprovalContext": { - "properties": { - "host": { - "type": "string" - }, - "protocol": { - "$ref": "#/definitions/NetworkApprovalProtocol" - } - }, - "required": [ - "host", - "protocol" - ], - "type": "object" - }, - "NetworkApprovalProtocol": { - "enum": [ - "http", - "https", - "socks5_tcp", - "socks5_udp" - ], - "type": "string" - }, - "ParsedCommand": { - "oneOf": [ - { - "properties": { - "cmd": { - "type": "string" - }, - "name": { - "type": "string" - }, - "path": { - "description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", - "type": "string" - }, - "type": { - "enum": [ - "read" - ], - "title": "ReadParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "name", - "path", - "type" - ], - "title": "ReadParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "list_files" - ], - "title": "ListFilesParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "ListFilesParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "path": { - "type": [ - "string", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "SearchParsedCommand", - "type": "object" - }, - { - "properties": { - "cmd": { - "type": "string" - }, - "type": { - "enum": [ - "unknown" - ], - "title": "UnknownParsedCommandType", - "type": "string" - } - }, - "required": [ - "cmd", - "type" - ], - "title": "UnknownParsedCommand", - "type": "object" - } - ] - }, - "PatchApplyStatus": { - "enum": [ - "completed", - "failed", - "declined" - ], - "type": "string" - }, - "PlanItemArg": { - "additionalProperties": false, - "properties": { - "status": { - "$ref": "#/definitions/StepStatus" - }, - "step": { - "type": "string" - } - }, - "required": [ - "status", - "step" - ], - "type": "object" - }, - "PlanType": { - "enum": [ - "free", - "go", - "plus", - "pro", - "team", - "business", - "enterprise", - "edu", - "unknown" - ], - "type": "string" - }, - "RateLimitSnapshot": { - "properties": { - "credits": { - "anyOf": [ - { - "$ref": "#/definitions/CreditsSnapshot" - }, - { - "type": "null" - } - ] - }, - "limit_id": { - "type": [ - "string", - "null" - ] - }, - "limit_name": { - "type": [ - "string", - "null" - ] - }, - "plan_type": { - "anyOf": [ - { - "$ref": "#/definitions/PlanType" - }, - { - "type": "null" - } - ] - }, - "primary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - }, - "secondary": { - "anyOf": [ - { - "$ref": "#/definitions/RateLimitWindow" - }, - { - "type": "null" - } - ] - } - }, - "type": "object" - }, - "RateLimitWindow": { - "properties": { - "resets_at": { - "description": "Unix timestamp (seconds since epoch) when the window resets.", - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "used_percent": { - "description": "Percentage (0-100) of the window that has been consumed.", - "format": "double", - "type": "number" - }, - "window_minutes": { - "description": "Rolling window duration, in minutes.", - "format": "int64", - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "used_percent" - ], - "type": "object" - }, - "ReadOnlyAccess": { - "description": "Determines how read-only file access is granted inside a restricted sandbox.", - "oneOf": [ - { - "description": "Restrict reads to an explicit set of roots.\n\nWhen `include_platform_defaults` is `true`, platform defaults required for basic execution are included in addition to `readable_roots`.", - "properties": { - "include_platform_defaults": { - "default": true, - "description": "Include built-in platform read roots required for basic process execution.", - "type": "boolean" - }, - "readable_roots": { - "description": "Additional absolute roots that should be readable.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - }, - "type": { - "enum": [ - "restricted" - ], - "title": "RestrictedReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "RestrictedReadOnlyAccess", - "type": "object" - }, - { - "description": "Allow unrestricted file reads.", - "properties": { - "type": { - "enum": [ - "full-access" - ], - "title": "FullAccessReadOnlyAccessType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "FullAccessReadOnlyAccess", - "type": "object" - } - ] - }, - "RealtimeAudioFrame": { - "properties": { - "data": { - "type": "string" - }, - "num_channels": { - "format": "uint16", - "minimum": 0.0, - "type": "integer" - }, - "sample_rate": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "samples_per_channel": { - "format": "uint32", - "minimum": 0.0, - "type": [ - "integer", - "null" - ] - } - }, - "required": [ - "data", - "num_channels", - "sample_rate" - ], - "type": "object" - }, - "RealtimeEvent": { - "oneOf": [ - { - "additionalProperties": false, - "properties": { - "SessionCreated": { - "properties": { - "session_id": { - "type": "string" - } - }, - "required": [ - "session_id" - ], - "type": "object" - } - }, - "required": [ - "SessionCreated" - ], - "title": "SessionCreatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "SessionUpdated": { - "properties": { - "backend_prompt": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - } - }, - "required": [ - "SessionUpdated" - ], - "title": "SessionUpdatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "AudioOut": { - "$ref": "#/definitions/RealtimeAudioFrame" - } - }, - "required": [ - "AudioOut" - ], - "title": "AudioOutRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "ConversationItemAdded": true - }, - "required": [ - "ConversationItemAdded" - ], - "title": "ConversationItemAddedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "Error": { - "type": "string" - } - }, - "required": [ - "Error" - ], - "title": "ErrorRealtimeEvent", - "type": "object" - } - ] - }, - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - }, - "ReasoningItemContent": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "reasoning_text" - ], - "title": "ReasoningTextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "ReasoningTextReasoningItemContent", - "type": "object" - }, - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextReasoningItemContentType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextReasoningItemContent", - "type": "object" - } - ] - }, - "ReasoningItemReasoningSummary": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "summary_text" - ], - "title": "SummaryTextReasoningItemReasoningSummaryType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "SummaryTextReasoningItemReasoningSummary", - "type": "object" - } - ] - }, - "RejectConfig": { - "properties": { - "mcp_elicitations": { - "description": "Reject MCP elicitation prompts.", - "type": "boolean" - }, - "rules": { - "description": "Reject prompts triggered by execpolicy `prompt` rules.", - "type": "boolean" - }, - "sandbox_approval": { - "description": "Reject approval prompts related to sandbox escalation.", - "type": "boolean" - } - }, - "required": [ - "mcp_elicitations", - "rules", - "sandbox_approval" - ], - "type": "object" - }, - "RemoteSkillSummary": { - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "description", - "id", - "name" - ], - "type": "object" - }, - "RequestId": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "int64", - "type": "integer" - } - ], - "description": "ID of a request, which can be either a string or an integer." - }, - "RequestUserInputQuestion": { - "properties": { - "header": { - "type": "string" - }, - "id": { - "type": "string" - }, - "isOther": { - "default": false, - "type": "boolean" - }, - "isSecret": { - "default": false, - "type": "boolean" - }, - "options": { - "items": { - "$ref": "#/definitions/RequestUserInputQuestionOption" - }, - "type": [ - "array", - "null" - ] - }, - "question": { - "type": "string" - } - }, - "required": [ - "header", - "id", - "question" - ], - "type": "object" - }, - "RequestUserInputQuestionOption": { - "properties": { - "description": { - "type": "string" - }, - "label": { - "type": "string" - } - }, - "required": [ - "description", - "label" - ], - "type": "object" - }, - "Resource": { - "description": "A known resource that the server is capable of reading.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "size": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uri": { - "type": "string" - } - }, - "required": [ - "name", - "uri" - ], - "type": "object" - }, - "ResourceTemplate": { - "description": "A template description for resources available on the server.", - "properties": { - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "mimeType": { - "type": [ - "string", - "null" - ] - }, - "name": { - "type": "string" - }, - "title": { - "type": [ - "string", - "null" - ] - }, - "uriTemplate": { - "type": "string" - } - }, - "required": [ - "name", - "uriTemplate" - ], - "type": "object" - }, - "ResponseItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/ContentItem" - }, - "type": "array" - }, - "end_turn": { - "type": [ - "boolean", - "null" - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ] - }, - "role": { - "type": "string" - }, - "type": { - "enum": [ - "message" - ], - "title": "MessageResponseItemType", - "type": "string" - } - }, - "required": [ - "content", - "role", - "type" - ], - "title": "MessageResponseItem", - "type": "object" - }, - { - "properties": { - "content": { - "default": null, - "items": { - "$ref": "#/definitions/ReasoningItemContent" - }, - "type": [ - "array", - "null" - ] - }, - "encrypted_content": { - "type": [ - "string", - "null" - ] - }, - "id": { - "type": "string", - "writeOnly": true - }, - "summary": { - "items": { - "$ref": "#/definitions/ReasoningItemReasoningSummary" - }, - "type": "array" - }, - "type": { - "enum": [ - "reasoning" - ], - "title": "ReasoningResponseItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary", - "type" - ], - "title": "ReasoningResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/LocalShellAction" - }, - "call_id": { - "description": "Set when using the Responses API.", - "type": [ - "string", - "null" - ] - }, - "id": { - "description": "Legacy id field retained for compatibility with older payloads.", - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "$ref": "#/definitions/LocalShellStatus" - }, - "type": { - "enum": [ - "local_shell_call" - ], - "title": "LocalShellCallResponseItemType", - "type": "string" - } - }, - "required": [ - "action", - "status", - "type" - ], - "title": "LocalShellCallResponseItem", - "type": "object" - }, - { - "properties": { - "arguments": { - "type": "string" - }, - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "name": { - "type": "string" - }, - "type": { - "enum": [ - "function_call" - ], - "title": "FunctionCallResponseItemType", - "type": "string" - } - }, - "required": [ - "arguments", - "call_id", - "name", - "type" - ], - "title": "FunctionCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "$ref": "#/definitions/FunctionCallOutputPayload" - }, - "type": { - "enum": [ - "function_call_output" - ], - "title": "FunctionCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "FunctionCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "input": { - "type": "string" - }, - "name": { - "type": "string" - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "custom_tool_call" - ], - "title": "CustomToolCallResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "input", - "name", - "type" - ], - "title": "CustomToolCallResponseItem", - "type": "object" - }, - { - "properties": { - "call_id": { - "type": "string" - }, - "output": { - "type": "string" - }, - "type": { - "enum": [ - "custom_tool_call_output" - ], - "title": "CustomToolCallOutputResponseItemType", - "type": "string" - } - }, - "required": [ - "call_id", - "output", - "type" - ], - "title": "CustomToolCallOutputResponseItem", - "type": "object" - }, - { - "properties": { - "action": { - "anyOf": [ - { - "$ref": "#/definitions/WebSearchAction" - }, - { - "type": "null" - } - ] - }, - "id": { - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "status": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "web_search_call" - ], - "title": "WebSearchCallResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "WebSearchCallResponseItem", - "type": "object" - }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, - { - "properties": { - "encrypted_content": { - "type": "string" - }, - "type": { - "enum": [ - "compaction" - ], - "title": "CompactionResponseItemType", - "type": "string" - } - }, - "required": [ - "encrypted_content", - "type" - ], - "title": "CompactionResponseItem", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherResponseItemType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherResponseItem", - "type": "object" - } - ] - }, - "Result_of_CallToolResult_or_String": { - "oneOf": [ - { - "properties": { - "Ok": { - "$ref": "#/definitions/CallToolResult" - } - }, - "required": [ - "Ok" - ], - "title": "OkResult_of_CallToolResult_or_String", - "type": "object" - }, - { - "properties": { - "Err": { - "type": "string" - } - }, - "required": [ - "Err" - ], - "title": "ErrResult_of_CallToolResult_or_String", - "type": "object" - } - ] - }, - "ReviewCodeLocation": { - "description": "Location of the code related to a review finding.", - "properties": { - "absolute_file_path": { - "type": "string" - }, - "line_range": { - "$ref": "#/definitions/ReviewLineRange" - } - }, - "required": [ - "absolute_file_path", - "line_range" - ], - "type": "object" - }, - "ReviewFinding": { - "description": "A single review finding describing an observed issue or recommendation.", - "properties": { - "body": { - "type": "string" - }, - "code_location": { - "$ref": "#/definitions/ReviewCodeLocation" - }, - "confidence_score": { - "format": "float", - "type": "number" - }, - "priority": { - "format": "int32", - "type": "integer" - }, - "title": { - "type": "string" - } - }, - "required": [ - "body", - "code_location", - "confidence_score", - "priority", - "title" - ], - "type": "object" - }, - "ReviewLineRange": { - "description": "Inclusive line range in a file associated with the finding.", - "properties": { - "end": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - }, - "start": { - "format": "uint32", - "minimum": 0.0, - "type": "integer" - } - }, - "required": [ - "end", - "start" - ], - "type": "object" - }, - "ReviewOutputEvent": { - "description": "Structured review result produced by a child review session.", - "properties": { - "findings": { - "items": { - "$ref": "#/definitions/ReviewFinding" - }, - "type": "array" - }, - "overall_confidence_score": { - "format": "float", - "type": "number" - }, - "overall_correctness": { - "type": "string" - }, - "overall_explanation": { - "type": "string" - } - }, - "required": [ - "findings", - "overall_confidence_score", - "overall_correctness", - "overall_explanation" - ], - "type": "object" - }, - "ReviewTarget": { - "oneOf": [ - { - "description": "Review the working tree: staged, unstaged, and untracked files.", - "properties": { - "type": { - "enum": [ - "uncommittedChanges" - ], - "title": "UncommittedChangesReviewTargetType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "UncommittedChangesReviewTarget", - "type": "object" - }, - { - "description": "Review changes between the current branch and the given base branch.", - "properties": { - "branch": { - "type": "string" - }, - "type": { - "enum": [ - "baseBranch" - ], - "title": "BaseBranchReviewTargetType", - "type": "string" - } - }, - "required": [ - "branch", - "type" - ], - "title": "BaseBranchReviewTarget", - "type": "object" - }, - { - "description": "Review the changes introduced by a specific commit.", - "properties": { - "sha": { - "type": "string" - }, - "title": { - "description": "Optional human-readable label (e.g., commit subject) for UIs.", - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "commit" - ], - "title": "CommitReviewTargetType", - "type": "string" - } - }, - "required": [ - "sha", - "type" - ], - "title": "CommitReviewTarget", - "type": "object" - }, - { - "description": "Arbitrary instructions provided by the user.", - "properties": { - "instructions": { - "type": "string" - }, - "type": { - "enum": [ - "custom" - ], - "title": "CustomReviewTargetType", - "type": "string" - } - }, - "required": [ - "instructions", - "type" - ], - "title": "CustomReviewTarget", - "type": "object" - } - ] - }, - "SandboxPolicy": { - "description": "Determines execution restrictions for model shell commands.", - "oneOf": [ - { - "description": "No restrictions whatsoever. Use with caution.", - "properties": { - "type": { - "enum": [ - "danger-full-access" - ], - "title": "DangerFullAccessSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "DangerFullAccessSandboxPolicy", - "type": "object" - }, - { - "description": "Read-only access configuration.", - "properties": { - "access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "read-only" - ], - "title": "ReadOnlySandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ReadOnlySandboxPolicy", - "type": "object" - }, - { - "description": "Indicates the process is already in an external sandbox. Allows full disk access while honoring the provided network setting.", - "properties": { - "network_access": { - "allOf": [ - { - "$ref": "#/definitions/NetworkAccess" - } - ], - "default": "restricted", - "description": "Whether the external sandbox permits outbound network traffic." - }, - "type": { - "enum": [ - "external-sandbox" - ], - "title": "ExternalSandboxSandboxPolicyType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "ExternalSandboxSandboxPolicy", - "type": "object" - }, - { - "description": "Same as `ReadOnly` but additionally grants write access to the current working directory (\"workspace\").", - "properties": { - "exclude_slash_tmp": { - "default": false, - "description": "When set to `true`, will NOT include the `/tmp` among the default writable roots on UNIX. Defaults to `false`.", - "type": "boolean" - }, - "exclude_tmpdir_env_var": { - "default": false, - "description": "When set to `true`, will NOT include the per-user `TMPDIR` environment variable among the default writable roots. Defaults to `false`.", - "type": "boolean" - }, - "network_access": { - "default": false, - "description": "When set to `true`, outbound network access is allowed. `false` by default.", - "type": "boolean" - }, - "read_only_access": { - "allOf": [ - { - "$ref": "#/definitions/ReadOnlyAccess" - } - ], - "description": "Read access granted while running under this policy." - }, - "type": { - "enum": [ - "workspace-write" - ], - "title": "WorkspaceWriteSandboxPolicyType", - "type": "string" - }, - "writable_roots": { - "description": "Additional folders (beyond cwd and possibly TMPDIR) that should be writable from within the sandbox.", - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "WorkspaceWriteSandboxPolicy", - "type": "object" - } - ] - }, - "SessionNetworkProxyRuntime": { - "properties": { - "admin_addr": { - "type": "string" - }, - "http_addr": { - "type": "string" - }, - "socks_addr": { - "type": "string" - } - }, - "required": [ - "admin_addr", - "http_addr", - "socks_addr" - ], - "type": "object" - }, - "SkillDependencies": { - "properties": { - "tools": { - "items": { - "$ref": "#/definitions/SkillToolDependency" - }, - "type": "array" - } - }, - "required": [ - "tools" - ], - "type": "object" - }, - "SkillErrorInfo": { - "properties": { - "message": { - "type": "string" - }, - "path": { - "type": "string" - } - }, - "required": [ - "message", - "path" - ], - "type": "object" - }, - "SkillInterface": { - "properties": { - "brand_color": { - "type": [ - "string", - "null" - ] - }, - "default_prompt": { - "type": [ - "string", - "null" - ] - }, - "display_name": { - "type": [ - "string", - "null" - ] - }, - "icon_large": { - "type": [ - "string", - "null" - ] - }, - "icon_small": { - "type": [ - "string", - "null" - ] - }, - "short_description": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - }, - "SkillMetadata": { - "properties": { - "dependencies": { - "anyOf": [ - { - "$ref": "#/definitions/SkillDependencies" - }, - { - "type": "null" - } - ] - }, - "description": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "interface": { - "anyOf": [ - { - "$ref": "#/definitions/SkillInterface" - }, - { - "type": "null" - } - ] - }, - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "scope": { - "$ref": "#/definitions/SkillScope" - }, - "short_description": { - "description": "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "description", - "enabled", - "name", - "path", - "scope" - ], - "type": "object" - }, - "SkillScope": { - "enum": [ - "user", - "repo", - "system", - "admin" - ], - "type": "string" - }, - "SkillToolDependency": { - "properties": { - "command": { - "type": [ - "string", - "null" - ] - }, - "description": { - "type": [ - "string", - "null" - ] - }, - "transport": { - "type": [ - "string", - "null" - ] - }, - "type": { - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - }, - "value": { - "type": "string" - } - }, - "required": [ - "type", - "value" - ], - "type": "object" - }, - "SkillsListEntry": { - "properties": { - "cwd": { - "type": "string" - }, - "errors": { - "items": { - "$ref": "#/definitions/SkillErrorInfo" - }, - "type": "array" - }, - "skills": { - "items": { - "$ref": "#/definitions/SkillMetadata" - }, - "type": "array" - } - }, - "required": [ - "cwd", - "errors", - "skills" - ], - "type": "object" - }, - "StepStatus": { - "enum": [ - "pending", - "in_progress", - "completed" - ], - "type": "string" - }, - "TextElement": { - "properties": { - "byte_range": { - "allOf": [ - { - "$ref": "#/definitions/ByteRange" - } - ], - "description": "Byte range in the parent `text` buffer that this element occupies." - }, - "placeholder": { - "description": "Optional human-readable placeholder for the element, displayed in the UI.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "byte_range" - ], - "type": "object" - }, - "ThreadId": { - "type": "string" - }, - "TokenUsage": { - "properties": { - "cached_input_tokens": { - "format": "int64", - "type": "integer" - }, - "input_tokens": { - "format": "int64", - "type": "integer" - }, - "output_tokens": { - "format": "int64", - "type": "integer" - }, - "reasoning_output_tokens": { - "format": "int64", - "type": "integer" - }, - "total_tokens": { - "format": "int64", - "type": "integer" - } - }, - "required": [ - "cached_input_tokens", - "input_tokens", - "output_tokens", - "reasoning_output_tokens", - "total_tokens" - ], - "type": "object" - }, - "TokenUsageInfo": { - "properties": { - "last_token_usage": { - "$ref": "#/definitions/TokenUsage" - }, - "model_context_window": { - "format": "int64", - "type": [ - "integer", - "null" - ] - }, - "total_token_usage": { - "$ref": "#/definitions/TokenUsage" - } - }, - "required": [ - "last_token_usage", - "total_token_usage" - ], - "type": "object" - }, - "Tool": { - "description": "Definition for a tool the client can call.", - "properties": { - "_meta": true, - "annotations": true, - "description": { - "type": [ - "string", - "null" - ] - }, - "icons": { - "items": true, - "type": [ - "array", - "null" - ] - }, - "inputSchema": true, - "name": { - "type": "string" - }, - "outputSchema": true, - "title": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "inputSchema", - "name" - ], - "type": "object" - }, - "TurnAbortReason": { - "enum": [ - "interrupted", - "replaced", - "review_ended" - ], - "type": "string" - }, - "TurnItem": { - "oneOf": [ - { - "properties": { - "content": { - "items": { - "$ref": "#/definitions/UserInput" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "type": { - "enum": [ - "UserMessage" - ], - "title": "UserMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "UserMessageTurnItem", - "type": "object" - }, - { - "description": "Assistant-authored message payload used in turn-item streams.\n\n`phase` is optional because not all providers/models emit it. Consumers should use it when present, but retain legacy completion semantics when it is `None`.", - "properties": { - "content": { - "items": { - "$ref": "#/definitions/AgentMessageContent" - }, - "type": "array" - }, - "id": { - "type": "string" - }, - "phase": { - "anyOf": [ - { - "$ref": "#/definitions/MessagePhase" - }, - { - "type": "null" - } - ], - "description": "Optional phase metadata carried through from `ResponseItem::Message`.\n\nThis is currently used by TUI rendering to distinguish mid-turn commentary from a final answer and avoid status-indicator jitter." - }, - "type": { - "enum": [ - "AgentMessage" - ], - "title": "AgentMessageTurnItemType", - "type": "string" - } - }, - "required": [ - "content", - "id", - "type" - ], - "title": "AgentMessageTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "text": { - "type": "string" - }, - "type": { - "enum": [ - "Plan" - ], - "title": "PlanTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "text", - "type" - ], - "title": "PlanTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "raw_content": { - "default": [], - "items": { - "type": "string" - }, - "type": "array" - }, - "summary_text": { - "items": { - "type": "string" - }, - "type": "array" - }, - "type": { - "enum": [ - "Reasoning" - ], - "title": "ReasoningTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "summary_text", - "type" - ], - "title": "ReasoningTurnItem", - "type": "object" - }, - { - "properties": { - "action": { - "$ref": "#/definitions/WebSearchAction" - }, - "id": { - "type": "string" - }, - "query": { - "type": "string" - }, - "type": { - "enum": [ - "WebSearch" - ], - "title": "WebSearchTurnItemType", - "type": "string" - } - }, - "required": [ - "action", - "id", - "query", - "type" - ], - "title": "WebSearchTurnItem", - "type": "object" - }, - { - "properties": { - "id": { - "type": "string" - }, - "type": { - "enum": [ - "ContextCompaction" - ], - "title": "ContextCompactionTurnItemType", - "type": "string" - } - }, - "required": [ - "id", - "type" - ], - "title": "ContextCompactionTurnItem", - "type": "object" - } - ] - }, - "UserInput": { - "description": "User input", - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "text_elements": { - "default": [], - "description": "UI-defined spans within `text` that should be treated as special elements. These are byte ranges into the UTF-8 `text` buffer and are used to render or persist rich input markers (e.g., image placeholders) across history and resume without mutating the literal text.", - "items": { - "$ref": "#/definitions/TextElement" - }, - "type": "array" - }, - "type": { - "enum": [ - "text" - ], - "title": "TextUserInputType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "TextUserInput", - "type": "object" - }, - { - "description": "Pre‑encoded data: URI image.", - "properties": { - "image_url": { - "type": "string" - }, - "type": { - "enum": [ - "image" - ], - "title": "ImageUserInputType", - "type": "string" - } - }, - "required": [ - "image_url", - "type" - ], - "title": "ImageUserInput", - "type": "object" - }, - { - "description": "Local image path provided by the user. This will be converted to an `Image` variant (base64 data URL) during request serialization.", - "properties": { - "path": { - "type": "string" - }, - "type": { - "enum": [ - "local_image" - ], - "title": "LocalImageUserInputType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "LocalImageUserInput", - "type": "object" - }, - { - "description": "Skill selected by the user (name + path to SKILL.md).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "skill" - ], - "title": "SkillUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "SkillUserInput", - "type": "object" - }, - { - "description": "Explicit mention selected by the user (name + app://connector id).", - "properties": { - "name": { - "type": "string" - }, - "path": { - "type": "string" - }, - "type": { - "enum": [ - "mention" - ], - "title": "MentionUserInputType", - "type": "string" - } - }, - "required": [ - "name", - "path", - "type" - ], - "title": "MentionUserInput", - "type": "object" - } - ] - }, - "WebSearchAction": { - "oneOf": [ - { - "properties": { - "queries": { - "items": { - "type": "string" - }, - "type": [ - "array", - "null" - ] - }, - "query": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "search" - ], - "title": "SearchWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "SearchWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "open_page" - ], - "title": "OpenPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "OpenPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "pattern": { - "type": [ - "string", - "null" - ] - }, - "type": { - "enum": [ - "find_in_page" - ], - "title": "FindInPageWebSearchActionType", - "type": "string" - }, - "url": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "type" - ], - "title": "FindInPageWebSearchAction", - "type": "object" - }, - { - "properties": { - "type": { - "enum": [ - "other" - ], - "title": "OtherWebSearchActionType", - "type": "string" - } - }, - "required": [ - "type" - ], - "title": "OtherWebSearchAction", - "type": "object" - } - ] - } - }, - "properties": { - "historyEntryCount": { - "format": "uint", - "minimum": 0.0, - "type": "integer" - }, - "historyLogId": { - "format": "uint64", - "minimum": 0.0, - "type": "integer" - }, - "initialMessages": { - "items": { - "$ref": "#/definitions/EventMsg" - }, - "type": [ - "array", - "null" - ] - }, - "model": { - "type": "string" - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - }, - "rolloutPath": { - "type": "string" - }, - "sessionId": { - "$ref": "#/definitions/ThreadId" - } - }, - "required": [ - "historyEntryCount", - "historyLogId", - "model", - "rolloutPath", - "sessionId" - ], - "title": "SessionConfiguredNotification", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelParams.json b/codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelParams.json deleted file mode 100644 index 3027420212..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelParams.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "ReasoningEffort": { - "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", - "enum": [ - "none", - "minimal", - "low", - "medium", - "high", - "xhigh" - ], - "type": "string" - } - }, - "properties": { - "model": { - "type": [ - "string", - "null" - ] - }, - "reasoningEffort": { - "anyOf": [ - { - "$ref": "#/definitions/ReasoningEffort" - }, - { - "type": "null" - } - ] - } - }, - "title": "SetDefaultModelParams", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelResponse.json b/codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelResponse.json deleted file mode 100644 index bb61dada65..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/SetDefaultModelResponse.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "SetDefaultModelResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v1/UserInfoResponse.json b/codex-rs/app-server-protocol/schema/json/v1/UserInfoResponse.json deleted file mode 100644 index 617f6b6706..0000000000 --- a/codex-rs/app-server-protocol/schema/json/v1/UserInfoResponse.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "allegedUserEmail": { - "type": [ - "string", - "null" - ] - } - }, - "title": "UserInfoResponse", - "type": "object" -} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 1a4edfdf57..b6c8da90ea 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -32,93 +32,41 @@ use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::process::Command; -use std::sync::LazyLock; use ts_rs::TS; const HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n"; const IGNORED_DEFINITIONS: &[&str] = &["Option<()>"]; -static VARIANT_TITLE_COLLISION_OVERRIDES: LazyLock> = - LazyLock::new(|| { - HashMap::from([ - ( - "base=McpStartupStatus|generated=StateMcpStartupStatus|literal:state=ready|only_property=state|required_only=state", - "StateMcpStartupStatus2", - ), - ( - "base=McpStartupStatus|generated=StateMcpStartupStatus|literal:state=cancelled|only_property=state|required_only=state", - "StateMcpStartupStatus3", - ), - ]) - }); -static NUMBERED_DEFINITION_COLLISION_OVERRIDES: LazyLock> = - LazyLock::new(|| { - HashMap::from([ - ( - "schema=ClientRequest|container=definitions|generated=AskForApproval2|base=AskForApproval", - "AskForApproval2", - ), - ( - "schema=ClientRequest|container=definitions|generated=NetworkAccess2|base=NetworkAccess", - "NetworkAccess2", - ), - ( - "schema=ClientRequest|container=definitions|generated=ReadOnlyAccess2|base=ReadOnlyAccess", - "ReadOnlyAccess2", - ), - ( - "schema=ClientRequest|container=definitions|generated=SandboxMode2|base=SandboxMode", - "SandboxMode2", - ), - ( - "schema=ClientRequest|container=definitions|generated=SandboxPolicy2|base=SandboxPolicy", - "SandboxPolicy2", - ), - ( - "schema=ServerNotification|container=definitions|generated=ByteRange2|base=ByteRange", - "ByteRange2", - ), - ( - "schema=ServerNotification|container=definitions|generated=CodexErrorInfo2|base=CodexErrorInfo", - "CodexErrorInfo2", - ), - ( - "schema=ServerNotification|container=definitions|generated=CreditsSnapshot2|base=CreditsSnapshot", - "CreditsSnapshot2", - ), - ( - "schema=ServerNotification|container=definitions|generated=MessagePhase2|base=MessagePhase", - "MessagePhase2", - ), - ( - "schema=ServerNotification|container=definitions|generated=ModelRerouteReason2|base=ModelRerouteReason", - "ModelRerouteReason2", - ), - ( - "schema=ServerNotification|container=definitions|generated=PatchApplyStatus2|base=PatchApplyStatus", - "PatchApplyStatus2", - ), - ( - "schema=ServerNotification|container=definitions|generated=RateLimitSnapshot2|base=RateLimitSnapshot", - "RateLimitSnapshot2", - ), - ( - "schema=ServerNotification|container=definitions|generated=RateLimitWindow2|base=RateLimitWindow", - "RateLimitWindow2", - ), - ( - "schema=ServerNotification|container=definitions|generated=TextElement2|base=TextElement", - "TextElement2", - ), - ( - "schema=ServerNotification|container=definitions|generated=UserInput2|base=UserInput", - "UserInput2", - ), - ( - "schema=ServerNotification|container=definitions|generated=WebSearchAction2|base=WebSearchAction", - "WebSearchAction2", - ), - ]) - }); +const JSON_V1_ALLOWLIST: &[&str] = &["InitializeParams", "InitializeResponse"]; +const V1_CLIENT_REQUEST_METHODS: &[&str] = &[ + "newConversation", + "getConversationSummary", + "listConversations", + "resumeConversation", + "forkConversation", + "archiveConversation", + "sendUserMessage", + "sendUserTurn", + "interruptConversation", + "addConversationListener", + "removeConversationListener", + "gitDiffToRemote", + "loginApiKey", + "loginChatGpt", + "cancelLoginChatGpt", + "logoutChatGpt", + "getAuthStatus", + "getUserSavedConfig", + "setDefaultModel", + "getUserAgent", + "userInfo", + "execOneOffCommand", +]; +const EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON: &[&str] = &[ + "authStatusChange", + "loginChatGptComplete", + "sessionConfigured", + "rawResponseItem/completed", +]; #[derive(Clone)] pub struct GeneratedSchema { @@ -264,6 +212,8 @@ pub fn generate_json_with_experimental(out_dir: &Path, experimental_api: bool) - schemas.extend(export_server_response_schemas(out_dir)?); schemas.extend(export_client_notification_schemas(out_dir)?); schemas.extend(export_server_notification_schemas(out_dir)?); + schemas + .retain(|schema| !schema.in_v1_dir || JSON_V1_ALLOWLIST.contains(&schema.logical_name())); let mut bundle = build_schema_bundle(schemas)?; if !experimental_api { @@ -1031,14 +981,23 @@ where T: JsonSchema, { let file_stem = name.trim(); + let (raw_namespace, logical_name) = split_namespace(file_stem); + let include_in_json_codegen = + raw_namespace != Some("v1") || JSON_V1_ALLOWLIST.contains(&logical_name); let schema = schema_for!(T); let mut schema_value = serde_json::to_value(schema)?; - enforce_numbered_definition_collision_overrides(file_stem, &mut schema_value); - annotate_schema(&mut schema_value, Some(file_stem)); + if include_in_json_codegen { + if file_stem == "ClientRequest" { + strip_v1_client_request_variants_from_json_schema(&mut schema_value); + } else if file_stem == "ServerNotification" { + strip_v1_server_notification_variants_from_json_schema(&mut schema_value); + } + enforce_numbered_definition_collision_overrides(file_stem, &mut schema_value); + annotate_schema(&mut schema_value, Some(file_stem)); + } // If the name looks like a namespaced path (e.g., "v2::Type"), mirror // the TypeScript layout and write to out_dir/v2/Type.json. Otherwise // write alongside the legacy files. - let (raw_namespace, logical_name) = split_namespace(file_stem); let out_path = if let Some(ns) = raw_namespace { let dir = out_dir.join(ns); ensure_dir(&dir)?; @@ -1047,7 +1006,7 @@ where out_dir.join(format!("{file_stem}.json")) }; - if !IGNORED_DEFINITIONS.contains(&logical_name) { + if include_in_json_codegen && !IGNORED_DEFINITIONS.contains(&logical_name) { write_pretty_json(out_path, &schema_value) .with_context(|| format!("Failed to write JSON schema for {file_stem}"))?; } @@ -1066,96 +1025,162 @@ where fn enforce_numbered_definition_collision_overrides(schema_name: &str, schema: &mut Value) { for defs_key in ["definitions", "$defs"] { - let renames = { - let Some(defs) = schema.get(defs_key).and_then(Value::as_object) else { - continue; - }; - collect_numbered_definition_collision_renames(schema_name, defs_key, defs) - }; - - if renames.is_empty() { + let Some(defs) = schema.get(defs_key).and_then(Value::as_object) else { continue; - } - - #[expect(clippy::expect_used)] - let defs = schema - .get_mut(defs_key) - .and_then(Value::as_object_mut) - .expect("definition map should still be present"); - for (old_name, new_name, collision_key) in &renames { - if old_name == new_name { - continue; - } - assert!( - !defs.contains_key(new_name), - "Numbered definition collision override produced duplicate definition {new_name} for {collision_key}", - ); - let schema_value = defs.remove(old_name).unwrap_or_else(|| { - panic!("Missing generated numbered definition {old_name} for {collision_key}") - }); - defs.insert(new_name.clone(), schema_value); - } - - for (old_name, new_name, _) in renames { - if old_name != new_name { - rewrite_named_local_ref(schema, defs_key, &old_name, &new_name); - } - } + }; + detect_numbered_definition_collisions(schema_name, defs_key, defs); } } -fn collect_numbered_definition_collision_renames( +fn strip_v1_client_request_variants_from_json_schema(schema: &mut Value) { + let v1_methods: HashSet<&str> = V1_CLIENT_REQUEST_METHODS.iter().copied().collect(); + strip_method_variants_from_json_schema(schema, &v1_methods); +} + +fn strip_v1_server_notification_variants_from_json_schema(schema: &mut Value) { + let methods: HashSet<&str> = EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON + .iter() + .copied() + .collect(); + strip_method_variants_from_json_schema(schema, &methods); +} + +fn strip_method_variants_from_json_schema(schema: &mut Value, methods_to_remove: &HashSet<&str>) { + { + let Some(root) = schema.as_object_mut() else { + return; + }; + let Some(Value::Array(variants)) = root.get_mut("oneOf") else { + return; + }; + variants.retain(|variant| !is_method_variant_in_set(variant, methods_to_remove)); + } + + let reachable = reachable_local_definitions(schema, "definitions"); + let Some(root) = schema.as_object_mut() else { + return; + }; + if let Some(definitions) = root.get_mut("definitions").and_then(Value::as_object_mut) { + definitions.retain(|name, _| reachable.contains(name)); + } +} + +fn is_method_variant_in_set(value: &Value, methods: &HashSet<&str>) -> bool { + let Value::Object(map) = value else { + return false; + }; + let Some(properties) = map.get("properties").and_then(Value::as_object) else { + return false; + }; + let Some(method_schema) = properties.get("method") else { + return false; + }; + let Some(method) = string_literal(method_schema) else { + return false; + }; + methods.contains(method) +} + +fn reachable_local_definitions(schema: &Value, defs_key: &str) -> HashSet { + let Some(definitions) = schema.get(defs_key).and_then(Value::as_object) else { + return HashSet::new(); + }; + let mut queue: Vec = Vec::new(); + let mut reachable: HashSet = HashSet::new(); + + collect_local_definition_refs_excluding_maps(schema, defs_key, &mut queue, &mut reachable); + + while let Some(name) = queue.pop() { + if let Some(def_schema) = definitions.get(&name) { + collect_local_definition_refs(def_schema, defs_key, &mut queue, &mut reachable); + } + } + reachable +} + +fn collect_local_definition_refs_excluding_maps( + value: &Value, + defs_key: &str, + queue: &mut Vec, + reachable: &mut HashSet, +) { + match value { + Value::Object(map) => { + for (key, child) in map { + if key == defs_key || key == "$defs" || key == "definitions" { + continue; + } + collect_local_definition_refs_excluding_maps(child, defs_key, queue, reachable); + } + } + Value::Array(items) => { + for child in items { + collect_local_definition_refs_excluding_maps(child, defs_key, queue, reachable); + } + } + _ => {} + } + collect_local_definition_ref_here(value, defs_key, queue, reachable); +} + +fn collect_local_definition_refs( + value: &Value, + defs_key: &str, + queue: &mut Vec, + reachable: &mut HashSet, +) { + collect_local_definition_ref_here(value, defs_key, queue, reachable); + match value { + Value::Object(map) => { + for child in map.values() { + collect_local_definition_refs(child, defs_key, queue, reachable); + } + } + Value::Array(items) => { + for child in items { + collect_local_definition_refs(child, defs_key, queue, reachable); + } + } + _ => {} + } +} + +fn collect_local_definition_ref_here( + value: &Value, + defs_key: &str, + queue: &mut Vec, + reachable: &mut HashSet, +) { + let Some(reference) = value + .as_object() + .and_then(|obj| obj.get("$ref")) + .and_then(Value::as_str) + else { + return; + }; + let Some(name) = reference.strip_prefix(&format!("#/{defs_key}/")) else { + return; + }; + let name = name.split('/').next().unwrap_or(name); + if reachable.insert(name.to_string()) { + queue.push(name.to_string()); + } +} + +fn detect_numbered_definition_collisions( schema_name: &str, defs_key: &str, defs: &Map, -) -> Vec<(String, String, String)> { - let mut renames = Vec::new(); - +) { for generated_name in defs.keys() { let base_name = generated_name.trim_end_matches(|c: char| c.is_ascii_digit()); if base_name == generated_name || !defs.contains_key(base_name) { continue; } - let collision_key = format!( - "schema={schema_name}|container={defs_key}|generated={generated_name}|base={base_name}" + panic!( + "Numbered definition naming collision detected: schema={schema_name}|container={defs_key}|generated={generated_name}|base={base_name}" ); - let replacement = NUMBERED_DEFINITION_COLLISION_OVERRIDES - .get(collision_key.as_str()) - .map(|value| (*value).to_string()) - .unwrap_or_else(|| { - panic!("Missing numbered definition collision override for {collision_key}") - }); - renames.push((generated_name.clone(), replacement, collision_key)); - } - - renames -} - -fn rewrite_named_local_ref(value: &mut Value, defs_key: &str, old_name: &str, new_name: &str) { - let direct = format!("#/{defs_key}/{old_name}"); - let prefixed = format!("{direct}/"); - let replacement = format!("#/{defs_key}/{new_name}"); - let replacement_prefixed = format!("{replacement}/"); - match value { - Value::Object(obj) => { - if let Some(Value::String(reference)) = obj.get_mut("$ref") { - if reference == &direct { - *reference = replacement; - } else if let Some(rest) = reference.strip_prefix(&prefixed) { - *reference = format!("{replacement_prefixed}{rest}"); - } - } - for child in obj.values_mut() { - rewrite_named_local_ref(child, defs_key, old_name, new_name); - } - } - Value::Array(items) => { - for child in items { - rewrite_named_local_ref(child, defs_key, old_name, new_name); - } - } - _ => {} } } @@ -1263,7 +1288,11 @@ fn variant_definition_name(base: &str, variant: &Value) -> Option { if props.len() == 1 && let Some(key) = props.keys().next() { - let pascal = to_pascal_case(key); + let pascal = props + .get(key) + .and_then(string_literal) + .map(to_pascal_case) + .unwrap_or_else(|| to_pascal_case(key)); return Some(format!("{pascal}{base}")); } } @@ -1376,20 +1405,11 @@ fn annotate_variant_list(variants: &mut [Value], base: Option<&str>) { && let Some(base_name) = base && let Some(name) = variant_definition_name(base_name, variant) { - let mut candidate = name.clone(); + let candidate = name.clone(); if seen.contains(&candidate) { let collision_key = variant_title_collision_key(base_name, &name, variant); - candidate = VARIANT_TITLE_COLLISION_OVERRIDES - .get(collision_key.as_str()) - .map(|value| (*value).to_string()) - .unwrap_or_else(|| { - panic!( - "Missing variant title collision override for {collision_key} (generated name: {name})" - ) - }); - assert!( - !seen.contains(&candidate), - "Variant title collision override produced duplicate title {candidate} for {collision_key}", + panic!( + "Variant title naming collision detected: {collision_key} (generated name: {name})" ); } if let Some(obj) = variant.as_object_mut() { From a8b4b569fbc92e910a9906178c530fdf4aa9a2ad Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Fri, 20 Feb 2026 22:02:35 -0800 Subject: [PATCH 048/385] fix(core) Filter non-matching prefix rules (#12314) ## Summary `gpt-5.3-codex` really likes to write complicated shell scripts, and suggest a partial prefix_rule that wouldn't actually approve the command. We should only show the `prefix_rule` suggestion from the model if it would actually fully approve the command the user is seeing. This will technically cause more instances of overly-specific suggestions when we fallback, but I think the UX is clearer, particularly when the model doesn't necessarily understand the current limitations of execpolicy parsing. ## Testing - [x] Add unit tests - [x] Add integration tests --- codex-rs/core/src/exec_policy.rs | 113 ++++++++++++++-- codex-rs/core/tests/suite/approvals.rs | 178 +++++++++++++++++++++++++ 2 files changed, 278 insertions(+), 13 deletions(-) diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index f2cedb3f94..52329a255f 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -224,6 +224,9 @@ impl ExecPolicyManager { let requested_amendment = derive_requested_execpolicy_amendment_from_prefix_rule( prefix_rule.as_ref(), &evaluation.matched_rules, + exec_policy.as_ref(), + &commands, + &exec_policy_fallback, ); match evaluation.decision { @@ -592,6 +595,9 @@ fn try_derive_execpolicy_amendment_for_allow_rules( fn derive_requested_execpolicy_amendment_from_prefix_rule( prefix_rule: Option<&Vec>, matched_rules: &[RuleMatch], + exec_policy: &Policy, + commands: &[Vec], + exec_policy_fallback: &impl Fn(&[String]) -> Decision, ) -> Option { let prefix_rule = prefix_rule?; if prefix_rule.is_empty() { @@ -612,7 +618,39 @@ fn derive_requested_execpolicy_amendment_from_prefix_rule( return None; } - Some(ExecPolicyAmendment::new(prefix_rule.clone())) + let amendment = ExecPolicyAmendment::new(prefix_rule.clone()); + if prefix_rule_would_approve_all_commands( + exec_policy, + &amendment.command, + commands, + exec_policy_fallback, + ) { + Some(amendment) + } else { + None + } +} + +fn prefix_rule_would_approve_all_commands( + exec_policy: &Policy, + prefix_rule: &[String], + commands: &[Vec], + exec_policy_fallback: &impl Fn(&[String]) -> Decision, +) -> bool { + let mut policy_with_prefix_rule = exec_policy.clone(); + if policy_with_prefix_rule + .add_prefix_rule(prefix_rule, Decision::Allow) + .is_err() + { + return false; + } + + commands.iter().all(|command| { + policy_with_prefix_rule + .check(command, exec_policy_fallback) + .decision + == Decision::Allow + }) } /// Only return a reason when a policy rule drove the prompt decision. @@ -1125,7 +1163,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") } #[tokio::test] - async fn keeps_requested_amendment_for_heredoc_fallback_prompts() { + async fn drops_requested_amendment_for_heredoc_fallback_prompts_when_it_wont_match() { let command = vec![ "bash".to_string(), "-lc".to_string(), @@ -1147,7 +1185,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") requirement, ExecApprovalRequirement::NeedsApproval { reason: None, - proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(requested_prefix)), + proposed_execpolicy_amendment: None, } ); } @@ -1472,6 +1510,38 @@ prefix_rule( ); } + #[tokio::test] + async fn request_rule_falls_back_when_prefix_rule_does_not_approve_all_commands() { + let command = vec![ + "bash".to_string(), + "-lc".to_string(), + "cargo install cargo-insta && rm -rf /tmp/codex".to_string(), + ]; + let manager = ExecPolicyManager::default(); + + let requirement = manager + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + command: &command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + sandbox_permissions: SandboxPermissions::RequireEscalated, + prefix_rule: Some(vec!["cargo".to_string(), "install".to_string()]), + }) + .await; + + assert_eq!( + requirement, + ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ + "rm".to_string(), + "-rf".to_string(), + "/tmp/codex".to_string(), + ])), + } + ); + } + #[tokio::test] async fn heuristics_apply_when_other_commands_match_policy() { let policy_src = r#"prefix_rule(pattern=["apple"], decision="allow")"#; @@ -1728,11 +1798,28 @@ prefix_rule( ); } + fn derive_requested_execpolicy_amendment_for_test( + prefix_rule: Option<&Vec>, + matched_rules: &[RuleMatch], + ) -> Option { + let commands = prefix_rule + .cloned() + .map(|prefix_rule| vec![prefix_rule]) + .unwrap_or_else(|| vec![vec!["echo".to_string()]]); + derive_requested_execpolicy_amendment_from_prefix_rule( + prefix_rule, + matched_rules, + &Policy::empty(), + &commands, + &|_: &[String]| Decision::Allow, + ) + } + #[test] fn derive_requested_execpolicy_amendment_returns_none_for_missing_prefix_rule() { assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule(None, &[]) + derive_requested_execpolicy_amendment_for_test(None, &[]) ); } @@ -1740,7 +1827,7 @@ prefix_rule( fn derive_requested_execpolicy_amendment_returns_none_for_empty_prefix_rule() { assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule(Some(&Vec::new()), &[]) + derive_requested_execpolicy_amendment_for_test(Some(&Vec::new()), &[]) ); } @@ -1748,7 +1835,7 @@ prefix_rule( fn derive_requested_execpolicy_amendment_returns_none_for_exact_banned_prefix_rule() { assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule( + derive_requested_execpolicy_amendment_for_test( Some(&vec!["python".to_string(), "-c".to_string()]), &[], ) @@ -1767,7 +1854,7 @@ prefix_rule( ] { assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule(Some(&prefix_rule), &[]) + derive_requested_execpolicy_amendment_for_test(Some(&prefix_rule), &[]) ); } } @@ -1793,7 +1880,7 @@ prefix_rule( ] { assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule(Some(&prefix_rule), &[]) + derive_requested_execpolicy_amendment_for_test(Some(&prefix_rule), &[]) ); } } @@ -1808,7 +1895,7 @@ prefix_rule( assert_eq!( Some(ExecPolicyAmendment::new(prefix_rule.clone())), - derive_requested_execpolicy_amendment_from_prefix_rule(Some(&prefix_rule), &[]) + derive_requested_execpolicy_amendment_for_test(Some(&prefix_rule), &[]) ); } @@ -1823,7 +1910,7 @@ prefix_rule( }]; assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule( + derive_requested_execpolicy_amendment_for_test( Some(&prefix_rule), &matched_rules_prompt ), @@ -1836,7 +1923,7 @@ prefix_rule( }]; assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule( + derive_requested_execpolicy_amendment_for_test( Some(&prefix_rule), &matched_rules_allow ), @@ -1849,9 +1936,9 @@ prefix_rule( }]; assert_eq!( None, - derive_requested_execpolicy_amendment_from_prefix_rule( + derive_requested_execpolicy_amendment_for_test( Some(&prefix_rule), - &matched_rules_forbidden + &matched_rules_forbidden, ), "should return none when prompt policy matches" ); diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 14d9c79e5e..374cc1ada7 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -184,6 +184,16 @@ fn shell_event( command: &str, timeout_ms: u64, sandbox_permissions: SandboxPermissions, +) -> Result { + shell_event_with_prefix_rule(call_id, command, timeout_ms, sandbox_permissions, None) +} + +fn shell_event_with_prefix_rule( + call_id: &str, + command: &str, + timeout_ms: u64, + sandbox_permissions: SandboxPermissions, + prefix_rule: Option>, ) -> Result { let mut args = json!({ "command": command, @@ -192,6 +202,9 @@ fn shell_event( if sandbox_permissions.requires_escalated_permissions() { args["sandbox_permissions"] = json!(sandbox_permissions); } + if let Some(prefix_rule) = prefix_rule { + args["prefix_rule"] = json!(prefix_rule); + } let args_str = serde_json::to_string(&args)?; Ok(ev_function_call(call_id, "shell_command", &args_str)) } @@ -1928,6 +1941,171 @@ async fn approving_execpolicy_amendment_persists_policy_and_skips_future_prompts Ok(()) } +#[tokio::test(flavor = "current_thread")] +#[cfg(unix)] +async fn invalid_requested_prefix_rule_falls_back_for_compound_command() -> Result<()> { + let server = start_mock_server().await; + let approval_policy = AskForApproval::OnRequest; + let sandbox_policy = SandboxPolicy::new_read_only_policy(); + let sandbox_policy_for_config = sandbox_policy.clone(); + let mut builder = test_codex().with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(approval_policy); + config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); + }); + let test = builder.build(&server).await?; + + let call_id = "invalid-prefix-rule"; + let command = + "touch /tmp/codex-fallback-rule-test.txt && echo hello > /tmp/codex-fallback-rule-test.txt"; + let event = shell_event_with_prefix_rule( + call_id, + command, + 1_000, + SandboxPermissions::RequireEscalated, + Some(vec!["touch".to_string()]), + )?; + + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-invalid-prefix-1"), + event, + ev_completed("resp-invalid-prefix-1"), + ]), + ) + .await; + + submit_turn( + &test, + "invalid-prefix-rule", + approval_policy, + sandbox_policy.clone(), + ) + .await?; + + let approval = expect_exec_approval(&test, command).await; + let amendment = approval + .proposed_execpolicy_amendment + .expect("should have a proposed execpolicy amendment"); + assert!(amendment.command.contains(&command.to_string())); + + Ok(()) +} + +#[tokio::test(flavor = "current_thread")] +#[cfg(unix)] +async fn approving_fallback_rule_for_compound_command_works() -> Result<()> { + let server = start_mock_server().await; + let approval_policy = AskForApproval::OnRequest; + let sandbox_policy = SandboxPolicy::new_read_only_policy(); + let sandbox_policy_for_config = sandbox_policy.clone(); + let mut builder = test_codex().with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(approval_policy); + config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); + }); + let test = builder.build(&server).await?; + + let call_id = "invalid-prefix-rule"; + let command = + "touch /tmp/codex-fallback-rule-test.txt && echo hello > /tmp/codex-fallback-rule-test.txt"; + let event = shell_event_with_prefix_rule( + call_id, + command, + 1_000, + SandboxPermissions::RequireEscalated, + Some(vec!["touch".to_string()]), + )?; + + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-invalid-prefix-1"), + event, + ev_completed("resp-invalid-prefix-1"), + ]), + ) + .await; + + submit_turn( + &test, + "invalid-prefix-rule", + approval_policy, + sandbox_policy.clone(), + ) + .await?; + + let approval = expect_exec_approval(&test, command).await; + let approval_id = approval.effective_approval_id(); + let amendment = approval + .proposed_execpolicy_amendment + .expect("should have a proposed execpolicy amendment"); + assert!(amendment.command.contains(&command.to_string())); + + test.codex + .submit(Op::ExecApproval { + id: approval_id, + turn_id: None, + decision: ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: amendment.clone(), + }, + }) + .await?; + wait_for_completion(&test).await; + + let call_id = "invalid-prefix-rule-again"; + let command = + "touch /tmp/codex-fallback-rule-test.txt && echo hello > /tmp/codex-fallback-rule-test.txt"; + let event = shell_event_with_prefix_rule( + call_id, + command, + 1_000, + SandboxPermissions::RequireEscalated, + Some(vec!["touch".to_string()]), + )?; + + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-invalid-prefix-1"), + event, + ev_completed("resp-invalid-prefix-1"), + ]), + ) + .await; + let second_results = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-invalid-prefix-1", "done"), + ev_completed("resp-invalid-prefix-2"), + ]), + ) + .await; + + submit_turn( + &test, + "invalid-prefix-rule", + approval_policy, + sandbox_policy.clone(), + ) + .await?; + + wait_for_completion_without_approval(&test).await; + + let second_output = parse_result( + &second_results + .single_request() + .function_call_output(call_id), + ); + assert_eq!(second_output.exit_code.unwrap_or(0), 0); + assert!( + second_output.stdout.is_empty(), + "unexpected stdout: {}", + second_output.stdout + ); + + Ok(()) +} + // todo(dylan) add ScenarioSpec support for rules #[tokio::test(flavor = "current_thread")] #[cfg(unix)] From 264fc444b62cbd6fe438e7bcb601a96830cd5969 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 20 Feb 2026 23:02:24 -0800 Subject: [PATCH 049/385] feat: discourage the use of the --all-features flag (#12429) ## Why Developers are frequently running low on disk space, and routine use of `--all-features` contributes to larger Cargo build caches in `target/` by compiling additional feature combinations. This change updates local workflow guidance to avoid `--all-features` by default and reserve it for cases where full feature coverage is specifically needed. ## What Changed - Updated `AGENTS.md` guidance for `codex-rs` to recommend `cargo test` / `just test` for full-suite local runs, and to call out the disk-usage cost of routine `--all-features` usage. - Updated the root `justfile` so `just fix` and `just clippy` no longer pass `--all-features` by default. - Updated `docs/install.md` to explicitly describe `cargo test --all-features` as an optional heavier-weight run (more build time and `target/` disk usage). ## Verification - Confirmed the `justfile` parses and the recipes list successfully with `just --list`. --- AGENTS.md | 2 +- docs/install.md | 4 +++- justfile | 6 ++++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fa2a4bbaba..09c32d02f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,7 @@ In the codex-rs folder where the rust code lives: Run `just fmt` (in `codex-rs` directory) automatically after you have finished making Rust code changes; do not ask for approval to run it. Additionally, run the tests: 1. Run the test for the specific project that was changed. For example, if changes were made in `codex-rs/tui`, run `cargo test -p codex-tui`. -2. Once those pass, if any changes were made in common, core, or protocol, run the complete test suite with `cargo test --all-features`. project-specific or individual tests can be run without asking the user, but do ask the user before running the complete test suite. +2. Once those pass, if any changes were made in common, core, or protocol, run the complete test suite with `cargo test` (or `just test` if `cargo-nextest` is installed). Avoid `--all-features` for routine local runs because it expands the build matrix and can significantly increase `target/` disk usage; use it only when you specifically need full feature coverage. project-specific or individual tests can be run without asking the user, but do ask the user before running the complete test suite. Before finalizing a large change to `codex-rs`, run `just fix -p ` (in `codex-rs` directory) to fix any linter issues in the code. Prefer scoping with `-p` to avoid slow workspace‑wide Clippy builds; only run `just fix` without `-p` if you changed shared crates. Do not re-run tests after running `fix` or `fmt`. diff --git a/docs/install.md b/docs/install.md index 16892c82fe..b7d4f0711a 100644 --- a/docs/install.md +++ b/docs/install.md @@ -43,7 +43,9 @@ just fix -p cargo test -p codex-tui # If you have cargo-nextest installed, `just test` runs the test suite via nextest: just test -# If you specifically want the full `--all-features` matrix, use: +# Avoid `--all-features` for routine local runs because it increases build +# time and `target/` disk usage by compiling additional feature combinations. +# If you specifically want full feature coverage, use: cargo test --all-features ``` diff --git a/justfile b/justfile index 33d62d515b..27ba4fc9c3 100644 --- a/justfile +++ b/justfile @@ -28,10 +28,10 @@ fmt: cargo fmt -- --config imports_granularity=Item 2>/dev/null fix *args: - cargo clippy --fix --all-features --tests --allow-dirty "$@" + cargo clippy --fix --tests --allow-dirty "$@" clippy: - cargo clippy --all-features --tests "$@" + cargo clippy --tests "$@" install: rustup show active-toolchain @@ -41,6 +41,8 @@ install: # --no-fail-fast is important to ensure all tests are run. # # Run `cargo install cargo-nextest` if you don't have it installed. +# Prefer this for routine local runs; use explicit `cargo test --all-features` +# only when you specifically need full feature coverage. test: cargo nextest run --no-fail-fast From bb0ac5be70fcef5f418abf77955e96e39add2f30 Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Fri, 20 Feb 2026 23:13:08 -0800 Subject: [PATCH 050/385] Fix compaction context reinjection and model baselines (#12252) ## Summary - move regular-turn context diff/full-context persistence into `run_turn` so pre-turn compaction runs before incoming context updates are recorded - after successful pre-turn compaction, rely on a cleared `reference_context_item` to trigger full context reinjection on the follow-up regular turn (manual `/compact` keeps replacement history summary-only and also clears the baseline) - preserve `` when full context is reinjected, and inject it *before* the rest of the full-context items - scope `reference_context_item` and `previous_model` to regular user turns only so standalone tasks (`/compact`, shell, review, undo) cannot suppress future reinjection or `` behavior - make context-diff persistence + `reference_context_item` updates explicit in the regular-turn path, with clearer docs/comments around the invariant - stop persisting local `/compact` `RolloutItem::TurnContext` snapshots (only regular turns persist `TurnContextItem` now) - simplify resume/fork previous-model/reference-baseline hydration by looking up the last surviving turn context from rollout lifecycle events, including rollback and compaction-crossing handling - remove the legacy fallback that guessed from bare `TurnContext` rollouts without lifecycle events - update compaction/remote-compaction/model-visible snapshots and compact test assertions (including remote compaction mock response shape) ## Why We were persisting incoming context items before spawning the regular turn task, which let pre-turn compaction requests accidentally include incoming context diffs without the new user message. Fixing that exposed follow-on baseline issues around `/compact`, resume/fork, and standalone tasks that could cause duplicate context injection or suppress `` instructions. This PR re-centers the invariants around regular turns: - regular turns persist model-visible context diffs/full reinjection and update the `reference_context_item` - standalone tasks do not advance those regular-turn baselines - compaction clears the baseline when replacement history may have stripped the referenced context diffs ## Follow-ups (TODOs left in code) - `TODO(ccunningham)`: fix rollback/backtracking baseline handling more comprehensively - `TODO(ccunningham)`: include pending incoming context items in pre-turn compaction threshold estimation - `TODO(ccunningham)`: inject updated personality spec alongside `` so some model-switch paths can avoid forced full reinjection - `TODO(ccunningham)`: review task turn lifecycle (`TurnStarted`/`TurnComplete`) behavior and emit task-start context diffs for task types that should have them (excluding `/compact`) ## Validation - `just fmt` - CI should cover the updated compaction/resume/model-visible snapshot expectations and rollout-hydration behavior - I did **not** rerun the full local test suite after the latest resume-lookup / rollout-persistence simplifications --- codex-rs/core/src/codex.rs | 713 ++++++++++++++---- codex-rs/core/src/compact.rs | 550 +++++++------- codex-rs/core/src/compact_remote.rs | 89 ++- codex-rs/core/src/context_manager/history.rs | 19 +- codex-rs/core/src/context_manager/updates.rs | 19 +- codex-rs/core/src/state/session.rs | 26 +- codex-rs/core/src/tasks/compact.rs | 9 +- codex-rs/core/src/tasks/mod.rs | 10 - codex-rs/core/src/tasks/undo.rs | 3 +- codex-rs/core/src/tasks/user_shell.rs | 4 + codex-rs/core/tests/common/responses.rs | 12 +- codex-rs/core/tests/suite/compact.rs | 38 +- codex-rs/core/tests/suite/compact_remote.rs | 57 +- .../core/tests/suite/compact_resume_fork.rs | 713 ++++-------------- .../core/tests/suite/model_visible_layout.rs | 8 +- codex-rs/core/tests/suite/prompt_caching.rs | 28 +- codex-rs/core/tests/suite/resume_warning.rs | 26 +- ...t__manual_compact_with_history_shapes.snap | 10 +- ...nual_compact_without_prev_user_shapes.snap | 8 +- ...mpling_model_switch_compaction_shapes.snap | 13 +- ..._compaction_including_incoming_shapes.snap | 15 +- ...n_strips_incoming_model_switch_shapes.snap | 15 +- ...te_manual_compact_with_history_shapes.snap | 16 +- ...y_reinjects_above_last_summary_shapes.snap | 27 +- ...te__remote_mid_turn_compaction_shapes.snap | 14 +- ...summary_only_reinjects_context_shapes.snap | 6 +- ..._compaction_including_incoming_shapes.snap | 9 +- ...n_strips_incoming_model_switch_shapes.snap | 14 +- ...resume_override_matches_rollout_model.snap | 7 +- ...layout_resume_with_personality_change.snap | 13 +- codex-rs/protocol/src/protocol.rs | 4 + 31 files changed, 1289 insertions(+), 1206 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 88e6fef893..90d496973a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -18,6 +18,7 @@ use crate::analytics_client::build_track_events_context; use crate::apps::render_apps_section; use crate::commit_attribution::commit_message_trailer_instruction; use crate::compact; +use crate::compact::InitialContextInjection; use crate::compact::run_inline_auto_compact_task; use crate::compact::should_use_remote_compact_task; use crate::compact_remote::run_inline_remote_auto_compact_task; @@ -1599,7 +1600,7 @@ impl Session { self.record_conversation_items(&turn_context, &items).await; { let mut state = self.state.lock().await; - state.initial_context_seeded = true; + state.set_reference_context_item(Some(turn_context.to_turn_context_item())); } self.set_previous_model(None).await; // Ensure initial items are visible to immediate readers (e.g., tests, forks). @@ -1609,19 +1610,26 @@ impl Session { let rollout_items = resumed_history.history; let restored_tool_selection = Self::extract_mcp_tool_selection_from_rollout(&rollout_items); - let previous_model = Self::last_rollout_model_name(&rollout_items) - .map(std::string::ToString::to_string); + let (previous_regular_turn_context_item, crossed_compaction_after_turn) = + Self::last_rollout_regular_turn_context_lookup(&rollout_items); + let previous_model = + previous_regular_turn_context_item.map(|ctx| ctx.model.clone()); + let curr = turn_context.model_info.slug.as_str(); + let reference_context_item = if !crossed_compaction_after_turn { + previous_regular_turn_context_item.cloned() + } else { + // Keep the baseline empty when compaction may have stripped the referenced + // context diffs so the first resumed regular turn fully reinjects context. + None + }; { let mut state = self.state.lock().await; - state.initial_context_seeded = false; + state.set_reference_context_item(reference_context_item); } - self.set_previous_model(previous_model).await; + self.set_previous_model(previous_model.clone()).await; // If resuming, warn when the last recorded model differs from the current one. - let curr = turn_context.model_info.slug.as_str(); - if let Some(prev) = - Self::last_rollout_model_name(&rollout_items).filter(|p| *p != curr) - { + if let Some(prev) = previous_model.as_deref().filter(|p| *p != curr) { warn!("resuming session with different model: previous={prev}, current={curr}"); self.send_event( &turn_context, @@ -1661,8 +1669,10 @@ impl Session { InitialHistory::Forked(rollout_items) => { let restored_tool_selection = Self::extract_mcp_tool_selection_from_rollout(&rollout_items); - let previous_model = Self::last_rollout_model_name(&rollout_items) - .map(std::string::ToString::to_string); + let (previous_regular_turn_context_item, _) = + Self::last_rollout_regular_turn_context_lookup(&rollout_items); + let previous_model = + previous_regular_turn_context_item.map(|ctx| ctx.model.clone()); self.set_previous_model(previous_model).await; // Always add response items to conversation history @@ -1695,7 +1705,7 @@ impl Session { .await; { let mut state = self.state.lock().await; - state.initial_context_seeded = true; + state.set_reference_context_item(Some(turn_context.to_turn_context_item())); } // Forked threads should remain file-backed immediately after startup. @@ -1707,14 +1717,148 @@ impl Session { } } - fn last_rollout_model_name(rollout_items: &[RolloutItem]) -> Option<&str> { - rollout_items.iter().rev().find_map(|it| { - if let RolloutItem::TurnContext(ctx) = it { - Some(ctx.model.as_str()) - } else { - None + /// Returns `(last_turn_context_item, crossed_compaction_after_turn)` from the + /// rollback-adjusted rollout view. + /// + /// This relies on the invariant that only regular turns persist `TurnContextItem`. + /// `ThreadRolledBack` markers are applied so resume/fork uses the post-rollback history view. + /// + /// Returns `(None, false)` when no persisted `TurnContextItem` can be found. + /// + /// Older/minimal rollouts may only contain `RolloutItem::TurnContext` entries without turn + /// lifecycle events. In that case we fall back to the last `TurnContextItem` (plus whether a + /// later `Compacted` item appears in rollout order). + // TODO(ccunningham): Simplify this lookup by sharing rollout traversal/rollback application + // with `reconstruct_history_from_rollout` so resume/fork baseline hydration does not need a + // second bespoke rollout scan. + fn last_rollout_regular_turn_context_lookup( + rollout_items: &[RolloutItem], + ) -> (Option<&TurnContextItem>, bool) { + // Reverse scan over rollout items. `ThreadRolledBack(num_turns)` is naturally handled by + // skipping the next `num_turns` completed turn spans we encounter while walking backward. + // + // "Active turn" here means: we have seen `TurnComplete`/`TurnAborted` and are currently + // scanning backward through that completed turn until its matching `TurnStarted`. + let mut turns_to_skip_due_to_rollback = 0usize; + let mut saw_surviving_compaction_after_candidate = false; + let mut saw_turn_lifecycle_event = false; + let mut active_turn_id: Option<&str> = None; + let mut active_turn_saw_user_message = false; + let mut active_turn_context: Option<&TurnContextItem> = None; + let mut active_turn_contains_compaction = false; + + for item in rollout_items.iter().rev() { + match item { + RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => { + // Rollbacks count completed turns, not `TurnContextItem`s. We must continue + // ignoring all items inside each skipped turn until we reach its + // corresponding `TurnStarted`. + let num_turns = usize::try_from(rollback.num_turns).unwrap_or(usize::MAX); + turns_to_skip_due_to_rollback = + turns_to_skip_due_to_rollback.saturating_add(num_turns); + } + RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => { + saw_turn_lifecycle_event = true; + // Enter the reverse "turn span" for this completed turn. + active_turn_id = Some(event.turn_id.as_str()); + active_turn_saw_user_message = false; + active_turn_context = None; + active_turn_contains_compaction = false; + } + RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => { + saw_turn_lifecycle_event = true; + // Same reverse-turn handling as `TurnComplete`. Some aborted turns may not + // have a turn id; in that case we cannot match `TurnContextItem`s to them. + active_turn_id = event.turn_id.as_deref(); + active_turn_saw_user_message = false; + active_turn_context = None; + active_turn_contains_compaction = false; + } + RolloutItem::EventMsg(EventMsg::UserMessage(_)) => { + if active_turn_id.is_some() { + active_turn_saw_user_message = true; + } + } + RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => { + saw_turn_lifecycle_event = true; + if active_turn_id == Some(event.turn_id.as_str()) { + let active_turn_is_rolled_back = + active_turn_saw_user_message && turns_to_skip_due_to_rollback > 0; + if active_turn_is_rolled_back { + // `ThreadRolledBack(num_turns)` counts user turns, so only consume a + // skip once we've confirmed this reverse-scanned turn span contains a + // user message. Standalone task turns must not consume rollback skips. + turns_to_skip_due_to_rollback -= 1; + } + if !active_turn_is_rolled_back { + if let Some(context_item) = active_turn_context { + return ( + Some(context_item), + saw_surviving_compaction_after_candidate, + ); + } + // No `TurnContextItem` in this surviving turn; keep scanning older + // turns, but remember if this turn compacted so the eventual + // candidate reports "compaction happened after it". + if active_turn_contains_compaction { + saw_surviving_compaction_after_candidate = true; + } + } + active_turn_id = None; + active_turn_saw_user_message = false; + active_turn_context = None; + active_turn_contains_compaction = false; + } + } + RolloutItem::TurnContext(ctx) => { + // Capture the latest turn context seen in this reverse-scanned turn span. If + // the turn later proves to be rolled back, we discard it when we hit the + // matching `TurnStarted`. Older rollouts may have lifecycle events but omit + // `TurnContextItem.turn_id`; accept those as belonging to the active turn + // span for resume/fork hydration. + if let Some(active_id) = active_turn_id + && ctx + .turn_id + .as_deref() + .is_none_or(|turn_id| turn_id == active_id) + { + // Reverse scan sees the latest `TurnContextItem` for the turn first. + active_turn_context.get_or_insert(ctx); + } + } + RolloutItem::Compacted(_) => { + if active_turn_id.is_some() { + // Compaction inside the currently scanned turn is only "after" the + // eventual candidate if this turn has no `TurnContextItem` and we keep + // scanning into older turns. + active_turn_contains_compaction = true; + } else { + saw_surviving_compaction_after_candidate = true; + } + } + _ => {} } - }) + } + + // Legacy/minimal rollouts may only persist `TurnContextItem`/`Compacted` without turn + // lifecycle events. Fall back to the last `TurnContextItem` in rollout order so + // resume/fork can still hydrate `previous_model` and detect compaction-after-baseline. + if !saw_turn_lifecycle_event { + let mut saw_compaction_after_last_turn_context = false; + for item in rollout_items.iter().rev() { + match item { + RolloutItem::Compacted(_) => { + saw_compaction_after_last_turn_context = true; + } + RolloutItem::TurnContext(ctx) => { + return (Some(ctx), saw_compaction_after_last_turn_context); + } + _ => {} + } + } + } + + (None, false) } fn last_token_info_from_rollout(rollout_items: &[RolloutItem]) -> Option { @@ -2033,33 +2177,21 @@ impl Session { .await } - pub(crate) fn is_model_switch_developer_message(item: &ResponseItem) -> bool { - let ResponseItem::Message { role, content, .. } = item else { - return false; - }; - role == "developer" - && content.iter().any(|content_item| { - matches!( - content_item, - ContentItem::InputText { text } if text.starts_with("") - ) - }) - } fn build_settings_update_items( &self, - previous_context: Option<&TurnContextItem>, - resumed_model: Option<&str>, + reference_context_item: Option<&TurnContextItem>, + previous_user_turn_model: Option<&str>, current_context: &TurnContext, ) -> Vec { // TODO: Make context updates a pure diff of persisted previous/current TurnContextItem // state so replay/backtracking is deterministic. Runtime inputs that affect model-visible - // context (shell, exec policy, feature gates, resumed model bridge) should be persisted + // context (shell, exec policy, feature gates, previous-model bridge) should be persisted // state or explicit non-state replay events. let shell = self.user_shell(); let exec_policy = self.services.exec_policy.current(); crate::context_manager::updates::build_settings_update_items( - previous_context, - resumed_model, + reference_context_item, + previous_user_turn_model, current_context, shell.as_ref(), exec_policy.as_ref(), @@ -2465,15 +2597,6 @@ impl Session { history.raw_items().to_vec() } - pub(crate) async fn process_compacted_history( - &self, - turn_context: &TurnContext, - compacted_history: Vec, - ) -> Vec { - let initial_context = self.build_initial_context(turn_context).await; - compact::process_compacted_history(compacted_history, &initial_context) - } - /// Append ResponseItems to the in-memory conversation history only. pub(crate) async fn record_into_history( &self, @@ -2542,24 +2665,13 @@ impl Session { true } - pub(crate) async fn replace_history(&self, items: Vec) { + pub(crate) async fn replace_history( + &self, + items: Vec, + reference_context_item: Option, + ) { let mut state = self.state.lock().await; - state.replace_history(items); - } - - pub(crate) async fn seed_initial_context_if_needed(&self, turn_context: &TurnContext) { - { - let mut state = self.state.lock().await; - if state.initial_context_seeded { - return; - } - state.initial_context_seeded = true; - } - - let initial_context = self.build_initial_context(turn_context).await; - self.record_conversation_items(turn_context, &initial_context) - .await; - self.flush_rollout().await; + state.replace_history(items, reference_context_item); } async fn persist_rollout_response_items(&self, items: &[ResponseItem]) { @@ -2693,14 +2805,61 @@ impl Session { state.clone_history() } - pub(crate) async fn previous_context_item(&self) -> Option { + pub(crate) async fn reference_context_item(&self) -> Option { let state = self.state.lock().await; - state.previous_context_item() + state.reference_context_item() } - pub(crate) async fn set_previous_context_item(&self, item: Option) { + /// Persist the latest turn context snapshot and emit any required model-visible context updates. + /// + /// When the reference snapshot is missing, this injects full initial context. Otherwise, it + /// emits only settings diff items. + /// + /// If full context is injected and a model switch occurred, this prepends the + /// `` developer message so model-specific instructions are not lost. + /// + /// Invariant: this is the only runtime path that writes a non-`None` + /// `reference_context_item`. Non-regular tasks intentionally do not update that + /// baseline; `reference_context_item` tracks the latest regular model turn. + pub(crate) async fn record_context_updates_and_set_reference_context_item( + &self, + turn_context: &TurnContext, + previous_user_turn_model: Option<&str>, + ) { + let reference_context_item = self.reference_context_item().await; + let should_inject_full_context = reference_context_item.is_none(); + let context_items = if should_inject_full_context { + let mut initial_context = self.build_initial_context(turn_context).await; + // Full reinjection bypasses the settings-diff path, so add the model-switch + // instruction explicitly when needed. Keep it before the rest of full context so + // model-specific guidance is read first. + if let Some(model_switch_item) = + crate::context_manager::updates::build_model_instructions_update_item( + previous_user_turn_model, + turn_context, + ) + { + // TODO(ccunningham): When a model switch changes the effective personality + // instructions, inject the updated personality spec alongside + // here so resume/model-switch paths can avoid forcing full reinjection. + initial_context.insert(0, model_switch_item); + } + initial_context + } else { + // Steady-state path: append only context diffs to minimize token overhead. + self.build_settings_update_items( + reference_context_item.as_ref(), + previous_user_turn_model, + turn_context, + ) + }; + if !context_items.is_empty() { + self.record_conversation_items(turn_context, &context_items) + .await; + } + let mut state = self.state.lock().await; - state.set_previous_context_item(item); + state.set_reference_context_item(Some(turn_context.to_turn_context_item())); } pub(crate) async fn update_token_usage_info( @@ -3168,11 +3327,6 @@ impl Session { } async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiver) { - // Seed with context in case there is an OverrideTurnContext first. - let initial_context = sess.new_default_turn().await; - sess.set_previous_context_item(Some(initial_context.to_turn_context_item())) - .await; - // To break out of this loop, send Op::Shutdown. while let Ok(sub) = rx_sub.recv().await { debug!(?sub, "Submission"); @@ -3486,26 +3640,11 @@ mod handlers { // Attempt to inject input into current task. if let Err(SteerInputError::NoActiveTurn(items)) = sess.steer_input(items, None).await { - sess.seed_initial_context_if_needed(¤t_context).await; - let previous_model = sess.previous_model().await; - let previous_context_item = sess.previous_context_item().await; - let update_items = sess.build_settings_update_items( - previous_context_item.as_ref(), - previous_model.as_deref(), - ¤t_context, - ); - if !update_items.is_empty() { - sess.record_conversation_items(¤t_context, &update_items) - .await; - } - sess.refresh_mcp_servers_if_requested(¤t_context) .await; let regular_task = sess.take_startup_regular_task().await.unwrap_or_default(); sess.spawn_task(Arc::clone(¤t_context), items, regular_task) .await; - sess.set_previous_context_item(Some(current_context.to_turn_context_item())) - .await; } } @@ -3534,8 +3673,6 @@ mod handlers { UserShellCommandTask::new(command), ) .await; - sess.set_previous_context_item(Some(turn_context.to_turn_context_item())) - .await; } pub async fn resolve_elicitation( @@ -3965,15 +4102,20 @@ mod handlers { } let turn_context = sess.new_default_turn_with_sub_id(sub_id).await; - sess.set_previous_model(Some(turn_context.model_info.slug.clone())) - .await; let mut history = sess.clone_history().await; + // TODO(ccunningham): Fix rollback/backtracking baseline handling. + // We clear `reference_context_item` here, but should restore the + // post-rollback baseline from the surviving history/rollout instead. + // Truncating history should also invalidate/recompute `previous_model` + // so the next regular turn replays any dropped model-switch + // instructions. history.drop_last_n_user_turns(num_turns); // Replace with the raw items. We don't want to replace with a normalized // version of the history. - sess.replace_history(history.raw_items().to_vec()).await; + sess.replace_history(history.raw_items().to_vec(), None) + .await; sess.recompute_token_usage(turn_context.as_ref()).await; sess.send_event_raw_flushed(Event { @@ -4247,6 +4389,9 @@ async fn spawn_review_thread( }]; let tc = Arc::new(review_turn_context); tc.turn_metadata_state.spawn_git_enrichment_task(); + // TODO(ccunningham): Review turns currently rely on `spawn_task` for TurnComplete but do not + // emit a parent TurnStarted. Consider giving review a full parent turn lifecycle + // (TurnStarted + TurnComplete) for consistency with other standalone tasks. sess.spawn_task(tc.clone(), input, ReviewTask::new()).await; // Announce entering review mode so UIs can switch modes. @@ -4346,6 +4491,10 @@ pub(crate) async fn run_turn( collaboration_mode_kind: turn_context.collaboration_mode.mode, }); sess.send_event(&turn_context, event).await; + // TODO(ccunningham): Pre-turn compaction runs before context updates and the + // new user message are recorded. Estimate pending incoming items (context + // diffs/full reinjection + user input) and trigger compaction preemptively + // when they would push the thread over the compaction threshold. if run_pre_sampling_compact(&sess, &turn_context) .await .is_err() @@ -4354,6 +4503,13 @@ pub(crate) async fn run_turn( return None; } + let previous_model = sess.previous_model().await; + sess.record_context_updates_and_set_reference_context_item( + turn_context.as_ref(), + previous_model.as_deref(), + ) + .await; + let skills_outcome = Some( sess.services .skills_manager @@ -4465,6 +4621,11 @@ pub(crate) async fn run_turn( let response_item: ResponseItem = initial_input_for_turn.clone().into(); sess.record_user_prompt_and_emit_turn_item(turn_context.as_ref(), &input, response_item) .await; + // Track the previous-model baseline from the regular user-turn path only so + // standalone tasks (compact/shell/review/undo) cannot suppress future + // `` injections. + sess.set_previous_model(Some(turn_context.model_info.slug.clone())) + .await; if !skill_items.is_empty() { sess.record_conversation_items(&turn_context, &skill_items) @@ -4568,7 +4729,14 @@ pub(crate) async fn run_turn( // as long as compaction works well in getting us way below the token limit, we shouldn't worry about being in an infinite loop. if token_limit_reached && needs_follow_up { - if run_auto_compact(&sess, &turn_context).await.is_err() { + if run_auto_compact( + &sess, + &turn_context, + InitialContextInjection::BeforeLastUserMessage, + ) + .await + .is_err() + { return None; } continue; @@ -4688,7 +4856,7 @@ async fn run_pre_sampling_compact( .unwrap_or(i64::MAX); // Compact if the total usage tokens are greater than the auto compact limit if total_usage_tokens >= auto_compact_limit { - run_auto_compact(sess, turn_context).await?; + run_auto_compact(sess, turn_context, InitialContextInjection::DoNotInject).await?; } Ok(()) } @@ -4696,47 +4864,67 @@ async fn run_pre_sampling_compact( /// Runs pre-sampling compaction against the previous model when switching to a smaller /// context-window model. /// -/// Returns `Ok(())` when compaction either completed successfully or was skipped because the -/// model/context-window preconditions were not met. Returns `Err(_)` only when compaction was -/// attempted and failed. +/// Returns `Ok(true)` when compaction ran successfully, `Ok(false)` when compaction was skipped +/// because the model/context-window preconditions were not met, and `Err(_)` only when compaction +/// was attempted and failed. async fn maybe_run_previous_model_inline_compact( sess: &Arc, turn_context: &Arc, total_usage_tokens: i64, -) -> CodexResult<()> { +) -> CodexResult { let Some(previous_model) = sess.previous_model().await else { - return Ok(()); + return Ok(false); }; - let previous_turn_context = Arc::new( + let previous_model_turn_context = Arc::new( turn_context .with_model(previous_model, &sess.services.models_manager) .await, ); - let Some(old_context_window) = previous_turn_context.model_context_window() else { - return Ok(()); + let Some(old_context_window) = previous_model_turn_context.model_context_window() else { + return Ok(false); }; let Some(new_context_window) = turn_context.model_context_window() else { - return Ok(()); + return Ok(false); }; let new_auto_compact_limit = turn_context .model_info .auto_compact_token_limit() .unwrap_or(i64::MAX); let should_run = total_usage_tokens > new_auto_compact_limit - && previous_turn_context.model_info.slug != turn_context.model_info.slug + && previous_model_turn_context.model_info.slug != turn_context.model_info.slug && old_context_window > new_context_window; if should_run { - run_auto_compact(sess, &previous_turn_context).await?; + run_auto_compact( + sess, + &previous_model_turn_context, + InitialContextInjection::DoNotInject, + ) + .await?; + return Ok(true); } - Ok(()) + Ok(false) } -async fn run_auto_compact(sess: &Arc, turn_context: &Arc) -> CodexResult<()> { +async fn run_auto_compact( + sess: &Arc, + turn_context: &Arc, + initial_context_injection: InitialContextInjection, +) -> CodexResult<()> { if should_use_remote_compact_task(&turn_context.provider) { - run_inline_remote_auto_compact_task(Arc::clone(sess), Arc::clone(turn_context)).await?; + run_inline_remote_auto_compact_task( + Arc::clone(sess), + Arc::clone(turn_context), + initial_context_injection, + ) + .await?; } else { - run_inline_auto_compact_task(Arc::clone(sess), Arc::clone(turn_context)).await?; + run_inline_auto_compact_task( + Arc::clone(sess), + Arc::clone(turn_context), + initial_context_injection, + ) + .await?; } Ok(()) } @@ -5525,6 +5713,9 @@ async fn try_run_sampling_request( prompt: &Prompt, cancellation_token: CancellationToken, ) -> CodexResult { + // Persist one TurnContext marker per sampling request (not just per user turn) so rollout + // analysis can reconstruct API-turn boundaries. `run_turn` persists model-visible context + // diffs/full reinjection earlier in the same regular turn before reaching this path. let rollout_item = RolloutItem::TurnContext(turn_context.to_turn_context_item()); feedback_tags!( @@ -6458,7 +6649,7 @@ mod tests { async fn record_initial_history_resumed_hydrates_previous_model() { let (session, turn_context) = make_session_and_context().await; let previous_model = "previous-rollout-model"; - let rollout_items = vec![RolloutItem::TurnContext(TurnContextItem { + let previous_context_item = TurnContextItem { turn_id: Some(turn_context.sub_id.clone()), cwd: turn_context.cwd.clone(), approval_policy: turn_context.approval_policy, @@ -6473,7 +6664,8 @@ mod tests { developer_instructions: None, final_output_json_schema: None, truncation_policy: Some(turn_context.truncation_policy.into()), - })]; + }; + let rollout_items = vec![RolloutItem::TurnContext(previous_context_item)]; session .record_initial_history(InitialHistory::Resumed(ResumedHistory { @@ -6490,7 +6682,182 @@ mod tests { } #[tokio::test] - async fn resumed_history_seeds_initial_context_on_first_turn_only() { + async fn record_initial_history_resumed_hydrates_previous_model_from_lifecycle_turn_with_missing_turn_context_id() + { + let (session, turn_context) = make_session_and_context().await; + let previous_model = "previous-rollout-model"; + let mut previous_context_item = TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + approval_policy: turn_context.approval_policy, + sandbox_policy: turn_context.sandbox_policy.clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + let turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + previous_context_item.turn_id = None; + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id, + last_agent_message: None, + }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_model().await, + Some(previous_model.to_string()) + ); + } + + #[tokio::test] + async fn record_initial_history_resumed_rollback_skips_only_user_turns() { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let user_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let standalone_turn_id = "standalone-task-turn".to_string(); + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: user_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: user_turn_id, + last_agent_message: None, + }, + )), + // Standalone task turn (no UserMessage) should not consume rollback skips. + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: standalone_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: standalone_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 1 }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!(session.previous_model().await, None); + assert!(session.reference_context_item().await.is_none()); + } + + #[tokio::test] + async fn record_initial_history_resumed_seeds_reference_context_item_without_compaction() { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let rollout_items = vec![RolloutItem::TurnContext(previous_context_item.clone())]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + serde_json::to_value(session.reference_context_item().await) + .expect("serialize seeded reference context item"), + serde_json::to_value(Some(previous_context_item)) + .expect("serialize expected reference context item") + ); + } + + #[tokio::test] + async fn record_initial_history_resumed_does_not_seed_reference_context_item_after_compaction() + { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let rollout_items = vec![ + RolloutItem::TurnContext(previous_context_item), + RolloutItem::Compacted(CompactedItem { + message: String::new(), + replacement_history: Some(Vec::new()), + }), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert!(session.reference_context_item().await.is_none()); + } + + #[tokio::test] + async fn resumed_history_injects_initial_context_on_first_context_update_only() { let (session, turn_context) = make_session_and_context().await; let (rollout_items, mut expected) = sample_rollout(&session, &turn_context).await; @@ -6505,12 +6872,16 @@ mod tests { let history_before_seed = session.state.lock().await.clone_history(); assert_eq!(expected, history_before_seed.raw_items()); - session.seed_initial_context_if_needed(&turn_context).await; + session + .record_context_updates_and_set_reference_context_item(&turn_context, None) + .await; expected.extend(session.build_initial_context(&turn_context).await); let history_after_seed = session.clone_history().await; assert_eq!(expected, history_after_seed.raw_items()); - session.seed_initial_context_if_needed(&turn_context).await; + session + .record_context_updates_and_set_reference_context_item(&turn_context, None) + .await; let history_after_second_seed = session.clone_history().await; assert_eq!(expected, history_after_second_seed.raw_items()); } @@ -6677,7 +7048,7 @@ mod tests { async fn record_initial_history_forked_hydrates_previous_model() { let (session, turn_context) = make_session_and_context().await; let previous_model = "forked-rollout-model"; - let rollout_items = vec![RolloutItem::TurnContext(TurnContextItem { + let previous_context_item = TurnContextItem { turn_id: Some(turn_context.sub_id.clone()), cwd: turn_context.cwd.clone(), approval_policy: turn_context.approval_policy, @@ -6692,7 +7063,8 @@ mod tests { developer_instructions: None, final_output_json_schema: None, truncation_policy: Some(turn_context.truncation_policy.into()), - })]; + }; + let rollout_items = vec![RolloutItem::TurnContext(previous_context_item)]; session .record_initial_history(InitialHistory::Forked(rollout_items)) @@ -6755,6 +7127,8 @@ mod tests { }, ]; sess.record_into_history(&turn_2, tc.as_ref()).await; + sess.set_previous_model(Some("previous-regular-model".to_string())) + .await; handlers::thread_rollback(&sess, "sub-1".to_string(), 1).await; @@ -6769,7 +7143,7 @@ mod tests { assert_eq!(expected, history.raw_items()); assert_eq!( sess.previous_model().await, - Some(tc.model_info.slug.clone()) + Some("previous-regular-model".to_string()) ); } @@ -7426,8 +7800,7 @@ mod tests { session_configuration.session_source.clone(), ); - let mut state = SessionState::new(session_configuration.clone()); - mark_state_initial_context_seeded(&mut state); + let state = SessionState::new(session_configuration.clone()); let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone())); let network_approval = Arc::new(NetworkApprovalService::default()); @@ -7583,8 +7956,7 @@ mod tests { session_configuration.session_source.clone(), ); - let mut state = SessionState::new(session_configuration.clone()); - mark_state_initial_context_seeded(&mut state); + let state = SessionState::new(session_configuration.clone()); let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone())); let network_approval = Arc::new(NetworkApprovalService::default()); @@ -7671,10 +8043,6 @@ mod tests { (session, turn_context, rx_event) } - fn mark_state_initial_context_seeded(state: &mut SessionState) { - state.initial_context_seeded = true; - } - #[tokio::test] async fn refresh_mcp_servers_is_deferred_until_next_turn() { let (session, turn_context) = make_session_and_context().await; @@ -7746,7 +8114,7 @@ mod tests { } #[tokio::test] - async fn spawn_task_hydrates_previous_model() { + async fn spawn_task_does_not_update_previous_model_for_non_run_turn_tasks() { let (sess, tc, _rx) = make_session_and_context_with_rx().await; sess.set_previous_model(None).await; let input = vec![UserInput::Text { @@ -7765,10 +8133,7 @@ mod tests { .await; sess.abort_all_tasks(TurnAbortReason::Interrupted).await; - assert_eq!( - sess.previous_model().await, - Some(tc.model_info.slug.clone()) - ); + assert_eq!(sess.previous_model().await, None); } #[tokio::test] @@ -7806,9 +8171,9 @@ mod tests { .expect("rebuild config layer stack with network requirements"); current_context.config = Arc::new(config); - let previous_context_item = previous_context.to_turn_context_item(); + let reference_context_item = previous_context.to_turn_context_item(); let update_items = session.build_settings_update_items( - Some(&previous_context_item), + Some(&reference_context_item), None, ¤t_context, ); @@ -7830,6 +8195,92 @@ mod tests { assert!(environment_update.contains("blocked.example.com")); } + #[tokio::test] + async fn record_context_updates_and_set_reference_context_item_injects_full_context_when_baseline_missing() + { + let (session, turn_context) = make_session_and_context().await; + session + .record_context_updates_and_set_reference_context_item(&turn_context, None) + .await; + let history = session.clone_history().await; + let initial_context = session.build_initial_context(&turn_context).await; + assert_eq!(history.raw_items().to_vec(), initial_context); + + let current_context = session.reference_context_item().await; + assert_eq!( + serde_json::to_value(current_context).expect("serialize current context item"), + serde_json::to_value(Some(turn_context.to_turn_context_item())) + .expect("serialize expected context item") + ); + } + + #[tokio::test] + async fn record_context_updates_and_set_reference_context_item_reinjects_full_context_after_clear() + { + let (session, turn_context) = make_session_and_context().await; + let compacted_summary = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: format!("{}\nsummary", crate::compact::SUMMARY_PREFIX), + }], + end_turn: None, + phase: None, + }; + session + .record_into_history(std::slice::from_ref(&compacted_summary), &turn_context) + .await; + session + .record_context_updates_and_set_reference_context_item(&turn_context, None) + .await; + { + let mut state = session.state.lock().await; + state.set_reference_context_item(None); + } + session + .replace_history(vec![compacted_summary.clone()], None) + .await; + + session + .record_context_updates_and_set_reference_context_item(&turn_context, None) + .await; + + let history = session.clone_history().await; + let mut expected_history = vec![compacted_summary]; + expected_history.extend(session.build_initial_context(&turn_context).await); + assert_eq!(history.raw_items().to_vec(), expected_history); + } + + #[tokio::test] + async fn run_user_shell_command_does_not_set_reference_context_item() { + let (session, _turn_context, rx) = make_session_and_context_with_rx().await; + { + let mut state = session.state.lock().await; + state.set_reference_context_item(None); + } + + handlers::run_user_shell_command(&session, "sub-id".to_string(), "echo shell".to_string()) + .await; + + let deadline = StdDuration::from_secs(5); + let start = std::time::Instant::now(); + loop { + let remaining = deadline.saturating_sub(start.elapsed()); + let evt = tokio::time::timeout(remaining, rx.recv()) + .await + .expect("timeout waiting for event") + .expect("event"); + if matches!(evt.msg, EventMsg::TurnComplete(_)) { + break; + } + } + + assert!( + session.reference_context_item().await.is_none(), + "standalone shell tasks should not mutate previous context" + ); + } + #[derive(Clone, Copy)] struct NeverEndingTask { kind: TaskKind, diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index 4065251425..43ee08fd4f 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -32,10 +32,37 @@ pub const SUMMARIZATION_PROMPT: &str = include_str!("../templates/compact/prompt pub const SUMMARY_PREFIX: &str = include_str!("../templates/compact/summary_prefix.md"); const COMPACT_USER_MESSAGE_MAX_TOKENS: usize = 20_000; +/// Controls whether compaction replacement history must include initial context. +/// +/// Pre-turn/manual compaction variants use `DoNotInject`: they replace history with a summary and +/// clear `reference_context_item`, so the next regular turn will fully reinject initial context +/// after compaction. +/// +/// Mid-turn compaction must use `BeforeLastUserMessage` because the model is trained to see the +/// compaction summary as the last item in history after mid-turn compaction; we therefore inject +/// initial context into the replacement history just above the last real user message. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum InitialContextInjection { + BeforeLastUserMessage, + DoNotInject, +} + pub(crate) fn should_use_remote_compact_task(provider: &ModelProviderInfo) -> bool { provider.is_openai() } +fn is_model_switch_developer_message(item: &ResponseItem) -> bool { + match item { + ResponseItem::Message { role, content, .. } if role == "developer" => { + matches!( + content.as_slice(), + [ContentItem::InputText { text }] if text.starts_with("\n") + ) + } + _ => false, + } +} + pub(crate) fn extract_trailing_model_switch_update_for_compaction_request( history: &mut ContextManager, ) -> Option { @@ -49,7 +76,7 @@ pub(crate) fn extract_trailing_model_switch_update_for_compaction_request( .rev() .find_map(|(i, item)| { let is_trailing = last_user_turn_boundary_index.is_none_or(|boundary| i > boundary); - if is_trailing && Session::is_model_switch_developer_message(item) { + if is_trailing && is_model_switch_developer_message(item) { Some(i) } else { None @@ -64,6 +91,7 @@ pub(crate) fn extract_trailing_model_switch_update_for_compaction_request( pub(crate) async fn run_inline_auto_compact_task( sess: Arc, turn_context: Arc, + initial_context_injection: InitialContextInjection, ) -> CodexResult<()> { let prompt = turn_context.compact_prompt().to_string(); let input = vec![UserInput::Text { @@ -72,7 +100,7 @@ pub(crate) async fn run_inline_auto_compact_task( text_elements: Vec::new(), }]; - run_compact_task_inner(sess, turn_context, input).await?; + run_compact_task_inner(sess, turn_context, input, initial_context_injection).await?; Ok(()) } @@ -87,13 +115,20 @@ pub(crate) async fn run_compact_task( collaboration_mode_kind: turn_context.collaboration_mode.mode, }); sess.send_event(&turn_context, start_event).await; - run_compact_task_inner(sess.clone(), turn_context, input).await + run_compact_task_inner( + sess.clone(), + turn_context, + input, + InitialContextInjection::DoNotInject, + ) + .await } async fn run_compact_task_inner( sess: Arc, turn_context: Arc, input: Vec, + initial_context_injection: InitialContextInjection, ) -> CodexResult<()> { let compaction_item = TurnItem::ContextCompaction(ContextCompactionItem::new()); sess.emit_turn_item_started(&turn_context, &compaction_item) @@ -118,9 +153,6 @@ async fn run_compact_task_inner( // Reuse one client session so turn-scoped state (sticky routing, websocket append tracking) // survives retries within this compact turn. - let rollout_item = RolloutItem::TurnContext(turn_context.to_turn_context_item()); - sess.persist_rollout_items(&[rollout_item]).await; - loop { // Clone is required because of the loop let turn_input = history @@ -202,8 +234,16 @@ async fn run_compact_task_inner( let summary_text = format!("{SUMMARY_PREFIX}\n{summary_suffix}"); let user_messages = collect_user_messages(history_items); - let initial_context = sess.build_initial_context(turn_context.as_ref()).await; - let mut new_history = build_compacted_history(initial_context, &user_messages, &summary_text); + let mut new_history = build_compacted_history(Vec::new(), &user_messages, &summary_text); + + if matches!( + initial_context_injection, + InitialContextInjection::BeforeLastUserMessage + ) { + let initial_context = sess.build_initial_context(turn_context.as_ref()).await; + new_history = + insert_initial_context_before_last_real_user_or_summary(new_history, initial_context); + } // Reattach the stripped model-switch update only after successful compaction so the model // still sees the switch instructions on the next real sampling request. if let Some(model_switch_item) = stripped_model_switch_item { @@ -215,12 +255,17 @@ async fn run_compact_task_inner( .cloned() .collect(); new_history.extend(ghost_snapshots); - sess.replace_history(new_history).await; + let reference_context_item = match initial_context_injection { + InitialContextInjection::DoNotInject => None, + InitialContextInjection::BeforeLastUserMessage => Some(turn_context.to_turn_context_item()), + }; + sess.replace_history(new_history.clone(), reference_context_item) + .await; sess.recompute_token_usage(&turn_context).await; let rollout_item = RolloutItem::Compacted(CompactedItem { message: summary_text.clone(), - replacement_history: None, + replacement_history: Some(new_history), }); sess.persist_rollout_items(&[rollout_item]).await; @@ -272,24 +317,50 @@ pub(crate) fn is_summary_message(message: &str) -> bool { message.starts_with(format!("{SUMMARY_PREFIX}\n").as_str()) } -pub(crate) fn process_compacted_history( +/// Inserts canonical initial context into compacted replacement history at the +/// model-expected boundary. +/// +/// Placement rules: +/// - Prefer immediately before the last real user message. +/// - If no real user messages remain, insert before the compaction summary so +/// the summary stays last. +/// - If there are no user messages, insert before the last compaction item so +/// that item remains last (remote compaction may return only compaction items). +/// - If there are no user messages or compaction items, append the context. +pub(crate) fn insert_initial_context_before_last_real_user_or_summary( mut compacted_history: Vec, - initial_context: &[ResponseItem], + initial_context: Vec, ) -> Vec { - compacted_history.retain(should_keep_compacted_history_item); - - let initial_context = initial_context.to_vec(); + let mut last_user_or_summary_index = None; + let mut last_real_user_index = None; + for (i, item) in compacted_history.iter().enumerate().rev() { + let Some(TurnItem::UserMessage(user)) = crate::event_mapping::parse_turn_item(item) else { + continue; + }; + // Compaction summaries are encoded as user messages, so track both: + // the last real user message (preferred insertion point) and the last + // user-message-like item (fallback summary insertion point). + last_user_or_summary_index.get_or_insert(i); + if !is_summary_message(&user.message()) { + last_real_user_index = Some(i); + break; + } + } + let last_compaction_index = compacted_history + .iter() + .enumerate() + .rev() + .find_map(|(i, item)| matches!(item, ResponseItem::Compaction { .. }).then_some(i)); + let insertion_index = last_real_user_index + .or(last_user_or_summary_index) + .or(last_compaction_index); // Re-inject canonical context from the current session since we stripped it - // from the pre-compaction history. Keep it right before the last user - // message so older user messages remain earlier in the transcript. - if let Some(last_user_index) = compacted_history.iter().rposition(|item| { - matches!( - crate::event_mapping::parse_turn_item(item), - Some(TurnItem::UserMessage(_)) - ) - }) { - compacted_history.splice(last_user_index..last_user_index, initial_context); + // from the pre-compaction history. Prefer placing it before the last real + // user message; if there is no real user message left, place it before the + // summary or compaction item so the compaction item remains last. + if let Some(insertion_index) = insertion_index { + compacted_history.splice(insertion_index..insertion_index, initial_context); } else { compacted_history.extend(initial_context); } @@ -297,30 +368,6 @@ pub(crate) fn process_compacted_history( compacted_history } -/// Returns whether an item from remote compaction output should be preserved. -/// -/// Called while processing the model-provided compacted transcript, before we -/// append fresh canonical context from the current session. -/// -/// We drop: -/// - `developer` messages because remote output can include stale/duplicated -/// instruction content. -/// - non-user-content `user` messages (session prefix/instruction wrappers), -/// keeping only real user messages as parsed by `parse_turn_item`. -/// -/// This intentionally keeps `user`-role warnings and compaction-generated -/// summary messages because they parse as `TurnItem::UserMessage`. -fn should_keep_compacted_history_item(item: &ResponseItem) -> bool { - match item { - ResponseItem::Message { role, .. } if role == "developer" => false, - ResponseItem::Message { role, .. } if role == "user" => matches!( - crate::event_mapping::parse_turn_item(item), - Some(TurnItem::UserMessage(_)) - ), - _ => true, - } -} - pub(crate) fn build_compacted_history( initial_context: Vec, user_messages: &[String], @@ -442,6 +489,21 @@ mod tests { use super::*; use pretty_assertions::assert_eq; + async fn process_compacted_history_with_test_session( + compacted_history: Vec, + ) -> (Vec, Vec) { + let (session, turn_context) = crate::codex::make_session_and_context().await; + let initial_context = session.build_initial_context(&turn_context).await; + let refreshed = crate::compact_remote::process_compacted_history( + &session, + &turn_context, + compacted_history, + InitialContextInjection::BeforeLastUserMessage, + ) + .await; + (refreshed, initial_context) + } + #[test] fn content_items_to_text_joins_non_empty_segments() { let items = vec![ @@ -514,7 +576,7 @@ mod tests { history .raw_items() .iter() - .all(|item| !Session::is_model_switch_developer_message(item)) + .all(|item| !is_model_switch_developer_message(item)) ); } @@ -569,7 +631,7 @@ mod tests { history .raw_items() .iter() - .any(Session::is_model_switch_developer_message) + .any(is_model_switch_developer_message) ); } @@ -708,8 +770,8 @@ do things assert_eq!(summary, summary_text); } - #[test] - fn process_compacted_history_replaces_developer_messages() { + #[tokio::test] + async fn process_compacted_history_replaces_developer_messages() { let compacted_history = vec![ ResponseItem::Message { id: None, @@ -739,88 +801,22 @@ do things phase: None, }, ]; - let initial_context = vec![ - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh permissions".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#" - /tmp - zsh -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh personality".to_string(), - }], - end_turn: None, - phase: None, - }, - ]; - - let refreshed = process_compacted_history(compacted_history, &initial_context); - let expected = vec![ - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh permissions".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#" - /tmp - zsh -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh personality".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "summary".to_string(), - }], - end_turn: None, - phase: None, - }, - ]; + let (refreshed, mut expected) = + process_compacted_history_with_test_session(compacted_history).await; + expected.push(ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "summary".to_string(), + }], + end_turn: None, + phase: None, + }); assert_eq!(refreshed, expected); } - #[test] - fn process_compacted_history_reinjects_full_initial_context() { + #[tokio::test] + async fn process_compacted_history_reinjects_full_initial_context() { let compacted_history = vec![ResponseItem::Message { id: None, role: "user".to_string(), @@ -830,124 +826,22 @@ do things end_turn: None, phase: None, }]; - let initial_context = vec![ - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh permissions".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#"# AGENTS.md instructions for /repo - - -keep me updated -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#" - /repo - zsh -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#" - turn-1 - interrupted -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ]; - - let refreshed = process_compacted_history(compacted_history, &initial_context); - let expected = vec![ - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh permissions".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#"# AGENTS.md instructions for /repo - - -keep me updated -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#" - /repo - zsh -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: r#" - turn-1 - interrupted -"# - .to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "summary".to_string(), - }], - end_turn: None, - phase: None, - }, - ]; + let (refreshed, mut expected) = + process_compacted_history_with_test_session(compacted_history).await; + expected.push(ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "summary".to_string(), + }], + end_turn: None, + phase: None, + }); assert_eq!(refreshed, expected); } - #[test] - fn process_compacted_history_drops_non_user_content_messages() { + #[tokio::test] + async fn process_compacted_history_drops_non_user_content_messages() { let compacted_history = vec![ ResponseItem::Message { id: None, @@ -1008,42 +902,22 @@ keep me updated phase: None, }, ]; - let initial_context = vec![ResponseItem::Message { + let (refreshed, mut expected) = + process_compacted_history_with_test_session(compacted_history).await; + expected.push(ResponseItem::Message { id: None, - role: "developer".to_string(), + role: "user".to_string(), content: vec![ContentItem::InputText { - text: "fresh developer instructions".to_string(), + text: "summary".to_string(), }], end_turn: None, phase: None, - }]; - - let refreshed = process_compacted_history(compacted_history, &initial_context); - let expected = vec![ - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh developer instructions".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "summary".to_string(), - }], - end_turn: None, - phase: None, - }, - ]; + }); assert_eq!(refreshed, expected); } - #[test] - fn process_compacted_history_inserts_context_before_last_real_user_message_only() { + #[tokio::test] + async fn process_compacted_history_inserts_context_before_last_real_user_message_only() { let compacted_history = vec![ ResponseItem::Message { id: None, @@ -1073,18 +947,10 @@ keep me updated phase: None, }, ]; - let initial_context = vec![ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "fresh permissions".to_string(), - }], - end_turn: None, - phase: None, - }]; - let refreshed = process_compacted_history(compacted_history, &initial_context); - let expected = vec![ + let (refreshed, initial_context) = + process_compacted_history_with_test_session(compacted_history).await; + let mut expected = vec![ ResponseItem::Message { id: None, role: "user".to_string(), @@ -1103,6 +969,75 @@ keep me updated end_turn: None, phase: None, }, + ]; + expected.extend(initial_context); + expected.push(ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "latest user".to_string(), + }], + end_turn: None, + phase: None, + }); + assert_eq!(refreshed, expected); + } + + #[test] + fn insert_initial_context_before_last_real_user_or_summary_keeps_summary_last() { + let compacted_history = vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "older user".to_string(), + }], + end_turn: None, + phase: None, + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "latest user".to_string(), + }], + end_turn: None, + phase: None, + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: format!("{SUMMARY_PREFIX}\nsummary text"), + }], + end_turn: None, + phase: None, + }, + ]; + let initial_context = vec![ResponseItem::Message { + id: None, + role: "developer".to_string(), + content: vec![ContentItem::InputText { + text: "fresh permissions".to_string(), + }], + end_turn: None, + phase: None, + }]; + + let refreshed = insert_initial_context_before_last_real_user_or_summary( + compacted_history, + initial_context, + ); + let expected = vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "older user".to_string(), + }], + end_turn: None, + phase: None, + }, ResponseItem::Message { id: None, role: "developer".to_string(), @@ -1121,6 +1056,51 @@ keep me updated end_turn: None, phase: None, }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: format!("{SUMMARY_PREFIX}\nsummary text"), + }], + end_turn: None, + phase: None, + }, + ]; + assert_eq!(refreshed, expected); + } + + #[test] + fn insert_initial_context_before_last_real_user_or_summary_keeps_compaction_last() { + let compacted_history = vec![ResponseItem::Compaction { + encrypted_content: "encrypted".to_string(), + }]; + let initial_context = vec![ResponseItem::Message { + id: None, + role: "developer".to_string(), + content: vec![ContentItem::InputText { + text: "fresh permissions".to_string(), + }], + end_turn: None, + phase: None, + }]; + + let refreshed = insert_initial_context_before_last_real_user_or_summary( + compacted_history, + initial_context, + ); + let expected = vec![ + ResponseItem::Message { + id: None, + role: "developer".to_string(), + content: vec![ContentItem::InputText { + text: "fresh permissions".to_string(), + }], + end_turn: None, + phase: None, + }, + ResponseItem::Compaction { + encrypted_content: "encrypted".to_string(), + }, ]; assert_eq!(refreshed, expected); } diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index 3d181f8855..2a9106c722 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -3,7 +3,9 @@ use std::sync::Arc; use crate::Prompt; use crate::codex::Session; use crate::codex::TurnContext; +use crate::compact::InitialContextInjection; use crate::compact::extract_trailing_model_switch_update_for_compaction_request; +use crate::compact::insert_initial_context_before_last_real_user_or_summary; use crate::context_manager::ContextManager; use crate::context_manager::TotalTokenUsageBreakdown; use crate::context_manager::estimate_response_item_model_visible_bytes; @@ -25,8 +27,9 @@ use tracing::info; pub(crate) async fn run_inline_remote_auto_compact_task( sess: Arc, turn_context: Arc, + initial_context_injection: InitialContextInjection, ) -> CodexResult<()> { - run_remote_compact_task_inner(&sess, &turn_context).await?; + run_remote_compact_task_inner(&sess, &turn_context, initial_context_injection).await?; Ok(()) } @@ -41,14 +44,17 @@ pub(crate) async fn run_remote_compact_task( }); sess.send_event(&turn_context, start_event).await; - run_remote_compact_task_inner(&sess, &turn_context).await + run_remote_compact_task_inner(&sess, &turn_context, InitialContextInjection::DoNotInject).await } async fn run_remote_compact_task_inner( sess: &Arc, turn_context: &Arc, + initial_context_injection: InitialContextInjection, ) -> CodexResult<()> { - if let Err(err) = run_remote_compact_task_inner_impl(sess, turn_context).await { + if let Err(err) = + run_remote_compact_task_inner_impl(sess, turn_context, initial_context_injection).await + { let event = EventMsg::Error( err.to_error_event(Some("Error running remote compact task".to_string())), ); @@ -61,6 +67,7 @@ async fn run_remote_compact_task_inner( async fn run_remote_compact_task_inner_impl( sess: &Arc, turn_context: &Arc, + initial_context_injection: InitialContextInjection, ) -> CodexResult<()> { let compaction_item = TurnItem::ContextCompaction(ContextCompactionItem::new()); sess.emit_turn_item_started(turn_context, &compaction_item) @@ -122,9 +129,13 @@ async fn run_remote_compact_task_inner_impl( Err(err) }) .await?; - new_history = sess - .process_compacted_history(turn_context, new_history) - .await; + new_history = process_compacted_history( + sess.as_ref(), + turn_context.as_ref(), + new_history, + initial_context_injection, + ) + .await; // Reattach the stripped model-switch update only after successful compaction so the model // still sees the switch instructions on the next real sampling request. if let Some(model_switch_item) = stripped_model_switch_item { @@ -134,7 +145,12 @@ async fn run_remote_compact_task_inner_impl( if !ghost_snapshots.is_empty() { new_history.extend(ghost_snapshots); } - sess.replace_history(new_history.clone()).await; + let reference_context_item = match initial_context_injection { + InitialContextInjection::DoNotInject => None, + InitialContextInjection::BeforeLastUserMessage => Some(turn_context.to_turn_context_item()), + }; + sess.replace_history(new_history.clone(), reference_context_item) + .await; sess.recompute_token_usage(turn_context).await; let compacted_item = CompactedItem { @@ -149,6 +165,65 @@ async fn run_remote_compact_task_inner_impl( Ok(()) } +pub(crate) async fn process_compacted_history( + sess: &Session, + turn_context: &TurnContext, + mut compacted_history: Vec, + initial_context_injection: InitialContextInjection, +) -> Vec { + // Mid-turn compaction is the only path that must inject initial context above the last user + // message in the replacement history. Pre-turn compaction instead injects context after the + // compaction item, but mid-turn compaction keeps the compaction item last for model training. + let initial_context = if matches!( + initial_context_injection, + InitialContextInjection::BeforeLastUserMessage + ) { + sess.build_initial_context(turn_context).await + } else { + Vec::new() + }; + + compacted_history.retain(should_keep_compacted_history_item); + insert_initial_context_before_last_real_user_or_summary(compacted_history, initial_context) +} + +/// Returns whether an item from remote compaction output should be preserved. +/// +/// Called while processing the model-provided compacted transcript, before we +/// append fresh canonical context from the current session. +/// +/// We drop: +/// - `developer` messages because remote output can include stale/duplicated +/// instruction content. +/// - non-user-content `user` messages (session prefix/instruction wrappers), +/// keeping only real user messages as parsed by `parse_turn_item`. +/// +/// This intentionally keeps: +/// - `assistant` messages (future remote compaction models may emit them) +/// - `user`-role warnings and compaction-generated summary messages because +/// they parse as `TurnItem::UserMessage`. +fn should_keep_compacted_history_item(item: &ResponseItem) -> bool { + match item { + ResponseItem::Message { role, .. } if role == "developer" => false, + ResponseItem::Message { role, .. } if role == "user" => matches!( + crate::event_mapping::parse_turn_item(item), + Some(TurnItem::UserMessage(_)) + ), + ResponseItem::Message { role, .. } if role == "assistant" => true, + ResponseItem::Message { .. } => false, + ResponseItem::Compaction { .. } => true, + ResponseItem::Reasoning { .. } + | ResponseItem::LocalShellCall { .. } + | ResponseItem::FunctionCall { .. } + | ResponseItem::FunctionCallOutput { .. } + | ResponseItem::CustomToolCall { .. } + | ResponseItem::CustomToolCallOutput { .. } + | ResponseItem::WebSearchCall { .. } + | ResponseItem::GhostSnapshot { .. } + | ResponseItem::Other => false, + } +} + #[derive(Debug)] struct CompactRequestLogData { failing_compaction_request_model_visible_bytes: i64, diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 0cd935523e..52df99fb02 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -27,12 +27,15 @@ pub(crate) struct ContextManager { /// The oldest items are at the beginning of the vector. items: Vec, token_info: Option, - /// Previous turn context snapshot used for diffing context and producing - /// model-visible settings update items. + /// Reference context snapshot used for diffing and producing model-visible + /// settings update items. + /// + /// This is the baseline for the next regular model turn, and may already + /// match the current turn after context updates are persisted. /// /// When this is `None`, settings diffing treats the next turn as having no /// baseline and emits a full reinjection of context state. - previous_context_item: Option, + reference_context_item: Option, } #[derive(Debug, Clone, Copy, Default)] @@ -48,7 +51,7 @@ impl ContextManager { Self { items: Vec::new(), token_info: TokenUsageInfo::new_or_append(&None, &None, None), - previous_context_item: None, + reference_context_item: None, } } @@ -60,12 +63,12 @@ impl ContextManager { self.token_info = info; } - pub(crate) fn set_previous_context_item(&mut self, item: Option) { - self.previous_context_item = item; + pub(crate) fn set_reference_context_item(&mut self, item: Option) { + self.reference_context_item = item; } - pub(crate) fn previous_context_item(&self) -> Option { - self.previous_context_item.clone() + pub(crate) fn reference_context_item(&self) -> Option { + self.reference_context_item.clone() } pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { diff --git a/codex-rs/core/src/context_manager/updates.rs b/codex-rs/core/src/context_manager/updates.rs index 217889a724..cdb53ff0c4 100644 --- a/codex-rs/core/src/context_manager/updates.rs +++ b/codex-rs/core/src/context_manager/updates.rs @@ -97,11 +97,10 @@ pub(crate) fn personality_message_for( } pub(crate) fn build_model_instructions_update_item( - previous: Option<&TurnContextItem>, - resumed_model: Option<&str>, + previous_user_turn_model: Option<&str>, next: &TurnContext, ) -> Option { - let previous_model = resumed_model.or_else(|| previous.map(|prev| prev.model.as_str()))?; + let previous_model = previous_user_turn_model?; if previous_model == next.model_info.slug { return None; } @@ -116,7 +115,7 @@ pub(crate) fn build_model_instructions_update_item( pub(crate) fn build_settings_update_items( previous: Option<&TurnContextItem>, - resumed_model: Option<&str>, + previous_user_turn_model: Option<&str>, next: &TurnContext, shell: &Shell, exec_policy: &Policy, @@ -124,6 +123,13 @@ pub(crate) fn build_settings_update_items( ) -> Vec { let mut update_items = Vec::new(); + // Keep model-switch instructions first so model-specific guidance is read before + // any other context diffs on this turn. + if let Some(model_instructions_item) = + build_model_instructions_update_item(previous_user_turn_model, next) + { + update_items.push(model_instructions_item); + } if let Some(env_item) = build_environment_update_item(previous, next, shell) { update_items.push(env_item); } @@ -133,11 +139,6 @@ pub(crate) fn build_settings_update_items( if let Some(collaboration_mode_item) = build_collaboration_mode_update_item(previous, next) { update_items.push(collaboration_mode_item); } - if let Some(model_instructions_item) = - build_model_instructions_update_item(previous, resumed_model, next) - { - update_items.push(model_instructions_item); - } if let Some(personality_item) = build_personality_update_item(previous, next, personality_feature_enabled) { diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 76c365ab5b..160225174f 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -21,12 +21,9 @@ pub(crate) struct SessionState { pub(crate) server_reasoning_included: bool, pub(crate) dependency_env: HashMap, pub(crate) mcp_dependency_prompted: HashSet, - /// Whether the session's initial context has been seeded into history. - /// - /// TODO(owen): This is a temporary solution to avoid updating a thread's updated_at - /// timestamp when resuming a session. Remove this once SQLite is in place. - pub(crate) initial_context_seeded: bool, - /// Previous model seen by the session, used for model-switch handling on task start. + /// Model used by the latest regular user turn, used for model-switch handling + /// on subsequent regular turns (including full-context reinjection after + /// resume or `/compact`). previous_model: Option, /// Startup regular task pre-created during session initialization. pub(crate) startup_regular_task: Option, @@ -45,7 +42,6 @@ impl SessionState { server_reasoning_included: false, dependency_env: HashMap::new(), mcp_dependency_prompted: HashSet::new(), - initial_context_seeded: false, previous_model: None, startup_regular_task: None, active_mcp_tool_selection: None, @@ -73,20 +69,26 @@ impl SessionState { self.history.clone() } - pub(crate) fn replace_history(&mut self, items: Vec) { + pub(crate) fn replace_history( + &mut self, + items: Vec, + reference_context_item: Option, + ) { self.history.replace(items); + self.history + .set_reference_context_item(reference_context_item); } pub(crate) fn set_token_info(&mut self, info: Option) { self.history.set_token_info(info); } - pub(crate) fn set_previous_context_item(&mut self, item: Option) { - self.history.set_previous_context_item(item); + pub(crate) fn set_reference_context_item(&mut self, item: Option) { + self.history.set_reference_context_item(item); } - pub(crate) fn previous_context_item(&self) -> Option { - self.history.previous_context_item() + pub(crate) fn reference_context_item(&self) -> Option { + self.history.reference_context_item() } // Token/rate limit helpers diff --git a/codex-rs/core/src/tasks/compact.rs b/codex-rs/core/src/tasks/compact.rs index b56f7b1df5..db2a494c3e 100644 --- a/codex-rs/core/src/tasks/compact.rs +++ b/codex-rs/core/src/tasks/compact.rs @@ -25,22 +25,21 @@ impl SessionTask for CompactTask { _cancellation_token: CancellationToken, ) -> Option { let session = session.clone_session(); - if crate::compact::should_use_remote_compact_task(&ctx.provider) { + let _ = if crate::compact::should_use_remote_compact_task(&ctx.provider) { let _ = session.services.otel_manager.counter( "codex.task.compact", 1, &[("type", "remote")], ); - let _ = crate::compact_remote::run_remote_compact_task(session, ctx).await; + crate::compact_remote::run_remote_compact_task(session.clone(), ctx).await } else { let _ = session.services.otel_manager.counter( "codex.task.compact", 1, &[("type", "local")], ); - let _ = crate::compact::run_compact_task(session, ctx, input).await; - } - + crate::compact::run_compact_task(session.clone(), ctx, input).await + }; None } } diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index eb04619ee9..861b18a52c 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -121,8 +121,6 @@ impl Session { ) { self.abort_all_tasks(TurnAbortReason::Replaced).await; self.clear_connector_selection().await; - self.seed_initial_context_if_needed(turn_context.as_ref()) - .await; let task: Arc = Arc::new(task); let task_kind = task.kind(); @@ -140,7 +138,6 @@ impl Session { tokio::spawn( async move { let ctx_for_finish = Arc::clone(&ctx); - let model_slug = ctx_for_finish.model_info.slug.clone(); let last_agent_message = task_for_run .run( Arc::clone(&session_ctx), @@ -151,9 +148,6 @@ impl Session { .await; let sess = session_ctx.clone_session(); sess.flush_rollout().await; - // Update previous model before TurnComplete is emitted so - // immediately following turns observe the correct switch state. - sess.set_previous_model(Some(model_slug)).await; if !task_cancellation_token.is_cancelled() { // Emit completion uniformly from spawn site so all tasks share the same lifecycle. sess.on_task_finished(Arc::clone(&ctx_for_finish), last_agent_message) @@ -278,10 +272,6 @@ impl Session { task.handle.abort(); - // Set previous model even when interrupted so model-switch handling stays correct. - self.set_previous_model(Some(task.turn_context.model_info.slug.clone())) - .await; - let session_ctx = Arc::new(SessionTaskContext::new(Arc::clone(self))); session_task .abort(session_ctx, Arc::clone(&task.turn_context)) diff --git a/codex-rs/core/src/tasks/undo.rs b/codex-rs/core/src/tasks/undo.rs index bb3b6d3152..b2fb4577a8 100644 --- a/codex-rs/core/src/tasks/undo.rs +++ b/codex-rs/core/src/tasks/undo.rs @@ -101,7 +101,8 @@ impl SessionTask for UndoTask { match restore_result { Ok(Ok(())) => { items.remove(idx); - sess.replace_history(items).await; + let reference_context_item = sess.reference_context_item().await; + sess.replace_history(items, reference_context_item).await; let short_id: String = commit_id.chars().take(7).collect(); info!(commit_id = commit_id, "Undo restored ghost snapshot"); completed.success = true; diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index d356193f58..3e378fcd7c 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -101,6 +101,10 @@ pub(crate) async fn execute_user_shell_command( // Auxiliary mode runs within an existing active turn. That turn already // emitted TurnStarted, so emitting another TurnStarted here would create // duplicate turn lifecycle events and confuse clients. + // TODO(ccunningham): After TurnStarted, emit model-visible turn context diffs for + // standalone lifecycle tasks (for example /shell, and review once it emits TurnStarted). + // `/compact` is an intentional exception because compaction requests should not include + // freshly reinjected context before the summary/replacement history is applied. let event = EventMsg::TurnStarted(TurnStartedEvent { turn_id: turn_context.sub_id.clone(), model_context_window: turn_context.model_context_window(), diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 702e13f81d..649d1cf0bc 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -867,7 +867,7 @@ pub async fn mount_compact_json_once(server: &MockServer, body: serde_json::Valu /// Mount a `/responses/compact` mock that mirrors the default remote compaction shape: /// keep user+developer messages from the request, drop assistant/tool artifacts, and append one -/// summary user message. +/// compaction item carrying the provided summary text. pub async fn mount_compact_user_history_with_summary_once( server: &MockServer, summary_text: &str, @@ -911,6 +911,9 @@ pub async fn mount_compact_user_history_with_summary_sequence( .cloned() .unwrap_or_default() .into_iter() + // TODO(ccunningham): Update this mock to match future compaction model behavior: + // return user/developer/assistant messages since the last compaction item, then + // append a single newest compaction item. // Match current remote compaction behavior: keep user/developer messages and // omit assistant/tool history entries. .filter(|item| { @@ -921,11 +924,10 @@ pub async fn mount_compact_user_history_with_summary_sequence( ) }) .collect::>(); - // Append the synthetic summary message as the newest user item. + // Append a synthetic compaction item as the newest item. output.push(serde_json::json!({ - "type": "message", - "role": "user", - "content": [{"type": "input_text", "text": summary_text}], + "type": "compaction", + "encrypted_content": summary_text, })); ResponseTemplate::new(200) .insert_header("content-type", "application/json") diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index 08850ec38f..c4745ab20e 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -363,7 +363,7 @@ async fn summarize_context_three_requests_and_instructions() { codex.submit(Op::Shutdown).await.unwrap(); wait_for_event(&codex, |ev| matches!(ev, EventMsg::ShutdownComplete)).await; - // Verify rollout contains APITurn entries for each API call and a Compacted entry. + // Verify rollout contains regular sampling TurnContext entries and a Compacted entry. println!("rollout path: {}", rollout_path.display()); let text = std::fs::read_to_string(&rollout_path).unwrap_or_else(|e| { panic!( @@ -371,7 +371,7 @@ async fn summarize_context_three_requests_and_instructions() { rollout_path.display() ) }); - let mut api_turn_count = 0usize; + let mut regular_turn_context_count = 0usize; let mut saw_compacted_summary = false; for line in text.lines() { let trimmed = line.trim(); @@ -383,7 +383,7 @@ async fn summarize_context_three_requests_and_instructions() { }; match entry.item { RolloutItem::TurnContext(_) => { - api_turn_count += 1; + regular_turn_context_count += 1; } RolloutItem::Compacted(ci) => { if ci.message == expected_summary_message { @@ -395,8 +395,8 @@ async fn summarize_context_three_requests_and_instructions() { } assert!( - api_turn_count == 3, - "expected three APITurn entries in rollout" + regular_turn_context_count == 2, + "expected two regular sampling TurnContext entries in rollout" ); assert!( saw_compacted_summary, @@ -2414,26 +2414,36 @@ async fn manual_compact_twice_preserves_latest_user_messages() { first_request_user_texts[first_turn_user_index], first_user_message, "first turn request should end with the submitted user message" ); - let seeded_user_prefix = &first_request_user_texts[..first_turn_user_index]; + let initial_seeded_user_prefix = &first_request_user_texts[..first_turn_user_index]; let final_request_user_texts = requests .last() .unwrap_or_else(|| panic!("final turn request missing for {final_user_message}")) .message_input_texts("user"); assert!( - final_request_user_texts - .as_slice() - .starts_with(seeded_user_prefix), - "final request should start with seeded user prefix from first request: {seeded_user_prefix:?}" + !initial_seeded_user_prefix.is_empty(), + "first turn should include seeded user prefix before the submitted user message" ); - let final_output = &final_request_user_texts[seeded_user_prefix.len()..]; - let expected = vec![ + let (final_request_last_user_text, final_request_before_last_user) = final_request_user_texts + .split_last() + .unwrap_or_else(|| panic!("final turn request missing user messages")); + assert_eq!( + final_request_last_user_text, final_user_message, + "final turn request should end with the submitted user message" + ); + let history_before_seeded_prefix = final_request_before_last_user + .strip_suffix(initial_seeded_user_prefix) + .unwrap_or_else(|| { + panic!( + "final request should end with the seeded user prefix from the first request: {initial_seeded_user_prefix:?}" + ) + }); + let expected_history = vec![ first_user_message.to_string(), second_user_message.to_string(), expected_second_summary, - final_user_message.to_string(), ]; - assert_eq!(final_output, expected.as_slice()); + assert_eq!(history_before_seeded_prefix, expected_history.as_slice()); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/codex-rs/core/tests/suite/compact_remote.rs b/codex-rs/core/tests/suite/compact_remote.rs index c9acde41ab..6baccc16f4 100644 --- a/codex-rs/core/tests/suite/compact_remote.rs +++ b/codex-rs/core/tests/suite/compact_remote.rs @@ -93,12 +93,9 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> { ) .await; - let compacted_history = vec![ - responses::user_message_item("REMOTE_COMPACTED_SUMMARY"), - ResponseItem::Compaction { - encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(), - }, - ]; + let compacted_history = vec![ResponseItem::Compaction { + encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(), + }]; let compact_mock = responses::mount_compact_json_once( harness.server(), serde_json::json!({ "output": compacted_history.clone() }), @@ -159,7 +156,7 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> { let follow_up_request = response_requests.last().expect("follow-up request missing"); let follow_up_body = follow_up_request.body_json().to_string(); assert!( - follow_up_body.contains("REMOTE_COMPACTED_SUMMARY"), + follow_up_body.contains("\"type\":\"compaction\""), "expected follow-up request to use compacted history" ); assert!( @@ -178,7 +175,7 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> { insta::assert_snapshot!( "remote_manual_compact_with_history_shapes", format_labeled_requests_snapshot( - "Remote manual /compact where remote compact output is summary-only: follow-up layout uses returned summary plus new user message.", + "Remote manual /compact where remote compact output is compaction-only: follow-up layout uses the returned compaction item plus new user message.", &[ ("Remote Compaction Request", &compact_request), ("Remote Post-Compaction History Layout", follow_up_request), @@ -958,7 +955,6 @@ async fn remote_compact_persists_replacement_history_in_rollout() -> Result<()> .await; let compacted_history = vec![ - responses::user_message_item("COMPACTED_USER_SUMMARY"), ResponseItem::Compaction { encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(), }, @@ -1012,17 +1008,6 @@ async fn remote_compact_persists_replacement_history_in_rollout() -> Result<()> && compacted.message.is_empty() && let Some(replacement_history) = compacted.replacement_history.as_ref() { - let has_compacted_user_summary = replacement_history.iter().any(|item| { - matches!( - item, - ResponseItem::Message { role, content, .. } - if role == "user" - && content.iter().any(|part| matches!( - part, - ContentItem::InputText { text } if text == "COMPACTED_USER_SUMMARY" - )) - ) - }); let has_compaction_item = replacement_history.iter().any(|item| { matches!( item, @@ -1054,7 +1039,7 @@ async fn remote_compact_persists_replacement_history_in_rollout() -> Result<()> ) }); - if has_compacted_user_summary && has_compaction_item && has_compacted_assistant_note { + if has_compaction_item && has_compacted_assistant_note { assert!( !has_permissions_developer_message, "manual remote compact rollout replacement history should not inject permissions context" @@ -1110,7 +1095,6 @@ async fn remote_compact_and_resume_refresh_stale_developer_instructions() -> Res .await; let compacted_history = vec![ - responses::user_message_item("REMOTE_COMPACTED_SUMMARY"), ResponseItem::Message { id: None, role: "developer".to_string(), @@ -1196,8 +1180,8 @@ async fn remote_compact_and_resume_refresh_stale_developer_instructions() -> Res "fresh developer instructions should be present after compaction" ); assert!( - after_compact_body.contains("REMOTE_COMPACTED_SUMMARY"), - "compacted summary should be present after compaction" + after_compact_body.contains("ENCRYPTED_COMPACTION_SUMMARY"), + "compaction item should be present after compaction" ); let after_resume_body = after_resume_request.body_json().to_string(); @@ -1210,8 +1194,8 @@ async fn remote_compact_and_resume_refresh_stale_developer_instructions() -> Res "fresh developer instructions should be present after resume" ); assert!( - after_resume_body.contains("REMOTE_COMPACTED_SUMMARY"), - "compacted summary should persist after resume" + after_resume_body.contains("ENCRYPTED_COMPACTION_SUMMARY"), + "compaction item should persist after resume" ); Ok(()) @@ -1243,7 +1227,6 @@ async fn remote_compact_refreshes_stale_developer_instructions_without_resume() .await; let compacted_history = vec![ - responses::user_message_item("REMOTE_COMPACTED_SUMMARY"), ResponseItem::Message { id: None, role: "developer".to_string(), @@ -1302,8 +1285,8 @@ async fn remote_compact_refreshes_stale_developer_instructions_without_resume() "fresh developer instructions should be present after compaction" ); assert!( - after_compact_body.contains("REMOTE_COMPACTED_SUMMARY"), - "compacted summary should be present after compaction" + after_compact_body.contains("ENCRYPTED_COMPACTION_SUMMARY"), + "compaction item should be present after compaction" ); Ok(()) @@ -1706,7 +1689,7 @@ async fn snapshot_request_shape_remote_mid_turn_continuation_compaction() -> Res insta::assert_snapshot!( "remote_mid_turn_compaction_shapes", format_labeled_requests_snapshot( - "Remote mid-turn continuation compaction after tool output: compact request includes tool artifacts and follow-up request includes the summary.", + "Remote mid-turn continuation compaction after tool output: compact request includes tool artifacts and the follow-up request includes the returned compaction item.", &[ ("Remote Compaction Request", &compact_request), ("Remote Post-Compaction History Layout", &requests[1]), @@ -1749,9 +1732,9 @@ async fn snapshot_request_shape_remote_mid_turn_compaction_summary_only_reinject ) .await; - let compacted_history = vec![responses::user_message_item(&summary_with_prefix( - "REMOTE_SUMMARY_ONLY", - ))]; + let compacted_history = vec![ResponseItem::Compaction { + encrypted_content: summary_with_prefix("REMOTE_SUMMARY_ONLY"), + }]; let compact_mock = responses::mount_compact_json_once( harness.server(), serde_json::json!({ "output": compacted_history }), @@ -1786,7 +1769,7 @@ async fn snapshot_request_shape_remote_mid_turn_compaction_summary_only_reinject insta::assert_snapshot!( "remote_mid_turn_compaction_summary_only_reinjects_context_shapes", format_labeled_requests_snapshot( - "Remote mid-turn compaction where compact output has only summary user content: continuation layout reinjects canonical context before that summary.", + "Remote mid-turn compaction where compact output has only a compaction item: continuation layout reinjects context before that compaction item.", &[ ("Remote Compaction Request", &compact_request), ( @@ -1893,13 +1876,13 @@ async fn snapshot_request_shape_remote_mid_turn_compaction_multi_summary_reinjec insta::assert_snapshot!( "remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes", format_labeled_requests_snapshot( - "Remote mid-turn compaction after an earlier summary compaction: the older summary remains in model-visible history and round-trips into the next compact request.", + "After a prior manual /compact produced an older remote compaction item, the next turn hits remote auto-compaction before the next sampling request. The compact request carries forward that earlier compaction item, and the next sampling request shows the latest compaction item with context reinjected before USER_TWO.", &[ + ("Remote Compaction Request", &compact_request), ( - "Second Turn Request (Before Mid-Turn Compaction)", + "Second Turn Request (After Compaction)", &second_turn_request ), - ("Remote Compaction Request", &compact_request), ] ) ); diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index fc77a2621f..b66edb84aa 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -81,25 +81,32 @@ fn normalize_line_endings_str(text: &str) -> String { } } -fn extract_summary_message(request: &Value, summary_text: &str) -> Value { +fn extract_summary_user_text(request: &Value, summary_text: &str) -> String { + json_message_input_texts(request, "user") + .into_iter() + .find(|text| text.contains(summary_text)) + .unwrap_or_else(|| panic!("expected summary message {summary_text}")) +} + +fn json_message_input_texts(request: &Value, role: &str) -> Vec { request .get("input") .and_then(Value::as_array) - .and_then(|items| { - items.iter().find(|item| { - item.get("type").and_then(Value::as_str) == Some("message") - && item.get("role").and_then(Value::as_str) == Some("user") - && item - .get("content") - .and_then(Value::as_array) - .and_then(|arr| arr.first()) - .and_then(|entry| entry.get("text")) - .and_then(Value::as_str) - .is_some_and(|text| text.contains(summary_text)) - }) + .into_iter() + .flatten() + .filter(|item| { + item.get("type").and_then(Value::as_str) == Some("message") + && item.get("role").and_then(Value::as_str) == Some(role) }) - .cloned() - .unwrap_or_else(|| panic!("expected summary message {summary_text}")) + .filter_map(|item| { + item.get("content") + .and_then(Value::as_array) + .and_then(|content| content.first()) + .and_then(|entry| entry.get("text")) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect() } fn normalize_compact_prompts(requests: &mut [Value]) { @@ -200,459 +207,88 @@ async fn compact_resume_and_fork_preserve_model_history_view() { &fork_arr[..compact_arr.len()] ); - let expected_model = requests[0]["model"] - .as_str() - .unwrap_or_default() - .to_string(); - let prompt = requests[0]["instructions"] - .as_str() - .unwrap_or_default() - .to_string(); - let permissions_message = requests[0]["input"][0].clone(); - let user_instructions = requests[0]["input"][1]["content"][0]["text"] - .as_str() - .unwrap_or_default() - .to_string(); - let environment_context = requests[0]["input"][2]["content"][0]["text"] - .as_str() - .unwrap_or_default() - .to_string(); - let tool_calls = json!(requests[0]["tools"].as_array()); - let prompt_cache_key = requests[0]["prompt_cache_key"] - .as_str() - .unwrap_or_default() - .to_string(); - let fork_prompt_cache_key = requests[requests.len() - 1]["prompt_cache_key"] - .as_str() - .unwrap_or_default() - .to_string(); - let summary_after_compact = extract_summary_message(&requests[2], SUMMARY_TEXT); - let summary_after_resume = extract_summary_message(&requests[3], SUMMARY_TEXT); - let summary_after_fork = extract_summary_message(&requests[4], SUMMARY_TEXT); - let user_turn_1 = json!( - { - "model": expected_model, - "instructions": prompt, - "input": [ - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hello world" - } - ] + let first_request_user_texts = json_message_input_texts(&requests[0], "user"); + let first_turn_user_index = first_request_user_texts + .len() + .checked_sub(1) + .unwrap_or_else(|| panic!("first turn request missing user messages")); + assert_eq!( + first_request_user_texts[first_turn_user_index], + "hello world" + ); + let seeded_user_prefix = &first_request_user_texts[..first_turn_user_index]; + let summary_after_compact = extract_summary_user_text(&requests[2], SUMMARY_TEXT); + let summary_after_resume = extract_summary_user_text(&requests[3], SUMMARY_TEXT); + let summary_after_fork = extract_summary_user_text(&requests[4], SUMMARY_TEXT); + let mut expected_after_compact_user_texts = + vec!["hello world".to_string(), summary_after_compact]; + expected_after_compact_user_texts.extend_from_slice(seeded_user_prefix); + expected_after_compact_user_texts.push("AFTER_COMPACT".to_string()); + assert_eq!( + json_message_input_texts(&requests[2], "user"), + expected_after_compact_user_texts + ); + + let mut expected_after_resume_user_texts = + vec!["hello world".to_string(), summary_after_resume]; + expected_after_resume_user_texts.extend_from_slice(seeded_user_prefix); + expected_after_resume_user_texts.push("AFTER_COMPACT".to_string()); + let after_resume_user_texts = json_message_input_texts(&requests[3], "user"); + let (after_resume_last, after_resume_prefix) = after_resume_user_texts + .split_last() + .unwrap_or_else(|| panic!("after-resume request missing user messages")); + assert_eq!(after_resume_last, "AFTER_RESUME"); + assert!( + after_resume_prefix.starts_with(&expected_after_resume_user_texts), + "after-resume user texts should preserve compacted history prefix" + ); + let after_resume_seeded_suffix = &after_resume_prefix[expected_after_resume_user_texts.len()..]; + if seeded_user_prefix.is_empty() { + assert!( + after_resume_seeded_suffix.is_empty(), + "after-resume request should not append unexpected user prefix items" + ); + } else { + let mut chunks = after_resume_seeded_suffix.chunks_exact(seeded_user_prefix.len()); + assert!( + chunks.remainder().is_empty(), + "after-resume suffix should be whole seeded-prefix repeats" + ); + for chunk in &mut chunks { + assert_eq!(chunk, seeded_user_prefix); } - ], - "tools": tool_calls, - "tool_choice": "auto", - "parallel_tool_calls": false, - "reasoning": { - "effort": "medium", - "summary": "auto" - }, - "store": false, - "stream": true, - "include": [ - "reasoning.encrypted_content" - ], - "prompt_cache_key": prompt_cache_key - }); - let compact_1 = json!( - { - "model": expected_model, - "instructions": prompt, - "input": [ - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hello world" - } - ] - }, - { - "type": "message", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "FIRST_REPLY" - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": SUMMARIZATION_PROMPT - } - ] + } + + let after_fork_user_texts = json_message_input_texts(&requests[4], "user"); + let mut expected_after_fork_history_prefix = + vec!["hello world".to_string(), summary_after_fork]; + expected_after_fork_history_prefix.extend_from_slice(seeded_user_prefix); + expected_after_fork_history_prefix.push("AFTER_COMPACT".to_string()); + let (after_fork_last, after_fork_prefix) = after_fork_user_texts + .split_last() + .unwrap_or_else(|| panic!("after-fork request missing user messages")); + assert_eq!(after_fork_last, "AFTER_FORK"); + assert!( + after_fork_prefix.starts_with(&expected_after_fork_history_prefix), + "after-fork user texts should preserve compacted user history prefix" + ); + let after_fork_seeded_suffix = &after_fork_prefix[expected_after_fork_history_prefix.len()..]; + if seeded_user_prefix.is_empty() { + assert!( + after_fork_seeded_suffix.is_empty(), + "after-fork request should not append unexpected user prefix items" + ); + } else { + let mut chunks = after_fork_seeded_suffix.chunks_exact(seeded_user_prefix.len()); + assert!( + chunks.remainder().is_empty(), + "after-fork suffix should be whole seeded-prefix repeats" + ); + for chunk in &mut chunks { + assert_eq!(chunk, seeded_user_prefix); } - ], - "tools": [], - "tool_choice": "auto", - "parallel_tool_calls": false, - "reasoning": { - "effort": "medium", - "summary": "auto" - }, - "store": false, - "stream": true, - "include": [ - "reasoning.encrypted_content" - ], - "prompt_cache_key": prompt_cache_key - }); - let user_turn_2_after_compact = json!( - { - "model": expected_model, - "instructions": prompt, - "input": [ - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hello world" - } - ] - }, - summary_after_compact, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_COMPACT" - } - ] - } - ], - "tools": tool_calls, - "tool_choice": "auto", - "parallel_tool_calls": false, - "reasoning": { - "effort": "medium", - "summary": "auto" - }, - "store": false, - "stream": true, - "include": [ - "reasoning.encrypted_content" - ], - "prompt_cache_key": prompt_cache_key - }); - let usert_turn_3_after_resume = json!( - { - "model": expected_model, - "instructions": prompt, - "input": [ - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hello world" - } - ] - }, - summary_after_resume, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_COMPACT" - } - ] - }, - { - "type": "message", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "AFTER_COMPACT_REPLY" - } - ] - }, - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_RESUME" - } - ] - } - ], - "tools": tool_calls, - "tool_choice": "auto", - "parallel_tool_calls": false, - "reasoning": { - "effort": "medium", - "summary": "auto" - }, - "store": false, - "stream": true, - "include": [ - "reasoning.encrypted_content" - ], - "prompt_cache_key": prompt_cache_key - }); - let user_turn_3_after_fork = json!( - { - "model": expected_model, - "instructions": prompt, - "input": [ - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "hello world" - } - ] - }, - summary_after_fork, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_COMPACT" - } - ] - }, - { - "type": "message", - "role": "assistant", - "content": [ - { - "type": "output_text", - "text": "AFTER_COMPACT_REPLY" - } - ] - }, - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_context - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_FORK" - } - ] - } - ], - "tools": tool_calls, - "tool_choice": "auto", - "parallel_tool_calls": false, - "reasoning": { - "effort": "medium", - "summary": "auto" - }, - "store": false, - "stream": true, - "include": [ - "reasoning.encrypted_content" - ], - "prompt_cache_key": fork_prompt_cache_key - }); - let mut expected = json!([ - user_turn_1, - compact_1, - user_turn_2_after_compact, - usert_turn_3_after_resume, - user_turn_3_after_fork - ]); - normalize_line_endings(&mut expected); - if let Some(arr) = expected.as_array_mut() { - normalize_compact_prompts(arr); } assert_eq!(requests.len(), 5); - assert_eq!(json!(requests), expected); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -725,118 +361,47 @@ async fn compact_resume_after_second_compaction_preserves_history() { compact_filtered.as_slice(), &resume_filtered[..compact_filtered.len()] ); - // hard coded test - let prompt = requests[0]["instructions"] - .as_str() - .unwrap_or_default() - .to_string(); - let permissions_message = requests[0]["input"][0].clone(); - let user_instructions = requests[0]["input"][1]["content"][0]["text"] - .as_str() - .unwrap_or_default() - .to_string(); - let environment_instructions = requests[0]["input"][2]["content"][0]["text"] - .as_str() - .unwrap_or_default() - .to_string(); - - // Build expected final request input: initial context + forked user message + - // compacted summary + post-compact user message + resumed user message. + let first_request_user_texts = json_message_input_texts(&requests[0], "user"); + let first_turn_user_index = first_request_user_texts + .len() + .checked_sub(1) + .unwrap_or_else(|| panic!("first turn request missing user messages")); + assert_eq!( + first_request_user_texts[first_turn_user_index], + "hello world" + ); + let seeded_user_prefix = &first_request_user_texts[..first_turn_user_index]; let summary_after_second_compact = - extract_summary_message(&requests[requests.len() - 3], SUMMARY_TEXT); - - let mut expected = json!([ - { - "instructions": prompt, - "input": [ - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_FORK" - } - ] - }, - summary_after_second_compact, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_COMPACT_2" - } - ] - }, - permissions_message, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": user_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": environment_instructions - } - ] - }, - { - "type": "message", - "role": "user", - "content": [ - { - "type": "input_text", - "text": "AFTER_SECOND_RESUME" - } - ] - } - ], - } - ]); - normalize_line_endings(&mut expected); - let mut last_request_after_2_compacts = json!([{ - "instructions": requests[requests.len() -1]["instructions"], - "input": requests[requests.len() -1]["input"], - }]); - if let Some(arr) = expected.as_array_mut() { - normalize_compact_prompts(arr); + extract_summary_user_text(&requests[requests.len() - 3], SUMMARY_TEXT); + let mut expected_after_second_compact_user_texts = + vec!["AFTER_FORK".to_string(), summary_after_second_compact]; + expected_after_second_compact_user_texts.extend_from_slice(seeded_user_prefix); + expected_after_second_compact_user_texts.push("AFTER_COMPACT_2".to_string()); + let final_user_texts = json_message_input_texts(&requests[requests.len() - 1], "user"); + let (final_last, final_prefix) = final_user_texts + .split_last() + .unwrap_or_else(|| panic!("after-second-resume request missing user messages")); + assert_eq!(final_last, AFTER_SECOND_RESUME); + assert!( + final_prefix.starts_with(&expected_after_second_compact_user_texts), + "after-second-resume user texts should preserve post-compact user history prefix" + ); + let final_seeded_suffix = &final_prefix[expected_after_second_compact_user_texts.len()..]; + if seeded_user_prefix.is_empty() { + assert!( + final_seeded_suffix.is_empty(), + "after-second-resume request should not append unexpected user prefix items" + ); + } else { + let mut chunks = final_seeded_suffix.chunks_exact(seeded_user_prefix.len()); + assert!( + chunks.remainder().is_empty(), + "after-second-resume suffix should be whole seeded-prefix repeats" + ); + for chunk in &mut chunks { + assert_eq!(chunk, seeded_user_prefix); + } } - if let Some(arr) = last_request_after_2_compacts.as_array_mut() { - normalize_compact_prompts(arr); - } - assert_eq!(expected, last_request_after_2_compacts); } fn normalize_line_endings(value: &mut Value) { diff --git a/codex-rs/core/tests/suite/model_visible_layout.rs b/codex-rs/core/tests/suite/model_visible_layout.rs index eda1b89151..f3daf06c8b 100644 --- a/codex-rs/core/tests/suite/model_visible_layout.rs +++ b/codex-rs/core/tests/suite/model_visible_layout.rs @@ -308,6 +308,8 @@ async fn snapshot_model_visible_layout_resume_with_personality_change() -> Resul config.personality = Some(Personality::Pragmatic); }); let resumed = resume_builder.resume(&server, home, rollout_path).await?; + let resume_override_cwd = resumed.cwd_path().join(PRETURN_CONTEXT_DIFF_CWD); + fs::create_dir_all(&resume_override_cwd)?; resumed .codex .submit(Op::UserTurn { @@ -316,7 +318,7 @@ async fn snapshot_model_visible_layout_resume_with_personality_change() -> Resul text_elements: Vec::new(), }], final_output_json_schema: None, - cwd: resumed.cwd_path().to_path_buf(), + cwd: resume_override_cwd, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), model: resumed.session_configured.model.clone(), @@ -398,10 +400,12 @@ async fn snapshot_model_visible_layout_resume_override_matches_rollout_model() - config.model = Some("gpt-5.2-codex".to_string()); }); let resumed = resume_builder.resume(&server, home, rollout_path).await?; + let resume_override_cwd = resumed.cwd_path().join(PRETURN_CONTEXT_DIFF_CWD); + fs::create_dir_all(&resume_override_cwd)?; resumed .codex .submit(Op::OverrideTurnContext { - cwd: None, + cwd: Some(resume_override_cwd), approval_policy: None, sandbox_policy: None, windows_sandbox_level: None, diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index cd3b4272a0..351d1d5752 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -672,12 +672,7 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res }); let expected_permissions_msg = body1["input"][0].clone(); let body1_input = body1["input"].as_array().expect("input array"); - let expected_permissions_msg_2 = body2["input"][body1_input.len() + 1].clone(); - assert_ne!( - expected_permissions_msg_2, expected_permissions_msg, - "expected updated permissions message after per-turn override" - ); - let expected_model_switch_msg = body2["input"][body1_input.len() + 2].clone(); + let expected_model_switch_msg = body2["input"][body1_input.len()].clone(); assert_eq!( expected_model_switch_msg["role"].as_str(), Some("developer") @@ -688,10 +683,15 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res .is_some_and(|text| text.contains("")), "expected model switch message after model override: {expected_model_switch_msg:?}" ); + let expected_permissions_msg_2 = body2["input"][body1_input.len() + 2].clone(); + assert_ne!( + expected_permissions_msg_2, expected_permissions_msg, + "expected updated permissions message after per-turn override" + ); let mut expected_body2 = body1_input.to_vec(); + expected_body2.push(expected_model_switch_msg); expected_body2.push(expected_env_msg_2); expected_body2.push(expected_permissions_msg_2); - expected_body2.push(expected_model_switch_msg); expected_body2.push(expected_user_message_2); assert_eq!(body2["input"], serde_json::Value::Array(expected_body2)); @@ -900,12 +900,7 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu assert_eq!(body1["input"], expected_input_1); let body1_input = body1["input"].as_array().expect("input array"); - let expected_permissions_msg_2 = body2["input"][body1_input.len()].clone(); - assert_ne!( - expected_permissions_msg_2, expected_permissions_msg, - "expected updated permissions message after policy change" - ); - let expected_model_switch_msg = body2["input"][body1_input.len() + 1].clone(); + let expected_model_switch_msg = body2["input"][body1_input.len()].clone(); assert_eq!( expected_model_switch_msg["role"].as_str(), Some("developer") @@ -916,14 +911,19 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu .is_some_and(|text| text.contains("")), "expected model switch message after model override: {expected_model_switch_msg:?}" ); + let expected_permissions_msg_2 = body2["input"][body1_input.len() + 1].clone(); + assert_ne!( + expected_permissions_msg_2, expected_permissions_msg, + "expected updated permissions message after policy change" + ); let expected_user_message_2 = text_user_input("hello 2".to_string()); let expected_input_2 = serde_json::Value::Array(vec![ expected_permissions_msg, expected_ui_msg, expected_env_msg_1, expected_user_message_1, - expected_permissions_msg_2, expected_model_switch_msg, + expected_permissions_msg_2, expected_user_message_2, ]); assert_eq!(body2["input"], expected_input_2); diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index 61726f913c..89a08b9e55 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -6,9 +6,13 @@ use codex_core::protocol::EventMsg; use codex_core::protocol::InitialHistory; use codex_core::protocol::ResumedHistory; use codex_core::protocol::RolloutItem; +use codex_core::protocol::TurnCompleteEvent; use codex_core::protocol::TurnContextItem; +use codex_core::protocol::TurnStartedEvent; +use codex_core::protocol::UserMessageEvent; use codex_core::protocol::WarningEvent; use codex_protocol::ThreadId; +use codex_protocol::config_types::ModeKind; use core::time::Duration; use core_test_support::load_default_config_for_test; use core_test_support::wait_for_event; @@ -19,8 +23,9 @@ fn resume_history( previous_model: &str, rollout_path: &std::path::Path, ) -> InitialHistory { + let turn_id = "resume-warning-seed-turn".to_string(); let turn_ctx = TurnContextItem { - turn_id: None, + turn_id: Some(turn_id.clone()), cwd: config.cwd.clone(), approval_policy: config.permissions.approval_policy.value(), sandbox_policy: config.permissions.sandbox_policy.get().clone(), @@ -38,7 +43,24 @@ fn resume_history( InitialHistory::Resumed(ResumedHistory { conversation_id: ThreadId::default(), - history: vec![RolloutItem::TurnContext(turn_ctx)], + history: vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { + turn_id: turn_id.clone(), + model_context_window: None, + collaboration_mode_kind: ModeKind::Default, + })), + RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: vec![], + text_elements: vec![], + })), + RolloutItem::TurnContext(turn_ctx), + RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent { + turn_id, + last_agent_message: None, + })), + ], rollout_path: rollout_path.to_path_buf(), }) } diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap index bcca5d3575..c88ff33122 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap @@ -13,9 +13,9 @@ Scenario: Manual /compact with prior user history compacts existing history and 05:message/user: ## Local Post-Compaction History Layout -00:message/developer: -01:message/user: -02:message/user:> -03:message/user:first manual turn -04:message/user:\nFIRST_MANUAL_SUMMARY +00:message/user:first manual turn +01:message/user:\nFIRST_MANUAL_SUMMARY +02:message/developer: +03:message/user: +04:message/user:> 05:message/user:second manual turn diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap index bdb4fe9bae..0c8f87d04c 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap @@ -11,8 +11,8 @@ Scenario: Manual /compact with no prior user turn currently still issues a compa 03:message/user: ## Local Post-Compaction History Layout -00:message/developer: -01:message/user: -02:message/user:> -03:message/user:\nMANUAL_EMPTY_SUMMARY +00:message/user:\nMANUAL_EMPTY_SUMMARY +01:message/developer: +02:message/user: +03:message/user:> 04:message/user:AFTER_MANUAL_EMPTY_COMPACT diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap index 8d6c4d9b1a..552c117c98 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap @@ -1,6 +1,5 @@ --- source: core/tests/suite/compact.rs -assertion_line: 1773 expression: "format_labeled_requests_snapshot(\"Pre-sampling compaction on model switch to a smaller context window: current behavior compacts using prior-turn history only (incoming user message excluded), and the follow-up request carries compacted history plus the new user message.\",\n&[(\"Initial Request (Previous Model)\", &requests[0]),\n(\"Pre-sampling Compaction Request\", &requests[1]),\n(\"Post-Compaction Follow-up Request (Next Model)\", &requests[2]),])" --- Scenario: Pre-sampling compaction on model switch to a smaller context window: current behavior compacts using prior-turn history only (incoming user message excluded), and the follow-up request carries compacted history plus the new user message. @@ -22,10 +21,10 @@ Scenario: Pre-sampling compaction on model switch to a smaller context window: c 06:message/user: ## Post-Compaction Follow-up Request (Next Model) -00:message/developer: -01:message/user: -02:message/user:> -03:message/user:before switch -04:message/user:\nPRE_SAMPLING_SUMMARY -05:message/developer:\nThe user was previously using a different model.... +00:message/user:before switch +01:message/user:\nPRE_SAMPLING_SUMMARY +02:message/developer:\nThe user was previously using a different model.... +03:message/developer: +04:message/user: +05:message/user:> 06:message/user:after switch diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap index e586c8521a..ea4fea2f21 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap @@ -12,14 +12,13 @@ Scenario: Pre-turn auto-compaction with a context override emits the context dif 04:message/assistant:FIRST_REPLY 05:message/user:USER_TWO 06:message/assistant:SECOND_REPLY -07:message/user: -08:message/user: +07:message/user: ## Local Post-Compaction History Layout -00:message/developer: -01:message/user: -02:message/user: -03:message/user:USER_ONE -04:message/user:USER_TWO -05:message/user:\nPRE_TURN_SUMMARY +00:message/user:USER_ONE +01:message/user:USER_TWO +02:message/user:\nPRE_TURN_SUMMARY +03:message/developer: +04:message/user: +05:message/user: 06:message/user: | | | USER_THREE diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap index 4d67af911d..59d3785a43 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap @@ -1,6 +1,5 @@ --- source: core/tests/suite/compact.rs -assertion_line: 3152 expression: "format_labeled_requests_snapshot(\"Pre-turn compaction during model switch (without pre-sampling model-switch compaction): current behavior strips incoming from the compact request and restores it in the post-compaction follow-up request.\",\n&[(\"Initial Request (Previous Model)\", &requests[0]),\n(\"Local Compaction Request\", &requests[1]),\n(\"Local Post-Compaction History Layout\", &requests[2]),])" --- Scenario: Pre-turn compaction during model switch (without pre-sampling model-switch compaction): current behavior strips incoming from the compact request and restores it in the post-compaction follow-up request. @@ -22,11 +21,11 @@ Scenario: Pre-turn compaction during model switch (without pre-sampling model-sw 06:message/user: ## Local Post-Compaction History Layout -00:message/developer: -01:message/developer: The user has requested a new communication st... -02:message/user: -03:message/user:> -04:message/user:BEFORE_SWITCH_USER -05:message/user:\nPRETURN_SWITCH_SUMMARY -06:message/developer:\nThe user was previously using a different model.... +00:message/user:BEFORE_SWITCH_USER +01:message/user:\nPRETURN_SWITCH_SUMMARY +02:message/developer:\nThe user was previously using a different model.... +03:message/developer: +04:message/developer: The user has requested a new communication st... +05:message/user: +06:message/user:> 07:message/user:AFTER_SWITCH_USER diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap index bc795a19f4..701e676761 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap @@ -1,9 +1,8 @@ --- source: core/tests/suite/compact_remote.rs -assertion_line: 178 -expression: "format_labeled_requests_snapshot(\"Remote manual /compact where remote compact output is summary-only: follow-up layout uses returned summary plus new user message.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", follow_up_request),])" +expression: "format_labeled_requests_snapshot(\"Remote manual /compact where remote compact output is compaction-only: follow-up layout uses the returned compaction item plus new user message.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", follow_up_request),])" --- -Scenario: Remote manual /compact where remote compact output is summary-only: follow-up layout uses returned summary plus new user message. +Scenario: Remote manual /compact where remote compact output is compaction-only: follow-up layout uses the returned compaction item plus new user message. ## Remote Compaction Request 00:message/developer: @@ -13,9 +12,8 @@ Scenario: Remote manual /compact where remote compact output is summary-only: fo 04:message/assistant:FIRST_REMOTE_REPLY ## Remote Post-Compaction History Layout -00:message/developer: -01:message/user: -02:message/user:> -03:message/user:REMOTE_COMPACTED_SUMMARY -04:compaction:encrypted=true -05:message/user:after compact +00:compaction:encrypted=true +01:message/developer: +02:message/user: +03:message/user:> +04:message/user:after compact diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap index 1f51f96544..7d5bcde902 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap @@ -1,21 +1,18 @@ --- source: core/tests/suite/compact_remote.rs -expression: "format_labeled_requests_snapshot(\"Remote mid-turn compaction after an earlier summary compaction: the older summary remains in model-visible history and round-trips into the next compact request.\",\n&[(\"Second Turn Request (Before Mid-Turn Compaction)\", &requests[1]),\n(\"Remote Compaction Request\", &compact_request),])" +assertion_line: 1876 +expression: "format_labeled_requests_snapshot(\"After a prior manual /compact produced an older remote compaction item, the next turn hits remote auto-compaction before the next sampling request. The compact request carries forward that earlier compaction item, and the next sampling request shows the latest compaction item with context reinjected before USER_TWO.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Second Turn Request (After Compaction)\", &second_turn_request),])" --- -Scenario: Remote mid-turn compaction after an earlier summary compaction: the older summary remains in model-visible history and round-trips into the next compact request. - -## Second Turn Request (Before Mid-Turn Compaction) -00:message/user:USER_ONE -01:message/user:\nREMOTE_OLDER_SUMMARY -02:message/developer: -03:message/user: -04:message/user:> -05:message/user:\nREMOTE_LATEST_SUMMARY -06:message/user:USER_TWO +Scenario: After a prior manual /compact produced an older remote compaction item, the next turn hits remote auto-compaction before the next sampling request. The compact request carries forward that earlier compaction item, and the next sampling request shows the latest compaction item with context reinjected before USER_TWO. ## Remote Compaction Request 00:message/user:USER_ONE -01:message/developer: -02:message/user: -03:message/user:> -04:message/user:\nREMOTE_OLDER_SUMMARY +01:compaction:encrypted=true + +## Second Turn Request (After Compaction) +00:message/user:USER_ONE +01:compaction:encrypted=true +02:message/developer: +03:message/user: +04:message/user:> +05:message/user:USER_TWO diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap index 8ef8701673..f5533b94a9 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap @@ -1,8 +1,8 @@ --- source: core/tests/suite/compact_remote.rs -expression: "format_labeled_requests_snapshot(\"Remote mid-turn continuation compaction after tool output: compact request includes tool artifacts and follow-up request includes the summary.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &requests[1]),])" +expression: "format_labeled_requests_snapshot(\"Remote mid-turn continuation compaction after tool output: compact request includes tool artifacts and the follow-up request includes the returned compaction item.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &requests[1]),])" --- -Scenario: Remote mid-turn continuation compaction after tool output: compact request includes tool artifacts and follow-up request includes the summary. +Scenario: Remote mid-turn continuation compaction after tool output: compact request includes tool artifacts and the follow-up request includes the returned compaction item. ## Remote Compaction Request 00:message/developer: @@ -13,8 +13,8 @@ Scenario: Remote mid-turn continuation compaction after tool output: compact req 05:function_call_output:unsupported call: test_tool ## Remote Post-Compaction History Layout -00:message/user:USER_ONE -01:message/developer: -02:message/user: -03:message/user:> -04:message/user:\nREMOTE_MID_TURN_SUMMARY +00:message/developer: +01:message/user: +02:message/user:> +03:message/user:USER_ONE +04:compaction:encrypted=true diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap index 4ede5c3cad..3f8c77e975 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap @@ -1,8 +1,8 @@ --- source: core/tests/suite/compact_remote.rs -expression: "format_labeled_requests_snapshot(\"Remote mid-turn compaction where compact output has only summary user content: continuation layout reinjects canonical context before that summary.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &requests[1]),])" +expression: "format_labeled_requests_snapshot(\"Remote mid-turn compaction where compact output has only a compaction item: continuation layout reinjects context before that compaction item.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &requests[1]),])" --- -Scenario: Remote mid-turn compaction where compact output has only summary user content: continuation layout reinjects canonical context before that summary. +Scenario: Remote mid-turn compaction where compact output has only a compaction item: continuation layout reinjects context before that compaction item. ## Remote Compaction Request 00:message/developer: @@ -16,4 +16,4 @@ Scenario: Remote mid-turn compaction where compact output has only summary user 00:message/developer: 01:message/user: 02:message/user:> -03:message/user:\nREMOTE_SUMMARY_ONLY +03:compaction:encrypted=true diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap index 00aaaeaa92..2236984a67 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap @@ -12,13 +12,12 @@ Scenario: Remote pre-turn auto-compaction with a context override emits the cont 04:message/assistant:REMOTE_FIRST_REPLY 05:message/user:USER_TWO 06:message/assistant:REMOTE_SECOND_REPLY -07:message/user: ## Remote Post-Compaction History Layout 00:message/user:USER_ONE 01:message/user:USER_TWO -02:message/developer: -03:message/user: -04:message/user: -05:message/user:\nREMOTE_PRE_TURN_SUMMARY +02:compaction:encrypted=true +03:message/developer: +04:message/user: +05:message/user: 06:message/user:USER_THREE diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap index fba17d719e..15beec5f27 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap @@ -1,6 +1,6 @@ --- source: core/tests/suite/compact_remote.rs -expression: "format_labeled_requests_snapshot(\"Remote pre-turn compaction during model switch currently excludes incoming user input, strips incoming from the compact request payload, and restores it in the post-compaction follow-up request.\",\n&[(\"Initial Request (Previous Model)\", &requests[0]),\n(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &requests[1]),])" +expression: "format_labeled_requests_snapshot(\"Remote pre-turn compaction during model switch currently excludes incoming user input, strips incoming from the compact request payload, and restores it in the post-compaction follow-up request.\",\n&[(\"Initial Request (Previous Model)\", &initial_turn_request),\n(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &post_compact_turn_request),])" --- Scenario: Remote pre-turn compaction during model switch currently excludes incoming user input, strips incoming from the compact request payload, and restores it in the post-compaction follow-up request. @@ -19,10 +19,10 @@ Scenario: Remote pre-turn compaction during model switch currently excludes inco ## Remote Post-Compaction History Layout 00:message/user:BEFORE_SWITCH_USER -01:message/developer: -02:message/developer: The user has requested a new communication st... -03:message/user: -04:message/user:> -05:message/user:\nREMOTE_SWITCH_SUMMARY -06:message/developer:\nThe user was previously using a different model.... +01:compaction:encrypted=true +02:message/developer:\nThe user was previously using a different model.... +03:message/developer: +04:message/developer: The user has requested a new communication st... +05:message/user: +06:message/user:> 07:message/user:AFTER_SWITCH_USER diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap index 850b6be0a2..06269eff76 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap @@ -1,5 +1,6 @@ --- source: core/tests/suite/model_visible_layout.rs +assertion_line: 435 expression: "format_labeled_requests_snapshot(\"First post-resume turn where pre-turn override sets model to rollout model; no model-switch update should appear.\",\n&[(\"Last Request Before Resume\", &initial_request),\n(\"First Request After Resume + Override\", &resumed_request),])" --- Scenario: First post-resume turn where pre-turn override sets model to rollout model; no model-switch update should appear. @@ -16,7 +17,5 @@ Scenario: First post-resume turn where pre-turn override sets model to rollout m 02:message/user:> 03:message/user:seed resume history 04:message/assistant:recorded before resume -05:message/developer: -06:message/user: -07:message/user:> -08:message/user:first resumed turn after model override +05:message/user: +06:message/user:first resumed turn after model override diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap index a37cd885ec..54417c6de2 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap @@ -1,5 +1,6 @@ --- source: core/tests/suite/model_visible_layout.rs +assertion_line: 337 expression: "format_labeled_requests_snapshot(\"First post-resume turn where resumed config model differs from rollout and personality changes.\",\n&[(\"Last Request Before Resume\", &initial_request),\n(\"First Request After Resume\", &resumed_request),])" --- Scenario: First post-resume turn where resumed config model differs from rollout and personality changes. @@ -16,11 +17,7 @@ Scenario: First post-resume turn where resumed config model differs from rollout 02:message/user:> 03:message/user:seed resume history 04:message/assistant:recorded before resume -05:message/developer: -06:message/developer: The user has requested a new communication style. Future messages should adhe... -07:message/user: -08:message/user:> -09:message/developer: -10:message/developer:\nThe user was previously using a different model. Please continue the conversatio... -11:message/developer: The user has requested a new communication style. Future messages should adhe... -12:message/user:resume and change personality +05:message/developer:\nThe user was previously using a different model. Please continue the conversatio... +06:message/user: +07:message/developer: +08:message/user:resume and change personality diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 86a1248657..a8b7ade166 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -2088,6 +2088,10 @@ pub struct TurnContextNetworkItem { pub denied_domains: Vec, } +/// Persist only when the same turn also persists the corresponding +/// model-visible context updates (diffs or full reinjection), so +/// resume/fork does not use a `reference_context_item` whose context +/// was never actually visible to the model. #[derive(Serialize, Deserialize, Clone, Debug, JsonSchema, TS)] pub struct TurnContextItem { #[serde(default, skip_serializing_if = "Option::is_none")] From 1a220ad77dc436082de5efc4e1f7fc30d711ab87 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 20 Feb 2026 23:19:29 -0800 Subject: [PATCH 051/385] chore: move config diagnostics out of codex-core (#12427) ## Why Compiling `codex-rs/core` is a bottleneck for local iteration, so this change continues the ongoing extraction of config-related functionality out of `codex-core` and into `codex-config`. The goal is not just to move code, but to reduce `codex-core` ownership and indirection so more code depends on `codex-config` directly. ## What Changed - Moved config diagnostics logic from `core/src/config_loader/diagnostics.rs` into `config/src/diagnostics.rs`. - Updated `codex-core` to use `codex-config` diagnostics types/functions directly where possible. - Removed the `core/src/config_loader/diagnostics.rs` shim module entirely; the remaining `ConfigToml`-specific calls are in `core/src/config_loader/mod.rs`. - Moved `CONFIG_TOML_FILE` into `codex-config` and updated existing references to use `codex_config::CONFIG_TOML_FILE` directly. - Added a direct `codex-config` dependency to `codex-cli` for its `CONFIG_TOML_FILE` use. --- codex-rs/Cargo.lock | 5 ++- codex-rs/cli/Cargo.toml | 1 + codex-rs/cli/src/main.rs | 2 +- codex-rs/config/Cargo.toml | 4 ++ .../src}/diagnostics.rs | 44 +++++++++++-------- codex-rs/config/src/lib.rs | 14 ++++++ codex-rs/core/Cargo.toml | 1 - codex-rs/core/src/codex.rs | 2 +- codex-rs/core/src/config/edit.rs | 2 +- codex-rs/core/src/config/mod.rs | 3 +- codex-rs/core/src/config/service.rs | 2 +- codex-rs/core/src/config_loader/layer_io.rs | 4 +- codex-rs/core/src/config_loader/mod.rs | 32 +++++++++----- codex-rs/core/src/config_loader/tests.rs | 6 +-- codex-rs/core/src/features.rs | 2 +- codex-rs/core/src/network_proxy_loader.rs | 2 +- codex-rs/core/src/skills/loader.rs | 2 +- .../tests/suite/unstable_features_warning.rs | 2 +- 18 files changed, 82 insertions(+), 48 deletions(-) rename codex-rs/{core/src/config_loader => config/src}/diagnostics.rs (90%) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index f05879a243..4ef13ad845 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1470,6 +1470,7 @@ dependencies = [ "codex-arg0", "codex-chatgpt", "codex-cloud-tasks", + "codex-config", "codex-core", "codex-exec", "codex-execpolicy", @@ -1600,10 +1601,13 @@ dependencies = [ "pretty_assertions", "serde", "serde_json", + "serde_path_to_error", "sha2", "thiserror 2.0.18", "tokio", "toml 0.9.11+spec-1.1.0", + "toml_edit 0.24.0+spec-1.1.0", + "tracing", ] [[package]] @@ -1681,7 +1685,6 @@ dependencies = [ "seccompiler", "serde", "serde_json", - "serde_path_to_error", "serde_yaml", "serial_test", "sha1", diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index fd15f87916..1d955bbaaf 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -26,6 +26,7 @@ codex-arg0 = { workspace = true } codex-chatgpt = { workspace = true } codex-cloud-tasks = { path = "../cloud-tasks" } codex-utils-cli = { workspace = true } +codex-config = { workspace = true } codex-core = { workspace = true } codex-exec = { workspace = true } codex-execpolicy = { workspace = true } diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 33c9f161bb..98a5ab0779 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -870,7 +870,7 @@ fn maybe_print_under_development_feature_warning( return; } - let config_path = codex_home.join(codex_core::config::CONFIG_TOML_FILE); + let config_path = codex_home.join(codex_config::CONFIG_TOML_FILE); eprintln!( "Under-development features enabled: {feature}. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in {}.", config_path.display() diff --git a/codex-rs/config/Cargo.toml b/codex-rs/config/Cargo.toml index 1c804fb8db..02446ed6f3 100644 --- a/codex-rs/config/Cargo.toml +++ b/codex-rs/config/Cargo.toml @@ -16,9 +16,13 @@ futures = { workspace = true, features = ["alloc", "std"] } multimap = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } +serde_path_to_error = { workspace = true } sha2 = { workspace = true } thiserror = { workspace = true } +tokio = { workspace = true, features = ["fs"] } toml = { workspace = true } +toml_edit = { workspace = true } +tracing = { workspace = true } [dev-dependencies] anyhow = { workspace = true } diff --git a/codex-rs/core/src/config_loader/diagnostics.rs b/codex-rs/config/src/diagnostics.rs similarity index 90% rename from codex-rs/core/src/config_loader/diagnostics.rs rename to codex-rs/config/src/diagnostics.rs index 64f9c83888..be6e123d33 100644 --- a/codex-rs/core/src/config_loader/diagnostics.rs +++ b/codex-rs/config/src/diagnostics.rs @@ -1,10 +1,12 @@ //! Helpers for mapping config parse/validation failures to file locations and //! rendering them in a user-friendly way. -use crate::config::CONFIG_TOML_FILE; -use crate::config::ConfigToml; +use crate::ConfigLayerEntry; +use crate::ConfigLayerStack; +use crate::ConfigLayerStackOrdering; use codex_app_server_protocol::ConfigLayerSource; use codex_utils_absolute_path::AbsolutePathBufGuard; +use serde::de::DeserializeOwned; use serde_path_to_error::Path as SerdePath; use serde_path_to_error::Segment as SerdeSegment; use std::fmt; @@ -17,10 +19,6 @@ use toml_edit::Item; use toml_edit::Table; use toml_edit::Value; -use super::ConfigLayerEntry; -use super::ConfigLayerStack; -use super::ConfigLayerStackOrdering; - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TextPosition { pub line: usize, @@ -88,7 +86,7 @@ impl std::error::Error for ConfigLoadError { } } -pub(crate) fn io_error_from_config_error( +pub fn io_error_from_config_error( kind: io::ErrorKind, error: ConfigError, source: Option, @@ -96,7 +94,7 @@ pub(crate) fn io_error_from_config_error( io::Error::new(kind, ConfigLoadError::new(error, source)) } -pub(crate) fn config_error_from_toml( +pub fn config_error_from_toml( path: impl AsRef, contents: &str, err: toml::de::Error, @@ -108,7 +106,7 @@ pub(crate) fn config_error_from_toml( ConfigError::new(path.as_ref().to_path_buf(), range, err.message()) } -pub(crate) fn config_error_from_config_toml( +pub fn config_error_from_typed_toml( path: impl AsRef, contents: &str, ) -> Option { @@ -117,7 +115,7 @@ pub(crate) fn config_error_from_config_toml( Err(err) => return Some(config_error_from_toml(path, contents, err)), }; - let result: Result = serde_path_to_error::deserialize(deserializer); + let result: Result = serde_path_to_error::deserialize(deserializer); match result { Ok(_) => None, Err(err) => { @@ -136,28 +134,36 @@ pub(crate) fn config_error_from_config_toml( } } -pub(crate) async fn first_layer_config_error(layers: &ConfigLayerStack) -> Option { +pub async fn first_layer_config_error( + layers: &ConfigLayerStack, + config_toml_file: &str, +) -> Option { // When the merged config fails schema validation, we surface the first concrete // per-file error to point users at a specific file and range rather than an // opaque merged-layer failure. - first_layer_config_error_for_entries( + first_layer_config_error_for_entries::( layers.get_layers(ConfigLayerStackOrdering::LowestPrecedenceFirst, false), + config_toml_file, ) .await } -pub(crate) async fn first_layer_config_error_from_entries( +pub async fn first_layer_config_error_from_entries( layers: &[ConfigLayerEntry], + config_toml_file: &str, ) -> Option { - first_layer_config_error_for_entries(layers.iter()).await + first_layer_config_error_for_entries::(layers.iter(), config_toml_file).await } -async fn first_layer_config_error_for_entries<'a, I>(layers: I) -> Option +async fn first_layer_config_error_for_entries<'a, T: DeserializeOwned, I>( + layers: I, + config_toml_file: &str, +) -> Option where I: IntoIterator, { for layer in layers { - let Some(path) = config_path_for_layer(layer) else { + let Some(path) = config_path_for_layer(layer, config_toml_file) else { continue; }; let contents = match tokio::fs::read_to_string(&path).await { @@ -174,7 +180,7 @@ where continue; }; let _guard = AbsolutePathBufGuard::new(parent); - if let Some(error) = config_error_from_config_toml(&path, &contents) { + if let Some(error) = config_error_from_typed_toml::(&path, &contents) { return Some(error); } } @@ -182,12 +188,12 @@ where None } -fn config_path_for_layer(layer: &ConfigLayerEntry) -> Option { +fn config_path_for_layer(layer: &ConfigLayerEntry, config_toml_file: &str) -> Option { match &layer.name { ConfigLayerSource::System { file } => Some(file.to_path_buf()), ConfigLayerSource::User { file } => Some(file.to_path_buf()), ConfigLayerSource::Project { dot_codex_folder } => { - Some(dot_codex_folder.as_path().join(CONFIG_TOML_FILE)) + Some(dot_codex_folder.as_path().join(config_toml_file)) } ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => Some(file.to_path_buf()), ConfigLayerSource::Mdm { .. } diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs index 42f3ad76af..41b9a3ae06 100644 --- a/codex-rs/config/src/lib.rs +++ b/codex-rs/config/src/lib.rs @@ -1,12 +1,15 @@ mod cloud_requirements; mod config_requirements; mod constraint; +mod diagnostics; mod fingerprint; mod merge; mod overrides; mod requirements_exec_policy; mod state; +pub const CONFIG_TOML_FILE: &str = "config.toml"; + pub use cloud_requirements::CloudRequirementsLoader; pub use config_requirements::ConfigRequirements; pub use config_requirements::ConfigRequirementsToml; @@ -24,6 +27,17 @@ pub use config_requirements::WebSearchModeRequirement; pub use constraint::Constrained; pub use constraint::ConstraintError; pub use constraint::ConstraintResult; +pub use diagnostics::ConfigError; +pub use diagnostics::ConfigLoadError; +pub use diagnostics::TextPosition; +pub use diagnostics::TextRange; +pub use diagnostics::config_error_from_toml; +pub use diagnostics::config_error_from_typed_toml; +pub use diagnostics::first_layer_config_error; +pub use diagnostics::first_layer_config_error_from_entries; +pub use diagnostics::format_config_error; +pub use diagnostics::format_config_error_with_source; +pub use diagnostics::io_error_from_config_error; pub use fingerprint::version_for_toml; pub use merge::merge_toml_values; pub use overrides::build_cli_overrides_layer; diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 2b62d96254..bda19d78ea 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -78,7 +78,6 @@ rmcp = { workspace = true, default-features = false, features = [ schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } -serde_path_to_error = { workspace = true } serde_yaml = { workspace = true } sha1 = { workspace = true } sha2 = { workspace = true } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 90d496973a..6c9c9a678f 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -120,7 +120,6 @@ use crate::client_common::Prompt; use crate::client_common::ResponseEvent; use crate::codex_thread::ThreadConfigSnapshot; use crate::compact::collect_user_messages; -use crate::config::CONFIG_TOML_FILE; use crate::config::Config; use crate::config::Constrained; use crate::config::ConstraintResult; @@ -136,6 +135,7 @@ use crate::error::CodexErr; use crate::error::Result as CodexResult; #[cfg(test)] use crate::exec::StreamOutput; +use codex_config::CONFIG_TOML_FILE; #[derive(Debug, PartialEq)] pub enum SteerInputError { diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 07443fa665..0dfb4efd8e 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -1,9 +1,9 @@ -use crate::config::CONFIG_TOML_FILE; use crate::config::types::McpServerConfig; use crate::config::types::Notice; use crate::path_utils::resolve_symlink_write_paths; use crate::path_utils::write_atomically; use anyhow::Context; +use codex_config::CONFIG_TOML_FILE; use codex_protocol::config_types::Personality; use codex_protocol::config_types::TrustLevel; use codex_protocol::openai_models::ReasoningEffort; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index edaabed1fa..ca3978b73d 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -117,8 +117,6 @@ pub(crate) const PROJECT_DOC_MAX_BYTES: usize = 32 * 1024; // 32 KiB pub(crate) const DEFAULT_AGENT_MAX_THREADS: Option = Some(6); pub(crate) const DEFAULT_AGENT_MAX_DEPTH: i32 = 1; -pub const CONFIG_TOML_FILE: &str = "config.toml"; - #[cfg(test)] pub(crate) fn test_config() -> Config { let codex_home = tempdir().expect("create temp dir"); @@ -2302,6 +2300,7 @@ mod tests { use crate::config::types::Notifications; use crate::config_loader::RequirementSource; use crate::features::Feature; + use codex_config::CONFIG_TOML_FILE; use super::*; use core_test_support::test_absolute_path; diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/core/src/config/service.rs index 1033db728d..da675d2389 100644 --- a/codex-rs/core/src/config/service.rs +++ b/codex-rs/core/src/config/service.rs @@ -1,4 +1,3 @@ -use super::CONFIG_TOML_FILE; use super::ConfigToml; use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; @@ -26,6 +25,7 @@ use codex_app_server_protocol::ConfigWriteResponse; use codex_app_server_protocol::MergeStrategy; use codex_app_server_protocol::OverriddenMetadata; use codex_app_server_protocol::WriteStatus; +use codex_config::CONFIG_TOML_FILE; use codex_utils_absolute_path::AbsolutePathBuf; use serde_json::Value as JsonValue; use std::borrow::Cow; diff --git a/codex-rs/core/src/config_loader/layer_io.rs b/codex-rs/core/src/config_loader/layer_io.rs index a97f285549..5caebdf527 100644 --- a/codex-rs/core/src/config_loader/layer_io.rs +++ b/codex-rs/core/src/config_loader/layer_io.rs @@ -1,10 +1,10 @@ use super::LoaderOverrides; -use super::diagnostics::config_error_from_toml; -use super::diagnostics::io_error_from_config_error; #[cfg(target_os = "macos")] use super::macos::ManagedAdminConfigLayer; #[cfg(target_os = "macos")] use super::macos::load_managed_admin_config_layer; +use codex_config::config_error_from_toml; +use codex_config::io_error_from_config_error; use codex_utils_absolute_path::AbsolutePathBuf; use std::io; use std::path::Path; diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index f30a627c40..70014c03b8 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -1,4 +1,3 @@ -mod diagnostics; mod layer_io; #[cfg(target_os = "macos")] mod macos; @@ -6,12 +5,12 @@ mod macos; #[cfg(test)] mod tests; -use crate::config::CONFIG_TOML_FILE; use crate::config::ConfigToml; use crate::config::deserialize_config_toml_with_base; use crate::config_loader::layer_io::LoadedConfigLayers; use crate::git_info::resolve_root_git_project_for_trust; use codex_app_server_protocol::ConfigLayerSource; +use codex_config::CONFIG_TOML_FILE; use codex_config::ConfigRequirementsWithSources; use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::TrustLevel; @@ -27,9 +26,11 @@ use std::path::PathBuf; use toml::Value as TomlValue; pub use codex_config::CloudRequirementsLoader; +pub use codex_config::ConfigError; pub use codex_config::ConfigLayerEntry; pub use codex_config::ConfigLayerStack; pub use codex_config::ConfigLayerStackOrdering; +pub use codex_config::ConfigLoadError; pub use codex_config::ConfigRequirements; pub use codex_config::ConfigRequirementsToml; pub use codex_config::ConstrainedWithSource; @@ -42,21 +43,17 @@ pub use codex_config::RequirementSource; pub use codex_config::ResidencyRequirement; pub use codex_config::SandboxModeRequirement; pub use codex_config::Sourced; +pub use codex_config::TextPosition; +pub use codex_config::TextRange; pub use codex_config::WebSearchModeRequirement; pub(crate) use codex_config::build_cli_overrides_layer; +pub(crate) use codex_config::config_error_from_toml; +pub use codex_config::format_config_error; +pub use codex_config::format_config_error_with_source; +pub(crate) use codex_config::io_error_from_config_error; pub use codex_config::merge_toml_values; #[cfg(test)] pub(crate) use codex_config::version_for_toml; -pub use diagnostics::ConfigError; -pub use diagnostics::ConfigLoadError; -pub use diagnostics::TextPosition; -pub use diagnostics::TextRange; -pub(crate) use diagnostics::config_error_from_toml; -pub(crate) use diagnostics::first_layer_config_error; -pub(crate) use diagnostics::first_layer_config_error_from_entries; -pub use diagnostics::format_config_error; -pub use diagnostics::format_config_error_with_source; -pub(crate) use diagnostics::io_error_from_config_error; /// On Unix systems, load default settings from this file path, if present. /// Note that /etc/codex/ is treated as a "config folder," so subfolders such @@ -68,6 +65,17 @@ const DEFAULT_PROGRAM_DATA_DIR_WINDOWS: &str = r"C:\ProgramData"; const DEFAULT_PROJECT_ROOT_MARKERS: &[&str] = &[".git"]; +pub(crate) async fn first_layer_config_error(layers: &ConfigLayerStack) -> Option { + codex_config::first_layer_config_error::(layers, CONFIG_TOML_FILE).await +} + +pub(crate) async fn first_layer_config_error_from_entries( + layers: &[ConfigLayerEntry], +) -> Option { + codex_config::first_layer_config_error_from_entries::(layers, CONFIG_TOML_FILE) + .await +} + /// To build up the set of admin-enforced constraints, we build up from multiple /// configuration layers in the following order, but a constraint defined in an /// earlier layer cannot be overridden by a later layer: diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index 08bbb5304d..3eab05ba18 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -1,6 +1,5 @@ use super::LoaderOverrides; use super::load_config_layers_state; -use crate::config::CONFIG_TOML_FILE; use crate::config::ConfigBuilder; use crate::config::ConfigOverrides; use crate::config::ConfigToml; @@ -15,6 +14,7 @@ use crate::config_loader::ConfigRequirementsWithSources; use crate::config_loader::RequirementSource; use crate::config_loader::load_requirements_toml; use crate::config_loader::version_for_toml; +use codex_config::CONFIG_TOML_FILE; use codex_protocol::config_types::TrustLevel; use codex_protocol::config_types::WebSearchMode; use codex_protocol::protocol::AskForApproval; @@ -153,7 +153,7 @@ async fn returns_config_error_for_schema_error_in_user_config() { let config_error = config_error_from_io(&err); let _guard = codex_utils_absolute_path::AbsolutePathBufGuard::new(tmp.path()); let expected_config_error = - super::diagnostics::config_error_from_config_toml(&config_path, contents) + codex_config::config_error_from_typed_toml::(&config_path, contents) .expect("schema error"); assert_eq!(config_error, &expected_config_error); } @@ -166,7 +166,7 @@ fn schema_error_points_to_feature_value() { std::fs::write(&config_path, contents).expect("write config"); let _guard = codex_utils_absolute_path::AbsolutePathBufGuard::new(tmp.path()); - let error = super::diagnostics::config_error_from_config_toml(&config_path, contents) + let error = codex_config::config_error_from_typed_toml::(&config_path, contents) .expect("schema error"); let value_line = contents.lines().nth(1).expect("value line"); diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index a4be91046c..4cefe4b216 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -5,13 +5,13 @@ //! booleans through multiple types, call sites consult a single `Features` //! container attached to `Config`. -use crate::config::CONFIG_TOML_FILE; use crate::config::Config; use crate::config::ConfigToml; use crate::config::profile::ConfigProfile; use crate::protocol::Event; use crate::protocol::EventMsg; use crate::protocol::WarningEvent; +use codex_config::CONFIG_TOML_FILE; use codex_otel::OtelManager; use schemars::JsonSchema; use serde::Deserialize; diff --git a/codex-rs/core/src/network_proxy_loader.rs b/codex-rs/core/src/network_proxy_loader.rs index 1af36b2acb..15d4e41664 100644 --- a/codex-rs/core/src/network_proxy_loader.rs +++ b/codex-rs/core/src/network_proxy_loader.rs @@ -1,4 +1,3 @@ -use crate::config::CONFIG_TOML_FILE; use crate::config::NetworkToml; use crate::config::PermissionsToml; use crate::config::find_codex_home; @@ -11,6 +10,7 @@ use anyhow::Context; use anyhow::Result; use async_trait::async_trait; use codex_app_server_protocol::ConfigLayerSource; +use codex_config::CONFIG_TOML_FILE; use codex_network_proxy::ConfigReloader; use codex_network_proxy::ConfigState; use codex_network_proxy::NetworkProxyConfig; diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index 3c497bfcf8..1ad231438a 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -806,7 +806,6 @@ fn extract_frontmatter(contents: &str) -> Option { #[cfg(test)] mod tests { use super::*; - use crate::config::CONFIG_TOML_FILE; use crate::config::ConfigBuilder; use crate::config::ConfigOverrides; use crate::config::ConfigToml; @@ -817,6 +816,7 @@ mod tests { use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigRequirements; use crate::config_loader::ConfigRequirementsToml; + use codex_config::CONFIG_TOML_FILE; use codex_protocol::config_types::TrustLevel; use codex_protocol::protocol::SkillScope; use codex_utils_absolute_path::AbsolutePathBuf; diff --git a/codex-rs/core/tests/suite/unstable_features_warning.rs b/codex-rs/core/tests/suite/unstable_features_warning.rs index 1cb07c1f4e..e5fdf61fdb 100644 --- a/codex-rs/core/tests/suite/unstable_features_warning.rs +++ b/codex-rs/core/tests/suite/unstable_features_warning.rs @@ -1,8 +1,8 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] +use codex_config::CONFIG_TOML_FILE; use codex_core::CodexAuth; use codex_core::NewThread; -use codex_core::config::CONFIG_TOML_FILE; use codex_core::features::Feature; use codex_core::protocol::EventMsg; use codex_core::protocol::InitialHistory; From a87c9c3299a451ea0cb96896e36ce619e84f9ee6 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Fri, 20 Feb 2026 23:32:59 -0800 Subject: [PATCH 052/385] Collapse waited message (#12430) image --- ...ified_exec_empty_then_non_empty_after.snap | 3 +- ...ified_exec_non_empty_then_empty_after.snap | 3 +- ...d_exec_wait_after_final_agent_message.snap | 3 +- ...ec_wait_before_streamed_agent_message.snap | 3 +- ...ied_exec_waiting_multiple_empty_after.snap | 3 +- codex-rs/tui/src/history_cell.rs | 29 ++++++++++--------- 6 files changed, 21 insertions(+), 23 deletions(-) diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_empty_then_non_empty_after.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_empty_then_non_empty_after.snap index 400845c82f..dcfad97ba0 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_empty_then_non_empty_after.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_empty_then_non_empty_after.snap @@ -2,8 +2,7 @@ source: tui/src/chatwidget/tests.rs expression: combined --- -↳ Interacted with background terminal · just fix - └ (waited) +• Waited for background terminal · just fix ↳ Interacted with background terminal · just fix └ ls diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_non_empty_then_empty_after.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_non_empty_then_empty_after.snap index f6f0188f95..952205e732 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_non_empty_then_empty_after.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_non_empty_then_empty_after.snap @@ -5,5 +5,4 @@ expression: combined ↳ Interacted with background terminal · just fix └ pwd -↳ Interacted with background terminal · just fix - └ (waited) +• Waited for background terminal · just fix diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_after_final_agent_message.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_after_final_agent_message.snap index 5caf42e1bc..fdbdffc5dd 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_after_final_agent_message.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_after_final_agent_message.snap @@ -2,7 +2,6 @@ source: tui/src/chatwidget/tests.rs expression: combined --- -↳ Interacted with background terminal · cargo test -p codex-core - └ (waited) +• Waited for background terminal · cargo test -p codex-core • Final response. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_before_streamed_agent_message.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_before_streamed_agent_message.snap index cfea4f8a66..f91637e2db 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_before_streamed_agent_message.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_wait_before_streamed_agent_message.snap @@ -2,7 +2,6 @@ source: tui/src/chatwidget/tests.rs expression: combined --- -↳ Interacted with background terminal · cargo test -p codex-core - └ (waited) +• Waited for background terminal · cargo test -p codex-core • Streaming response. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_waiting_multiple_empty_after.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_waiting_multiple_empty_after.snap index 782ecb1eab..99bf8e2bdc 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_waiting_multiple_empty_after.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__unified_exec_waiting_multiple_empty_after.snap @@ -2,5 +2,4 @@ source: tui/src/chatwidget/tests.rs expression: combined --- -↳ Interacted with background terminal · just fix - └ (waited) +• Waited for background terminal · just fix diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 8789196946..8c4d0147df 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -589,8 +589,13 @@ impl HistoryCell for UnifiedExecInteractionCell { return Vec::new(); } let wrap_width = width as usize; + let waited_only = self.stdin.is_empty(); - let mut header_spans = vec!["↳ ".dim(), "Interacted with background terminal".bold()]; + let mut header_spans = if waited_only { + vec!["• Waited for background terminal".bold()] + } else { + vec!["↳ ".dim(), "Interacted with background terminal".bold()] + }; if let Some(command) = &self.command_display && !command.is_empty() { @@ -603,14 +608,15 @@ impl HistoryCell for UnifiedExecInteractionCell { let header_wrapped = word_wrap_line(&header, RtOptions::new(wrap_width)); push_owned_lines(&header_wrapped, &mut out); - let input_lines: Vec> = if self.stdin.is_empty() { - vec![vec!["(waited)".dim()].into()] - } else { - self.stdin - .lines() - .map(|line| Line::from(line.to_string())) - .collect() - }; + if waited_only { + return out; + } + + let input_lines: Vec> = self + .stdin + .lines() + .map(|line| Line::from(line.to_string())) + .collect(); let input_wrapped = word_wrap_lines( input_lines, @@ -2465,10 +2471,7 @@ mod tests { fn unified_exec_interaction_cell_renders_wait() { let cell = new_unified_exec_interaction(None, String::new()); let lines = render_transcript(&cell); - assert_eq!( - lines, - vec!["↳ Interacted with background terminal", " └ (waited)"], - ); + assert_eq!(lines, vec!["• Waited for background terminal"]); } #[test] From 1af2a37ada16b8227ecd1b8e8411d2449d97ec21 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 20 Feb 2026 23:45:35 -0800 Subject: [PATCH 053/385] chore: remove codex-core public protocol/shell re-exports (#12432) ## Why `codex-rs/core/src/lib.rs` re-exported a broad set of types and modules from `codex-protocol` and `codex-shell-command`. That made it easy for workspace crates to import those APIs through `codex-core`, which in turn hides dependency edges and makes it harder to reduce compile-time coupling over time. This change removes those public re-exports so call sites must import from the source crates directly. Even when a crate still depends on `codex-core` today, this makes dependency boundaries explicit and unblocks future work to drop `codex-core` dependencies where possible. ## What Changed - Removed public re-exports from `codex-rs/core/src/lib.rs` for: - `codex_protocol::protocol` and related protocol/model types (including `InitialHistory`) - `codex_protocol::config_types` (`protocol_config_types`) - `codex_shell_command::{bash, is_dangerous_command, is_safe_command, parse_command, powershell}` - Migrated workspace Rust call sites to import directly from: - `codex_protocol::protocol` - `codex_protocol::config_types` - `codex_protocol::models` - `codex_shell_command` - Added explicit `Cargo.toml` dependencies (`codex-protocol` / `codex-shell-command`) in crates that now import those crates directly. - Kept `codex-core` internal modules compiling by using `pub(crate)` aliases in `core/src/lib.rs` (internal-only, not part of the public API). - Updated the two utility crates that can already drop a `codex-core` dependency edge entirely: - `codex-utils-approval-presets` - `codex-utils-cli` ## Verification - `cargo test -p codex-utils-approval-presets` - `cargo test -p codex-utils-cli` - `cargo check --workspace --all-targets` - `just clippy` --- codex-rs/Cargo.lock | 11 +- .../schema/json/ApplyPatchApprovalParams.json | 2 +- .../json/ExecCommandApprovalParams.json | 2 +- .../schema/json/ServerRequest.json | 4 +- .../codex_app_server_protocol.schemas.json | 4 +- .../typescript/ApplyPatchApprovalParams.ts | 4 +- .../typescript/ExecCommandApprovalParams.ts | 4 +- .../app-server-protocol/src/protocol/v1.rs | 8 +- codex-rs/app-server/Cargo.toml | 1 + .../app-server/src/bespoke_event_handling.rs | 46 +++--- .../app-server/src/codex_message_processor.rs | 14 +- .../suite/codex_message_processor_flow.rs | 8 +- codex-rs/app-server/tests/suite/config.rs | 2 +- .../app-server/tests/suite/fork_thread.rs | 2 +- codex-rs/app-server/tests/suite/interrupt.rs | 2 +- .../app-server/tests/suite/list_resume.rs | 2 +- .../app-server/tests/suite/output_schema.rs | 4 +- codex-rs/app-server/tests/suite/v2/review.rs | 2 +- .../app-server/tests/suite/v2/turn_start.rs | 2 +- .../tests/suite/v2/turn_start_zsh_fork.rs | 4 +- codex-rs/cli/src/main.rs | 4 +- codex-rs/cli/src/mcp_cmd.rs | 2 +- codex-rs/core/src/lib.rs | 23 +-- codex-rs/core/tests/common/lib.rs | 13 +- codex-rs/core/tests/common/test_codex.rs | 10 +- codex-rs/core/tests/responses_headers.rs | 4 +- codex-rs/core/tests/suite/abort_tasks.rs | 4 +- codex-rs/core/tests/suite/apply_patch_cli.rs | 8 +- codex-rs/core/tests/suite/approvals.rs | 14 +- codex-rs/core/tests/suite/cli_stream.rs | 2 +- codex-rs/core/tests/suite/client.rs | 16 +- .../core/tests/suite/client_websockets.rs | 10 +- codex-rs/core/tests/suite/codex_delegate.rs | 14 +- .../tests/suite/collaboration_instructions.rs | 8 +- codex-rs/core/tests/suite/compact.rs | 18 +-- codex-rs/core/tests/suite/compact_remote.rs | 12 +- .../core/tests/suite/compact_resume_fork.rs | 6 +- .../core/tests/suite/deprecation_notice.rs | 4 +- codex-rs/core/tests/suite/exec.rs | 2 +- codex-rs/core/tests/suite/exec_policy.rs | 8 +- codex-rs/core/tests/suite/fork_thread.rs | 8 +- codex-rs/core/tests/suite/image_rollout.rs | 12 +- codex-rs/core/tests/suite/items.rs | 20 +-- codex-rs/core/tests/suite/json_result.rs | 8 +- codex-rs/core/tests/suite/live_reload.rs | 8 +- codex-rs/core/tests/suite/model_overrides.rs | 4 +- codex-rs/core/tests/suite/model_switching.rs | 8 +- .../core/tests/suite/model_visible_layout.rs | 8 +- codex-rs/core/tests/suite/models_cache_ttl.rs | 8 +- .../core/tests/suite/models_etag_responses.rs | 8 +- codex-rs/core/tests/suite/override_updates.rs | 16 +- codex-rs/core/tests/suite/pending_input.rs | 4 +- .../core/tests/suite/permissions_messages.rs | 8 +- codex-rs/core/tests/suite/personality.rs | 8 +- codex-rs/core/tests/suite/prompt_caching.rs | 12 +- codex-rs/core/tests/suite/quota_exceeded.rs | 4 +- .../core/tests/suite/realtime_conversation.rs | 20 +-- codex-rs/core/tests/suite/remote_models.rs | 10 +- .../core/tests/suite/request_compression.rs | 4 +- .../core/tests/suite/request_user_input.rs | 8 +- codex-rs/core/tests/suite/resume.rs | 4 +- codex-rs/core/tests/suite/resume_warning.rs | 18 +-- codex-rs/core/tests/suite/review.rs | 28 ++-- codex-rs/core/tests/suite/rmcp_client.rs | 12 +- .../core/tests/suite/rollout_list_find.rs | 2 +- .../tests/suite/safety_check_downgrade.rs | 10 +- codex-rs/core/tests/suite/search_tool.rs | 8 +- codex-rs/core/tests/suite/seatbelt.rs | 2 +- .../core/tests/suite/shell_serialization.rs | 2 +- codex-rs/core/tests/suite/shell_snapshot.rs | 12 +- codex-rs/core/tests/suite/skills.rs | 16 +- .../suite/stream_error_allows_next_turn.rs | 4 +- .../core/tests/suite/stream_no_completed.rs | 4 +- codex-rs/core/tests/suite/tool_harness.rs | 8 +- codex-rs/core/tests/suite/tool_parallelism.rs | 8 +- codex-rs/core/tests/suite/tools.rs | 4 +- codex-rs/core/tests/suite/truncation.rs | 8 +- codex-rs/core/tests/suite/undo.rs | 6 +- codex-rs/core/tests/suite/unified_exec.rs | 10 +- .../tests/suite/unstable_features_warning.rs | 6 +- .../core/tests/suite/user_notification.rs | 4 +- codex-rs/core/tests/suite/user_shell_cmd.rs | 16 +- codex-rs/core/tests/suite/view_image.rs | 8 +- codex-rs/core/tests/suite/web_search.rs | 2 +- .../core/tests/suite/websocket_fallback.rs | 8 +- codex-rs/exec-server/Cargo.toml | 3 + codex-rs/exec-server/src/posix.rs | 2 +- .../exec-server/src/posix/escalate_server.rs | 2 +- codex-rs/exec-server/src/posix/mcp.rs | 2 +- codex-rs/exec-server/tests/common/Cargo.toml | 1 + codex-rs/exec-server/tests/common/lib.rs | 2 +- codex-rs/exec/src/event_processor.rs | 4 +- .../src/event_processor_with_human_output.rs | 76 +++++----- .../src/event_processor_with_jsonl_output.rs | 22 +-- codex-rs/exec/src/lib.rs | 16 +- .../tests/event_processor_with_json_output.rs | 72 ++++----- codex-rs/exec/tests/suite/sandbox.rs | 2 +- codex-rs/linux-sandbox/Cargo.toml | 1 + codex-rs/linux-sandbox/src/bwrap.rs | 6 +- codex-rs/linux-sandbox/src/landlock.rs | 4 +- codex-rs/linux-sandbox/src/linux_run_main.rs | 14 +- .../linux-sandbox/tests/suite/landlock.rs | 4 +- codex-rs/mcp-server/Cargo.toml | 1 + codex-rs/mcp-server/src/codex_tool_config.rs | 2 +- codex-rs/mcp-server/src/codex_tool_runner.rs | 16 +- codex-rs/mcp-server/src/exec_approval.rs | 4 +- codex-rs/mcp-server/src/message_processor.rs | 4 +- codex-rs/mcp-server/src/outgoing_message.rs | 12 +- codex-rs/mcp-server/src/patch_approval.rs | 6 +- codex-rs/mcp-server/tests/suite/codex_tool.rs | 6 +- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/additional_dirs.rs | 6 +- codex-rs/tui/src/app.rs | 48 +++--- codex-rs/tui/src/app_backtrack.rs | 8 +- codex-rs/tui/src/app_event.rs | 10 +- .../tui/src/bottom_pane/approval_overlay.rs | 14 +- codex-rs/tui/src/bottom_pane/chat_composer.rs | 2 +- .../src/bottom_pane/chat_composer_history.rs | 4 +- codex-rs/tui/src/bottom_pane/feedback_view.rs | 2 +- codex-rs/tui/src/bottom_pane/mod.rs | 2 +- .../src/bottom_pane/request_user_input/mod.rs | 2 +- .../tui/src/bottom_pane/skills_toggle_view.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 122 +++++++-------- codex-rs/tui/src/chatwidget/agent.rs | 16 +- codex-rs/tui/src/chatwidget/interrupts.rs | 14 +- codex-rs/tui/src/chatwidget/skills.rs | 6 +- codex-rs/tui/src/chatwidget/tests.rs | 141 +++++++++--------- codex-rs/tui/src/debug_config.rs | 6 +- codex-rs/tui/src/diff_render.rs | 2 +- codex-rs/tui/src/exec_cell/model.rs | 2 +- codex-rs/tui/src/exec_cell/render.rs | 6 +- codex-rs/tui/src/exec_command.rs | 2 +- codex-rs/tui/src/history_cell.rs | 16 +- codex-rs/tui/src/lib.rs | 16 +- codex-rs/tui/src/main.rs | 5 +- codex-rs/tui/src/multi_agents.rs | 20 +-- codex-rs/tui/src/pager_overlay.rs | 6 +- codex-rs/tui/src/session_log.rs | 2 +- codex-rs/tui/src/status/card.rs | 10 +- codex-rs/tui/src/status/rate_limits.rs | 6 +- codex-rs/tui/src/status/tests.rs | 14 +- codex-rs/tui/src/status_indicator_widget.rs | 2 +- codex-rs/utils/approval-presets/Cargo.toml | 2 +- codex-rs/utils/approval-presets/src/lib.rs | 4 +- codex-rs/utils/cli/Cargo.toml | 1 - .../utils/cli/src/approval_mode_cli_arg.rs | 2 +- .../utils/cli/src/sandbox_mode_cli_arg.rs | 2 +- codex-rs/utils/sandbox-summary/Cargo.toml | 1 + .../sandbox-summary/src/sandbox_summary.rs | 4 +- 149 files changed, 769 insertions(+), 752 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 4ef13ad845..e9fd6ed167 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1309,6 +1309,7 @@ dependencies = [ "codex-login", "codex-protocol", "codex-rmcp-client", + "codex-shell-command", "codex-utils-absolute-path", "codex-utils-cargo-bin", "codex-utils-cli", @@ -1773,6 +1774,8 @@ dependencies = [ "clap", "codex-core", "codex-execpolicy", + "codex-protocol", + "codex-shell-command", "codex-utils-cargo-bin", "exec_server_test_support", "libc", @@ -1910,6 +1913,7 @@ dependencies = [ "cc", "clap", "codex-core", + "codex-protocol", "codex-utils-absolute-path", "landlock", "libc", @@ -1966,6 +1970,7 @@ dependencies = [ "codex-arg0", "codex-core", "codex-protocol", + "codex-shell-command", "codex-utils-cli", "codex-utils-json-to-toml", "core_test_support", @@ -2240,6 +2245,7 @@ dependencies = [ "codex-login", "codex-otel", "codex-protocol", + "codex-shell-command", "codex-state", "codex-utils-absolute-path", "codex-utils-approval-presets", @@ -2320,7 +2326,7 @@ dependencies = [ name = "codex-utils-approval-presets" version = "0.0.0" dependencies = [ - "codex-core", + "codex-protocol", ] [[package]] @@ -2346,7 +2352,6 @@ name = "codex-utils-cli" version = "0.0.0" dependencies = [ "clap", - "codex-core", "codex-protocol", "pretty_assertions", "serde", @@ -2439,6 +2444,7 @@ name = "codex-utils-sandbox-summary" version = "0.0.0" dependencies = [ "codex-core", + "codex-protocol", "codex-utils-absolute-path", "pretty_assertions", ] @@ -3540,6 +3546,7 @@ version = "0.0.0" dependencies = [ "anyhow", "codex-core", + "codex-protocol", "codex-utils-cargo-bin", "rmcp", "serde_json", diff --git a/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalParams.json b/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalParams.json index da271c75ad..d1174a05b0 100644 --- a/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalParams.json @@ -77,7 +77,7 @@ }, "properties": { "callId": { - "description": "Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent] and [codex_core::protocol::PatchApplyEndEvent].", + "description": "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].", "type": "string" }, "conversationId": { diff --git a/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalParams.json b/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalParams.json index 3855168e09..43f85d21ae 100644 --- a/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalParams.json @@ -125,7 +125,7 @@ ] }, "callId": { - "description": "Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent] and [codex_core::protocol::ExecCommandEndEvent].", + "description": "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].", "type": "string" }, "command": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index 865912058e..553f189dc6 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -4,7 +4,7 @@ "ApplyPatchApprovalParams": { "properties": { "callId": { - "description": "Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent] and [codex_core::protocol::PatchApplyEndEvent].", + "description": "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].", "type": "string" }, "conversationId": { @@ -290,7 +290,7 @@ ] }, "callId": { - "description": "Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent] and [codex_core::protocol::ExecCommandEndEvent].", + "description": "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].", "type": "string" }, "command": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 89f7dc34c3..d478bb2c78 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -93,7 +93,7 @@ "$schema": "http://json-schema.org/draft-07/schema#", "properties": { "callId": { - "description": "Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent] and [codex_core::protocol::PatchApplyEndEvent].", + "description": "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].", "type": "string" }, "conversationId": { @@ -4247,7 +4247,7 @@ ] }, "callId": { - "description": "Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent] and [codex_core::protocol::ExecCommandEndEvent].", + "description": "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].", "type": "string" }, "command": { diff --git a/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalParams.ts index 27de027cc6..d04f7b75df 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalParams.ts @@ -6,8 +6,8 @@ import type { ThreadId } from "./ThreadId"; export type ApplyPatchApprovalParams = { conversationId: ThreadId, /** - * Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent] - * and [codex_core::protocol::PatchApplyEndEvent]. + * Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] + * and [codex_protocol::protocol::PatchApplyEndEvent]. */ callId: string, fileChanges: { [key in string]?: FileChange }, /** diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandApprovalParams.ts index 5637d1305a..f68872905d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ExecCommandApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ExecCommandApprovalParams.ts @@ -6,8 +6,8 @@ import type { ThreadId } from "./ThreadId"; export type ExecCommandApprovalParams = { conversationId: ThreadId, /** - * Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent] - * and [codex_core::protocol::ExecCommandEndEvent]. + * Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] + * and [codex_protocol::protocol::ExecCommandEndEvent]. */ callId: string, /** diff --git a/codex-rs/app-server-protocol/src/protocol/v1.rs b/codex-rs/app-server-protocol/src/protocol/v1.rs index 13308ffafe..976f4e69d8 100644 --- a/codex-rs/app-server-protocol/src/protocol/v1.rs +++ b/codex-rs/app-server-protocol/src/protocol/v1.rs @@ -234,8 +234,8 @@ pub struct GitDiffToRemoteResponse { #[serde(rename_all = "camelCase")] pub struct ApplyPatchApprovalParams { pub conversation_id: ThreadId, - /// Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent] - /// and [codex_core::protocol::PatchApplyEndEvent]. + /// Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] + /// and [codex_protocol::protocol::PatchApplyEndEvent]. pub call_id: String, pub file_changes: HashMap, /// Optional explanatory reason (e.g. request for extra write access). @@ -255,8 +255,8 @@ pub struct ApplyPatchApprovalResponse { #[serde(rename_all = "camelCase")] pub struct ExecCommandApprovalParams { pub conversation_id: ThreadId, - /// Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent] - /// and [codex_core::protocol::ExecCommandEndEvent]. + /// Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] + /// and [codex_protocol::protocol::ExecCommandEndEvent]. pub call_id: String, /// Identifier for this specific approval callback. pub approval_id: Option, diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 7b90affe69..2f273a6794 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -21,6 +21,7 @@ async-trait = { workspace = true } codex-arg0 = { workspace = true } codex-cloud-requirements = { workspace = true } codex-core = { workspace = true } +codex-shell-command = { workspace = true } codex-utils-cli = { workspace = true } codex-backend-client = { workspace = true } codex-file-search = { workspace = true } diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index f53b10b843..fe3eb96852 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -76,28 +76,28 @@ use codex_app_server_protocol::convert_patch_changes; use codex_core::CodexThread; use codex_core::ThreadManager; use codex_core::find_thread_name_by_id; -use codex_core::parse_command::shlex_join; -use codex_core::protocol::ApplyPatchApprovalRequestEvent; -use codex_core::protocol::CodexErrorInfo as CoreCodexErrorInfo; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecApprovalRequestEvent; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::McpToolCallBeginEvent; -use codex_core::protocol::McpToolCallEndEvent; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewDecision; -use codex_core::protocol::TokenCountEvent; -use codex_core::protocol::TurnDiffEvent; use codex_core::review_format::format_review_findings_block; use codex_core::review_prompts; use codex_protocol::ThreadId; use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem; use codex_protocol::dynamic_tools::DynamicToolResponse as CoreDynamicToolResponse; use codex_protocol::plan_tool::UpdatePlanArgs; +use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; +use codex_protocol::protocol::CodexErrorInfo as CoreCodexErrorInfo; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecApprovalRequestEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::McpToolCallBeginEvent; +use codex_protocol::protocol::McpToolCallEndEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::ReviewOutputEvent; +use codex_protocol::protocol::TokenCountEvent; +use codex_protocol::protocol::TurnDiffEvent; use codex_protocol::request_user_input::RequestUserInputAnswer as CoreRequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputResponse as CoreRequestUserInputResponse; +use codex_shell_command::parse_command::shlex_join; use std::collections::HashMap; use std::convert::TryFrom; use std::path::Path; @@ -1942,7 +1942,7 @@ async fn on_command_execution_request_approval_response( } fn collab_resume_begin_item( - begin_event: codex_core::protocol::CollabResumeBeginEvent, + begin_event: codex_protocol::protocol::CollabResumeBeginEvent, ) -> ThreadItem { ThreadItem::CollabAgentToolCall { id: begin_event.call_id, @@ -1955,7 +1955,7 @@ fn collab_resume_begin_item( } } -fn collab_resume_end_item(end_event: codex_core::protocol::CollabResumeEndEvent) -> ThreadItem { +fn collab_resume_end_item(end_event: codex_protocol::protocol::CollabResumeEndEvent) -> ThreadItem { let status = match &end_event.status { codex_protocol::protocol::AgentStatus::Errored(_) | codex_protocol::protocol::AgentStatus::NotFound => V2CollabToolCallStatus::Failed, @@ -2060,17 +2060,17 @@ mod tests { use anyhow::anyhow; use anyhow::bail; use codex_app_server_protocol::TurnPlanStepStatus; - use codex_core::protocol::CollabResumeBeginEvent; - use codex_core::protocol::CollabResumeEndEvent; - use codex_core::protocol::CreditsSnapshot; - use codex_core::protocol::McpInvocation; - use codex_core::protocol::RateLimitSnapshot; - use codex_core::protocol::RateLimitWindow; - use codex_core::protocol::TokenUsage; - use codex_core::protocol::TokenUsageInfo; use codex_protocol::mcp::CallToolResult; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; + use codex_protocol::protocol::CollabResumeBeginEvent; + use codex_protocol::protocol::CollabResumeEndEvent; + use codex_protocol::protocol::CreditsSnapshot; + use codex_protocol::protocol::McpInvocation; + use codex_protocol::protocol::RateLimitSnapshot; + use codex_protocol::protocol::RateLimitWindow; + use codex_protocol::protocol::TokenUsage; + use codex_protocol::protocol::TokenUsageInfo; use pretty_assertions::assert_eq; use rmcp::model::Content; use serde_json::Value as JsonValue; diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 17a67fa4dc..d28b79db7e 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -175,7 +175,6 @@ use codex_core::AuthManager; use codex_core::CodexAuth; use codex_core::CodexThread; use codex_core::Cursor as RolloutCursor; -use codex_core::InitialHistory; use codex_core::NewThread; use codex_core::RolloutRecorder; use codex_core::SessionMeta; @@ -210,12 +209,6 @@ use codex_core::git_info::git_diff_to_remote; use codex_core::mcp::collect_mcp_snapshot; use codex_core::mcp::group_tools_by_server; use codex_core::parse_cursor; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewDelivery as CoreReviewDelivery; -use codex_core::protocol::ReviewRequest; -use codex_core::protocol::ReviewTarget as CoreReviewTarget; -use codex_core::protocol::SessionConfiguredEvent; use codex_core::read_head_for_summary; use codex_core::read_session_meta_line; use codex_core::rollout_date_parts; @@ -240,13 +233,20 @@ use codex_protocol::dynamic_tools::DynamicToolSpec as CoreDynamicToolSpec; use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::AgentStatus; +use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::GitInfo as CoreGitInfo; +use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::McpAuthStatus as CoreMcpAuthStatus; use codex_protocol::protocol::McpServerRefreshConfig; +use codex_protocol::protocol::Op; use codex_protocol::protocol::RateLimitSnapshot as CoreRateLimitSnapshot; use codex_protocol::protocol::RemoteSkillHazelnutScope; use codex_protocol::protocol::RemoteSkillProductSurface; +use codex_protocol::protocol::ReviewDelivery as CoreReviewDelivery; +use codex_protocol::protocol::ReviewRequest; +use codex_protocol::protocol::ReviewTarget as CoreReviewTarget; use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::USER_MESSAGE_BEGIN; use codex_protocol::user_input::UserInput as CoreInputItem; diff --git a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs index e6f887dba0..f6d3b9efb9 100644 --- a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs +++ b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs @@ -21,15 +21,15 @@ use codex_app_server_protocol::SendUserMessageResponse; use codex_app_server_protocol::SendUserTurnParams; use codex_app_server_protocol::SendUserTurnResponse; use codex_app_server_protocol::ServerRequest; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol_config_types::ReasoningSummary; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::SandboxMode; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::parse_command::ParsedCommand; +use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::SandboxPolicy; use pretty_assertions::assert_eq; use std::env; use std::path::Path; @@ -312,7 +312,7 @@ async fn test_send_user_turn_changes_approval_policy_behavior() -> Result<()> { // Approve so the first turn can complete mcp.send_response( request_id, - serde_json::json!({ "decision": codex_core::protocol::ReviewDecision::Approved }), + serde_json::json!({ "decision": codex_protocol::protocol::ReviewDecision::Approved }), ) .await?; diff --git a/codex-rs/app-server/tests/suite/config.rs b/codex-rs/app-server/tests/suite/config.rs index 84b268a3c2..27a44ef550 100644 --- a/codex-rs/app-server/tests/suite/config.rs +++ b/codex-rs/app-server/tests/suite/config.rs @@ -9,12 +9,12 @@ use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SandboxSettings; use codex_app_server_protocol::Tools; use codex_app_server_protocol::UserSavedConfig; -use codex_core::protocol::AskForApproval; use codex_protocol::config_types::ForcedLoginMethod; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::Verbosity; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::AskForApproval; use pretty_assertions::assert_eq; use std::collections::HashMap; use std::path::Path; diff --git a/codex-rs/app-server/tests/suite/fork_thread.rs b/codex-rs/app-server/tests/suite/fork_thread.rs index 17548fe041..ec282be4a1 100644 --- a/codex-rs/app-server/tests/suite/fork_thread.rs +++ b/codex-rs/app-server/tests/suite/fork_thread.rs @@ -10,7 +10,7 @@ use codex_app_server_protocol::NewConversationParams; // reused for overrides sh use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::SessionConfiguredNotification; -use codex_core::protocol::EventMsg; +use codex_protocol::protocol::EventMsg; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::time::timeout; diff --git a/codex-rs/app-server/tests/suite/interrupt.rs b/codex-rs/app-server/tests/suite/interrupt.rs index 2270afce28..dd09b832f8 100644 --- a/codex-rs/app-server/tests/suite/interrupt.rs +++ b/codex-rs/app-server/tests/suite/interrupt.rs @@ -12,7 +12,7 @@ use codex_app_server_protocol::NewConversationResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SendUserMessageParams; use codex_app_server_protocol::SendUserMessageResponse; -use codex_core::protocol::TurnAbortReason; +use codex_protocol::protocol::TurnAbortReason; use core_test_support::skip_if_no_network; use tempfile::TempDir; use tokio::time::timeout; diff --git a/codex-rs/app-server/tests/suite/list_resume.rs b/codex-rs/app-server/tests/suite/list_resume.rs index efa90ea351..97c8f41d11 100644 --- a/codex-rs/app-server/tests/suite/list_resume.rs +++ b/codex-rs/app-server/tests/suite/list_resume.rs @@ -12,9 +12,9 @@ use codex_app_server_protocol::ResumeConversationParams; use codex_app_server_protocol::ResumeConversationResponse; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::SessionConfiguredNotification; -use codex_core::protocol::EventMsg; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::EventMsg; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::time::timeout; diff --git a/codex-rs/app-server/tests/suite/output_schema.rs b/codex-rs/app-server/tests/suite/output_schema.rs index c120a7fe2d..3d83bec7dd 100644 --- a/codex-rs/app-server/tests/suite/output_schema.rs +++ b/codex-rs/app-server/tests/suite/output_schema.rs @@ -9,10 +9,10 @@ use codex_app_server_protocol::NewConversationResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SendUserTurnParams; use codex_app_server_protocol::SendUserTurnResponse; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; use core_test_support::responses; use core_test_support::skip_if_no_network; use pretty_assertions::assert_eq; diff --git a/codex-rs/app-server/tests/suite/v2/review.rs b/codex-rs/app-server/tests/suite/v2/review.rs index 219812d6b1..262b13969e 100644 --- a/codex-rs/app-server/tests/suite/v2/review.rs +++ b/codex-rs/app-server/tests/suite/v2/review.rs @@ -209,7 +209,7 @@ async fn review_start_exec_approval_item_id_matches_command_execution_item() -> mcp.send_response( request_id, - serde_json::json!({ "decision": codex_core::protocol::ReviewDecision::Approved }), + serde_json::json!({ "decision": codex_protocol::protocol::ReviewDecision::Approved }), ) .await?; timeout( diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 8d6db34731..eaa017d6ae 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -39,10 +39,10 @@ use codex_core::config::ConfigToml; use codex_core::features::FEATURES; use codex_core::features::Feature; use codex_core::personality_migration::PERSONALITY_MIGRATION_FILENAME; -use codex_core::protocol_config_types::ReasoningSummary; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Personality; +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; use codex_protocol::openai_models::ReasoningEffort; use core_test_support::responses; diff --git a/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs b/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs index 4be127dff8..94467b8719 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs @@ -111,7 +111,7 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> { sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::DangerFullAccess), model: Some("mock-model".to_string()), effort: Some(codex_protocol::openai_models::ReasoningEffort::Medium), - summary: Some(codex_core::protocol_config_types::ReasoningSummary::Auto), + summary: Some(codex_protocol::config_types::ReasoningSummary::Auto), ..Default::default() }) .await?; @@ -505,7 +505,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() }), model: Some("mock-model".to_string()), effort: Some(codex_protocol::openai_models::ReasoningEffort::Medium), - summary: Some(codex_core::protocol_config_types::ReasoningSummary::Auto), + summary: Some(codex_protocol::config_types::ReasoningSummary::Auto), ..Default::default() }) .await?; diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 98a5ab0779..e5478f1b90 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -390,7 +390,7 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec TuiCli { diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index be3678e07e..396e077411 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -14,7 +14,7 @@ use codex_core::config::types::McpServerTransportConfig; use codex_core::mcp::auth::McpOAuthLoginSupport; use codex_core::mcp::auth::compute_auth_statuses; use codex_core::mcp::auth::oauth_login_support; -use codex_core::protocol::McpAuthStatus; +use codex_protocol::protocol::McpAuthStatus; use codex_rmcp_client::delete_oauth_tokens; use codex_rmcp_client::perform_oauth_login; use codex_utils_cli::CliConfigOverrides; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 4dc2a607c6..b54830a539 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -84,7 +84,6 @@ mod seatbelt_permissions; mod thread_manager; pub mod web_search; pub mod windows_sandbox_read_grants; -pub use codex_protocol::protocol::InitialHistory; pub use thread_manager::NewThread; pub use thread_manager::ThreadManager; #[deprecated(note = "use ThreadManager")] @@ -138,11 +137,12 @@ mod state; mod tasks; mod user_shell_command; pub mod util; -pub use codex_shell_command::bash; -pub use codex_shell_command::is_dangerous_command; -pub use codex_shell_command::is_safe_command; -pub use codex_shell_command::parse_command; -pub use codex_shell_command::powershell; +pub(crate) use codex_protocol::protocol; +pub(crate) use codex_shell_command::bash; +pub(crate) use codex_shell_command::is_dangerous_command; +pub(crate) use codex_shell_command::is_safe_command; +pub(crate) use codex_shell_command::parse_command; +pub(crate) use codex_shell_command::powershell; pub use apply_patch::CODEX_APPLY_PATCH_ARG1; pub use client::X_CODEX_TURN_METADATA_HEADER; @@ -155,12 +155,6 @@ pub use safety::get_platform_sandbox; pub use tools::spec::parse_tool_input_schema; pub use turn_metadata::build_turn_metadata_header; pub use zsh_exec_bridge::maybe_run_zsh_exec_wrapper_mode; -// Re-export the protocol types from the standalone `codex-protocol` crate so existing -// `codex_core::protocol::...` references continue to work across the workspace. -pub use codex_protocol::protocol; -// Re-export protocol config enums to ensure call sites can use the same types -// as those in the protocol crate when constructing protocol messages. -pub use codex_protocol::config_types as protocol_config_types; pub use client::ModelClient; pub use client::ModelClientSession; @@ -168,11 +162,6 @@ pub use client_common::Prompt; pub use client_common::REVIEW_PROMPT; pub use client_common::ResponseEvent; pub use client_common::ResponseStream; -pub use codex_protocol::models::ContentItem; -pub use codex_protocol::models::LocalShellAction; -pub use codex_protocol::models::LocalShellExecAction; -pub use codex_protocol::models::LocalShellStatus; -pub use codex_protocol::models::ResponseItem; pub use compact::content_items_to_text; pub use event_mapping::parse_turn_item; pub mod compact; diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index a7fda23cd0..a4422e4580 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -175,9 +175,12 @@ pub fn load_sse_fixture_with_id_from_str(raw: &str, id: &str) -> String { .collect() } -pub async fn wait_for_event(codex: &CodexThread, predicate: F) -> codex_core::protocol::EventMsg +pub async fn wait_for_event( + codex: &CodexThread, + predicate: F, +) -> codex_protocol::protocol::EventMsg where - F: FnMut(&codex_core::protocol::EventMsg) -> bool, + F: FnMut(&codex_protocol::protocol::EventMsg) -> bool, { use tokio::time::Duration; wait_for_event_with_timeout(codex, predicate, Duration::from_secs(1)).await @@ -185,7 +188,7 @@ where pub async fn wait_for_event_match(codex: &CodexThread, matcher: F) -> T where - F: Fn(&codex_core::protocol::EventMsg) -> Option, + F: Fn(&codex_protocol::protocol::EventMsg) -> Option, { let ev = wait_for_event(codex, |ev| matcher(ev).is_some()).await; matcher(&ev).unwrap() @@ -195,9 +198,9 @@ pub async fn wait_for_event_with_timeout( codex: &CodexThread, mut predicate: F, wait_time: tokio::time::Duration, -) -> codex_core::protocol::EventMsg +) -> codex_protocol::protocol::EventMsg where - F: FnMut(&codex_core::protocol::EventMsg) -> bool, + F: FnMut(&codex_protocol::protocol::EventMsg) -> bool, { use tokio::time::Duration; use tokio::time::timeout; diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index b06aa6c58e..8205909238 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -11,12 +11,12 @@ use codex_core::ThreadManager; use codex_core::built_in_model_providers; use codex_core::config::Config; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::SessionConfiguredEvent; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::user_input::UserInput; use serde_json::Value; use tempfile::TempDir; diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 71c8b4717a..b392081eeb 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -2,17 +2,17 @@ use std::process::Command; use std::sync::Arc; use codex_core::CodexAuth; -use codex_core::ContentItem; use codex_core::ModelClient; use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; -use codex_core::ResponseItem; use codex_core::WireApi; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; use codex_protocol::ThreadId; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use core_test_support::load_default_config_for_test; diff --git a/codex-rs/core/tests/suite/abort_tasks.rs b/codex-rs/core/tests/suite/abort_tasks.rs index 53b5a26b02..af3c70b74e 100644 --- a/codex-rs/core/tests/suite/abort_tasks.rs +++ b/codex-rs/core/tests/suite/abort_tasks.rs @@ -2,8 +2,8 @@ use assert_matches::assert_matches; use std::sync::Arc; use std::time::Duration; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index b84df343d0..9ef2715d8c 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -11,11 +11,11 @@ use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::responses::ev_apply_patch_function_call; diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 374cc1ada7..38ae062ab2 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -3,16 +3,16 @@ use anyhow::Result; use codex_core::config::Constrained; use codex_core::features::Feature; -use codex_core::protocol::ApplyPatchApprovalRequestEvent; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecApprovalRequestEvent; -use codex_core::protocol::ExecPolicyAmendment; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_core::sandboxing::SandboxPermissions; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecApprovalRequestEvent; +use codex_protocol::protocol::ExecPolicyAmendment; +use codex_protocol::protocol::Op; use codex_protocol::protocol::ReviewDecision; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; diff --git a/codex-rs/core/tests/suite/cli_stream.rs b/codex-rs/core/tests/suite/cli_stream.rs index d677d96edb..07faed70a8 100644 --- a/codex-rs/core/tests/suite/cli_stream.rs +++ b/codex-rs/core/tests/suite/cli_stream.rs @@ -1,6 +1,6 @@ use assert_cmd::Command as AssertCommand; use codex_core::auth::CODEX_API_KEY_ENV_VAR; -use codex_core::protocol::GitInfo; +use codex_protocol::protocol::GitInfo; use codex_utils_cargo_bin::find_resource; use core_test_support::fs_wait; use core_test_support::responses; diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index cc5fee3066..77a2ba33e0 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -1,14 +1,9 @@ use codex_core::CodexAuth; -use codex_core::ContentItem; -use codex_core::LocalShellAction; -use codex_core::LocalShellExecAction; -use codex_core::LocalShellStatus; use codex_core::ModelClient; use codex_core::ModelProviderInfo; use codex_core::NewThread; use codex_core::Prompt; use codex_core::ResponseEvent; -use codex_core::ResponseItem; use codex_core::ThreadManager; use codex_core::WireApi; use codex_core::auth::AuthCredentialsStoreMode; @@ -16,9 +11,6 @@ use codex_core::built_in_model_providers; use codex_core::default_client::originator; use codex_core::error::CodexErr; use codex_core::features::Feature; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SessionSource; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; use codex_protocol::ThreadId; @@ -27,12 +19,20 @@ use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; use codex_protocol::config_types::Verbosity; +use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::LocalShellAction; +use codex_protocol::models::LocalShellExecAction; +use codex_protocol::models::LocalShellStatus; use codex_protocol::models::MessagePhase; use codex_protocol::models::ReasoningItemContent; use codex_protocol::models::ReasoningItemReasoningSummary; +use codex_protocol::models::ResponseItem; use codex_protocol::models::WebSearchAction; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SessionSource; use codex_protocol::user_input::UserInput; use core_test_support::apps_test_server::AppsTestServer; use core_test_support::load_default_config_for_test; diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 736e5f50fe..54e197e568 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -1,18 +1,13 @@ #![allow(clippy::expect_used, clippy::unwrap_used)] use codex_core::CodexAuth; -use codex_core::ContentItem; use codex_core::ModelClient; use codex_core::ModelClientSession; use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; -use codex_core::ResponseItem; use codex_core::WireApi; use codex_core::X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER; use codex_core::features::Feature; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SessionSource; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; use codex_otel::metrics::MetricsClient; @@ -21,8 +16,13 @@ use codex_protocol::ThreadId; use codex_protocol::account::PlanType; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::BaseInstructions; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SessionSource; use codex_protocol::user_input::UserInput; use core_test_support::load_default_config_for_test; use core_test_support::responses::WebSocketConnectionConfig; diff --git a/codex-rs/core/tests/suite/codex_delegate.rs b/codex-rs/core/tests/suite/codex_delegate.rs index 841dbbb2cb..e71d99b620 100644 --- a/codex-rs/core/tests/suite/codex_delegate.rs +++ b/codex-rs/core/tests/suite/codex_delegate.rs @@ -1,12 +1,12 @@ use codex_core::config::Constrained; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewDecision; -use codex_core::protocol::ReviewRequest; -use codex_core::protocol::ReviewTarget; -use codex_core::protocol::SandboxPolicy; use codex_core::sandboxing::SandboxPermissions; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; +use codex_protocol::protocol::ReviewRequest; +use codex_protocol::protocol::ReviewTarget; +use codex_protocol::protocol::SandboxPolicy; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/collaboration_instructions.rs b/codex-rs/core/tests/suite/collaboration_instructions.rs index a6cad3a5ce..68d695325d 100644 --- a/codex-rs/core/tests/suite/collaboration_instructions.rs +++ b/codex-rs/core/tests/suite/collaboration_instructions.rs @@ -1,11 +1,11 @@ use anyhow::Result; -use codex_core::protocol::COLLABORATION_MODE_CLOSE_TAG; -use codex_core::protocol::COLLABORATION_MODE_OPEN_TAG; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; +use codex_protocol::protocol::COLLABORATION_MODE_CLOSE_TAG; +use codex_protocol::protocol::COLLABORATION_MODE_OPEN_TAG; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index c4745ab20e..9e9ce931e9 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -5,19 +5,19 @@ use codex_core::built_in_model_providers; use codex_core::compact::SUMMARIZATION_PROMPT; use codex_core::compact::SUMMARY_PREFIX; use codex_core::config::Config; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ItemCompletedEvent; -use codex_core::protocol::ItemStartedEvent; -use codex_core::protocol::Op; -use codex_core::protocol::RolloutItem; -use codex_core::protocol::RolloutLine; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::WarningEvent; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::items::TurnItem; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelsResponse; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::ItemStartedEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::UserInput; use core_test_support::context_snapshot; use core_test_support::context_snapshot::ContextSnapshotOptions; diff --git a/codex-rs/core/tests/suite/compact_remote.rs b/codex-rs/core/tests/suite/compact_remote.rs index 6baccc16f4..1d450f9b11 100644 --- a/codex-rs/core/tests/suite/compact_remote.rs +++ b/codex-rs/core/tests/suite/compact_remote.rs @@ -6,15 +6,15 @@ use std::path::PathBuf; use anyhow::Result; use codex_core::CodexAuth; use codex_core::compact::SUMMARY_PREFIX; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ItemCompletedEvent; -use codex_core::protocol::ItemStartedEvent; -use codex_core::protocol::Op; -use codex_core::protocol::RolloutItem; -use codex_core::protocol::RolloutLine; use codex_protocol::items::TurnItem; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::ItemStartedEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; use codex_protocol::user_input::UserInput; use core_test_support::context_snapshot; use core_test_support::context_snapshot::ContextSnapshotOptions; diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index b66edb84aa..5b3f409125 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -14,10 +14,10 @@ use codex_core::CodexThread; use codex_core::ThreadManager; use codex_core::compact::SUMMARIZATION_PROMPT; use codex_core::config::Config; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::WarningEvent; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::UserInput; use core_test_support::responses::ResponseMock; use core_test_support::responses::ev_assistant_message; diff --git a/codex-rs/core/tests/suite/deprecation_notice.rs b/codex-rs/core/tests/suite/deprecation_notice.rs index dbae99006d..2a7563bea1 100644 --- a/codex-rs/core/tests/suite/deprecation_notice.rs +++ b/codex-rs/core/tests/suite/deprecation_notice.rs @@ -7,8 +7,8 @@ use codex_core::config_loader::ConfigLayerStack; use codex_core::config_loader::ConfigRequirements; use codex_core::config_loader::ConfigRequirementsToml; use codex_core::features::Feature; -use codex_core::protocol::DeprecationNoticeEvent; -use codex_core::protocol::EventMsg; +use codex_protocol::protocol::DeprecationNoticeEvent; +use codex_protocol::protocol::EventMsg; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_absolute_path; diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index c3cb15875b..6546600681 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -7,10 +7,10 @@ use codex_core::exec::ExecParams; use codex_core::exec::ExecToolCallOutput; use codex_core::exec::SandboxType; use codex_core::exec::process_exec_tool_call; -use codex_core::protocol::SandboxPolicy; use codex_core::sandboxing::SandboxPermissions; use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::protocol::SandboxPolicy; use tempfile::TempDir; use codex_core::error::Result; diff --git a/codex-rs/core/tests/suite/exec_policy.rs b/codex-rs/core/tests/suite/exec_policy.rs index 4922fcf9c8..3fd06d83c7 100644 --- a/codex-rs/core/tests/suite/exec_policy.rs +++ b/codex-rs/core/tests/suite/exec_policy.rs @@ -2,14 +2,14 @@ use anyhow::Result; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/fork_thread.rs b/codex-rs/core/tests/suite/fork_thread.rs index 3d97400a97..96457065de 100644 --- a/codex-rs/core/tests/suite/fork_thread.rs +++ b/codex-rs/core/tests/suite/fork_thread.rs @@ -1,10 +1,10 @@ use codex_core::NewThread; use codex_core::parse_turn_item; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::RolloutItem; -use codex_core::protocol::RolloutLine; use codex_protocol::items::TurnItem; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; diff --git a/codex-rs/core/tests/suite/image_rollout.rs b/codex-rs/core/tests/suite/image_rollout.rs index 691531e049..2349d9f5fa 100644 --- a/codex-rs/core/tests/suite/image_rollout.rs +++ b/codex-rs/core/tests/suite/image_rollout.rs @@ -1,13 +1,13 @@ use anyhow::Context; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::RolloutItem; -use codex_core::protocol::RolloutLine; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ev_assistant_message; diff --git a/codex-rs/core/tests/suite/items.rs b/codex-rs/core/tests/suite/items.rs index 842122dfea..844c55c6bc 100644 --- a/codex-rs/core/tests/suite/items.rs +++ b/codex-rs/core/tests/suite/items.rs @@ -1,16 +1,16 @@ #![cfg(not(target_os = "windows"))] use anyhow::Ok; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ItemCompletedEvent; -use codex_core::protocol::ItemStartedEvent; -use codex_core::protocol::Op; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; use codex_protocol::items::AgentMessageContent; use codex_protocol::items::TurnItem; use codex_protocol::models::WebSearchAction; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::ItemStartedEvent; +use codex_protocol::protocol::Op; use codex_protocol::user_input::ByteRange; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; @@ -373,8 +373,8 @@ async fn plan_mode_emits_plan_item_from_proposed_plan_block() -> anyhow::Result< }], final_output_json_schema: None, cwd: std::env::current_dir()?, - approval_policy: codex_core::protocol::AskForApproval::Never, - sandbox_policy: codex_core::protocol::SandboxPolicy::DangerFullAccess, + approval_policy: codex_protocol::protocol::AskForApproval::Never, + sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, summary: codex_protocol::config_types::ReasoningSummary::Auto, @@ -448,8 +448,8 @@ async fn plan_mode_strips_plan_from_agent_messages() -> anyhow::Result<()> { }], final_output_json_schema: None, cwd: std::env::current_dir()?, - approval_policy: codex_core::protocol::AskForApproval::Never, - sandbox_policy: codex_core::protocol::SandboxPolicy::DangerFullAccess, + approval_policy: codex_protocol::protocol::AskForApproval::Never, + sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, summary: codex_protocol::config_types::ReasoningSummary::Auto, @@ -544,8 +544,8 @@ async fn plan_mode_handles_missing_plan_close_tag() -> anyhow::Result<()> { }], final_output_json_schema: None, cwd: std::env::current_dir()?, - approval_policy: codex_core::protocol::AskForApproval::Never, - sandbox_policy: codex_core::protocol::SandboxPolicy::DangerFullAccess, + approval_policy: codex_protocol::protocol::AskForApproval::Never, + sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, summary: codex_protocol::config_types::ReasoningSummary::Auto, diff --git a/codex-rs/core/tests/suite/json_result.rs b/codex-rs/core/tests/suite/json_result.rs index b76d7ac899..e32865e0c7 100644 --- a/codex-rs/core/tests/suite/json_result.rs +++ b/codex-rs/core/tests/suite/json_result.rs @@ -1,10 +1,10 @@ #![cfg(not(target_os = "windows"))] -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::skip_if_no_network; diff --git a/codex-rs/core/tests/suite/live_reload.rs b/codex-rs/core/tests/suite/live_reload.rs index 0ebcb332ef..3ea0a3cbe9 100644 --- a/codex-rs/core/tests/suite/live_reload.rs +++ b/codex-rs/core/tests/suite/live_reload.rs @@ -7,12 +7,12 @@ use std::time::Duration; use anyhow::Result; use codex_core::config::ProjectConfig; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::TrustLevel; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ResponsesRequest; diff --git a/codex-rs/core/tests/suite/model_overrides.rs b/codex-rs/core/tests/suite/model_overrides.rs index 698ee15b61..1ba469f7f9 100644 --- a/codex-rs/core/tests/suite/model_overrides.rs +++ b/codex-rs/core/tests/suite/model_overrides.rs @@ -1,6 +1,6 @@ -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use core_test_support::responses::start_mock_server; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index 4d4abafeb6..6e06b0f224 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -3,10 +3,6 @@ use codex_core::CodexAuth; use codex_core::config::types::Personality; use codex_core::features::Feature; use codex_core::models_manager::manager::RefreshStrategy; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; @@ -17,6 +13,10 @@ use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::openai_models::default_input_modalities; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed_with_tokens; use core_test_support::responses::ev_response_created; diff --git a/codex-rs/core/tests/suite/model_visible_layout.rs b/codex-rs/core/tests/suite/model_visible_layout.rs index f3daf06c8b..3288eb5c05 100644 --- a/codex-rs/core/tests/suite/model_visible_layout.rs +++ b/codex-rs/core/tests/suite/model_visible_layout.rs @@ -6,11 +6,11 @@ use std::sync::Arc; use anyhow::Result; use codex_core::config::types::Personality; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::context_snapshot; use core_test_support::context_snapshot::ContextSnapshotOptions; diff --git a/codex-rs/core/tests/suite/models_cache_ttl.rs b/codex-rs/core/tests/suite/models_cache_ttl.rs index e9f0a73f98..3422e397b8 100644 --- a/codex-rs/core/tests/suite/models_cache_ttl.rs +++ b/codex-rs/core/tests/suite/models_cache_ttl.rs @@ -7,9 +7,6 @@ use chrono::TimeZone; use chrono::Utc; use codex_core::CodexAuth; use codex_core::models_manager::manager::RefreshStrategy; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; @@ -19,6 +16,9 @@ use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::openai_models::default_input_modalities; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ev_assistant_message; @@ -95,7 +95,7 @@ async fn renews_cache_ttl_on_matching_models_etag() -> Result<()> { }], final_output_json_schema: None, cwd: test.cwd_path().to_path_buf(), - approval_policy: codex_core::protocol::AskForApproval::Never, + approval_policy: codex_protocol::protocol::AskForApproval::Never, sandbox_policy: SandboxPolicy::DangerFullAccess, model: test.session_configured.model.clone(), effort: None, diff --git a/codex-rs/core/tests/suite/models_etag_responses.rs b/codex-rs/core/tests/suite/models_etag_responses.rs index 13c31cd7f9..7c40bec987 100644 --- a/codex-rs/core/tests/suite/models_etag_responses.rs +++ b/codex-rs/core/tests/suite/models_etag_responses.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use anyhow::Result; use codex_core::CodexAuth; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ModelsResponse; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ev_assistant_message; diff --git a/codex-rs/core/tests/suite/override_updates.rs b/codex-rs/core/tests/suite/override_updates.rs index d8455824b7..7ae78891f1 100644 --- a/codex-rs/core/tests/suite/override_updates.rs +++ b/codex-rs/core/tests/suite/override_updates.rs @@ -1,13 +1,13 @@ use anyhow::Result; use codex_core::config::Constrained; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::COLLABORATION_MODE_CLOSE_TAG; -use codex_core::protocol::COLLABORATION_MODE_OPEN_TAG; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::RolloutItem; -use codex_core::protocol::RolloutLine; -use codex_core::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::COLLABORATION_MODE_CLOSE_TAG; +use codex_protocol::protocol::COLLABORATION_MODE_OPEN_TAG; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; diff --git a/codex-rs/core/tests/suite/pending_input.rs b/codex-rs/core/tests/suite/pending_input.rs index c89bcb9a90..30b0d9d50b 100644 --- a/codex-rs/core/tests/suite/pending_input.rs +++ b/codex-rs/core/tests/suite/pending_input.rs @@ -1,5 +1,5 @@ -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/permissions_messages.rs b/codex-rs/core/tests/suite/permissions_messages.rs index 5db3bf9f0a..4bbe5f4ab2 100644 --- a/codex-rs/core/tests/suite/permissions_messages.rs +++ b/codex-rs/core/tests/suite/permissions_messages.rs @@ -1,11 +1,11 @@ use anyhow::Result; use codex_core::config::Constrained; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_execpolicy::Policy; use codex_protocol::models::DeveloperInstructions; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index d15147ed36..0b4d485cfb 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -2,10 +2,6 @@ use codex_core::config::types::Personality; use codex_core::features::Feature; use codex_core::models_manager::manager::ModelsManager; use codex_core::models_manager::manager::RefreshStrategy; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; @@ -17,6 +13,10 @@ use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::openai_models::default_input_modalities; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::load_default_config_for_test; use core_test_support::responses::mount_models_once; diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 351d1d5752..38a8145d50 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -2,19 +2,19 @@ use codex_apply_patch::APPLY_PATCH_TOOL_INSTRUCTIONS; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol_config_types::ReasoningSummary; use codex_core::shell::Shell; use codex_core::shell::default_user_shell; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; use codex_protocol::config_types::WebSearchMode; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/quota_exceeded.rs b/codex-rs/core/tests/suite/quota_exceeded.rs index afa23275e0..466680e6a8 100644 --- a/codex-rs/core/tests/suite/quota_exceeded.rs +++ b/codex-rs/core/tests/suite/quota_exceeded.rs @@ -1,6 +1,6 @@ use anyhow::Result; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_once; diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index 3d94ccf533..466686788d 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -1,14 +1,14 @@ use anyhow::Result; -use codex_core::protocol::CodexErrorInfo; -use codex_core::protocol::ConversationAudioParams; -use codex_core::protocol::ConversationStartParams; -use codex_core::protocol::ConversationTextParams; -use codex_core::protocol::ErrorEvent; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::RealtimeAudioFrame; -use codex_core::protocol::RealtimeConversationRealtimeEvent; -use codex_core::protocol::RealtimeEvent; +use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::ConversationAudioParams; +use codex_protocol::protocol::ConversationStartParams; +use codex_protocol::protocol::ConversationTextParams; +use codex_protocol::protocol::ErrorEvent; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RealtimeAudioFrame; +use codex_protocol::protocol::RealtimeConversationRealtimeEvent; +use codex_protocol::protocol::RealtimeEvent; use core_test_support::responses::start_websocket_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::test_codex; diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index 110150d447..f4d0d1b843 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -9,11 +9,6 @@ use codex_core::ModelProviderInfo; use codex_core::built_in_model_providers; use codex_core::models_manager::manager::ModelsManager; use codex_core::models_manager::manager::RefreshStrategy; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecCommandSource; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; @@ -24,6 +19,11 @@ use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::openai_models::default_input_modalities; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::load_default_config_for_test; use core_test_support::responses::ev_assistant_message; diff --git a/codex-rs/core/tests/suite/request_compression.rs b/codex-rs/core/tests/suite/request_compression.rs index 9a99b913fd..9942435048 100644 --- a/codex-rs/core/tests/suite/request_compression.rs +++ b/codex-rs/core/tests/suite/request_compression.rs @@ -2,8 +2,8 @@ use codex_core::CodexAuth; use codex_core::features::Feature; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; diff --git a/codex-rs/core/tests/suite/request_user_input.rs b/codex-rs/core/tests/suite/request_user_input.rs index 6d8b8cb035..ac6c1d2f3f 100644 --- a/codex-rs/core/tests/suite/request_user_input.rs +++ b/codex-rs/core/tests/suite/request_user_input.rs @@ -3,14 +3,14 @@ use std::collections::HashMap; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputResponse; use codex_protocol::user_input::UserInput; diff --git a/codex-rs/core/tests/suite/resume.rs b/codex-rs/core/tests/suite/resume.rs index 261ec58089..3d75879e49 100644 --- a/codex-rs/core/tests/suite/resume.rs +++ b/codex-rs/core/tests/suite/resume.rs @@ -1,6 +1,6 @@ use anyhow::Result; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::ByteRange; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index 89a08b9e55..b0503d5929 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -2,17 +2,17 @@ use codex_core::CodexAuth; use codex_core::NewThread; -use codex_core::protocol::EventMsg; -use codex_core::protocol::InitialHistory; -use codex_core::protocol::ResumedHistory; -use codex_core::protocol::RolloutItem; -use codex_core::protocol::TurnCompleteEvent; -use codex_core::protocol::TurnContextItem; -use codex_core::protocol::TurnStartedEvent; -use codex_core::protocol::UserMessageEvent; -use codex_core::protocol::WarningEvent; use codex_protocol::ThreadId; use codex_protocol::config_types::ModeKind; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::InitialHistory; +use codex_protocol::protocol::ResumedHistory; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnContextItem; +use codex_protocol::protocol::TurnStartedEvent; +use codex_protocol::protocol::UserMessageEvent; +use codex_protocol::protocol::WarningEvent; use core::time::Duration; use core_test_support::load_default_config_for_test; use core_test_support::wait_for_event; diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index 113776b81f..a123981444 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -1,21 +1,21 @@ use codex_core::CodexThread; -use codex_core::ContentItem; use codex_core::REVIEW_PROMPT; -use codex_core::ResponseItem; use codex_core::config::Config; -use codex_core::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExitedReviewModeEvent; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewCodeLocation; -use codex_core::protocol::ReviewFinding; -use codex_core::protocol::ReviewLineRange; -use codex_core::protocol::ReviewOutputEvent; -use codex_core::protocol::ReviewRequest; -use codex_core::protocol::ReviewTarget; -use codex_core::protocol::RolloutItem; -use codex_core::protocol::RolloutLine; use codex_core::review_format::render_review_output_text; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExitedReviewModeEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewCodeLocation; +use codex_protocol::protocol::ReviewFinding; +use codex_protocol::protocol::ReviewLineRange; +use codex_protocol::protocol::ReviewOutputEvent; +use codex_protocol::protocol::ReviewRequest; +use codex_protocol::protocol::ReviewTarget; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; use codex_protocol::user_input::UserInput; use core_test_support::load_sse_fixture_with_id_from_str; use core_test_support::responses::ResponseMock; diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 4c8cd563a6..df389c5ef7 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -13,12 +13,6 @@ use codex_core::config::types::McpServerConfig; use codex_core::config::types::McpServerTransportConfig; use codex_core::models_manager::manager::RefreshStrategy; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::McpInvocation; -use codex_core::protocol::McpToolCallBeginEvent; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; @@ -27,6 +21,12 @@ use codex_protocol::openai_models::ModelVisibility; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationPolicyConfig; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::McpInvocation; +use codex_protocol::protocol::McpToolCallBeginEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use codex_utils_cargo_bin::cargo_bin; use core_test_support::responses; diff --git a/codex-rs/core/tests/suite/rollout_list_find.rs b/codex-rs/core/tests/suite/rollout_list_find.rs index d9f92b85bd..83350a0d02 100644 --- a/codex-rs/core/tests/suite/rollout_list_find.rs +++ b/codex-rs/core/tests/suite/rollout_list_find.rs @@ -11,9 +11,9 @@ use codex_core::config::ConfigBuilder; use codex_core::find_archived_thread_path_by_id_str; use codex_core::find_thread_path_by_id_str; use codex_core::find_thread_path_by_name_str; -use codex_core::protocol::SessionSource; use codex_protocol::ThreadId; use codex_protocol::models::BaseInstructions; +use codex_protocol::protocol::SessionSource; use codex_state::StateRuntime; use codex_state::ThreadMetadataBuilder; use pretty_assertions::assert_eq; diff --git a/codex-rs/core/tests/suite/safety_check_downgrade.rs b/codex-rs/core/tests/suite/safety_check_downgrade.rs index 6f4fbe553b..247cfdaedc 100644 --- a/codex-rs/core/tests/suite/safety_check_downgrade.rs +++ b/codex-rs/core/tests/suite/safety_check_downgrade.rs @@ -1,12 +1,12 @@ use anyhow::Result; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ModelRerouteReason; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ModelRerouteReason; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_function_call; diff --git a/codex-rs/core/tests/suite/search_tool.rs b/codex-rs/core/tests/suite/search_tool.rs index 7d2de4eb9a..1caab45b12 100644 --- a/codex-rs/core/tests/suite/search_tool.rs +++ b/codex-rs/core/tests/suite/search_tool.rs @@ -11,10 +11,10 @@ use codex_core::config::Config; use codex_core::config::types::McpServerConfig; use codex_core::config::types::McpServerTransportConfig; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::apps_test_server::AppsTestServer; use core_test_support::responses::ResponsesRequest; diff --git a/codex-rs/core/tests/suite/seatbelt.rs b/codex-rs/core/tests/suite/seatbelt.rs index 89674494a9..cfb91caeed 100644 --- a/codex-rs/core/tests/suite/seatbelt.rs +++ b/codex-rs/core/tests/suite/seatbelt.rs @@ -7,10 +7,10 @@ use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; -use codex_core::protocol::SandboxPolicy; use codex_core::seatbelt::spawn_command_under_seatbelt; use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; use codex_core::spawn::StdioPolicy; +use codex_protocol::protocol::SandboxPolicy; use tempfile::TempDir; struct TestScenario { diff --git a/codex-rs/core/tests/suite/shell_serialization.rs b/codex-rs/core/tests/suite/shell_serialization.rs index 6969b6533d..3e5942da6a 100644 --- a/codex-rs/core/tests/suite/shell_serialization.rs +++ b/codex-rs/core/tests/suite/shell_serialization.rs @@ -2,7 +2,7 @@ #![allow(clippy::expect_used)] use anyhow::Result; -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::SandboxPolicy; use core_test_support::assert_regex_match; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/shell_snapshot.rs b/codex-rs/core/tests/suite/shell_snapshot.rs index 6a0983a6ed..2a8017b393 100644 --- a/codex-rs/core/tests/suite/shell_snapshot.rs +++ b/codex-rs/core/tests/suite/shell_snapshot.rs @@ -1,12 +1,12 @@ use anyhow::Result; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecCommandBeginEvent; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/skills.rs b/codex-rs/core/tests/suite/skills.rs index 54cdba4d21..f681ca1b64 100644 --- a/codex-rs/core/tests/suite/skills.rs +++ b/codex-rs/core/tests/suite/skills.rs @@ -2,9 +2,9 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] use anyhow::Result; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; @@ -84,7 +84,7 @@ async fn user_turn_includes_skill_instructions() -> Result<()> { .await?; core_test_support::wait_for_event(test.codex.as_ref(), |event| { - matches!(event, codex_core::protocol::EventMsg::TurnComplete(_)) + matches!(event, codex_protocol::protocol::EventMsg::TurnComplete(_)) }) .await; @@ -124,7 +124,9 @@ async fn skill_load_errors_surface_in_session_configured() -> Result<()> { .await?; let response = core_test_support::wait_for_event_match(test.codex.as_ref(), |event| match event { - codex_core::protocol::EventMsg::ListSkillsResponse(response) => Some(response.clone()), + codex_protocol::protocol::EventMsg::ListSkillsResponse(response) => { + Some(response.clone()) + } _ => None, }) .await; @@ -192,7 +194,9 @@ async fn list_skills_includes_system_cache_entries() -> Result<()> { .await?; let response = core_test_support::wait_for_event_match(test.codex.as_ref(), |event| match event { - codex_core::protocol::EventMsg::ListSkillsResponse(response) => Some(response.clone()), + codex_protocol::protocol::EventMsg::ListSkillsResponse(response) => { + Some(response.clone()) + } _ => None, }) .await; diff --git a/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs b/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs index 3562ec2500..a8d1b37950 100644 --- a/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs +++ b/codex-rs/core/tests/suite/stream_error_allows_next_turn.rs @@ -1,7 +1,7 @@ use codex_core::ModelProviderInfo; use codex_core::WireApi; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; diff --git a/codex-rs/core/tests/suite/stream_no_completed.rs b/codex-rs/core/tests/suite/stream_no_completed.rs index 6528e6277d..ac6d59b21b 100644 --- a/codex-rs/core/tests/suite/stream_no_completed.rs +++ b/codex-rs/core/tests/suite/stream_no_completed.rs @@ -3,8 +3,8 @@ use codex_core::ModelProviderInfo; use codex_core::WireApi; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::load_sse_fixture; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/tool_harness.rs b/codex-rs/core/tests/suite/tool_harness.rs index 6114760253..507c8eb068 100644 --- a/codex-rs/core/tests/suite/tool_harness.rs +++ b/codex-rs/core/tests/suite/tool_harness.rs @@ -4,12 +4,12 @@ use std::fs; use assert_matches::assert_matches; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::plan_tool::StepStatus; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::responses; diff --git a/codex-rs/core/tests/suite/tool_parallelism.rs b/codex-rs/core/tests/suite/tool_parallelism.rs index 8db03c3d10..357dcff0fd 100644 --- a/codex-rs/core/tests/suite/tool_parallelism.rs +++ b/codex-rs/core/tests/suite/tool_parallelism.rs @@ -5,11 +5,11 @@ use std::fs; use std::time::Duration; use std::time::Instant; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index 5e62cd698f..9f1803c75e 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -8,9 +8,9 @@ use std::time::Instant; use anyhow::Context; use anyhow::Result; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::SandboxPolicy; use codex_core::sandboxing::SandboxPermissions; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; use core_test_support::assert_regex_match; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/truncation.rs b/codex-rs/core/tests/suite/truncation.rs index 9475a9c510..8ede6c621f 100644 --- a/codex-rs/core/tests/suite/truncation.rs +++ b/codex-rs/core/tests/suite/truncation.rs @@ -5,11 +5,11 @@ use anyhow::Context; use anyhow::Result; use codex_core::config::types::McpServerConfig; use codex_core::config::types::McpServerTransportConfig; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::responses; diff --git a/codex-rs/core/tests/suite/undo.rs b/codex-rs/core/tests/suite/undo.rs index 61bc3b4fdf..e129a815bf 100644 --- a/codex-rs/core/tests/suite/undo.rs +++ b/codex-rs/core/tests/suite/undo.rs @@ -10,9 +10,9 @@ use anyhow::Result; use anyhow::bail; use codex_core::CodexThread; use codex_core::features::Feature; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::UndoCompletedEvent; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::UndoCompletedEvent; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 34c5bd9617..705e415620 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -6,12 +6,12 @@ use std::sync::OnceLock; use anyhow::Context; use anyhow::Result; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecCommandSource; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::process::process_is_alive; diff --git a/codex-rs/core/tests/suite/unstable_features_warning.rs b/codex-rs/core/tests/suite/unstable_features_warning.rs index e5fdf61fdb..a215ecbc06 100644 --- a/codex-rs/core/tests/suite/unstable_features_warning.rs +++ b/codex-rs/core/tests/suite/unstable_features_warning.rs @@ -4,9 +4,9 @@ use codex_config::CONFIG_TOML_FILE; use codex_core::CodexAuth; use codex_core::NewThread; use codex_core::features::Feature; -use codex_core::protocol::EventMsg; -use codex_core::protocol::InitialHistory; -use codex_core::protocol::WarningEvent; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::InitialHistory; +use codex_protocol::protocol::WarningEvent; use codex_utils_absolute_path::AbsolutePathBuf; use core::time::Duration; use core_test_support::load_default_config_for_test; diff --git a/codex-rs/core/tests/suite/user_notification.rs b/codex-rs/core/tests/suite/user_notification.rs index 69f30bb5ad..5ef939776b 100644 --- a/codex-rs/core/tests/suite/user_notification.rs +++ b/codex-rs/core/tests/suite/user_notification.rs @@ -2,8 +2,8 @@ use std::os::unix::fs::PermissionsExt; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::fs_wait; use core_test_support::responses; diff --git a/codex-rs/core/tests/suite/user_shell_cmd.rs b/codex-rs/core/tests/suite/user_shell_cmd.rs index a021509eea..c38b86e443 100644 --- a/codex-rs/core/tests/suite/user_shell_cmd.rs +++ b/codex-rs/core/tests/suite/user_shell_cmd.rs @@ -1,14 +1,14 @@ use anyhow::Context; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::ExecCommandSource; -use codex_core::protocol::ExecOutputStream; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::TurnAbortReason; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::ExecOutputStream; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::TurnAbortReason; use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::responses; diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index bad9efa2d0..96315e5c75 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -4,10 +4,6 @@ use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_core::CodexAuth; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; @@ -17,6 +13,10 @@ use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationPolicyConfig; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ev_assistant_message; diff --git a/codex-rs/core/tests/suite/web_search.rs b/codex-rs/core/tests/suite/web_search.rs index 8909e01cf4..e7082a832c 100644 --- a/codex-rs/core/tests/suite/web_search.rs +++ b/codex-rs/core/tests/suite/web_search.rs @@ -1,8 +1,8 @@ #![allow(clippy::unwrap_used)] use codex_core::features::Feature; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::WebSearchMode; +use codex_protocol::protocol::SandboxPolicy; use core_test_support::responses; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; diff --git a/codex-rs/core/tests/suite/websocket_fallback.rs b/codex-rs/core/tests/suite/websocket_fallback.rs index ceb7fc6057..b5c27ae923 100644 --- a/codex-rs/core/tests/suite/websocket_fallback.rs +++ b/codex-rs/core/tests/suite/websocket_fallback.rs @@ -1,10 +1,10 @@ use anyhow::Result; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ev_completed; diff --git a/codex-rs/exec-server/Cargo.toml b/codex-rs/exec-server/Cargo.toml index 9346db63c1..4d9d79270d 100644 --- a/codex-rs/exec-server/Cargo.toml +++ b/codex-rs/exec-server/Cargo.toml @@ -25,6 +25,8 @@ async-trait = { workspace = true } clap = { workspace = true, features = ["derive"] } codex-core = { workspace = true } codex-execpolicy = { workspace = true } +codex-protocol = { workspace = true } +codex-shell-command = { workspace = true } libc = { workspace = true } path-absolutize = { workspace = true } rmcp = { workspace = true, default-features = false, features = [ @@ -57,6 +59,7 @@ tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"] } [dev-dependencies] codex-utils-cargo-bin = { workspace = true } +codex-protocol = { workspace = true } exec_server_test_support = { workspace = true } maplit = { workspace = true } pretty_assertions = { workspace = true } diff --git a/codex-rs/exec-server/src/posix.rs b/codex-rs/exec-server/src/posix.rs index 7f9ce569c6..907ec14b68 100644 --- a/codex-rs/exec-server/src/posix.rs +++ b/codex-rs/exec-server/src/posix.rs @@ -62,11 +62,11 @@ use std::sync::Arc; use anyhow::Context as _; use clap::Parser; use codex_core::config::find_codex_home; -use codex_core::is_dangerous_command::command_might_be_dangerous; use codex_core::sandboxing::SandboxPermissions; use codex_execpolicy::Decision; use codex_execpolicy::Policy; use codex_execpolicy::RuleMatch; +use codex_shell_command::is_dangerous_command::command_might_be_dangerous; use rmcp::ErrorData as McpError; use tokio::sync::RwLock; use tracing_subscriber::EnvFilter; diff --git a/codex-rs/exec-server/src/posix/escalate_server.rs b/codex-rs/exec-server/src/posix/escalate_server.rs index f66e92dc8b..de4bdfc2cd 100644 --- a/codex-rs/exec-server/src/posix/escalate_server.rs +++ b/codex-rs/exec-server/src/posix/escalate_server.rs @@ -10,8 +10,8 @@ use path_absolutize::Absolutize as _; use codex_core::SandboxState; use codex_core::exec::process_exec_tool_call; -use codex_core::protocol_config_types::WindowsSandboxLevel; use codex_core::sandboxing::SandboxPermissions; +use codex_protocol::config_types::WindowsSandboxLevel; use tokio::process::Command; use tokio_util::sync::CancellationToken; diff --git a/codex-rs/exec-server/src/posix/mcp.rs b/codex-rs/exec-server/src/posix/mcp.rs index 7e8d0ccdff..5319a1f916 100644 --- a/codex-rs/exec-server/src/posix/mcp.rs +++ b/codex-rs/exec-server/src/posix/mcp.rs @@ -7,8 +7,8 @@ use anyhow::Result; use codex_core::MCP_SANDBOX_STATE_CAPABILITY; use codex_core::MCP_SANDBOX_STATE_METHOD; use codex_core::SandboxState; -use codex_core::protocol::SandboxPolicy; use codex_execpolicy::Policy; +use codex_protocol::protocol::SandboxPolicy; use rmcp::ErrorData as McpError; use rmcp::RoleServer; use rmcp::ServerHandler; diff --git a/codex-rs/exec-server/tests/common/Cargo.toml b/codex-rs/exec-server/tests/common/Cargo.toml index 6444b61f97..ca1a713c27 100644 --- a/codex-rs/exec-server/tests/common/Cargo.toml +++ b/codex-rs/exec-server/tests/common/Cargo.toml @@ -10,6 +10,7 @@ path = "lib.rs" [dependencies] anyhow = { workspace = true } codex-core = { workspace = true } +codex-protocol = { workspace = true } codex-utils-cargo-bin = { workspace = true } rmcp = { workspace = true } serde_json = { workspace = true } diff --git a/codex-rs/exec-server/tests/common/lib.rs b/codex-rs/exec-server/tests/common/lib.rs index 57fce3a150..bd602d09c8 100644 --- a/codex-rs/exec-server/tests/common/lib.rs +++ b/codex-rs/exec-server/tests/common/lib.rs @@ -1,6 +1,6 @@ use codex_core::MCP_SANDBOX_STATE_METHOD; use codex_core::SandboxState; -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::SandboxPolicy; use codex_utils_cargo_bin::find_resource; use rmcp::ClientHandler; use rmcp::ErrorData as McpError; diff --git a/codex-rs/exec/src/event_processor.rs b/codex-rs/exec/src/event_processor.rs index 2a0b1eb833..fc9d123e0d 100644 --- a/codex-rs/exec/src/event_processor.rs +++ b/codex-rs/exec/src/event_processor.rs @@ -1,8 +1,8 @@ use std::path::Path; use codex_core::config::Config; -use codex_core::protocol::Event; -use codex_core::protocol::SessionConfiguredEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::SessionConfiguredEvent; pub(crate) enum CodexStatus { Running, diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 1e2a1b9e6d..13599294d5 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -1,39 +1,39 @@ use codex_core::config::Config; -use codex_core::protocol::AgentMessageEvent; -use codex_core::protocol::AgentReasoningRawContentEvent; -use codex_core::protocol::AgentStatus; -use codex_core::protocol::BackgroundEventEvent; -use codex_core::protocol::CollabAgentInteractionBeginEvent; -use codex_core::protocol::CollabAgentInteractionEndEvent; -use codex_core::protocol::CollabAgentSpawnBeginEvent; -use codex_core::protocol::CollabAgentSpawnEndEvent; -use codex_core::protocol::CollabCloseBeginEvent; -use codex_core::protocol::CollabCloseEndEvent; -use codex_core::protocol::CollabWaitingBeginEvent; -use codex_core::protocol::CollabWaitingEndEvent; -use codex_core::protocol::DeprecationNoticeEvent; -use codex_core::protocol::ErrorEvent; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecCommandBeginEvent; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::FileChange; -use codex_core::protocol::ItemCompletedEvent; -use codex_core::protocol::McpInvocation; -use codex_core::protocol::McpToolCallBeginEvent; -use codex_core::protocol::McpToolCallEndEvent; -use codex_core::protocol::PatchApplyBeginEvent; -use codex_core::protocol::PatchApplyEndEvent; -use codex_core::protocol::SessionConfiguredEvent; -use codex_core::protocol::StreamErrorEvent; -use codex_core::protocol::TurnAbortReason; -use codex_core::protocol::TurnCompleteEvent; -use codex_core::protocol::TurnDiffEvent; -use codex_core::protocol::WarningEvent; -use codex_core::protocol::WebSearchEndEvent; use codex_core::web_search::web_search_detail; use codex_protocol::items::TurnItem; use codex_protocol::num_format::format_with_separators; +use codex_protocol::protocol::AgentMessageEvent; +use codex_protocol::protocol::AgentReasoningRawContentEvent; +use codex_protocol::protocol::AgentStatus; +use codex_protocol::protocol::BackgroundEventEvent; +use codex_protocol::protocol::CollabAgentInteractionBeginEvent; +use codex_protocol::protocol::CollabAgentInteractionEndEvent; +use codex_protocol::protocol::CollabAgentSpawnBeginEvent; +use codex_protocol::protocol::CollabAgentSpawnEndEvent; +use codex_protocol::protocol::CollabCloseBeginEvent; +use codex_protocol::protocol::CollabCloseEndEvent; +use codex_protocol::protocol::CollabWaitingBeginEvent; +use codex_protocol::protocol::CollabWaitingEndEvent; +use codex_protocol::protocol::DeprecationNoticeEvent; +use codex_protocol::protocol::ErrorEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::FileChange; +use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::McpInvocation; +use codex_protocol::protocol::McpToolCallBeginEvent; +use codex_protocol::protocol::McpToolCallEndEvent; +use codex_protocol::protocol::PatchApplyBeginEvent; +use codex_protocol::protocol::PatchApplyEndEvent; +use codex_protocol::protocol::SessionConfiguredEvent; +use codex_protocol::protocol::StreamErrorEvent; +use codex_protocol::protocol::TurnAbortReason; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnDiffEvent; +use codex_protocol::protocol::WarningEvent; +use codex_protocol::protocol::WebSearchEndEvent; use codex_utils_elapsed::format_duration; use codex_utils_elapsed::format_elapsed; use owo_colors::OwoColorize; @@ -73,7 +73,7 @@ pub(crate) struct EventProcessorWithHumanOutput { show_agent_reasoning: bool, show_raw_agent_reasoning: bool, last_message_path: Option, - last_total_token_usage: Option, + last_total_token_usage: Option, final_message: Option, last_proposed_plan: Option, } @@ -201,10 +201,12 @@ impl EventProcessor for EventProcessorWithHumanOutput { } EventMsg::McpStartupUpdate(update) => { let status_text = match update.status { - codex_core::protocol::McpStartupStatus::Starting => "starting".to_string(), - codex_core::protocol::McpStartupStatus::Ready => "ready".to_string(), - codex_core::protocol::McpStartupStatus::Cancelled => "cancelled".to_string(), - codex_core::protocol::McpStartupStatus::Failed { ref error } => { + codex_protocol::protocol::McpStartupStatus::Starting => "starting".to_string(), + codex_protocol::protocol::McpStartupStatus::Ready => "ready".to_string(), + codex_protocol::protocol::McpStartupStatus::Cancelled => { + "cancelled".to_string() + } + codex_protocol::protocol::McpStartupStatus::Failed { ref error } => { format!("failed: {error}") } }; diff --git a/codex-rs/exec/src/event_processor_with_jsonl_output.rs b/codex-rs/exec/src/event_processor_with_jsonl_output.rs index 6cefcbd940..8bec82b15d 100644 --- a/codex-rs/exec/src/event_processor_with_jsonl_output.rs +++ b/codex-rs/exec/src/event_processor_with_jsonl_output.rs @@ -39,19 +39,19 @@ use crate::exec_events::TurnStartedEvent; use crate::exec_events::Usage; use crate::exec_events::WebSearchItem; use codex_core::config::Config; -use codex_core::protocol; -use codex_core::protocol::AgentStatus as CoreAgentStatus; -use codex_core::protocol::CollabAgentInteractionBeginEvent; -use codex_core::protocol::CollabAgentInteractionEndEvent; -use codex_core::protocol::CollabAgentSpawnBeginEvent; -use codex_core::protocol::CollabAgentSpawnEndEvent; -use codex_core::protocol::CollabCloseBeginEvent; -use codex_core::protocol::CollabCloseEndEvent; -use codex_core::protocol::CollabWaitingBeginEvent; -use codex_core::protocol::CollabWaitingEndEvent; use codex_protocol::models::WebSearchAction; use codex_protocol::plan_tool::StepStatus; use codex_protocol::plan_tool::UpdatePlanArgs; +use codex_protocol::protocol; +use codex_protocol::protocol::AgentStatus as CoreAgentStatus; +use codex_protocol::protocol::CollabAgentInteractionBeginEvent; +use codex_protocol::protocol::CollabAgentInteractionEndEvent; +use codex_protocol::protocol::CollabAgentSpawnBeginEvent; +use codex_protocol::protocol::CollabAgentSpawnEndEvent; +use codex_protocol::protocol::CollabCloseBeginEvent; +use codex_protocol::protocol::CollabCloseEndEvent; +use codex_protocol::protocol::CollabWaitingBeginEvent; +use codex_protocol::protocol::CollabWaitingEndEvent; use serde_json::Value as JsonValue; use tracing::error; use tracing::warn; @@ -65,7 +65,7 @@ pub struct EventProcessorWithJsonOutput { running_patch_applies: HashMap, // Tracks the todo list for the current turn (at most one per turn). running_todo_list: Option, - last_total_token_usage: Option, + last_total_token_usage: Option, running_mcp_tool_calls: HashMap, running_collab_tool_calls: HashMap, running_web_search_calls: HashMap, diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 70ddb70f13..89180d89e6 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -32,15 +32,15 @@ use codex_core::config_loader::format_config_error_with_source; use codex_core::format_exec_policy_error_with_source; use codex_core::git_info::get_git_repo_root; use codex_core::models_manager::manager::RefreshStrategy; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewRequest; -use codex_core::protocol::ReviewTarget; -use codex_core::protocol::SessionSource; use codex_protocol::approvals::ElicitationAction; use codex_protocol::config_types::SandboxMode; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewRequest; +use codex_protocol::protocol::ReviewTarget; +use codex_protocol::protocol::SessionSource; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_oss::ensure_oss_provider_ready; @@ -570,7 +570,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any } if let EventMsg::McpStartupUpdate(update) = &event.msg && required_mcp_servers.contains(&update.server) - && let codex_core::protocol::McpStartupStatus::Failed { error } = &update.status + && let codex_protocol::protocol::McpStartupStatus::Failed { error } = &update.status { error_seen = true; eprintln!( diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index c04fcdb532..6595e82eab 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -1,29 +1,3 @@ -use codex_core::protocol::AgentMessageEvent; -use codex_core::protocol::AgentReasoningEvent; -use codex_core::protocol::AgentStatus; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::CollabAgentSpawnBeginEvent; -use codex_core::protocol::CollabAgentSpawnEndEvent; -use codex_core::protocol::CollabWaitingEndEvent; -use codex_core::protocol::ErrorEvent; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecCommandBeginEvent; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::ExecCommandSource; -use codex_core::protocol::ExecCommandStatus as CoreExecCommandStatus; -use codex_core::protocol::FileChange; -use codex_core::protocol::McpInvocation; -use codex_core::protocol::McpToolCallBeginEvent; -use codex_core::protocol::McpToolCallEndEvent; -use codex_core::protocol::PatchApplyBeginEvent; -use codex_core::protocol::PatchApplyEndEvent; -use codex_core::protocol::PatchApplyStatus as CorePatchApplyStatus; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::SessionConfiguredEvent; -use codex_core::protocol::WarningEvent; -use codex_core::protocol::WebSearchBeginEvent; -use codex_core::protocol::WebSearchEndEvent; use codex_exec::event_processor_with_jsonl_output::EventProcessorWithJsonOutput; use codex_exec::exec_events::AgentMessageItem; use codex_exec::exec_events::CollabAgentState; @@ -63,9 +37,35 @@ use codex_protocol::models::WebSearchAction; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; use codex_protocol::plan_tool::UpdatePlanArgs; +use codex_protocol::protocol::AgentMessageEvent; +use codex_protocol::protocol::AgentReasoningEvent; +use codex_protocol::protocol::AgentStatus; +use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::CollabAgentSpawnBeginEvent; +use codex_protocol::protocol::CollabAgentSpawnEndEvent; +use codex_protocol::protocol::CollabWaitingEndEvent; +use codex_protocol::protocol::ErrorEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; use codex_protocol::protocol::ExecCommandOutputDeltaEvent; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus; use codex_protocol::protocol::ExecOutputStream; +use codex_protocol::protocol::FileChange; +use codex_protocol::protocol::McpInvocation; +use codex_protocol::protocol::McpToolCallBeginEvent; +use codex_protocol::protocol::McpToolCallEndEvent; +use codex_protocol::protocol::PatchApplyBeginEvent; +use codex_protocol::protocol::PatchApplyEndEvent; +use codex_protocol::protocol::PatchApplyStatus as CorePatchApplyStatus; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::SessionConfiguredEvent; +use codex_protocol::protocol::WarningEvent; +use codex_protocol::protocol::WebSearchBeginEvent; +use codex_protocol::protocol::WebSearchEndEvent; use pretty_assertions::assert_eq; use rmcp::model::Content; use serde_json::json; @@ -118,7 +118,7 @@ fn task_started_produces_turn_started_event() { let mut ep = EventProcessorWithJsonOutput::new(None); let out = ep.collect_thread_events(&event( "t1", - EventMsg::TurnStarted(codex_core::protocol::TurnStartedEvent { + EventMsg::TurnStarted(codex_protocol::protocol::TurnStartedEvent { turn_id: "turn-1".to_string(), model_context_window: Some(32_000), collaboration_mode_kind: ModeKind::Default, @@ -312,7 +312,7 @@ fn plan_update_emits_todo_list_started_updated_and_completed() { // Task completes => item.completed (same id, latest state) let complete = event( "p3", - EventMsg::TurnComplete(codex_core::protocol::TurnCompleteEvent { + EventMsg::TurnComplete(codex_protocol::protocol::TurnCompleteEvent { turn_id: "turn-1".to_string(), last_agent_message: None, }), @@ -683,7 +683,7 @@ fn plan_update_after_complete_starts_new_todo_list_with_new_id() { let _ = ep.collect_thread_events(&start); let complete = event( "t2", - EventMsg::TurnComplete(codex_core::protocol::TurnCompleteEvent { + EventMsg::TurnComplete(codex_protocol::protocol::TurnCompleteEvent { turn_id: "turn-1".to_string(), last_agent_message: None, }), @@ -763,7 +763,7 @@ fn error_event_produces_error() { let mut ep = EventProcessorWithJsonOutput::new(None); let out = ep.collect_thread_events(&event( "e1", - EventMsg::Error(codex_core::protocol::ErrorEvent { + EventMsg::Error(codex_protocol::protocol::ErrorEvent { message: "boom".to_string(), codex_error_info: Some(CodexErrorInfo::Other), }), @@ -803,7 +803,7 @@ fn stream_error_event_produces_error() { let mut ep = EventProcessorWithJsonOutput::new(None); let out = ep.collect_thread_events(&event( "e1", - EventMsg::StreamError(codex_core::protocol::StreamErrorEvent { + EventMsg::StreamError(codex_protocol::protocol::StreamErrorEvent { message: "retrying".to_string(), codex_error_info: Some(CodexErrorInfo::Other), additional_details: None, @@ -837,7 +837,7 @@ fn error_followed_by_task_complete_produces_turn_failed() { let complete_event = event( "e2", - EventMsg::TurnComplete(codex_core::protocol::TurnCompleteEvent { + EventMsg::TurnComplete(codex_protocol::protocol::TurnCompleteEvent { turn_id: "turn-1".to_string(), last_agent_message: None, }), @@ -1267,21 +1267,21 @@ fn task_complete_produces_turn_completed_with_usage() { let mut ep = EventProcessorWithJsonOutput::new(None); // First, feed a TokenCount event with known totals. - let usage = codex_core::protocol::TokenUsage { + let usage = codex_protocol::protocol::TokenUsage { input_tokens: 1200, cached_input_tokens: 200, output_tokens: 345, reasoning_output_tokens: 0, total_tokens: 0, }; - let info = codex_core::protocol::TokenUsageInfo { + let info = codex_protocol::protocol::TokenUsageInfo { total_token_usage: usage.clone(), last_token_usage: usage, model_context_window: None, }; let token_count_event = event( "e1", - EventMsg::TokenCount(codex_core::protocol::TokenCountEvent { + EventMsg::TokenCount(codex_protocol::protocol::TokenCountEvent { info: Some(info), rate_limits: None, }), @@ -1291,7 +1291,7 @@ fn task_complete_produces_turn_completed_with_usage() { // Then TurnComplete should produce turn.completed with the captured usage. let complete_event = event( "e2", - EventMsg::TurnComplete(codex_core::protocol::TurnCompleteEvent { + EventMsg::TurnComplete(codex_protocol::protocol::TurnCompleteEvent { turn_id: "turn-1".to_string(), last_agent_message: Some("done".to_string()), }), diff --git a/codex-rs/exec/tests/suite/sandbox.rs b/codex-rs/exec/tests/suite/sandbox.rs index ce2e79eac2..e6dd37927b 100644 --- a/codex-rs/exec/tests/suite/sandbox.rs +++ b/codex-rs/exec/tests/suite/sandbox.rs @@ -1,6 +1,6 @@ #![cfg(unix)] -use codex_core::protocol::SandboxPolicy; use codex_core::spawn::StdioPolicy; +use codex_protocol::protocol::SandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::future::Future; diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index ff16a569fe..63af5c81fa 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -18,6 +18,7 @@ workspace = true [target.'cfg(target_os = "linux")'.dependencies] clap = { workspace = true, features = ["derive"] } codex-core = { workspace = true } +codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } landlock = { workspace = true } libc = { workspace = true } diff --git a/codex-rs/linux-sandbox/src/bwrap.rs b/codex-rs/linux-sandbox/src/bwrap.rs index 71704e7299..854774b781 100644 --- a/codex-rs/linux-sandbox/src/bwrap.rs +++ b/codex-rs/linux-sandbox/src/bwrap.rs @@ -15,8 +15,8 @@ use std::path::PathBuf; use codex_core::error::CodexErr; use codex_core::error::Result; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::WritableRoot; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::WritableRoot; /// Options that control how bubblewrap is invoked. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -322,7 +322,7 @@ fn find_first_non_existent_component(target_path: &Path) -> Option { #[cfg(test)] mod tests { use super::*; - use codex_core::protocol::SandboxPolicy; + use codex_protocol::protocol::SandboxPolicy; use pretty_assertions::assert_eq; #[test] diff --git a/codex-rs/linux-sandbox/src/landlock.rs b/codex-rs/linux-sandbox/src/landlock.rs index 8d568dba0a..621bfd5b60 100644 --- a/codex-rs/linux-sandbox/src/landlock.rs +++ b/codex-rs/linux-sandbox/src/landlock.rs @@ -8,7 +8,7 @@ use std::path::Path; use codex_core::error::CodexErr; use codex_core::error::Result; use codex_core::error::SandboxErr; -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::SandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use landlock::ABI; @@ -204,7 +204,7 @@ fn install_network_seccomp_filter_on_current_thread() -> std::result::Result<(), #[cfg(test)] mod tests { use super::should_install_network_seccomp; - use codex_core::protocol::SandboxPolicy; + use codex_protocol::protocol::SandboxPolicy; use pretty_assertions::assert_eq; #[test] diff --git a/codex-rs/linux-sandbox/src/linux_run_main.rs b/codex-rs/linux-sandbox/src/linux_run_main.rs index c2a6a4d312..84e7cb34fc 100644 --- a/codex-rs/linux-sandbox/src/linux_run_main.rs +++ b/codex-rs/linux-sandbox/src/linux_run_main.rs @@ -25,7 +25,7 @@ pub struct LandlockCommand { pub sandbox_policy_cwd: PathBuf, #[arg(long = "sandbox-policy")] - pub sandbox_policy: codex_core::protocol::SandboxPolicy, + pub sandbox_policy: codex_protocol::protocol::SandboxPolicy, /// Opt-in: use the bubblewrap-based Linux sandbox pipeline. /// @@ -142,7 +142,7 @@ pub fn run_main() -> ! { fn run_bwrap_with_proc_fallback( sandbox_policy_cwd: &Path, - sandbox_policy: &codex_core::protocol::SandboxPolicy, + sandbox_policy: &codex_protocol::protocol::SandboxPolicy, inner: Vec, mount_proc: bool, allow_network_for_proxy: bool, @@ -164,7 +164,7 @@ fn run_bwrap_with_proc_fallback( } fn bwrap_network_mode( - sandbox_policy: &codex_core::protocol::SandboxPolicy, + sandbox_policy: &codex_protocol::protocol::SandboxPolicy, allow_network_for_proxy: bool, ) -> BwrapNetworkMode { if allow_network_for_proxy { @@ -178,7 +178,7 @@ fn bwrap_network_mode( fn build_bwrap_argv( inner: Vec, - sandbox_policy: &codex_core::protocol::SandboxPolicy, + sandbox_policy: &codex_protocol::protocol::SandboxPolicy, sandbox_policy_cwd: &Path, options: BwrapOptions, ) -> Vec { @@ -201,7 +201,7 @@ fn build_bwrap_argv( fn preflight_proc_mount_support( sandbox_policy_cwd: &Path, - sandbox_policy: &codex_core::protocol::SandboxPolicy, + sandbox_policy: &codex_protocol::protocol::SandboxPolicy, ) -> bool { let preflight_command = vec![resolve_true_command()]; let preflight_argv = build_bwrap_argv( @@ -315,7 +315,7 @@ fn is_proc_mount_failure(stderr: &str) -> bool { /// Build the inner command that applies seccomp after bubblewrap. fn build_inner_seccomp_command( sandbox_policy_cwd: &Path, - sandbox_policy: &codex_core::protocol::SandboxPolicy, + sandbox_policy: &codex_protocol::protocol::SandboxPolicy, use_bwrap_sandbox: bool, allow_network_for_proxy: bool, command: Vec, @@ -374,7 +374,7 @@ fn exec_or_panic(command: Vec) -> ! { #[cfg(test)] mod tests { use super::*; - use codex_core::protocol::SandboxPolicy; + use codex_protocol::protocol::SandboxPolicy; use pretty_assertions::assert_eq; #[test] diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index 9a1b82413e..362fcaf35f 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -7,9 +7,9 @@ use codex_core::error::SandboxErr; use codex_core::exec::ExecParams; use codex_core::exec::process_exec_tool_call; use codex_core::exec_env::create_env; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol_config_types::WindowsSandboxLevel; use codex_core::sandboxing::SandboxPermissions; +use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::protocol::SandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use std::collections::HashMap; diff --git a/codex-rs/mcp-server/Cargo.toml b/codex-rs/mcp-server/Cargo.toml index e3f0db82eb..2ecce383ce 100644 --- a/codex-rs/mcp-server/Cargo.toml +++ b/codex-rs/mcp-server/Cargo.toml @@ -20,6 +20,7 @@ anyhow = { workspace = true } codex-arg0 = { workspace = true } codex-core = { workspace = true } codex-protocol = { workspace = true } +codex-shell-command = { workspace = true } codex-utils-cli = { workspace = true } codex-utils-json-to-toml = { workspace = true } rmcp = { workspace = true } diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index cf34dc280e..3125221d1a 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -2,9 +2,9 @@ use codex_core::config::Config; use codex_core::config::ConfigOverrides; -use codex_core::protocol::AskForApproval; use codex_protocol::ThreadId; use codex_protocol::config_types::SandboxMode; +use codex_protocol::protocol::AskForApproval; use codex_utils_json_to_toml::json_to_toml; use rmcp::model::JsonObject; use rmcp::model::Tool; diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index 762052ccf4..b720a1b258 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -13,15 +13,15 @@ use codex_core::CodexThread; use codex_core::NewThread; use codex_core::ThreadManager; use codex_core::config::Config as CodexConfig; -use codex_core::protocol::AgentMessageEvent; -use codex_core::protocol::ApplyPatchApprovalRequestEvent; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecApprovalRequestEvent; -use codex_core::protocol::Op; -use codex_core::protocol::Submission; -use codex_core::protocol::TurnCompleteEvent; use codex_protocol::ThreadId; +use codex_protocol::protocol::AgentMessageEvent; +use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecApprovalRequestEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::Submission; +use codex_protocol::protocol::TurnCompleteEvent; use codex_protocol::user_input::UserInput; use rmcp::model::CallToolResult; use rmcp::model::Content; diff --git a/codex-rs/mcp-server/src/exec_approval.rs b/codex-rs/mcp-server/src/exec_approval.rs index 54994f9fdb..3b5ef87cdb 100644 --- a/codex-rs/mcp-server/src/exec_approval.rs +++ b/codex-rs/mcp-server/src/exec_approval.rs @@ -2,10 +2,10 @@ use std::path::PathBuf; use std::sync::Arc; use codex_core::CodexThread; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewDecision; use codex_protocol::ThreadId; use codex_protocol::parse_command::ParsedCommand; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use rmcp::model::ErrorData; use rmcp::model::RequestId; use serde::Deserialize; diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 3b18f2fd43..95d48aa822 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -6,9 +6,9 @@ use codex_core::ThreadManager; use codex_core::config::Config; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; -use codex_core::protocol::Submission; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::Submission; use rmcp::model::CallToolRequestParams; use rmcp::model::CallToolResult; use rmcp::model::ClientNotification; @@ -572,7 +572,7 @@ impl MessageProcessor { if let Err(e) = codex_arc .submit_with_id(Submission { id: request_id_string, - op: codex_core::protocol::Op::Interrupt, + op: codex_protocol::protocol::Op::Interrupt, }) .await { diff --git a/codex-rs/mcp-server/src/outgoing_message.rs b/codex-rs/mcp-server/src/outgoing_message.rs index 3f83e1990e..7dcfa0c233 100644 --- a/codex-rs/mcp-server/src/outgoing_message.rs +++ b/codex-rs/mcp-server/src/outgoing_message.rs @@ -2,8 +2,8 @@ use std::collections::HashMap; use std::sync::atomic::AtomicI64; use std::sync::atomic::Ordering; -use codex_core::protocol::Event; use codex_protocol::ThreadId; +use codex_protocol::protocol::Event; use rmcp::model::CustomNotification; use rmcp::model::CustomRequest; use rmcp::model::ErrorData; @@ -200,7 +200,7 @@ pub(crate) struct OutgoingNotificationParams { pub event: serde_json::Value, } -// Additional mcp-specific data to be added to a [`codex_core::protocol::Event`] as notification.params._meta +// Additional mcp-specific data to be added to a [`codex_protocol::protocol::Event`] as notification.params._meta // MCP Spec: https://modelcontextprotocol.io/specification/2025-06-18/basic#meta // Typescript Schema: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/0695a497eb50a804fc0e88c18a93a21a675d6b3e/schema/2025-06-18/schema.ts #[derive(Debug, Clone, PartialEq, Serialize)] @@ -231,12 +231,12 @@ mod tests { use std::path::PathBuf; use anyhow::Result; - use codex_core::protocol::AskForApproval; - use codex_core::protocol::EventMsg; - use codex_core::protocol::SandboxPolicy; - use codex_core::protocol::SessionConfiguredEvent; use codex_protocol::ThreadId; use codex_protocol::openai_models::ReasoningEffort; + use codex_protocol::protocol::AskForApproval; + use codex_protocol::protocol::EventMsg; + use codex_protocol::protocol::SandboxPolicy; + use codex_protocol::protocol::SessionConfiguredEvent; use pretty_assertions::assert_eq; use serde_json::json; use tempfile::NamedTempFile; diff --git a/codex-rs/mcp-server/src/patch_approval.rs b/codex-rs/mcp-server/src/patch_approval.rs index 60eba66433..e392694d3a 100644 --- a/codex-rs/mcp-server/src/patch_approval.rs +++ b/codex-rs/mcp-server/src/patch_approval.rs @@ -3,10 +3,10 @@ use std::path::PathBuf; use std::sync::Arc; use codex_core::CodexThread; -use codex_core::protocol::FileChange; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewDecision; use codex_protocol::ThreadId; +use codex_protocol::protocol::FileChange; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use rmcp::model::ErrorData; use rmcp::model::RequestId; use serde::Deserialize; diff --git a/codex-rs/mcp-server/tests/suite/codex_tool.rs b/codex-rs/mcp-server/tests/suite/codex_tool.rs index de8a9306d4..041fcc0217 100644 --- a/codex-rs/mcp-server/tests/suite/codex_tool.rs +++ b/codex-rs/mcp-server/tests/suite/codex_tool.rs @@ -3,15 +3,15 @@ use std::env; use std::path::Path; use std::path::PathBuf; -use codex_core::parse_command; -use codex_core::protocol::FileChange; -use codex_core::protocol::ReviewDecision; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_mcp_server::CodexToolCallParam; use codex_mcp_server::ExecApprovalElicitRequestParams; use codex_mcp_server::ExecApprovalResponse; use codex_mcp_server::PatchApprovalElicitRequestParams; use codex_mcp_server::PatchApprovalResponse; +use codex_protocol::protocol::FileChange; +use codex_protocol::protocol::ReviewDecision; +use codex_shell_command::parse_command; use pretty_assertions::assert_eq; use rmcp::model::JsonRpcResponse; use rmcp::model::JsonRpcVersion2_0; diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index f791a3fc98..683b0828dc 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -38,6 +38,7 @@ codex-file-search = { workspace = true } codex-login = { workspace = true } codex-otel = { workspace = true } codex-protocol = { workspace = true } +codex-shell-command = { workspace = true } codex-state = { workspace = true } codex-utils-approval-presets = { workspace = true } codex-utils-absolute-path = { workspace = true } diff --git a/codex-rs/tui/src/additional_dirs.rs b/codex-rs/tui/src/additional_dirs.rs index 98724aa161..f7d2ef5508 100644 --- a/codex-rs/tui/src/additional_dirs.rs +++ b/codex-rs/tui/src/additional_dirs.rs @@ -1,4 +1,4 @@ -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::SandboxPolicy; use std::path::PathBuf; /// Returns a warning describing why `--add-dir` entries will be ignored for the @@ -34,8 +34,8 @@ fn format_warning(additional_dirs: &[PathBuf]) -> String { #[cfg(test)] mod tests { use super::add_dir_warning_message; - use codex_core::protocol::NetworkAccess; - use codex_core::protocol::SandboxPolicy; + use codex_protocol::protocol::NetworkAccess; + use codex_protocol::protocol::SandboxPolicy; use pretty_assertions::assert_eq; use std::path::PathBuf; diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 0090ef5e9b..ebbf757523 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -45,16 +45,6 @@ use codex_core::features::Feature; use codex_core::models_manager::manager::RefreshStrategy; use codex_core::models_manager::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG; use codex_core::models_manager::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::FinalOutput; -use codex_core::protocol::ListSkillsResponseEvent; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::SessionSource; -use codex_core::protocol::SkillErrorInfo; -use codex_core::protocol::TokenUsage; #[cfg(target_os = "windows")] use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_otel::OtelManager; @@ -67,7 +57,17 @@ use codex_protocol::items::TurnItem; use codex_protocol::openai_models::ModelPreset; use codex_protocol::openai_models::ModelUpgrade; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::FinalOutput; +use codex_protocol::protocol::ListSkillsResponseEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionConfiguredEvent; +use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::SkillErrorInfo; +use codex_protocol::protocol::TokenUsage; use codex_utils_absolute_path::AbsolutePathBuf; use color_eyre::eyre::Result; use color_eyre::eyre::WrapErr; @@ -1248,8 +1248,8 @@ impl App { != WindowsSandboxLevel::Disabled && matches!( app.config.permissions.sandbox_policy.get(), - codex_core::protocol::SandboxPolicy::WorkspaceWrite { .. } - | codex_core::protocol::SandboxPolicy::ReadOnly { .. } + codex_protocol::protocol::SandboxPolicy::WorkspaceWrite { .. } + | codex_protocol::protocol::SandboxPolicy::ReadOnly { .. } ) && !app .config @@ -2200,8 +2200,8 @@ impl App { #[cfg(target_os = "windows")] let policy_is_workspace_write_or_ro = matches!( &policy, - codex_core::protocol::SandboxPolicy::WorkspaceWrite { .. } - | codex_core::protocol::SandboxPolicy::ReadOnly { .. } + codex_protocol::protocol::SandboxPolicy::WorkspaceWrite { .. } + | codex_protocol::protocol::SandboxPolicy::ReadOnly { .. } ); let policy_for_chat = policy.clone(); @@ -2767,7 +2767,7 @@ impl App { (!model.starts_with("codex-auto-")).then(|| Self::reasoning_label(reasoning_effort)) } - pub(crate) fn token_usage(&self) -> codex_core::protocol::TokenUsage { + pub(crate) fn token_usage(&self) -> codex_protocol::protocol::TokenUsage { self.chat_widget.token_usage() } @@ -2939,7 +2939,7 @@ impl App { cwd: PathBuf, env_map: std::collections::HashMap, logs_base_dir: PathBuf, - sandbox_policy: codex_core::protocol::SandboxPolicy, + sandbox_policy: codex_protocol::protocol::SandboxPolicy, tx: AppEventSender, ) { tokio::task::spawn_blocking(move || { @@ -3000,16 +3000,16 @@ mod tests { use codex_core::CodexAuth; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; - use codex_core::protocol::AskForApproval; - use codex_core::protocol::Event; - use codex_core::protocol::EventMsg; - use codex_core::protocol::SandboxPolicy; - use codex_core::protocol::SessionConfiguredEvent; - use codex_core::protocol::SessionSource; - use codex_core::protocol::ThreadRolledBackEvent; - use codex_core::protocol::UserMessageEvent; use codex_otel::OtelManager; use codex_protocol::ThreadId; + use codex_protocol::protocol::AskForApproval; + use codex_protocol::protocol::Event; + use codex_protocol::protocol::EventMsg; + use codex_protocol::protocol::SandboxPolicy; + use codex_protocol::protocol::SessionConfiguredEvent; + use codex_protocol::protocol::SessionSource; + use codex_protocol::protocol::ThreadRolledBackEvent; + use codex_protocol::protocol::UserMessageEvent; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; use crossterm::event::KeyModifiers; diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index b9b5be2b5f..1bb2c29569 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -34,11 +34,11 @@ use crate::history_cell::UserHistoryCell; use crate::pager_overlay::Overlay; use crate::tui; use crate::tui::TuiEvent; -use codex_core::protocol::CodexErrorInfo; -use codex_core::protocol::ErrorEvent; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; use codex_protocol::ThreadId; +use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::ErrorEvent; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::user_input::TextElement; use color_eyre::eyre::Result; use crossterm::event::KeyCode; diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 17ce9f14b4..159cda88f4 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -11,11 +11,11 @@ use std::path::PathBuf; use codex_chatgpt::connectors::AppInfo; -use codex_core::protocol::Event; -use codex_core::protocol::RateLimitSnapshot; use codex_file_search::FileMatch; use codex_protocol::ThreadId; use codex_protocol::openai_models::ModelPreset; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::RateLimitSnapshot; use codex_utils_approval_presets::ApprovalPreset; use crate::bottom_pane::ApprovalRequest; @@ -23,11 +23,11 @@ use crate::bottom_pane::StatusLineItem; use crate::history_cell::HistoryCell; use codex_core::features::Feature; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::config_types::Personality; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(not(target_os = "windows"), allow(dead_code))] @@ -73,7 +73,7 @@ pub(crate) enum AppEvent { /// Forward an `Op` to the Agent. Using an `AppEvent` for this avoids /// bubbling channels through layers of widgets. - CodexOp(codex_core::protocol::Op), + CodexOp(codex_protocol::protocol::Op), /// Kick off an asynchronous file search for the given query (text after /// the `@`). Previous searches may be cancelled by the app layer so there diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 169c8bdcc6..bac964b919 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -17,13 +17,13 @@ use crate::render::highlight::highlight_bash_to_lines; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::Renderable; use codex_core::features::Features; -use codex_core::protocol::ElicitationAction; -use codex_core::protocol::ExecPolicyAmendment; -use codex_core::protocol::FileChange; -use codex_core::protocol::NetworkApprovalContext; -use codex_core::protocol::Op; -use codex_core::protocol::ReviewDecision; use codex_protocol::mcp::RequestId; +use codex_protocol::protocol::ElicitationAction; +use codex_protocol::protocol::ExecPolicyAmendment; +use codex_protocol::protocol::FileChange; +use codex_protocol::protocol::NetworkApprovalContext; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; @@ -576,7 +576,7 @@ fn elicitation_options() -> Vec { mod tests { use super::*; use crate::app_event::AppEvent; - use codex_core::protocol::NetworkApprovalProtocol; + use codex_protocol::protocol::NetworkApprovalProtocol; use pretty_assertions::assert_eq; use tokio::sync::mpsc::unbounded_channel; diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 91dfa00a52..8498cd9b42 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -3252,7 +3252,7 @@ impl ChatComposer { insert_text: format!("${skill_name}"), search_terms, path: Some(skill.path.to_string_lossy().into_owned()), - category_tag: (skill.scope == codex_core::protocol::SkillScope::Repo) + category_tag: (skill.scope == codex_protocol::protocol::SkillScope::Repo) .then(|| "[Repo]".to_string()), }); } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer_history.rs b/codex-rs/tui/src/bottom_pane/chat_composer_history.rs index 604641d208..f6df497187 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer_history.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer_history.rs @@ -5,7 +5,7 @@ use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::MentionBinding; use crate::mention_codec::decode_history_mentions; -use codex_core::protocol::Op; +use codex_protocol::protocol::Op; use codex_protocol::user_input::TextElement; /// A composer history entry that can rehydrate draft state. @@ -292,7 +292,7 @@ impl ChatComposerHistory { mod tests { use super::*; use crate::app_event::AppEvent; - use codex_core::protocol::Op; + use codex_protocol::protocol::Op; use pretty_assertions::assert_eq; use tokio::sync::mpsc::unbounded_channel; diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index eeca6aef18..03d3779c57 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -19,7 +19,7 @@ use crate::app_event::FeedbackCategory; use crate::app_event_sender::AppEventSender; use crate::history_cell; use crate::render::renderable::Renderable; -use codex_core::protocol::SessionSource; +use codex_protocol::protocol::SessionSource; use super::CancellationEvent; use super::bottom_pane_view::BottomPaneView; diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 46917dd9fa..234bb8b728 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -979,7 +979,7 @@ impl Renderable for BottomPane { mod tests { use super::*; use crate::app_event::AppEvent; - use codex_core::protocol::Op; + use codex_protocol::protocol::Op; use codex_protocol::protocol::SkillScope; use crossterm::event::KeyModifiers; use insta::assert_snapshot; diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs b/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs index c2a4291cf1..79b1229800 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/mod.rs @@ -30,7 +30,7 @@ use crate::bottom_pane::selection_popup_common::measure_rows_height; use crate::history_cell; use crate::render::renderable::Renderable; -use codex_core::protocol::Op; +use codex_protocol::protocol::Op; use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputEvent; use codex_protocol::request_user_input::RequestUserInputResponse; diff --git a/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs b/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs index 7b25b9841e..1e0230c904 100644 --- a/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs +++ b/codex-rs/tui/src/bottom_pane/skills_toggle_view.rs @@ -22,7 +22,7 @@ use crate::render::renderable::Renderable; use crate::skills_helpers::match_skill; use crate::skills_helpers::truncate_skill_name; use crate::style::user_message_style; -use codex_core::protocol::Op; +use codex_protocol::protocol::Op; use super::CancellationEvent; use super::bottom_pane_view::BottomPaneView; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 1cd3b3e14f..238a60730c 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -61,54 +61,6 @@ use codex_core::git_info::get_git_repo_root; use codex_core::git_info::local_git_branches; use codex_core::models_manager::manager::ModelsManager; use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME; -use codex_core::protocol::AgentMessageDeltaEvent; -use codex_core::protocol::AgentMessageEvent; -use codex_core::protocol::AgentReasoningDeltaEvent; -use codex_core::protocol::AgentReasoningEvent; -use codex_core::protocol::AgentReasoningRawContentDeltaEvent; -use codex_core::protocol::AgentReasoningRawContentEvent; -use codex_core::protocol::ApplyPatchApprovalRequestEvent; -use codex_core::protocol::BackgroundEventEvent; -use codex_core::protocol::CodexErrorInfo; -use codex_core::protocol::CreditsSnapshot; -use codex_core::protocol::DeprecationNoticeEvent; -use codex_core::protocol::ErrorEvent; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecApprovalRequestEvent; -use codex_core::protocol::ExecCommandBeginEvent; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::ExecCommandOutputDeltaEvent; -use codex_core::protocol::ExecCommandSource; -use codex_core::protocol::ExitedReviewModeEvent; -use codex_core::protocol::ListCustomPromptsResponseEvent; -use codex_core::protocol::ListSkillsResponseEvent; -use codex_core::protocol::McpListToolsResponseEvent; -use codex_core::protocol::McpStartupCompleteEvent; -use codex_core::protocol::McpStartupStatus; -use codex_core::protocol::McpStartupUpdateEvent; -use codex_core::protocol::McpToolCallBeginEvent; -use codex_core::protocol::McpToolCallEndEvent; -use codex_core::protocol::Op; -use codex_core::protocol::PatchApplyBeginEvent; -use codex_core::protocol::RateLimitSnapshot; -use codex_core::protocol::ReviewRequest; -use codex_core::protocol::ReviewTarget; -use codex_core::protocol::SkillMetadata as ProtocolSkillMetadata; -use codex_core::protocol::StreamErrorEvent; -use codex_core::protocol::TerminalInteractionEvent; -use codex_core::protocol::TokenUsage; -use codex_core::protocol::TokenUsageInfo; -use codex_core::protocol::TurnAbortReason; -use codex_core::protocol::TurnCompleteEvent; -use codex_core::protocol::TurnDiffEvent; -use codex_core::protocol::UndoCompletedEvent; -use codex_core::protocol::UndoStartedEvent; -use codex_core::protocol::UserMessageEvent; -use codex_core::protocol::ViewImageToolCallEvent; -use codex_core::protocol::WarningEvent; -use codex_core::protocol::WebSearchBeginEvent; -use codex_core::protocol::WebSearchEndEvent; use codex_core::skills::model::SkillMetadata; use codex_core::terminal::TerminalName; use codex_core::terminal::terminal_info; @@ -130,6 +82,54 @@ use codex_protocol::items::AgentMessageItem; use codex_protocol::models::MessagePhase; use codex_protocol::models::local_image_label_text; use codex_protocol::parse_command::ParsedCommand; +use codex_protocol::protocol::AgentMessageDeltaEvent; +use codex_protocol::protocol::AgentMessageEvent; +use codex_protocol::protocol::AgentReasoningDeltaEvent; +use codex_protocol::protocol::AgentReasoningEvent; +use codex_protocol::protocol::AgentReasoningRawContentDeltaEvent; +use codex_protocol::protocol::AgentReasoningRawContentEvent; +use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; +use codex_protocol::protocol::BackgroundEventEvent; +use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::CreditsSnapshot; +use codex_protocol::protocol::DeprecationNoticeEvent; +use codex_protocol::protocol::ErrorEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecApprovalRequestEvent; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::ExecCommandOutputDeltaEvent; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::ExitedReviewModeEvent; +use codex_protocol::protocol::ListCustomPromptsResponseEvent; +use codex_protocol::protocol::ListSkillsResponseEvent; +use codex_protocol::protocol::McpListToolsResponseEvent; +use codex_protocol::protocol::McpStartupCompleteEvent; +use codex_protocol::protocol::McpStartupStatus; +use codex_protocol::protocol::McpStartupUpdateEvent; +use codex_protocol::protocol::McpToolCallBeginEvent; +use codex_protocol::protocol::McpToolCallEndEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::PatchApplyBeginEvent; +use codex_protocol::protocol::RateLimitSnapshot; +use codex_protocol::protocol::ReviewRequest; +use codex_protocol::protocol::ReviewTarget; +use codex_protocol::protocol::SkillMetadata as ProtocolSkillMetadata; +use codex_protocol::protocol::StreamErrorEvent; +use codex_protocol::protocol::TerminalInteractionEvent; +use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TokenUsageInfo; +use codex_protocol::protocol::TurnAbortReason; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnDiffEvent; +use codex_protocol::protocol::UndoCompletedEvent; +use codex_protocol::protocol::UndoStartedEvent; +use codex_protocol::protocol::UserMessageEvent; +use codex_protocol::protocol::ViewImageToolCallEvent; +use codex_protocol::protocol::WarningEvent; +use codex_protocol::protocol::WebSearchBeginEvent; +use codex_protocol::protocol::WebSearchEndEvent; use codex_protocol::request_user_input::RequestUserInputEvent; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; @@ -268,13 +268,13 @@ use chrono::Local; use codex_core::AuthManager; use codex_core::CodexAuth; use codex_core::ThreadManager; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::SandboxPolicy; use codex_file_search::FileMatch; use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ModelPreset; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::plan_tool::UpdatePlanArgs; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; use codex_utils_approval_presets::ApprovalPreset; use codex_utils_approval_presets::builtin_approval_presets; use strum::IntoEnumIterator; @@ -650,7 +650,7 @@ pub(crate) struct ChatWidget { // Current working directory (if known) current_cwd: Option, // Runtime network proxy bind addresses from SessionConfigured. - session_network_proxy: Option, + session_network_proxy: Option, // Shared latch so we only warn once about invalid status-line item IDs. status_line_invalid_items_warned: Arc, // Cached git branch name for the status line (None if unknown). @@ -1060,7 +1060,7 @@ impl ChatWidget { } // --- Small event handlers --- - fn on_session_configured(&mut self, event: codex_core::protocol::SessionConfiguredEvent) { + fn on_session_configured(&mut self, event: codex_protocol::protocol::SessionConfiguredEvent) { self.bottom_pane .set_history_metadata(event.history_log_id, event.history_entry_count); self.set_skills(None); @@ -1159,7 +1159,7 @@ impl ChatWidget { }); } - fn on_thread_name_updated(&mut self, event: codex_core::protocol::ThreadNameUpdatedEvent) { + fn on_thread_name_updated(&mut self, event: codex_protocol::protocol::ThreadNameUpdatedEvent) { if self.thread_id == Some(event.thread_id) { self.thread_name = event.thread_name; self.request_redraw(); @@ -1982,7 +1982,7 @@ impl ChatWidget { self.request_redraw(); } - fn on_patch_apply_end(&mut self, event: codex_core::protocol::PatchApplyEndEvent) { + fn on_patch_apply_end(&mut self, event: codex_protocol::protocol::PatchApplyEndEvent) { let ev2 = event.clone(); self.defer_or_handle( |q| q.push_patch_end(event), @@ -2144,9 +2144,9 @@ impl ChatWidget { fn on_get_history_entry_response( &mut self, - event: codex_core::protocol::GetHistoryEntryResponseEvent, + event: codex_protocol::protocol::GetHistoryEntryResponseEvent, ) { - let codex_core::protocol::GetHistoryEntryResponseEvent { + let codex_protocol::protocol::GetHistoryEntryResponseEvent { offset, log_id, entry, @@ -2412,7 +2412,7 @@ impl ChatWidget { pub(crate) fn handle_patch_apply_end_now( &mut self, - event: codex_core::protocol::PatchApplyEndEvent, + event: codex_protocol::protocol::PatchApplyEndEvent, ) { // If the patch was successful, just let the "Edited" block stand. // Otherwise, add a failure block. @@ -2923,7 +2923,7 @@ impl ChatWidget { pub(crate) fn new_from_existing( common: ChatWidgetInit, conversation: std::sync::Arc, - session_configured: codex_core::protocol::SessionConfiguredEvent, + session_configured: codex_protocol::protocol::SessionConfiguredEvent, ) -> Self { let ChatWidgetInit { config, @@ -3505,11 +3505,11 @@ impl ChatWidget { } } SlashCommand::TestApproval => { - use codex_core::protocol::EventMsg; + use codex_protocol::protocol::EventMsg; use std::collections::HashMap; - use codex_core::protocol::ApplyPatchApprovalRequestEvent; - use codex_core::protocol::FileChange; + use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; + use codex_protocol::protocol::FileChange; self.app_event_tx.send(AppEvent::CodexEvent(Event { id: "1".to_string(), diff --git a/codex-rs/tui/src/chatwidget/agent.rs b/codex-rs/tui/src/chatwidget/agent.rs index d905f884f8..63d519a7a5 100644 --- a/codex-rs/tui/src/chatwidget/agent.rs +++ b/codex-rs/tui/src/chatwidget/agent.rs @@ -4,9 +4,9 @@ use codex_core::CodexThread; use codex_core::NewThread; use codex_core::ThreadManager; use codex_core::config::Config; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::unbounded_channel; @@ -44,10 +44,10 @@ pub(crate) fn spawn_agent( }; // Forward the captured `SessionConfigured` event so it can be rendered in the UI. - let ev = codex_core::protocol::Event { + let ev = codex_protocol::protocol::Event { // The `id` does not matter for rendering, so we can use a fake value. id: "".to_string(), - msg: codex_core::protocol::EventMsg::SessionConfigured(session_configured), + msg: codex_protocol::protocol::EventMsg::SessionConfigured(session_configured), }; app_event_tx_clone.send(AppEvent::CodexEvent(ev)); @@ -80,7 +80,7 @@ pub(crate) fn spawn_agent( /// events and accepts Ops for submission. pub(crate) fn spawn_agent_from_existing( thread: std::sync::Arc, - session_configured: codex_core::protocol::SessionConfiguredEvent, + session_configured: codex_protocol::protocol::SessionConfiguredEvent, app_event_tx: AppEventSender, ) -> UnboundedSender { let (codex_op_tx, mut codex_op_rx) = unbounded_channel::(); @@ -88,9 +88,9 @@ pub(crate) fn spawn_agent_from_existing( let app_event_tx_clone = app_event_tx; tokio::spawn(async move { // Forward the captured `SessionConfigured` event so it can be rendered in the UI. - let ev = codex_core::protocol::Event { + let ev = codex_protocol::protocol::Event { id: "".to_string(), - msg: codex_core::protocol::EventMsg::SessionConfigured(session_configured), + msg: codex_protocol::protocol::EventMsg::SessionConfigured(session_configured), }; app_event_tx_clone.send(AppEvent::CodexEvent(ev)); diff --git a/codex-rs/tui/src/chatwidget/interrupts.rs b/codex-rs/tui/src/chatwidget/interrupts.rs index fccd438434..8216398448 100644 --- a/codex-rs/tui/src/chatwidget/interrupts.rs +++ b/codex-rs/tui/src/chatwidget/interrupts.rs @@ -1,13 +1,13 @@ use std::collections::VecDeque; -use codex_core::protocol::ApplyPatchApprovalRequestEvent; -use codex_core::protocol::ExecApprovalRequestEvent; -use codex_core::protocol::ExecCommandBeginEvent; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::McpToolCallBeginEvent; -use codex_core::protocol::McpToolCallEndEvent; -use codex_core::protocol::PatchApplyEndEvent; use codex_protocol::approvals::ElicitationRequestEvent; +use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; +use codex_protocol::protocol::ExecApprovalRequestEvent; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::McpToolCallBeginEvent; +use codex_protocol::protocol::McpToolCallEndEvent; +use codex_protocol::protocol::PatchApplyEndEvent; use codex_protocol::request_user_input::RequestUserInputEvent; use super::ChatWidget; diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index e7fadde1af..1d71cc61ec 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -14,13 +14,13 @@ use crate::skills_helpers::skill_description; use crate::skills_helpers::skill_display_name; use codex_chatgpt::connectors::AppInfo; use codex_core::connectors::connector_mention_slug; -use codex_core::protocol::ListSkillsResponseEvent; -use codex_core::protocol::SkillMetadata as ProtocolSkillMetadata; -use codex_core::protocol::SkillsListEntry; use codex_core::skills::model::SkillDependencies; use codex_core::skills::model::SkillInterface; use codex_core::skills::model::SkillMetadata; use codex_core::skills::model::SkillToolDependency; +use codex_protocol::protocol::ListSkillsResponseEvent; +use codex_protocol::protocol::SkillMetadata as ProtocolSkillMetadata; +use codex_protocol::protocol::SkillsListEntry; impl ChatWidget { pub(crate) fn open_skills_list(&mut self) { diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index f04d02f658..b9f5ddf814 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -1,6 +1,6 @@ //! Exercises `ChatWidget` event handling and rendering invariants. //! -//! These tests treat the widget as the adapter between `codex_core::protocol::EventMsg` inputs and +//! These tests treat the widget as the adapter between `codex_protocol::protocol::EventMsg` inputs and //! the TUI output. Many assertions are snapshot-based so that layout regressions and status/header //! changes show up as stable, reviewable diffs. @@ -25,47 +25,6 @@ use codex_core::config::types::WindowsSandboxModeToml; use codex_core::config_loader::RequirementSource; use codex_core::features::Feature; use codex_core::models_manager::manager::ModelsManager; -use codex_core::protocol::AgentMessageDeltaEvent; -use codex_core::protocol::AgentMessageEvent; -use codex_core::protocol::AgentReasoningDeltaEvent; -use codex_core::protocol::AgentReasoningEvent; -use codex_core::protocol::ApplyPatchApprovalRequestEvent; -use codex_core::protocol::BackgroundEventEvent; -use codex_core::protocol::CreditsSnapshot; -use codex_core::protocol::Event; -use codex_core::protocol::EventMsg; -use codex_core::protocol::ExecApprovalRequestEvent; -use codex_core::protocol::ExecCommandBeginEvent; -use codex_core::protocol::ExecCommandEndEvent; -use codex_core::protocol::ExecCommandSource; -use codex_core::protocol::ExecCommandStatus as CoreExecCommandStatus; -use codex_core::protocol::ExecPolicyAmendment; -use codex_core::protocol::ExitedReviewModeEvent; -use codex_core::protocol::FileChange; -use codex_core::protocol::ItemCompletedEvent; -use codex_core::protocol::McpStartupCompleteEvent; -use codex_core::protocol::McpStartupStatus; -use codex_core::protocol::McpStartupUpdateEvent; -use codex_core::protocol::Op; -use codex_core::protocol::PatchApplyBeginEvent; -use codex_core::protocol::PatchApplyEndEvent; -use codex_core::protocol::PatchApplyStatus as CorePatchApplyStatus; -use codex_core::protocol::RateLimitWindow; -use codex_core::protocol::ReviewRequest; -use codex_core::protocol::ReviewTarget; -use codex_core::protocol::SessionSource; -use codex_core::protocol::StreamErrorEvent; -use codex_core::protocol::TerminalInteractionEvent; -use codex_core::protocol::ThreadRolledBackEvent; -use codex_core::protocol::TokenCountEvent; -use codex_core::protocol::TokenUsage; -use codex_core::protocol::TokenUsageInfo; -use codex_core::protocol::TurnCompleteEvent; -use codex_core::protocol::TurnStartedEvent; -use codex_core::protocol::UndoCompletedEvent; -use codex_core::protocol::UndoStartedEvent; -use codex_core::protocol::ViewImageToolCallEvent; -use codex_core::protocol::WarningEvent; use codex_core::skills::model::SkillMetadata; use codex_core::terminal::TerminalName; use codex_otel::OtelManager; @@ -87,8 +46,49 @@ use codex_protocol::parse_command::ParsedCommand; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; use codex_protocol::plan_tool::UpdatePlanArgs; +use codex_protocol::protocol::AgentMessageDeltaEvent; +use codex_protocol::protocol::AgentMessageEvent; +use codex_protocol::protocol::AgentReasoningDeltaEvent; +use codex_protocol::protocol::AgentReasoningEvent; +use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; +use codex_protocol::protocol::BackgroundEventEvent; use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::CreditsSnapshot; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecApprovalRequestEvent; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus; +use codex_protocol::protocol::ExecPolicyAmendment; +use codex_protocol::protocol::ExitedReviewModeEvent; +use codex_protocol::protocol::FileChange; +use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::McpStartupCompleteEvent; +use codex_protocol::protocol::McpStartupStatus; +use codex_protocol::protocol::McpStartupUpdateEvent; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::PatchApplyBeginEvent; +use codex_protocol::protocol::PatchApplyEndEvent; +use codex_protocol::protocol::PatchApplyStatus as CorePatchApplyStatus; +use codex_protocol::protocol::RateLimitWindow; +use codex_protocol::protocol::ReviewRequest; +use codex_protocol::protocol::ReviewTarget; +use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SkillScope; +use codex_protocol::protocol::StreamErrorEvent; +use codex_protocol::protocol::TerminalInteractionEvent; +use codex_protocol::protocol::ThreadRolledBackEvent; +use codex_protocol::protocol::TokenCountEvent; +use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TokenUsageInfo; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnStartedEvent; +use codex_protocol::protocol::UndoCompletedEvent; +use codex_protocol::protocol::UndoStartedEvent; +use codex_protocol::protocol::ViewImageToolCallEvent; +use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; @@ -149,7 +149,7 @@ async fn resumed_initial_messages_render_history() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -218,7 +218,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -277,7 +277,7 @@ async fn replayed_user_message_preserves_remote_image_urls() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -333,7 +333,7 @@ async fn replayed_user_message_with_only_remote_images_renders_history_cell() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -384,7 +384,7 @@ async fn replayed_user_message_with_only_local_images_does_not_render_history_ce let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -494,7 +494,7 @@ async fn submission_preserves_text_elements_and_local_images() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -576,7 +576,7 @@ async fn submission_with_remote_and_local_images_keeps_local_placeholder_numberi let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -669,7 +669,7 @@ async fn enter_with_only_remote_images_submits_user_turn() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -731,7 +731,7 @@ async fn shift_enter_with_only_remote_images_does_not_submit_user_turn() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -769,7 +769,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_modal_is_active() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -807,7 +807,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_input_disabled() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -846,7 +846,7 @@ async fn submission_prefers_selected_duplicate_skill_path() { let conversation_id = ThreadId::new(); let rollout_file = NamedTempFile::new().unwrap(); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, thread_name: None, @@ -1119,7 +1119,7 @@ async fn interrupted_turn_restores_queued_messages_with_images_and_elements() { // must be renumbered to match the combined local image list. chat.handle_codex_event(Event { id: "interrupt".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -1184,7 +1184,7 @@ async fn interrupted_turn_restore_keeps_active_mode_for_resubmission() { chat.handle_codex_event(Event { id: "interrupt".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -2852,7 +2852,8 @@ fn begin_exec_with_source( // Build the full command vec and parse it using core's parser, // then convert to protocol variants for the event payload. let command = vec!["bash".to_string(), "-lc".to_string(), raw_cmd.to_string()]; - let parsed_cmd: Vec = codex_core::parse_command::parse_command(&command); + let parsed_cmd: Vec = + codex_shell_command::parse_command::parse_command(&command); let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); let interaction_input = None; let event = ExecCommandBeginEvent { @@ -3494,7 +3495,7 @@ async fn exec_end_without_begin_uses_event_command() { "-lc".to_string(), "echo orphaned".to_string(), ]; - let parsed_cmd = codex_core::parse_command::parse_command(&command); + let parsed_cmd = codex_shell_command::parse_command::parse_command(&command); let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); chat.handle_codex_event(Event { id: "call-orphan".to_string(), @@ -4037,7 +4038,7 @@ async fn plan_slash_command_with_args_submits_prompt_in_plan_mode() { let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; chat.set_feature_enabled(Feature::CollaborationModes, true); - let configured = codex_core::protocol::SessionConfiguredEvent { + let configured = codex_protocol::protocol::SessionConfiguredEvent { session_id: ThreadId::new(), forked_from_id: None, thread_name: None, @@ -4639,7 +4640,7 @@ async fn interrupt_exec_marks_failed_snapshot() { // cause the active exec cell to be finalized as failed and flushed. chat.handle_codex_event(Event { id: "call-int".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -4675,7 +4676,7 @@ async fn interrupted_turn_error_message_snapshot() { // Abort the turn (like pressing Esc) and drain inserted history. chat.handle_codex_event(Event { id: "task-1".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -6330,7 +6331,7 @@ async fn interrupt_restores_queued_messages_into_composer() { // Deliver a TurnAborted event with Interrupted reason (as if Esc was pressed). chat.handle_codex_event(Event { id: "turn-1".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -6369,7 +6370,7 @@ async fn interrupt_prepends_queued_messages_before_existing_composer_text() { chat.handle_codex_event(Event { id: "turn-1".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -6398,7 +6399,7 @@ async fn interrupt_clears_unified_exec_processes() { chat.handle_codex_event(Event { id: "turn-1".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -6419,7 +6420,7 @@ async fn review_ended_keeps_unified_exec_processes() { chat.handle_codex_event(Event { id: "turn-1".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::ReviewEnded, }), @@ -6464,7 +6465,7 @@ async fn interrupt_clears_unified_exec_wait_streak_snapshot() { chat.handle_codex_event(Event { id: "turn-1".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), @@ -6572,7 +6573,7 @@ async fn ui_snapshots_small_heights_task_running() { // task (status indicator active) while an approval request is shown. #[tokio::test] async fn status_widget_and_approval_modal_snapshot() { - use codex_core::protocol::ExecApprovalRequestEvent; + use codex_protocol::protocol::ExecApprovalRequestEvent; let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; // Begin a running task so the status indicator would be active. @@ -6955,7 +6956,7 @@ async fn apply_patch_approval_sends_op_with_call_id() { while let Ok(app_ev) = rx.try_recv() { if let AppEvent::CodexOp(Op::PatchApproval { id, decision }) = app_ev { assert_eq!(id, "call-999"); - assert_matches!(decision, codex_core::protocol::ReviewDecision::Approved); + assert_matches!(decision, codex_protocol::protocol::ReviewDecision::Approved); found = true; break; } @@ -7003,7 +7004,7 @@ async fn apply_patch_full_flow_integration_like() { match forwarded { Op::PatchApproval { id, decision } => { assert_eq!(id, "call-1"); - assert_matches!(decision, codex_core::protocol::ReviewDecision::Approved); + assert_matches!(decision, codex_protocol::protocol::ReviewDecision::Approved); } other => panic!("unexpected op forwarded: {other:?}"), } @@ -7344,7 +7345,7 @@ async fn status_line_branch_refreshes_after_interrupt() { chat.handle_codex_event(Event { id: "turn-1".into(), - msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { turn_id: Some("turn-1".to_string()), reason: TurnAbortReason::Interrupted, }), diff --git a/codex-rs/tui/src/debug_config.rs b/codex-rs/tui/src/debug_config.rs index 38faf2d35b..a3e98d85c7 100644 --- a/codex-rs/tui/src/debug_config.rs +++ b/codex-rs/tui/src/debug_config.rs @@ -9,7 +9,7 @@ use codex_core::config_loader::RequirementSource; use codex_core::config_loader::ResidencyRequirement; use codex_core::config_loader::SandboxModeRequirement; use codex_core::config_loader::WebSearchModeRequirement; -use codex_core::protocol::SessionNetworkProxyRuntime; +use codex_protocol::protocol::SessionNetworkProxyRuntime; use ratatui::style::Stylize; use ratatui::text::Line; use toml::Value as TomlValue; @@ -404,9 +404,9 @@ mod tests { use codex_core::config_loader::SandboxModeRequirement; use codex_core::config_loader::Sourced; use codex_core::config_loader::WebSearchModeRequirement; - use codex_core::protocol::AskForApproval; - use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::WebSearchMode; + use codex_protocol::protocol::AskForApproval; + use codex_protocol::protocol::SandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use ratatui::text::Line; use std::collections::BTreeMap; diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index 9683df53ba..6fdf3a43f5 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -19,7 +19,7 @@ use crate::render::renderable::ColumnRenderable; use crate::render::renderable::InsetRenderable; use crate::render::renderable::Renderable; use codex_core::git_info::get_git_repo_root; -use codex_core::protocol::FileChange; +use codex_protocol::protocol::FileChange; // Internal representation for diff line rendering enum DiffLineType { diff --git a/codex-rs/tui/src/exec_cell/model.rs b/codex-rs/tui/src/exec_cell/model.rs index 21799c6199..f08b088ef7 100644 --- a/codex-rs/tui/src/exec_cell/model.rs +++ b/codex-rs/tui/src/exec_cell/model.rs @@ -1,8 +1,8 @@ use std::time::Duration; use std::time::Instant; -use codex_core::protocol::ExecCommandSource; use codex_protocol::parse_command::ParsedCommand; +use codex_protocol::protocol::ExecCommandSource; #[derive(Clone, Debug, Default)] pub(crate) struct CommandOutput { diff --git a/codex-rs/tui/src/exec_cell/render.rs b/codex-rs/tui/src/exec_cell/render.rs index 4f7b1cd635..6e57c21520 100644 --- a/codex-rs/tui/src/exec_cell/render.rs +++ b/codex-rs/tui/src/exec_cell/render.rs @@ -13,9 +13,9 @@ use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_line; use crate::wrapping::word_wrap_lines; use codex_ansi_escape::ansi_escape_line; -use codex_core::bash::extract_bash_command; -use codex_core::protocol::ExecCommandSource; use codex_protocol::parse_command::ParsedCommand; +use codex_protocol::protocol::ExecCommandSource; +use codex_shell_command::bash::extract_bash_command; use codex_utils_elapsed::format_duration; use itertools::Itertools; use ratatui::prelude::*; @@ -611,7 +611,7 @@ const EXEC_DISPLAY_LAYOUT: ExecDisplayLayout = ExecDisplayLayout::new( #[cfg(test)] mod tests { use super::*; - use codex_core::protocol::ExecCommandSource; + use codex_protocol::protocol::ExecCommandSource; #[test] fn user_shell_output_is_limited_by_screen_lines() { diff --git a/codex-rs/tui/src/exec_command.rs b/codex-rs/tui/src/exec_command.rs index 8ce6c2632e..bcfbc1776d 100644 --- a/codex-rs/tui/src/exec_command.rs +++ b/codex-rs/tui/src/exec_command.rs @@ -1,7 +1,7 @@ use std::path::Path; use std::path::PathBuf; -use codex_core::parse_command::extract_shell_command; +use codex_shell_command::parse_command::extract_shell_command; use dirs::home_dir; use shlex::try_join; diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 8c4d0147df..bd08c370e4 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -39,10 +39,6 @@ use crate::wrapping::word_wrap_lines; use base64::Engine; use codex_core::config::Config; use codex_core::config::types::McpServerTransportConfig; -use codex_core::protocol::FileChange; -use codex_core::protocol::McpAuthStatus; -use codex_core::protocol::McpInvocation; -use codex_core::protocol::SessionConfiguredEvent; use codex_core::web_search::web_search_detail; use codex_otel::RuntimeMetricsSummary; use codex_protocol::account::PlanType; @@ -54,6 +50,10 @@ use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; use codex_protocol::plan_tool::UpdatePlanArgs; +use codex_protocol::protocol::FileChange; +use codex_protocol::protocol::McpAuthStatus; +use codex_protocol::protocol::McpInvocation; +use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputQuestion; use codex_protocol::user_input::TextElement; @@ -791,9 +791,9 @@ fn exec_snippet(command: &[String]) -> String { pub fn new_approval_decision_cell( command: Vec, - decision: codex_core::protocol::ReviewDecision, + decision: codex_protocol::protocol::ReviewDecision, ) -> Box { - use codex_core::protocol::ReviewDecision::*; + use codex_protocol::protocol::ReviewDecision::*; let (symbol, summary): (Span<'static>, Vec>) = match decision { Approved => { @@ -2383,19 +2383,19 @@ mod tests { use codex_core::config::ConfigBuilder; use codex_core::config::types::McpServerConfig; use codex_core::config::types::McpServerTransportConfig; - use codex_core::protocol::McpAuthStatus; use codex_otel::RuntimeMetricTotals; use codex_otel::RuntimeMetricsSummary; use codex_protocol::models::WebSearchAction; use codex_protocol::parse_command::ParsedCommand; + use codex_protocol::protocol::McpAuthStatus; use dirs::home_dir; use pretty_assertions::assert_eq; use serde_json::json; use std::collections::HashMap; - use codex_core::protocol::ExecCommandSource; use codex_protocol::mcp::CallToolResult; use codex_protocol::mcp::Tool; + use codex_protocol::protocol::ExecCommandSource; use rmcp::model::Content; const SMALL_PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 20c9fc21b0..c44b5eb751 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -30,13 +30,13 @@ use codex_core::find_thread_path_by_id_str; use codex_core::find_thread_path_by_name_str; use codex_core::format_exec_policy_error_with_source; use codex_core::path_utils; -use codex_core::protocol::AskForApproval; use codex_core::read_session_meta_line; use codex_core::terminal::Multiplexer; use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_protocol::config_types::AltScreenMode; use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_state::log_db; @@ -468,7 +468,7 @@ async fn run_ratatui_app( UpdatePromptOutcome::RunUpdate(action) => { crate::tui::restore()?; return Ok(AppExitInfo { - token_usage: codex_core::protocol::TokenUsage::default(), + token_usage: codex_protocol::protocol::TokenUsage::default(), thread_id: None, thread_name: None, update_action: Some(action), @@ -511,7 +511,7 @@ async fn run_ratatui_app( session_log::log_session_end(); let _ = tui.terminal.clear(); return Ok(AppExitInfo { - token_usage: codex_core::protocol::TokenUsage::default(), + token_usage: codex_protocol::protocol::TokenUsage::default(), thread_id: None, thread_name: None, update_action: None, @@ -551,7 +551,7 @@ async fn run_ratatui_app( session_log::log_session_end(); let _ = tui.terminal.clear(); Ok(AppExitInfo { - token_usage: codex_core::protocol::TokenUsage::default(), + token_usage: codex_protocol::protocol::TokenUsage::default(), thread_id: None, thread_name: None, update_action: None, @@ -600,7 +600,7 @@ async fn run_ratatui_app( restore(); session_log::log_session_end(); return Ok(AppExitInfo { - token_usage: codex_core::protocol::TokenUsage::default(), + token_usage: codex_protocol::protocol::TokenUsage::default(), thread_id: None, thread_name: None, update_action: None, @@ -651,7 +651,7 @@ async fn run_ratatui_app( restore(); session_log::log_session_end(); return Ok(AppExitInfo { - token_usage: codex_core::protocol::TokenUsage::default(), + token_usage: codex_protocol::protocol::TokenUsage::default(), thread_id: None, thread_name: None, update_action: None, @@ -681,7 +681,7 @@ async fn run_ratatui_app( restore(); session_log::log_session_end(); return Ok(AppExitInfo { - token_usage: codex_core::protocol::TokenUsage::default(), + token_usage: codex_protocol::protocol::TokenUsage::default(), thread_id: None, thread_name: None, update_action: None, @@ -965,7 +965,7 @@ mod tests { use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::ProjectConfig; - use codex_core::protocol::AskForApproval; + use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionMeta; diff --git a/codex-rs/tui/src/main.rs b/codex-rs/tui/src/main.rs index 7f043ef0f9..b7a27576e8 100644 --- a/codex-rs/tui/src/main.rs +++ b/codex-rs/tui/src/main.rs @@ -24,7 +24,10 @@ fn main() -> anyhow::Result<()> { let exit_info = run_main(inner, codex_linux_sandbox_exe).await?; let token_usage = exit_info.token_usage; if !token_usage.is_zero() { - println!("{}", codex_core::protocol::FinalOutput::from(token_usage),); + println!( + "{}", + codex_protocol::protocol::FinalOutput::from(token_usage), + ); } Ok(()) }) diff --git a/codex-rs/tui/src/multi_agents.rs b/codex-rs/tui/src/multi_agents.rs index 57df8b8891..806400f2e3 100644 --- a/codex-rs/tui/src/multi_agents.rs +++ b/codex-rs/tui/src/multi_agents.rs @@ -1,17 +1,17 @@ use crate::history_cell::PlainHistoryCell; use crate::render::line_utils::prefix_lines; use crate::text_formatting::truncate_text; -use codex_core::protocol::AgentStatus; -use codex_core::protocol::CollabAgentInteractionEndEvent; -use codex_core::protocol::CollabAgentRef; -use codex_core::protocol::CollabAgentSpawnEndEvent; -use codex_core::protocol::CollabAgentStatusEntry; -use codex_core::protocol::CollabCloseEndEvent; -use codex_core::protocol::CollabResumeBeginEvent; -use codex_core::protocol::CollabResumeEndEvent; -use codex_core::protocol::CollabWaitingBeginEvent; -use codex_core::protocol::CollabWaitingEndEvent; use codex_protocol::ThreadId; +use codex_protocol::protocol::AgentStatus; +use codex_protocol::protocol::CollabAgentInteractionEndEvent; +use codex_protocol::protocol::CollabAgentRef; +use codex_protocol::protocol::CollabAgentSpawnEndEvent; +use codex_protocol::protocol::CollabAgentStatusEntry; +use codex_protocol::protocol::CollabCloseEndEvent; +use codex_protocol::protocol::CollabResumeBeginEvent; +use codex_protocol::protocol::CollabResumeEndEvent; +use codex_protocol::protocol::CollabWaitingBeginEvent; +use codex_protocol::protocol::CollabWaitingEndEvent; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index f04310cd86..00c18dd71a 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -796,8 +796,8 @@ fn render_offset_content( #[cfg(test)] mod tests { use super::*; - use codex_core::protocol::ExecCommandSource; - use codex_core::protocol::ReviewDecision; + use codex_protocol::protocol::ExecCommandSource; + use codex_protocol::protocol::ReviewDecision; use insta::assert_snapshot; use pretty_assertions::assert_eq; use std::collections::HashMap; @@ -809,8 +809,8 @@ mod tests { use crate::history_cell; use crate::history_cell::HistoryCell; use crate::history_cell::new_patch_event; - use codex_core::protocol::FileChange; use codex_protocol::parse_command::ParsedCommand; + use codex_protocol::protocol::FileChange; use ratatui::Terminal; use ratatui::backend::TestBackend; use ratatui::text::Text; diff --git a/codex-rs/tui/src/session_log.rs b/codex-rs/tui/src/session_log.rs index b2858e8f21..ca4d39cd18 100644 --- a/codex-rs/tui/src/session_log.rs +++ b/codex-rs/tui/src/session_log.rs @@ -7,7 +7,7 @@ use std::sync::Mutex; use std::sync::OnceLock; use codex_core::config::Config; -use codex_core::protocol::Op; +use codex_protocol::protocol::Op; use serde::Serialize; use serde_json::json; diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index e6d5a27d29..bf55c0ace1 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -7,14 +7,14 @@ use chrono::DateTime; use chrono::Local; use codex_core::WireApi; use codex_core::config::Config; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::NetworkAccess; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::TokenUsage; -use codex_core::protocol::TokenUsageInfo; use codex_protocol::ThreadId; use codex_protocol::account::PlanType; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::NetworkAccess; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TokenUsageInfo; use codex_utils_sandbox_summary::summarize_sandbox_policy; use ratatui::prelude::*; use ratatui::style::Stylize; diff --git a/codex-rs/tui/src/status/rate_limits.rs b/codex-rs/tui/src/status/rate_limits.rs index 8d46bc8c99..10dbaaaa2f 100644 --- a/codex-rs/tui/src/status/rate_limits.rs +++ b/codex-rs/tui/src/status/rate_limits.rs @@ -13,9 +13,9 @@ use chrono::DateTime; use chrono::Duration as ChronoDuration; use chrono::Local; use chrono::Utc; -use codex_core::protocol::CreditsSnapshot as CoreCreditsSnapshot; -use codex_core::protocol::RateLimitSnapshot; -use codex_core::protocol::RateLimitWindow; +use codex_protocol::protocol::CreditsSnapshot as CoreCreditsSnapshot; +use codex_protocol::protocol::RateLimitSnapshot; +use codex_protocol::protocol::RateLimitWindow; const STATUS_LIMIT_BAR_SEGMENTS: usize = 20; const STATUS_LIMIT_BAR_FILLED: &str = "█"; diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index 02838c651e..fb1aad7275 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -7,16 +7,16 @@ use chrono::Utc; use codex_core::AuthManager; use codex_core::config::Config; use codex_core::config::ConfigBuilder; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::CreditsSnapshot; -use codex_core::protocol::RateLimitSnapshot; -use codex_core::protocol::RateLimitWindow; -use codex_core::protocol::SandboxPolicy; -use codex_core::protocol::TokenUsage; -use codex_core::protocol::TokenUsageInfo; use codex_protocol::ThreadId; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::CreditsSnapshot; +use codex_protocol::protocol::RateLimitSnapshot; +use codex_protocol::protocol::RateLimitWindow; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TokenUsageInfo; use insta::assert_snapshot; use pretty_assertions::assert_eq; use ratatui::prelude::*; diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index b41a2fa3ca..fa266f9760 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -7,7 +7,7 @@ use std::time::Duration; use std::time::Instant; -use codex_core::protocol::Op; +use codex_protocol::protocol::Op; use crossterm::event::KeyCode; use ratatui::buffer::Buffer; use ratatui::layout::Rect; diff --git a/codex-rs/utils/approval-presets/Cargo.toml b/codex-rs/utils/approval-presets/Cargo.toml index 1237545cd6..0e387f07a8 100644 --- a/codex-rs/utils/approval-presets/Cargo.toml +++ b/codex-rs/utils/approval-presets/Cargo.toml @@ -8,4 +8,4 @@ license.workspace = true workspace = true [dependencies] -codex-core = { workspace = true } +codex-protocol = { workspace = true } diff --git a/codex-rs/utils/approval-presets/src/lib.rs b/codex-rs/utils/approval-presets/src/lib.rs index 9e66e39e08..fbfa120e61 100644 --- a/codex-rs/utils/approval-presets/src/lib.rs +++ b/codex-rs/utils/approval-presets/src/lib.rs @@ -1,5 +1,5 @@ -use codex_core::protocol::AskForApproval; -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; /// A simple preset pairing an approval policy with a sandbox policy. #[derive(Debug, Clone)] diff --git a/codex-rs/utils/cli/Cargo.toml b/codex-rs/utils/cli/Cargo.toml index 7e9d2c5a1d..d9adf42b3f 100644 --- a/codex-rs/utils/cli/Cargo.toml +++ b/codex-rs/utils/cli/Cargo.toml @@ -9,7 +9,6 @@ workspace = true [dependencies] clap = { workspace = true, features = ["derive", "wrap_help"] } -codex-core = { workspace = true } codex-protocol = { workspace = true } serde = { workspace = true } toml = { workspace = true } diff --git a/codex-rs/utils/cli/src/approval_mode_cli_arg.rs b/codex-rs/utils/cli/src/approval_mode_cli_arg.rs index 08b7be6cca..ee4ecabcb6 100644 --- a/codex-rs/utils/cli/src/approval_mode_cli_arg.rs +++ b/codex-rs/utils/cli/src/approval_mode_cli_arg.rs @@ -2,7 +2,7 @@ use clap::ValueEnum; -use codex_core::protocol::AskForApproval; +use codex_protocol::protocol::AskForApproval; #[derive(Clone, Copy, Debug, ValueEnum)] #[value(rename_all = "kebab-case")] diff --git a/codex-rs/utils/cli/src/sandbox_mode_cli_arg.rs b/codex-rs/utils/cli/src/sandbox_mode_cli_arg.rs index 18935840f4..b7d1a248b8 100644 --- a/codex-rs/utils/cli/src/sandbox_mode_cli_arg.rs +++ b/codex-rs/utils/cli/src/sandbox_mode_cli_arg.rs @@ -1,6 +1,6 @@ //! Standard type to use with the `--sandbox` (`-s`) CLI option. //! -//! This mirrors the variants of [`codex_core::protocol::SandboxPolicy`], but +//! This mirrors the variants of [`codex_protocol::protocol::SandboxPolicy`], but //! without any of the associated data so it can be expressed as a simple flag //! on the command-line. Users that need to tweak the advanced options for //! `workspace-write` can continue to do so via `-c` overrides or their diff --git a/codex-rs/utils/sandbox-summary/Cargo.toml b/codex-rs/utils/sandbox-summary/Cargo.toml index 6e44b2d201..202dfaf22b 100644 --- a/codex-rs/utils/sandbox-summary/Cargo.toml +++ b/codex-rs/utils/sandbox-summary/Cargo.toml @@ -9,6 +9,7 @@ workspace = true [dependencies] codex-core = { workspace = true } +codex-protocol = { workspace = true } [dev-dependencies] codex-utils-absolute-path = { workspace = true } diff --git a/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs b/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs index 53851d86b7..a5c9b31fdd 100644 --- a/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs +++ b/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs @@ -1,5 +1,5 @@ -use codex_core::protocol::NetworkAccess; -use codex_core::protocol::SandboxPolicy; +use codex_protocol::protocol::NetworkAccess; +use codex_protocol::protocol::SandboxPolicy; pub fn summarize_sandbox_policy(sandbox_policy: &SandboxPolicy) -> String { match sandbox_policy { From 2fe4be1aa98b1706ac911ebaebc16a6c31407dcb Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sat, 21 Feb 2026 00:20:42 -0800 Subject: [PATCH 054/385] fix: codex-arg0 no longer depends on codex-core (#12434) ## Why `codex-rs/arg0` only needed two things from `codex-core`: - the `find_codex_home()` wrapper - the special argv flag used for the internal `apply_patch` self-invocation path That made `codex-arg0` depend on `codex-core` for a very small surface area. This change removes that dependency edge and moves the shared `apply_patch` invocation flag to a more natural boundary (`codex-apply-patch`) while keeping the contract explicitly documented. ## What Changed - Moved the internal `apply_patch` argv[1] flag constant out of `codex-core` and into `codex-apply-patch`. - Renamed the constant to `CODEX_CORE_APPLY_PATCH_ARG1` and documented that it is part of the Codex core process-invocation contract (even though it now lives in `codex-apply-patch`). - Updated `arg0`, the core apply-patch runtime, and the `codex-exec` apply-patch test to import the constant from `codex-apply-patch`. - Updated `codex-rs/arg0` to call `codex_utils_home_dir::find_codex_home()` directly instead of `codex_core::config::find_codex_home()`. - Removed the `codex-core` dependency from `codex-rs/arg0` and added the needed direct dependency on `codex-utils-home-dir`. - Added `codex-apply-patch` as a dev-dependency for `codex-rs/exec` tests (the apply-patch test now imports the moved constant directly). ## Verification - `cargo test -p codex-apply-patch` - `cargo test -p codex-arg0` - `cargo test -p codex-core --lib apply_patch` - `cargo test -p codex-exec test_standalone_exec_cli_can_use_apply_patch` - `cargo shear` --- codex-rs/Cargo.lock | 3 ++- codex-rs/apply-patch/src/lib.rs | 9 +++++++++ codex-rs/arg0/Cargo.toml | 2 +- codex-rs/arg0/src/lib.rs | 13 +++++++------ codex-rs/core/src/apply_patch.rs | 5 ++--- codex-rs/core/src/lib.rs | 1 - codex-rs/core/src/tools/runtimes/apply_patch.rs | 7 +++++-- codex-rs/exec/Cargo.toml | 1 + codex-rs/exec/tests/suite/apply_patch.rs | 4 ++-- 9 files changed, 29 insertions(+), 16 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index e9fd6ed167..42521a48df 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1398,8 +1398,8 @@ version = "0.0.0" dependencies = [ "anyhow", "codex-apply-patch", - "codex-core", "codex-linux-sandbox", + "codex-utils-home-dir", "dotenvy", "tempfile", "tokio", @@ -1735,6 +1735,7 @@ dependencies = [ "anyhow", "assert_cmd", "clap", + "codex-apply-patch", "codex-arg0", "codex-cloud-requirements", "codex-core", diff --git a/codex-rs/apply-patch/src/lib.rs b/codex-rs/apply-patch/src/lib.rs index f58055f450..1fc60474b9 100644 --- a/codex-rs/apply-patch/src/lib.rs +++ b/codex-rs/apply-patch/src/lib.rs @@ -25,6 +25,15 @@ use crate::invocation::ExtractHeredocError; /// Detailed instructions for gpt-4.1 on how to use the `apply_patch` tool. pub const APPLY_PATCH_TOOL_INSTRUCTIONS: &str = include_str!("../apply_patch_tool_instructions.md"); +/// Special argv[1] flag used when the Codex executable self-invokes to run the +/// internal `apply_patch` path. +/// +/// Although this constant lives in `codex-apply-patch` (to avoid forcing +/// `codex-arg0` to depend on `codex-core`), it is part of the "codex core" +/// process-invocation contract between the apply-patch runtime and the arg0 +/// dispatcher. +pub const CODEX_CORE_APPLY_PATCH_ARG1: &str = "--codex-run-as-apply-patch"; + #[derive(Debug, Error, PartialEq)] pub enum ApplyPatchError { #[error(transparent)] diff --git a/codex-rs/arg0/Cargo.toml b/codex-rs/arg0/Cargo.toml index c82bdd58da..c5d9681327 100644 --- a/codex-rs/arg0/Cargo.toml +++ b/codex-rs/arg0/Cargo.toml @@ -14,8 +14,8 @@ workspace = true [dependencies] anyhow = { workspace = true } codex-apply-patch = { workspace = true } -codex-core = { workspace = true } codex-linux-sandbox = { workspace = true } +codex-utils-home-dir = { workspace = true } dotenvy = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["rt-multi-thread"] } diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index dd89baeff3..3ac7e017f2 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -3,7 +3,8 @@ use std::future::Future; use std::path::Path; use std::path::PathBuf; -use codex_core::CODEX_APPLY_PATCH_ARG1; +use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1; +use codex_utils_home_dir::find_codex_home; #[cfg(unix)] use std::os::unix::fs::symlink; use tempfile::TempDir; @@ -46,7 +47,7 @@ pub fn arg0_dispatch() -> Option { } let argv1 = args.next().unwrap_or_default(); - if argv1 == CODEX_APPLY_PATCH_ARG1 { + if argv1 == CODEX_CORE_APPLY_PATCH_ARG1 { let patch_arg = args.next().and_then(|s| s.to_str().map(str::to_owned)); let exit_code = match patch_arg { Some(patch_arg) => { @@ -58,7 +59,7 @@ pub fn arg0_dispatch() -> Option { } } None => { - eprintln!("Error: {CODEX_APPLY_PATCH_ARG1} requires a UTF-8 PATCH argument."); + eprintln!("Error: {CODEX_CORE_APPLY_PATCH_ARG1} requires a UTF-8 PATCH argument."); 1 } }; @@ -139,7 +140,7 @@ const ILLEGAL_ENV_VAR_PREFIX: &str = "CODEX_"; /// Security: Do not allow `.env` files to create or modify any variables /// with names starting with `CODEX_`. fn load_dotenv() { - if let Ok(codex_home) = codex_core::config::find_codex_home() + if let Ok(codex_home) = find_codex_home() && let Ok(iter) = dotenvy::from_path_iter(codex_home.join(".env")) { set_filtered(iter); @@ -175,7 +176,7 @@ where /// IMPORTANT: This function modifies the PATH environment variable, so it MUST /// be called before multiple threads are spawned. pub fn prepend_path_entry_for_codex_aliases() -> std::io::Result { - let codex_home = codex_core::config::find_codex_home()?; + let codex_home = find_codex_home()?; #[cfg(not(debug_assertions))] { // Guard against placing helpers in system temp directories outside debug builds. @@ -242,7 +243,7 @@ pub fn prepend_path_entry_for_codex_aliases() -> std::io::Result anyhow::Result<()> { fs::write(&absolute_path, "original content\n")?; Command::new(codex_utils_cargo_bin::cargo_bin("codex-exec")?) - .arg(CODEX_APPLY_PATCH_ARG1) + .arg(CODEX_CORE_APPLY_PATCH_ARG1) .arg( r#"*** Begin Patch *** Update File: source.txt From 85ce91a5b329f1e999eca87354e8b80e2ba74f3d Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sat, 21 Feb 2026 00:34:08 -0800 Subject: [PATCH 055/385] refactor(core): move embedded system skills into codex-skills crate (#12435) ## Why `codex-core` was carrying the embedded system-skill sample assets (and a `build.rs` that walks those files to register rerun triggers). Those assets change infrequently, but any change under `codex-core` still ties them to `codex-core`'s build/cache lifecycle. This change moves the embedded system-skills packaging into a dedicated `codex-skills` crate so it can be cached independently. That reduces unnecessary invalidation/rebuild pressure on `codex-core` when the skills bundle is the only thing that changes. ## What Changed - Added a new `codex-rs/skills` crate (`codex-skills`) with: - `Cargo.toml` - `BUILD.bazel` - `build.rs` to track skill asset file changes for Cargo rebuilds - `src/lib.rs` containing the embedded system-skills install/cache logic previously in `codex-core` - Moved the embedded sample skill assets from `codex-rs/core/src/skills/assets/samples` to `codex-rs/skills/src/assets/samples`. - Updated `codex-rs/core/Cargo.toml` to depend on `codex-skills` and removed `codex-core`'s direct `include_dir` dependency. - Removed `codex-core`'s `build.rs`. - Replaced `codex-rs/core/src/skills/system.rs` implementation with a thin re-export wrapper to keep existing `codex-core` call sites unchanged. - Updated workspace manifests/lockfile (`codex-rs/Cargo.toml`, `codex-rs/Cargo.lock`) for the new crate. --- codex-rs/Cargo.lock | 11 +- codex-rs/Cargo.toml | 2 + codex-rs/core/Cargo.toml | 3 +- codex-rs/core/src/skills/system.rs | 198 +----------------- codex-rs/skills/BUILD.bazel | 15 ++ codex-rs/skills/Cargo.toml | 19 ++ codex-rs/{core => skills}/build.rs | 2 +- .../assets/samples/skill-creator/SKILL.md | 0 .../samples/skill-creator/agents/openai.yaml | 0 .../assets/skill-creator-small.svg | 0 .../skill-creator/assets/skill-creator.png | Bin .../assets/samples/skill-creator/license.txt | 0 .../skill-creator/references/openai_yaml.md | 0 .../scripts/generate_openai_yaml.py | 0 .../skill-creator/scripts/init_skill.py | 0 .../skill-creator/scripts/quick_validate.py | 0 .../samples/skill-installer/LICENSE.txt | 0 .../assets/samples/skill-installer/SKILL.md | 0 .../skill-installer/agents/openai.yaml | 0 .../assets/skill-installer-small.svg | 0 .../assets/skill-installer.png | Bin .../skill-installer/scripts/github_utils.py | 0 .../scripts/install-skill-from-github.py | 0 .../skill-installer/scripts/list-skills.py | 0 codex-rs/skills/src/lib.rs | 195 +++++++++++++++++ 25 files changed, 245 insertions(+), 200 deletions(-) create mode 100644 codex-rs/skills/BUILD.bazel create mode 100644 codex-rs/skills/Cargo.toml rename codex-rs/{core => skills}/build.rs (89%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/SKILL.md (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/agents/openai.yaml (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/assets/skill-creator-small.svg (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/assets/skill-creator.png (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/license.txt (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/references/openai_yaml.md (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/scripts/generate_openai_yaml.py (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/scripts/init_skill.py (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-creator/scripts/quick_validate.py (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/LICENSE.txt (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/SKILL.md (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/agents/openai.yaml (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/assets/skill-installer-small.svg (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/assets/skill-installer.png (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/scripts/github_utils.py (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/scripts/install-skill-from-github.py (100%) rename codex-rs/{core/src/skills => skills/src}/assets/samples/skill-installer/scripts/list-skills.py (100%) create mode 100644 codex-rs/skills/src/lib.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 42521a48df..03276a7adb 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1644,6 +1644,7 @@ dependencies = [ "codex-rmcp-client", "codex-secrets", "codex-shell-command", + "codex-skills", "codex-state", "codex-utils-absolute-path", "codex-utils-cargo-bin", @@ -1663,7 +1664,6 @@ dependencies = [ "futures", "http 1.4.0", "image", - "include_dir", "indexmap 2.13.0", "indoc", "insta", @@ -2189,6 +2189,15 @@ dependencies = [ "which", ] +[[package]] +name = "codex-skills" +version = "0.0.0" +dependencies = [ + "codex-utils-absolute-path", + "include_dir", + "thiserror 2.0.18", +] + [[package]] name = "codex-state" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 8ff0c456b8..d23ed3c27b 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -17,6 +17,7 @@ members = [ "cli", "config", "shell-command", + "skills", "core", "hooks", "secrets", @@ -112,6 +113,7 @@ codex-responses-api-proxy = { path = "responses-api-proxy" } codex-rmcp-client = { path = "rmcp-client" } codex-secrets = { path = "secrets" } codex-shell-command = { path = "shell-command" } +codex-skills = { path = "skills" } codex-state = { path = "state" } codex-stdio-to-uds = { path = "stdio-to-uds" } codex-tui = { path = "tui" } diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index bda19d78ea..15f9d7d11c 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -3,7 +3,6 @@ edition.workspace = true license.workspace = true name = "codex-core" version.workspace = true -build = "build.rs" [lib] doctest = false @@ -34,6 +33,7 @@ codex-async-utils = { workspace = true } codex-client = { workspace = true } codex-config = { workspace = true } codex-shell-command = { workspace = true } +codex-skills = { workspace = true } codex-execpolicy = { workspace = true } codex-file-search = { workspace = true } codex-git = { workspace = true } @@ -58,7 +58,6 @@ env-flags = { workspace = true } eventsource-stream = { workspace = true } futures = { workspace = true } http = { workspace = true } -include_dir = { workspace = true } indexmap = { workspace = true } indoc = { workspace = true } keyring = { workspace = true, features = ["crypto-rust"] } diff --git a/codex-rs/core/src/skills/system.rs b/codex-rs/core/src/skills/system.rs index cf8404096d..42b48ea3a5 100644 --- a/codex-rs/core/src/skills/system.rs +++ b/codex-rs/core/src/skills/system.rs @@ -1,196 +1,2 @@ -use codex_utils_absolute_path::AbsolutePathBuf; -use include_dir::Dir; -use std::collections::hash_map::DefaultHasher; -use std::fs; -use std::hash::Hash; -use std::hash::Hasher; -use std::path::Path; -use std::path::PathBuf; - -use thiserror::Error; - -const SYSTEM_SKILLS_DIR: Dir = - include_dir::include_dir!("$CARGO_MANIFEST_DIR/src/skills/assets/samples"); - -const SYSTEM_SKILLS_DIR_NAME: &str = ".system"; -const SKILLS_DIR_NAME: &str = "skills"; -const SYSTEM_SKILLS_MARKER_FILENAME: &str = ".codex-system-skills.marker"; -const SYSTEM_SKILLS_MARKER_SALT: &str = "v1"; - -/// Returns the on-disk cache location for embedded system skills. -/// -/// This is typically located at `CODEX_HOME/skills/.system`. -pub(crate) fn system_cache_root_dir(codex_home: &Path) -> PathBuf { - AbsolutePathBuf::try_from(codex_home) - .and_then(|codex_home| system_cache_root_dir_abs(&codex_home)) - .map(AbsolutePathBuf::into_path_buf) - .unwrap_or_else(|_| { - codex_home - .join(SKILLS_DIR_NAME) - .join(SYSTEM_SKILLS_DIR_NAME) - }) -} - -fn system_cache_root_dir_abs(codex_home: &AbsolutePathBuf) -> std::io::Result { - codex_home - .join(SKILLS_DIR_NAME)? - .join(SYSTEM_SKILLS_DIR_NAME) -} - -/// Installs embedded system skills into `CODEX_HOME/skills/.system`. -/// -/// Clears any existing system skills directory first and then writes the embedded -/// skills directory into place. -/// -/// To avoid doing unnecessary work on every startup, a marker file is written -/// with a fingerprint of the embedded directory. When the marker matches, the -/// install is skipped. -pub(crate) fn install_system_skills(codex_home: &Path) -> Result<(), SystemSkillsError> { - let codex_home = AbsolutePathBuf::try_from(codex_home) - .map_err(|source| SystemSkillsError::io("normalize codex home dir", source))?; - let skills_root_dir = codex_home - .join(SKILLS_DIR_NAME) - .map_err(|source| SystemSkillsError::io("resolve skills root dir", source))?; - fs::create_dir_all(skills_root_dir.as_path()) - .map_err(|source| SystemSkillsError::io("create skills root dir", source))?; - - let dest_system = system_cache_root_dir_abs(&codex_home) - .map_err(|source| SystemSkillsError::io("resolve system skills cache root dir", source))?; - - let marker_path = dest_system - .join(SYSTEM_SKILLS_MARKER_FILENAME) - .map_err(|source| SystemSkillsError::io("resolve system skills marker path", source))?; - let expected_fingerprint = embedded_system_skills_fingerprint(); - if dest_system.as_path().is_dir() - && read_marker(&marker_path).is_ok_and(|marker| marker == expected_fingerprint) - { - return Ok(()); - } - - if dest_system.as_path().exists() { - fs::remove_dir_all(dest_system.as_path()) - .map_err(|source| SystemSkillsError::io("remove existing system skills dir", source))?; - } - - write_embedded_dir(&SYSTEM_SKILLS_DIR, &dest_system)?; - fs::write(marker_path.as_path(), format!("{expected_fingerprint}\n")) - .map_err(|source| SystemSkillsError::io("write system skills marker", source))?; - Ok(()) -} - -fn read_marker(path: &AbsolutePathBuf) -> Result { - Ok(fs::read_to_string(path.as_path()) - .map_err(|source| SystemSkillsError::io("read system skills marker", source))? - .trim() - .to_string()) -} - -fn embedded_system_skills_fingerprint() -> String { - let mut items = Vec::new(); - collect_fingerprint_items(&SYSTEM_SKILLS_DIR, &mut items); - items.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); - - let mut hasher = DefaultHasher::new(); - SYSTEM_SKILLS_MARKER_SALT.hash(&mut hasher); - for (path, contents_hash) in items { - path.hash(&mut hasher); - contents_hash.hash(&mut hasher); - } - format!("{:x}", hasher.finish()) -} - -fn collect_fingerprint_items(dir: &Dir<'_>, items: &mut Vec<(String, Option)>) { - for entry in dir.entries() { - match entry { - include_dir::DirEntry::Dir(subdir) => { - items.push((subdir.path().to_string_lossy().to_string(), None)); - collect_fingerprint_items(subdir, items); - } - include_dir::DirEntry::File(file) => { - let mut file_hasher = DefaultHasher::new(); - file.contents().hash(&mut file_hasher); - items.push(( - file.path().to_string_lossy().to_string(), - Some(file_hasher.finish()), - )); - } - } - } -} - -/// Writes the embedded `include_dir::Dir` to disk under `dest`. -/// -/// Preserves the embedded directory structure. -fn write_embedded_dir(dir: &Dir<'_>, dest: &AbsolutePathBuf) -> Result<(), SystemSkillsError> { - fs::create_dir_all(dest.as_path()) - .map_err(|source| SystemSkillsError::io("create system skills dir", source))?; - - for entry in dir.entries() { - match entry { - include_dir::DirEntry::Dir(subdir) => { - let subdir_dest = dest.join(subdir.path()).map_err(|source| { - SystemSkillsError::io("resolve system skills subdir", source) - })?; - fs::create_dir_all(subdir_dest.as_path()).map_err(|source| { - SystemSkillsError::io("create system skills subdir", source) - })?; - write_embedded_dir(subdir, dest)?; - } - include_dir::DirEntry::File(file) => { - let path = dest.join(file.path()).map_err(|source| { - SystemSkillsError::io("resolve system skills file", source) - })?; - if let Some(parent) = path.as_path().parent() { - fs::create_dir_all(parent).map_err(|source| { - SystemSkillsError::io("create system skills file parent", source) - })?; - } - fs::write(path.as_path(), file.contents()) - .map_err(|source| SystemSkillsError::io("write system skill file", source))?; - } - } - } - - Ok(()) -} - -#[derive(Debug, Error)] -pub(crate) enum SystemSkillsError { - #[error("io error while {action}: {source}")] - Io { - action: &'static str, - #[source] - source: std::io::Error, - }, -} - -impl SystemSkillsError { - fn io(action: &'static str, source: std::io::Error) -> Self { - Self::Io { action, source } - } -} - -#[cfg(test)] -mod tests { - use super::SYSTEM_SKILLS_DIR; - use super::collect_fingerprint_items; - - #[test] - fn fingerprint_traverses_nested_entries() { - let mut items = Vec::new(); - collect_fingerprint_items(&SYSTEM_SKILLS_DIR, &mut items); - let mut paths: Vec = items.into_iter().map(|(path, _)| path).collect(); - paths.sort_unstable(); - - assert!( - paths - .binary_search_by(|probe| probe.as_str().cmp("skill-creator/SKILL.md")) - .is_ok() - ); - assert!( - paths - .binary_search_by(|probe| probe.as_str().cmp("skill-creator/scripts/init_skill.py")) - .is_ok() - ); - } -} +pub(crate) use codex_skills::install_system_skills; +pub(crate) use codex_skills::system_cache_root_dir; diff --git a/codex-rs/skills/BUILD.bazel b/codex-rs/skills/BUILD.bazel new file mode 100644 index 0000000000..1c3fc16954 --- /dev/null +++ b/codex-rs/skills/BUILD.bazel @@ -0,0 +1,15 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "skills", + crate_name = "codex_skills", + compile_data = glob( + include = ["**"], + exclude = [ + "**/* *", + "BUILD.bazel", + "Cargo.toml", + ], + allow_empty = True, + ), +) diff --git a/codex-rs/skills/Cargo.toml b/codex-rs/skills/Cargo.toml new file mode 100644 index 0000000000..babb5a177a --- /dev/null +++ b/codex-rs/skills/Cargo.toml @@ -0,0 +1,19 @@ +[package] +edition.workspace = true +license.workspace = true +name = "codex-skills" +version.workspace = true +build = "build.rs" + +[lib] +doctest = false +name = "codex_skills" +path = "src/lib.rs" + +[lints] +workspace = true + +[dependencies] +codex-utils-absolute-path = { workspace = true } +include_dir = { workspace = true } +thiserror = { workspace = true } diff --git a/codex-rs/core/build.rs b/codex-rs/skills/build.rs similarity index 89% rename from codex-rs/core/build.rs rename to codex-rs/skills/build.rs index 587415a3fd..db4ef68416 100644 --- a/codex-rs/core/build.rs +++ b/codex-rs/skills/build.rs @@ -2,7 +2,7 @@ use std::fs; use std::path::Path; fn main() { - let samples_dir = Path::new("src/skills/assets/samples"); + let samples_dir = Path::new("src/assets/samples"); if !samples_dir.exists() { return; } diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/SKILL.md b/codex-rs/skills/src/assets/samples/skill-creator/SKILL.md similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/SKILL.md rename to codex-rs/skills/src/assets/samples/skill-creator/SKILL.md diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/agents/openai.yaml b/codex-rs/skills/src/assets/samples/skill-creator/agents/openai.yaml similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/agents/openai.yaml rename to codex-rs/skills/src/assets/samples/skill-creator/agents/openai.yaml diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/assets/skill-creator-small.svg b/codex-rs/skills/src/assets/samples/skill-creator/assets/skill-creator-small.svg similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/assets/skill-creator-small.svg rename to codex-rs/skills/src/assets/samples/skill-creator/assets/skill-creator-small.svg diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/assets/skill-creator.png b/codex-rs/skills/src/assets/samples/skill-creator/assets/skill-creator.png similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/assets/skill-creator.png rename to codex-rs/skills/src/assets/samples/skill-creator/assets/skill-creator.png diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/license.txt b/codex-rs/skills/src/assets/samples/skill-creator/license.txt similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/license.txt rename to codex-rs/skills/src/assets/samples/skill-creator/license.txt diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/references/openai_yaml.md b/codex-rs/skills/src/assets/samples/skill-creator/references/openai_yaml.md similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/references/openai_yaml.md rename to codex-rs/skills/src/assets/samples/skill-creator/references/openai_yaml.md diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/scripts/generate_openai_yaml.py b/codex-rs/skills/src/assets/samples/skill-creator/scripts/generate_openai_yaml.py similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/scripts/generate_openai_yaml.py rename to codex-rs/skills/src/assets/samples/skill-creator/scripts/generate_openai_yaml.py diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/scripts/init_skill.py b/codex-rs/skills/src/assets/samples/skill-creator/scripts/init_skill.py similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/scripts/init_skill.py rename to codex-rs/skills/src/assets/samples/skill-creator/scripts/init_skill.py diff --git a/codex-rs/core/src/skills/assets/samples/skill-creator/scripts/quick_validate.py b/codex-rs/skills/src/assets/samples/skill-creator/scripts/quick_validate.py similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-creator/scripts/quick_validate.py rename to codex-rs/skills/src/assets/samples/skill-creator/scripts/quick_validate.py diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/LICENSE.txt b/codex-rs/skills/src/assets/samples/skill-installer/LICENSE.txt similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/LICENSE.txt rename to codex-rs/skills/src/assets/samples/skill-installer/LICENSE.txt diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/SKILL.md b/codex-rs/skills/src/assets/samples/skill-installer/SKILL.md similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/SKILL.md rename to codex-rs/skills/src/assets/samples/skill-installer/SKILL.md diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/agents/openai.yaml b/codex-rs/skills/src/assets/samples/skill-installer/agents/openai.yaml similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/agents/openai.yaml rename to codex-rs/skills/src/assets/samples/skill-installer/agents/openai.yaml diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/assets/skill-installer-small.svg b/codex-rs/skills/src/assets/samples/skill-installer/assets/skill-installer-small.svg similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/assets/skill-installer-small.svg rename to codex-rs/skills/src/assets/samples/skill-installer/assets/skill-installer-small.svg diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/assets/skill-installer.png b/codex-rs/skills/src/assets/samples/skill-installer/assets/skill-installer.png similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/assets/skill-installer.png rename to codex-rs/skills/src/assets/samples/skill-installer/assets/skill-installer.png diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/scripts/github_utils.py b/codex-rs/skills/src/assets/samples/skill-installer/scripts/github_utils.py similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/scripts/github_utils.py rename to codex-rs/skills/src/assets/samples/skill-installer/scripts/github_utils.py diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/scripts/install-skill-from-github.py b/codex-rs/skills/src/assets/samples/skill-installer/scripts/install-skill-from-github.py similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/scripts/install-skill-from-github.py rename to codex-rs/skills/src/assets/samples/skill-installer/scripts/install-skill-from-github.py diff --git a/codex-rs/core/src/skills/assets/samples/skill-installer/scripts/list-skills.py b/codex-rs/skills/src/assets/samples/skill-installer/scripts/list-skills.py similarity index 100% rename from codex-rs/core/src/skills/assets/samples/skill-installer/scripts/list-skills.py rename to codex-rs/skills/src/assets/samples/skill-installer/scripts/list-skills.py diff --git a/codex-rs/skills/src/lib.rs b/codex-rs/skills/src/lib.rs new file mode 100644 index 0000000000..99cde06f6f --- /dev/null +++ b/codex-rs/skills/src/lib.rs @@ -0,0 +1,195 @@ +use codex_utils_absolute_path::AbsolutePathBuf; +use include_dir::Dir; +use std::collections::hash_map::DefaultHasher; +use std::fs; +use std::hash::Hash; +use std::hash::Hasher; +use std::path::Path; +use std::path::PathBuf; + +use thiserror::Error; + +const SYSTEM_SKILLS_DIR: Dir = include_dir::include_dir!("$CARGO_MANIFEST_DIR/src/assets/samples"); + +const SYSTEM_SKILLS_DIR_NAME: &str = ".system"; +const SKILLS_DIR_NAME: &str = "skills"; +const SYSTEM_SKILLS_MARKER_FILENAME: &str = ".codex-system-skills.marker"; +const SYSTEM_SKILLS_MARKER_SALT: &str = "v1"; + +/// Returns the on-disk cache location for embedded system skills. +/// +/// This is typically located at `CODEX_HOME/skills/.system`. +pub fn system_cache_root_dir(codex_home: &Path) -> PathBuf { + AbsolutePathBuf::try_from(codex_home) + .and_then(|codex_home| system_cache_root_dir_abs(&codex_home)) + .map(AbsolutePathBuf::into_path_buf) + .unwrap_or_else(|_| { + codex_home + .join(SKILLS_DIR_NAME) + .join(SYSTEM_SKILLS_DIR_NAME) + }) +} + +fn system_cache_root_dir_abs(codex_home: &AbsolutePathBuf) -> std::io::Result { + codex_home + .join(SKILLS_DIR_NAME)? + .join(SYSTEM_SKILLS_DIR_NAME) +} + +/// Installs embedded system skills into `CODEX_HOME/skills/.system`. +/// +/// Clears any existing system skills directory first and then writes the embedded +/// skills directory into place. +/// +/// To avoid doing unnecessary work on every startup, a marker file is written +/// with a fingerprint of the embedded directory. When the marker matches, the +/// install is skipped. +pub fn install_system_skills(codex_home: &Path) -> Result<(), SystemSkillsError> { + let codex_home = AbsolutePathBuf::try_from(codex_home) + .map_err(|source| SystemSkillsError::io("normalize codex home dir", source))?; + let skills_root_dir = codex_home + .join(SKILLS_DIR_NAME) + .map_err(|source| SystemSkillsError::io("resolve skills root dir", source))?; + fs::create_dir_all(skills_root_dir.as_path()) + .map_err(|source| SystemSkillsError::io("create skills root dir", source))?; + + let dest_system = system_cache_root_dir_abs(&codex_home) + .map_err(|source| SystemSkillsError::io("resolve system skills cache root dir", source))?; + + let marker_path = dest_system + .join(SYSTEM_SKILLS_MARKER_FILENAME) + .map_err(|source| SystemSkillsError::io("resolve system skills marker path", source))?; + let expected_fingerprint = embedded_system_skills_fingerprint(); + if dest_system.as_path().is_dir() + && read_marker(&marker_path).is_ok_and(|marker| marker == expected_fingerprint) + { + return Ok(()); + } + + if dest_system.as_path().exists() { + fs::remove_dir_all(dest_system.as_path()) + .map_err(|source| SystemSkillsError::io("remove existing system skills dir", source))?; + } + + write_embedded_dir(&SYSTEM_SKILLS_DIR, &dest_system)?; + fs::write(marker_path.as_path(), format!("{expected_fingerprint}\n")) + .map_err(|source| SystemSkillsError::io("write system skills marker", source))?; + Ok(()) +} + +fn read_marker(path: &AbsolutePathBuf) -> Result { + Ok(fs::read_to_string(path.as_path()) + .map_err(|source| SystemSkillsError::io("read system skills marker", source))? + .trim() + .to_string()) +} + +fn embedded_system_skills_fingerprint() -> String { + let mut items = Vec::new(); + collect_fingerprint_items(&SYSTEM_SKILLS_DIR, &mut items); + items.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); + + let mut hasher = DefaultHasher::new(); + SYSTEM_SKILLS_MARKER_SALT.hash(&mut hasher); + for (path, contents_hash) in items { + path.hash(&mut hasher); + contents_hash.hash(&mut hasher); + } + format!("{:x}", hasher.finish()) +} + +fn collect_fingerprint_items(dir: &Dir<'_>, items: &mut Vec<(String, Option)>) { + for entry in dir.entries() { + match entry { + include_dir::DirEntry::Dir(subdir) => { + items.push((subdir.path().to_string_lossy().to_string(), None)); + collect_fingerprint_items(subdir, items); + } + include_dir::DirEntry::File(file) => { + let mut file_hasher = DefaultHasher::new(); + file.contents().hash(&mut file_hasher); + items.push(( + file.path().to_string_lossy().to_string(), + Some(file_hasher.finish()), + )); + } + } + } +} + +/// Writes the embedded `include_dir::Dir` to disk under `dest`. +/// +/// Preserves the embedded directory structure. +fn write_embedded_dir(dir: &Dir<'_>, dest: &AbsolutePathBuf) -> Result<(), SystemSkillsError> { + fs::create_dir_all(dest.as_path()) + .map_err(|source| SystemSkillsError::io("create system skills dir", source))?; + + for entry in dir.entries() { + match entry { + include_dir::DirEntry::Dir(subdir) => { + let subdir_dest = dest.join(subdir.path()).map_err(|source| { + SystemSkillsError::io("resolve system skills subdir", source) + })?; + fs::create_dir_all(subdir_dest.as_path()).map_err(|source| { + SystemSkillsError::io("create system skills subdir", source) + })?; + write_embedded_dir(subdir, dest)?; + } + include_dir::DirEntry::File(file) => { + let path = dest.join(file.path()).map_err(|source| { + SystemSkillsError::io("resolve system skills file", source) + })?; + if let Some(parent) = path.as_path().parent() { + fs::create_dir_all(parent).map_err(|source| { + SystemSkillsError::io("create system skills file parent", source) + })?; + } + fs::write(path.as_path(), file.contents()) + .map_err(|source| SystemSkillsError::io("write system skill file", source))?; + } + } + } + + Ok(()) +} + +#[derive(Debug, Error)] +pub enum SystemSkillsError { + #[error("io error while {action}: {source}")] + Io { + action: &'static str, + #[source] + source: std::io::Error, + }, +} + +impl SystemSkillsError { + fn io(action: &'static str, source: std::io::Error) -> Self { + Self::Io { action, source } + } +} + +#[cfg(test)] +mod tests { + use super::SYSTEM_SKILLS_DIR; + use super::collect_fingerprint_items; + + #[test] + fn fingerprint_traverses_nested_entries() { + let mut items = Vec::new(); + collect_fingerprint_items(&SYSTEM_SKILLS_DIR, &mut items); + let mut paths: Vec = items.into_iter().map(|(path, _)| path).collect(); + paths.sort_unstable(); + + assert!( + paths + .binary_search_by(|probe| probe.as_str().cmp("skill-creator/SKILL.md")) + .is_ok() + ); + assert!( + paths + .binary_search_by(|probe| probe.as_str().cmp("skill-creator/scripts/init_skill.py")) + .is_ok() + ); + } +} From f5d7a7456854454a289e5f1179f6e35b2481c622 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sat, 21 Feb 2026 00:44:55 -0800 Subject: [PATCH 056/385] chore: delete empty codex-rs/code file (#12440) This file was added in https://github.com/openai/codex/pull/4195, but I think it may have been a mistake? --- codex-rs/code | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 codex-rs/code diff --git a/codex-rs/code b/codex-rs/code deleted file mode 100644 index e69de29bb2..0000000000 From e7b6f38b58932e1f0d3512e5e69e4ad58d9022f1 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Sat, 21 Feb 2026 00:50:27 -0800 Subject: [PATCH 057/385] Delete AggregatedStream (#12441) Used only in test --- codex-rs/codex-api/src/endpoint/aggregate.rs | 163 ------------------- codex-rs/codex-api/src/endpoint/mod.rs | 1 - codex-rs/codex-api/src/lib.rs | 1 - codex-rs/codex-api/tests/sse_end_to_end.rs | 68 -------- 4 files changed, 233 deletions(-) delete mode 100644 codex-rs/codex-api/src/endpoint/aggregate.rs diff --git a/codex-rs/codex-api/src/endpoint/aggregate.rs b/codex-rs/codex-api/src/endpoint/aggregate.rs deleted file mode 100644 index 6d8e785c82..0000000000 --- a/codex-rs/codex-api/src/endpoint/aggregate.rs +++ /dev/null @@ -1,163 +0,0 @@ -use crate::common::ResponseEvent; -use crate::common::ResponseStream; -use crate::error::ApiError; -use codex_protocol::models::ContentItem; -use codex_protocol::models::ReasoningItemContent; -use codex_protocol::models::ResponseItem; -use futures::Stream; -use std::collections::VecDeque; -use std::pin::Pin; -use std::task::Context; -use std::task::Poll; - -/// Stream adapter that merges token deltas into a single assistant message per turn. -pub struct AggregatedStream { - inner: ResponseStream, - cumulative: String, - cumulative_reasoning: String, - pending: VecDeque, -} - -impl Stream for AggregatedStream { - type Item = Result; - - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.get_mut(); - - if let Some(ev) = this.pending.pop_front() { - return Poll::Ready(Some(Ok(ev))); - } - - loop { - match Pin::new(&mut this.inner).poll_next(cx) { - Poll::Pending => return Poll::Pending, - Poll::Ready(None) => return Poll::Ready(None), - Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err))), - Poll::Ready(Some(Ok(ResponseEvent::OutputItemDone(item)))) => { - let is_assistant_message = matches!( - &item, - ResponseItem::Message { role, .. } if role == "assistant" - ); - - if is_assistant_message { - if this.cumulative.is_empty() - && let ResponseItem::Message { content, .. } = &item - && let Some(text) = content.iter().find_map(|c| match c { - ContentItem::OutputText { text } => Some(text), - _ => None, - }) - { - this.cumulative.push_str(text); - } - continue; - } - - return Poll::Ready(Some(Ok(ResponseEvent::OutputItemDone(item)))); - } - Poll::Ready(Some(Ok(ResponseEvent::ServerReasoningIncluded(included)))) => { - return Poll::Ready(Some(Ok(ResponseEvent::ServerReasoningIncluded(included)))); - } - Poll::Ready(Some(Ok(ResponseEvent::RateLimits(snapshot)))) => { - return Poll::Ready(Some(Ok(ResponseEvent::RateLimits(snapshot)))); - } - Poll::Ready(Some(Ok(ResponseEvent::ModelsEtag(etag)))) => { - return Poll::Ready(Some(Ok(ResponseEvent::ModelsEtag(etag)))); - } - Poll::Ready(Some(Ok(ResponseEvent::ServerModel(model)))) => { - return Poll::Ready(Some(Ok(ResponseEvent::ServerModel(model)))); - } - Poll::Ready(Some(Ok(ResponseEvent::Completed { - response_id, - token_usage, - can_append: _can_append, - }))) => { - let mut emitted_any = false; - - if !this.cumulative_reasoning.is_empty() { - let aggregated_reasoning = ResponseItem::Reasoning { - id: String::new(), - summary: Vec::new(), - content: Some(vec![ReasoningItemContent::ReasoningText { - text: std::mem::take(&mut this.cumulative_reasoning), - }]), - encrypted_content: None, - }; - this.pending - .push_back(ResponseEvent::OutputItemDone(aggregated_reasoning)); - emitted_any = true; - } - - if !this.cumulative.is_empty() { - let aggregated_message = ResponseItem::Message { - id: None, - role: "assistant".to_string(), - content: vec![ContentItem::OutputText { - text: std::mem::take(&mut this.cumulative), - }], - end_turn: None, - phase: None, - }; - this.pending - .push_back(ResponseEvent::OutputItemDone(aggregated_message)); - emitted_any = true; - } - - if emitted_any { - this.pending.push_back(ResponseEvent::Completed { - response_id: response_id.clone(), - token_usage: token_usage.clone(), - can_append: false, - }); - if let Some(ev) = this.pending.pop_front() { - return Poll::Ready(Some(Ok(ev))); - } - } - - return Poll::Ready(Some(Ok(ResponseEvent::Completed { - response_id, - token_usage, - can_append: false, - }))); - } - Poll::Ready(Some(Ok(ResponseEvent::Created))) => continue, - Poll::Ready(Some(Ok(ResponseEvent::OutputTextDelta(delta)))) => { - this.cumulative.push_str(&delta); - continue; - } - Poll::Ready(Some(Ok(ResponseEvent::ReasoningContentDelta { - delta, - content_index: _, - }))) => { - this.cumulative_reasoning.push_str(&delta); - continue; - } - Poll::Ready(Some(Ok(ResponseEvent::ReasoningSummaryDelta { .. }))) => continue, - Poll::Ready(Some(Ok(ResponseEvent::ReasoningSummaryPartAdded { .. }))) => continue, - Poll::Ready(Some(Ok(ResponseEvent::OutputItemAdded(item)))) => { - return Poll::Ready(Some(Ok(ResponseEvent::OutputItemAdded(item)))); - } - } - } - } -} - -pub trait AggregateStreamExt { - fn aggregate(self) -> AggregatedStream; -} - -impl AggregateStreamExt for ResponseStream { - fn aggregate(self) -> AggregatedStream { - AggregatedStream::new(self) - } -} - -impl AggregatedStream { - fn new(inner: ResponseStream) -> Self { - AggregatedStream { - inner, - cumulative: String::new(), - cumulative_reasoning: String::new(), - pending: VecDeque::new(), - } - } -} diff --git a/codex-rs/codex-api/src/endpoint/mod.rs b/codex-rs/codex-api/src/endpoint/mod.rs index 981643904e..6a748e533d 100644 --- a/codex-rs/codex-api/src/endpoint/mod.rs +++ b/codex-rs/codex-api/src/endpoint/mod.rs @@ -1,4 +1,3 @@ -pub mod aggregate; pub mod compact; pub mod memories; pub mod models; diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs index 23c08d7e2b..b9152ec576 100644 --- a/codex-rs/codex-api/src/lib.rs +++ b/codex-rs/codex-api/src/lib.rs @@ -25,7 +25,6 @@ pub use crate::common::ResponseEvent; pub use crate::common::ResponseStream; pub use crate::common::ResponsesApiRequest; pub use crate::common::create_text_param_for_request; -pub use crate::endpoint::aggregate::AggregateStreamExt; pub use crate::endpoint::compact::CompactClient; pub use crate::endpoint::memories::MemoriesClient; pub use crate::endpoint::models::ModelsClient; diff --git a/codex-rs/codex-api/tests/sse_end_to_end.rs b/codex-rs/codex-api/tests/sse_end_to_end.rs index 9f29033783..ca840d1b9f 100644 --- a/codex-rs/codex-api/tests/sse_end_to_end.rs +++ b/codex-rs/codex-api/tests/sse_end_to_end.rs @@ -3,7 +3,6 @@ use std::time::Duration; use anyhow::Result; use async_trait::async_trait; use bytes::Bytes; -use codex_api::AggregateStreamExt; use codex_api::AuthProvider; use codex_api::Provider; use codex_api::ResponseEvent; @@ -14,7 +13,6 @@ use codex_client::Request; use codex_client::Response; use codex_client::StreamResponse; use codex_client::TransportError; -use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; use futures::StreamExt; use http::HeaderMap; @@ -172,69 +170,3 @@ async fn responses_stream_parses_items_and_completed_end_to_end() -> Result<()> Ok(()) } - -#[tokio::test] -async fn responses_stream_aggregates_output_text_deltas() -> Result<()> { - let delta1 = serde_json::json!({ - "type": "response.output_text.delta", - "delta": "Hello, " - }); - - let delta2 = serde_json::json!({ - "type": "response.output_text.delta", - "delta": "world" - }); - - let completed = serde_json::json!({ - "type": "response.completed", - "response": { "id": "resp-agg" } - }); - - let body = build_responses_body(vec![delta1, delta2, completed]); - let transport = FixtureSseTransport::new(body); - let client = ResponsesClient::new(transport, provider("openai"), NoAuth); - - let stream = client - .stream( - serde_json::json!({"echo": true}), - HeaderMap::new(), - Compression::None, - None, - ) - .await?; - - let mut stream = stream.aggregate(); - let mut events = Vec::new(); - while let Some(ev) = stream.next().await { - events.push(ev?); - } - - let events: Vec = events - .into_iter() - .filter(|ev| !matches!(ev, ResponseEvent::RateLimits(_))) - .collect(); - - assert_eq!(events.len(), 2); - - match &events[0] { - ResponseEvent::OutputItemDone(ResponseItem::Message { content, .. }) => { - let mut aggregated = String::new(); - for item in content { - if let ContentItem::OutputText { text } = item { - aggregated.push_str(text); - } - } - assert_eq!(aggregated, "Hello, world"); - } - other => panic!("unexpected first event: {other:?}"), - } - - match &events[1] { - ResponseEvent::Completed { response_id, .. } => { - assert_eq!(response_id, "resp-agg"); - } - other => panic!("unexpected second event: {other:?}"), - } - - Ok(()) -} From b3202cbd581721774b73d2d9c90c56cc43974425 Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Sat, 21 Feb 2026 10:16:34 -0800 Subject: [PATCH 058/385] feat(linux-sandbox): implement proxy-only egress via TCP-UDS-TCP bridge (#11293) ## Summary - Implement Linux proxy-only routing in `codex-rs/linux-sandbox` with a two-stage bridge: host namespace `loopback TCP proxy endpoint -> UDS`, then bwrap netns `loopback TCP listener -> host UDS`. - Add hidden `--proxy-route-spec` plumbing for outer-to-inner stage handoff. - Fail closed in proxy mode when no valid loopback proxy endpoints can be routed. - Introduce explicit network seccomp modes: `Restricted` (legacy restricted networking) and `ProxyRouted` (allow INET/INET6 for routed proxy access, deny `AF_UNIX` and `socketpair`). - Enforce that proxy bridge/routing is bwrap-only by validating `--apply-seccomp-then-exec` requires `--use-bwrap-sandbox`. - Keep landlock-only flows unchanged (no proxy bridge behavior outside bwrap). --------- Co-authored-by: Codex <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com> --- codex-rs/Cargo.lock | 2 + codex-rs/linux-sandbox/Cargo.toml | 2 + codex-rs/linux-sandbox/README.md | 5 + codex-rs/linux-sandbox/src/bwrap.rs | 34 +- codex-rs/linux-sandbox/src/landlock.rs | 168 +++- codex-rs/linux-sandbox/src/lib.rs | 2 + codex-rs/linux-sandbox/src/linux_run_main.rs | 168 ++-- .../linux-sandbox/src/linux_run_main_tests.rs | 159 ++++ codex-rs/linux-sandbox/src/proxy_routing.rs | 796 ++++++++++++++++++ .../tests/suite/managed_proxy.rs | 313 +++++++ codex-rs/linux-sandbox/tests/suite/mod.rs | 1 + 11 files changed, 1501 insertions(+), 149 deletions(-) create mode 100644 codex-rs/linux-sandbox/src/linux_run_main_tests.rs create mode 100644 codex-rs/linux-sandbox/src/proxy_routing.rs create mode 100644 codex-rs/linux-sandbox/tests/suite/managed_proxy.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 03276a7adb..31bc8d65a7 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1921,9 +1921,11 @@ dependencies = [ "pkg-config", "pretty_assertions", "seccompiler", + "serde", "serde_json", "tempfile", "tokio", + "url", ] [[package]] diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index 63af5c81fa..88da2d7479 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -23,7 +23,9 @@ codex-utils-absolute-path = { workspace = true } landlock = { workspace = true } libc = { workspace = true } seccompiler = { workspace = true } +serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } +url = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] pretty_assertions = { workspace = true } diff --git a/codex-rs/linux-sandbox/README.md b/codex-rs/linux-sandbox/README.md index 0abd641708..b03919c963 100644 --- a/codex-rs/linux-sandbox/README.md +++ b/codex-rs/linux-sandbox/README.md @@ -28,6 +28,11 @@ into this binary. - When enabled, the helper isolates the PID namespace via `--unshare-pid`. - When enabled and network is restricted without proxy routing, the helper also isolates the network namespace via `--unshare-net`. +- In managed proxy mode, the helper uses `--unshare-net` plus an internal + TCP->UDS->TCP routing bridge so tool traffic reaches only configured proxy + endpoints. +- In managed proxy mode, after the bridge is live, seccomp blocks new + AF_UNIX/socketpair creation for the user command. - When enabled, it mounts a fresh `/proc` via `--proc /proc` by default, but you can skip this in restrictive container environments with `--no-proc`. diff --git a/codex-rs/linux-sandbox/src/bwrap.rs b/codex-rs/linux-sandbox/src/bwrap.rs index 854774b781..d1fefc1747 100644 --- a/codex-rs/linux-sandbox/src/bwrap.rs +++ b/codex-rs/linux-sandbox/src/bwrap.rs @@ -49,8 +49,8 @@ pub(crate) enum BwrapNetworkMode { Isolated, /// Intended proxy-only mode. /// - /// Bubblewrap does not currently enforce proxy-only egress, so this is - /// treated as isolated for fail-closed behavior. + /// Bubblewrap enforces this by unsharing the network namespace. The + /// proxy-routing bridge is established by the helper process after startup. ProxyOnly, } @@ -323,6 +323,7 @@ fn find_first_non_existent_component(target_path: &Path) -> Option { mod tests { use super::*; use codex_protocol::protocol::SandboxPolicy; + use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; #[test] @@ -373,4 +374,33 @@ mod tests { ] ); } + + #[test] + fn mounts_dev_before_writable_dev_binds() { + let sandbox_policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![AbsolutePathBuf::try_from(Path::new("/dev")).expect("/dev path")], + read_only_access: Default::default(), + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + + let args = create_filesystem_args(&sandbox_policy, Path::new("/")).expect("bwrap fs args"); + assert_eq!( + args, + vec![ + "--ro-bind".to_string(), + "/".to_string(), + "/".to_string(), + "--dev".to_string(), + "/dev".to_string(), + "--bind".to_string(), + "/dev".to_string(), + "/dev".to_string(), + "--bind".to_string(), + "/".to_string(), + "/".to_string(), + ] + ); + } } diff --git a/codex-rs/linux-sandbox/src/landlock.rs b/codex-rs/linux-sandbox/src/landlock.rs index 621bfd5b60..f9477a1264 100644 --- a/codex-rs/linux-sandbox/src/landlock.rs +++ b/codex-rs/linux-sandbox/src/landlock.rs @@ -43,22 +43,26 @@ pub(crate) fn apply_sandbox_policy_to_current_thread( cwd: &Path, apply_landlock_fs: bool, allow_network_for_proxy: bool, + proxy_routed_network: bool, ) -> Result<()> { - let install_network_seccomp = - should_install_network_seccomp(sandbox_policy, allow_network_for_proxy); + let network_seccomp_mode = network_seccomp_mode( + sandbox_policy, + allow_network_for_proxy, + proxy_routed_network, + ); // `PR_SET_NO_NEW_PRIVS` is required for seccomp, but it also prevents // setuid privilege elevation. Many `bwrap` deployments rely on setuid, so // we avoid this unless we need seccomp or we are explicitly using the // legacy Landlock filesystem pipeline. - if install_network_seccomp + if network_seccomp_mode.is_some() || (apply_landlock_fs && !sandbox_policy.has_full_disk_write_access()) { set_no_new_privs()?; } - if install_network_seccomp { - install_network_seccomp_filter_on_current_thread()?; + if let Some(mode) = network_seccomp_mode { + install_network_seccomp_filter_on_current_thread(mode)?; } if apply_landlock_fs && !sandbox_policy.has_full_disk_write_access() { @@ -80,6 +84,12 @@ pub(crate) fn apply_sandbox_policy_to_current_thread( Ok(()) } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum NetworkSeccompMode { + Restricted, + ProxyRouted, +} + fn should_install_network_seccomp( sandbox_policy: &SandboxPolicy, allow_network_for_proxy: bool, @@ -89,6 +99,20 @@ fn should_install_network_seccomp( !sandbox_policy.has_full_network_access() || allow_network_for_proxy } +fn network_seccomp_mode( + sandbox_policy: &SandboxPolicy, + allow_network_for_proxy: bool, + proxy_routed_network: bool, +) -> Option { + if !should_install_network_seccomp(sandbox_policy, allow_network_for_proxy) { + None + } else if proxy_routed_network { + Some(NetworkSeccompMode::ProxyRouted) + } else { + Some(NetworkSeccompMode::Restricted) + } +} + /// Enable `PR_SET_NO_NEW_PRIVS` so seccomp can be applied safely. fn set_no_new_privs() -> Result<()> { let result = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) }; @@ -135,51 +159,87 @@ fn install_filesystem_landlock_rules_on_current_thread( Ok(()) } -/// Installs a seccomp filter that blocks outbound network access except for -/// AF_UNIX domain sockets. +/// Installs a seccomp filter for Linux network sandboxing. /// /// The filter is applied to the current thread so only the sandboxed child /// inherits it. -fn install_network_seccomp_filter_on_current_thread() -> std::result::Result<(), SandboxErr> { +fn install_network_seccomp_filter_on_current_thread( + mode: NetworkSeccompMode, +) -> std::result::Result<(), SandboxErr> { + fn deny_syscall(rules: &mut BTreeMap>, nr: i64) { + rules.insert(nr, vec![]); // empty rule vec = unconditional match + } + // Build rule map. let mut rules: BTreeMap> = BTreeMap::new(); - // Helper – insert unconditional deny rule for syscall number. - let mut deny_syscall = |nr: i64| { - rules.insert(nr, vec![]); // empty rule vec = unconditional match - }; + deny_syscall(&mut rules, libc::SYS_ptrace); + deny_syscall(&mut rules, libc::SYS_io_uring_setup); + deny_syscall(&mut rules, libc::SYS_io_uring_enter); + deny_syscall(&mut rules, libc::SYS_io_uring_register); - deny_syscall(libc::SYS_connect); - deny_syscall(libc::SYS_accept); - deny_syscall(libc::SYS_accept4); - deny_syscall(libc::SYS_bind); - deny_syscall(libc::SYS_listen); - deny_syscall(libc::SYS_getpeername); - deny_syscall(libc::SYS_getsockname); - deny_syscall(libc::SYS_shutdown); - deny_syscall(libc::SYS_sendto); - deny_syscall(libc::SYS_sendmmsg); - // NOTE: allowing recvfrom allows some tools like: `cargo clippy` to run - // with their socketpair + child processes for sub-proc management - // deny_syscall(libc::SYS_recvfrom); - deny_syscall(libc::SYS_recvmmsg); - deny_syscall(libc::SYS_getsockopt); - deny_syscall(libc::SYS_setsockopt); - deny_syscall(libc::SYS_ptrace); - deny_syscall(libc::SYS_io_uring_setup); - deny_syscall(libc::SYS_io_uring_enter); - deny_syscall(libc::SYS_io_uring_register); + match mode { + NetworkSeccompMode::Restricted => { + deny_syscall(&mut rules, libc::SYS_connect); + deny_syscall(&mut rules, libc::SYS_accept); + deny_syscall(&mut rules, libc::SYS_accept4); + deny_syscall(&mut rules, libc::SYS_bind); + deny_syscall(&mut rules, libc::SYS_listen); + deny_syscall(&mut rules, libc::SYS_getpeername); + deny_syscall(&mut rules, libc::SYS_getsockname); + deny_syscall(&mut rules, libc::SYS_shutdown); + deny_syscall(&mut rules, libc::SYS_sendto); + deny_syscall(&mut rules, libc::SYS_sendmmsg); + // NOTE: allowing recvfrom allows some tools like: `cargo clippy` + // to run with their socketpair + child processes for sub-proc + // management. + // deny_syscall(&mut rules, libc::SYS_recvfrom); + deny_syscall(&mut rules, libc::SYS_recvmmsg); + deny_syscall(&mut rules, libc::SYS_getsockopt); + deny_syscall(&mut rules, libc::SYS_setsockopt); - // For `socket` we allow AF_UNIX (arg0 == AF_UNIX) and deny everything else. - let unix_only_rule = SeccompRule::new(vec![SeccompCondition::new( - 0, // first argument (domain) - SeccompCmpArgLen::Dword, - SeccompCmpOp::Ne, - libc::AF_UNIX as u64, - )?])?; + // For `socket` we allow AF_UNIX (arg0 == AF_UNIX) and deny + // everything else. + let unix_only_rule = SeccompRule::new(vec![SeccompCondition::new( + 0, // first argument (domain) + SeccompCmpArgLen::Dword, + SeccompCmpOp::Ne, + libc::AF_UNIX as u64, + )?])?; - rules.insert(libc::SYS_socket, vec![unix_only_rule.clone()]); - rules.insert(libc::SYS_socketpair, vec![unix_only_rule]); // always deny (Unix can use socketpair but fine, keep open?) + rules.insert(libc::SYS_socket, vec![unix_only_rule.clone()]); + rules.insert(libc::SYS_socketpair, vec![unix_only_rule]); + } + NetworkSeccompMode::ProxyRouted => { + // In proxy-routed mode we allow IP sockets in the isolated + // namespace (used to reach the local TCP bridge) but deny all + // other socket families, including AF_UNIX. This prevents + // bypassing the routed bridge via new Unix sockets and narrows the + // socket surface in proxy-only mode. + let deny_non_ip_socket = SeccompRule::new(vec![ + SeccompCondition::new( + 0, + SeccompCmpArgLen::Dword, + SeccompCmpOp::Ne, + libc::AF_INET as u64, + )?, + SeccompCondition::new( + 0, + SeccompCmpArgLen::Dword, + SeccompCmpOp::Ne, + libc::AF_INET6 as u64, + )?, + ])?; + let deny_unix_socketpair = SeccompRule::new(vec![SeccompCondition::new( + 0, + SeccompCmpArgLen::Dword, + SeccompCmpOp::Eq, + libc::AF_UNIX as u64, + )?])?; + rules.insert(libc::SYS_socket, vec![deny_non_ip_socket]); + rules.insert(libc::SYS_socketpair, vec![deny_unix_socketpair]); + } + } let filter = SeccompFilter::new( rules, @@ -203,6 +263,8 @@ fn install_network_seccomp_filter_on_current_thread() -> std::result::Result<(), #[cfg(test)] mod tests { + use super::NetworkSeccompMode; + use super::network_seccomp_mode; use super::should_install_network_seccomp; use codex_protocol::protocol::SandboxPolicy; use pretty_assertions::assert_eq; @@ -234,4 +296,28 @@ mod tests { true )); } + + #[test] + fn managed_proxy_routes_use_proxy_routed_seccomp_mode() { + assert_eq!( + network_seccomp_mode(&SandboxPolicy::DangerFullAccess, true, true), + Some(NetworkSeccompMode::ProxyRouted) + ); + } + + #[test] + fn restricted_network_without_proxy_routing_uses_restricted_mode() { + assert_eq!( + network_seccomp_mode(&SandboxPolicy::new_read_only_policy(), false, false), + Some(NetworkSeccompMode::Restricted) + ); + } + + #[test] + fn full_network_without_managed_proxy_skips_network_seccomp_mode() { + assert_eq!( + network_seccomp_mode(&SandboxPolicy::DangerFullAccess, false, false), + None + ); + } } diff --git a/codex-rs/linux-sandbox/src/lib.rs b/codex-rs/linux-sandbox/src/lib.rs index 3347f3f92d..e364c19251 100644 --- a/codex-rs/linux-sandbox/src/lib.rs +++ b/codex-rs/linux-sandbox/src/lib.rs @@ -10,6 +10,8 @@ mod landlock; #[cfg(target_os = "linux")] mod linux_run_main; #[cfg(target_os = "linux")] +mod proxy_routing; +#[cfg(target_os = "linux")] mod vendored_bwrap; #[cfg(target_os = "linux")] diff --git a/codex-rs/linux-sandbox/src/linux_run_main.rs b/codex-rs/linux-sandbox/src/linux_run_main.rs index 84e7cb34fc..c9fdd06a32 100644 --- a/codex-rs/linux-sandbox/src/linux_run_main.rs +++ b/codex-rs/linux-sandbox/src/linux_run_main.rs @@ -10,6 +10,8 @@ use crate::bwrap::BwrapNetworkMode; use crate::bwrap::BwrapOptions; use crate::bwrap::create_bwrap_command_args; use crate::landlock::apply_sandbox_policy_to_current_thread; +use crate::proxy_routing::activate_proxy_routes_in_netns; +use crate::proxy_routing::prepare_host_proxy_route_spec; use crate::vendored_bwrap::exec_vendored_bwrap; use crate::vendored_bwrap::run_vendored_bwrap_main; @@ -44,11 +46,15 @@ pub struct LandlockCommand { /// Internal compatibility flag. /// /// By default, restricted-network sandboxing uses isolated networking. - /// If set, sandbox setup switches to proxy-only network mode - /// (currently enforced the same as isolated networking). + /// If set, sandbox setup switches to proxy-only network mode with + /// managed routing bridges. #[arg(long = "allow-network-for-proxy", hide = true, default_value_t = false)] pub allow_network_for_proxy: bool, + /// Internal route spec used for managed proxy routing in bwrap mode. + #[arg(long = "proxy-route-spec", hide = true)] + pub proxy_route_spec: Option, + /// When set, skip mounting a fresh `/proc` even though PID isolation is /// still enabled. This is primarily intended for restrictive container /// environments that deny `--proc /proc`. @@ -74,6 +80,7 @@ pub fn run_main() -> ! { use_bwrap_sandbox, apply_seccomp_then_exec, allow_network_for_proxy, + proxy_route_spec, no_proc, command, } = LandlockCommand::parse(); @@ -81,15 +88,26 @@ pub fn run_main() -> ! { if command.is_empty() { panic!("No command specified to execute."); } + ensure_inner_stage_mode_is_valid(apply_seccomp_then_exec, use_bwrap_sandbox); // Inner stage: apply seccomp/no_new_privs after bubblewrap has already // established the filesystem view. if apply_seccomp_then_exec { + if allow_network_for_proxy { + let spec = proxy_route_spec + .as_deref() + .unwrap_or_else(|| panic!("managed proxy mode requires --proxy-route-spec")); + if let Err(err) = activate_proxy_routes_in_netns(spec) { + panic!("error activating Linux proxy routing bridge: {err}"); + } + } + let proxy_routing_active = allow_network_for_proxy; if let Err(e) = apply_sandbox_policy_to_current_thread( &sandbox_policy, &sandbox_policy_cwd, false, allow_network_for_proxy, + proxy_routing_active, ) { panic!("error applying Linux sandbox restrictions: {e:?}"); } @@ -102,6 +120,7 @@ pub fn run_main() -> ! { &sandbox_policy_cwd, false, allow_network_for_proxy, + false, ) { panic!("error applying Linux sandbox restrictions: {e:?}"); } @@ -112,11 +131,20 @@ pub fn run_main() -> ! { // Outer stage: bubblewrap first, then re-enter this binary in the // sandboxed environment to apply seccomp. This path never falls back // to legacy Landlock on failure. + let proxy_route_spec = + if allow_network_for_proxy { + Some(prepare_host_proxy_route_spec().unwrap_or_else(|err| { + panic!("failed to prepare host proxy routing bridge: {err}") + })) + } else { + None + }; let inner = build_inner_seccomp_command( &sandbox_policy_cwd, &sandbox_policy, use_bwrap_sandbox, allow_network_for_proxy, + proxy_route_spec, command, ); run_bwrap_with_proc_fallback( @@ -134,12 +162,19 @@ pub fn run_main() -> ! { &sandbox_policy_cwd, true, allow_network_for_proxy, + false, ) { panic!("error applying legacy Linux sandbox restrictions: {e:?}"); } exec_or_panic(command); } +fn ensure_inner_stage_mode_is_valid(apply_seccomp_then_exec: bool, use_bwrap_sandbox: bool) { + if apply_seccomp_then_exec && !use_bwrap_sandbox { + panic!("--apply-seccomp-then-exec requires --use-bwrap-sandbox"); + } +} + fn run_bwrap_with_proc_fallback( sandbox_policy_cwd: &Path, sandbox_policy: &codex_protocol::protocol::SandboxPolicy, @@ -147,14 +182,15 @@ fn run_bwrap_with_proc_fallback( mount_proc: bool, allow_network_for_proxy: bool, ) -> ! { + let network_mode = bwrap_network_mode(sandbox_policy, allow_network_for_proxy); let mut mount_proc = mount_proc; - if mount_proc && !preflight_proc_mount_support(sandbox_policy_cwd, sandbox_policy) { + if mount_proc && !preflight_proc_mount_support(sandbox_policy_cwd, sandbox_policy, network_mode) + { eprintln!("codex-linux-sandbox: bwrap could not mount /proc; retrying with --no-proc"); mount_proc = false; } - let network_mode = bwrap_network_mode(sandbox_policy, allow_network_for_proxy); let options = BwrapOptions { mount_proc, network_mode, @@ -202,19 +238,29 @@ fn build_bwrap_argv( fn preflight_proc_mount_support( sandbox_policy_cwd: &Path, sandbox_policy: &codex_protocol::protocol::SandboxPolicy, + network_mode: BwrapNetworkMode, ) -> bool { + let preflight_argv = + build_preflight_bwrap_argv(sandbox_policy_cwd, sandbox_policy, network_mode); + let stderr = run_bwrap_in_child_capture_stderr(preflight_argv); + !is_proc_mount_failure(stderr.as_str()) +} + +fn build_preflight_bwrap_argv( + sandbox_policy_cwd: &Path, + sandbox_policy: &codex_protocol::protocol::SandboxPolicy, + network_mode: BwrapNetworkMode, +) -> Vec { let preflight_command = vec![resolve_true_command()]; - let preflight_argv = build_bwrap_argv( + build_bwrap_argv( preflight_command, sandbox_policy, sandbox_policy_cwd, BwrapOptions { mount_proc: true, - network_mode: BwrapNetworkMode::FullAccess, + network_mode, }, - ); - let stderr = run_bwrap_in_child_capture_stderr(preflight_argv); - !is_proc_mount_failure(stderr.as_str()) + ) } fn resolve_true_command() -> String { @@ -318,6 +364,7 @@ fn build_inner_seccomp_command( sandbox_policy: &codex_protocol::protocol::SandboxPolicy, use_bwrap_sandbox: bool, allow_network_for_proxy: bool, + proxy_route_spec: Option, command: Vec, ) -> Vec { let current_exe = match std::env::current_exe() { @@ -342,6 +389,10 @@ fn build_inner_seccomp_command( } if allow_network_for_proxy { inner.push("--allow-network-for-proxy".to_string()); + let proxy_route_spec = proxy_route_spec + .unwrap_or_else(|| panic!("managed proxy mode requires a proxy route spec")); + inner.push("--proxy-route-spec".to_string()); + inner.push(proxy_route_spec); } inner.push("--".to_string()); inner.extend(command); @@ -371,100 +422,5 @@ fn exec_or_panic(command: Vec) -> ! { panic!("Failed to execvp {}: {err}", command[0].as_str()); } -#[cfg(test)] -mod tests { - use super::*; - use codex_protocol::protocol::SandboxPolicy; - use pretty_assertions::assert_eq; - - #[test] - fn detects_proc_mount_invalid_argument_failure() { - let stderr = "bwrap: Can't mount proc on /newroot/proc: Invalid argument"; - assert_eq!(is_proc_mount_failure(stderr), true); - } - - #[test] - fn detects_proc_mount_operation_not_permitted_failure() { - let stderr = "bwrap: Can't mount proc on /newroot/proc: Operation not permitted"; - assert_eq!(is_proc_mount_failure(stderr), true); - } - - #[test] - fn detects_proc_mount_permission_denied_failure() { - let stderr = "bwrap: Can't mount proc on /newroot/proc: Permission denied"; - assert_eq!(is_proc_mount_failure(stderr), true); - } - - #[test] - fn ignores_non_proc_mount_errors() { - let stderr = "bwrap: Can't bind mount /dev/null: Operation not permitted"; - assert_eq!(is_proc_mount_failure(stderr), false); - } - - #[test] - fn inserts_bwrap_argv0_before_command_separator() { - let argv = build_bwrap_argv( - vec!["/bin/true".to_string()], - &SandboxPolicy::new_read_only_policy(), - Path::new("/"), - BwrapOptions { - mount_proc: true, - network_mode: BwrapNetworkMode::FullAccess, - }, - ); - assert_eq!( - argv, - vec![ - "bwrap".to_string(), - "--new-session".to_string(), - "--die-with-parent".to_string(), - "--ro-bind".to_string(), - "/".to_string(), - "/".to_string(), - "--dev".to_string(), - "/dev".to_string(), - "--unshare-pid".to_string(), - "--proc".to_string(), - "/proc".to_string(), - "--argv0".to_string(), - "codex-linux-sandbox".to_string(), - "--".to_string(), - "/bin/true".to_string(), - ] - ); - } - - #[test] - fn inserts_unshare_net_when_network_isolation_requested() { - let argv = build_bwrap_argv( - vec!["/bin/true".to_string()], - &SandboxPolicy::new_read_only_policy(), - Path::new("/"), - BwrapOptions { - mount_proc: true, - network_mode: BwrapNetworkMode::Isolated, - }, - ); - assert_eq!(argv.contains(&"--unshare-net".to_string()), true); - } - - #[test] - fn inserts_unshare_net_when_proxy_only_network_mode_requested() { - let argv = build_bwrap_argv( - vec!["/bin/true".to_string()], - &SandboxPolicy::new_read_only_policy(), - Path::new("/"), - BwrapOptions { - mount_proc: true, - network_mode: BwrapNetworkMode::ProxyOnly, - }, - ); - assert_eq!(argv.contains(&"--unshare-net".to_string()), true); - } - - #[test] - fn proxy_only_mode_takes_precedence_over_full_network_policy() { - let mode = bwrap_network_mode(&SandboxPolicy::DangerFullAccess, true); - assert_eq!(mode, BwrapNetworkMode::ProxyOnly); - } -} +#[path = "linux_run_main_tests.rs"] +mod tests; diff --git a/codex-rs/linux-sandbox/src/linux_run_main_tests.rs b/codex-rs/linux-sandbox/src/linux_run_main_tests.rs new file mode 100644 index 0000000000..11471afbe7 --- /dev/null +++ b/codex-rs/linux-sandbox/src/linux_run_main_tests.rs @@ -0,0 +1,159 @@ +#[cfg(test)] +use super::*; +#[cfg(test)] +use codex_protocol::protocol::SandboxPolicy; + +#[test] +fn detects_proc_mount_invalid_argument_failure() { + let stderr = "bwrap: Can't mount proc on /newroot/proc: Invalid argument"; + assert!(is_proc_mount_failure(stderr)); +} + +#[test] +fn detects_proc_mount_operation_not_permitted_failure() { + let stderr = "bwrap: Can't mount proc on /newroot/proc: Operation not permitted"; + assert!(is_proc_mount_failure(stderr)); +} + +#[test] +fn detects_proc_mount_permission_denied_failure() { + let stderr = "bwrap: Can't mount proc on /newroot/proc: Permission denied"; + assert!(is_proc_mount_failure(stderr)); +} + +#[test] +fn ignores_non_proc_mount_errors() { + let stderr = "bwrap: Can't bind mount /dev/null: Operation not permitted"; + assert!(!is_proc_mount_failure(stderr)); +} + +#[test] +fn inserts_bwrap_argv0_before_command_separator() { + let argv = build_bwrap_argv( + vec!["/bin/true".to_string()], + &SandboxPolicy::new_read_only_policy(), + Path::new("/"), + BwrapOptions { + mount_proc: true, + network_mode: BwrapNetworkMode::FullAccess, + }, + ); + assert_eq!( + argv, + vec![ + "bwrap".to_string(), + "--new-session".to_string(), + "--die-with-parent".to_string(), + "--ro-bind".to_string(), + "/".to_string(), + "/".to_string(), + "--dev".to_string(), + "/dev".to_string(), + "--unshare-pid".to_string(), + "--proc".to_string(), + "/proc".to_string(), + "--argv0".to_string(), + "codex-linux-sandbox".to_string(), + "--".to_string(), + "/bin/true".to_string(), + ] + ); +} + +#[test] +fn inserts_unshare_net_when_network_isolation_requested() { + let argv = build_bwrap_argv( + vec!["/bin/true".to_string()], + &SandboxPolicy::new_read_only_policy(), + Path::new("/"), + BwrapOptions { + mount_proc: true, + network_mode: BwrapNetworkMode::Isolated, + }, + ); + assert!(argv.contains(&"--unshare-net".to_string())); +} + +#[test] +fn inserts_unshare_net_when_proxy_only_network_mode_requested() { + let argv = build_bwrap_argv( + vec!["/bin/true".to_string()], + &SandboxPolicy::new_read_only_policy(), + Path::new("/"), + BwrapOptions { + mount_proc: true, + network_mode: BwrapNetworkMode::ProxyOnly, + }, + ); + assert!(argv.contains(&"--unshare-net".to_string())); +} + +#[test] +fn proxy_only_mode_takes_precedence_over_full_network_policy() { + let mode = bwrap_network_mode(&SandboxPolicy::DangerFullAccess, true); + assert_eq!(mode, BwrapNetworkMode::ProxyOnly); +} + +#[test] +fn managed_proxy_preflight_argv_is_wrapped_for_full_access_policy() { + let mode = bwrap_network_mode(&SandboxPolicy::DangerFullAccess, true); + let argv = build_preflight_bwrap_argv(Path::new("/"), &SandboxPolicy::DangerFullAccess, mode); + assert!(argv.iter().any(|arg| arg == "--")); +} + +#[test] +fn managed_proxy_inner_command_includes_route_spec() { + let args = build_inner_seccomp_command( + Path::new("/tmp"), + &SandboxPolicy::new_read_only_policy(), + true, + true, + Some("{\"routes\":[]}".to_string()), + vec!["/bin/true".to_string()], + ); + + assert!(args.iter().any(|arg| arg == "--proxy-route-spec")); + assert!(args.iter().any(|arg| arg == "{\"routes\":[]}")); +} + +#[test] +fn non_managed_inner_command_omits_route_spec() { + let args = build_inner_seccomp_command( + Path::new("/tmp"), + &SandboxPolicy::new_read_only_policy(), + true, + false, + None, + vec!["/bin/true".to_string()], + ); + + assert!(!args.iter().any(|arg| arg == "--proxy-route-spec")); +} + +#[test] +fn managed_proxy_inner_command_requires_route_spec() { + let result = std::panic::catch_unwind(|| { + build_inner_seccomp_command( + Path::new("/tmp"), + &SandboxPolicy::new_read_only_policy(), + true, + true, + None, + vec!["/bin/true".to_string()], + ) + }); + assert!(result.is_err()); +} + +#[test] +fn apply_seccomp_then_exec_without_bwrap_panics() { + let result = std::panic::catch_unwind(|| ensure_inner_stage_mode_is_valid(true, false)); + assert!(result.is_err()); +} + +#[test] +fn valid_inner_stage_modes_do_not_panic() { + ensure_inner_stage_mode_is_valid(false, false); + ensure_inner_stage_mode_is_valid(false, true); + ensure_inner_stage_mode_is_valid(true, true); +} diff --git a/codex-rs/linux-sandbox/src/proxy_routing.rs b/codex-rs/linux-sandbox/src/proxy_routing.rs new file mode 100644 index 0000000000..f57472c8a1 --- /dev/null +++ b/codex-rs/linux-sandbox/src/proxy_routing.rs @@ -0,0 +1,796 @@ +use serde::Deserialize; +use serde::Serialize; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::fs::DirBuilder; +use std::fs::File; +use std::fs::Permissions; +use std::io; +use std::io::Read; +use std::io::Write; +use std::net::IpAddr; +use std::net::Ipv4Addr; +use std::net::SocketAddr; +use std::net::TcpListener; +use std::net::TcpStream; +use std::os::fd::FromRawFd; +use std::os::unix::fs::DirBuilderExt; +use std::os::unix::fs::PermissionsExt; +use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; +use std::path::Path; +use std::path::PathBuf; +use std::time::Duration; +use url::Url; + +const PROXY_ENV_KEYS: &[&str] = &[ + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "FTP_PROXY", + "YARN_HTTP_PROXY", + "YARN_HTTPS_PROXY", + "NPM_CONFIG_HTTP_PROXY", + "NPM_CONFIG_HTTPS_PROXY", + "NPM_CONFIG_PROXY", + "BUNDLE_HTTP_PROXY", + "BUNDLE_HTTPS_PROXY", + "PIP_PROXY", + "DOCKER_HTTP_PROXY", + "DOCKER_HTTPS_PROXY", +]; + +const PROXY_SOCKET_DIR_PREFIX: &str = "codex-linux-sandbox-proxy-"; +const HOST_BRIDGE_READY: u8 = 1; +const LOOPBACK_INTERFACE_NAME: &[u8] = b"lo"; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct ProxyRouteSpec { + routes: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +struct ProxyRouteEntry { + env_key: String, + uds_path: PathBuf, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct PlannedProxyRoute { + env_key: String, + endpoint: SocketAddr, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ProxyRoutePlan { + routes: Vec, + has_proxy_config: bool, +} + +pub(crate) fn prepare_host_proxy_route_spec() -> io::Result { + let env: HashMap = std::env::vars().collect(); + let plan = plan_proxy_routes(&env); + + if plan.routes.is_empty() { + let message = if plan.has_proxy_config { + "managed proxy mode requires parseable loopback proxy endpoints" + } else { + "managed proxy mode requires proxy environment variables" + }; + return Err(io::Error::new(io::ErrorKind::InvalidInput, message)); + } + + let socket_parent_dir = proxy_socket_parent_dir(); + let _ = cleanup_stale_proxy_socket_dirs_in(socket_parent_dir.as_path()); + + let socket_dir = create_proxy_socket_dir()?; + let mut socket_by_endpoint: BTreeMap = BTreeMap::new(); + let mut next_index = 0usize; + for route in &plan.routes { + if socket_by_endpoint.contains_key(&route.endpoint) { + continue; + } + let socket_path = socket_dir.join(format!("proxy-route-{next_index}.sock")); + next_index += 1; + socket_by_endpoint.insert(route.endpoint, socket_path); + } + + let mut host_bridge_pids = Vec::with_capacity(socket_by_endpoint.len()); + for (endpoint, socket_path) in &socket_by_endpoint { + host_bridge_pids.push(spawn_host_bridge(*endpoint, socket_path)?); + } + spawn_proxy_socket_dir_cleanup_worker(socket_dir, host_bridge_pids)?; + + let mut routes = Vec::with_capacity(plan.routes.len()); + for route in plan.routes { + let Some(uds_path) = socket_by_endpoint.get(&route.endpoint) else { + return Err(io::Error::other(format!( + "missing UDS path for endpoint {}", + route.endpoint + ))); + }; + routes.push(ProxyRouteEntry { + env_key: route.env_key, + uds_path: uds_path.clone(), + }); + } + + serde_json::to_string(&ProxyRouteSpec { routes }).map_err(io::Error::other) +} + +pub(crate) fn activate_proxy_routes_in_netns(serialized_spec: &str) -> io::Result<()> { + let spec: ProxyRouteSpec = serde_json::from_str(serialized_spec).map_err(io::Error::other)?; + + if spec.routes.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "proxy routing spec contained no routes", + )); + } + + let mut local_port_by_uds_path: BTreeMap = BTreeMap::new(); + for route in &spec.routes { + if local_port_by_uds_path.contains_key(&route.uds_path) { + continue; + } + let local_port = spawn_local_bridge(route.uds_path.as_path())?; + local_port_by_uds_path.insert(route.uds_path.clone(), local_port); + } + + for route in spec.routes { + let Some(local_port) = local_port_by_uds_path.get(&route.uds_path) else { + return Err(io::Error::other(format!( + "missing local bridge port for UDS path {}", + route.uds_path.display() + ))); + }; + let original_value = std::env::var(&route.env_key).map_err(|_| { + io::Error::new( + io::ErrorKind::NotFound, + format!("missing proxy env key {}", route.env_key), + ) + })?; + let Some(rewritten) = rewrite_proxy_env_value(&original_value, *local_port) else { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("could not rewrite proxy URL for env key {}", route.env_key), + )); + }; + // SAFETY: this helper process is single-threaded at this point, and + // env mutation happens before execing the user command. + unsafe { + std::env::set_var(route.env_key, rewritten); + } + } + + Ok(()) +} + +fn plan_proxy_routes(env: &HashMap) -> ProxyRoutePlan { + let mut routes = Vec::new(); + let mut has_proxy_config = false; + + for (key, value) in env { + if !is_proxy_env_key(key) { + continue; + } + + let trimmed = value.trim(); + if trimmed.is_empty() { + continue; + } + has_proxy_config = true; + + let Some(endpoint) = parse_loopback_proxy_endpoint(trimmed) else { + continue; + }; + routes.push(PlannedProxyRoute { + env_key: key.clone(), + endpoint, + }); + } + + routes.sort_by(|left, right| left.env_key.cmp(&right.env_key)); + ProxyRoutePlan { + routes, + has_proxy_config, + } +} + +fn is_proxy_env_key(key: &str) -> bool { + let upper = key.to_ascii_uppercase(); + PROXY_ENV_KEYS.contains(&upper.as_str()) +} + +fn parse_loopback_proxy_endpoint(proxy_url: &str) -> Option { + let candidate = if proxy_url.contains("://") { + proxy_url.to_string() + } else { + format!("http://{proxy_url}") + }; + + let parsed = Url::parse(&candidate).ok()?; + let host = parsed.host_str()?; + if !is_loopback_host(host) { + return None; + } + + let scheme = parsed.scheme().to_ascii_lowercase(); + let port = parsed + .port() + .unwrap_or_else(|| default_proxy_port(scheme.as_str())); + if port == 0 { + return None; + } + + let ip = if host.eq_ignore_ascii_case("localhost") { + IpAddr::V4(Ipv4Addr::LOCALHOST) + } else { + host.parse::().ok()? + }; + if ip.is_loopback() { + Some(SocketAddr::new(ip, port)) + } else { + None + } +} + +fn is_loopback_host(host: &str) -> bool { + host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" +} + +fn default_proxy_port(scheme: &str) -> u16 { + match scheme { + "https" => 443, + "socks5" | "socks5h" | "socks4" | "socks4a" => 1080, + _ => 80, + } +} + +fn rewrite_proxy_env_value(proxy_url: &str, local_port: u16) -> Option { + let had_scheme = proxy_url.contains("://"); + let candidate = if had_scheme { + proxy_url.to_string() + } else { + format!("http://{proxy_url}") + }; + + let mut parsed = Url::parse(&candidate).ok()?; + parsed.set_host(Some("127.0.0.1")).ok()?; + parsed.set_port(Some(local_port)).ok()?; + let mut rewritten = parsed.to_string(); + if !had_scheme { + rewritten = rewritten + .strip_prefix("http://") + .unwrap_or(rewritten.as_str()) + .to_string(); + } + if !proxy_url.ends_with('/') + && !proxy_url.contains('?') + && !proxy_url.contains('#') + && rewritten.ends_with('/') + { + rewritten.pop(); + } + Some(rewritten) +} + +fn create_proxy_socket_dir() -> io::Result { + let temp_dir = proxy_socket_parent_dir(); + let pid = std::process::id(); + for attempt in 0..128 { + let candidate = temp_dir.join(format!("{PROXY_SOCKET_DIR_PREFIX}{pid}-{attempt}")); + // The bridge UDS paths live under a shared temp root, so the per-run + // directory should not be traversable by other processes. + let mut dir_builder = DirBuilder::new(); + dir_builder.mode(0o700); + match dir_builder.create(&candidate) { + Ok(()) => return Ok(candidate), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(err) => return Err(err), + } + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!( + "failed to allocate proxy routing temp dir under {}", + temp_dir.display() + ), + )) +} + +fn proxy_socket_parent_dir() -> PathBuf { + if let Some(codex_home) = std::env::var_os("CODEX_HOME") { + let candidate = PathBuf::from(codex_home).join("tmp"); + if ensure_private_proxy_socket_parent_dir(candidate.as_path()).is_ok() { + return candidate; + } + } + std::env::temp_dir() +} + +fn ensure_private_proxy_socket_parent_dir(path: &Path) -> io::Result<()> { + let mut dir_builder = DirBuilder::new(); + dir_builder.recursive(true); + dir_builder.mode(0o700); + match dir_builder.create(path) { + Ok(()) => {} + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {} + Err(err) => return Err(err), + } + std::fs::set_permissions(path, Permissions::from_mode(0o700)) +} + +fn cleanup_stale_proxy_socket_dirs_in(temp_dir: &Path) -> io::Result<()> { + for entry in std::fs::read_dir(temp_dir)? { + let entry = match entry { + Ok(entry) => entry, + Err(_) => continue, + }; + let file_type = match entry.file_type() { + Ok(file_type) => file_type, + Err(_) => continue, + }; + if !file_type.is_dir() { + continue; + } + + let file_name = entry.file_name(); + let file_name = file_name.to_string_lossy(); + let Some(owner_pid) = parse_proxy_socket_dir_owner_pid(file_name.as_ref()) else { + continue; + }; + if is_pid_alive(owner_pid) { + continue; + } + + let _ = cleanup_proxy_socket_dir(entry.path().as_path()); + } + + Ok(()) +} + +fn parse_proxy_socket_dir_owner_pid(file_name: &str) -> Option { + let suffix = file_name.strip_prefix(PROXY_SOCKET_DIR_PREFIX)?; + let (pid_raw, _) = suffix.split_once('-')?; + pid_raw.parse::().ok().filter(|pid| *pid != 0) +} + +fn is_pid_alive(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { + return false; + }; + is_pid_alive_raw(pid) +} + +fn is_pid_alive_raw(pid: libc::pid_t) -> bool { + let status = unsafe { libc::kill(pid, 0) }; + if status == 0 { + return true; + } + let err = io::Error::last_os_error(); + !matches!(err.raw_os_error(), Some(libc::ESRCH)) +} + +fn spawn_proxy_socket_dir_cleanup_worker( + socket_dir: PathBuf, + host_bridge_pids: Vec, +) -> io::Result<()> { + let pid = unsafe { libc::fork() }; + if pid < 0 { + return Err(io::Error::last_os_error()); + } + + if pid == 0 { + loop { + if host_bridge_pids + .iter() + .copied() + .all(|bridge_pid| !is_pid_alive_raw(bridge_pid)) + { + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + + let _ = cleanup_proxy_socket_dir(socket_dir.as_path()); + unsafe { libc::_exit(0) }; + } + + Ok(()) +} + +fn cleanup_proxy_socket_dir(socket_dir: &Path) -> io::Result<()> { + for _ in 0..20 { + match std::fs::remove_dir_all(socket_dir) { + Ok(()) => return Ok(()), + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(_) => std::thread::sleep(Duration::from_millis(100)), + } + } + + match std::fs::remove_dir_all(socket_dir) { + Ok(()) => Ok(()), + Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()), + Err(err) => Err(err), + } +} + +fn spawn_host_bridge(endpoint: SocketAddr, uds_path: &Path) -> io::Result { + let (read_fd, write_fd) = create_ready_pipe()?; + let pid = unsafe { libc::fork() }; + if pid < 0 { + let err = io::Error::last_os_error(); + close_fd(read_fd)?; + close_fd(write_fd)?; + return Err(err); + } + + if pid == 0 { + if close_fd(read_fd).is_err() { + unsafe { libc::_exit(1) }; + } + let result = run_host_bridge(endpoint, uds_path, write_fd); + if result.is_err() { + unsafe { libc::_exit(1) }; + } + unsafe { libc::_exit(0) }; + } + + close_fd(write_fd)?; + let mut ready = [0_u8; 1]; + let mut read_file = unsafe { File::from_raw_fd(read_fd) }; + read_file.read_exact(&mut ready)?; + if ready[0] != HOST_BRIDGE_READY { + return Err(io::Error::other( + "host bridge did not acknowledge readiness", + )); + } + Ok(pid) +} + +fn run_host_bridge(endpoint: SocketAddr, uds_path: &Path, ready_fd: libc::c_int) -> io::Result<()> { + set_parent_death_signal()?; + if uds_path.exists() { + std::fs::remove_file(uds_path)?; + } + let listener = UnixListener::bind(uds_path)?; + + let mut ready_file = unsafe { File::from_raw_fd(ready_fd) }; + ready_file.write_all(&[HOST_BRIDGE_READY])?; + drop(ready_file); + + loop { + let (unix_stream, _) = listener.accept()?; + std::thread::spawn(move || { + let tcp_stream = match TcpStream::connect(endpoint) { + Ok(stream) => stream, + Err(_) => return, + }; + let _ = proxy_bidirectional(tcp_stream, unix_stream); + }); + } +} + +fn spawn_local_bridge(uds_path: &Path) -> io::Result { + let (read_fd, write_fd) = create_ready_pipe()?; + let pid = unsafe { libc::fork() }; + if pid < 0 { + let err = io::Error::last_os_error(); + close_fd(read_fd)?; + close_fd(write_fd)?; + return Err(err); + } + + if pid == 0 { + if close_fd(read_fd).is_err() { + unsafe { libc::_exit(1) }; + } + let result = run_local_bridge(uds_path, write_fd); + if result.is_err() { + unsafe { libc::_exit(1) }; + } + unsafe { libc::_exit(0) }; + } + + close_fd(write_fd)?; + let mut port_bytes = [0_u8; 2]; + let mut read_file = unsafe { File::from_raw_fd(read_fd) }; + read_file.read_exact(&mut port_bytes)?; + Ok(u16::from_be_bytes(port_bytes)) +} + +fn run_local_bridge(uds_path: &Path, ready_fd: libc::c_int) -> io::Result<()> { + set_parent_death_signal()?; + let listener = bind_local_loopback_listener()?; + let port = listener.local_addr()?.port(); + + let mut ready_file = unsafe { File::from_raw_fd(ready_fd) }; + ready_file.write_all(&port.to_be_bytes())?; + drop(ready_file); + + let uds_path = uds_path.to_path_buf(); + loop { + let (tcp_stream, _) = listener.accept()?; + let socket_path = uds_path.clone(); + std::thread::spawn(move || { + let unix_stream = match UnixStream::connect(socket_path) { + Ok(stream) => stream, + Err(_) => return, + }; + let _ = proxy_bidirectional(tcp_stream, unix_stream); + }); + } +} + +fn bind_local_loopback_listener() -> io::Result { + match TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) { + Ok(listener) => Ok(listener), + Err(bind_err) => { + let should_retry_after_lo_up = matches!( + bind_err.raw_os_error(), + Some(errno) if errno == libc::EADDRNOTAVAIL || errno == libc::ENETUNREACH + ); + if !should_retry_after_lo_up { + return Err(bind_err); + } + + ensure_loopback_interface_up()?; + TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + } + } +} + +fn ensure_loopback_interface_up() -> io::Result<()> { + let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + + let mut ifreq = unsafe { std::mem::zeroed::() }; + for (index, byte) in LOOPBACK_INTERFACE_NAME.iter().copied().enumerate() { + ifreq.ifr_name[index] = byte as libc::c_char; + } + + let read_flags_result = + unsafe { libc::ioctl(fd, libc::SIOCGIFFLAGS as libc::Ioctl, &mut ifreq) }; + if read_flags_result < 0 { + let err = io::Error::last_os_error(); + let _ = close_fd(fd); + return Err(err); + } + + let current_flags = unsafe { ifreq.ifr_ifru.ifru_flags }; + let up_flag = libc::IFF_UP as libc::c_short; + if (current_flags & up_flag) != up_flag { + ifreq.ifr_ifru.ifru_flags = current_flags | up_flag; + let set_flags_result = + unsafe { libc::ioctl(fd, libc::SIOCSIFFLAGS as libc::Ioctl, &ifreq) }; + if set_flags_result < 0 { + let err = io::Error::last_os_error(); + let _ = close_fd(fd); + return Err(err); + } + } + + let mut addr_req = unsafe { std::mem::zeroed::() }; + for (index, byte) in LOOPBACK_INTERFACE_NAME.iter().copied().enumerate() { + addr_req.ifr_name[index] = byte as libc::c_char; + } + let loopback_addr = libc::sockaddr_in { + sin_family: libc::AF_INET as libc::sa_family_t, + sin_port: 0, + sin_addr: libc::in_addr { + s_addr: libc::htonl(libc::INADDR_LOOPBACK), + }, + sin_zero: [0; 8], + }; + unsafe { + addr_req.ifr_ifru.ifru_addr = + *(&loopback_addr as *const libc::sockaddr_in as *const libc::sockaddr); + } + let set_addr_result = unsafe { libc::ioctl(fd, libc::SIOCSIFADDR as libc::Ioctl, &addr_req) }; + if set_addr_result < 0 { + let err = io::Error::last_os_error(); + let allow_existing_or_immutable_addr = + matches!(err.raw_os_error(), Some(libc::EEXIST | libc::EPERM)); + if !allow_existing_or_immutable_addr { + let _ = close_fd(fd); + return Err(err); + } + } + + close_fd(fd) +} + +fn set_parent_death_signal() -> io::Result<()> { + let res = unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) }; + if res != 0 { + Err(io::Error::last_os_error()) + } else if unsafe { libc::getppid() } == 1 { + Err(io::Error::other("parent process already exited")) + } else { + Ok(()) + } +} + +fn proxy_bidirectional(mut tcp_stream: TcpStream, mut unix_stream: UnixStream) -> io::Result<()> { + let mut tcp_reader = tcp_stream.try_clone()?; + let mut unix_writer = unix_stream.try_clone()?; + let tcp_to_unix = std::thread::spawn(move || std::io::copy(&mut tcp_reader, &mut unix_writer)); + let unix_to_tcp = std::io::copy(&mut unix_stream, &mut tcp_stream); + let tcp_to_unix = tcp_to_unix + .join() + .map_err(|_| io::Error::other("bridge thread panicked"))?; + tcp_to_unix?; + unix_to_tcp?; + Ok(()) +} + +fn create_ready_pipe() -> io::Result<(libc::c_int, libc::c_int)> { + let mut pipe_fds = [0; 2]; + let res = unsafe { libc::pipe2(pipe_fds.as_mut_ptr(), libc::O_CLOEXEC) }; + if res != 0 { + return Err(io::Error::last_os_error()); + } + Ok((pipe_fds[0], pipe_fds[1])) +} + +fn close_fd(fd: libc::c_int) -> io::Result<()> { + let res = unsafe { libc::close(fd) }; + if res < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::PROXY_SOCKET_DIR_PREFIX; + use super::ProxyRouteEntry; + use super::ProxyRouteSpec; + use super::cleanup_proxy_socket_dir; + use super::cleanup_stale_proxy_socket_dirs_in; + use super::default_proxy_port; + use super::is_proxy_env_key; + use super::parse_loopback_proxy_endpoint; + use super::parse_proxy_socket_dir_owner_pid; + use super::plan_proxy_routes; + use super::rewrite_proxy_env_value; + use pretty_assertions::assert_eq; + use std::collections::HashMap; + use std::net::SocketAddr; + use std::path::PathBuf; + + #[test] + fn recognizes_proxy_env_keys_case_insensitively() { + assert_eq!(is_proxy_env_key("HTTP_PROXY"), true); + assert_eq!(is_proxy_env_key("http_proxy"), true); + assert_eq!(is_proxy_env_key("PATH"), false); + } + + #[test] + fn parses_loopback_proxy_endpoint() { + let endpoint = parse_loopback_proxy_endpoint("http://127.0.0.1:43128"); + assert_eq!( + endpoint, + Some( + "127.0.0.1:43128" + .parse::() + .expect("valid socket") + ) + ); + } + + #[test] + fn ignores_non_loopback_proxy_endpoint() { + assert_eq!( + parse_loopback_proxy_endpoint("http://example.com:3128"), + None + ); + } + + #[test] + fn plan_proxy_routes_only_includes_valid_loopback_endpoints() { + let mut env = HashMap::new(); + env.insert( + "HTTP_PROXY".to_string(), + "http://127.0.0.1:43128".to_string(), + ); + env.insert( + "HTTPS_PROXY".to_string(), + "http://example.com:3128".to_string(), + ); + env.insert("PATH".to_string(), "/usr/bin".to_string()); + + let plan = plan_proxy_routes(&env); + assert_eq!(plan.has_proxy_config, true); + assert_eq!(plan.routes.len(), 1); + assert_eq!(plan.routes[0].env_key, "HTTP_PROXY"); + assert_eq!( + plan.routes[0].endpoint, + "127.0.0.1:43128" + .parse::() + .expect("valid socket") + ); + } + + #[test] + fn rewrites_proxy_url_to_local_loopback_port() { + let rewritten = + rewrite_proxy_env_value("socks5h://127.0.0.1:8081", 43210).expect("rewritten value"); + assert_eq!(rewritten, "socks5h://127.0.0.1:43210"); + } + + #[test] + fn default_proxy_ports_match_expected_schemes() { + assert_eq!(default_proxy_port("http"), 80); + assert_eq!(default_proxy_port("https"), 443); + assert_eq!(default_proxy_port("socks5h"), 1080); + } + + #[test] + fn cleanup_proxy_socket_dir_removes_bridge_artifacts() { + let root = tempfile::tempdir().expect("tempdir should create"); + let socket_dir = root.path().join("codex-linux-sandbox-proxy-test"); + std::fs::create_dir(&socket_dir).expect("socket dir should create"); + let marker = socket_dir.join("bridge.sock"); + std::fs::write(&marker, b"test").expect("marker should write"); + + cleanup_proxy_socket_dir(socket_dir.as_path()).expect("cleanup should succeed"); + + assert_eq!(socket_dir.exists(), false); + } + + #[test] + fn proxy_route_spec_serialization_omits_proxy_urls() { + let spec = ProxyRouteSpec { + routes: vec![ProxyRouteEntry { + env_key: "HTTP_PROXY".to_string(), + uds_path: PathBuf::from("/tmp/proxy-route-0.sock"), + }], + }; + let serialized = serde_json::to_string(&spec).expect("proxy route spec should serialize"); + + assert_eq!( + serialized, + r#"{"routes":[{"env_key":"HTTP_PROXY","uds_path":"/tmp/proxy-route-0.sock"}]}"# + ); + } + + #[test] + fn parse_proxy_socket_dir_owner_pid_reads_owner_pid() { + assert_eq!( + parse_proxy_socket_dir_owner_pid("codex-linux-sandbox-proxy-1234-0"), + Some(1234) + ); + assert_eq!( + parse_proxy_socket_dir_owner_pid("codex-linux-sandbox-proxy-x"), + None + ); + assert_eq!(parse_proxy_socket_dir_owner_pid("not-a-proxy-dir"), None); + } + + #[test] + fn cleanup_stale_proxy_socket_dirs_removes_dead_pid_directories() { + let root = tempfile::tempdir().expect("tempdir should create"); + let dead_dir = root + .path() + .join(format!("{PROXY_SOCKET_DIR_PREFIX}{}-0", u32::MAX)); + std::fs::create_dir(&dead_dir).expect("dead dir should create"); + + let alive_dir = root + .path() + .join(format!("{PROXY_SOCKET_DIR_PREFIX}{}-1", std::process::id())); + std::fs::create_dir(&alive_dir).expect("alive dir should create"); + + let unrelated_dir = root.path().join("unrelated-proxy-dir"); + std::fs::create_dir(&unrelated_dir).expect("unrelated dir should create"); + + cleanup_stale_proxy_socket_dirs_in(root.path()).expect("stale cleanup should succeed"); + + assert_eq!(dead_dir.exists(), false); + assert_eq!(alive_dir.exists(), true); + assert_eq!(unrelated_dir.exists(), true); + } +} diff --git a/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs new file mode 100644 index 0000000000..e27930cdb5 --- /dev/null +++ b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs @@ -0,0 +1,313 @@ +#![cfg(target_os = "linux")] +#![allow(clippy::unwrap_used)] + +use codex_core::config::types::ShellEnvironmentPolicy; +use codex_core::exec_env::create_env; +use codex_protocol::protocol::SandboxPolicy; +use pretty_assertions::assert_eq; +use std::collections::HashMap; +use std::io::Read; +use std::io::Write; +use std::net::Ipv4Addr; +use std::net::TcpListener; +use std::process::Output; +use std::process::Stdio; +use std::time::Duration; +use tokio::process::Command; + +const BWRAP_UNAVAILABLE_ERR: &str = "build-time bubblewrap is not available in this build."; +const NETWORK_TIMEOUT_MS: u64 = 4_000; +const MANAGED_PROXY_PERMISSION_ERR_SNIPPETS: &[&str] = &[ + "loopback: Failed RTM_NEWADDR", + "loopback: Failed RTM_NEWLINK", + "setting up uid map: Permission denied", + "No permissions to create a new namespace", + "error isolating Linux network namespace for proxy mode", +]; + +const PROXY_ENV_KEYS: &[&str] = &[ + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "FTP_PROXY", + "YARN_HTTP_PROXY", + "YARN_HTTPS_PROXY", + "NPM_CONFIG_HTTP_PROXY", + "NPM_CONFIG_HTTPS_PROXY", + "NPM_CONFIG_PROXY", + "BUNDLE_HTTP_PROXY", + "BUNDLE_HTTPS_PROXY", + "PIP_PROXY", + "DOCKER_HTTP_PROXY", + "DOCKER_HTTPS_PROXY", +]; + +fn create_env_from_core_vars() -> HashMap { + let policy = ShellEnvironmentPolicy::default(); + create_env(&policy, None) +} + +fn strip_proxy_env(env: &mut HashMap) { + for key in PROXY_ENV_KEYS { + env.remove(*key); + let lower = key.to_ascii_lowercase(); + env.remove(lower.as_str()); + } +} + +fn is_bwrap_unavailable_output(output: &Output) -> bool { + String::from_utf8_lossy(&output.stderr).contains(BWRAP_UNAVAILABLE_ERR) +} + +async fn should_skip_bwrap_tests() -> bool { + let mut env = create_env_from_core_vars(); + strip_proxy_env(&mut env); + + let output = run_linux_sandbox_direct( + &["bash", "-c", "true"], + &SandboxPolicy::new_read_only_policy(), + false, + env, + NETWORK_TIMEOUT_MS, + ) + .await; + is_bwrap_unavailable_output(&output) +} + +fn is_managed_proxy_permission_error(stderr: &str) -> bool { + MANAGED_PROXY_PERMISSION_ERR_SNIPPETS + .iter() + .any(|snippet| stderr.contains(snippet)) +} + +async fn managed_proxy_skip_reason() -> Option { + if should_skip_bwrap_tests().await { + return Some("vendored bwrap was not built in this environment".to_string()); + } + + let mut env = create_env_from_core_vars(); + strip_proxy_env(&mut env); + env.insert("HTTP_PROXY".to_string(), "http://127.0.0.1:9".to_string()); + + let output = run_linux_sandbox_direct( + &["bash", "-c", "true"], + &SandboxPolicy::DangerFullAccess, + true, + env, + NETWORK_TIMEOUT_MS, + ) + .await; + if output.status.success() { + return None; + } + + let stderr = String::from_utf8_lossy(&output.stderr); + if is_managed_proxy_permission_error(stderr.as_ref()) { + return Some(format!( + "managed proxy requires kernel namespace privileges unavailable here: {}", + stderr.trim() + )); + } + + None +} + +async fn run_linux_sandbox_direct( + command: &[&str], + sandbox_policy: &SandboxPolicy, + allow_network_for_proxy: bool, + env: HashMap, + timeout_ms: u64, +) -> Output { + let cwd = match std::env::current_dir() { + Ok(cwd) => cwd, + Err(err) => panic!("cwd should exist: {err}"), + }; + let policy_json = match serde_json::to_string(sandbox_policy) { + Ok(policy_json) => policy_json, + Err(err) => panic!("policy should serialize: {err}"), + }; + + let mut args = vec![ + "--sandbox-policy-cwd".to_string(), + cwd.to_string_lossy().to_string(), + "--sandbox-policy".to_string(), + policy_json, + "--use-bwrap-sandbox".to_string(), + ]; + if allow_network_for_proxy { + args.push("--allow-network-for-proxy".to_string()); + } + args.push("--".to_string()); + args.extend(command.iter().map(|entry| (*entry).to_string())); + + let mut cmd = Command::new(env!("CARGO_BIN_EXE_codex-linux-sandbox")); + cmd.args(args) + .current_dir(cwd) + .env_clear() + .envs(env) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let output = match tokio::time::timeout(Duration::from_millis(timeout_ms), cmd.output()).await { + Ok(output) => output, + Err(err) => panic!("sandbox command should not time out: {err}"), + }; + match output { + Ok(output) => output, + Err(err) => panic!("sandbox command should execute: {err}"), + } +} + +#[tokio::test] +async fn managed_proxy_mode_fails_closed_without_proxy_env() { + if let Some(skip_reason) = managed_proxy_skip_reason().await { + eprintln!("skipping managed proxy test: {skip_reason}"); + return; + } + + let mut env = create_env_from_core_vars(); + strip_proxy_env(&mut env); + + let output = run_linux_sandbox_direct( + &["bash", "-c", "true"], + &SandboxPolicy::DangerFullAccess, + true, + env, + NETWORK_TIMEOUT_MS, + ) + .await; + + assert_eq!(output.status.success(), false); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("managed proxy mode requires proxy environment variables"), + "expected fail-closed managed-proxy message, got stderr: {stderr}" + ); +} + +#[tokio::test] +async fn managed_proxy_mode_routes_through_bridge_and_blocks_direct_egress() { + if let Some(skip_reason) = managed_proxy_skip_reason().await { + eprintln!("skipping managed proxy test: {skip_reason}"); + return; + } + + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind proxy listener"); + let proxy_port = listener + .local_addr() + .expect("proxy listener local addr") + .port(); + let (request_tx, request_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept proxy connection"); + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("set read timeout"); + let mut buf = [0_u8; 4096]; + let read = stream.read(&mut buf).expect("read proxy request"); + let request = String::from_utf8_lossy(&buf[..read]).to_string(); + request_tx.send(request).expect("send proxy request"); + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK") + .expect("write proxy response"); + }); + + let mut env = create_env_from_core_vars(); + strip_proxy_env(&mut env); + env.insert( + "HTTP_PROXY".to_string(), + format!("http://127.0.0.1:{proxy_port}"), + ); + + let routed_output = run_linux_sandbox_direct( + &[ + "bash", + "-c", + "proxy=\"${HTTP_PROXY#*://}\"; host=\"${proxy%%:*}\"; port=\"${proxy##*:}\"; exec 3<>/dev/tcp/${host}/${port}; printf 'GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n' >&3; IFS= read -r line <&3; printf '%s\\n' \"$line\"", + ], + &SandboxPolicy::DangerFullAccess, + true, + env.clone(), + NETWORK_TIMEOUT_MS, + ) + .await; + + assert_eq!( + routed_output.status.success(), + true, + "expected routed command to execute successfully; status={:?}; stdout={}; stderr={}", + routed_output.status.code(), + String::from_utf8_lossy(&routed_output.stdout), + String::from_utf8_lossy(&routed_output.stderr) + ); + let stdout = String::from_utf8_lossy(&routed_output.stdout); + assert!( + stdout.contains("HTTP/1.1 200 OK"), + "expected bridge-routed proxy response, got stdout: {stdout}" + ); + + let request = request_rx + .recv_timeout(Duration::from_secs(3)) + .expect("expected proxy request"); + assert!( + request.contains("GET http://example.com/ HTTP/1.1"), + "expected HTTP proxy absolute-form request, got request: {request}" + ); + + let direct_egress_output = run_linux_sandbox_direct( + &["bash", "-c", "echo hi > /dev/tcp/192.0.2.1/80"], + &SandboxPolicy::DangerFullAccess, + true, + env, + NETWORK_TIMEOUT_MS, + ) + .await; + assert_eq!(direct_egress_output.status.success(), false); +} + +#[tokio::test] +async fn managed_proxy_mode_denies_af_unix_creation_for_user_command() { + if let Some(skip_reason) = managed_proxy_skip_reason().await { + eprintln!("skipping managed proxy test: {skip_reason}"); + return; + } + + let python_available = Command::new("bash") + .arg("-c") + .arg("command -v python3 >/dev/null") + .status() + .await + .expect("python3 probe should execute") + .success(); + if !python_available { + eprintln!("skipping managed proxy AF_UNIX test: python3 is unavailable"); + return; + } + + let mut env = create_env_from_core_vars(); + strip_proxy_env(&mut env); + env.insert("HTTP_PROXY".to_string(), "http://127.0.0.1:9".to_string()); + + let output = run_linux_sandbox_direct( + &[ + "python3", + "-c", + "import socket,sys\ntry:\n socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\nexcept PermissionError:\n sys.exit(0)\nexcept OSError:\n sys.exit(2)\nsys.exit(1)\n", + ], + &SandboxPolicy::DangerFullAccess, + true, + env, + NETWORK_TIMEOUT_MS, + ) + .await; + + assert_eq!( + output.status.code(), + Some(0), + "expected AF_UNIX creation to be denied cleanly for user command; status={:?}; stdout={}; stderr={}", + output.status.code(), + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} diff --git a/codex-rs/linux-sandbox/tests/suite/mod.rs b/codex-rs/linux-sandbox/tests/suite/mod.rs index d2a6bfa148..8ef44a61a4 100644 --- a/codex-rs/linux-sandbox/tests/suite/mod.rs +++ b/codex-rs/linux-sandbox/tests/suite/mod.rs @@ -1,2 +1,3 @@ // Aggregates all former standalone integration tests as modules. mod landlock; +mod managed_proxy; From 5a635f3427101033564070a35a5e99ae534cd941 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Sat, 21 Feb 2026 11:39:02 -0800 Subject: [PATCH 059/385] profile-level model_catalog_json overrie (#12410) enable `model-catalog_json` config value on `ConfigProfile` as well --- codex-rs/core/config.schema.json | 8 ++++++++ codex-rs/core/src/config/mod.rs | 7 ++++++- codex-rs/core/src/config/profile.rs | 2 ++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 23963196a1..addbcbe313 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -440,6 +440,14 @@ "model": { "type": "string" }, + "model_catalog_json": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "Optional path to a JSON model catalog (applied on startup only)." + }, "model_instructions_file": { "allOf": [ { diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index ca3978b73d..ddc5aa9cdd 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1908,7 +1908,12 @@ impl Config { let review_model = override_review_model.or(cfg.review_model); let check_for_update_on_startup = cfg.check_for_update_on_startup.unwrap_or(true); - let model_catalog = load_model_catalog(cfg.model_catalog_json.clone())?; + let model_catalog = load_model_catalog( + config_profile + .model_catalog_json + .clone() + .or(cfg.model_catalog_json.clone()), + )?; let log_dir = cfg .log_dir diff --git a/codex-rs/core/src/config/profile.rs b/codex-rs/core/src/config/profile.rs index 3c7d575cdc..61b02adcd0 100644 --- a/codex-rs/core/src/config/profile.rs +++ b/codex-rs/core/src/config/profile.rs @@ -27,6 +27,8 @@ pub struct ConfigProfile { pub plan_mode_reasoning_effort: Option, pub model_reasoning_summary: Option, pub model_verbosity: Option, + /// Optional path to a JSON model catalog (applied on startup only). + pub model_catalog_json: Option, pub personality: Option, pub chatgpt_base_url: Option, /// Optional path to a file containing model instructions. From a6b2bacb5b8bb485a52d979d6d53bf1e639811d7 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Sat, 21 Feb 2026 11:55:03 -0800 Subject: [PATCH 060/385] Prevent replayed runtime events from forcing active status (#12420) Fixes #11852 Resume replay was applying transient runtime events (`TurnStarted`, `StreamError`) as if they were live, which could leave the TUI stuck in a stale `Working` / `Reconnecting...` state after resuming an interrupted reconnect. This change makes replay transcript-oriented for these events by: - skipping retry-status restoration for replayed non-stream events - ignoring replayed `TurnStarted` for task-running state - ignoring replayed `StreamError` for reconnect/status UI Also adds TUI regression tests and snapshot coverage for the interrupted reconnect replay case. --- codex-rs/tui/src/chatwidget.rs | 36 +++- ...ayed_interrupted_reconnect_footer_row.snap | 6 + codex-rs/tui/src/chatwidget/tests.rs | 154 ++++++++++++++++++ 3 files changed, 189 insertions(+), 7 deletions(-) create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__replayed_interrupted_reconnect_footer_row.snap diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 238a60730c..9bfddd18e4 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -832,6 +832,12 @@ fn remap_placeholders_for_message(message: UserMessage, next_label: &mut usize) } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ReplayKind { + ResumeInitialMessages, + ThreadSnapshot, +} + impl ChatWidget { /// Synchronize the bottom-pane "task running" indicator with the current lifecycles. /// @@ -4002,13 +4008,13 @@ impl ChatWidget { continue; } // `id: None` indicates a synthetic/fake id coming from replay. - self.dispatch_event_msg(None, msg, true); + self.dispatch_event_msg(None, msg, Some(ReplayKind::ResumeInitialMessages)); } } pub(crate) fn handle_codex_event(&mut self, event: Event) { let Event { id, msg } = event; - self.dispatch_event_msg(Some(id), msg, false); + self.dispatch_event_msg(Some(id), msg, None); } pub(crate) fn handle_codex_event_replay(&mut self, event: Event) { @@ -4016,7 +4022,7 @@ impl ChatWidget { if matches!(msg, EventMsg::ShutdownComplete) { return; } - self.dispatch_event_msg(None, msg, true); + self.dispatch_event_msg(None, msg, Some(ReplayKind::ThreadSnapshot)); } /// Dispatch a protocol `EventMsg` to the appropriate handler. @@ -4024,9 +4030,17 @@ impl ChatWidget { /// `id` is `Some` for live events and `None` for replayed events from /// `replay_initial_messages()`. Callers should treat `None` as a "fake" id /// that must not be used to correlate follow-up actions. - fn dispatch_event_msg(&mut self, id: Option, msg: EventMsg, from_replay: bool) { + fn dispatch_event_msg( + &mut self, + id: Option, + msg: EventMsg, + replay_kind: Option, + ) { + let from_replay = replay_kind.is_some(); + let is_resume_initial_replay = + matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages)); let is_stream_error = matches!(&msg, EventMsg::StreamError(_)); - if !is_stream_error { + if !is_resume_initial_replay && !is_stream_error { self.restore_retry_status_header_if_present(); } @@ -4061,7 +4075,11 @@ impl ChatWidget { self.on_agent_reasoning_final(); } EventMsg::AgentReasoningSectionBreak(_) => self.on_reasoning_section_break(), - EventMsg::TurnStarted(_) => self.on_task_started(), + EventMsg::TurnStarted(_) => { + if !is_resume_initial_replay { + self.on_task_started(); + } + } EventMsg::TurnComplete(TurnCompleteEvent { last_agent_message, .. }) => self.on_task_complete(last_agent_message, from_replay), @@ -4151,7 +4169,11 @@ impl ChatWidget { message, additional_details, .. - }) => self.on_stream_error(message, additional_details), + }) => { + if !is_resume_initial_replay { + self.on_stream_error(message, additional_details); + } + } EventMsg::UserMessage(ev) => { if from_replay { self.on_user_message_event(ev); diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__replayed_interrupted_reconnect_footer_row.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__replayed_interrupted_reconnect_footer_row.snap new file mode 100644 index 0000000000..eb3183f574 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__replayed_interrupted_reconnect_footer_row.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/chatwidget/tests.rs +assertion_line: 7060 +expression: header +--- +› Ask Codex to do anything diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index b9f5ddf814..e634d3ba39 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -7228,6 +7228,160 @@ async fn stream_error_updates_status_indicator() { assert_eq!(status.details(), Some(details)); } +#[tokio::test] +async fn replayed_turn_started_does_not_mark_task_running() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + + chat.replay_initial_messages(vec![EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: ModeKind::Default, + })]); + + assert!(!chat.bottom_pane.is_task_running()); + assert!(chat.bottom_pane.status_widget().is_none()); +} + +#[tokio::test] +async fn thread_snapshot_replayed_turn_started_marks_task_running() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + + chat.handle_codex_event_replay(Event { + id: "turn-1".into(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: ModeKind::Default, + }), + }); + + drain_insert_history(&mut rx); + assert!(chat.bottom_pane.is_task_running()); + let status = chat + .bottom_pane + .status_widget() + .expect("status indicator should be visible"); + assert_eq!(status.header(), "Working"); +} + +#[tokio::test] +async fn replayed_stream_error_does_not_set_retry_status_or_status_indicator() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + chat.set_status_header("Idle".to_string()); + + chat.replay_initial_messages(vec![EventMsg::StreamError(StreamErrorEvent { + message: "Reconnecting... 2/5".to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + additional_details: Some("Idle timeout waiting for SSE".to_string()), + })]); + + let cells = drain_insert_history(&mut rx); + assert!( + cells.is_empty(), + "expected no history cell for replayed StreamError event" + ); + assert_eq!(chat.current_status_header, "Idle"); + assert!(chat.retry_status_header.is_none()); + assert!(chat.bottom_pane.status_widget().is_none()); +} + +#[tokio::test] +async fn thread_snapshot_replayed_stream_recovery_restores_previous_status_header() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + + chat.handle_codex_event_replay(Event { + id: "task".into(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: ModeKind::Default, + }), + }); + drain_insert_history(&mut rx); + + chat.handle_codex_event_replay(Event { + id: "retry".into(), + msg: EventMsg::StreamError(StreamErrorEvent { + message: "Reconnecting... 1/5".to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + additional_details: None, + }), + }); + drain_insert_history(&mut rx); + + chat.handle_codex_event_replay(Event { + id: "delta".into(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "hello".to_string(), + }), + }); + + let status = chat + .bottom_pane + .status_widget() + .expect("status indicator should be visible"); + assert_eq!(status.header(), "Working"); + assert_eq!(status.details(), None); + assert!(chat.retry_status_header.is_none()); +} + +#[tokio::test] +async fn resume_replay_interrupted_reconnect_does_not_leave_stale_working_state() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + chat.set_status_header("Idle".to_string()); + + chat.replay_initial_messages(vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: ModeKind::Default, + }), + EventMsg::StreamError(StreamErrorEvent { + message: "Reconnecting... 1/5".to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + additional_details: None, + }), + EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "hello".to_string(), + }), + ]); + + let cells = drain_insert_history(&mut rx); + assert!( + cells.is_empty(), + "expected no history cells for replayed interrupted reconnect sequence" + ); + assert!(!chat.bottom_pane.is_task_running()); + assert!(chat.bottom_pane.status_widget().is_none()); + assert_eq!(chat.current_status_header, "Idle"); + assert!(chat.retry_status_header.is_none()); +} + +#[tokio::test] +async fn replayed_interrupted_reconnect_footer_row_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + + chat.replay_initial_messages(vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: ModeKind::Default, + }), + EventMsg::StreamError(StreamErrorEvent { + message: "Reconnecting... 2/5".to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + additional_details: Some("Idle timeout waiting for SSE".to_string()), + }), + ]); + + let header = render_bottom_first_row(&chat, 80); + assert!( + !header.contains("Reconnecting") && !header.contains("Working"), + "expected replayed interrupted reconnect to avoid active status row, got {header:?}" + ); + assert_snapshot!("replayed_interrupted_reconnect_footer_row", header); +} + #[tokio::test] async fn stream_error_restores_hidden_status_indicator() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; From b17148f13a2e261d36884ab3fa105d235426bf5a Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Sat, 21 Feb 2026 12:08:04 -0800 Subject: [PATCH 061/385] Prefer v2 websockets if available (#12428) And also cleanup settings flow to avoid reading many separate flags. --------- Co-authored-by: Codex --- codex-rs/core/src/client.rs | 136 ++++++++++-------- codex-rs/core/src/codex.rs | 20 +-- codex-rs/core/src/lib.rs | 2 + codex-rs/core/tests/responses_headers.rs | 10 +- codex-rs/core/tests/suite/client.rs | 4 +- .../core/tests/suite/client_websockets.rs | 60 +++++++- 6 files changed, 153 insertions(+), 79 deletions(-) diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 6f33910ce7..5239841041 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -92,6 +92,7 @@ use crate::auth::RefreshTokenError; use crate::client_common::Prompt; use crate::client_common::ResponseEvent; use crate::client_common::ResponseStream; +use crate::config::Config; use crate::default_client::build_reqwest_client; use crate::error::CodexErr; use crate::error::Result; @@ -107,6 +108,28 @@ pub const X_CODEX_TURN_METADATA_HEADER: &str = "x-codex-turn-metadata"; pub const X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER: &str = "x-responsesapi-include-timing-metrics"; const RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResponsesWebsocketVersion { + V1, + V2, +} + +pub fn ws_version_from_features(config: &Config) -> Option { + match ( + config + .features + .enabled(crate::features::Feature::ResponsesWebsockets), + config + .features + .enabled(crate::features::Feature::ResponsesWebsocketsV2), + ) { + (_, true) => Some(ResponsesWebsocketVersion::V2), + (true, false) => Some(ResponsesWebsocketVersion::V1), + (false, false) => None, + } +} + /// Session-scoped state shared by all [`ModelClient`] clones. /// /// This is intentionally kept minimal so `ModelClient` does not need to hold a full `Config`. Most @@ -118,8 +141,7 @@ struct ModelClientState { provider: ModelProviderInfo, session_source: SessionSource, model_verbosity: Option, - enable_responses_websockets: bool, - enable_responses_websockets_v2: bool, + responses_websocket_version: Option, enable_request_compression: bool, include_timing_metrics: bool, beta_features_header: Option, @@ -209,14 +231,11 @@ impl ModelClient { provider: ModelProviderInfo, session_source: SessionSource, model_verbosity: Option, - enable_responses_websockets: bool, - enable_responses_websockets_v2: bool, + responses_websocket_version: Option, enable_request_compression: bool, include_timing_metrics: bool, beta_features_header: Option, ) -> Self { - let enable_responses_websockets = - enable_responses_websockets || enable_responses_websockets_v2; Self { state: Arc::new(ModelClientState { auth_manager, @@ -224,8 +243,7 @@ impl ModelClient { provider, session_source, model_verbosity, - enable_responses_websockets, - enable_responses_websockets_v2, + responses_websocket_version, enable_request_compression, include_timing_metrics, beta_features_header, @@ -367,26 +385,25 @@ impl ModelClient { request_telemetry } - /// Returns whether this session is configured to use Responses-over-WebSocket. + /// Returns the active Responses-over-WebSocket version for this session. /// /// This combines provider capability and feature gating; both must be true for websocket paths /// to be eligible. - pub fn responses_websocket_enabled(&self, model_info: &ModelInfo) -> bool { - self.state.provider.supports_websockets - && (self.state.enable_responses_websockets - || self.state.enable_responses_websockets_v2 - || model_info.prefer_websockets) - } - - fn responses_websockets_v2_enabled(&self) -> bool { - self.state.enable_responses_websockets_v2 - } - - /// Returns whether websocket transport has been permanently disabled for this session. /// - /// Once set by fallback activation, subsequent turns must stay on HTTP transport. - fn websockets_disabled(&self) -> bool { - self.state.disable_websockets.load(Ordering::Relaxed) + /// If websockets are only enabled via model preference (no explicit feature flag), default to + /// v1 behavior. + pub fn active_ws_version(&self, model_info: &ModelInfo) -> Option { + if !self.state.provider.supports_websockets + || self.state.disable_websockets.load(Ordering::Relaxed) + { + return None; + } + + match self.state.responses_websocket_version { + Some(version) => Some(version), + None if model_info.prefer_websockets => Some(ResponsesWebsocketVersion::V1), + None => None, + } } /// Returns auth + provider configuration resolved from the current session auth state. @@ -419,10 +436,12 @@ impl ModelClient { otel_manager: &OtelManager, api_provider: codex_api::Provider, api_auth: CoreAuthProvider, + ws_version: ResponsesWebsocketVersion, turn_state: Option>>, turn_metadata_header: Option<&str>, ) -> std::result::Result { - let headers = self.build_websocket_headers(turn_state.as_ref(), turn_metadata_header); + let headers = + self.build_websocket_headers(ws_version, turn_state.as_ref(), turn_metadata_header); let websocket_telemetry = ModelClientSession::build_websocket_telemetry(otel_manager); ApiWebSocketResponsesClient::new(api_provider, api_auth) .connect( @@ -440,6 +459,7 @@ impl ModelClient { /// replayed on reconnect within the same turn. fn build_websocket_headers( &self, + ws_version: ResponsesWebsocketVersion, turn_state: Option<&Arc>>, turn_metadata_header: Option<&str>, ) -> ApiHeaderMap { @@ -452,10 +472,9 @@ impl ModelClient { headers.extend(build_conversation_headers(Some( self.state.conversation_id.to_string(), ))); - let responses_websockets_beta_header = if self.responses_websockets_v2_enabled() { - RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE - } else { - OPENAI_BETA_RESPONSES_WEBSOCKETS + let responses_websockets_beta_header = match ws_version { + ResponsesWebsocketVersion::V2 => RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE, + ResponsesWebsocketVersion::V1 => OPENAI_BETA_RESPONSES_WEBSOCKETS, }; headers.insert( OPENAI_BETA_HEADER, @@ -628,35 +647,39 @@ impl ModelClientSession { &mut self, payload: ResponseCreateWsRequest, request: &ResponsesApiRequest, + ws_version: ResponsesWebsocketVersion, ) -> ResponsesWsRequest { let Some(last_response) = self.get_last_response() else { return ResponsesWsRequest::ResponseCreate(payload); }; - let responses_websockets_v2_enabled = self.client.responses_websockets_v2_enabled(); - if !responses_websockets_v2_enabled && !last_response.can_append { - trace!("incremental request failed, can't append"); + let Some(append_items) = self.get_incremental_items(request, Some(&last_response)) else { return ResponsesWsRequest::ResponseCreate(payload); - } - let incremental_items = self.get_incremental_items(request, Some(&last_response)); - if let Some(append_items) = incremental_items { - if responses_websockets_v2_enabled && !last_response.response_id.is_empty() { - let payload = ResponseCreateWsRequest { + }; + + match ws_version { + ResponsesWebsocketVersion::V2 => { + if last_response.response_id.is_empty() { + trace!("incremental request failed, no previous response id"); + return ResponsesWsRequest::ResponseCreate(payload); + } + + ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest { previous_response_id: Some(last_response.response_id), input: append_items, ..payload - }; - return ResponsesWsRequest::ResponseCreate(payload); + }) } - - if !responses_websockets_v2_enabled { - return ResponsesWsRequest::ResponseAppend(ResponseAppendWsRequest { + ResponsesWebsocketVersion::V1 => { + if !last_response.can_append { + trace!("incremental request failed, can't append"); + return ResponsesWsRequest::ResponseCreate(payload); + } + ResponsesWsRequest::ResponseAppend(ResponseAppendWsRequest { input: append_items, client_metadata: payload.client_metadata, - }); + }) } } - - ResponsesWsRequest::ResponseCreate(payload) } /// Opportunistically warms a websocket for this turn-scoped client session. @@ -667,10 +690,9 @@ impl ModelClientSession { otel_manager: &OtelManager, model_info: &ModelInfo, ) -> std::result::Result<(), ApiError> { - if !self.client.responses_websocket_enabled(model_info) || self.client.websockets_disabled() - { + let Some(ws_version) = self.client.active_ws_version(model_info) else { return Ok(()); - } + }; if self.connection.is_some() { return Ok(()); } @@ -687,6 +709,7 @@ impl ModelClientSession { otel_manager, client_setup.api_provider, client_setup.api_auth, + ws_version, Some(Arc::clone(&self.turn_state)), None, ) @@ -701,6 +724,7 @@ impl ModelClientSession { otel_manager: &OtelManager, api_provider: codex_api::Provider, api_auth: CoreAuthProvider, + ws_version: ResponsesWebsocketVersion, turn_metadata_header: Option<&str>, options: &ApiResponsesOptions, ) -> std::result::Result<&ApiWebSocketConnection, ApiError> { @@ -722,6 +746,7 @@ impl ModelClientSession { otel_manager, api_provider, api_auth, + ws_version, Some(turn_state), turn_metadata_header, ) @@ -818,6 +843,7 @@ impl ModelClientSession { &mut self, prompt: &Prompt, model_info: &ModelInfo, + ws_version: ResponsesWebsocketVersion, otel_manager: &OtelManager, effort: Option, summary: ReasoningSummaryConfig, @@ -850,6 +876,7 @@ impl ModelClientSession { otel_manager, client_setup.api_provider, client_setup.api_auth, + ws_version, turn_metadata_header, &options, ) @@ -870,7 +897,7 @@ impl ModelClientSession { Err(err) => return Err(map_api_error(err)), } - let ws_request = self.prepare_websocket_request(ws_payload, &request); + let ws_request = self.prepare_websocket_request(ws_payload, &request, ws_version); let stream_result = self .connection @@ -928,14 +955,12 @@ impl ModelClientSession { let wire_api = self.client.state.provider.wire_api; match wire_api { WireApi::Responses => { - let websocket_enabled = self.client.responses_websocket_enabled(model_info) - && !self.client.websockets_disabled(); - - if websocket_enabled { + if let Some(ws_version) = self.client.active_ws_version(model_info) { match self .stream_responses_websocket( prompt, model_info, + ws_version, otel_manager, effort, summary, @@ -974,7 +999,7 @@ impl ModelClientSession { otel_manager: &OtelManager, model_info: &ModelInfo, ) -> bool { - let websocket_enabled = self.client.responses_websocket_enabled(model_info); + let websocket_enabled = self.client.active_ws_version(model_info).is_some(); let activated = self.activate_http_fallback(websocket_enabled); if activated { warn!("falling back to HTTP"); @@ -1224,8 +1249,7 @@ mod tests { provider, session_source, None, - false, - false, + None, false, false, None, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 6c9c9a678f..55a8062187 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -45,6 +45,7 @@ use crate::terminal; use crate::truncate::TruncationPolicy; use crate::turn_metadata::TurnMetadataState; use crate::util::error_or_panic; +use crate::ws_version_from_features; use async_channel::Receiver; use async_channel::Sender; use codex_hooks::HookEvent; @@ -1335,9 +1336,7 @@ impl Session { session_configuration.provider.clone(), session_configuration.session_source.clone(), config.model_verbosity, - config.features.enabled(Feature::ResponsesWebsockets) - || config.features.enabled(Feature::ResponsesWebsocketsV2), - config.features.enabled(Feature::ResponsesWebsocketsV2), + ws_version_from_features(config.as_ref()), config.features.enabled(Feature::EnableRequestCompression), config.features.enabled(Feature::RuntimeMetrics), Self::build_model_client_beta_features_header(config.as_ref()), @@ -5198,10 +5197,11 @@ async fn run_sampling_request( // transient reconnect messages. In debug builds, keep full visibility for diagnosis. let report_error = retries > 1 || cfg!(debug_assertions) - || !sess + || sess .services .model_client - .responses_websocket_enabled(&turn_context.model_info); + .active_ws_version(&turn_context.model_info) + .is_none(); if report_error { // Surface retry information to any UI/front‑end so the @@ -7844,10 +7844,7 @@ mod tests { session_configuration.provider.clone(), session_configuration.session_source.clone(), config.model_verbosity, - model_info.prefer_websockets - || config.features.enabled(Feature::ResponsesWebsockets) - || config.features.enabled(Feature::ResponsesWebsocketsV2), - config.features.enabled(Feature::ResponsesWebsocketsV2), + ws_version_from_features(config.as_ref()), config.features.enabled(Feature::EnableRequestCompression), config.features.enabled(Feature::RuntimeMetrics), Session::build_model_client_beta_features_header(config.as_ref()), @@ -8000,10 +7997,7 @@ mod tests { session_configuration.provider.clone(), session_configuration.session_source.clone(), config.model_verbosity, - model_info.prefer_websockets - || config.features.enabled(Feature::ResponsesWebsockets) - || config.features.enabled(Feature::ResponsesWebsocketsV2), - config.features.enabled(Feature::ResponsesWebsocketsV2), + ws_version_from_features(config.as_ref()), config.features.enabled(Feature::EnableRequestCompression), config.features.enabled(Feature::RuntimeMetrics), Session::build_model_client_beta_features_header(config.as_ref()), diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index a0ad85a421..e40905e314 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -157,6 +157,8 @@ pub use zsh_exec_bridge::maybe_run_zsh_exec_wrapper_mode; pub use client::ModelClient; pub use client::ModelClientSession; +pub use client::ResponsesWebsocketVersion; +pub use client::ws_version_from_features; pub use client_common::Prompt; pub use client_common::REVIEW_PROMPT; pub use client_common::ResponseEvent; diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index b392081eeb..126dc2c288 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -6,6 +6,7 @@ use codex_core::ModelClient; use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; +use codex_core::ResponsesWebsocketVersion; use codex_core::WireApi; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; @@ -91,8 +92,7 @@ async fn responses_stream_includes_subagent_header_on_review() { provider.clone(), session_source, config.model_verbosity, - false, - false, + None::, false, false, None, @@ -197,8 +197,7 @@ async fn responses_stream_includes_subagent_header_on_other() { provider.clone(), session_source, config.model_verbosity, - false, - false, + None::, false, false, None, @@ -302,8 +301,7 @@ async fn responses_respects_model_info_overrides_from_config() { provider.clone(), session_source, config.model_verbosity, - false, - false, + None::, false, false, None, diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 77a2ba33e0..5fc94a033e 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -4,6 +4,7 @@ use codex_core::ModelProviderInfo; use codex_core::NewThread; use codex_core::Prompt; use codex_core::ResponseEvent; +use codex_core::ResponsesWebsocketVersion; use codex_core::ThreadManager; use codex_core::WireApi; use codex_core::auth::AuthCredentialsStoreMode; @@ -1353,8 +1354,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { provider.clone(), SessionSource::Exec, config.model_verbosity, - false, - false, + None::, false, false, None, diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 54e197e568..d8b1940d15 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -8,6 +8,7 @@ use codex_core::ResponseEvent; use codex_core::WireApi; use codex_core::X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER; use codex_core::features::Feature; +use codex_core::ws_version_from_features; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; use codex_otel::metrics::MetricsClient; @@ -319,6 +320,62 @@ async fn responses_websocket_v2_requests_use_v2_when_model_prefers_websockets() server.shutdown().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_websocket_v2_wins_when_both_features_enabled() { + skip_if_no_network!(); + + let server = start_websocket_server(vec![vec![ + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "assistant output"), + ev_done_with_id("resp-1"), + ], + vec![ev_response_created("resp-2"), ev_completed("resp-2")], + ]]) + .await; + + let harness = websocket_harness_with_options(&server, false, true, true, false).await; + let mut client_session = harness.client.new_session(); + let prompt_one = prompt_with_input(vec![message_item("hello")]); + let prompt_two = prompt_with_input(vec![ + message_item("hello"), + assistant_message_item("msg-1", "assistant output"), + message_item("second"), + ]); + + stream_until_complete(&mut client_session, &harness, &prompt_one).await; + stream_until_complete(&mut client_session, &harness, &prompt_two).await; + + let connection = server.single_connection(); + assert_eq!(connection.len(), 2); + let second = connection.get(1).expect("missing request").body_json(); + assert_eq!(second["type"].as_str(), Some("response.create")); + assert_eq!(second["previous_response_id"].as_str(), Some("resp-1")); + assert_eq!( + second["input"], + serde_json::to_value(&prompt_two.input[2..]).unwrap() + ); + + let handshake = server.single_handshake(); + let openai_beta_header = handshake + .header(OPENAI_BETA_HEADER) + .expect("missing OpenAI-Beta header"); + assert!( + openai_beta_header + .split(',') + .map(str::trim) + .any(|value| value == WS_V2_BETA_HEADER_VALUE) + ); + assert!( + !openai_beta_header + .split(',') + .map(str::trim) + .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) + ); + + server.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[traced_test] async fn responses_websocket_emits_websocket_telemetry_events() { @@ -1251,8 +1308,7 @@ async fn websocket_harness_with_options( provider.clone(), SessionSource::Exec, config.model_verbosity, - websocket_enabled, - websocket_v2_enabled, + ws_version_from_features(&config), false, runtime_metrics_enabled, None, From 3586fcb8020a3a3bd377582c09de275fa4c3d312 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Sat, 21 Feb 2026 14:25:36 -0800 Subject: [PATCH 062/385] Improve token usage estimate for images (#12419) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #11845. Adjust context/token estimation for inline image `data:*;base64,...` URLs so we do not count the raw base64 payload as model-visible text. What changed: - keep the existing JSON-length estimator as the baseline - detect only inline base64 `data:` image URLs in message and function-call output content items - subtract only the base64 payload bytes (preserving data URL prefix + JSON overhead) - add a fixed per-image estimate of 340 bytes (~85 tokens at the repo’s 4-bytes/token heuristic) This avoids large overestimates from MCP image tool outputs while leaving normal image URLs (`https://`, `file://`, non-base64 `data:` URLs) unchanged. Tests: - message image data URL estimate regression - function-call output image data URL estimate regression - non-base64 image URLs unchanged - non-base64 `data:` URLs unchanged - `data:application/octet-stream;base64,...` adjusted - multiple inline images apply multiple fixed costs - text-only items unchanged --- codex-rs/core/src/context_manager/history.rs | 97 ++++++++- .../core/src/context_manager/history_tests.rs | 192 ++++++++++++++++++ 2 files changed, 286 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 52df99fb02..a3dbc643bb 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -419,6 +419,12 @@ fn estimate_item_token_count(item: &ResponseItem) -> i64 { approx_tokens_from_byte_count_i64(model_visible_bytes) } +/// Approximate model-visible byte cost for one image input. +/// +/// The estimator later converts bytes to tokens using a 4-bytes/token heuristic, +/// so 340 bytes is approximately 85 tokens. +const IMAGE_BYTES_ESTIMATE: i64 = 340; + pub(crate) fn estimate_response_item_model_visible_bytes(item: &ResponseItem) -> i64 { match item { ResponseItem::GhostSnapshot { .. } => 0, @@ -429,12 +435,97 @@ pub(crate) fn estimate_response_item_model_visible_bytes(item: &ResponseItem) -> | ResponseItem::Compaction { encrypted_content: content, } => i64::try_from(estimate_reasoning_length(content.len())).unwrap_or(i64::MAX), - item => serde_json::to_string(item) - .map(|serialized| i64::try_from(serialized.len()).unwrap_or(i64::MAX)) - .unwrap_or_default(), + item => { + let raw = serde_json::to_string(item) + .map(|serialized| i64::try_from(serialized.len()).unwrap_or(i64::MAX)) + .unwrap_or_default(); + let (payload_bytes, image_count) = image_data_url_estimate_adjustment(item); + if payload_bytes == 0 || image_count == 0 { + raw + } else { + // Replace raw base64 payload bytes with a fixed per-image cost. + // We intentionally preserve the data URL prefix and JSON wrapper + // bytes already included in `raw`. + raw.saturating_sub(payload_bytes) + .saturating_add(image_count.saturating_mul(IMAGE_BYTES_ESTIMATE)) + } + } } } +/// Returns the base64 payload byte length for inline image data URLs that are +/// eligible for token-estimation discounting. +/// +/// We only discount payloads for `data:image/...;base64,...` URLs (case +/// insensitive markers) and leave everything else at raw serialized size. +fn base64_data_url_payload_len(url: &str) -> Option { + if !url + .get(.."data:".len()) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("data:")) + { + return None; + } + let comma_index = url.find(',')?; + let metadata = &url[..comma_index]; + let payload = &url[comma_index + 1..]; + // Parse the media type and parameters without decoding. This keeps the + // estimator cheap while ensuring we only apply the fixed-cost image + // heuristic to image-typed base64 data URLs. + let metadata_without_scheme = &metadata["data:".len()..]; + let mut metadata_parts = metadata_without_scheme.split(';'); + let mime_type = metadata_parts.next().unwrap_or_default(); + let has_base64_marker = metadata_parts.any(|part| part.eq_ignore_ascii_case("base64")); + if !mime_type + .get(.."image/".len()) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("image/")) + { + return None; + } + if !has_base64_marker { + return None; + } + Some(payload.len()) +} + +/// Scans one response item for discount-eligible inline image data URLs and +/// returns: +/// - total base64 payload bytes to subtract from raw serialized size +/// - count of qualifying images to replace with `IMAGE_BYTES_ESTIMATE` +fn image_data_url_estimate_adjustment(item: &ResponseItem) -> (i64, i64) { + let mut payload_bytes = 0i64; + let mut image_count = 0i64; + + let mut accumulate = |image_url: &str| { + if let Some(payload_len) = base64_data_url_payload_len(image_url) { + payload_bytes = + payload_bytes.saturating_add(i64::try_from(payload_len).unwrap_or(i64::MAX)); + image_count = image_count.saturating_add(1); + } + }; + + match item { + ResponseItem::Message { content, .. } => { + for content_item in content { + if let ContentItem::InputImage { image_url } = content_item { + accumulate(image_url); + } + } + } + ResponseItem::FunctionCallOutput { output, .. } => { + if let FunctionCallOutputBody::ContentItems(items) = &output.body { + for content_item in items { + if let FunctionCallOutputContentItem::InputImage { image_url } = content_item { + accumulate(image_url); + } + } + } + } + _ => {} + } + + (payload_bytes, image_count) +} + fn is_model_generated_item(item: &ResponseItem) -> bool { match item { ResponseItem::Message { role, .. } => role == "assistant", diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index dbecaa9efc..3e11dae40a 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -1240,3 +1240,195 @@ fn normalize_mixed_inserts_and_removals_panics_in_debug() { let mut h = create_history_with_items(items); h.normalize_history(&default_input_modalities()); } + +#[test] +fn image_data_url_payload_does_not_dominate_message_estimate() { + let payload = "A".repeat(100_000); + let image_url = format!("data:image/png;base64,{payload}"); + let image_item = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ + ContentItem::InputText { + text: "Here is the screenshot".to_string(), + }, + ContentItem::InputImage { image_url }, + ], + end_turn: None, + phase: None, + }; + let text_only_item = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "Here is the screenshot".to_string(), + }], + end_turn: None, + phase: None, + }; + + let raw_len = serde_json::to_string(&image_item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&image_item); + let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + let text_only_estimated = estimate_response_item_model_visible_bytes(&text_only_item); + + assert_eq!(estimated, expected); + assert!(estimated < raw_len); + assert!(estimated > text_only_estimated); +} + +#[test] +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 { + call_id: "call-abc".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputText { + text: "Screenshot captured".to_string(), + }, + FunctionCallOutputContentItem::InputImage { image_url }, + ]), + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + + assert_eq!(estimated, expected); + assert!(estimated < raw_len); +} + +#[test] +fn non_base64_image_urls_are_unchanged() { + let message_item = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputImage { + image_url: "https://example.com/foo.png".to_string(), + }], + end_turn: None, + phase: None, + }; + let function_output_item = ResponseItem::FunctionCallOutput { + call_id: "call-1".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url: "file:///tmp/foo.png".to_string(), + }, + ]), + }; + + assert_eq!( + estimate_response_item_model_visible_bytes(&message_item), + serde_json::to_string(&message_item).unwrap().len() as i64 + ); + assert_eq!( + estimate_response_item_model_visible_bytes(&function_output_item), + serde_json::to_string(&function_output_item).unwrap().len() as i64 + ); +} + +#[test] +fn data_url_without_base64_marker_is_unchanged() { + let item = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputImage { + image_url: "data:image/svg+xml,".to_string(), + }], + end_turn: None, + phase: None, + }; + + assert_eq!( + estimate_response_item_model_visible_bytes(&item), + serde_json::to_string(&item).unwrap().len() as i64 + ); +} + +#[test] +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 { + call_id: "call-octet".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { image_url }, + ]), + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + + assert_eq!(estimated, raw_len); +} + +#[test] +fn mixed_case_data_url_markers_are_adjusted() { + let payload = "F".repeat(1_024); + let image_url = format!("DATA:image/png;BASE64,{payload}"); + let item = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputImage { image_url }], + end_turn: None, + phase: None, + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + + assert_eq!(estimated, expected); +} + +#[test] +fn multiple_inline_images_apply_multiple_fixed_costs() { + let payload_one = "D".repeat(100); + let payload_two = "E".repeat(200); + let image_url_one = format!("data:image/png;base64,{payload_one}"); + let image_url_two = format!("data:image/jpeg;base64,{payload_two}"); + let item = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ + ContentItem::InputText { + text: "images".to_string(), + }, + ContentItem::InputImage { + image_url: image_url_one, + }, + ContentItem::InputImage { + image_url: image_url_two, + }, + ], + end_turn: None, + phase: None, + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let payload_sum = (payload_one.len() + payload_two.len()) as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + let expected = raw_len - payload_sum + (2 * IMAGE_BYTES_ESTIMATE); + + assert_eq!(estimated, expected); +} + +#[test] +fn text_only_items_unchanged() { + let item = ResponseItem::Message { + id: None, + role: "assistant".to_string(), + content: vec![ContentItem::OutputText { + text: "Hello world, this is a response.".to_string(), + }], + end_turn: None, + phase: None, + }; + + let estimated = estimate_response_item_model_visible_bytes(&item); + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + + assert_eq!(estimated, raw_len); +} From f33ac830aad5cdee4e52cf7eca0a73686a17b375 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sat, 21 Feb 2026 14:40:13 -0800 Subject: [PATCH 063/385] fix: make skills loader tests hermetic with ~/.agents skills (#12474) --- codex-rs/core/src/skills/loader.rs | 82 ++++++++++++++++++------------ 1 file changed, 49 insertions(+), 33 deletions(-) diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index 1ad231438a..6508d4fd10 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -137,7 +137,17 @@ impl fmt::Display for SkillParseError { impl Error for SkillParseError {} pub fn load_skills(config: &Config) -> SkillLoadOutcome { - load_skills_from_roots(skill_roots(config)) + load_skills_with_home_dir(config, home_dir().as_deref()) +} + +fn load_skills_with_home_dir(config: &Config, home_dir: Option<&Path>) -> SkillLoadOutcome { + let mut roots = skill_roots_from_layer_stack_inner(&config.config_layer_stack, home_dir); + roots.extend(repo_agents_skill_roots( + &config.config_layer_stack, + &config.cwd, + )); + dedupe_skill_roots_by_path(&mut roots); + load_skills_from_roots(roots) } pub(crate) struct SkillRoot { @@ -240,6 +250,7 @@ fn skill_roots_from_layer_stack_inner( roots } +#[cfg(test)] fn skill_roots(config: &Config) -> Vec { skill_roots_from_layer_stack_with_agents(&config.config_layer_stack, &config.cwd) } @@ -867,6 +878,11 @@ mod tests { .expect("defaults for test should always succeed") } + fn load_skills_for_test(config: &Config) -> SkillLoadOutcome { + // Keep unit tests hermetic by never scanning the real `$HOME/.agents/skills`. + super::load_skills_with_home_dir(config, None) + } + fn mark_as_git_repo(dir: &Path) { // Config/project-root discovery only checks for the presence of `.git` (file or dir), // so we can avoid shelling out to `git init` in tests. @@ -1129,7 +1145,7 @@ mod tests { ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1208,7 +1224,7 @@ interface: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1258,7 +1274,7 @@ policy: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1289,7 +1305,7 @@ policy: {} ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1332,7 +1348,7 @@ permissions: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1394,7 +1410,7 @@ permissions: {} ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1452,7 +1468,7 @@ permissions: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1502,7 +1518,7 @@ permissions: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1547,7 +1563,7 @@ permissions: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1595,7 +1611,7 @@ permissions: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1642,7 +1658,7 @@ permissions: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1691,7 +1707,7 @@ permissions: ); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1736,7 +1752,7 @@ permissions: symlink_dir(shared.path(), &codex_home.path().join("skills/shared")); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1773,7 +1789,7 @@ permissions: symlink_file(&shared_skill_path, &skill_dir.join(SKILLS_FILENAME)); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1797,7 +1813,7 @@ permissions: let skill_path = write_skill_at(&cycle_dir, "demo", "cycle-skill", "still loads"); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1875,7 +1891,7 @@ permissions: symlink_dir(shared.path(), &repo_skills_root.join("shared")); let cfg = make_config_for_cwd(&codex_home, repo_dir.path().to_path_buf()).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -1972,7 +1988,7 @@ permissions: let skill_path = write_skill(&codex_home, "demo", "demo-skill", "does things\ncarefully"); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2004,7 +2020,7 @@ permissions: fs::write(&skill_path, contents).unwrap(); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2038,7 +2054,7 @@ permissions: fs::write(skill_dir.join(SKILLS_FILENAME), contents).unwrap(); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert_eq!(outcome.skills.len(), 0); assert_eq!(outcome.errors.len(), 1); assert!( @@ -2067,7 +2083,7 @@ permissions: fs::write(invalid_dir.join(SKILLS_FILENAME), "---\nname: bad").unwrap(); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert_eq!(outcome.skills.len(), 0); assert_eq!(outcome.errors.len(), 1); assert!( @@ -2085,7 +2101,7 @@ permissions: write_skill(&codex_home, "max-len", "max-len", &max_desc); let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2095,7 +2111,7 @@ permissions: let too_long_desc = "\u{1F4A1}".repeat(MAX_DESCRIPTION_LEN + 1); write_skill(&codex_home, "too-long", "too-long", &too_long_desc); - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert_eq!(outcome.skills.len(), 1); assert_eq!(outcome.errors.len(), 1); assert!( @@ -2117,7 +2133,7 @@ permissions: let skill_path = write_skill_at(&skills_root, "repo", "repo-skill", "from repo"); let cfg = make_config_for_cwd(&codex_home, repo_dir.path().to_path_buf()).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2153,7 +2169,7 @@ permissions: ); let cfg = make_config_for_cwd(&codex_home, repo_dir.path().to_path_buf()).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2206,7 +2222,7 @@ permissions: let cfg = make_config_for_cwd(&codex_home, nested_dir).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2258,7 +2274,7 @@ permissions: let cfg = make_config_for_cwd(&codex_home, work_dir.path().to_path_buf()).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2337,7 +2353,7 @@ permissions: let cfg = make_config_for_cwd(&codex_home, repo_dir.path().to_path_buf()).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2402,7 +2418,7 @@ permissions: ); let cfg = make_config_for_cwd(&codex_home, nested_dir).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), @@ -2468,7 +2484,7 @@ permissions: let cfg = make_config_for_cwd(&codex_home, repo_dir).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2497,7 +2513,7 @@ permissions: let cfg = make_config_for_cwd(&codex_home, file_path).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2538,7 +2554,7 @@ permissions: let cfg = make_config_for_cwd(&codex_home, nested_dir).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", @@ -2556,7 +2572,7 @@ permissions: let cfg = make_config_for_cwd(&codex_home, work_dir.path().to_path_buf()).await; - let outcome = load_skills(&cfg); + let outcome = load_skills_for_test(&cfg); assert!( outcome.errors.is_empty(), "unexpected errors: {:?}", From 66d5d34e6e14ff4b15c4bcd06bffd922abad809c Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sat, 21 Feb 2026 14:40:24 -0800 Subject: [PATCH 064/385] core: preserve constrained approval/sandbox policies in TurnContext (#12473) --- codex-rs/core/src/apply_patch.rs | 4 +- codex-rs/core/src/codex.rs | 58 +++++++++++-------- codex-rs/core/src/context_manager/updates.rs | 8 ++- codex-rs/core/src/mcp/skill_dependencies.rs | 4 +- codex-rs/core/src/mcp_tool_call.rs | 4 +- .../core/src/tools/handlers/apply_patch.rs | 16 ++++- .../core/src/tools/handlers/multi_agents.rs | 11 ++-- codex-rs/core/src/tools/handlers/shell.rs | 16 +++-- .../core/src/tools/handlers/unified_exec.rs | 4 +- codex-rs/core/src/tools/js_repl/mod.rs | 32 +++++++--- codex-rs/core/src/tools/network_approval.rs | 2 +- codex-rs/core/src/unified_exec/mod.rs | 8 ++- .../core/src/unified_exec/process_manager.rs | 6 +- 13 files changed, 112 insertions(+), 61 deletions(-) diff --git a/codex-rs/core/src/apply_patch.rs b/codex-rs/core/src/apply_patch.rs index 714d9c40fe..0b9cca1c9d 100644 --- a/codex-rs/core/src/apply_patch.rs +++ b/codex-rs/core/src/apply_patch.rs @@ -38,8 +38,8 @@ pub(crate) async fn apply_patch( ) -> InternalApplyPatchInvocation { match assess_patch_safety( &action, - turn_context.approval_policy, - &turn_context.sandbox_policy, + turn_context.approval_policy.value(), + turn_context.sandbox_policy.get(), &turn_context.cwd, turn_context.windows_sandbox_level, ) { diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 55a8062187..832592d406 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -558,8 +558,8 @@ pub(crate) struct TurnContext { pub(crate) user_instructions: Option, pub(crate) collaboration_mode: CollaborationMode, pub(crate) personality: Option, - pub(crate) approval_policy: AskForApproval, - pub(crate) sandbox_policy: SandboxPolicy, + pub(crate) approval_policy: Constrained, + pub(crate) sandbox_policy: Constrained, pub(crate) network: Option, pub(crate) windows_sandbox_level: WindowsSandboxLevel, pub(crate) shell_environment_policy: ShellEnvironmentPolicy, @@ -640,7 +640,7 @@ impl TurnContext { user_instructions: self.user_instructions.clone(), collaboration_mode, personality: self.personality, - approval_policy: self.approval_policy, + approval_policy: self.approval_policy.clone(), sandbox_policy: self.sandbox_policy.clone(), network: self.network.clone(), windows_sandbox_level: self.windows_sandbox_level, @@ -674,8 +674,8 @@ impl TurnContext { TurnContextItem { turn_id: Some(self.sub_id.clone()), cwd: self.cwd.clone(), - approval_policy: self.approval_policy, - sandbox_policy: self.sandbox_policy.clone(), + approval_policy: self.approval_policy.value(), + sandbox_policy: self.sandbox_policy.get().clone(), network: self.turn_context_network_item(), model: self.model_info.slug.clone(), personality: self.personality, @@ -980,8 +980,8 @@ impl Session { user_instructions: session_configuration.user_instructions.clone(), collaboration_mode: session_configuration.collaboration_mode.clone(), personality: session_configuration.personality, - approval_policy: session_configuration.approval_policy.value(), - sandbox_policy: session_configuration.sandbox_policy.get().clone(), + approval_policy: session_configuration.approval_policy.clone(), + sandbox_policy: session_configuration.sandbox_policy.clone(), network, windows_sandbox_level: session_configuration.windows_sandbox_level, shell_environment_policy: per_turn_config.permissions.shell_environment_policy.clone(), @@ -2713,8 +2713,8 @@ impl Session { let shell = self.user_shell(); items.push( DeveloperInstructions::from_policy( - &turn_context.sandbox_policy, - turn_context.approval_policy, + turn_context.sandbox_policy.get(), + turn_context.approval_policy.value(), self.services.exec_policy.current().as_ref(), &turn_context.cwd, ) @@ -3227,7 +3227,7 @@ impl Session { ); let auth_statuses = compute_auth_statuses(mcp_servers.iter(), store_mode).await; let sandbox_state = SandboxState { - sandbox_policy: turn_context.sandbox_policy.clone(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), codex_linux_sandbox_exe: turn_context.codex_linux_sandbox_exe.clone(), sandbox_cwd: turn_context.cwd.clone(), use_linux_sandbox_bwrap: turn_context.features.enabled(Feature::UseLinuxSandboxBwrap), @@ -4340,7 +4340,7 @@ async fn spawn_review_thread( let turn_metadata_state = Arc::new(TurnMetadataState::new( review_turn_id.clone(), parent_turn_context.cwd.clone(), - &parent_turn_context.sandbox_policy, + parent_turn_context.sandbox_policy.get(), parent_turn_context.windows_sandbox_level, parent_turn_context .features @@ -4365,7 +4365,7 @@ async fn spawn_review_thread( compact_prompt: parent_turn_context.compact_prompt.clone(), collaboration_mode: parent_turn_context.collaboration_mode.clone(), personality: parent_turn_context.personality, - approval_policy: parent_turn_context.approval_policy, + approval_policy: parent_turn_context.approval_policy.clone(), sandbox_policy: parent_turn_context.sandbox_policy.clone(), network: parent_turn_context.network.clone(), windows_sandbox_level: parent_turn_context.windows_sandbox_level, @@ -5720,8 +5720,8 @@ async fn try_run_sampling_request( feedback_tags!( model = turn_context.model_info.slug.clone(), - approval_policy = turn_context.approval_policy, - sandbox_policy = turn_context.sandbox_policy, + approval_policy = turn_context.approval_policy.value(), + sandbox_policy = turn_context.sandbox_policy.get(), effort = turn_context.reasoning_effort, auth_mode = sess.services.auth_manager.auth_mode(), features = sess.features.enabled_features(), @@ -6652,8 +6652,8 @@ mod tests { let previous_context_item = TurnContextItem { turn_id: Some(turn_context.sub_id.clone()), cwd: turn_context.cwd.clone(), - approval_policy: turn_context.approval_policy, - sandbox_policy: turn_context.sandbox_policy.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), network: None, model: previous_model.to_string(), personality: turn_context.personality, @@ -6689,8 +6689,8 @@ mod tests { let mut previous_context_item = TurnContextItem { turn_id: Some(turn_context.sub_id.clone()), cwd: turn_context.cwd.clone(), - approval_policy: turn_context.approval_policy, - sandbox_policy: turn_context.sandbox_policy.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), network: None, model: previous_model.to_string(), personality: turn_context.personality, @@ -7051,8 +7051,8 @@ mod tests { let previous_context_item = TurnContextItem { turn_id: Some(turn_context.sub_id.clone()), cwd: turn_context.cwd.clone(), - approval_policy: turn_context.approval_policy, - sandbox_policy: turn_context.sandbox_policy.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), network: None, model: previous_model.to_string(), personality: turn_context.personality, @@ -8809,7 +8809,10 @@ mod tests { let (session, mut turn_context_raw) = make_session_and_context().await; // Ensure policy is NOT OnRequest so the early rejection path triggers - turn_context_raw.approval_policy = AskForApproval::OnFailure; + turn_context_raw + .approval_policy + .set(AskForApproval::OnFailure) + .expect("test setup should allow updating approval policy"); let session = Arc::new(session); let mut turn_context = Arc::new(turn_context_raw); @@ -8883,7 +8886,7 @@ mod tests { let expected = format!( "approval policy is {policy:?}; reject command — you should not ask for escalated permissions if the approval policy is {policy:?}", - policy = turn_context.approval_policy + policy = turn_context.approval_policy.value() ); pretty_assertions::assert_eq!(output, expected); @@ -8892,7 +8895,9 @@ mod tests { // Force DangerFullAccess to avoid platform sandbox dependencies in tests. Arc::get_mut(&mut turn_context) .expect("unique turn context Arc") - .sandbox_policy = SandboxPolicy::DangerFullAccess; + .sandbox_policy + .set(SandboxPolicy::DangerFullAccess) + .expect("test setup should allow updating sandbox policy"); let resp2 = handler .handle(ToolInvocation { @@ -8946,7 +8951,10 @@ mod tests { use crate::turn_diff_tracker::TurnDiffTracker; let (session, mut turn_context_raw) = make_session_and_context().await; - turn_context_raw.approval_policy = AskForApproval::OnFailure; + turn_context_raw + .approval_policy + .set(AskForApproval::OnFailure) + .expect("test setup should allow updating approval policy"); let session = Arc::new(session); let turn_context = Arc::new(turn_context_raw); let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())); @@ -8976,7 +8984,7 @@ mod tests { let expected = format!( "approval policy is {policy:?}; reject command — you cannot ask for escalated permissions if the approval policy is {policy:?}", - policy = turn_context.approval_policy + policy = turn_context.approval_policy.value() ); pretty_assertions::assert_eq!(output, expected); diff --git a/codex-rs/core/src/context_manager/updates.rs b/codex-rs/core/src/context_manager/updates.rs index cdb53ff0c4..87a31031b3 100644 --- a/codex-rs/core/src/context_manager/updates.rs +++ b/codex-rs/core/src/context_manager/updates.rs @@ -31,14 +31,16 @@ fn build_permissions_update_item( exec_policy: &Policy, ) -> Option { let prev = previous?; - if prev.sandbox_policy == next.sandbox_policy && prev.approval_policy == next.approval_policy { + if prev.sandbox_policy == *next.sandbox_policy.get() + && prev.approval_policy == next.approval_policy.value() + { return None; } Some( DeveloperInstructions::from_policy( - &next.sandbox_policy, - next.approval_policy, + next.sandbox_policy.get(), + next.approval_policy.value(), exec_policy, &next.cwd, ) diff --git a/codex-rs/core/src/mcp/skill_dependencies.rs b/codex-rs/core/src/mcp/skill_dependencies.rs index e8b2d4f7b0..f2138cc293 100644 --- a/codex-rs/core/src/mcp/skill_dependencies.rs +++ b/codex-rs/core/src/mcp/skill_dependencies.rs @@ -32,9 +32,9 @@ const MCP_DEPENDENCY_OPTION_INSTALL: &str = "Install"; const MCP_DEPENDENCY_OPTION_SKIP: &str = "Continue anyway"; fn is_full_access_mode(turn_context: &TurnContext) -> bool { - matches!(turn_context.approval_policy, AskForApproval::Never) + matches!(turn_context.approval_policy.value(), AskForApproval::Never) && matches!( - turn_context.sandbox_policy, + turn_context.sandbox_policy.get(), SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } ) } diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index f194ee79a6..ce260773d2 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -401,9 +401,9 @@ async fn maybe_request_mcp_tool_approval( } fn is_full_access_mode(turn_context: &TurnContext) -> bool { - matches!(turn_context.approval_policy, AskForApproval::Never) + matches!(turn_context.approval_policy.value(), AskForApproval::Never) && matches!( - turn_context.sandbox_policy, + turn_context.sandbox_policy.get(), SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } ) } diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 8f14fccedf..3ef79f7aa0 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -145,7 +145,13 @@ impl ToolHandler for ApplyPatchHandler { tool_name: tool_name.to_string(), }; let out = orchestrator - .run(&mut runtime, &req, &tool_ctx, &turn, turn.approval_policy) + .run( + &mut runtime, + &req, + &tool_ctx, + &turn, + turn.approval_policy.value(), + ) .await .map(|result| result.output); let event_ctx = ToolEventCtx::new( @@ -235,7 +241,13 @@ pub(crate) async fn intercept_apply_patch( tool_name: tool_name.to_string(), }; let out = orchestrator - .run(&mut runtime, &req, &tool_ctx, turn, turn.approval_policy) + .run( + &mut runtime, + &req, + &tool_ctx, + turn, + turn.approval_policy.value(), + ) .await .map(|result| result.output); let event_ctx = diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index b0c4cc4126..455a209526 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -919,7 +919,7 @@ fn build_agent_shared_config( config .permissions .sandbox_policy - .set(turn.sandbox_policy.clone()) + .set(turn.sandbox_policy.get().clone()) .map_err(|err| { FunctionCallError::RespondToModel(format!("sandbox_policy is invalid: {err}")) })?; @@ -1913,10 +1913,13 @@ mod tests { let temp_dir = tempfile::tempdir().expect("temp dir"); turn.cwd = temp_dir.path().to_path_buf(); turn.codex_linux_sandbox_exe = Some(PathBuf::from("/bin/echo")); - turn.sandbox_policy = pick_allowed_sandbox_policy( + let sandbox_policy = pick_allowed_sandbox_policy( &turn.config.permissions.sandbox_policy, turn.config.permissions.sandbox_policy.get().clone(), ); + turn.sandbox_policy + .set(sandbox_policy) + .expect("sandbox policy set"); let config = build_agent_spawn_config(&base_instructions, &turn, 0).expect("spawn config"); let mut expected = (*turn.config).clone(); @@ -1938,7 +1941,7 @@ mod tests { expected .permissions .sandbox_policy - .set(turn.sandbox_policy) + .set(turn.sandbox_policy.get().clone()) .expect("sandbox policy set"); assert_eq!(config, expected); } @@ -1987,7 +1990,7 @@ mod tests { expected .permissions .sandbox_policy - .set(turn.sandbox_policy) + .set(turn.sandbox_policy.get().clone()) .expect("sandbox policy set"); assert_eq!(config, expected); } diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index f040b4ba64..4cdbf454c4 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -281,11 +281,11 @@ impl ShellHandler { .sandbox_permissions .requires_escalated_permissions() && !matches!( - turn.approval_policy, + turn.approval_policy.value(), codex_protocol::protocol::AskForApproval::OnRequest ) { - let approval_policy = turn.approval_policy; + let approval_policy = turn.approval_policy.value(); return Err(FunctionCallError::RespondToModel(format!( "approval policy is {approval_policy:?}; reject command — you should not ask for escalated permissions if the approval policy is {approval_policy:?}" ))); @@ -322,8 +322,8 @@ impl ShellHandler { .exec_policy .create_exec_approval_requirement_for_command(ExecApprovalRequest { command: &exec_params.command, - approval_policy: turn.approval_policy, - sandbox_policy: &turn.sandbox_policy, + approval_policy: turn.approval_policy.value(), + sandbox_policy: turn.sandbox_policy.get(), sandbox_permissions: exec_params.sandbox_permissions, prefix_rule, }) @@ -349,7 +349,13 @@ impl ShellHandler { tool_name, }; let out = orchestrator - .run(&mut runtime, &req, &tool_ctx, &turn, turn.approval_policy) + .run( + &mut runtime, + &req, + &tool_ctx, + &turn, + turn.approval_policy.value(), + ) .await .map(|result| result.output); let event_ctx = ToolEventCtx::new(session.as_ref(), turn.as_ref(), &call_id, None); diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 62da64a877..c7d57731e3 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -152,11 +152,11 @@ impl ToolHandler for UnifiedExecHandler { if sandbox_permissions.requires_escalated_permissions() && !matches!( - context.turn.approval_policy, + context.turn.approval_policy.value(), codex_protocol::protocol::AskForApproval::OnRequest ) { - let approval_policy = context.turn.approval_policy; + let approval_policy = context.turn.approval_policy.value(); manager.release_process_id(&process_id).await; return Err(FunctionCallError::RespondToModel(format!( "approval policy is {approval_policy:?}; reject command — you cannot ask for escalated permissions if the approval policy is {approval_policy:?}" diff --git a/codex-rs/core/src/tools/js_repl/mod.rs b/codex-rs/core/src/tools/js_repl/mod.rs index 5b7b539bb3..79195d97f6 100644 --- a/codex-rs/core/src/tools/js_repl/mod.rs +++ b/codex-rs/core/src/tools/js_repl/mod.rs @@ -1800,8 +1800,12 @@ mod tests { } let (session, mut turn) = make_session_and_context().await; - turn.approval_policy = AskForApproval::Never; - turn.sandbox_policy = SandboxPolicy::DangerFullAccess; + turn.approval_policy + .set(AskForApproval::Never) + .expect("test setup should allow updating approval policy"); + turn.sandbox_policy + .set(SandboxPolicy::DangerFullAccess) + .expect("test setup should allow updating sandbox policy"); let session = Arc::new(session); let turn = Arc::new(turn); @@ -1843,8 +1847,12 @@ mod tests { } let (session, mut turn) = make_session_and_context().await; - turn.approval_policy = AskForApproval::Never; - turn.sandbox_policy = SandboxPolicy::DangerFullAccess; + turn.approval_policy + .set(AskForApproval::Never) + .expect("test setup should allow updating approval policy"); + turn.sandbox_policy + .set(SandboxPolicy::DangerFullAccess) + .expect("test setup should allow updating sandbox policy"); let session = Arc::new(session); let turn = Arc::new(turn); @@ -1891,8 +1899,12 @@ try { } let (session, mut turn) = make_session_and_context().await; - turn.approval_policy = AskForApproval::Never; - turn.sandbox_policy = SandboxPolicy::DangerFullAccess; + turn.approval_policy + .set(AskForApproval::Never) + .expect("test setup should allow updating approval policy"); + turn.sandbox_policy + .set(SandboxPolicy::DangerFullAccess) + .expect("test setup should allow updating sandbox policy"); let session = Arc::new(session); let turn = Arc::new(turn); @@ -1941,8 +1953,12 @@ console.log("cell-complete"); { return Ok(()); } - turn.approval_policy = AskForApproval::Never; - turn.sandbox_policy = SandboxPolicy::DangerFullAccess; + turn.approval_policy + .set(AskForApproval::Never) + .expect("test setup should allow updating approval policy"); + turn.sandbox_policy + .set(SandboxPolicy::DangerFullAccess) + .expect("test setup should allow updating sandbox policy"); let session = Arc::new(session); let turn = Arc::new(turn); diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index 4a893f74e9..0d4f2f3078 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -299,7 +299,7 @@ impl NetworkApprovalService { .await; return NetworkDecision::deny(REASON_NOT_ALLOWED); }; - if !allows_network_prompt(turn_context.approval_policy) { + if !allows_network_prompt(turn_context.approval_policy.value()) { pending.set_decision(PendingApprovalDecision::Deny).await; let mut pending_approvals = self.pending_host_approvals.lock().await; pending_approvals.remove(&key); diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index a586572dd1..62269a96d6 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -193,8 +193,12 @@ mod tests { async fn test_session_and_turn() -> (Arc, Arc) { let (session, mut turn) = make_session_and_context().await; - turn.approval_policy = AskForApproval::Never; - turn.sandbox_policy = SandboxPolicy::DangerFullAccess; + turn.approval_policy + .set(AskForApproval::Never) + .expect("test setup should allow updating approval policy"); + turn.sandbox_policy + .set(SandboxPolicy::DangerFullAccess) + .expect("test setup should allow updating sandbox policy"); (Arc::new(session), Arc::new(turn)) } diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 6945316469..68c4f95ceb 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -576,8 +576,8 @@ impl UnifiedExecProcessManager { .exec_policy .create_exec_approval_requirement_for_command(ExecApprovalRequest { command: &request.command, - approval_policy: context.turn.approval_policy, - sandbox_policy: &context.turn.sandbox_policy, + approval_policy: context.turn.approval_policy.value(), + sandbox_policy: context.turn.sandbox_policy.get(), sandbox_permissions: request.sandbox_permissions, prefix_rule: request.prefix_rule.clone(), }) @@ -605,7 +605,7 @@ impl UnifiedExecProcessManager { &req, &tool_ctx, context.turn.as_ref(), - context.turn.approval_policy, + context.turn.approval_policy.value(), ) .await .map(|result| (result.output, result.deferred_network_approval)) From 2ba2c57af4b548512a749a6947341452a16b3521 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Sat, 21 Feb 2026 20:31:41 -0300 Subject: [PATCH 065/385] fix(tui): preserve URL clickability across all TUI views (#12067) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem Long URLs containing `/` and `-` characters are split across multiple terminal lines by `textwrap`'s default hyphenation rules. This breaks terminal link detection: emulators can no longer identify the URL as clickable, and copy-paste yields a truncated fragment. The issue affects every view that renders user or agent text — exec output, history cells, markdown, the app-link setup screen, and the VT100 scrollback path. A secondary bug compounds the first: `desired_height()` calculations count logical lines rather than viewport rows. When a URL overflows its line and wraps visually, the height budget is too small, causing content to clip or leave gaps. Here is how the complete URL is interpreted by the terminal before (first line only) and after (complete URL): | Before | After | |---|---| | Screenshot 2026-02-17 at 7 59 11
PM | Screenshot 2026-02-17 at 7 58
40 PM | ## Mental model The TUI now treats URL-like tokens as atomic units that must never be split by the wrapping engine. Every call site that previously used `word_wrap_*` has been migrated to `adaptive_wrap_*`, which inspects each line for URL-like tokens and switches wrapping strategy accordingly: - **Non-URL lines** follow the existing `textwrap` path unchanged (word boundaries, optional indentation, hyphenation). - **URL-only lines** (with at most decorative markers like `│`, `-`, `1.`) are emitted unwrapped so terminal link detection works; ratatui's `Wrap { trim: false }` handles the final character wrap at render time. - **Mixed lines** (URL + substantive non-URL prose) flow through `adaptive_wrap_line` so prose wraps naturally at word boundaries while URL tokens remain unsplit. Height measurement everywhere now delegates to `Paragraph::line_count(width)`, which accounts for the visual row cost of overflowed lines. This single source of truth replaces ad-hoc line counting in individual cells. For terminal scrollback (the VT100 path that prints history when the TUI exits), URL-only lines are emitted unwrapped so the terminal's own link detector can find them. Mixed URL+prose lines use adaptive wrapping so surrounding text wraps naturally. Continuation rows are pre-cleared to avoid stale content artifacts. ## Non-goals - Full RFC 3986 URL parsing. The detector is a conservative heuristic that covers `scheme://host`, bare domains (`example.com/path`), `localhost:port`, and IPv4 hosts. IPv6 (`[::1]:8080`) and exotic schemes are intentionally excluded from v1. - Changing wrapping behavior for non-URL content. - Reflowing or reformatting existing terminal scrollback on resize. ## Tradeoffs | Decision | Upside | Downside | |----------|--------|----------| | Heuristic URL detection vs. full parser | Fast, zero-alloc on the hot path; conservative enough to reject file paths like `src/main.rs` | False negatives on obscure URL formats (they get split as before) | | Adaptive (three-path) wrapping | Non-URL lines are untouched — no behavior change, no perf cost; mixed lines wrap prose naturally while preserving URLs | Three wrapping strategies to reason about when debugging layout | | Row-based truncation with line-unit ellipsis | Accurate viewport budget; stable "N lines omitted" count across terminal widths | `truncate_lines_middle` is more complex (must compute per-line row cost) | | Unwrapped URL-only lines in scrollback | Terminal emulators detect clickable links; copy-paste gets the full URL | TUI and scrollback formatting diverge for URL-only lines | | Default `desired_height` via `Paragraph::line_count` | DRY — most cells inherit correct measurement | Cells with custom layout must remember to override | ## Architecture ```mermaid flowchart TD A["adaptive_wrap_*()"] --> B{"line_contains_url_like?"} B -- No URL tokens --> C["word_wrap_line
(textwrap default)"] B -- Has URL tokens --> D{"mixed URL + prose?"} D -- "URL-only
(+ decorative markers)" --> E["emit unwrapped
(terminal char-wraps)"] D -- "Mixed
(URL + substantive text)" --> F["adaptive_wrap_line
(AsciiSpace + custom WordSplitter)"] C --> G["Paragraph::line_count(w)
(single height truth)"] E --> G F --> G ``` **Changed files:** | File | Role | |------|------| | `wrapping.rs` | URL detection heuristics, mixed-line detection, `adaptive_wrap_*` functions, custom `WordSplitter` | | `exec_cell/render.rs` | Row-aware `truncate_lines_middle`, adaptive wrapping for command/output display | | `history_cell.rs` | Migrate all cell types to `adaptive_wrap_*`; default `desired_height` via `Paragraph::line_count` | | `insert_history.rs` | Three-path scrollback wrapping (unwrapped URL-only, adaptive mixed, word-wrapped text); continuation row clearing | | `app_link_view.rs` | Adaptive wrapping for setup URL; `desired_height` via `Paragraph::line_count` | | `markdown_render.rs` | Adaptive wrapping in `finish_paragraph` | | `model_migration.rs` | Viewport-aware wrapping for narrow-pane markdown | | `pager_overlay.rs` | `Wrap { trim: false }` for transcript and streaming chunks | | `queued_user_messages.rs` | Migrate to `adaptive_wrap_lines` | | `status/card.rs` | Migrate to `adaptive_wrap_lines` | ## Observability - **Ellipsis message** in truncated exec output reports omitted count in logical lines (stable across resize) rather than viewport rows (fluctuates). - URL detection is deterministic and stateless — no hidden caching or memoization to go stale. - Height mismatch bugs surface immediately as visual clipping or gaps; the `Paragraph::line_count` path is the same code ratatui uses at render time, so measurement and rendering cannot diverge. ## Tests 26 new unit tests across 7 files, covering: - **URL integrity**: assert a URL-like token appears on exactly one rendered line (not split across two). - **Height accuracy**: compare `desired_height()` against `Paragraph::line_count()` for URL-containing content. - **Row-aware truncation**: verify ellipsis counts logical lines and output fits within the row budget. - **Scrollback rendering**: VT100 backend tests confirm prefix and URL land on the same row; continuation rows are cleared; mixed URL+prose lines wrap prose while preserving URL tokens. - **Mixed URL+prose detection**: `line_has_mixed_url_and_non_url_tokens` correctly distinguishes lines with substantive non-URL text from lines with only decorative markers alongside a URL. - **Heuristic correctness**: positive matches (`https://...`, `example.com/path`, `localhost:3000/api`, `192.168.1.1:8080/health`) and negative matches (`src/main.rs`, `foo/bar`, `hello-world`). ## Risks and open items 1. **URL-like tokens in code output** (e.g. `example.com/api` inside a JSON blob) will trigger URL-preserving wrap on that line. This is acceptable — the worst case is a slightly wider line, not broken output. 2. **Very long non-URL tokens on a URL line** can only break at character boundaries (the custom splitter emits all char indices for non-URL words). On extremely narrow terminals this could overflow, but narrow terminals already degrade gracefully. 3. **No IPv6 support** — `[::1]:8080/path` will be treated as a non-URL and may get split. Can be added later without API changes. Fixes #5457 --- codex-rs/tui/src/bottom_pane/app_link_view.rs | 108 +++- .../src/bottom_pane/queued_user_messages.rs | 36 +- codex-rs/tui/src/custom_terminal.rs | 44 +- codex-rs/tui/src/exec_cell/render.rs | 385 +++++++++-- codex-rs/tui/src/history_cell.rs | 394 ++++++++--- codex-rs/tui/src/insert_history.rs | 213 +++++- codex-rs/tui/src/markdown_render.rs | 18 +- codex-rs/tui/src/model_migration.rs | 37 +- codex-rs/tui/src/onboarding/auth.rs | 142 +++- .../onboarding/auth/headless_chatgpt_login.rs | 14 +- codex-rs/tui/src/pager_overlay.rs | 7 +- ...pdate_with_note_and_wrapping_snapshot.snap | 4 +- codex-rs/tui/src/status/card.rs | 4 +- codex-rs/tui/src/wrapping.rs | 610 +++++++++++++++++- 14 files changed, 1839 insertions(+), 177 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/app_link_view.rs b/codex-rs/tui/src/bottom_pane/app_link_view.rs index 698825d6f7..2e6fab3d24 100644 --- a/codex-rs/tui/src/bottom_pane/app_link_view.rs +++ b/codex-rs/tui/src/bottom_pane/app_link_view.rs @@ -10,6 +10,7 @@ use ratatui::text::Line; use ratatui::widgets::Block; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; +use ratatui::widgets::Wrap; use textwrap::wrap; use super::CancellationEvent; @@ -24,7 +25,8 @@ use crate::key_hint; use crate::render::Insets; use crate::render::RectExt as _; use crate::style::user_message_style; -use crate::wrapping::word_wrap_lines; +use crate::wrapping::RtOptions; +use crate::wrapping::adaptive_wrap_lines; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum AppLinkScreen { @@ -234,7 +236,10 @@ impl AppLinkView { lines.push(Line::from("")); lines.push(Line::from(vec!["Setup URL:".dim()])); let url_line = Line::from(vec![self.url.clone().cyan().underlined()]); - lines.extend(word_wrap_lines(vec![url_line], usable_width)); + lines.extend(adaptive_wrap_lines( + vec![url_line], + RtOptions::new(usable_width), + )); lines } @@ -374,8 +379,12 @@ impl crate::render::renderable::Renderable for AppLinkView { fn desired_height(&self, width: u16) -> u16 { let content_width = width.saturating_sub(4).max(1); let content_lines = self.content_lines(content_width); + let content_rows = Paragraph::new(content_lines) + .wrap(Wrap { trim: false }) + .line_count(content_width) + .max(1) as u16; let action_rows_height = self.action_rows_height(content_width); - content_lines.len() as u16 + action_rows_height + 3 + content_rows + action_rows_height + 3 } fn render(&self, area: Rect, buf: &mut Buffer) { @@ -398,7 +407,9 @@ impl crate::render::renderable::Renderable for AppLinkView { let inner = content_area.inset(Insets::vh(1, 2)); let content_width = inner.width.max(1); let lines = self.content_lines(content_width); - Paragraph::new(lines).render(inner, buf); + Paragraph::new(lines) + .wrap(Wrap { trim: false }) + .render(inner, buf); if actions_area.height > 0 { let actions_area = Rect { @@ -435,6 +446,7 @@ impl crate::render::renderable::Renderable for AppLinkView { mod tests { use super::*; use crate::app_event::AppEvent; + use crate::render::renderable::Renderable; use tokio::sync::mpsc::unbounded_channel; #[test] @@ -493,4 +505,92 @@ mod tests { vec!["Manage on ChatGPT", "Enable app", "Back"] ); } + + #[test] + fn install_confirmation_does_not_split_long_url_like_token_without_scheme() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let url_like = + "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890"; + let mut view = AppLinkView::new( + AppLinkViewParams { + app_id: "connector_1".to_string(), + title: "Notion".to_string(), + description: None, + instructions: "Manage app".to_string(), + url: url_like.to_string(), + is_installed: true, + is_enabled: true, + }, + tx, + ); + view.screen = AppLinkScreen::InstallConfirmation; + + let rendered: Vec = view + .content_lines(40) + .into_iter() + .map(|line| { + line.spans + .into_iter() + .map(|span| span.content.into_owned()) + .collect::() + }) + .collect(); + + assert_eq!( + rendered + .iter() + .filter(|line| line.contains(url_like)) + .count(), + 1, + "expected full URL-like token in one rendered line, got: {rendered:?}" + ); + } + + #[test] + fn install_confirmation_render_keeps_url_tail_visible_when_narrow() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let url = "https://example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path/tail42"; + let mut view = AppLinkView::new( + AppLinkViewParams { + app_id: "connector_1".to_string(), + title: "Notion".to_string(), + description: None, + instructions: "Manage app".to_string(), + url: url.to_string(), + is_installed: true, + is_enabled: true, + }, + tx, + ); + view.screen = AppLinkScreen::InstallConfirmation; + + let width: u16 = 36; + let height = view.desired_height(width); + let area = Rect::new(0, 0, width, height); + let mut buf = Buffer::empty(area); + view.render(area, &mut buf); + + let rendered_blob = (0..area.height) + .map(|y| { + (0..area.width) + .map(|x| { + let symbol = buf[(x, y)].symbol(); + if symbol.is_empty() { + ' ' + } else { + symbol.chars().next().unwrap_or(' ') + } + }) + .collect::() + }) + .collect::>() + .join("\n"); + + assert!( + rendered_blob.contains("tail42"), + "expected wrapped setup URL tail to remain visible in narrow pane, got:\n{rendered_blob}" + ); + } } diff --git a/codex-rs/tui/src/bottom_pane/queued_user_messages.rs b/codex-rs/tui/src/bottom_pane/queued_user_messages.rs index 010b88111c..30a525f457 100644 --- a/codex-rs/tui/src/bottom_pane/queued_user_messages.rs +++ b/codex-rs/tui/src/bottom_pane/queued_user_messages.rs @@ -8,7 +8,7 @@ use ratatui::widgets::Paragraph; use crate::key_hint; use crate::render::renderable::Renderable; use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; +use crate::wrapping::adaptive_wrap_lines; /// Widget that displays a list of user messages queued while a turn is in progress. /// @@ -46,7 +46,7 @@ impl QueuedUserMessages { let mut lines = vec![]; for message in &self.messages { - let wrapped = word_wrap_lines( + let wrapped = adaptive_wrap_lines( message.lines().map(|line| line.dim().italic()), RtOptions::new(width as usize) .initial_indent(Line::from(" ↳ ".dim())) @@ -170,4 +170,36 @@ mod tests { queue.render(Rect::new(0, 0, width, height), &mut buf); assert_snapshot!("render_many_line_message", format!("{buf:?}")); } + + #[test] + fn long_url_like_message_does_not_expand_into_wrapped_ellipsis_rows() { + let mut queue = QueuedUserMessages::new(); + queue.messages.push( + "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/session_id=abc123def456ghi789" + .to_string(), + ); + + let width = 36; + let height = queue.desired_height(width); + assert_eq!( + height, 2, + "expected one message row plus hint row for URL-like token" + ); + + let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); + queue.render(Rect::new(0, 0, width, height), &mut buf); + + let rendered_rows = (0..height) + .map(|y| { + (0..width) + .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' ')) + .collect::() + }) + .collect::>(); + + assert!( + !rendered_rows.iter().any(|row| row.contains('…')), + "expected no wrapped-ellipsis row for URL-like token, got rows: {rendered_rows:?}" + ); + } } diff --git a/codex-rs/tui/src/custom_terminal.rs b/codex-rs/tui/src/custom_terminal.rs index 26284a7fa1..a749ca5d2f 100644 --- a/codex-rs/tui/src/custom_terminal.rs +++ b/codex-rs/tui/src/custom_terminal.rs @@ -43,6 +43,40 @@ use ratatui::layout::Size; use ratatui::style::Color; use ratatui::style::Modifier; use ratatui::widgets::WidgetRef; +use unicode_width::UnicodeWidthStr; + +/// Returns the display width of a cell symbol, ignoring OSC escape sequences. +/// +/// OSC sequences (e.g. OSC 8 hyperlinks: `\x1B]8;;URL\x07`) are terminal +/// control sequences that don't consume display columns. The standard +/// `UnicodeWidthStr::width()` method incorrectly counts the printable +/// characters inside OSC payloads (like `]`, `8`, `;`, and URL characters). +/// This function strips them first so that only visible characters contribute +/// to the width. +fn display_width(s: &str) -> usize { + // Fast path: no escape sequences present. + if !s.contains('\x1B') { + return s.width(); + } + + // Strip OSC sequences: ESC ] ... BEL + let mut visible = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(ch) = chars.next() { + if ch == '\x1B' && chars.clone().next() == Some(']') { + // Consume the ']' and everything up to and including BEL. + chars.next(); // skip ']' + for c in chars.by_ref() { + if c == '\x07' { + break; + } + } + continue; + } + visible.push(ch); + } + visible.width() +} #[derive(Debug, Hash)] pub struct Frame<'a> { @@ -412,7 +446,6 @@ where } use ratatui::buffer::Cell; -use unicode_width::UnicodeWidthStr; #[derive(Debug, IsVariant)] enum DrawCommand { @@ -441,7 +474,7 @@ fn diff_buffers(a: &Buffer, b: &Buffer) -> Vec { let mut column = 0usize; while column < row.len() { let cell = &row[column]; - let width = cell.symbol().width(); + let width = display_width(cell.symbol()); if cell.symbol() != " " || cell.bg != bg || cell.modifier != Modifier::empty() { last_nonblank_column = column + (width.saturating_sub(1)); } @@ -474,9 +507,12 @@ fn diff_buffers(a: &Buffer, b: &Buffer) -> Vec { } } - to_skip = current.symbol().width().saturating_sub(1); + to_skip = display_width(current.symbol()).saturating_sub(1); - let affected_width = std::cmp::max(current.symbol().width(), previous.symbol().width()); + let affected_width = std::cmp::max( + display_width(current.symbol()), + display_width(previous.symbol()), + ); invalidated = std::cmp::max(affected_width, invalidated).saturating_sub(1); } updates diff --git a/codex-rs/tui/src/exec_cell/render.rs b/codex-rs/tui/src/exec_cell/render.rs index 6e57c21520..14f48529dc 100644 --- a/codex-rs/tui/src/exec_cell/render.rs +++ b/codex-rs/tui/src/exec_cell/render.rs @@ -10,8 +10,8 @@ use crate::render::line_utils::prefix_lines; use crate::render::line_utils::push_owned_lines; use crate::shimmer::shimmer_spans; use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_line; -use crate::wrapping::word_wrap_lines; +use crate::wrapping::adaptive_wrap_line; +use crate::wrapping::adaptive_wrap_lines; use codex_ansi_escape::ansi_escape_line; use codex_protocol::parse_command::ParsedCommand; use codex_protocol::protocol::ExecCommandSource; @@ -21,6 +21,8 @@ use itertools::Itertools; use ratatui::prelude::*; use ratatui::style::Modifier; use ratatui::style::Stylize; +use ratatui::widgets::Paragraph; +use ratatui::widgets::Wrap; use textwrap::WordSplitter; use unicode_width::UnicodeWidthStr; @@ -202,10 +204,6 @@ impl HistoryCell for ExecCell { } } - fn desired_transcript_height(&self, width: u16) -> u16 { - self.transcript_lines(width).len() as u16 - } - fn transcript_lines(&self, width: u16) -> Vec> { let mut lines: Vec> = vec![]; for (i, call) in self.iter_calls().enumerate() { @@ -214,7 +212,7 @@ impl HistoryCell for ExecCell { } let script = strip_bash_lc_and_escape(&call.command); let highlighted_script = highlight_bash_to_lines(&script); - let cmd_display = word_wrap_lines( + let cmd_display = adaptive_wrap_lines( &highlighted_script, RtOptions::new(width as usize) .initial_indent("$ ".magenta().into()) @@ -227,7 +225,7 @@ impl HistoryCell for ExecCell { let wrap_width = width.max(1) as usize; let wrap_opts = RtOptions::new(wrap_width); for unwrapped in output.formatted_output.lines().map(ansi_escape_line) { - let wrapped = word_wrap_line(&unwrapped, wrap_opts.clone()); + let wrapped = adaptive_wrap_line(&unwrapped, wrap_opts.clone()); push_owned_lines(&wrapped, &mut lines); } } @@ -341,7 +339,7 @@ impl ExecCell { let line = Line::from(line); let initial_indent = Line::from(vec![title.cyan(), " ".into()]); let subsequent_indent = " ".repeat(initial_indent.width()).into(); - let wrapped = word_wrap_line( + let wrapped = adaptive_wrap_line( &line, RtOptions::new(width as usize) .initial_indent(initial_indent) @@ -401,8 +399,9 @@ impl ExecCell { let available_first_width = (width as usize).saturating_sub(header_prefix_width).max(1); let first_opts = RtOptions::new(available_first_width).word_splitter(WordSplitter::NoHyphenation); + let mut first_wrapped: Vec> = Vec::new(); - push_owned_lines(&word_wrap_line(first, first_opts), &mut first_wrapped); + push_owned_lines(&adaptive_wrap_line(first, first_opts), &mut first_wrapped); let mut first_wrapped_iter = first_wrapped.into_iter(); if let Some(first_segment) = first_wrapped_iter.next() { header_line.extend(first_segment); @@ -411,7 +410,7 @@ impl ExecCell { for line in rest { push_owned_lines( - &word_wrap_line(line, continuation_opts.clone()), + &adaptive_wrap_line(line, continuation_opts.clone()), &mut continuation_lines, ); } @@ -470,20 +469,28 @@ impl ExecCell { RtOptions::new(output_wrap_width).word_splitter(WordSplitter::NoHyphenation); for line in &raw_output.lines { push_owned_lines( - &word_wrap_line(line, output_opts.clone()), + &adaptive_wrap_line(line, output_opts.clone()), &mut wrapped_output, ); } - let trimmed_output = - Self::truncate_lines_middle(&wrapped_output, display_limit, raw_output.omitted); + let prefixed_output = prefix_lines( + wrapped_output, + Span::from(layout.output_block.initial_prefix).dim(), + Span::from(layout.output_block.subsequent_prefix), + ); + let trimmed_output = Self::truncate_lines_middle( + &prefixed_output, + display_limit, + width, + raw_output.omitted, + Some(Line::from( + Span::from(layout.output_block.subsequent_prefix).dim(), + )), + ); if !trimmed_output.is_empty() { - lines.extend(prefix_lines( - trimmed_output, - Span::from(layout.output_block.initial_prefix).dim(), - Span::from(layout.output_block.subsequent_prefix), - )); + lines.extend(trimmed_output); } } } @@ -504,18 +511,55 @@ impl ExecCell { out } + /// Truncates a list of lines to fit within `max_rows` viewport rows, + /// keeping a head portion and a tail portion with an ellipsis line + /// in between. + /// + /// `max_rows` is measured in viewport rows (the actual space a line + /// occupies after `Paragraph::wrap`), not logical lines. Each line's + /// row cost is computed via `Paragraph::line_count` at the given + /// `width`. This ensures that a single logical line containing a + /// long URL (which wraps to several viewport rows) is properly + /// accounted for. + /// + /// The ellipsis message reports the number of omitted *lines* + /// (logical, not rows) to keep the count stable across terminal + /// widths. `omitted_hint` carries forward any previously reported + /// omitted count (from upstream truncation); `ellipsis_prefix` + /// prepends the output gutter prefix to the ellipsis line. fn truncate_lines_middle( lines: &[Line<'static>], - max: usize, + max_rows: usize, + width: u16, omitted_hint: Option, + ellipsis_prefix: Option>, ) -> Vec> { - if max == 0 { + let width = width.max(1); + if max_rows == 0 { return Vec::new(); } - if lines.len() <= max { + let line_rows: Vec = lines + .iter() + .map(|line| { + let is_whitespace_only = line + .spans + .iter() + .all(|span| span.content.chars().all(char::is_whitespace)); + if is_whitespace_only { + line.width().div_ceil(usize::from(width)).max(1) + } else { + Paragraph::new(Text::from(vec![line.clone()])) + .wrap(Wrap { trim: false }) + .line_count(width) + .max(1) + } + }) + .collect(); + let total_rows: usize = line_rows.iter().sum(); + if total_rows <= max_rows { return lines.to_vec(); } - if max == 1 { + if max_rows == 1 { // Carry forward any previously omitted count and add any // additionally hidden content lines from this truncation. let base = omitted_hint.unwrap_or(0); @@ -526,27 +570,53 @@ impl ExecCell { .len() .saturating_sub(usize::from(omitted_hint.is_some())); let omitted = base + extra; - return vec![Self::ellipsis_line(omitted)]; + return vec![Self::ellipsis_line_with_prefix( + omitted, + ellipsis_prefix.as_ref(), + )]; } - let head = (max - 1) / 2; - let tail = max - head - 1; - let mut out: Vec> = Vec::new(); - - if head > 0 { - out.extend(lines[..head].iter().cloned()); + let head_budget = (max_rows - 1) / 2; + let tail_budget = max_rows - head_budget - 1; + let mut head_lines: Vec> = Vec::new(); + let mut head_rows = 0usize; + let mut head_end = 0usize; + while head_end < lines.len() { + let line_row_count = line_rows[head_end]; + if head_rows + line_row_count > head_budget { + break; + } + head_rows += line_row_count; + head_lines.push(lines[head_end].clone()); + head_end += 1; } + let mut tail_lines_reversed: Vec> = Vec::new(); + let mut tail_rows = 0usize; + let mut tail_start = lines.len(); + while tail_start > head_end { + let idx = tail_start - 1; + let line_row_count = line_rows[idx]; + if tail_rows + line_row_count > tail_budget { + break; + } + tail_rows += line_row_count; + tail_lines_reversed.push(lines[idx].clone()); + tail_start -= 1; + } + + let mut out = head_lines; let base = omitted_hint.unwrap_or(0); let additional = lines .len() - .saturating_sub(head + tail) + .saturating_sub(out.len() + tail_lines_reversed.len()) .saturating_sub(usize::from(omitted_hint.is_some())); - out.push(Self::ellipsis_line(base + additional)); + out.push(Self::ellipsis_line_with_prefix( + base + additional, + ellipsis_prefix.as_ref(), + )); - if tail > 0 { - out.extend(lines[lines.len() - tail..].iter().cloned()); - } + out.extend(tail_lines_reversed.into_iter().rev()); out } @@ -554,6 +624,14 @@ impl ExecCell { fn ellipsis_line(omitted: usize) -> Line<'static> { Line::from(vec![format!("… +{omitted} lines").dim()]) } + + /// Builds an ellipsis line (`… +N lines`) with an optional leading + /// prefix so the ellipsis aligns with the output gutter. + fn ellipsis_line_with_prefix(omitted: usize, prefix: Option<&Line<'static>>) -> Line<'static> { + let mut line = prefix.cloned().unwrap_or_default(); + line.push_span(format!("… +{omitted} lines").dim()); + line + } } #[derive(Clone, Copy)] @@ -612,20 +690,15 @@ const EXEC_DISPLAY_LAYOUT: ExecDisplayLayout = ExecDisplayLayout::new( mod tests { use super::*; use codex_protocol::protocol::ExecCommandSource; + use pretty_assertions::assert_eq; #[test] fn user_shell_output_is_limited_by_screen_lines() { - // Construct a user shell exec cell whose aggregated output consists of a - // small number of very long logical lines. These will wrap into many - // on-screen lines at narrow widths. - // - // Use a short marker so it survives wrapping intact inside each - // rendered screen line; the previous test used a marker longer than - // the wrap width, so it was split across lines and the assertion - // never actually saw it. - let marker = "Z"; - let long_chunk = marker.repeat(800); - let aggregated_output = format!("{long_chunk}\n{long_chunk}\n"); + let long_url_like = format!( + "https://example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/{}", + "very-long-segment-".repeat(120), + ); + let aggregated_output = format!("{long_url_like}\n{long_url_like}\n"); // Baseline: how many screen lines would we get if we simply wrapped // all logical lines without any truncation? @@ -653,14 +726,18 @@ mod tests { let mut full_wrapped_output: Vec> = Vec::new(); for line in &raw_output.lines { push_owned_lines( - &word_wrap_line(line, output_opts.clone()), + &adaptive_wrap_line(line, output_opts.clone()), &mut full_wrapped_output, ); } - let full_screen_lines = full_wrapped_output - .iter() - .filter(|line| line.spans.iter().any(|span| span.content.contains(marker))) - .count(); + let full_prefixed_output = prefix_lines( + full_wrapped_output, + Span::from(layout.output_block.initial_prefix).dim(), + Span::from(layout.output_block.subsequent_prefix), + ); + let full_screen_lines = Paragraph::new(Text::from(full_prefixed_output)) + .wrap(Wrap { trim: false }) + .line_count(width); // Sanity check: this scenario should produce more screen lines than // the user shell per-call limit when no truncation is applied. If @@ -685,21 +762,207 @@ mod tests { // Use a narrow width so each logical line wraps into many on-screen lines. let lines = cell.command_display_lines(width); + let rendered_rows = Paragraph::new(Text::from(lines.clone())) + .wrap(Wrap { trim: false }) + .line_count(width); + let header_rows = Paragraph::new(Text::from(vec![lines[0].clone()])) + .wrap(Wrap { trim: false }) + .line_count(width); + let output_screen_rows = rendered_rows.saturating_sub(header_rows); - // Count how many rendered lines contain our marker text. This approximates - // the number of visible output "screen lines" for this command. - let output_screen_lines = lines + let contains_ellipsis = lines .iter() - .filter(|line| line.spans.iter().any(|span| span.content.contains(marker))) - .count(); + .any(|line| line.spans.iter().any(|span| span.content.contains("… +"))); // Regression guard: previously this scenario could render hundreds of - // wrapped lines because truncation happened before wrapping. Now the - // truncation is applied after wrapping, so the number of visible - // screen lines is bounded by USER_SHELL_TOOL_CALL_MAX_LINES. + // wrapped rows because truncation happened before final viewport + // wrapping. The row-aware truncation now caps visible output rows. assert!( - output_screen_lines <= USER_SHELL_TOOL_CALL_MAX_LINES, - "expected at most {USER_SHELL_TOOL_CALL_MAX_LINES} screen lines of user shell output, got {output_screen_lines}", + output_screen_rows <= USER_SHELL_TOOL_CALL_MAX_LINES, + "expected at most {USER_SHELL_TOOL_CALL_MAX_LINES} output rows, got {output_screen_rows} (total rows: {rendered_rows})", + ); + assert!( + contains_ellipsis, + "expected truncated output to include an ellipsis line" + ); + } + + #[test] + fn truncate_lines_middle_keeps_omitted_count_in_line_units() { + let lines = vec![ + Line::from(" └ short"), + Line::from(" this-is-a-very-long-token-that-wraps-many-rows"), + Line::from(" … +4 lines"), + Line::from(" tail"), + ]; + + let truncated = + ExecCell::truncate_lines_middle(&lines, 2, 12, Some(4), Some(Line::from(" ".dim()))); + let rendered: Vec = truncated + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect(); + + assert!( + rendered.iter().any(|line| line.contains("… +6 lines")), + "expected omitted hint to count hidden lines (not wrapped rows), got: {rendered:?}" + ); + } + + #[test] + fn truncate_lines_middle_does_not_truncate_blank_prefixed_output_lines() { + let mut lines = vec![Line::from(" └ start")]; + lines.extend(std::iter::repeat_n(Line::from(" "), 26)); + lines.push(Line::from(" end")); + + let truncated = ExecCell::truncate_lines_middle(&lines, 28, 80, None, None); + + assert_eq!(truncated, lines); + } + + #[test] + fn command_display_does_not_split_long_url_token() { + let url = "http://example.com/long-url-with-dashes-wider-than-terminal-window/blah-blah-blah-text/more-gibberish-text"; + + let call = ExecCall { + call_id: "call-id".to_string(), + command: vec!["bash".into(), "-lc".into(), format!("echo {url}")], + parsed: Vec::new(), + output: None, + source: ExecCommandSource::UserShell, + start_time: None, + duration: None, + interaction_input: None, + }; + + let cell = ExecCell::new(call, false); + let rendered: Vec = cell + .command_display_lines(36) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect(); + + assert_eq!( + rendered.iter().filter(|line| line.contains(url)).count(), + 1, + "expected full URL in one rendered line, got: {rendered:?}" + ); + } + + #[test] + fn exploring_display_does_not_split_long_url_like_search_query() { + let url_like = "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path"; + let call = ExecCall { + call_id: "call-id".to_string(), + command: vec!["bash".into(), "-lc".into(), "rg foo".into()], + parsed: vec![ParsedCommand::Search { + cmd: format!("rg {url_like}"), + query: Some(url_like.to_string()), + path: None, + }], + output: None, + source: ExecCommandSource::Agent, + start_time: None, + duration: None, + interaction_input: None, + }; + + let cell = ExecCell::new(call, false); + let rendered: Vec = cell + .display_lines(36) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect(); + + assert_eq!( + rendered + .iter() + .filter(|line| line.contains(url_like)) + .count(), + 1, + "expected full URL-like query in one rendered line, got: {rendered:?}" + ); + } + + #[test] + fn output_display_does_not_split_long_url_like_token_without_scheme() { + let url = "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/session_id=abc123def456ghi789jkl012mno345pqr678"; + + let call = ExecCall { + call_id: "call-id".to_string(), + command: vec!["bash".into(), "-lc".into(), "echo done".into()], + parsed: Vec::new(), + output: Some(CommandOutput { + exit_code: 0, + formatted_output: String::new(), + aggregated_output: url.to_string(), + }), + source: ExecCommandSource::UserShell, + start_time: None, + duration: None, + interaction_input: None, + }; + + let cell = ExecCell::new(call, false); + let rendered: Vec = cell + .command_display_lines(36) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect(); + + assert_eq!( + rendered.iter().filter(|line| line.contains(url)).count(), + 1, + "expected full URL-like token in one rendered line, got: {rendered:?}" + ); + } + + #[test] + fn desired_transcript_height_accounts_for_wrapped_url_like_rows() { + let url = "https://example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path/that/keeps/going/for/testing/purposes"; + let call = ExecCall { + call_id: "call-id".to_string(), + command: vec!["bash".into(), "-lc".into(), "echo done".into()], + parsed: Vec::new(), + output: Some(CommandOutput { + exit_code: 0, + formatted_output: url.to_string(), + aggregated_output: url.to_string(), + }), + source: ExecCommandSource::Agent, + start_time: None, + duration: None, + interaction_input: None, + }; + + let cell = ExecCell::new(call, false); + let width: u16 = 36; + let logical_height = cell.transcript_lines(width).len() as u16; + let wrapped_height = cell.desired_transcript_height(width); + + assert!( + wrapped_height > logical_height, + "expected transcript height to account for wrapped URL-like rows, logical_height={logical_height}, wrapped_height={wrapped_height}" ); } } diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index bd08c370e4..5ec09c25ff 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -34,8 +34,8 @@ use crate::ui_consts::LIVE_PREFIX_COLS; use crate::update_action::UpdateAction; use crate::version::CODEX_CLI_VERSION; use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_line; -use crate::wrapping::word_wrap_lines; +use crate::wrapping::adaptive_wrap_line; +use crate::wrapping::adaptive_wrap_lines; use base64::Engine; use codex_core::config::Config; use codex_core::config::types::McpServerTransportConfig; @@ -82,9 +82,26 @@ use unicode_width::UnicodeWidthStr; /// Represents an event to display in the conversation history. Returns its /// `Vec>` representation to make it easier to display in a /// scrollable list. +/// A single renderable unit of conversation history. +/// +/// Each cell produces logical `Line`s and reports how many viewport +/// rows those lines occupy at a given terminal width. The default +/// height implementations use `Paragraph::wrap` to account for lines +/// that overflow the viewport width (e.g. long URLs that are kept +/// intact by adaptive wrapping). Concrete types only need to override +/// heights when they apply additional layout logic beyond what +/// `Paragraph::line_count` captures. pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any { + /// Returns the logical lines for the main chat viewport. fn display_lines(&self, width: u16) -> Vec>; + /// Returns the number of viewport rows needed to render this cell. + /// + /// The default delegates to `Paragraph::line_count` with + /// `Wrap { trim: false }`, which measures the actual row count after + /// ratatui's viewport-level character wrapping. This is critical + /// for lines containing URL-like tokens that are wider than the + /// terminal — the logical line count would undercount. fn desired_height(&self, width: u16) -> u16 { Paragraph::new(Text::from(self.display_lines(width))) .wrap(Wrap { trim: false }) @@ -93,13 +110,24 @@ pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any { .unwrap_or(0) } + /// Returns lines for the transcript overlay (`Ctrl+T`). + /// + /// Defaults to `display_lines`. Override when the transcript + /// representation differs (e.g. `ExecCell` shows all calls with + /// `$`-prefixed commands and exit status). fn transcript_lines(&self, width: u16) -> Vec> { self.display_lines(width) } + /// Returns the number of viewport rows for the transcript overlay. + /// + /// Uses the same `Paragraph::line_count` measurement as + /// `desired_height`. Contains a workaround for a ratatui bug where + /// a single whitespace-only line reports 2 rows instead of 1. fn desired_transcript_height(&self, width: u16) -> u16 { let lines = self.transcript_lines(width); - // Workaround for ratatui bug: if there's only one line and it's whitespace-only, ratatui gives 2 lines. + // Workaround: ratatui's line_count returns 2 for a single + // whitespace-only line. Clamp to 1 in that case. if let [line] = &lines[..] && line .spans @@ -138,15 +166,16 @@ pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any { impl Renderable for Box { fn render(&self, area: Rect, buf: &mut Buffer) { let lines = self.display_lines(area.width); + let paragraph = Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false }); let y = if area.height == 0 { 0 } else { - let overflow = lines.len().saturating_sub(usize::from(area.height)); + let overflow = paragraph + .line_count(area.width) + .saturating_sub(usize::from(area.height)); u16::try_from(overflow).unwrap_or(u16::MAX) }; - Paragraph::new(Text::from(lines)) - .scroll((y, 0)) - .render(area, buf); + paragraph.scroll((y, 0)).render(area, buf); } fn desired_height(&self, width: u16) -> u16 { HistoryCell::desired_height(self.as_ref(), width) @@ -266,7 +295,7 @@ impl HistoryCell for UserHistoryCell { let wrapped_remote_images = if self.remote_image_urls.is_empty() { None } else { - Some(word_wrap_lines( + Some(adaptive_wrap_lines( self.remote_image_urls .iter() .enumerate() @@ -282,7 +311,7 @@ impl HistoryCell for UserHistoryCell { None } else if self.text_elements.is_empty() { let message_without_trailing_newlines = self.message.trim_end_matches(['\r', '\n']); - let wrapped = word_wrap_lines( + let wrapped = adaptive_wrap_lines( message_without_trailing_newlines .split('\n') .map(|line| Line::from(line).style(style)), @@ -299,7 +328,7 @@ impl HistoryCell for UserHistoryCell { style, element_style, ); - let wrapped = word_wrap_lines( + let wrapped = adaptive_wrap_lines( raw_lines, RtOptions::new(usize::from(wrap_width)) .wrap_algorithm(textwrap::WrapAlgorithm::FirstFit), @@ -336,20 +365,6 @@ impl HistoryCell for UserHistoryCell { lines.push(Line::from("").style(style)); lines } - - fn desired_height(&self, width: u16) -> u16 { - self.display_lines(width) - .len() - .try_into() - .unwrap_or(u16::MAX) - } - - fn desired_transcript_height(&self, width: u16) -> u16 { - self.display_lines(width) - .len() - .try_into() - .unwrap_or(u16::MAX) - } } #[derive(Debug)] @@ -388,7 +403,7 @@ impl ReasoningSummaryCell { }) .collect::>(); - word_wrap_lines( + adaptive_wrap_lines( &summary_lines, RtOptions::new(width as usize) .initial_indent("• ".dim().into()) @@ -406,21 +421,9 @@ impl HistoryCell for ReasoningSummaryCell { } } - fn desired_height(&self, width: u16) -> u16 { - if self.transcript_only { - 0 - } else { - self.lines(width).len() as u16 - } - } - fn transcript_lines(&self, width: u16) -> Vec> { self.lines(width) } - - fn desired_transcript_height(&self, width: u16) -> u16 { - self.lines(width).len() as u16 - } } #[derive(Debug)] @@ -440,7 +443,7 @@ impl AgentMessageCell { impl HistoryCell for AgentMessageCell { fn display_lines(&self, width: u16) -> Vec> { - word_wrap_lines( + adaptive_wrap_lines( &self.lines, RtOptions::new(width as usize) .initial_indent(if self.is_first_line { @@ -557,14 +560,7 @@ impl HistoryCell for PrefixedWrappedHistoryCell { let opts = RtOptions::new(width.max(1) as usize) .initial_indent(self.initial_prefix.clone()) .subsequent_indent(self.subsequent_prefix.clone()); - let wrapped = word_wrap_lines(&self.text, opts); - let mut out = Vec::new(); - push_owned_lines(&wrapped, &mut out); - out - } - - fn desired_height(&self, width: u16) -> u16 { - self.display_lines(width).len() as u16 + adaptive_wrap_lines(&self.text, opts) } } @@ -605,7 +601,7 @@ impl HistoryCell for UnifiedExecInteractionCell { let header = Line::from(header_spans); let mut out: Vec> = Vec::new(); - let header_wrapped = word_wrap_line(&header, RtOptions::new(wrap_width)); + let header_wrapped = adaptive_wrap_line(&header, RtOptions::new(wrap_width)); push_owned_lines(&header_wrapped, &mut out); if waited_only { @@ -618,7 +614,7 @@ impl HistoryCell for UnifiedExecInteractionCell { .map(|line| Line::from(line.to_string())) .collect(); - let input_wrapped = word_wrap_lines( + let input_wrapped = adaptive_wrap_lines( input_lines, RtOptions::new(wrap_width) .initial_indent(Line::from(" └ ".dim())) @@ -627,10 +623,6 @@ impl HistoryCell for UnifiedExecInteractionCell { out.extend(input_wrapped); out } - - fn desired_height(&self, width: u16) -> u16 { - self.display_lines(width).len() as u16 - } } pub(crate) fn new_unified_exec_interaction( @@ -1397,7 +1389,7 @@ impl HistoryCell for McpToolCallCell { let opts = RtOptions::new((width as usize).saturating_sub(4)) .initial_indent("".into()) .subsequent_indent(" ".into()); - let wrapped = word_wrap_line(&invocation_line, opts); + let wrapped = adaptive_wrap_line(&invocation_line, opts); let body_lines: Vec> = wrapped.iter().map(line_to_static).collect(); lines.extend(prefix_lines(body_lines, " └ ".dim(), " ".into())); } @@ -1414,7 +1406,7 @@ impl HistoryCell for McpToolCallCell { let text = Self::render_content_block(block, detail_wrap_width); for segment in text.split('\n') { let line = Line::from(segment.to_string().dim()); - let wrapped = word_wrap_line( + let wrapped = adaptive_wrap_line( &line, RtOptions::new(detail_wrap_width) .initial_indent("".into()) @@ -1432,7 +1424,7 @@ impl HistoryCell for McpToolCallCell { width as usize, ); let err_line = Line::from(err_text.dim()); - let wrapped = word_wrap_line( + let wrapped = adaptive_wrap_line( &err_line, RtOptions::new(detail_wrap_width) .initial_indent("".into()) @@ -1645,11 +1637,9 @@ impl HistoryCell for DeprecationNoticeCell { let wrap_width = width.saturating_sub(4).max(1) as usize; if let Some(details) = &self.details { - let line = textwrap::wrap(details, wrap_width) - .into_iter() - .map(|s| s.to_string().dim().into()) - .collect::>(); - lines.extend(line); + let detail_line = Line::from(details.clone().dim()); + let wrapped = adaptive_wrap_line(&detail_line, RtOptions::new(wrap_width)); + push_owned_lines(&wrapped, &mut lines); } lines @@ -1974,17 +1964,14 @@ fn wrap_with_prefix( subsequent_prefix: Span<'static>, style: Style, ) -> Vec> { - let prefix_width = initial_prefix - .content - .width() - .max(subsequent_prefix.content.width()); - let wrap_width = width.saturating_sub(prefix_width).max(1); - let wrapped = textwrap::wrap(text, wrap_width); - let wrapped_lines = wrapped - .into_iter() - .map(|segment| Span::from(segment.to_string()).set_style(style).into()) - .collect::>>(); - prefix_lines(wrapped_lines, initial_prefix, subsequent_prefix) + let line = Line::from(vec![Span::from(text.to_string()).set_style(style)]); + let opts = RtOptions::new(width.max(1)) + .initial_indent(Line::from(vec![initial_prefix])) + .subsequent_indent(Line::from(vec![subsequent_prefix])); + let wrapped = adaptive_wrap_line(&line, opts); + let mut out = Vec::new(); + push_owned_lines(&wrapped, &mut out); + out } /// Split a request_user_input answer into option labels and an optional freeform note. @@ -2077,10 +2064,11 @@ impl HistoryCell for PlanUpdateCell { fn display_lines(&self, width: u16) -> Vec> { let render_note = |text: &str| -> Vec> { let wrap_width = width.saturating_sub(4).max(1) as usize; - textwrap::wrap(text, wrap_width) - .into_iter() - .map(|s| s.to_string().dim().italic().into()) - .collect() + let note = Line::from(text.to_string().dim().italic()); + let wrapped = adaptive_wrap_line(¬e, RtOptions::new(wrap_width)); + let mut out = Vec::new(); + push_owned_lines(&wrapped, &mut out); + out }; let render_step = |status: &StepStatus, text: &str| -> Vec> { @@ -2089,16 +2077,15 @@ impl HistoryCell for PlanUpdateCell { StepStatus::InProgress => ("□ ", Style::default().cyan().bold()), StepStatus::Pending => ("□ ", Style::default().dim()), }; - let wrap_width = (width as usize) - .saturating_sub(4) - .saturating_sub(box_str.width()) - .max(1); - let parts = textwrap::wrap(text, wrap_width); - let step_text = parts - .into_iter() - .map(|s| s.to_string().set_style(step_style).into()) - .collect(); - prefix_lines(step_text, box_str.into(), " ".into()) + + let opts = RtOptions::new(width.saturating_sub(4).max(1) as usize) + .initial_indent(box_str.into()) + .subsequent_indent(" ".into()); + let step = Line::from(text.to_string().set_style(step_style)); + let wrapped = adaptive_wrap_line(&step, opts); + let mut out = Vec::new(); + push_owned_lines(&wrapped, &mut out); + out }; let mut lines: Vec> = vec![]; @@ -2713,6 +2700,113 @@ mod tests { ); } + #[test] + fn prefixed_wrapped_history_cell_does_not_split_url_like_token() { + let url_like = + "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890"; + let cell = PrefixedWrappedHistoryCell::new(Line::from(url_like), "✔ ".green(), " "); + let rendered = render_lines(&cell.display_lines(24)); + + assert_eq!( + rendered + .iter() + .filter(|line| line.contains(url_like)) + .count(), + 1, + "expected full URL-like token in one rendered line, got: {rendered:?}" + ); + } + + #[test] + fn unified_exec_interaction_cell_does_not_split_url_like_stdin_token() { + let url_like = + "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890"; + let cell = UnifiedExecInteractionCell::new(Some("true".to_string()), url_like.to_string()); + let rendered = render_lines(&cell.display_lines(24)); + + assert_eq!( + rendered + .iter() + .filter(|line| line.contains(url_like)) + .count(), + 1, + "expected full URL-like token in one rendered line, got: {rendered:?}" + ); + } + + #[test] + fn prefixed_wrapped_history_cell_height_matches_wrapped_rendering() { + let url_like = "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path"; + let cell: Box = Box::new(PrefixedWrappedHistoryCell::new( + Line::from(url_like), + "✔ ".green(), + " ", + )); + + let width: u16 = 24; + let logical_height = cell.display_lines(width).len() as u16; + let wrapped_height = cell.desired_height(width); + assert!( + wrapped_height > logical_height, + "expected wrapped height to exceed logical line count ({logical_height}), got {wrapped_height}" + ); + + let area = Rect::new(0, 0, width, wrapped_height); + let mut buf = ratatui::buffer::Buffer::empty(area); + cell.render(area, &mut buf); + + let first_row = (0..area.width) + .map(|x| { + let symbol = buf[(x, 0)].symbol(); + if symbol.is_empty() { + ' ' + } else { + symbol.chars().next().unwrap_or(' ') + } + }) + .collect::(); + assert!( + first_row.contains("✔"), + "expected first rendered row to keep the prefix visible, got: {first_row:?}" + ); + } + + #[test] + fn unified_exec_interaction_cell_height_matches_wrapped_rendering() { + let url_like = "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path"; + let cell: Box = Box::new(UnifiedExecInteractionCell::new( + Some("true".to_string()), + url_like.to_string(), + )); + + let width: u16 = 24; + let logical_height = cell.display_lines(width).len() as u16; + let wrapped_height = cell.desired_height(width); + assert!( + wrapped_height > logical_height, + "expected wrapped height to exceed logical line count ({logical_height}), got {wrapped_height}" + ); + + let area = Rect::new(0, 0, width, wrapped_height); + let mut buf = ratatui::buffer::Buffer::empty(area); + cell.render(area, &mut buf); + + let first_row = (0..area.width) + .map(|x| { + let symbol = buf[(x, 0)].symbol(); + if symbol.is_empty() { + ' ' + } else { + symbol.chars().next().unwrap_or(' ') + } + }) + .collect::(); + assert!( + first_row.contains("Interacted with"), + "expected first rendered row to keep the header visible, got: {first_row:?}" + ); + } + #[test] fn web_search_history_cell_snapshot() { let query = @@ -3564,6 +3658,55 @@ mod tests { assert!(rendered.iter().any(|line| line.contains("tokenized"))); } + #[test] + fn render_uses_wrapping_for_long_url_like_line() { + let url = "https://example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path/that/keeps/going/for/testing/purposes-only-and-does/not/need/to/resolve/index.html?session_id=abc123def456ghi789jkl012mno345pqr678stu901vwx234yz"; + let cell: Box = Box::new(UserHistoryCell { + message: url.to_string(), + text_elements: Vec::new(), + local_image_paths: Vec::new(), + remote_image_urls: Vec::new(), + }); + + let width: u16 = 52; + let height = cell.desired_height(width); + assert!( + height > 1, + "expected wrapped height for long URL, got {height}" + ); + + let area = Rect::new(0, 0, width, height); + let mut buf = ratatui::buffer::Buffer::empty(area); + cell.render(area, &mut buf); + + let rendered = (0..area.height) + .map(|y| { + (0..area.width) + .map(|x| { + let symbol = buf[(x, y)].symbol(); + if symbol.is_empty() { + ' ' + } else { + symbol.chars().next().unwrap_or(' ') + } + }) + .collect::() + }) + .collect::>(); + let rendered_blob = rendered.join("\n"); + + assert!( + rendered_blob.contains("session_id=abc123"), + "expected URL tail to be visible after wrapping, got:\n{rendered_blob}" + ); + + let non_empty_rows = rendered.iter().filter(|row| !row.trim().is_empty()).count() as u16; + assert!( + non_empty_rows > 3, + "expected long URL to span multiple visible rows, got:\n{rendered_blob}" + ); + } + #[test] fn plan_update_with_note_and_wrapping_snapshot() { // Long explanation forces wrapping; include long step text to verify step wrapping and alignment. @@ -3616,6 +3759,43 @@ mod tests { let rendered = render_lines(&lines).join("\n"); insta::assert_snapshot!(rendered); } + + #[test] + fn plan_update_does_not_split_url_like_tokens_in_note_or_step() { + let note_url = + "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890"; + let step_url = "example.test/api/v1/projects/beta-team/releases/2026-02-17/builds/0987654321/artifacts/reports/performance"; + let update = UpdatePlanArgs { + explanation: Some(format!( + "Investigate failures under {note_url} immediately." + )), + plan: vec![PlanItemArg { + step: format!("Validate callbacks under {step_url} before rollout."), + status: StepStatus::InProgress, + }], + }; + + let cell = new_plan_update(update); + let rendered = render_lines(&cell.display_lines(30)); + + assert_eq!( + rendered + .iter() + .filter(|line| line.contains(note_url)) + .count(), + 1, + "expected full note URL-like token in one rendered line, got: {rendered:?}" + ); + assert_eq!( + rendered + .iter() + .filter(|line| line.contains(step_url)) + .count(), + 1, + "expected full step URL-like token in one rendered line, got: {rendered:?}" + ); + } + #[test] fn reasoning_summary_block() { let cell = new_reasoning_summary_block( @@ -3629,6 +3809,50 @@ mod tests { assert_eq!(rendered_transcript, vec!["• Detailed reasoning goes here."]); } + #[test] + fn reasoning_summary_height_matches_wrapped_rendering_for_url_like_content() { + let summary = "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path/that/keeps/going"; + let cell: Box = Box::new(ReasoningSummaryCell::new( + "High level reasoning".to_string(), + summary.to_string(), + false, + )); + let width: u16 = 24; + + let logical_height = cell.display_lines(width).len() as u16; + let wrapped_height = cell.desired_height(width); + let expected_wrapped_height = Paragraph::new(Text::from(cell.display_lines(width))) + .wrap(Wrap { trim: false }) + .line_count(width) as u16; + assert_eq!(wrapped_height, expected_wrapped_height); + assert!( + wrapped_height >= logical_height, + "expected wrapped height to be at least logical line count ({logical_height}), got {wrapped_height}" + ); + + let wrapped_transcript_height = cell.desired_transcript_height(width); + assert_eq!(wrapped_transcript_height, wrapped_height); + + let area = Rect::new(0, 0, width, wrapped_height); + let mut buf = ratatui::buffer::Buffer::empty(area); + cell.render(area, &mut buf); + + let first_row = (0..area.width) + .map(|x| { + let symbol = buf[(x, 0)].symbol(); + if symbol.is_empty() { + ' ' + } else { + symbol.chars().next().unwrap_or(' ') + } + }) + .collect::(); + assert!( + first_row.contains("•"), + "expected first rendered row to keep summary bullet visible, got: {first_row:?}" + ); + } + #[test] fn reasoning_summary_block_returns_reasoning_cell_when_feature_disabled() { let cell = new_reasoning_summary_block("Detailed reasoning goes here.".to_string()); diff --git a/codex-rs/tui/src/insert_history.rs b/codex-rs/tui/src/insert_history.rs index 36ef47da5e..9fe4316a98 100644 --- a/codex-rs/tui/src/insert_history.rs +++ b/codex-rs/tui/src/insert_history.rs @@ -2,9 +2,16 @@ use std::fmt; use std::io; use std::io::Write; -use crate::wrapping::word_wrap_lines_borrowed; +use crate::wrapping::RtOptions; +use crate::wrapping::adaptive_wrap_line; +use crate::wrapping::line_contains_url_like; +use crate::wrapping::line_has_mixed_url_and_non_url_tokens; use crossterm::Command; +use crossterm::cursor::MoveDown; use crossterm::cursor::MoveTo; +use crossterm::cursor::MoveToColumn; +use crossterm::cursor::RestorePosition; +use crossterm::cursor::SavePosition; use crossterm::queue; use crossterm::style::Color as CColor; use crossterm::style::Colors; @@ -38,10 +45,35 @@ where let last_cursor_pos = terminal.last_known_cursor_pos; let writer = terminal.backend_mut(); - // Pre-wrap lines using word-aware wrapping so terminal scrollback sees the same - // formatting as the TUI. This avoids character-level hard wrapping by the terminal. - let wrapped = word_wrap_lines_borrowed(&lines, area.width.max(1) as usize); - let wrapped_lines = wrapped.len() as u16; + // Pre-wrap lines for terminal scrollback. Three paths: + // + // - URL-only-ish lines are kept intact (no hard newlines inserted) so that + // terminal emulators can match them as clickable links. The + // terminal will character-wrap these lines at the viewport + // boundary. + // - Mixed lines (URL + non-URL prose) are adaptively wrapped so + // non-URL text still wraps naturally while URL tokens remain + // unsplit. + // - Non-URL lines also flow through adaptive wrapping; behavior is + // equivalent to standard wrapping when no URL is present. + let wrap_width = area.width.max(1) as usize; + let mut wrapped = Vec::new(); + let mut wrapped_rows = 0usize; + + for line in &lines { + let line_wrapped = + if line_contains_url_like(line) && !line_has_mixed_url_and_non_url_tokens(line) { + vec![line.clone()] + } else { + adaptive_wrap_line(line, RtOptions::new(wrap_width)) + }; + wrapped_rows += line_wrapped + .iter() + .map(|wrapped_line| wrapped_line.width().max(1).div_ceil(wrap_width)) + .sum::(); + wrapped.extend(line_wrapped); + } + let wrapped_lines = wrapped_rows as u16; let cursor_top = if area.bottom() < screen_size.height { // If the viewport is not at the bottom of the screen, scroll it down to make room. // Don't scroll it past the bottom of the screen. @@ -94,6 +126,18 @@ where for line in wrapped { queue!(writer, Print("\r\n"))?; + // URL lines can be wider than the terminal and will + // character-wrap onto continuation rows. Pre-clear those rows + // so stale content from a previously longer line is erased. + let physical_rows = line.width().max(1).div_ceil(wrap_width); + if physical_rows > 1 { + queue!(writer, SavePosition)?; + for _ in 1..physical_rows { + queue!(writer, MoveDown(1), MoveToColumn(0))?; + queue!(writer, Clear(ClearType::UntilNewLine))?; + } + queue!(writer, RestorePosition)?; + } queue!( writer, SetColors(Colors::new( @@ -527,4 +571,163 @@ mod tests { ); } } + + #[test] + fn vt100_prefixed_url_keeps_prefix_and_url_on_same_row() { + let width: u16 = 48; + let height: u16 = 8; + let backend = VT100Backend::new(width, height); + let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); + let viewport = Rect::new(0, height - 1, width, 1); + term.set_viewport_area(viewport); + + let url = "http://a-long-url.com/this/that/blablablab/new.aspx/many_people_like_how"; + let line: Line<'static> = Line::from(vec![" │ ".into(), url.into()]); + + insert_history_lines(&mut term, vec![line]).expect("insert history"); + + let rows: Vec = term.backend().vt100().screen().rows(0, width).collect(); + + assert!( + rows.iter().any(|r| r.contains("│ http://a-long-url.com")), + "expected prefix and URL on same row, rows: {rows:?}" + ); + assert!( + !rows.iter().any(|r| r.trim_end() == "│"), + "unexpected orphan prefix row, rows: {rows:?}" + ); + } + + #[test] + fn vt100_prefixed_url_like_without_scheme_keeps_prefix_and_token_on_same_row() { + let width: u16 = 48; + let height: u16 = 8; + let backend = VT100Backend::new(width, height); + let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); + let viewport = Rect::new(0, height - 1, width, 1); + term.set_viewport_area(viewport); + + let url_like = + "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890"; + let line: Line<'static> = Line::from(vec![" │ ".into(), url_like.into()]); + + insert_history_lines(&mut term, vec![line]).expect("insert history"); + + let rows: Vec = term.backend().vt100().screen().rows(0, width).collect(); + + assert!( + rows.iter() + .any(|r| r.contains("│ example.test/api/v1/projects")), + "expected prefix and URL-like token on same row, rows: {rows:?}" + ); + assert!( + !rows.iter().any(|r| r.trim_end() == "│"), + "unexpected orphan prefix row, rows: {rows:?}" + ); + } + + #[test] + fn vt100_prefixed_mixed_url_line_wraps_suffix_words_together() { + let width: u16 = 24; + let height: u16 = 10; + let backend = VT100Backend::new(width, height); + let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); + let viewport = Rect::new(0, height - 1, width, 1); + term.set_viewport_area(viewport); + + let url = "https://example.test/path/abcdef12345"; + let line: Line<'static> = Line::from(vec![ + " │ ".into(), + "see ".into(), + url.into(), + " tail words".into(), + ]); + + insert_history_lines(&mut term, vec![line]).expect("insert mixed history"); + + let rows: Vec = term.backend().vt100().screen().rows(0, width).collect(); + assert!( + rows.iter().any(|r| r.contains("│ see")), + "expected prefixed prose before URL, rows: {rows:?}" + ); + assert!( + rows.iter().any(|r| r.contains("tail words")), + "expected suffix words to wrap as a phrase, rows: {rows:?}" + ); + } + + #[test] + fn vt100_unwrapped_url_like_clears_continuation_rows() { + let width: u16 = 20; + let height: u16 = 10; + let backend = VT100Backend::new(width, height); + let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); + let viewport = Rect::new(0, height - 1, width, 1); + term.set_viewport_area(viewport); + + let filler_line: Line<'static> = Line::from(vec![ + " │ ".into(), + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".into(), + ]); + insert_history_lines(&mut term, vec![filler_line]).expect("insert filler history"); + + let url_like = "example.test/api/v1/short"; + let url_line: Line<'static> = Line::from(vec![" │ ".into(), url_like.into()]); + insert_history_lines(&mut term, vec![url_line]).expect("insert url-like history"); + + let rows: Vec = term.backend().vt100().screen().rows(0, width).collect(); + let first_row = rows + .iter() + .position(|row| row.contains("│ example.test/api")) + .unwrap_or_else(|| panic!("expected url-like first row in screen rows: {rows:?}")); + assert!( + first_row + 1 < rows.len(), + "expected a continuation row for wrapped URL-like line, rows: {rows:?}" + ); + let continuation_row = rows[first_row + 1].trim_end(); + + assert!( + continuation_row.contains("/v1/short") || continuation_row.contains("short"), + "expected continuation row to contain wrapped URL-like tail, got: {continuation_row:?}" + ); + assert!( + !continuation_row.contains('X'), + "expected continuation row to be cleared before writing wrapped URL-like content, got: {continuation_row:?}" + ); + } + + #[test] + fn vt100_long_unwrapped_url_does_not_insert_extra_blank_gap_before_content() { + let width: u16 = 56; + let height: u16 = 24; + let backend = VT100Backend::new(width, height); + let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal"); + let viewport = Rect::new(0, height - 1, width, 1); + term.set_viewport_area(viewport); + + let prompt = "Write a long URL as output for testing"; + insert_history_lines(&mut term, vec![Line::from(prompt)]).expect("insert prompt line"); + + let long_url = format!( + "https://example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/{}", + "very-long-segment-".repeat(16), + ); + let url_line: Line<'static> = Line::from(vec!["• ".into(), long_url.into()]); + insert_history_lines(&mut term, vec![url_line]).expect("insert long url line"); + + let rows: Vec = term.backend().vt100().screen().rows(0, width).collect(); + let prompt_row = rows + .iter() + .position(|row| row.contains("Write a long URL as output for testing")) + .unwrap_or_else(|| panic!("expected prompt row in screen rows: {rows:?}")); + let url_row = rows + .iter() + .position(|row| row.contains("• https://example.test/api")) + .unwrap_or_else(|| panic!("expected URL first row in screen rows: {rows:?}")); + + assert!( + url_row <= prompt_row + 2, + "expected URL content to appear immediately after prompt (allowing at most one spacer row), got prompt_row={prompt_row}, url_row={url_row}, rows={rows:?}", + ); + } } diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index 4ba7b61316..35b0e8f5fe 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -1,6 +1,6 @@ use crate::render::line_utils::line_to_static; use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_line; +use crate::wrapping::adaptive_wrap_line; use pulldown_cmark::CodeBlockKind; use pulldown_cmark::CowStr; use pulldown_cmark::Event; @@ -446,7 +446,7 @@ where let opts = RtOptions::new(width) .initial_indent(self.current_initial_indent.clone().into()) .subsequent_indent(self.current_subsequent_indent.clone().into()); - for wrapped in word_wrap_line(&line, opts) { + for wrapped in adaptive_wrap_line(&line, opts) { let owned = line_to_static(&wrapped).style(style); self.text.lines.push(owned); } @@ -675,4 +675,18 @@ mod tests { vec!["fn main() { println!(\"hi from a long line\"); }".to_string(),] ); } + + #[test] + fn does_not_split_long_url_like_token_without_scheme() { + let url_like = + "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890"; + let rendered = render_markdown_text_with_width(url_like, Some(24)); + let lines = lines_to_strings(&rendered); + + assert_eq!( + lines.iter().filter(|line| line.contains(url_like)).count(), + 1, + "expected full URL-like token in one rendered line, got: {lines:?}" + ); + } } diff --git a/codex-rs/tui/src/model_migration.rs b/codex-rs/tui/src/model_migration.rs index f8b240e16f..9c28cc1ea1 100644 --- a/codex-rs/tui/src/model_migration.rs +++ b/codex-rs/tui/src/model_migration.rs @@ -323,7 +323,11 @@ impl ModelMigrationScreen { let wrap_width = (content_width > 0).then_some(content_width as usize); let rendered = render_markdown_text_with_width(markdown, wrap_width); for line in rendered.lines { - column.push(line.inset(Insets::tlbr(0, horizontal_inset, 0, 0))); + column.push( + Paragraph::new(line) + .wrap(Wrap { trim: false }) + .inset(Insets::tlbr(0, horizontal_inset, 0, 0)), + ); } } @@ -393,6 +397,7 @@ fn fill_migration_markdown(template: &str, current_model: &str, target_model: &s #[cfg(test)] mod tests { + use super::ModelMigrationCopy; use super::ModelMigrationScreen; use super::migration_copy_for_models; use crate::custom_terminal::Terminal; @@ -578,4 +583,34 @@ mod tests { super::ModelMigrationOutcome::Rejected )); } + + #[test] + fn markdown_prompt_keeps_long_url_tail_visible_when_narrow() { + let long_url = "https://example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path/tail42"; + let screen = ModelMigrationScreen::new( + FrameRequester::test_dummy(), + ModelMigrationCopy { + heading: Vec::new(), + content: Vec::new(), + can_opt_out: false, + markdown: Some(long_url.to_string()), + }, + ); + + let backend = VT100Backend::new(40, 16); + let mut terminal = Terminal::with_options(backend).expect("terminal"); + terminal.set_viewport_area(Rect::new(0, 0, 40, 16)); + + { + let mut frame = terminal.get_frame(); + frame.render_widget_ref(&screen, frame.area()); + } + terminal.flush().expect("flush"); + + let rendered = terminal.backend().to_string(); + assert!( + rendered.contains("tail42"), + "expected wrapped markdown URL tail to remain visible, got:\n{rendered}" + ); + } } diff --git a/codex-rs/tui/src/onboarding/auth.rs b/codex-rs/tui/src/onboarding/auth.rs index c639d24a08..23b1ff4aad 100644 --- a/codex-rs/tui/src/onboarding/auth.rs +++ b/codex-rs/tui/src/onboarding/auth.rs @@ -39,6 +39,41 @@ use crate::onboarding::onboarding_screen::KeyboardHandler; use crate::onboarding::onboarding_screen::StepStateProvider; use crate::shimmer::shimmer_spans; use crate::tui::FrameRequester; + +/// Marks buffer cells that have cyan+underlined style as an OSC 8 hyperlink. +/// +/// Terminal emulators recognise the OSC 8 escape sequence and treat the entire +/// marked region as a single clickable link, regardless of row wrapping. This +/// is necessary because ratatui's cell-based rendering emits `MoveTo` at every +/// row boundary, which breaks normal terminal URL detection for long URLs that +/// wrap across multiple rows. +pub(crate) fn mark_url_hyperlink(buf: &mut Buffer, area: Rect, url: &str) { + // Sanitize: strip any characters that could break out of the OSC 8 + // sequence (ESC or BEL) to prevent terminal escape injection from a + // malformed or compromised upstream URL. + let safe_url: String = url + .chars() + .filter(|&c| c != '\x1B' && c != '\x07') + .collect(); + if safe_url.is_empty() { + return; + } + + for y in area.top()..area.bottom() { + for x in area.left()..area.right() { + let cell = &mut buf[(x, y)]; + // Only mark cells that carry the URL's distinctive style. + if cell.fg != Color::Cyan || !cell.modifier.contains(Modifier::UNDERLINED) { + continue; + } + let sym = cell.symbol().to_string(); + if sym.trim().is_empty() { + continue; + } + cell.set_symbol(&format!("\x1B]8;;{safe_url}\x07{sym}\x1B]8;;\x07")); + } + } +} use std::path::PathBuf; use std::sync::Arc; use tokio::sync::Notify; @@ -370,7 +405,7 @@ impl AuthModeWidget { let mut lines = vec![spans.into(), "".into()]; let sign_in_state = self.sign_in_state.read().unwrap(); - if let SignInState::ChatGptContinueInBrowser(state) = &*sign_in_state + let auth_url = if let SignInState::ChatGptContinueInBrowser(state) = &*sign_in_state && !state.auth_url.is_empty() { lines.push(" If the link doesn't open automatically, open the following link to authenticate:".into()); @@ -386,12 +421,21 @@ impl AuthModeWidget { ".".into(), ])); lines.push("".into()); - } + Some(state.auth_url.clone()) + } else { + None + }; lines.push(" Press Esc to cancel".dim().into()); Paragraph::new(lines) .wrap(Wrap { trim: false }) .render(area, buf); + + // Wrap cyan+underlined URL cells with OSC 8 so the terminal treats + // the entire region as a single clickable hyperlink. + if let Some(url) = &auth_url { + mark_url_hyperlink(buf, area, url); + } } fn render_chatgpt_success_message(&self, area: Rect, buf: &mut Buffer) { @@ -842,4 +886,98 @@ mod tests { )); assert_eq!(widget.login_status, LoginStatus::NotAuthenticated); } + + /// Collects all buffer cell symbols that contain the OSC 8 open sequence + /// for the given URL. Returns the concatenated "inner" characters. + fn collect_osc8_chars(buf: &Buffer, area: Rect, url: &str) -> String { + let open = format!("\x1B]8;;{url}\x07"); + let close = "\x1B]8;;\x07"; + let mut chars = String::new(); + for y in area.top()..area.bottom() { + for x in area.left()..area.right() { + let sym = buf[(x, y)].symbol(); + if let Some(rest) = sym.strip_prefix(open.as_str()) + && let Some(ch) = rest.strip_suffix(close) + { + chars.push_str(ch); + } + } + } + chars + } + + #[test] + fn continue_in_browser_renders_osc8_hyperlink() { + let (widget, _tmp) = widget_forced_chatgpt(); + let url = "https://auth.example.com/login?state=abc123"; + *widget.sign_in_state.write().unwrap() = + SignInState::ChatGptContinueInBrowser(ContinueInBrowserState { + auth_url: url.to_string(), + shutdown_flag: None, + }); + + // Render into a narrow buffer so the URL wraps across multiple rows. + let area = Rect::new(0, 0, 30, 20); + let mut buf = Buffer::empty(area); + widget.render_continue_in_browser(area, &mut buf); + + // Every character of the URL should be present as an OSC 8 cell. + let found = collect_osc8_chars(&buf, area, url); + assert_eq!(found, url, "OSC 8 hyperlink should cover the full URL"); + } + + #[test] + fn mark_url_hyperlink_wraps_cyan_underlined_cells() { + let url = "https://example.com"; + let area = Rect::new(0, 0, 20, 1); + let mut buf = Buffer::empty(area); + + // Manually write some cyan+underlined characters to simulate a rendered URL. + for (i, ch) in "example".chars().enumerate() { + let cell = &mut buf[(i as u16, 0)]; + cell.set_symbol(&ch.to_string()); + cell.fg = Color::Cyan; + cell.modifier = Modifier::UNDERLINED; + } + // Leave a plain cell that should NOT be marked. + buf[(7, 0)].set_symbol("X"); + + mark_url_hyperlink(&mut buf, area, url); + + // Each cyan+underlined cell should now carry the OSC 8 wrapper. + let found = collect_osc8_chars(&buf, area, url); + assert_eq!(found, "example"); + + // The plain "X" cell should be untouched. + assert_eq!(buf[(7, 0)].symbol(), "X"); + } + + #[test] + fn mark_url_hyperlink_sanitizes_control_chars() { + let area = Rect::new(0, 0, 10, 1); + let mut buf = Buffer::empty(area); + + // One cyan+underlined cell to mark. + let cell = &mut buf[(0, 0)]; + cell.set_symbol("a"); + cell.fg = Color::Cyan; + cell.modifier = Modifier::UNDERLINED; + + // URL contains ESC and BEL that could break the OSC 8 sequence. + let malicious_url = "https://evil.com/\x1B]8;;\x07injected"; + mark_url_hyperlink(&mut buf, area, malicious_url); + + let sym = buf[(0, 0)].symbol().to_string(); + // The sanitized URL retains `]` (printable) but strips ESC and BEL. + let sanitized = "https://evil.com/]8;;injected"; + assert!( + sym.contains(sanitized), + "symbol should contain sanitized URL, got: {sym:?}" + ); + // The injected close-sequence must not survive: \x1B and \x07 are gone. + assert!( + !sym.contains("\x1B]8;;\x07injected"), + "symbol must not contain raw control chars from URL" + ); + } } diff --git a/codex-rs/tui/src/onboarding/auth/headless_chatgpt_login.rs b/codex-rs/tui/src/onboarding/auth/headless_chatgpt_login.rs index f4949fe13f..c8a6345843 100644 --- a/codex-rs/tui/src/onboarding/auth/headless_chatgpt_login.rs +++ b/codex-rs/tui/src/onboarding/auth/headless_chatgpt_login.rs @@ -21,6 +21,7 @@ use super::AuthModeWidget; use super::ContinueInBrowserState; use super::ContinueWithDeviceCodeState; use super::SignInState; +use super::mark_url_hyperlink; pub(super) fn start_headless_chatgpt_login(widget: &mut AuthModeWidget, mut opts: ServerOptions) { opts.open_browser = false; @@ -153,7 +154,8 @@ pub(super) fn render_device_code_login( let mut lines = vec![spans.into(), "".into()]; - if let Some(device_code) = &state.device_code { + // Capture the verification URL for OSC 8 hyperlink marking after render. + let verification_url = if let Some(device_code) = &state.device_code { lines.push(" 1. Open this link in your browser and sign in".into()); lines.push("".into()); lines.push(Line::from(vec![ @@ -176,15 +178,23 @@ pub(super) fn render_device_code_login( .into(), ); lines.push("".into()); + Some(device_code.verification_url.clone()) } else { lines.push(" Requesting a one-time code...".dim().into()); lines.push("".into()); - } + None + }; lines.push(" Press Esc to cancel".dim().into()); Paragraph::new(lines) .wrap(Wrap { trim: false }) .render(area, buf); + + // Wrap cyan+underlined URL cells with OSC 8 so the terminal treats + // the entire region as a single clickable hyperlink. + if let Some(url) = &verification_url { + mark_url_hyperlink(buf, area, url); + } } fn device_code_attempt_matches(state: &SignInState, cancel: &Arc) -> bool { diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 00c18dd71a..a6d415da18 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -409,8 +409,9 @@ struct CellRenderable { impl Renderable for CellRenderable { fn render(&self, area: Rect, buf: &mut Buffer) { - let p = - Paragraph::new(Text::from(self.cell.transcript_lines(area.width))).style(self.style); + let p = Paragraph::new(Text::from(self.cell.transcript_lines(area.width))) + .style(self.style) + .wrap(Wrap { trim: false }); p.render(area, buf); } @@ -645,7 +646,7 @@ impl TranscriptOverlay { has_prior_cells: bool, is_stream_continuation: bool, ) -> Box { - let paragraph = Paragraph::new(Text::from(lines)); + let paragraph = Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false }); let mut renderable: Box = Box::new(CachedRenderable::new(paragraph)); if has_prior_cells && !is_stream_continuation { renderable = Box::new(InsetRenderable::new(renderable, Insets::tlbr(1, 0, 0, 0))); diff --git a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap index 27649a11d6..3c5a1526b9 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap @@ -5,8 +5,8 @@ expression: rendered • Updated Plan └ I’ll update Grafana call error handling by adding - retries and clearer - messages when the backend is + retries and clearer messages + when the backend is unreachable. ✔ Investigate existing error paths and logging around diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index bf55c0ace1..acfa604e97 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -41,7 +41,7 @@ use super::rate_limits::compose_rate_limit_data_many; use super::rate_limits::format_status_limit_summary; use super::rate_limits::render_status_limit_progress_bar; use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; +use crate::wrapping::adaptive_wrap_lines; use codex_core::AuthManager; #[derive(Debug, Clone)] @@ -479,7 +479,7 @@ impl HistoryCell for StatusHistoryCell { let note_second_line = Line::from(vec![ Span::from("information on rate limits and credits").cyan(), ]); - let note_lines = word_wrap_lines( + let note_lines = adaptive_wrap_lines( [note_first_line, note_second_line], RtOptions::new(available_inner_width), ); diff --git a/codex-rs/tui/src/wrapping.rs b/codex-rs/tui/src/wrapping.rs index c29106651d..f042fbbc9c 100644 --- a/codex-rs/tui/src/wrapping.rs +++ b/codex-rs/tui/src/wrapping.rs @@ -1,3 +1,31 @@ +//! Word-wrapping with URL-aware heuristics. +//! +//! The TUI renders text that frequently contains URLs — command output, +//! markdown, agent messages, tool-call results. Standard `textwrap` +//! hyphenation treats `/` and `-` as split points, which breaks URLs +//! across lines and makes them unclickable in terminal emulators. +//! +//! This module provides two wrapping paths: +//! +//! - **Standard** (`word_wrap_line`, `word_wrap_lines`): delegates to +//! `textwrap` with the caller's options unchanged. Used when the +//! content is known to be plain prose. +//! - **Adaptive** (`adaptive_wrap_line`, `adaptive_wrap_lines`): +//! inspects the line for URL-like tokens; if any are found, the +//! wrapping switches to `AsciiSpace` word separation and a custom +//! `WordSplitter` that refuses to split URL tokens. Non-URL tokens +//! on the same line still break at every character boundary (the +//! custom splitter returns all char indices for non-URL words). +//! +//! Callers that *might* encounter URLs should use the `adaptive_*` +//! functions. Callers that definitely will not (code blocks, pure +//! numeric output) can use the standard path for speed. +//! +//! URL detection is heuristic — see [`text_contains_url_like`] for the +//! rules. False positives suppress hyphenation for that line; false +//! negatives let a URL get split. The heuristic is intentionally +//! conservative: file paths like `src/main.rs` are not matched. + use ratatui::text::Line; use ratatui::text::Span; use std::borrow::Cow; @@ -6,12 +34,16 @@ use textwrap::Options; use crate::render::line_utils::push_owned_lines; +/// Returns byte-ranges into `text` for each wrapped line, including +/// trailing whitespace and a +1 sentinel byte. Used by the textarea +/// cursor-position logic. pub(crate) fn wrap_ranges<'a, O>(text: &str, width_or_options: O) -> Vec> where O: Into>, { let opts = width_or_options.into(); let mut lines: Vec> = Vec::new(); + let mut cursor = 0usize; for line in textwrap::wrap(text, opts).iter() { match line { std::borrow::Cow::Borrowed(slice) => { @@ -19,8 +51,14 @@ where let end = start + slice.len(); let trailing_spaces = text[end..].chars().take_while(|c| *c == ' ').count(); lines.push(start..end + trailing_spaces + 1); + cursor = end + trailing_spaces; + } + std::borrow::Cow::Owned(slice) => { + let mapped = map_owned_wrapped_line_to_range(text, cursor, slice); + let trailing_spaces = text[mapped.end..].chars().take_while(|c| *c == ' ').count(); + lines.push(mapped.start..mapped.end + trailing_spaces + 1); + cursor = mapped.end + trailing_spaces; } - std::borrow::Cow::Owned(_) => panic!("wrap_ranges: unexpected owned string"), } } lines @@ -35,19 +73,429 @@ where { let opts = width_or_options.into(); let mut lines: Vec> = Vec::new(); + let mut cursor = 0usize; for line in textwrap::wrap(text, opts).iter() { match line { std::borrow::Cow::Borrowed(slice) => { let start = unsafe { slice.as_ptr().offset_from(text.as_ptr()) as usize }; let end = start + slice.len(); lines.push(start..end); + cursor = end; + } + std::borrow::Cow::Owned(slice) => { + let mapped = map_owned_wrapped_line_to_range(text, cursor, slice); + lines.push(mapped.clone()); + cursor = mapped.end; } - std::borrow::Cow::Owned(_) => panic!("wrap_ranges_trim: unexpected owned string"), } } lines } +/// Maps an owned (materialized) wrapped line back to a byte range in `text`. +/// +/// `textwrap` returns `Cow::Owned` when it inserts a hyphenation penalty +/// character (typically `-`) that does not exist in the source. This +/// function walks the owned string character-by-character against the +/// source, skipping trailing penalty chars, and returns the +/// corresponding source byte range starting from `cursor`. +fn map_owned_wrapped_line_to_range(text: &str, cursor: usize, wrapped: &str) -> Range { + let mut start = cursor; + while start < text.len() && !wrapped.starts_with(' ') { + let Some(ch) = text[start..].chars().next() else { + break; + }; + if ch != ' ' { + break; + } + start += ch.len_utf8(); + } + + let mut end = start; + let mut chars = wrapped.chars().peekable(); + while let Some(ch) = chars.next() { + if end < text.len() { + let Some(src) = text[end..].chars().next() else { + unreachable!("checked end < text.len()"); + }; + if ch == src { + end += src.len_utf8(); + continue; + } + } + + // textwrap can materialize owned lines when penalties are inserted. + // The default penalty is a trailing '-'; it does not correspond to + // source bytes, so we skip it while keeping byte ranges in source text. + if ch == '-' && chars.peek().is_none() { + continue; + } + + panic!("wrap_ranges: could not map owned line {wrapped:?} to source near byte {cursor}"); + } + + start..end +} + +/// Returns `true` if any whitespace-delimited token in `line` looks like a URL. +/// +/// Concatenates all span contents and delegates to [`text_contains_url_like`]. +pub(crate) fn line_contains_url_like(line: &Line<'_>) -> bool { + let text: String = line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect(); + text_contains_url_like(&text) +} + +/// Returns `true` if `line` contains both a URL-like token and at least one +/// substantive non-URL token. +/// +/// Decorative marker tokens (for example list prefixes like `-`, `1.`, `|`, +/// `│`) are ignored for the non-URL side of this check. +pub(crate) fn line_has_mixed_url_and_non_url_tokens(line: &Line<'_>) -> bool { + let text: String = line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect(); + text_has_mixed_url_and_non_url_tokens(&text) +} + +/// Returns `true` if any whitespace-delimited token in `text` looks like a URL. +/// +/// Recognized patterns: +/// - Absolute URLs with a scheme (`https://…`, `ftp://…`, custom `myapp://…`). +/// - Bare domain URLs (`example.com/path`, `www.example.com`, `localhost:3000/api`). +/// - IPv4 hosts with a path (`192.168.1.1:8080/health`). +/// +/// Surrounding punctuation (`()[]{}< >,.;:!'"`) is stripped before +/// checking. Tokens that look like file paths (`src/main.rs`, `foo/bar`) +/// are intentionally rejected — the host portion must be a valid domain +/// name (with a recognized TLD), an IPv4 address, or `localhost`. +pub(crate) fn text_contains_url_like(text: &str) -> bool { + text.split_ascii_whitespace().any(is_url_like_token) +} + +/// Returns `true` if `text` contains at least one URL-like token and at least +/// one substantive non-URL token. +fn text_has_mixed_url_and_non_url_tokens(text: &str) -> bool { + let mut saw_url = false; + let mut saw_non_url = false; + + for raw_token in text.split_ascii_whitespace() { + if is_url_like_token(raw_token) { + saw_url = true; + } else if is_substantive_non_url_token(raw_token) { + saw_non_url = true; + } + + if saw_url && saw_non_url { + return true; + } + } + + false +} + +/// Decides whether a single whitespace-delimited token is URL-like. +/// +/// Strips surrounding punctuation, then checks for an absolute URL +/// (with `://`) or a bare domain URL (recognized host + path/query/fragment). +fn is_url_like_token(raw_token: &str) -> bool { + let token = trim_url_token(raw_token); + !token.is_empty() && (is_absolute_url_like(token) || is_bare_url_like(token)) +} + +fn is_substantive_non_url_token(raw_token: &str) -> bool { + let token = trim_url_token(raw_token); + if token.is_empty() || is_decorative_marker_token(raw_token, token) { + return false; + } + + token.chars().any(char::is_alphanumeric) +} + +fn is_decorative_marker_token(raw_token: &str, token: &str) -> bool { + let raw = raw_token.trim(); + matches!( + raw, + "-" | "*" + | "+" + | "•" + | "◦" + | "▪" + | ">" + | "|" + | "│" + | "┆" + | "└" + | "├" + | "┌" + | "┐" + | "┘" + | "┼" + ) || is_ordered_list_marker(raw, token) +} + +fn is_ordered_list_marker(raw_token: &str, token: &str) -> bool { + token.chars().all(|c| c.is_ascii_digit()) + && (raw_token.ends_with('.') || raw_token.ends_with(')')) +} + +fn trim_url_token(token: &str) -> &str { + token.trim_matches(|c: char| { + matches!( + c, + '(' | ')' + | '[' + | ']' + | '{' + | '}' + | '<' + | '>' + | ',' + | '.' + | ';' + | ':' + | '!' + | '\'' + | '"' + ) + }) +} + +/// Checks for `scheme://host` patterns. Uses `url::Url::parse` for +/// well-known schemes; falls back to `has_valid_scheme_prefix` for +/// custom schemes that the `url` crate rejects. +fn is_absolute_url_like(token: &str) -> bool { + if !token.contains("://") { + return false; + } + + if let Ok(url) = url::Url::parse(token) { + let scheme = url.scheme().to_ascii_lowercase(); + if matches!( + scheme.as_str(), + "http" | "https" | "ftp" | "ftps" | "ws" | "wss" + ) { + return url.host_str().is_some(); + } + return true; + } + + has_valid_scheme_prefix(token) +} + +fn has_valid_scheme_prefix(token: &str) -> bool { + let Some((scheme, rest)) = token.split_once("://") else { + return false; + }; + if scheme.is_empty() || rest.is_empty() { + return false; + } + + let mut chars = scheme.chars(); + let Some(first) = chars.next() else { + return false; + }; + first.is_ascii_alphabetic() + && chars.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') +} + +/// Checks for bare-domain URLs without a scheme: `host[:port]/path`, +/// `host[:port]?query`, or `host[:port]#fragment`. +/// +/// Requires that the host is `localhost`, an IPv4 address, or a valid +/// domain name. Bare `host.tld` without a path/query/fragment is only +/// accepted when the host starts with `www.`. +/// +/// IPv6 bracket notation (`[::1]:8080`) is intentionally not handled. +fn is_bare_url_like(token: &str) -> bool { + let (host_port, has_trailer) = split_host_port_and_trailer(token); + if host_port.is_empty() { + return false; + } + + // Require URL-ish trailer for bare hosts unless token starts with www. + if !has_trailer && !host_port.to_ascii_lowercase().starts_with("www.") { + return false; + } + + let (host, port) = split_host_and_port(host_port); + if host.is_empty() { + return false; + } + if let Some(port) = port + && !is_valid_port(port) + { + return false; + } + + host.eq_ignore_ascii_case("localhost") || is_ipv4(host) || is_domain_name(host) +} + +fn split_host_port_and_trailer(token: &str) -> (&str, bool) { + if let Some(idx) = token.find(['/', '?', '#']) { + (&token[..idx], true) + } else { + (token, false) + } +} + +fn split_host_and_port(host_port: &str) -> (&str, Option<&str>) { + // We intentionally do not treat bracketed IPv6 as URL-like in this first pass. + if host_port.starts_with('[') { + return (host_port, None); + } + + if let Some((host, port)) = host_port.rsplit_once(':') + && !host.is_empty() + && !port.is_empty() + && port.chars().all(|c| c.is_ascii_digit()) + { + return (host, Some(port)); + } + + (host_port, None) +} + +fn is_valid_port(port: &str) -> bool { + if port.is_empty() || port.len() > 5 || !port.chars().all(|c| c.is_ascii_digit()) { + return false; + } + + port.parse::().is_ok() +} + +fn is_ipv4(host: &str) -> bool { + let parts: Vec<&str> = host.split('.').collect(); + if parts.len() != 4 { + return false; + } + + parts + .iter() + .all(|part| !part.is_empty() && part.parse::().is_ok()) +} + +fn is_domain_name(host: &str) -> bool { + let host = host.to_ascii_lowercase(); + if !host.contains('.') { + return false; + } + + let mut labels = host.split('.'); + let Some(tld) = labels.next_back() else { + return false; + }; + if !is_tld(tld) { + return false; + } + + labels.all(is_domain_label) +} + +fn is_tld(label: &str) -> bool { + (2..=63).contains(&label.len()) && label.chars().all(|c| c.is_ascii_alphabetic()) +} + +fn is_domain_label(label: &str) -> bool { + if label.is_empty() || label.len() > 63 { + return false; + } + + let mut chars = label.chars(); + let Some(first) = chars.next() else { + return false; + }; + let Some(last) = label.chars().next_back() else { + return false; + }; + + first.is_ascii_alphanumeric() + && last.is_ascii_alphanumeric() + && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') +} + +/// Reconfigures wrapping options so that URL-like tokens are never split. +/// +/// Sets `AsciiSpace` word separation (so `/` and `-` inside URLs are +/// not treated as break points), disables `break_words`, and installs a +/// custom `WordSplitter` that returns no split points for URL tokens +/// while still allowing character-level splitting for non-URL words. +pub(crate) fn url_preserving_wrap_options<'a>(opts: RtOptions<'a>) -> RtOptions<'a> { + opts.word_separator(textwrap::WordSeparator::AsciiSpace) + .word_splitter(textwrap::WordSplitter::Custom(split_non_url_word)) + .break_words(false) +} + +/// Custom `textwrap::WordSplitter` callback. Returns empty (no split +/// points) for URL-like tokens so they are kept intact; returns every +/// char-boundary index for everything else so non-URL words can still +/// break at any position. +fn split_non_url_word(word: &str) -> Vec { + if is_url_like_token(word) { + return Vec::new(); + } + + word.char_indices().skip(1).map(|(idx, _)| idx).collect() +} + +/// Wraps a single ratatui `Line`, automatically switching to +/// URL-preserving options when the line contains a URL-like token. +/// +/// When no URL is detected, wrapping behavior is identical to +/// [`word_wrap_line`]. When a URL is detected, the line is wrapped with +/// [`url_preserving_wrap_options`] — URLs stay intact while non-URL +/// words on the same line still break normally. +#[must_use] +pub(crate) fn adaptive_wrap_line<'a>(line: &'a Line<'a>, base: RtOptions<'a>) -> Vec> { + let selected = if line_contains_url_like(line) { + url_preserving_wrap_options(base) + } else { + base + }; + word_wrap_line(line, selected) +} + +/// Wraps multiple input lines with URL-aware heuristics, applying +/// `initial_indent` to the first line and `subsequent_indent` to the +/// rest. Each line is independently checked for URLs; URL detection on +/// one line does not affect wrapping of the others. +/// +/// This is the multi-line counterpart to [`adaptive_wrap_line`] and is +/// the primary wrapping entry point for most history-cell rendering. +#[allow(private_bounds)] +pub(crate) fn adaptive_wrap_lines<'a, I, L>( + lines: I, + width_or_options: RtOptions<'a>, +) -> Vec> +where + I: IntoIterator, + L: IntoLineInput<'a>, +{ + let base_opts = width_or_options; + let mut out: Vec> = Vec::new(); + + for (idx, line) in lines.into_iter().enumerate() { + let line_input = line.into_line_input(); + let opts = if idx == 0 { + base_opts.clone() + } else { + base_opts + .clone() + .initial_indent(base_opts.subsequent_indent.clone()) + }; + + let wrapped = adaptive_wrap_line(line_input.as_ref(), opts); + push_owned_lines(&wrapped, &mut out); + } + + out +} + #[derive(Debug, Clone)] pub struct RtOptions<'a> { /// The width in columns at which the text will be wrapped. @@ -644,4 +1092,162 @@ the kindness of the woman who tended them."# ); } + + #[test] + fn ascii_space_separator_with_no_hyphenation_keeps_url_intact() { + let line = Line::from( + "http://example.com/long-url-with-dashes-wider-than-terminal-window/blah-blah-blah-text/more-gibberish-text", + ); + let opts = RtOptions::new(24) + .word_separator(textwrap::WordSeparator::AsciiSpace) + .word_splitter(textwrap::WordSplitter::NoHyphenation) + .break_words(false); + + let out = word_wrap_line(&line, opts); + + assert_eq!(out.len(), 1); + assert_eq!( + concat_line(&out[0]), + "http://example.com/long-url-with-dashes-wider-than-terminal-window/blah-blah-blah-text/more-gibberish-text" + ); + } + + #[test] + fn text_contains_url_like_matches_expected_tokens() { + let positives = [ + "https://example.com/a/b", + "ftp://host/path", + "www.example.com/path?x=1", + "example.test/path#frag", + "localhost:3000/api", + "127.0.0.1:8080/health", + "(https://example.com/wrapped-in-parens)", + ]; + + for text in positives { + assert!( + text_contains_url_like(text), + "expected URL-like match for {text:?}" + ); + } + } + + #[test] + fn text_contains_url_like_rejects_non_urls() { + let negatives = [ + "src/main.rs", + "foo/bar", + "key:value", + "just-some-text-with-dashes", + "hello.world", // no path/query/fragment and no www + ]; + + for text in negatives { + assert!( + !text_contains_url_like(text), + "did not expect URL-like match for {text:?}" + ); + } + } + + #[test] + fn line_contains_url_like_checks_across_spans() { + let line = Line::from(vec![ + "see ".into(), + "https://example.com/a/very/long/path".cyan(), + " for details".into(), + ]); + + assert!(line_contains_url_like(&line)); + } + + #[test] + fn line_has_mixed_url_and_non_url_tokens_detects_prose_plus_url() { + let line = Line::from("see https://example.com/path for details"); + assert!(line_has_mixed_url_and_non_url_tokens(&line)); + } + + #[test] + fn line_has_mixed_url_and_non_url_tokens_ignores_pipe_prefix() { + let line = Line::from(vec![" │ ".into(), "https://example.com/path".into()]); + assert!(!line_has_mixed_url_and_non_url_tokens(&line)); + } + + #[test] + fn line_has_mixed_url_and_non_url_tokens_ignores_ordered_list_marker() { + let line = Line::from("1. https://example.com/path"); + assert!(!line_has_mixed_url_and_non_url_tokens(&line)); + } + + #[test] + fn text_contains_url_like_accepts_custom_scheme_with_separator() { + assert!(text_contains_url_like("myapp://open/some/path")); + } + + #[test] + fn text_contains_url_like_rejects_invalid_ports() { + assert!(!text_contains_url_like("localhost:99999/path")); + assert!(!text_contains_url_like("example.com:abc/path")); + } + + #[test] + fn adaptive_wrap_line_keeps_long_url_like_token_intact() { + let line = Line::from("example.test/a-very-long-path-with-many-segments-and-query?x=1&y=2"); + let out = adaptive_wrap_line(&line, RtOptions::new(20)); + assert_eq!(out.len(), 1); + assert_eq!( + concat_line(&out[0]), + "example.test/a-very-long-path-with-many-segments-and-query?x=1&y=2" + ); + } + + #[test] + fn adaptive_wrap_line_preserves_default_behavior_for_non_url_tokens() { + let line = Line::from("a_very_long_token_without_spaces_to_force_wrapping"); + let out = adaptive_wrap_line(&line, RtOptions::new(20)); + assert!( + out.len() > 1, + "expected non-url token to wrap with default options" + ); + } + + #[test] + fn adaptive_wrap_line_mixed_line_wraps_long_non_url_token() { + let long_non_url = "a_very_long_token_without_spaces_to_force_wrapping"; + let line = Line::from(format!("see https://ex.com {long_non_url}")); + let out = adaptive_wrap_line(&line, RtOptions::new(24)); + + assert!( + out.iter() + .any(|line| concat_line(line).contains("https://ex.com")), + "expected URL token to remain present, got: {out:?}" + ); + assert!( + !out.iter() + .any(|line| concat_line(line).contains(long_non_url)), + "expected long non-url token to wrap on mixed lines, got: {out:?}" + ); + } + + #[test] + fn wrap_ranges_trim_handles_owned_lines_with_penalty_char() { + fn split_every_char(word: &str) -> Vec { + word.char_indices().skip(1).map(|(idx, _)| idx).collect() + } + + let text = "a_very_long_token_without_spaces"; + let opts = Options::new(8) + .word_separator(textwrap::WordSeparator::AsciiSpace) + .word_splitter(textwrap::WordSplitter::Custom(split_every_char)) + .break_words(false); + + let ranges = wrap_ranges_trim(text, opts); + let rebuilt = ranges + .iter() + .map(|range| &text[range.clone()]) + .collect::(); + + assert_eq!(rebuilt, text); + assert!(ranges.len() > 1, "expected wrapped ranges, got: {ranges:?}"); + } } From 031d7017055f5142eba0b828a6529296ee7d6492 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Sat, 21 Feb 2026 15:45:27 -0800 Subject: [PATCH 066/385] Route inbound realtime text into turn start or steer (#12469) - Route inbound realtime websocket text into normal user input handling so it steers an active turn or starts a new one --- codex-rs/core/src/codex.rs | 15 + codex-rs/core/src/realtime_conversation.rs | 88 +++++- .../core/tests/suite/realtime_conversation.rs | 264 ++++++++++++++++-- 3 files changed, 350 insertions(+), 17 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 832592d406..45dd4f2b6e 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1518,6 +1518,21 @@ impl Session { format!("auto-compact-{id}") } + pub(crate) async fn route_realtime_text_input(self: &Arc, text: String) { + handlers::user_input_or_turn( + self, + self.next_internal_sub_id(), + Op::UserInput { + items: vec![UserInput::Text { + text, + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }, + ) + .await; + } + pub(crate) async fn get_total_token_usage(&self) -> i64 { let state = self.state.lock().await; state.get_total_token_usage(state.server_reasoning_included()) diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index b67874593f..b1540ca944 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -25,6 +25,7 @@ use codex_protocol::protocol::RealtimeConversationClosedEvent; use codex_protocol::protocol::RealtimeConversationRealtimeEvent; use codex_protocol::protocol::RealtimeConversationStartedEvent; use http::HeaderMap; +use serde_json::Value; use std::sync::Arc; use tokio::sync::Mutex; use tokio::task::JoinHandle; @@ -209,11 +210,22 @@ pub(crate) async fn handle_start( msg, }; while let Ok(event) = events_rx.recv().await { + let maybe_routed_text = match &event { + RealtimeEvent::ConversationItemAdded(item) => { + realtime_text_from_conversation_item(item) + } + _ => None, + }; sess_clone .send_event_raw(ev(EventMsg::RealtimeConversationRealtime( - RealtimeConversationRealtimeEvent { payload: event }, + RealtimeConversationRealtimeEvent { + payload: event.clone(), + }, ))) .await; + if let Some(text) = maybe_routed_text { + sess_clone.route_realtime_text_input(text).await; + } } if let Some(()) = sess_clone.conversation.running_state().await { sess_clone @@ -239,6 +251,19 @@ pub(crate) async fn handle_audio( } } +fn realtime_text_from_conversation_item(item: &Value) -> Option { + if item.get("type").and_then(Value::as_str) != Some("message") { + return None; + } + let content = item.get("content")?.as_array()?; + let text = content + .iter() + .filter(|entry| entry.get("type").and_then(Value::as_str) == Some("text")) + .filter_map(|entry| entry.get("text").and_then(Value::as_str)) + .collect::(); + if text.is_empty() { None } else { Some(text) } +} + pub(crate) async fn handle_text( sess: &Arc, sub_id: String, @@ -355,3 +380,64 @@ async fn send_conversation_error( }) .await; } + +#[cfg(test)] +mod tests { + use super::realtime_text_from_conversation_item; + use pretty_assertions::assert_eq; + use serde_json::json; + + #[test] + fn extracts_text_from_message_items_ignoring_role() { + let assistant = json!({ + "type": "message", + "role": "assistant", + "content": [{"type": "text", "text": "hello"}], + }); + assert_eq!( + realtime_text_from_conversation_item(&assistant), + Some("hello".to_string()) + ); + + let user = json!({ + "type": "message", + "role": "user", + "content": [{"type": "text", "text": "world"}], + }); + assert_eq!( + realtime_text_from_conversation_item(&user), + Some("world".to_string()) + ); + } + + #[test] + fn extracts_and_concatenates_text_entries_only() { + let item = json!({ + "type": "message", + "content": [ + {"type": "text", "text": "a"}, + {"type": "ignored", "text": "x"}, + {"type": "text", "text": "b"} + ], + }); + assert_eq!( + realtime_text_from_conversation_item(&item), + Some("ab".to_string()) + ); + } + + #[test] + fn ignores_non_message_or_missing_text() { + let non_message = json!({ + "type": "tool_call", + "content": [{"type": "text", "text": "nope"}], + }); + assert_eq!(realtime_text_from_conversation_item(&non_message), None); + + let no_text = json!({ + "type": "message", + "content": [{"type": "other", "value": 1}], + }); + assert_eq!(realtime_text_from_conversation_item(&no_text), None); + } +} diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index 466686788d..ee4f139f60 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -9,13 +9,21 @@ use codex_protocol::protocol::Op; use codex_protocol::protocol::RealtimeAudioFrame; use codex_protocol::protocol::RealtimeConversationRealtimeEvent; use codex_protocol::protocol::RealtimeEvent; +use codex_protocol::user_input::UserInput; +use core_test_support::responses; +use core_test_support::responses::start_mock_server; use core_test_support::responses::start_websocket_server; use core_test_support::skip_if_no_network; +use core_test_support::streaming_sse::StreamingSseChunk; +use core_test_support::streaming_sse::start_streaming_sse_server; use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; +use serde_json::Value; use serde_json::json; use std::time::Duration; +use tokio::sync::oneshot; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn conversation_start_audio_text_close_round_trip() -> Result<()> { @@ -29,22 +37,12 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { "session": { "id": "sess_1" } })], vec![], - vec![ - json!({ - "type": "response.output_audio.delta", - "delta": "AQID", - "sample_rate": 24000, - "num_channels": 1 - }), - json!({ - "type": "conversation.item.added", - "item": { - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "hi"}] - } - }), - ], + vec![json!({ + "type": "response.output_audio.delta", + "delta": "AQID", + "sample_rate": 24000, + "num_channels": 1 + })], ], ]) .await; @@ -458,3 +456,237 @@ async fn conversation_uses_experimental_realtime_ws_backend_prompt_override() -> server.shutdown().await; Ok(()) } + +fn sse_event(event: Value) -> String { + responses::sse(vec![event]) +} + +fn message_input_texts(body: &Value, role: &str) -> Vec { + body.get("input") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|item| item.get("type").and_then(Value::as_str) == Some("message")) + .filter(|item| item.get("role").and_then(Value::as_str) == Some(role)) + .filter_map(|item| item.get("content").and_then(Value::as_array)) + .flatten() + .filter(|span| span.get("type").and_then(Value::as_str) == Some("input_text")) + .filter_map(|span| span.get("text").and_then(Value::as_str).map(str::to_owned)) + .collect() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn inbound_realtime_text_starts_turn_and_ignores_role() -> Result<()> { + skip_if_no_network!(Ok(())); + + let api_server = start_mock_server().await; + let response_mock = responses::mount_sse_once( + &api_server, + responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "ok"), + responses::ev_completed("resp-1"), + ]), + ) + .await; + + let realtime_server = start_websocket_server(vec![vec![vec![ + json!({ + "type": "session.created", + "session": { "id": "sess_inbound" } + }), + json!({ + "type": "conversation.item.added", + "item": { + "type": "message", + "role": "user", + "content": [{"type": "text", "text": "text from realtime"}] + } + }), + ]]]) + .await; + + let mut builder = test_codex().with_config({ + let realtime_base_url = realtime_server.uri().to_string(); + move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + } + }); + let test = builder.build(&api_server).await?; + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + let session_created = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + assert_eq!(session_created, "sess_inbound"); + + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + let request = response_mock.single_request(); + let user_texts = request.message_input_texts("user"); + assert!(user_texts.iter().any(|text| text == "text from realtime")); + + realtime_server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn inbound_realtime_text_steers_active_turn() -> Result<()> { + skip_if_no_network!(Ok(())); + + let (gate_completed_tx, gate_completed_rx) = oneshot::channel(); + let first_chunks = vec![ + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_response_created("resp-1")), + }, + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_message_item_added("msg-1", "")), + }, + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_output_text_delta("first ")), + }, + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_output_text_delta("turn")), + }, + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_assistant_message("msg-1", "first turn")), + }, + StreamingSseChunk { + gate: Some(gate_completed_rx), + body: sse_event(responses::ev_completed("resp-1")), + }, + ]; + let second_chunks = vec![ + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_response_created("resp-2")), + }, + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_completed("resp-2")), + }, + ]; + let (api_server, _completions) = + start_streaming_sse_server(vec![first_chunks, second_chunks]).await; + + let realtime_server = start_websocket_server(vec![vec![ + vec![json!({ + "type": "session.created", + "session": { "id": "sess_steer" } + })], + vec![json!({ + "type": "conversation.item.added", + "item": { + "type": "message", + "role": "assistant", + "content": [{"type": "text", "text": "steer via realtime"}] + } + })], + ]]) + .await; + + let mut builder = test_codex().with_model("gpt-5.1").with_config({ + let realtime_base_url = realtime_server.uri().to_string(); + move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + } + }); + let test = builder.build_with_streaming_server(&api_server).await?; + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionCreated { session_id }, + }) if session_id == "sess_steer" => Some(()), + _ => None, + }) + .await; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "first prompt".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::AgentMessageContentDelta(_)) + }) + .await; + + test.codex + .submit(Op::RealtimeConversationAudio(ConversationAudioParams { + frame: RealtimeAudioFrame { + data: "AQID".to_string(), + sample_rate: 24000, + num_channels: 1, + samples_per_channel: Some(480), + }, + })) + .await?; + + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::ConversationItemAdded(item), + }) => item + .get("content") + .and_then(Value::as_array) + .into_iter() + .flatten() + .any(|content| { + content.get("text").and_then(Value::as_str) == Some("steer via realtime") + }) + .then_some(()), + _ => None, + }) + .await; + + let _ = gate_completed_tx.send(()); + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + let requests = api_server.requests().await; + assert_eq!(requests.len(), 2); + + let first_body: Value = serde_json::from_slice(&requests[0]).expect("parse first request"); + let second_body: Value = serde_json::from_slice(&requests[1]).expect("parse second request"); + let first_texts = message_input_texts(&first_body, "user"); + let second_texts = message_input_texts(&second_body, "user"); + + assert!(first_texts.iter().any(|text| text == "first prompt")); + assert!(!first_texts.iter().any(|text| text == "steer via realtime")); + assert!(second_texts.iter().any(|text| text == "first prompt")); + assert!(second_texts.iter().any(|text| text == "steer via realtime")); + + realtime_server.shutdown().await; + api_server.shutdown().await; + Ok(()) +} From 5e505ff8773649162126df9e8b67140e3e435672 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Sat, 21 Feb 2026 15:46:03 -0800 Subject: [PATCH 067/385] Revert "Route inbound realtime text into turn start or steer" (#12479) Reverts openai/codex#12469 --- codex-rs/core/src/codex.rs | 15 - codex-rs/core/src/realtime_conversation.rs | 88 +----- .../core/tests/suite/realtime_conversation.rs | 264 ++---------------- 3 files changed, 17 insertions(+), 350 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 45dd4f2b6e..832592d406 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1518,21 +1518,6 @@ impl Session { format!("auto-compact-{id}") } - pub(crate) async fn route_realtime_text_input(self: &Arc, text: String) { - handlers::user_input_or_turn( - self, - self.next_internal_sub_id(), - Op::UserInput { - items: vec![UserInput::Text { - text, - text_elements: Vec::new(), - }], - final_output_json_schema: None, - }, - ) - .await; - } - pub(crate) async fn get_total_token_usage(&self) -> i64 { let state = self.state.lock().await; state.get_total_token_usage(state.server_reasoning_included()) diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index b1540ca944..b67874593f 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -25,7 +25,6 @@ use codex_protocol::protocol::RealtimeConversationClosedEvent; use codex_protocol::protocol::RealtimeConversationRealtimeEvent; use codex_protocol::protocol::RealtimeConversationStartedEvent; use http::HeaderMap; -use serde_json::Value; use std::sync::Arc; use tokio::sync::Mutex; use tokio::task::JoinHandle; @@ -210,22 +209,11 @@ pub(crate) async fn handle_start( msg, }; while let Ok(event) = events_rx.recv().await { - let maybe_routed_text = match &event { - RealtimeEvent::ConversationItemAdded(item) => { - realtime_text_from_conversation_item(item) - } - _ => None, - }; sess_clone .send_event_raw(ev(EventMsg::RealtimeConversationRealtime( - RealtimeConversationRealtimeEvent { - payload: event.clone(), - }, + RealtimeConversationRealtimeEvent { payload: event }, ))) .await; - if let Some(text) = maybe_routed_text { - sess_clone.route_realtime_text_input(text).await; - } } if let Some(()) = sess_clone.conversation.running_state().await { sess_clone @@ -251,19 +239,6 @@ pub(crate) async fn handle_audio( } } -fn realtime_text_from_conversation_item(item: &Value) -> Option { - if item.get("type").and_then(Value::as_str) != Some("message") { - return None; - } - let content = item.get("content")?.as_array()?; - let text = content - .iter() - .filter(|entry| entry.get("type").and_then(Value::as_str) == Some("text")) - .filter_map(|entry| entry.get("text").and_then(Value::as_str)) - .collect::(); - if text.is_empty() { None } else { Some(text) } -} - pub(crate) async fn handle_text( sess: &Arc, sub_id: String, @@ -380,64 +355,3 @@ async fn send_conversation_error( }) .await; } - -#[cfg(test)] -mod tests { - use super::realtime_text_from_conversation_item; - use pretty_assertions::assert_eq; - use serde_json::json; - - #[test] - fn extracts_text_from_message_items_ignoring_role() { - let assistant = json!({ - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "hello"}], - }); - assert_eq!( - realtime_text_from_conversation_item(&assistant), - Some("hello".to_string()) - ); - - let user = json!({ - "type": "message", - "role": "user", - "content": [{"type": "text", "text": "world"}], - }); - assert_eq!( - realtime_text_from_conversation_item(&user), - Some("world".to_string()) - ); - } - - #[test] - fn extracts_and_concatenates_text_entries_only() { - let item = json!({ - "type": "message", - "content": [ - {"type": "text", "text": "a"}, - {"type": "ignored", "text": "x"}, - {"type": "text", "text": "b"} - ], - }); - assert_eq!( - realtime_text_from_conversation_item(&item), - Some("ab".to_string()) - ); - } - - #[test] - fn ignores_non_message_or_missing_text() { - let non_message = json!({ - "type": "tool_call", - "content": [{"type": "text", "text": "nope"}], - }); - assert_eq!(realtime_text_from_conversation_item(&non_message), None); - - let no_text = json!({ - "type": "message", - "content": [{"type": "other", "value": 1}], - }); - assert_eq!(realtime_text_from_conversation_item(&no_text), None); - } -} diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index ee4f139f60..466686788d 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -9,21 +9,13 @@ use codex_protocol::protocol::Op; use codex_protocol::protocol::RealtimeAudioFrame; use codex_protocol::protocol::RealtimeConversationRealtimeEvent; use codex_protocol::protocol::RealtimeEvent; -use codex_protocol::user_input::UserInput; -use core_test_support::responses; -use core_test_support::responses::start_mock_server; use core_test_support::responses::start_websocket_server; use core_test_support::skip_if_no_network; -use core_test_support::streaming_sse::StreamingSseChunk; -use core_test_support::streaming_sse::start_streaming_sse_server; use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; -use serde_json::Value; use serde_json::json; use std::time::Duration; -use tokio::sync::oneshot; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn conversation_start_audio_text_close_round_trip() -> Result<()> { @@ -37,12 +29,22 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { "session": { "id": "sess_1" } })], vec![], - vec![json!({ - "type": "response.output_audio.delta", - "delta": "AQID", - "sample_rate": 24000, - "num_channels": 1 - })], + vec![ + json!({ + "type": "response.output_audio.delta", + "delta": "AQID", + "sample_rate": 24000, + "num_channels": 1 + }), + json!({ + "type": "conversation.item.added", + "item": { + "type": "message", + "role": "assistant", + "content": [{"type": "text", "text": "hi"}] + } + }), + ], ], ]) .await; @@ -456,237 +458,3 @@ async fn conversation_uses_experimental_realtime_ws_backend_prompt_override() -> server.shutdown().await; Ok(()) } - -fn sse_event(event: Value) -> String { - responses::sse(vec![event]) -} - -fn message_input_texts(body: &Value, role: &str) -> Vec { - body.get("input") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter(|item| item.get("type").and_then(Value::as_str) == Some("message")) - .filter(|item| item.get("role").and_then(Value::as_str) == Some(role)) - .filter_map(|item| item.get("content").and_then(Value::as_array)) - .flatten() - .filter(|span| span.get("type").and_then(Value::as_str) == Some("input_text")) - .filter_map(|span| span.get("text").and_then(Value::as_str).map(str::to_owned)) - .collect() -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn inbound_realtime_text_starts_turn_and_ignores_role() -> Result<()> { - skip_if_no_network!(Ok(())); - - let api_server = start_mock_server().await; - let response_mock = responses::mount_sse_once( - &api_server, - responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "ok"), - responses::ev_completed("resp-1"), - ]), - ) - .await; - - let realtime_server = start_websocket_server(vec![vec![vec![ - json!({ - "type": "session.created", - "session": { "id": "sess_inbound" } - }), - json!({ - "type": "conversation.item.added", - "item": { - "type": "message", - "role": "user", - "content": [{"type": "text", "text": "text from realtime"}] - } - }), - ]]]) - .await; - - let mut builder = test_codex().with_config({ - let realtime_base_url = realtime_server.uri().to_string(); - move |config| { - config.experimental_realtime_ws_base_url = Some(realtime_base_url); - } - }); - let test = builder.build(&api_server).await?; - - test.codex - .submit(Op::RealtimeConversationStart(ConversationStartParams { - prompt: "backend prompt".to_string(), - session_id: None, - })) - .await?; - - let session_created = wait_for_event_match(&test.codex, |msg| match msg { - EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, - }) => Some(session_id.clone()), - _ => None, - }) - .await; - assert_eq!(session_created, "sess_inbound"); - - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - - let request = response_mock.single_request(); - let user_texts = request.message_input_texts("user"); - assert!(user_texts.iter().any(|text| text == "text from realtime")); - - realtime_server.shutdown().await; - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn inbound_realtime_text_steers_active_turn() -> Result<()> { - skip_if_no_network!(Ok(())); - - let (gate_completed_tx, gate_completed_rx) = oneshot::channel(); - let first_chunks = vec![ - StreamingSseChunk { - gate: None, - body: sse_event(responses::ev_response_created("resp-1")), - }, - StreamingSseChunk { - gate: None, - body: sse_event(responses::ev_message_item_added("msg-1", "")), - }, - StreamingSseChunk { - gate: None, - body: sse_event(responses::ev_output_text_delta("first ")), - }, - StreamingSseChunk { - gate: None, - body: sse_event(responses::ev_output_text_delta("turn")), - }, - StreamingSseChunk { - gate: None, - body: sse_event(responses::ev_assistant_message("msg-1", "first turn")), - }, - StreamingSseChunk { - gate: Some(gate_completed_rx), - body: sse_event(responses::ev_completed("resp-1")), - }, - ]; - let second_chunks = vec![ - StreamingSseChunk { - gate: None, - body: sse_event(responses::ev_response_created("resp-2")), - }, - StreamingSseChunk { - gate: None, - body: sse_event(responses::ev_completed("resp-2")), - }, - ]; - let (api_server, _completions) = - start_streaming_sse_server(vec![first_chunks, second_chunks]).await; - - let realtime_server = start_websocket_server(vec![vec![ - vec![json!({ - "type": "session.created", - "session": { "id": "sess_steer" } - })], - vec![json!({ - "type": "conversation.item.added", - "item": { - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "steer via realtime"}] - } - })], - ]]) - .await; - - let mut builder = test_codex().with_model("gpt-5.1").with_config({ - let realtime_base_url = realtime_server.uri().to_string(); - move |config| { - config.experimental_realtime_ws_base_url = Some(realtime_base_url); - } - }); - let test = builder.build_with_streaming_server(&api_server).await?; - - test.codex - .submit(Op::RealtimeConversationStart(ConversationStartParams { - prompt: "backend prompt".to_string(), - session_id: None, - })) - .await?; - let _ = wait_for_event_match(&test.codex, |msg| match msg { - EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, - }) if session_id == "sess_steer" => Some(()), - _ => None, - }) - .await; - - test.codex - .submit(Op::UserInput { - items: vec![UserInput::Text { - text: "first prompt".to_string(), - text_elements: Vec::new(), - }], - final_output_json_schema: None, - }) - .await?; - - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::AgentMessageContentDelta(_)) - }) - .await; - - test.codex - .submit(Op::RealtimeConversationAudio(ConversationAudioParams { - frame: RealtimeAudioFrame { - data: "AQID".to_string(), - sample_rate: 24000, - num_channels: 1, - samples_per_channel: Some(480), - }, - })) - .await?; - - let _ = wait_for_event_match(&test.codex, |msg| match msg { - EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::ConversationItemAdded(item), - }) => item - .get("content") - .and_then(Value::as_array) - .into_iter() - .flatten() - .any(|content| { - content.get("text").and_then(Value::as_str) == Some("steer via realtime") - }) - .then_some(()), - _ => None, - }) - .await; - - let _ = gate_completed_tx.send(()); - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - - let requests = api_server.requests().await; - assert_eq!(requests.len(), 2); - - let first_body: Value = serde_json::from_slice(&requests[0]).expect("parse first request"); - let second_body: Value = serde_json::from_slice(&requests[1]).expect("parse second request"); - let first_texts = message_input_texts(&first_body, "user"); - let second_texts = message_input_texts(&second_body, "user"); - - assert!(first_texts.iter().any(|text| text == "first prompt")); - assert!(!first_texts.iter().any(|text| text == "steer via realtime")); - assert!(second_texts.iter().any(|text| text == "first prompt")); - assert!(second_texts.iter().any(|text| text == "steer via realtime")); - - realtime_server.shutdown().await; - api_server.shutdown().await; - Ok(()) -} From b73c4b50a27e2acdbe80875b4bfba20666889e28 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sat, 21 Feb 2026 17:06:35 -0800 Subject: [PATCH 068/385] fix: make realtime conversation flake test order-insensitive (#12475) ## Why `codex-core::all` has a flaky test, `suite::realtime_conversation::conversation_start_audio_text_close_round_trip`, that assumes a fixed ordering between `conversation.item.create` and `response.input_audio.delta` requests. That ordering is not guaranteed: realtime text and audio input are forwarded through separate queues and a background task, so either request can be observed first while still being correct behavior. ## What Changed - Updated the assertion in `codex-rs/core/tests/suite/realtime_conversation.rs` to compare the two observed request types order-independently. - Kept the existing checks that `session.create` is sent first and that exactly two follow-up requests are recorded. ## Verification - Re-ran `cargo test -p codex-core --test all conversation_start_audio_text_close_round_trip` 10 times locally. --- codex-rs/core/tests/suite/realtime_conversation.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index 466686788d..fc7b21e0e8 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -120,7 +120,7 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { .as_deref() .expect("started session id should be present") ); - let request_types = [ + let mut request_types = [ connection[1].body_json()["type"] .as_str() .expect("request type") @@ -130,6 +130,7 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { .expect("request type") .to_string(), ]; + request_types.sort(); assert_eq!( request_types, [ From 1dad0a7f4ac80fec91b36981d1cf3cb58326be9f Mon Sep 17 00:00:00 2001 From: Alex Kwiatkowski Date: Sat, 21 Feb 2026 20:08:02 -0800 Subject: [PATCH 069/385] Make shell detection tests robust to Nix shell paths (#12476) ## Summary - Updated `codex-rs/core/src/shell.rs` tests for shell detection to stop asserting hardcoded shell paths. - `detects_bash` and `detects_sh` now assert executable basenames (`bash`, `sh`) rather than `/bin/*`/`/usr/bin/*` absolute paths. - This keeps behavior the same while avoiding failures in Nix environments where shells are resolved from `/nix/store/.../bin`. ## Testing - `nix develop .#default --command sh -lc 'export PKG_CONFIG_PATH=/nix/store/6az1q591wwlgazzskngr6rl7gmhpyvnc-libcap-2.77-dev/lib/pkgconfig:/nix/store/fgm3pz8486ksh3f94629lpb7xjr2wjp7-openssl-3.6.0-dev/lib/pkgconfig:$PKG_CONFIG_PATH; export PKG_CONFIG_PATH_FOR_TARGET=$PKG_CONFIG_PATH; cd /home/alex/workspace/openai/codex/codex-rs && cargo test -p codex-core --lib detects_bash && cargo test -p codex-core --lib detects_sh'` ## Why The two failing tests previously hardcoded fixed paths and failed under the Nix shell due to Nix-provided shell binary locations. ## Links - Bug report / enhancement request: not publicly filed yet; this was reproduced in the local Nix environment. --- codex-rs/core/src/shell.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/shell.rs b/codex-rs/core/src/shell.rs index e4a1faf791..cec5d8a93a 100644 --- a/codex-rs/core/src/shell.rs +++ b/codex-rs/core/src/shell.rs @@ -343,7 +343,6 @@ mod detect_shell_type_tests { #[cfg(unix)] mod tests { use super::*; - use std::path::Path; use std::path::PathBuf; use std::process::Command; @@ -354,7 +353,7 @@ mod tests { let shell_path = zsh_shell.shell_path; - assert_eq!(shell_path, Path::new("/bin/zsh")); + assert_eq!(shell_path, std::path::Path::new("/bin/zsh")); } #[test] @@ -364,7 +363,7 @@ mod tests { let shell_path = zsh_shell.shell_path; - assert_eq!(shell_path, Path::new("/bin/zsh")); + assert_eq!(shell_path, std::path::Path::new("/bin/zsh")); } #[test] @@ -373,9 +372,7 @@ mod tests { let shell_path = bash_shell.shell_path; assert!( - shell_path == Path::new("/bin/bash") - || shell_path == Path::new("/usr/bin/bash") - || shell_path == Path::new("/usr/local/bin/bash"), + shell_path.file_name().and_then(|name| name.to_str()) == Some("bash"), "shell path: {shell_path:?}", ); } @@ -385,7 +382,7 @@ mod tests { let sh_shell = get_shell(ShellType::Sh, None).unwrap(); let shell_path = sh_shell.shell_path; assert!( - shell_path == Path::new("/bin/sh") || shell_path == Path::new("/usr/bin/sh"), + shell_path.file_name().and_then(|name| name.to_str()) == Some("sh"), "shell path: {shell_path:?}", ); } From c4f1af7a86a08d52a5bbbd27dcb5314c779827db Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Sun, 22 Feb 2026 01:26:58 -0300 Subject: [PATCH 070/385] feat(tui): syntax highlighting via syntect with theme picker (#11447) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Adds syntax highlighting to the TUI for fenced code blocks in markdown responses and file diffs, plus a `/theme` command with live preview and persistent theme selection. Uses syntect (~250 grammars, 32 bundled themes, ~1 MB binary cost) — the same engine behind `bat`, `delta`, and `xi-editor`. Includes guardrails for large inputs, graceful fallback to plain text, and SSH-aware clipboard integration for the `/copy` command. image image ## Problem Code blocks in the TUI (markdown responses and file diffs) render without syntax highlighting, making it hard to scan code at a glance. Users also have no way to pick a color theme that matches their terminal aesthetic. ## Mental model The highlighting system has three layers: 1. **Syntax engine** (`render::highlight`) -- a thin wrapper around syntect + two-face. It owns a process-global `SyntaxSet` (~250 grammars) and a `RwLock` that can be swapped at runtime. All public entry points accept `(code, lang)` and return ratatui `Span`/`Line` vectors or `None` when the language is unrecognized or the input exceeds safety guardrails. 2. **Rendering consumers** -- `markdown_render` feeds fenced code blocks through the engine; `diff_render` highlights Add/Delete content as a whole file and Update hunks per-hunk (preserving parser state across hunk lines). Both callers fall back to plain unstyled text when the engine returns `None`. 3. **Theme lifecycle** -- at startup the config's `tui.theme` is resolved to a syntect `Theme` via `set_theme_override`. At runtime the `/theme` picker calls `set_syntax_theme` to swap themes live; on cancel it restores the snapshot taken at open. On confirm it persists `[tui] theme = "..."` to config.toml. ## Non-goals - Inline diff highlighting (word-level change detection within a line). - Semantic / LSP-backed highlighting. - Theme authoring tooling; users supply standard `.tmTheme` files. ## Tradeoffs | Decision | Upside | Downside | | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | syntect over tree-sitter / arborium | ~1 MB binary increase for ~250 grammars + 32 themes; battle-tested crate powering widely-used tools (`bat`, `delta`, `xi-editor`). tree-sitter would add ~12 MB for 20-30 languages or ~35 MB for full coverage. | Regex-based; less structurally accurate than tree-sitter for some languages (e.g. language injections like JS-in-HTML). | | Global `RwLock` | Enables live `/theme` preview without threading Theme through every call site | Lock contention risk (mitigated: reads vastly outnumber writes, single UI thread) | | Skip background / italic / underline from themes | Terminal BG preserved, avoids ugly rendering on some themes | Themes that rely on these properties lose fidelity | | Guardrails: 512 KB / 10k lines | Prevents pathological stalls on huge diffs or pastes | Very large files render without color | ## Architecture ``` config.toml ─[tui.theme]─> set_theme_override() ─> THEME (RwLock) │ ┌───────────────────────────────────────────┘ │ markdown_render ─── highlight_code_to_lines(code, lang) ─> Vec diff_render ─── highlight_code_to_styled_spans(code, lang) ─> Option>> │ │ (None ⇒ plain text fallback) │ /theme picker ─── set_syntax_theme(theme) // live preview swap ─── current_syntax_theme() // snapshot for cancel ─── resolve_theme_by_name(name) // lookup by kebab-case ``` Key files: - `tui/src/render/highlight.rs` -- engine, theme management, guardrails - `tui/src/diff_render.rs` -- syntax-aware diff line wrapping - `tui/src/theme_picker.rs` -- `/theme` command builder - `tui/src/bottom_pane/list_selection_view.rs` -- side content panel, callbacks - `core/src/config/types.rs` -- `Tui::theme` field - `core/src/config/edit.rs` -- `syntax_theme_edit()` helper ## Observability - `tracing::warn` when a configured theme name cannot be resolved. - `Config::startup_warnings` surfaces the same message as a TUI banner. - `tracing::error` when persisting theme selection fails. ## Tests - Unit tests in `highlight.rs`: language coverage, fallback behavior, CRLF stripping, style conversion, guardrail enforcement, theme name mapping exhaustiveness. - Unit tests in `diff_render.rs`: snapshot gallery at multiple terminal sizes (80x24, 94x35, 120x40), syntax-highlighted wrapping, large-diff guardrail, rename-to-different-extension highlighting, parser state preservation across hunk lines. - Unit tests in `theme_picker.rs`: preview rendering (wide + narrow), dim overlay on deletions, subtitle truncation, cancel-restore, fallback for unavailable configured theme. - Unit tests in `list_selection_view.rs`: side layout geometry, stacked fallback, buffer clearing, cancel/selection-changed callbacks. - Integration test in `lib.rs`: theme warning uses the final (post-resume) config. ## Cargo Deny: Unmaintained Dependency Exceptions This PR adds two `cargo deny` advisory exceptions for transitive dependencies pulled in by `syntect v5.3.0`: | Advisory | Crate | Status | |----------|-------|--------| | RUSTSEC-2024-0320 | `yaml-rust` | Unmaintained (maintainer unreachable) | | RUSTSEC-2025-0141 | `bincode` | Unmaintained (development ceased; v1.3.3 considered complete) | **Why this is safe in our usage:** - Neither advisory describes a known security vulnerability. Both are "unmaintained" notices only. - `bincode` is used by syntect to deserialize pre-compiled syntax sets. Again, these are **static vendored artifacts** baked into the binary at build time. No user-supplied bincode data is ever deserialized. - Attack surface is zero for both crates; exploitation would require a supply-chain compromise of our own build artifacts. - These exceptions can be removed when syntect migrates to `yaml-rust2` and drops `bincode`, or when alternative crates are available upstream. --- codex-rs/Cargo.lock | 107 +- codex-rs/Cargo.toml | 2 +- codex-rs/core/config.schema.json | 5 + codex-rs/core/src/config/edit.rs | 8 + codex-rs/core/src/config/mod.rs | 33 + codex-rs/core/src/config/types.rs | 7 + codex-rs/deny.toml | 3 + codex-rs/tui/Cargo.toml | 4 +- codex-rs/tui/src/app.rs | 64 + codex-rs/tui/src/app_event.rs | 5 + .../src/bottom_pane/list_selection_view.rs | 625 ++++++++- codex-rs/tui/src/bottom_pane/mod.rs | 3 + codex-rs/tui/src/chatwidget.rs | 22 + ...dget__tests__exec_approval_modal_exec.snap | 3 + codex-rs/tui/src/diff_render.rs | 889 ++++++++++-- codex-rs/tui/src/lib.rs | 59 +- codex-rs/tui/src/markdown_render.rs | 79 +- codex-rs/tui/src/markdown_render_tests.rs | 137 +- codex-rs/tui/src/render/highlight.rs | 1233 ++++++++++++++--- codex-rs/tui/src/slash_command.rs | 3 + ...ff_render__tests__diff_gallery_120x40.snap | 44 + ...iff_render__tests__diff_gallery_80x24.snap | 28 + ...iff_render__tests__diff_gallery_94x35.snap | 39 + ...ests__syntax_highlighted_insert_wraps.snap | 14 + ..._syntax_highlighted_insert_wraps_text.snap | 7 + codex-rs/tui/src/theme_picker.rs | 620 +++++++++ 26 files changed, 3726 insertions(+), 317 deletions(-) create mode 100644 codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_120x40.snap create mode 100644 codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_80x24.snap create mode 100644 codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_94x35.snap create mode 100644 codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps.snap create mode 100644 codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps_text.snap create mode 100644 codex-rs/tui/src/theme_picker.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 31bc8d65a7..c910f95442 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -852,6 +852,15 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + [[package]] name = "bit-set" version = "0.5.3" @@ -2297,6 +2306,7 @@ dependencies = [ "strum 0.27.2", "strum_macros 0.27.2", "supports-color 3.0.2", + "syntect", "tempfile", "textwrap 0.16.2", "thiserror 2.0.18", @@ -2307,8 +2317,7 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", - "tree-sitter-bash", - "tree-sitter-highlight", + "two-face", "unicode-segmentation", "unicode-width 0.2.1", "url", @@ -5157,6 +5166,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + [[package]] name = "linux-keyutils" version = "0.2.4" @@ -5964,6 +5979,28 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "onig" +version = "6.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "336b9c63443aceef14bea841b899035ae3abe89b7c486aaf4c5bd8aafedac3f0" +dependencies = [ + "bitflags 2.10.0", + "libc", + "once_cell", + "onig_sys", +] + +[[package]] +name = "onig_sys" +version = "69.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f86c6eef3d6df15f23bcfb6af487cbd2fed4e5581d58d5bf1f5f8b7f6727dc" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "opaque-debug" version = "0.3.1" @@ -6381,6 +6418,19 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +[[package]] +name = "plist" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" +dependencies = [ + "base64 0.22.1", + "indexmap 2.13.0", + "quick-xml", + "serde", + "time", +] + [[package]] name = "png" version = "0.18.0" @@ -8886,6 +8936,27 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "syntect" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925" +dependencies = [ + "bincode", + "flate2", + "fnv", + "once_cell", + "onig", + "plist", + "regex-syntax 0.8.8", + "serde", + "serde_derive", + "serde_json", + "thiserror 2.0.18", + "walkdir", + "yaml-rust", +] + [[package]] name = "sys-locale" version = "0.3.2" @@ -9622,18 +9693,6 @@ dependencies = [ "tree-sitter-language", ] -[[package]] -name = "tree-sitter-highlight" -version = "0.25.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc5f880ad8d8f94e88cb81c3557024cf1a8b75e3b504c50481ed4f5a6006ff3" -dependencies = [ - "regex", - "streaming-iterator", - "thiserror 2.0.18", - "tree-sitter", -] - [[package]] name = "tree-sitter-language" version = "0.1.7" @@ -9701,6 +9760,17 @@ dependencies = [ "utf-8", ] +[[package]] +name = "two-face" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b285c51f8a6ade109ed4566d33ac4fb289fb5d6cf87ed70908a5eaf65e948e34" +dependencies = [ + "serde", + "serde_derive", + "syntect", +] + [[package]] name = "type-map" version = "0.5.1" @@ -10965,6 +11035,15 @@ dependencies = [ "lzma-sys", ] +[[package]] +name = "yaml-rust" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +dependencies = [ + "linked-hash-map", +] + [[package]] name = "yansi" version = "1.0.1" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index d23ed3c27b..e22dba12c2 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -276,7 +276,7 @@ tracing-subscriber = "0.3.22" tracing-test = "0.2.5" tree-sitter = "0.25.10" tree-sitter-bash = "0.25" -tree-sitter-highlight = "0.25.10" +syntect = "5" ts-rs = "11" tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] } uds_windows = "1.1.0" diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index addbcbe313..ed1ae8ddbf 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1400,6 +1400,11 @@ "type": "string" }, "type": "array" + }, + "theme": { + "default": null, + "description": "Syntax highlighting theme name (kebab-case).\n\nWhen set, overrides automatic light/dark theme detection. Use `/theme` in the TUI or see `$CODEX_HOME/themes` for custom themes.", + "type": "string" } }, "type": "object" diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 0dfb4efd8e..fceb965998 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -55,6 +55,14 @@ pub enum ConfigEdit { ClearPath { segments: Vec }, } +/// Produces a config edit that sets `[tui] theme = ""`. +pub fn syntax_theme_edit(name: &str) -> ConfigEdit { + ConfigEdit::SetPath { + segments: vec!["tui".to_string(), "theme".to_string()], + value: value(name.to_string()), + } +} + pub fn status_line_items_edit(items: &[String]) -> ConfigEdit { let mut array = toml_edit::Array::new(); for item in items { diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index ddc5aa9cdd..6474ca4bc0 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -278,6 +278,9 @@ pub struct Config { /// `current-dir`. pub tui_status_line: Option>, + /// Syntax highlighting theme override (kebab-case name). + pub tui_theme: Option, + /// The directory that should be treated as the current working directory /// for the session. All relative paths inside the business-logic layer are /// resolved against this path. @@ -2120,6 +2123,7 @@ impl Config { .map(|t| t.alternate_screen) .unwrap_or_default(), tui_status_line: cfg.tui.as_ref().and_then(|t| t.status_line.clone()), + tui_theme: cfg.tui.as_ref().and_then(|t| t.theme.clone()), otel: { let t: OtelConfigToml = cfg.otel.unwrap_or_default(); let log_user_prompt = t.log_user_prompt.unwrap_or(false); @@ -2518,6 +2522,30 @@ allowed_domains = ["openai.com"] Ok(()) } + #[test] + fn tui_theme_deserializes_from_toml() { + let cfg = r#" +[tui] +theme = "dracula" +"#; + let parsed = + toml::from_str::(cfg).expect("TOML deserialization should succeed"); + assert_eq!( + parsed.tui.as_ref().and_then(|t| t.theme.as_deref()), + Some("dracula"), + ); + } + + #[test] + fn tui_theme_defaults_to_none() { + let cfg = r#" +[tui] +"#; + let parsed = + toml::from_str::(cfg).expect("TOML deserialization should succeed"); + assert_eq!(parsed.tui.as_ref().and_then(|t| t.theme.as_deref()), None); + } + #[test] fn tui_config_missing_notifications_field_defaults_to_enabled() { let cfg = r#" @@ -2537,6 +2565,7 @@ allowed_domains = ["openai.com"] show_tooltips: true, alternate_screen: AltScreenMode::Auto, status_line: None, + theme: None, } ); } @@ -4646,6 +4675,7 @@ model_verbosity = "high" feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, tui_status_line: None, + tui_theme: None, otel: OtelConfig::default(), }, o3_profile_config @@ -4768,6 +4798,7 @@ model_verbosity = "high" feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, tui_status_line: None, + tui_theme: None, otel: OtelConfig::default(), }; @@ -4888,6 +4919,7 @@ model_verbosity = "high" feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, tui_status_line: None, + tui_theme: None, otel: OtelConfig::default(), }; @@ -4994,6 +5026,7 @@ model_verbosity = "high" feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, tui_status_line: None, + tui_theme: None, otel: OtelConfig::default(), }; diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index 2e3573f770..678766e807 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -681,6 +681,13 @@ pub struct Tui { /// `current-dir`. #[serde(default)] pub status_line: Option>, + + /// Syntax highlighting theme name (kebab-case). + /// + /// When set, overrides automatic light/dark theme detection. + /// Use `/theme` in the TUI or see `$CODEX_HOME/themes` for custom themes. + #[serde(default)] + pub theme: Option, } const fn default_true() -> bool { diff --git a/codex-rs/deny.toml b/codex-rs/deny.toml index e96e6fbd33..29bf6c5880 100644 --- a/codex-rs/deny.toml +++ b/codex-rs/deny.toml @@ -75,6 +75,9 @@ ignore = [ { id = "RUSTSEC-2024-0436", reason = "paste is unmaintained; pulled in via ratatui/rmcp/starlark used by tui/execpolicy; no fixed release yet" }, # TODO(joshka, nornagon): remove this exception when once we update the ratatui fork to a version that uses lru 0.13+. { id = "RUSTSEC-2026-0002", reason = "lru 0.12.5 is pulled in via ratatui fork; cannot upgrade until the fork is updated" }, + # TODO(fcoury): remove this exception when syntect drops yaml-rust and bincode, or updates to versions that have fixed the vulnerabilities. + { id = "RUSTSEC-2024-0320", reason = "yaml-rust is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, + { id = "RUSTSEC-2025-0141", reason = "bincode is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, ] # If this is true, then cargo deny will use the git executable to fetch advisory database. # If this is false, then it uses a built-in git library. diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 683b0828dc..1b0ed9771e 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -93,8 +93,8 @@ toml = { workspace = true } tracing = { workspace = true, features = ["log"] } tracing-appender = { workspace = true } tracing-subscriber = { workspace = true, features = ["env-filter"] } -tree-sitter-bash = { workspace = true } -tree-sitter-highlight = { workspace = true } +syntect = "5" +two-face = { version = "0.5", default-features = false, features = ["syntect-default-onig"] } unicode-segmentation = { workspace = true } unicode-width = { workspace = true } url = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index ebbf757523..22ceed1ffa 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -2605,6 +2605,34 @@ impl App { AppEvent::StatusLineSetupCancelled => { self.chat_widget.cancel_status_line_setup(); } + AppEvent::SyntaxThemeSelected { name } => { + let edit = codex_core::config::edit::syntax_theme_edit(&name); + let apply_result = ConfigEditsBuilder::new(&self.config.codex_home) + .with_edits([edit]) + .apply() + .await; + match apply_result { + Ok(()) => { + // Ensure the selected theme is active in the current + // session. The preview callback covers arrow-key + // navigation, but if the user presses Enter without + // navigating, the runtime theme must still be applied. + if let Some(theme) = crate::render::highlight::resolve_theme_by_name( + &name, + Some(&self.config.codex_home), + ) { + crate::render::highlight::set_syntax_theme(theme); + } + self.sync_tui_theme_selection(name); + } + Err(err) => { + self.restore_runtime_theme_from_config(); + tracing::error!(error = %err, "failed to persist theme selection"); + self.chat_widget + .add_error_message(format!("Failed to save theme: {err}")); + } + } + } } Ok(AppRunControl::Continue) } @@ -2783,6 +2811,29 @@ impl App { self.chat_widget.set_personality(personality); } + fn sync_tui_theme_selection(&mut self, name: String) { + self.config.tui_theme = Some(name.clone()); + self.chat_widget.set_tui_theme(Some(name)); + } + + fn restore_runtime_theme_from_config(&self) { + if let Some(name) = self.config.tui_theme.as_deref() + && let Some(theme) = + crate::render::highlight::resolve_theme_by_name(name, Some(&self.config.codex_home)) + { + crate::render::highlight::set_syntax_theme(theme); + return; + } + + let auto_theme_name = crate::render::highlight::adaptive_default_theme_name(); + if let Some(theme) = crate::render::highlight::resolve_theme_by_name( + auto_theme_name, + Some(&self.config.codex_home), + ) { + crate::render::highlight::set_syntax_theme(theme); + } + } + fn personality_label(personality: Personality) -> &'static str { match personality { Personality::None => "None", @@ -3655,6 +3706,19 @@ mod tests { Ok(()) } + #[tokio::test] + async fn sync_tui_theme_selection_updates_chat_widget_config_copy() { + let mut app = make_test_app().await; + + app.sync_tui_theme_selection("dracula".to_string()); + + assert_eq!(app.config.tui_theme.as_deref(), Some("dracula")); + assert_eq!( + app.chat_widget.config_ref().tui_theme.as_deref(), + Some("dracula") + ); + } + #[tokio::test] async fn backtrack_selection_with_duplicate_history_targets_unique_turn() { let (mut app, _app_event_rx, mut op_rx) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 159cda88f4..60c25fcc4e 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -360,6 +360,11 @@ pub(crate) enum AppEvent { }, /// Dismiss the status-line setup UI without changing config. StatusLineSetupCancelled, + + /// Apply a user-confirmed syntax theme selection. + SyntaxThemeSelected { + name: String, + }, } /// The exit strategy requested by the UI layer. diff --git a/codex-rs/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rs index 14f94ca6f4..ad40c1660f 100644 --- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs @@ -33,9 +33,76 @@ use super::selection_popup_common::render_rows_stable_col_widths; use super::selection_popup_common::render_rows_with_col_width_mode; use unicode_width::UnicodeWidthStr; +/// Minimum list width (in content columns) required before the side-by-side +/// layout is activated. Keeps the list usable even when sharing horizontal +/// space with the side content panel. +const MIN_LIST_WIDTH_FOR_SIDE: u16 = 40; + +/// Horizontal gap (in columns) between the list area and the side content +/// panel when side-by-side layout is active. +const SIDE_CONTENT_GAP: u16 = 2; + +/// Shared menu-surface horizontal inset (2 cells per side) used by selection popups. +const MENU_SURFACE_HORIZONTAL_INSET: u16 = 4; + +/// Controls how the side content panel is sized relative to the popup width. +/// +/// When the computed side width falls below `side_content_min_width` or the +/// remaining list area would be narrower than [`MIN_LIST_WIDTH_FOR_SIDE`], the +/// side-by-side layout is abandoned and the stacked fallback is used instead. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SideContentWidth { + /// Fixed number of columns. `Fixed(0)` disables side content entirely. + Fixed(u16), + /// Exact 50/50 split of the content area (minus the inter-column gap). + Half, +} + +impl Default for SideContentWidth { + fn default() -> Self { + Self::Fixed(0) + } +} + +/// Returns the popup content width after subtracting the shared menu-surface +/// horizontal inset (2 columns on each side). +pub(crate) fn popup_content_width(total_width: u16) -> u16 { + total_width.saturating_sub(MENU_SURFACE_HORIZONTAL_INSET) +} + +/// Returns side-by-side layout widths as `(list_width, side_width)` when the +/// layout can fit. Returns `None` when the side panel is disabled/too narrow or +/// when the remaining list width would become unusably small. +pub(crate) fn side_by_side_layout_widths( + content_width: u16, + side_content_width: SideContentWidth, + side_content_min_width: u16, +) -> Option<(u16, u16)> { + let side_width = match side_content_width { + SideContentWidth::Fixed(0) => return None, + SideContentWidth::Fixed(width) => width, + SideContentWidth::Half => content_width.saturating_sub(SIDE_CONTENT_GAP) / 2, + }; + if side_width < side_content_min_width { + return None; + } + let list_width = content_width.saturating_sub(SIDE_CONTENT_GAP + side_width); + (list_width >= MIN_LIST_WIDTH_FOR_SIDE).then_some((list_width, side_width)) +} + /// One selectable item in the generic selection list. pub(crate) type SelectionAction = Box; +/// Callback invoked whenever the highlighted item changes (arrow keys, search +/// filter, number-key jump). Receives the *actual* index into the unfiltered +/// `items` list and the event sender. Used by the theme picker for live preview. +pub(crate) type OnSelectionChangedCallback = + Option>; + +/// Callback invoked when the picker is dismissed without accepting (Esc or +/// Ctrl+C). Used by the theme picker to restore the pre-open theme. +pub(crate) type OnCancelCallback = Option>; + /// One row in a [`ListSelectionView`] selection list. /// /// This is the source-of-truth model for row state before filtering and @@ -79,6 +146,28 @@ pub(crate) struct SelectionViewParams { pub col_width_mode: ColumnWidthMode, pub header: Box, pub initial_selected_idx: Option, + + /// Rich content rendered beside (wide terminals) or below (narrow terminals) + /// the list items, inside the bordered menu surface. Used by the theme picker + /// to show a syntax-highlighted preview. + pub side_content: Box, + + /// Width mode for side content when side-by-side layout is active. + pub side_content_width: SideContentWidth, + + /// Minimum side panel width required before side-by-side layout activates. + pub side_content_min_width: u16, + + /// Optional fallback content rendered when side-by-side does not fit. + /// When absent, `side_content` is reused. + pub stacked_side_content: Option>, + + /// Called when the highlighted item changes (navigation, filter, number-key). + /// Receives the *actual* item index, not the filtered/visible index. + pub on_selection_changed: OnSelectionChangedCallback, + + /// Called when the picker is dismissed via Esc/Ctrl+C without selecting. + pub on_cancel: OnCancelCallback, } impl Default for SelectionViewParams { @@ -95,6 +184,12 @@ impl Default for SelectionViewParams { col_width_mode: ColumnWidthMode::AutoVisible, header: Box::new(()), initial_selected_idx: None, + side_content: Box::new(()), + side_content_width: SideContentWidth::default(), + side_content_min_width: 0, + stacked_side_content: None, + on_selection_changed: None, + on_cancel: None, } } } @@ -120,6 +215,16 @@ pub(crate) struct ListSelectionView { last_selected_actual_idx: Option, header: Box, initial_selected_idx: Option, + side_content: Box, + side_content_width: SideContentWidth, + side_content_min_width: u16, + stacked_side_content: Option>, + + /// Called when the highlighted item changes (navigation, filter, number-key). + on_selection_changed: OnSelectionChangedCallback, + + /// Called when the picker is dismissed via Esc/Ctrl+C without selecting. + on_cancel: OnCancelCallback, } impl ListSelectionView { @@ -161,6 +266,12 @@ impl ListSelectionView { last_selected_actual_idx: None, header, initial_selected_idx: params.initial_selected_idx, + side_content: params.side_content, + side_content_width: params.side_content_width, + side_content_min_width: params.side_content_min_width, + stacked_side_content: params.stacked_side_content, + on_selection_changed: params.on_selection_changed, + on_cancel: params.on_cancel, }; s.apply_filter(); s @@ -174,11 +285,15 @@ impl ListSelectionView { MAX_POPUP_ROWS.min(len.max(1)) } - fn apply_filter(&mut self) { - let previously_selected = self - .state + fn selected_actual_idx(&self) -> Option { + self.state .selected_idx .and_then(|visible_idx| self.filtered_indices.get(visible_idx).copied()) + } + + fn apply_filter(&mut self) { + let previously_selected = self + .selected_actual_idx() .or_else(|| { (!self.is_searchable) .then(|| self.items.iter().position(|item| item.is_current)) @@ -222,6 +337,13 @@ impl ListSelectionView { let visible = Self::max_visible_rows(len); self.state.clamp_selection(len); self.state.ensure_visible(len, visible); + + // Notify the callback when filtering changes the selected actual item + // so live preview stays in sync (e.g. typing in the theme picker). + let new_actual = self.selected_actual_idx(); + if new_actual != previously_selected { + self.fire_selection_changed(); + } } fn build_rows(&self) -> Vec { @@ -273,19 +395,35 @@ impl ListSelectionView { } fn move_up(&mut self) { + let before = self.selected_actual_idx(); let len = self.visible_len(); self.state.move_up_wrap(len); let visible = Self::max_visible_rows(len); self.state.ensure_visible(len, visible); self.skip_disabled_up(); + if self.selected_actual_idx() != before { + self.fire_selection_changed(); + } } fn move_down(&mut self) { + let before = self.selected_actual_idx(); let len = self.visible_len(); self.state.move_down_wrap(len); let visible = Self::max_visible_rows(len); self.state.ensure_visible(len, visible); self.skip_disabled_down(); + if self.selected_actual_idx() != before { + self.fire_selection_changed(); + } + } + + fn fire_selection_changed(&self) { + if let Some(cb) = &self.on_selection_changed + && let Some(actual) = self.selected_actual_idx() + { + cb(actual, &self.app_event_tx); + } } fn accept(&mut self) { @@ -310,6 +448,9 @@ impl ListSelectionView { self.complete = true; } } else if selected_item.is_none() { + if let Some(cb) = &self.on_cancel { + cb(&self.app_event_tx); + } self.complete = true; } } @@ -328,6 +469,63 @@ impl ListSelectionView { total_width.saturating_sub(2) } + fn clear_to_terminal_bg(buf: &mut Buffer, area: Rect) { + let buf_area = buf.area(); + let min_x = area.x.max(buf_area.x); + let min_y = area.y.max(buf_area.y); + let max_x = area + .x + .saturating_add(area.width) + .min(buf_area.x.saturating_add(buf_area.width)); + let max_y = area + .y + .saturating_add(area.height) + .min(buf_area.y.saturating_add(buf_area.height)); + for y in min_y..max_y { + for x in min_x..max_x { + buf[(x, y)] + .set_symbol(" ") + .set_style(ratatui::style::Style::reset()); + } + } + } + + fn force_bg_to_terminal_bg(buf: &mut Buffer, area: Rect) { + let buf_area = buf.area(); + let min_x = area.x.max(buf_area.x); + let min_y = area.y.max(buf_area.y); + let max_x = area + .x + .saturating_add(area.width) + .min(buf_area.x.saturating_add(buf_area.width)); + let max_y = area + .y + .saturating_add(area.height) + .min(buf_area.y.saturating_add(buf_area.height)); + for y in min_y..max_y { + for x in min_x..max_x { + buf[(x, y)].set_bg(ratatui::style::Color::Reset); + } + } + } + + fn stacked_side_content(&self) -> &dyn Renderable { + self.stacked_side_content + .as_deref() + .unwrap_or_else(|| self.side_content.as_ref()) + } + + /// Returns `Some(side_width)` when the content area is wide enough for a + /// side-by-side layout (list + gap + side panel), `None` otherwise. + fn side_layout_width(&self, content_width: u16) -> Option { + side_by_side_layout_widths( + content_width, + self.side_content_width, + self.side_content_min_width, + ) + .map(|(_, side_width)| side_width) + } + fn skip_disabled_down(&mut self) { let len = self.visible_len(); for _ in 0..len { @@ -469,6 +667,9 @@ impl BottomPaneView for ListSelectionView { } fn on_ctrl_c(&mut self) -> CancellationEvent { + if let Some(cb) = &self.on_cancel { + cb(&self.app_event_tx); + } self.complete = true; CancellationEvent::Handled } @@ -476,38 +677,59 @@ impl BottomPaneView for ListSelectionView { impl Renderable for ListSelectionView { fn desired_height(&self, width: u16) -> u16 { - // Measure wrapped height for up to MAX_POPUP_ROWS items at the given width. - // Build the same display rows used by the renderer so wrapping math matches. + // Inner content width after menu surface horizontal insets (2 per side). + let inner_width = popup_content_width(width); + + // When side-by-side is active, measure the list at the reduced width + // that accounts for the gap and side panel. + let effective_rows_width = if let Some(side_w) = self.side_layout_width(inner_width) { + Self::rows_width(width).saturating_sub(SIDE_CONTENT_GAP + side_w) + } else { + Self::rows_width(width) + }; + + // Measure wrapped height for up to MAX_POPUP_ROWS items. let rows = self.build_rows(); - let rows_width = Self::rows_width(width); let rows_height = match self.col_width_mode { ColumnWidthMode::AutoVisible => measure_rows_height( &rows, &self.state, MAX_POPUP_ROWS, - rows_width.saturating_add(1), + effective_rows_width.saturating_add(1), ), ColumnWidthMode::AutoAllRows => measure_rows_height_stable_col_widths( &rows, &self.state, MAX_POPUP_ROWS, - rows_width.saturating_add(1), + effective_rows_width.saturating_add(1), ), ColumnWidthMode::Fixed => measure_rows_height_with_col_width_mode( &rows, &self.state, MAX_POPUP_ROWS, - rows_width.saturating_add(1), + effective_rows_width.saturating_add(1), ColumnWidthMode::Fixed, ), }; - // Subtract 4 for the padding on the left and right of the header. - let mut height = self.header.desired_height(width.saturating_sub(4)); + let mut height = self.header.desired_height(inner_width); height = height.saturating_add(rows_height + 3); if self.is_searchable { height = height.saturating_add(1); } + + // Side content: when the terminal is wide enough the panel sits beside + // the list and shares vertical space; otherwise it stacks below. + if self.side_layout_width(inner_width).is_some() { + // Side-by-side — side content shares list rows vertically so it + // doesn't add to total height. + } else { + let side_h = self.stacked_side_content().desired_height(inner_width); + if side_h > 0 { + height = height.saturating_add(1 + side_h); + } + } + if let Some(note) = &self.footer_note { let note_width = width.saturating_sub(2); let note_lines = wrap_styled_line(note, note_width); @@ -538,41 +760,60 @@ impl Renderable for ListSelectionView { // Paint the shared menu surface and then layout inside the returned inset. let content_area = render_menu_surface(outer_content_area, buf); - let header_height = self - .header - // Subtract 4 for the padding on the left and right of the header. - .desired_height(outer_content_area.width.saturating_sub(4)); + let inner_width = popup_content_width(outer_content_area.width); + let side_w = self.side_layout_width(inner_width); + + // When side-by-side is active, shrink the list to make room. + let full_rows_width = Self::rows_width(outer_content_area.width); + let effective_rows_width = if let Some(sw) = side_w { + full_rows_width.saturating_sub(SIDE_CONTENT_GAP + sw) + } else { + full_rows_width + }; + + let header_height = self.header.desired_height(inner_width); let rows = self.build_rows(); - let rows_width = Self::rows_width(outer_content_area.width); let rows_height = match self.col_width_mode { ColumnWidthMode::AutoVisible => measure_rows_height( &rows, &self.state, MAX_POPUP_ROWS, - rows_width.saturating_add(1), + effective_rows_width.saturating_add(1), ), ColumnWidthMode::AutoAllRows => measure_rows_height_stable_col_widths( &rows, &self.state, MAX_POPUP_ROWS, - rows_width.saturating_add(1), + effective_rows_width.saturating_add(1), ), ColumnWidthMode::Fixed => measure_rows_height_with_col_width_mode( &rows, &self.state, MAX_POPUP_ROWS, - rows_width.saturating_add(1), + effective_rows_width.saturating_add(1), ColumnWidthMode::Fixed, ), }; - let [header_area, _, search_area, list_area] = Layout::vertical([ + + // Stacked (fallback) side content height — only used when not side-by-side. + let stacked_side_h = if side_w.is_none() { + self.stacked_side_content().desired_height(inner_width) + } else { + 0 + }; + let stacked_gap = if stacked_side_h > 0 { 1 } else { 0 }; + + let [header_area, _, search_area, list_area, _, stacked_side_area] = Layout::vertical([ Constraint::Max(header_height), Constraint::Max(1), Constraint::Length(if self.is_searchable { 1 } else { 0 }), Constraint::Length(rows_height), + Constraint::Length(stacked_gap), + Constraint::Length(stacked_side_h), ]) .areas(content_area); + // -- Header -- if header_area.height < header_height { let [header_area, elision_area] = Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(header_area); @@ -585,6 +826,7 @@ impl Renderable for ListSelectionView { self.header.render(header_area, buf); } + // -- Search bar -- if self.is_searchable { Line::from(self.search_query.clone()).render(search_area, buf); let query_span: Span<'static> = if self.search_query.is_empty() { @@ -598,11 +840,12 @@ impl Renderable for ListSelectionView { Line::from(query_span).render(search_area, buf); } + // -- List rows -- if list_area.height > 0 { let render_area = Rect { x: list_area.x.saturating_sub(2), y: list_area.y, - width: rows_width.max(1), + width: effective_rows_width.max(1), height: list_area.height, }; match self.col_width_mode { @@ -634,6 +877,53 @@ impl Renderable for ListSelectionView { }; } + // -- Side content (preview panel) -- + if let Some(sw) = side_w { + // Side-by-side: render to the right half of the popup content + // area so preview content can center vertically in that panel. + let side_x = content_area.x + content_area.width - sw; + let side_area = Rect::new(side_x, content_area.y, sw, content_area.height); + + // Clear the menu-surface background behind the side panel so the + // preview appears on the terminal's own background. + let clear_x = side_x.saturating_sub(SIDE_CONTENT_GAP); + let clear_w = outer_content_area + .x + .saturating_add(outer_content_area.width) + .saturating_sub(clear_x); + Self::clear_to_terminal_bg( + buf, + Rect::new( + clear_x, + outer_content_area.y, + clear_w, + outer_content_area.height, + ), + ); + self.side_content.render(side_area, buf); + Self::force_bg_to_terminal_bg( + buf, + Rect::new( + clear_x, + outer_content_area.y, + clear_w, + outer_content_area.height, + ), + ); + } else if stacked_side_area.height > 0 { + // Stacked fallback: render below the list (same as old footer_content). + let clear_height = (outer_content_area.y + outer_content_area.height) + .saturating_sub(stacked_side_area.y); + let clear_area = Rect::new( + outer_content_area.x, + stacked_side_area.y, + outer_content_area.width, + clear_height, + ); + Self::clear_to_terminal_bg(buf, clear_area); + self.stacked_side_content().render(stacked_side_area, buf); + } + if footer_area.height > 0 { let [note_area, hint_area] = Layout::vertical([ Constraint::Length(note_height), @@ -683,9 +973,33 @@ mod tests { use crossterm::event::KeyCode; use insta::assert_snapshot; use pretty_assertions::assert_eq; + use ratatui::buffer::Buffer; use ratatui::layout::Rect; + use ratatui::style::Color; + use ratatui::style::Style; use tokio::sync::mpsc::unbounded_channel; + struct MarkerRenderable { + marker: &'static str, + height: u16, + } + + impl Renderable for MarkerRenderable { + fn render(&self, area: Rect, buf: &mut Buffer) { + for y in area.y..area.y.saturating_add(area.height) { + for x in area.x..area.x.saturating_add(area.width) { + if x < buf.area().width && y < buf.area().height { + buf[(x, y)].set_symbol(self.marker); + } + } + } + } + + fn desired_height(&self, _width: u16) -> u16 { + self.height + } + } + fn make_selection_view(subtitle: Option<&str>) -> ListSelectionView { let (tx_raw, _rx) = unbounded_channel::(); let tx = AppEventSender::new(tx_raw); @@ -722,7 +1036,10 @@ mod tests { } fn render_lines_with_width(view: &ListSelectionView, width: u16) -> String { - let height = view.desired_height(width); + render_lines_in_area(view, width, view.desired_height(width)) + } + + fn render_lines_in_area(view: &ListSelectionView, width: u16, height: u16) -> String { let area = Rect::new(0, 0, width, height); let mut buf = Buffer::empty(area); view.render(area, &mut buf); @@ -808,6 +1125,20 @@ mod tests { assert_snapshot!("list_selection_spacing_with_subtitle", render_lines(&view)); } + #[test] + fn theme_picker_subtitle_uses_fallback_text_in_94x35_terminal() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let home = dirs::home_dir().expect("home directory should be available"); + let codex_home = home.join(".codex"); + let params = + crate::theme_picker::build_theme_picker_params(None, Some(&codex_home), Some(94)); + let view = ListSelectionView::new(params, tx); + + let rendered = render_lines_in_area(&view, 94, 35); + assert!(rendered.contains("Move up/down to live preview themes")); + } + #[test] fn snapshot_footer_note_wraps() { let (tx_raw, _rx) = unbounded_channel::(); @@ -871,6 +1202,66 @@ mod tests { ); } + #[test] + fn enter_with_no_matches_triggers_cancel_callback() { + let (tx_raw, mut rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut view = ListSelectionView::new( + SelectionViewParams { + items: vec![SelectionItem { + name: "Read Only".to_string(), + dismiss_on_select: true, + ..Default::default() + }], + is_searchable: true, + on_cancel: Some(Box::new(|tx: &_| { + tx.send(AppEvent::OpenApprovalsPopup); + })), + ..Default::default() + }, + tx, + ); + view.set_search_query("no-matches".to_string()); + + view.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + assert!(view.is_complete()); + match rx.try_recv() { + Ok(AppEvent::OpenApprovalsPopup) => {} + Ok(other) => panic!("expected OpenApprovalsPopup cancel event, got {other:?}"), + Err(err) => panic!("expected cancel callback event, got {err}"), + } + } + + #[test] + fn move_down_without_selection_change_does_not_fire_callback() { + let (tx_raw, mut rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut view = ListSelectionView::new( + SelectionViewParams { + items: vec![SelectionItem { + name: "Only choice".to_string(), + dismiss_on_select: true, + ..Default::default() + }], + on_selection_changed: Some(Box::new(|_idx, tx: &_| { + tx.send(AppEvent::OpenApprovalsPopup); + })), + ..Default::default() + }, + tx, + ); + + while rx.try_recv().is_ok() {} + + view.handle_key_event(KeyEvent::from(KeyCode::Down)); + + assert!( + rx.try_recv().is_err(), + "moving down in a single-item list should not fire on_selection_changed", + ); + } + #[test] fn wraps_long_option_without_overflowing_columns() { let (tx_raw, _rx) = unbounded_channel::(); @@ -1159,4 +1550,194 @@ mod tests { "fixed description column changed across scroll:\nbefore:\n{before_scroll}\nafter:\n{after_scroll}" ); } + + #[test] + fn side_layout_width_half_uses_exact_split() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let view = ListSelectionView::new( + SelectionViewParams { + items: vec![SelectionItem { + name: "Item 1".to_string(), + dismiss_on_select: true, + ..Default::default() + }], + side_content: Box::new(MarkerRenderable { + marker: "W", + height: 1, + }), + side_content_width: SideContentWidth::Half, + side_content_min_width: 10, + ..Default::default() + }, + tx, + ); + + let content_width: u16 = 120; + let expected = content_width.saturating_sub(SIDE_CONTENT_GAP) / 2; + assert_eq!(view.side_layout_width(content_width), Some(expected)); + } + + #[test] + fn side_layout_width_half_falls_back_when_list_would_be_too_narrow() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let view = ListSelectionView::new( + SelectionViewParams { + items: vec![SelectionItem { + name: "Item 1".to_string(), + dismiss_on_select: true, + ..Default::default() + }], + side_content: Box::new(MarkerRenderable { + marker: "W", + height: 1, + }), + side_content_width: SideContentWidth::Half, + side_content_min_width: 50, + ..Default::default() + }, + tx, + ); + + assert_eq!(view.side_layout_width(80), None); + } + + #[test] + fn stacked_side_content_is_used_when_side_by_side_does_not_fit() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let view = ListSelectionView::new( + SelectionViewParams { + title: Some("Debug".to_string()), + items: vec![SelectionItem { + name: "Item 1".to_string(), + dismiss_on_select: true, + ..Default::default() + }], + side_content: Box::new(MarkerRenderable { + marker: "W", + height: 1, + }), + stacked_side_content: Some(Box::new(MarkerRenderable { + marker: "N", + height: 1, + })), + side_content_width: SideContentWidth::Half, + side_content_min_width: 60, + ..Default::default() + }, + tx, + ); + + let rendered = render_lines_with_width(&view, 70); + assert!( + rendered.contains('N'), + "expected stacked marker to be rendered:\n{rendered}" + ); + assert!( + !rendered.contains('W'), + "wide marker should not render in stacked mode:\n{rendered}" + ); + } + + #[test] + fn side_content_clearing_resets_symbols_and_style() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let view = ListSelectionView::new( + SelectionViewParams { + title: Some("Debug".to_string()), + items: vec![SelectionItem { + name: "Item 1".to_string(), + dismiss_on_select: true, + ..Default::default() + }], + side_content: Box::new(MarkerRenderable { + marker: "W", + height: 1, + }), + side_content_width: SideContentWidth::Half, + side_content_min_width: 10, + ..Default::default() + }, + tx, + ); + + let width = 120; + let height = view.desired_height(width); + let area = Rect::new(0, 0, width, height); + let mut buf = Buffer::empty(area); + for y in 0..height { + for x in 0..width { + buf[(x, y)] + .set_symbol("X") + .set_style(Style::default().bg(Color::Red)); + } + } + view.render(area, &mut buf); + + let cell = &buf[(width - 1, 0)]; + assert_eq!(cell.symbol(), " "); + let style = cell.style(); + assert_eq!(style.fg, Some(Color::Reset)); + assert_eq!(style.bg, Some(Color::Reset)); + assert_eq!(style.underline_color, Some(Color::Reset)); + + let mut saw_marker = false; + for y in 0..height { + for x in 0..width { + let cell = &buf[(x, y)]; + if cell.symbol() == "W" { + saw_marker = true; + assert_eq!(cell.style().bg, Some(Color::Reset)); + } + } + } + assert!( + saw_marker, + "expected side marker renderable to draw into buffer" + ); + } + + #[test] + fn side_content_clearing_handles_non_zero_buffer_origin() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let view = ListSelectionView::new( + SelectionViewParams { + title: Some("Debug".to_string()), + items: vec![SelectionItem { + name: "Item 1".to_string(), + dismiss_on_select: true, + ..Default::default() + }], + side_content: Box::new(MarkerRenderable { + marker: "W", + height: 1, + }), + side_content_width: SideContentWidth::Half, + side_content_min_width: 10, + ..Default::default() + }, + tx, + ); + + let width = 120; + let height = view.desired_height(width); + let area = Rect::new(0, 20, width, height); + let mut buf = Buffer::empty(area); + for y in area.y..area.y + height { + for x in area.x..area.x + width { + buf[(x, y)] + .set_symbol("X") + .set_style(Style::default().bg(Color::Red)); + } + } + view.render(area, &mut buf); + + let cell = &buf[(area.x + width - 1, area.y)]; + assert_eq!(cell.symbol(), " "); + assert_eq!(cell.style().bg, Some(Color::Reset)); + } } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 234bb8b728..9c7b940f0e 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -78,6 +78,9 @@ mod slash_commands; pub(crate) use footer::CollaborationModeIndicator; pub(crate) use list_selection_view::ColumnWidthMode; pub(crate) use list_selection_view::SelectionViewParams; +pub(crate) use list_selection_view::SideContentWidth; +pub(crate) use list_selection_view::popup_content_width; +pub(crate) use list_selection_view::side_by_side_layout_widths; mod feedback_view; pub(crate) use feedback_view::FeedbackAudience; pub(crate) use feedback_view::feedback_disabled_params; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 9bfddd18e4..ba7013c3c1 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -3482,6 +3482,9 @@ impl ChatWidget { SlashCommand::Statusline => { self.open_status_line_setup(); } + SlashCommand::Theme => { + self.open_theme_picker(); + } SlashCommand::Ps => { self.add_ps_output(); } @@ -4431,6 +4434,20 @@ impl ChatWidget { self.bottom_pane.show_view(Box::new(view)); } + fn open_theme_picker(&mut self) { + let codex_home = codex_core::config::find_codex_home().ok(); + let terminal_width = self + .last_rendered_width + .get() + .and_then(|width| u16::try_from(width).ok()); + let params = crate::theme_picker::build_theme_picker_params( + self.config.tui_theme.as_deref(), + codex_home.as_deref(), + terminal_width, + ); + self.bottom_pane.show_selection_view(params); + } + /// Parses configured status-line ids into known items and collects unknown ids. /// /// Unknown ids are deduplicated in insertion order for warning messages. @@ -6338,6 +6355,11 @@ impl ChatWidget { self.config.personality = Some(personality); } + /// Set the syntax theme override in the widget's config copy. + pub(crate) fn set_tui_theme(&mut self, theme: Option) { + self.config.tui_theme = theme; + } + /// Set the model in the widget's config copy and stored collaboration mode. pub(crate) fn set_model(&mut self, model: &str) { self.current_collaboration_mode = diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap index 1c6a3ef136..055a6292f1 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap @@ -27,6 +27,9 @@ Buffer { x: 73, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, x: 2, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: ITALIC, x: 7, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 4, y: 7, fg: Rgb(137, 180, 250), bg: Reset, underline: Reset, modifier: NONE, + x: 8, y: 7, fg: Rgb(205, 214, 244), bg: Reset, underline: Reset, modifier: NONE, + x: 20, y: 7, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, x: 0, y: 9, fg: Cyan, bg: Reset, underline: Reset, modifier: BOLD, x: 21, y: 9, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, x: 48, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index 6fdf3a43f5..aa0481d044 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -1,3 +1,23 @@ +//! Renders unified diffs with line numbers, gutter signs, and optional syntax +//! highlighting. +//! +//! Each `FileChange` variant (Add / Delete / Update) is rendered as a block of +//! diff lines, each prefixed by a right-aligned line number, a gutter sign +//! (`+` / `-` / ` `), and the content text. When a recognized file extension +//! is present, the content text is syntax-highlighted using +//! [`crate::render::highlight`]. +//! +//! **Highlighting strategy for `Update` diffs:** the renderer highlights each +//! hunk as a single concatenated block rather than line-by-line. This +//! preserves syntect's parser state across consecutive lines within a hunk +//! (important for multi-line strings, block comments, etc.). Cross-hunk state +//! is intentionally *not* preserved because hunks are visually separated and +//! re-synchronize at context boundaries anyway. +//! +//! **Wrapping:** long lines are hard-wrapped at the available column width. +//! Syntax-highlighted spans are split at character boundaries with styles +//! preserved across the split so that no color information is lost. + use diffy::Hunk; use ratatui::buffer::Buffer; use ratatui::layout::Rect; @@ -12,8 +32,15 @@ use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; +use unicode_width::UnicodeWidthChar; + +/// Display width of a tab character in columns. +const TAB_WIDTH: usize = 4; + use crate::exec_command::relativize_to_home; use crate::render::Insets; +use crate::render::highlight::exceeds_highlight_limits; +use crate::render::highlight::highlight_code_to_styled_spans; use crate::render::line_utils::prefix_lines; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::InsetRenderable; @@ -21,8 +48,13 @@ use crate::render::renderable::Renderable; use codex_core::git_info::get_git_repo_root; use codex_protocol::protocol::FileChange; -// Internal representation for diff line rendering -enum DiffLineType { +/// Classifies a diff line for gutter sign rendering and style selection. +/// +/// `Insert` renders with a `+` sign and green text, `Delete` with `-` and red +/// text (plus dim overlay when syntax-highlighted), and `Context` with a space +/// and default styling. +#[derive(Clone, Copy)] +pub(crate) enum DiffLineType { Insert, Delete, Context, @@ -42,13 +74,13 @@ impl DiffSummary { impl Renderable for FileChange { fn render(&self, area: Rect, buf: &mut Buffer) { let mut lines = vec![]; - render_change(self, &mut lines, area.width as usize); + render_change(self, &mut lines, area.width as usize, None); Paragraph::new(lines).render(area, buf); } fn desired_height(&self, width: u16) -> u16 { let mut lines = vec![]; - render_change(self, &mut lines, width as usize); + render_change(self, &mut lines, width as usize, None); lines.len() as u16 } } @@ -185,47 +217,100 @@ fn render_changes_block(rows: Vec, wrap_cols: usize, cwd: &Path) -> Vec>, width: usize) { +/// Detect the programming language for a file path by its extension. +/// Returns the raw extension string for `normalize_lang` / `find_syntax` +/// to resolve downstream. +fn detect_lang_for_path(path: &Path) -> Option { + let ext = path.extension()?.to_str()?; + Some(ext.to_string()) +} + +fn render_change( + change: &FileChange, + out: &mut Vec>, + width: usize, + lang: Option<&str>, +) { match change { FileChange::Add { content } => { + // Pre-highlight the entire file content as a whole. + let syntax_lines = lang.and_then(|l| highlight_code_to_styled_spans(content, l)); let line_number_width = line_number_width(content.lines().count()); for (i, raw) in content.lines().enumerate() { - out.extend(push_wrapped_diff_line( - i + 1, - DiffLineType::Insert, - raw, - width, - line_number_width, - )); + let syn = syntax_lines.as_ref().and_then(|sl| sl.get(i)); + if let Some(spans) = syn { + out.extend(push_wrapped_diff_line_with_syntax( + i + 1, + DiffLineType::Insert, + raw, + width, + line_number_width, + spans, + )); + } else { + out.extend(push_wrapped_diff_line( + i + 1, + DiffLineType::Insert, + raw, + width, + line_number_width, + )); + } } } FileChange::Delete { content } => { + let syntax_lines = lang.and_then(|l| highlight_code_to_styled_spans(content, l)); let line_number_width = line_number_width(content.lines().count()); for (i, raw) in content.lines().enumerate() { - out.extend(push_wrapped_diff_line( - i + 1, - DiffLineType::Delete, - raw, - width, - line_number_width, - )); + let syn = syntax_lines.as_ref().and_then(|sl| sl.get(i)); + if let Some(spans) = syn { + out.extend(push_wrapped_diff_line_with_syntax( + i + 1, + DiffLineType::Delete, + raw, + width, + line_number_width, + spans, + )); + } else { + out.extend(push_wrapped_diff_line( + i + 1, + DiffLineType::Delete, + raw, + width, + line_number_width, + )); + } } } FileChange::Update { unified_diff, .. } => { if let Ok(patch) = diffy::Patch::from_str(unified_diff) { let mut max_line_number = 0; + let mut total_diff_bytes: usize = 0; + let mut total_diff_lines: usize = 0; for h in patch.hunks() { let mut old_ln = h.old_range().start(); let mut new_ln = h.new_range().start(); for l in h.lines() { + let text = match l { + diffy::Line::Insert(t) + | diffy::Line::Delete(t) + | diffy::Line::Context(t) => t, + }; + total_diff_bytes += text.len(); + total_diff_lines += 1; match l { diffy::Line::Insert(_) => { max_line_number = max_line_number.max(new_ln); @@ -243,6 +328,16 @@ fn render_change(change: &FileChange, out: &mut Vec>, width: usi } } } + + // Skip per-line syntax highlighting when the patch is too + // large — avoids thousands of parser initializations that + // would stall rendering on big diffs. + let diff_lang = if exceeds_highlight_limits(total_diff_bytes, total_diff_lines) { + None + } else { + lang + }; + let line_number_width = line_number_width(max_line_number); let mut is_first_hunk = true; for h in patch.hunks() { @@ -253,41 +348,93 @@ fn render_change(change: &FileChange, out: &mut Vec>, width: usi } is_first_hunk = false; + // Highlight each hunk as a single block so syntect parser + // state is preserved across consecutive lines. + let hunk_syntax_lines = diff_lang.and_then(|language| { + let hunk_text: String = h + .lines() + .iter() + .map(|line| match line { + diffy::Line::Insert(text) + | diffy::Line::Delete(text) + | diffy::Line::Context(text) => *text, + }) + .collect(); + let syntax_lines = highlight_code_to_styled_spans(&hunk_text, language)?; + (syntax_lines.len() == h.lines().len()).then_some(syntax_lines) + }); + let mut old_ln = h.old_range().start(); let mut new_ln = h.new_range().start(); - for l in h.lines() { + for (line_idx, l) in h.lines().iter().enumerate() { + let syntax_spans = hunk_syntax_lines + .as_ref() + .and_then(|syntax_lines| syntax_lines.get(line_idx)); match l { diffy::Line::Insert(text) => { let s = text.trim_end_matches('\n'); - out.extend(push_wrapped_diff_line( - new_ln, - DiffLineType::Insert, - s, - width, - line_number_width, - )); + if let Some(syn) = syntax_spans { + out.extend(push_wrapped_diff_line_with_syntax( + new_ln, + DiffLineType::Insert, + s, + width, + line_number_width, + syn, + )); + } else { + out.extend(push_wrapped_diff_line( + new_ln, + DiffLineType::Insert, + s, + width, + line_number_width, + )); + } new_ln += 1; } diffy::Line::Delete(text) => { let s = text.trim_end_matches('\n'); - out.extend(push_wrapped_diff_line( - old_ln, - DiffLineType::Delete, - s, - width, - line_number_width, - )); + if let Some(syn) = syntax_spans { + out.extend(push_wrapped_diff_line_with_syntax( + old_ln, + DiffLineType::Delete, + s, + width, + line_number_width, + syn, + )); + } else { + out.extend(push_wrapped_diff_line( + old_ln, + DiffLineType::Delete, + s, + width, + line_number_width, + )); + } old_ln += 1; } diffy::Line::Context(text) => { let s = text.trim_end_matches('\n'); - out.extend(push_wrapped_diff_line( - new_ln, - DiffLineType::Context, - s, - width, - line_number_width, - )); + if let Some(syn) = syntax_spans { + out.extend(push_wrapped_diff_line_with_syntax( + new_ln, + DiffLineType::Context, + s, + width, + line_number_width, + syn, + )); + } else { + out.extend(push_wrapped_diff_line( + new_ln, + DiffLineType::Context, + s, + width, + line_number_width, + )); + } old_ln += 1; new_ln += 1; } @@ -342,68 +489,213 @@ pub(crate) fn calculate_add_remove_from_diff(diff: &str) -> (usize, usize) { } } -fn push_wrapped_diff_line( +/// Render a single diff line (no syntax highlighting) as one or more wrapped +/// ratatui `Line`s. The first output line carries the gutter sign; continuation +/// lines are indented under the line number column. +pub(crate) fn push_wrapped_diff_line( line_number: usize, kind: DiffLineType, text: &str, width: usize, line_number_width: usize, +) -> Vec> { + push_wrapped_diff_line_inner(line_number, kind, text, width, line_number_width, None) +} + +/// Render a single diff line with pre-computed syntax spans. The sign character +/// uses the diff color; content gets syntax colors with a dim overlay for delete +/// lines. +pub(crate) fn push_wrapped_diff_line_with_syntax( + line_number: usize, + kind: DiffLineType, + text: &str, + width: usize, + line_number_width: usize, + syntax_spans: &[RtSpan<'static>], +) -> Vec> { + push_wrapped_diff_line_inner( + line_number, + kind, + text, + width, + line_number_width, + Some(syntax_spans), + ) +} + +fn push_wrapped_diff_line_inner( + line_number: usize, + kind: DiffLineType, + text: &str, + width: usize, + line_number_width: usize, + syntax_spans: Option<&[RtSpan<'static>]>, ) -> Vec> { let ln_str = line_number.to_string(); - let mut remaining_text: &str = text; // Reserve a fixed number of spaces (equal to the widest line number plus a // trailing spacer) so the sign column stays aligned across the diff block. let gutter_width = line_number_width.max(1); let prefix_cols = gutter_width + 1; - let mut first = true; let (sign_char, line_style) = match kind { DiffLineType::Insert => ('+', style_add()), DiffLineType::Delete => ('-', style_del()), DiffLineType::Context => (' ', style_context()), }; - let mut lines: Vec> = Vec::new(); - loop { - // Fit the content for the current terminal row: - // compute how many columns are available after the prefix, then split - // at a UTF-8 character boundary so this row's chunk fits exactly. + // When we have syntax spans, compose them with the diff style for a richer + // view. The sign character keeps the diff color; content gets syntax colors + // with an overlay modifier for delete lines (dim). + if let Some(syn_spans) = syntax_spans { + let gutter = format!("{ln_str:>gutter_width$} "); + let sign = format!("{sign_char}"); + let dim_overlay = matches!(kind, DiffLineType::Delete); + + // Apply dim overlay to syntax spans if this is a delete line. + let styled: Vec> = syn_spans + .iter() + .map(|sp| { + let mut style = sp.style; + if dim_overlay { + style.add_modifier |= Modifier::DIM; + } + RtSpan::styled(sp.content.clone().into_owned(), style) + }) + .collect(); + + // Determine how many display columns remain for content after the + // gutter and sign character. let available_content_cols = width.saturating_sub(prefix_cols + 1).max(1); - let split_at_byte_index = remaining_text - .char_indices() - .nth(available_content_cols) - .map(|(i, _)| i) - .unwrap_or_else(|| remaining_text.len()); - let (chunk, rest) = remaining_text.split_at(split_at_byte_index); - remaining_text = rest; - if first { - // Build gutter (right-aligned line number plus spacer) as a dimmed span - let gutter = format!("{ln_str:>gutter_width$} "); - // Content with a sign ('+'/'-'/' ') styled per diff kind - let content = format!("{sign_char}{chunk}"); - lines.push(RtLine::from(vec![ - RtSpan::styled(gutter, style_gutter()), - RtSpan::styled(content, line_style), - ])); - first = false; - } else { - // Continuation lines keep a space for the sign column so content aligns - let gutter = format!("{:gutter_width$} ", ""); - lines.push(RtLine::from(vec![ - RtSpan::styled(gutter, style_gutter()), - RtSpan::styled(chunk.to_string(), line_style), - ])); - } - if remaining_text.is_empty() { - break; + // Wrap the styled content spans to fit within the available columns. + let wrapped_chunks = wrap_styled_spans(&styled, available_content_cols); + + let mut lines: Vec> = Vec::new(); + for (i, chunk) in wrapped_chunks.into_iter().enumerate() { + let mut row_spans: Vec> = Vec::new(); + if i == 0 { + // First line: gutter + sign + content + row_spans.push(RtSpan::styled(gutter.clone(), style_gutter())); + row_spans.push(RtSpan::styled(sign.clone(), line_style)); + } else { + // Continuation: empty gutter + two-space indent (matches + // the plain-text wrapping continuation style). + let cont_gutter = format!("{:gutter_width$} ", ""); + row_spans.push(RtSpan::styled(cont_gutter, style_gutter())); + } + row_spans.extend(chunk); + lines.push(RtLine::from(row_spans)); } + return lines; } + + let available_content_cols = width.saturating_sub(prefix_cols + 1).max(1); + let styled = vec![RtSpan::styled(text.to_string(), line_style)]; + let wrapped_chunks = wrap_styled_spans(&styled, available_content_cols); + + let mut lines: Vec> = Vec::new(); + for (i, chunk) in wrapped_chunks.into_iter().enumerate() { + let mut row_spans: Vec> = Vec::new(); + if i == 0 { + let gutter = format!("{ln_str:>gutter_width$} "); + let sign = format!("{sign_char}"); + row_spans.push(RtSpan::styled(gutter, style_gutter())); + row_spans.push(RtSpan::styled(sign, line_style)); + } else { + let cont_gutter = format!("{:gutter_width$} ", ""); + row_spans.push(RtSpan::styled(cont_gutter, style_gutter())); + } + row_spans.extend(chunk); + lines.push(RtLine::from(row_spans)); + } + lines } -fn line_number_width(max_line_number: usize) -> usize { +/// Split styled spans into chunks that fit within `max_cols` display columns. +/// +/// Returns one `Vec` per output line. Styles are preserved across +/// split boundaries so that wrapping never loses syntax coloring. +/// +/// The algorithm walks characters using their Unicode display width (with tabs +/// expanded to [`TAB_WIDTH`] columns). When a character would overflow the +/// current line, the accumulated text is flushed and a new line begins. A +/// single character wider than the remaining space forces a line break *before* +/// the character so that progress is always made (avoiding infinite loops on +/// CJK characters or tabs at the end of a line). +fn wrap_styled_spans(spans: &[RtSpan<'static>], max_cols: usize) -> Vec>> { + let mut result: Vec>> = Vec::new(); + let mut current_line: Vec> = Vec::new(); + let mut col: usize = 0; + + for span in spans { + let style = span.style; + let text = span.content.as_ref(); + let mut remaining = text; + + while !remaining.is_empty() { + // Accumulate characters until we fill the line. + let mut byte_end = 0; + let mut chars_col = 0; + + for ch in remaining.chars() { + // Tabs have no Unicode width; treat them as TAB_WIDTH columns. + let w = ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 0 }); + if col + chars_col + w > max_cols { + // Adding this character would exceed the line width. + // Break here; if this is the first character in `remaining` + // we will flush/start a new line in the `byte_end == 0` + // branch below before consuming it. + break; + } + byte_end += ch.len_utf8(); + chars_col += w; + } + + if byte_end == 0 { + // Single character wider than remaining space — force onto a + // new line so we make progress. + if !current_line.is_empty() { + result.push(std::mem::take(&mut current_line)); + } + // Take at least one character to avoid an infinite loop. + let Some(ch) = remaining.chars().next() else { + break; + }; + let ch_len = ch.len_utf8(); + current_line.push(RtSpan::styled(remaining[..ch_len].to_string(), style)); + // Use fallback width 1 (not 0) so this branch always advances + // even if `ch` has unknown/zero display width. + col = ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 1 }); + remaining = &remaining[ch_len..]; + continue; + } + + let (chunk, rest) = remaining.split_at(byte_end); + current_line.push(RtSpan::styled(chunk.to_string(), style)); + col += chars_col; + remaining = rest; + + // If we exactly filled or exceeded the line, start a new one. + // Do not gate on !remaining.is_empty() — the next span in the + // outer loop may still have content that must start on a fresh line. + if col >= max_cols { + result.push(std::mem::take(&mut current_line)); + col = 0; + } + } + } + + // Push the last line (always at least one, even if empty). + if !current_line.is_empty() || result.is_empty() { + result.push(current_line); + } + + result +} + +pub(crate) fn line_number_width(max_line_number: usize) -> usize { if max_line_number == 0 { 1 } else { @@ -454,6 +746,19 @@ mod tests { assert_snapshot!(name, terminal.backend()); } + fn display_width(text: &str) -> usize { + text.chars() + .map(|ch| ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 0 })) + .sum() + } + + fn line_display_width(line: &RtLine<'static>) -> usize { + line.spans + .iter() + .map(|span| display_width(span.content.as_ref())) + .sum() + } + fn snapshot_lines_text(name: &str, lines: &[RtLine<'static>]) { // Convert Lines to plain text rows and trim trailing spaces so it's // easier to validate indentation visually in snapshots. @@ -471,6 +776,71 @@ mod tests { assert_snapshot!(name, text); } + fn diff_gallery_changes() -> HashMap { + let mut changes: HashMap = HashMap::new(); + + let rust_original = + "fn greet(name: &str) {\n println!(\"hello\");\n println!(\"bye\");\n}\n"; + let rust_modified = "fn greet(name: &str) {\n println!(\"hello {name}\");\n println!(\"emoji: 🚀✨ and CJK: 你好世界\");\n}\n"; + let rust_patch = diffy::create_patch(rust_original, rust_modified).to_string(); + changes.insert( + PathBuf::from("src/lib.rs"), + FileChange::Update { + unified_diff: rust_patch, + move_path: None, + }, + ); + + let py_original = "def add(a, b):\n\treturn a + b\n\nprint(add(1, 2))\n"; + let py_modified = "def add(a, b):\n\treturn a + b + 42\n\nprint(add(1, 2))\n"; + let py_patch = diffy::create_patch(py_original, py_modified).to_string(); + changes.insert( + PathBuf::from("scripts/calc.txt"), + FileChange::Update { + unified_diff: py_patch, + move_path: Some(PathBuf::from("scripts/calc.py")), + }, + ); + + changes.insert( + PathBuf::from("assets/banner.txt"), + FileChange::Add { + content: "HEADER\tVALUE\nrocket\t🚀\ncity\t東京\n".to_string(), + }, + ); + changes.insert( + PathBuf::from("examples/new_sample.rs"), + FileChange::Add { + content: "pub fn greet(name: &str) {\n println!(\"Hello, {name}!\");\n}\n" + .to_string(), + }, + ); + + changes.insert( + PathBuf::from("tmp/obsolete.log"), + FileChange::Delete { + content: "old line 1\nold line 2\nold line 3\n".to_string(), + }, + ); + changes.insert( + PathBuf::from("legacy/old_script.py"), + FileChange::Delete { + content: "def legacy(x):\n return x + 1\nprint(legacy(3))\n".to_string(), + }, + ); + + changes + } + + fn snapshot_diff_gallery(name: &str, width: u16, height: u16) { + let lines = create_diff_summary( + &diff_gallery_changes(), + &PathBuf::from("/"), + usize::from(width), + ); + snapshot_lines(name, lines, width, height); + } + #[test] fn display_path_prefers_cwd_without_git_repo() { let cwd = if cfg!(windows) { @@ -694,4 +1064,367 @@ mod tests { snapshot_lines("apply_update_block_relativizes_path", lines, 80, 10); } + + #[test] + fn ui_snapshot_syntax_highlighted_insert_wraps() { + // A long Rust line that exceeds 80 cols with syntax highlighting should + // wrap to multiple output lines rather than being clipped. + let long_rust = "fn very_long_function_name(arg_one: String, arg_two: String, arg_three: String, arg_four: String) -> Result> { Ok(arg_one) }"; + + let syntax_spans = + highlight_code_to_styled_spans(long_rust, "rust").expect("rust highlighting"); + let spans = &syntax_spans[0]; + + let lines = push_wrapped_diff_line_with_syntax( + 1, + DiffLineType::Insert, + long_rust, + 80, + line_number_width(1), + spans, + ); + + assert!( + lines.len() > 1, + "syntax-highlighted long line should wrap to multiple lines, got {}", + lines.len() + ); + + snapshot_lines("syntax_highlighted_insert_wraps", lines, 90, 10); + } + + #[test] + fn ui_snapshot_syntax_highlighted_insert_wraps_text() { + let long_rust = "fn very_long_function_name(arg_one: String, arg_two: String, arg_three: String, arg_four: String) -> Result> { Ok(arg_one) }"; + + let syntax_spans = + highlight_code_to_styled_spans(long_rust, "rust").expect("rust highlighting"); + let spans = &syntax_spans[0]; + + let lines = push_wrapped_diff_line_with_syntax( + 1, + DiffLineType::Insert, + long_rust, + 80, + line_number_width(1), + spans, + ); + + snapshot_lines_text("syntax_highlighted_insert_wraps_text", &lines); + } + + #[test] + fn ui_snapshot_diff_gallery_80x24() { + snapshot_diff_gallery("diff_gallery_80x24", 80, 24); + } + + #[test] + fn ui_snapshot_diff_gallery_94x35() { + snapshot_diff_gallery("diff_gallery_94x35", 94, 35); + } + + #[test] + fn ui_snapshot_diff_gallery_120x40() { + snapshot_diff_gallery("diff_gallery_120x40", 120, 40); + } + + #[test] + fn add_diff_uses_path_extension_for_highlighting() { + let mut changes: HashMap = HashMap::new(); + changes.insert( + PathBuf::from("highlight_add.rs"), + FileChange::Add { + content: "pub fn sum(a: i32, b: i32) -> i32 { a + b }\n".to_string(), + }, + ); + + let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80); + let has_rgb = lines.iter().any(|line| { + line.spans + .iter() + .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..)))) + }); + assert!( + has_rgb, + "add diff for .rs file should produce syntax-highlighted (RGB) spans" + ); + } + + #[test] + fn delete_diff_uses_path_extension_for_highlighting() { + let mut changes: HashMap = HashMap::new(); + changes.insert( + PathBuf::from("highlight_delete.py"), + FileChange::Delete { + content: "def scale(x):\n return x * 2\n".to_string(), + }, + ); + + let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80); + let has_rgb = lines.iter().any(|line| { + line.spans + .iter() + .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..)))) + }); + assert!( + has_rgb, + "delete diff for .py file should produce syntax-highlighted (RGB) spans" + ); + } + + #[test] + fn detect_lang_for_common_paths() { + // Standard extensions are detected. + assert!(detect_lang_for_path(Path::new("foo.rs")).is_some()); + assert!(detect_lang_for_path(Path::new("bar.py")).is_some()); + assert!(detect_lang_for_path(Path::new("app.tsx")).is_some()); + + // Extensionless files return None. + assert!(detect_lang_for_path(Path::new("Makefile")).is_none()); + assert!(detect_lang_for_path(Path::new("randomfile")).is_none()); + } + + #[test] + fn wrap_styled_spans_single_line() { + // Content that fits in one line should produce exactly one chunk. + let spans = vec![RtSpan::raw("short")]; + let result = wrap_styled_spans(&spans, 80); + assert_eq!(result.len(), 1); + } + + #[test] + fn wrap_styled_spans_splits_long_content() { + // Content wider than max_cols should produce multiple chunks. + let long_text = "a".repeat(100); + let spans = vec![RtSpan::raw(long_text)]; + let result = wrap_styled_spans(&spans, 40); + assert!( + result.len() >= 3, + "100 chars at 40 cols should produce at least 3 lines, got {}", + result.len() + ); + } + + #[test] + fn wrap_styled_spans_flushes_at_span_boundary() { + // When span A fills exactly to max_cols and span B follows, the line + // must be flushed before B starts. Otherwise B's first character lands + // on an already-full line, producing over-width output. + let style_a = Style::default().fg(Color::Red); + let style_b = Style::default().fg(Color::Blue); + let spans = vec![ + RtSpan::styled("aaaa", style_a), // 4 cols, fills line exactly at max_cols=4 + RtSpan::styled("bb", style_b), // should start on a new line + ]; + let result = wrap_styled_spans(&spans, 4); + assert_eq!( + result.len(), + 2, + "span ending exactly at max_cols should flush before next span: {result:?}" + ); + // First line should only contain the 'a' span. + let first_width: usize = result[0].iter().map(|s| s.content.chars().count()).sum(); + assert!( + first_width <= 4, + "first line should be at most 4 cols wide, got {first_width}" + ); + } + + #[test] + fn wrap_styled_spans_preserves_styles() { + // Verify that styles survive split boundaries. + let style = Style::default().fg(Color::Green); + let text = "x".repeat(50); + let spans = vec![RtSpan::styled(text, style)]; + let result = wrap_styled_spans(&spans, 20); + for chunk in &result { + for span in chunk { + assert_eq!(span.style, style, "style should be preserved across wraps"); + } + } + } + + #[test] + fn wrap_styled_spans_tabs_have_visible_width() { + // A tab should count as TAB_WIDTH columns, not zero. + // With max_cols=8, a tab (4 cols) + "abcde" (5 cols) = 9 cols → must wrap. + let spans = vec![RtSpan::raw("\tabcde")]; + let result = wrap_styled_spans(&spans, 8); + assert!( + result.len() >= 2, + "tab + 5 chars should exceed 8 cols and wrap, got {} line(s): {result:?}", + result.len() + ); + } + + #[test] + fn wrap_styled_spans_wraps_before_first_overflowing_char() { + let spans = vec![RtSpan::raw("abcd\t界")]; + let result = wrap_styled_spans(&spans, 5); + + let line_text: Vec = result + .iter() + .map(|line| { + line.iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect(); + assert_eq!(line_text, vec!["abcd", "\t", "界"]); + + let line_width = |line: &[RtSpan<'static>]| -> usize { + line.iter() + .flat_map(|span| span.content.chars()) + .map(|ch| ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 0 })) + .sum() + }; + for line in &result { + assert!( + line_width(line) <= 5, + "wrapped line exceeded width 5: {line:?}" + ); + } + } + + #[test] + fn fallback_wrapping_uses_display_width_for_tabs_and_wide_chars() { + let width = 8; + let lines = push_wrapped_diff_line( + 1, + DiffLineType::Insert, + "abcd\t界🙂", + width, + line_number_width(1), + ); + + assert!(lines.len() >= 2, "expected wrapped output, got {lines:?}"); + for line in &lines { + assert!( + line_display_width(line) <= width, + "fallback wrapped line exceeded width {width}: {line:?}" + ); + } + } + + #[test] + fn large_update_diff_skips_highlighting() { + // Build a patch large enough to exceed MAX_HIGHLIGHT_LINES (10_000). + // Without the pre-check this would attempt 10k+ parser initializations. + let line_count = 10_500; + let original: String = (0..line_count).map(|i| format!("line {i}\n")).collect(); + let modified: String = (0..line_count) + .map(|i| { + if i % 2 == 0 { + format!("line {i} changed\n") + } else { + format!("line {i}\n") + } + }) + .collect(); + let patch = diffy::create_patch(&original, &modified).to_string(); + + let mut changes: HashMap = HashMap::new(); + changes.insert( + PathBuf::from("huge.rs"), + FileChange::Update { + unified_diff: patch, + move_path: None, + }, + ); + + // Should complete quickly (no per-line parser init). If guardrails + // are bypassed this would be extremely slow. + let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80); + + // The diff rendered without timing out — the guardrails prevented + // thousands of per-line parser initializations. Verify we actually + // got output (the patch is non-empty). + assert!( + lines.len() > 100, + "expected many output lines from large diff, got {}", + lines.len(), + ); + + // No span should contain an RGB foreground color (syntax themes + // produce RGB; plain diff styles only use named Color variants). + for line in &lines { + for span in &line.spans { + if let Some(ratatui::style::Color::Rgb(..)) = span.style.fg { + panic!( + "large diff should not have syntax-highlighted spans, \ + got RGB color in style {:?} for {:?}", + span.style, span.content, + ); + } + } + } + } + + #[test] + fn rename_diff_uses_destination_extension_for_highlighting() { + // A rename from an unknown extension to .rs should highlight as Rust. + // Without the fix, detect_lang_for_path uses the source path (.xyzzy), + // which has no syntax definition, so highlighting is skipped. + let original = "fn main() {}\n"; + let modified = "fn main() { println!(\"hi\"); }\n"; + let patch = diffy::create_patch(original, modified).to_string(); + + let mut changes: HashMap = HashMap::new(); + changes.insert( + PathBuf::from("foo.xyzzy"), + FileChange::Update { + unified_diff: patch, + move_path: Some(PathBuf::from("foo.rs")), + }, + ); + + let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80); + let has_rgb = lines.iter().any(|line| { + line.spans + .iter() + .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..)))) + }); + assert!( + has_rgb, + "rename from .xyzzy to .rs should produce syntax-highlighted (RGB) spans" + ); + } + + #[test] + fn update_diff_preserves_multiline_highlight_state_within_hunk() { + let original = "fn demo() {\n let s = \"hello\";\n}\n"; + let modified = "fn demo() {\n let s = \"hello\nworld\";\n}\n"; + let patch = diffy::create_patch(original, modified).to_string(); + + let mut changes: HashMap = HashMap::new(); + changes.insert( + PathBuf::from("demo.rs"), + FileChange::Update { + unified_diff: patch, + move_path: None, + }, + ); + + let expected_multiline = + highlight_code_to_styled_spans(" let s = \"hello\nworld\";\n", "rust") + .expect("rust highlighting"); + let expected_style = expected_multiline + .get(1) + .and_then(|line| { + line.iter() + .find(|span| span.content.as_ref().contains("world")) + }) + .map(|span| span.style) + .expect("expected highlighted span for second multiline string line"); + + let lines = create_diff_summary(&changes, &PathBuf::from("/"), 120); + let actual_style = lines + .iter() + .flat_map(|line| line.spans.iter()) + .find(|span| span.content.as_ref().contains("world")) + .map(|span| span.style) + .expect("expected rendered diff span containing 'world'"); + + assert_eq!(actual_style, expected_style); + } } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index c44b5eb751..87d7089591 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -105,6 +105,7 @@ mod streaming; mod style; mod terminal_palette; mod text_formatting; +mod theme_picker; mod tooltips; mod tui; mod ui_consts; @@ -545,6 +546,7 @@ async fn run_ratatui_app( } else { initial_config }; + let mut missing_session_exit = |id_str: &str, action: &str| { error!("Error finding conversation path: {id_str}"); restore(); @@ -693,7 +695,7 @@ async fn run_ratatui_app( None => None, }; - let config = match &session_selection { + let mut config = match &session_selection { resume_picker::SessionSelection::Resume(_) | resume_picker::SessionSelection::Fork(_) => { load_config_or_exit_with_fallback_cwd( cli_kv_overrides.clone(), @@ -705,6 +707,17 @@ async fn run_ratatui_app( } _ => config, }; + + // Configure syntax highlighting theme from the final config — onboarding + // and resume/fork can both reload config with a different tui_theme, so + // this must happen after the last possible reload. + if let Some(w) = crate::render::highlight::set_theme_override( + config.tui_theme.clone(), + find_codex_home().ok(), + ) { + config.startup_warnings.push(w); + } + set_default_client_residency_requirement(config.enforce_residency.value()); let active_profile = config.active_profile.clone(); let should_show_trust_screen = should_show_trust_screen(&config); @@ -1186,6 +1199,50 @@ trust_level = "untrusted" Ok(()) } + /// Regression: theme must be configured from the *final* config. + /// + /// `run_ratatui_app` can reload config during onboarding and again + /// during session resume/fork. The syntax theme override (stored in + /// a `OnceLock`) must use the final config's `tui_theme`, not the + /// initial one — otherwise users resuming a thread in a project with + /// a different theme get the wrong highlighting. + /// + /// We verify the invariant indirectly: `validate_theme_name` (the + /// pure validation core of `set_theme_override`) must be called with + /// the *final* config's theme, and its warning must land in the + /// final config's `startup_warnings`. + #[tokio::test] + async fn theme_warning_uses_final_config() -> std::io::Result<()> { + use crate::render::highlight::validate_theme_name; + + let temp_dir = TempDir::new()?; + + // initial_config has a valid theme — no warning. + let initial_config = build_config(&temp_dir).await?; + assert!(initial_config.tui_theme.is_none()); + + // Simulate resume/fork reload: the final config has an invalid theme. + let mut config = build_config(&temp_dir).await?; + config.tui_theme = Some("bogus-theme".into()); + + // Theme override must use the final config (not initial_config). + // This mirrors the real call site in run_ratatui_app. + if let Some(w) = validate_theme_name(config.tui_theme.as_deref(), Some(temp_dir.path())) { + config.startup_warnings.push(w); + } + + assert_eq!( + config.startup_warnings.len(), + 1, + "warning from final config's invalid theme should be present" + ); + assert!( + config.startup_warnings[0].contains("bogus-theme"), + "warning should reference the final config's theme name" + ); + Ok(()) + } + #[tokio::test] async fn read_session_cwd_falls_back_to_session_meta() -> std::io::Result<()> { let temp_dir = TempDir::new()?; diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index 35b0e8f5fe..ba8b47d5ed 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -1,3 +1,4 @@ +use crate::render::highlight::highlight_code_to_lines; use crate::render::line_utils::line_to_static; use crate::wrapping::RtOptions; use crate::wrapping::adaptive_wrap_line; @@ -99,6 +100,8 @@ where pending_marker_line: bool, in_paragraph: bool, in_code_block: bool, + code_block_lang: Option, + code_block_buffer: String, wrap_width: Option, current_line_content: Option>, current_initial_indent: Vec>, @@ -124,6 +127,8 @@ where pending_marker_line: false, in_paragraph: false, in_code_block: false, + code_block_lang: None, + code_block_buffer: String::new(), wrap_width, current_line_content: None, current_initial_indent: Vec::new(), @@ -278,6 +283,16 @@ where self.push_line(Line::default()); } self.pending_marker_line = false; + + // When inside a fenced code block with a known language, accumulate + // text into the buffer for batch highlighting in end_codeblock(). + // Append verbatim — pulldown-cmark text events already contain the + // original line breaks, so inserting separators would double them. + if self.in_code_block && self.code_block_lang.is_some() { + self.code_block_buffer.push_str(&text); + return; + } + if self.in_code_block && !self.needs_newline { let has_content = self .current_line_content @@ -394,12 +409,25 @@ where self.needs_newline = false; } - fn start_codeblock(&mut self, _lang: Option, indent: Option>) { + fn start_codeblock(&mut self, lang: Option, indent: Option>) { self.flush_current_line(); if !self.text.lines.is_empty() { self.push_blank_line(); } self.in_code_block = true; + + // Extract the language token from the info string. CommonMark info + // strings can contain metadata after the language, separated by commas, + // spaces, or other delimiters (e.g. "rust,no_run", "rust title=demo"). + // Take only the first token so the syntax lookup succeeds. + let lang = lang + .as_deref() + .and_then(|s| s.split([',', ' ', '\t']).next()) + .filter(|s| !s.is_empty()) + .map(std::string::ToString::to_string); + self.code_block_lang = lang; + self.code_block_buffer.clear(); + self.indent_stack.push(IndentContext::new( vec![indent.unwrap_or_default()], None, @@ -409,6 +437,20 @@ where } fn end_codeblock(&mut self) { + // If we buffered code for a known language, syntax-highlight it now. + if let Some(lang) = self.code_block_lang.take() { + let code = std::mem::take(&mut self.code_block_buffer); + if !code.is_empty() { + let highlighted = highlight_code_to_lines(&code, &lang); + for hl_line in highlighted { + self.push_line(Line::default()); + for span in hl_line.spans { + self.push_span(span); + } + } + } + } + self.needs_newline = true; self.in_code_block = false; self.indent_stack.pop(); @@ -689,4 +731,39 @@ mod tests { "expected full URL-like token in one rendered line, got: {lines:?}" ); } + + #[test] + fn fenced_code_info_string_with_metadata_highlights() { + // CommonMark info strings like "rust,no_run" or "rust title=demo" + // contain metadata after the language token. The language must be + // extracted (first word / comma-separated token) so highlighting works. + for info in &["rust,no_run", "rust no_run", "rust title=\"demo\""] { + let markdown = format!("```{info}\nfn main() {{}}\n```\n"); + let rendered = render_markdown_text(&markdown); + let has_rgb = rendered.lines.iter().any(|line| { + line.spans + .iter() + .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..)))) + }); + assert!( + has_rgb, + "info string \"{info}\" should still produce syntax highlighting" + ); + } + } + + #[test] + fn crlf_code_block_no_extra_blank_lines() { + // pulldown-cmark can split CRLF code blocks into multiple Text events. + // The buffer must concatenate them verbatim — no inserted separators. + let markdown = "```rust\r\nfn main() {}\r\n line2\r\n```\r\n"; + let rendered = render_markdown_text(markdown); + let lines = lines_to_strings(&rendered); + // Should be exactly two code lines; no spurious blank line between them. + assert_eq!( + lines, + vec!["fn main() {}".to_string(), " line2".to_string()], + "CRLF code block should not produce extra blank lines: {lines:?}" + ); + } } diff --git a/codex-rs/tui/src/markdown_render_tests.rs b/codex-rs/tui/src/markdown_render_tests.rs index c549699695..68daaaab7f 100644 --- a/codex-rs/tui/src/markdown_render_tests.rs +++ b/codex-rs/tui/src/markdown_render_tests.rs @@ -652,10 +652,83 @@ fn link() { } #[test] -fn code_block_unhighlighted() { +fn code_block_known_lang_has_syntax_colors() { let text = render_markdown_text("```rust\nfn main() {}\n```\n"); - let expected = Text::from_iter([Line::from_iter(["", "fn main() {}"])]); - assert_eq!(text, expected); + let content: Vec = text + .lines + .iter() + .map(|l| { + l.spans + .iter() + .map(|s| s.content.clone()) + .collect::() + }) + .collect(); + // Content should be preserved; ignore trailing empty line from highlighting. + let content: Vec<&str> = content + .iter() + .map(std::string::String::as_str) + .filter(|s| !s.is_empty()) + .collect(); + assert_eq!(content, vec!["fn main() {}"]); + + // At least one span should have non-default style (syntax highlighting). + let has_colored_span = text + .lines + .iter() + .flat_map(|l| l.spans.iter()) + .any(|sp| sp.style.fg.is_some()); + assert!(has_colored_span, "expected syntax-highlighted spans with color"); +} + +#[test] +fn code_block_unknown_lang_plain() { + let text = render_markdown_text("```xyzlang\nhello world\n```\n"); + let content: Vec = text + .lines + .iter() + .map(|l| { + l.spans + .iter() + .map(|s| s.content.clone()) + .collect::() + }) + .collect(); + let content: Vec<&str> = content + .iter() + .map(std::string::String::as_str) + .filter(|s| !s.is_empty()) + .collect(); + assert_eq!(content, vec!["hello world"]); + + // No syntax coloring for unknown language — all spans have default style. + let has_colored_span = text + .lines + .iter() + .flat_map(|l| l.spans.iter()) + .any(|sp| sp.style.fg.is_some()); + assert!(!has_colored_span, "expected no syntax coloring for unknown lang"); +} + +#[test] +fn code_block_no_lang_plain() { + let text = render_markdown_text("```\nno lang specified\n```\n"); + let content: Vec = text + .lines + .iter() + .map(|l| { + l.spans + .iter() + .map(|s| s.content.clone()) + .collect::() + }) + .collect(); + let content: Vec<&str> = content + .iter() + .map(std::string::String::as_str) + .filter(|s| !s.is_empty()) + .collect(); + assert_eq!(content, vec!["no lang specified"]); } #[test] @@ -721,16 +794,25 @@ Here is a code block that shows another fenced block: .collect::() }) .collect(); + // Filter empty trailing lines for stability; the code block may or may + // not emit a trailing blank depending on the highlighting path. + let trimmed: Vec<&str> = { + let mut v: Vec<&str> = lines.iter().map(std::string::String::as_str).collect(); + while v.last() == Some(&"") { + v.pop(); + } + v + }; assert_eq!( - lines, + trimmed, vec![ - "Here is a code block that shows another fenced block:".to_string(), - String::new(), - "```md".to_string(), - "# Inside fence".to_string(), - "- bullet".to_string(), - "- `inline code`".to_string(), - "```".to_string(), + "Here is a code block that shows another fenced block:", + "", + "```md", + "# Inside fence", + "- bullet", + "- `inline code`", + "```", ] ); } @@ -993,3 +1075,36 @@ fn nested_item_continuation_paragraph_is_indented() { ]); assert_eq!(text, expected); } + +#[test] +fn code_block_preserves_trailing_blank_lines() { + // A fenced code block with an intentional trailing blank line must keep it. + let md = "```rust\nfn main() {}\n\n```\n"; + let text = render_markdown_text(md); + let content: Vec = text + .lines + .iter() + .map(|l| { + l.spans + .iter() + .map(|s| s.content.clone()) + .collect::() + }) + .collect(); + // Should have: "fn main() {}" then "" (the blank line). + // Filter only to content lines (skip leading/trailing empty from rendering). + assert!( + content.iter().any(|c| c == "fn main() {}"), + "expected code line, got {content:?}" + ); + // The trailing blank line inside the fence should be preserved. + let code_start = content.iter().position(|c| c == "fn main() {}").unwrap(); + assert!( + content.len() > code_start + 1, + "expected a line after 'fn main() {{}}' but content ends: {content:?}" + ); + assert_eq!( + content[code_start + 1], "", + "trailing blank line inside code fence was lost: {content:?}" + ); +} diff --git a/codex-rs/tui/src/render/highlight.rs b/codex-rs/tui/src/render/highlight.rs index e6d200cc3d..b0898ffe0a 100644 --- a/codex-rs/tui/src/render/highlight.rs +++ b/codex-rs/tui/src/render/highlight.rs @@ -1,154 +1,574 @@ +//! Syntax highlighting engine for the TUI. +//! +//! Wraps [syntect] with the [two_face] grammar and theme bundles to provide +//! ~250-language syntax highlighting and 32 bundled color themes. The module +//! owns four process-global singletons: +//! +//! | Singleton | Type | Purpose | +//! |---|---|---| +//! | `SYNTAX_SET` | `OnceLock` | Grammar database, immutable after init | +//! | `THEME` | `OnceLock>` | Active color theme, swappable at runtime | +//! | `THEME_OVERRIDE` | `OnceLock>` | Persisted user preference (write-once) | +//! | `CODEX_HOME` | `OnceLock>` | Root for custom `.tmTheme` discovery | +//! +//! **Lifecycle:** call [`set_theme_override`] once at startup (after the final +//! config is resolved) to persist the user preference and seed the `THEME` +//! lock. After that, [`set_syntax_theme`] and [`current_syntax_theme`] can +//! swap/snapshot the theme for live preview. All highlighting functions read +//! the theme via `theme_lock()`. +//! +//! **Guardrails:** inputs exceeding 512 KB or 10 000 lines are rejected early +//! (returns `None`) to prevent pathological CPU/memory usage. Callers must +//! fall back to plain unstyled text. + +use ratatui::style::Color as RtColor; +use ratatui::style::Modifier; use ratatui::style::Style; -use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::text::Span; +use std::path::Path; +use std::path::PathBuf; use std::sync::OnceLock; -use tree_sitter_highlight::Highlight; -use tree_sitter_highlight::HighlightConfiguration; -use tree_sitter_highlight::HighlightEvent; -use tree_sitter_highlight::Highlighter; +use std::sync::RwLock; +use syntect::easy::HighlightLines; +use syntect::highlighting::FontStyle; +use syntect::highlighting::Style as SyntectStyle; +use syntect::highlighting::Theme; +use syntect::highlighting::ThemeSet; +use syntect::parsing::SyntaxReference; +use syntect::parsing::SyntaxSet; +use syntect::util::LinesWithEndings; +use two_face::theme::EmbeddedThemeName; -// Ref: https://github.com/tree-sitter/tree-sitter-bash/blob/master/queries/highlights.scm -#[derive(Copy, Clone)] -enum BashHighlight { - Comment, - Constant, - Embedded, - Function, - Keyword, - Number, - Operator, - Property, - String, +// -- Global singletons ------------------------------------------------------- + +static SYNTAX_SET: OnceLock = OnceLock::new(); +static THEME: OnceLock> = OnceLock::new(); +static THEME_OVERRIDE: OnceLock> = OnceLock::new(); +static CODEX_HOME: OnceLock> = OnceLock::new(); + +fn syntax_set() -> &'static SyntaxSet { + SYNTAX_SET.get_or_init(two_face::syntax::extra_newlines) } -impl BashHighlight { - const ALL: [Self; 9] = [ - Self::Comment, - Self::Constant, - Self::Embedded, - Self::Function, - Self::Keyword, - Self::Number, - Self::Operator, - Self::Property, - Self::String, - ]; - - const fn as_str(self) -> &'static str { - match self { - Self::Comment => "comment", - Self::Constant => "constant", - Self::Embedded => "embedded", - Self::Function => "function", - Self::Keyword => "keyword", - Self::Number => "number", - Self::Operator => "operator", - Self::Property => "property", - Self::String => "string", +/// Set the user-configured syntax theme override and codex home path. +/// +/// Call this with the **final resolved config** (after onboarding, resume, and +/// fork reloads complete). The first call persists `name` and `codex_home` in +/// `OnceLock`s used by startup/default theme resolution. +/// +/// Subsequent calls cannot change the persisted `OnceLock` values, but they +/// still update the runtime theme immediately for live preview flows. +/// +/// Returns a warning message when the configured theme name cannot be +/// resolved to a bundled theme or a custom `.tmTheme` file on disk. +/// The caller should surface this via `Config::startup_warnings` so it +/// appears as a `⚠` banner in the TUI. +pub(crate) fn set_theme_override( + name: Option, + codex_home: Option, +) -> Option { + let mut warning = validate_theme_name(name.as_deref(), codex_home.as_deref()); + let override_set_ok = THEME_OVERRIDE.set(name.clone()).is_ok(); + let codex_home_set_ok = CODEX_HOME.set(codex_home.clone()).is_ok(); + if THEME.get().is_some() { + set_syntax_theme(resolve_theme_with_override( + name.as_deref(), + codex_home.as_deref(), + )); + } + if !override_set_ok || !codex_home_set_ok { + let duplicate_msg = "Ignoring duplicate or late syntax theme override persistence; runtime theme was updated from the latest override, but persisted override config can only be initialized once."; + tracing::warn!("{duplicate_msg}"); + if warning.is_none() { + warning = Some(duplicate_msg.to_string()); } } + warning +} - fn style(self) -> Style { - match self { - Self::Comment | Self::Operator | Self::String => Style::default().dim(), - _ => Style::default(), - } +/// Check whether a theme name resolves to a bundled theme or a custom +/// `.tmTheme` file. Returns a user-facing warning when it does not. +pub(crate) fn validate_theme_name(name: Option<&str>, codex_home: Option<&Path>) -> Option { + let name = name?; + let custom_theme_path_display = codex_home + .map(|home| custom_theme_path(name, home).display().to_string()) + .unwrap_or_else(|| format!("$CODEX_HOME/themes/{name}.tmTheme")); + // Bundled themes always resolve. + if parse_theme_name(name).is_some() { + return None; } -} - -static HIGHLIGHT_CONFIG: OnceLock = OnceLock::new(); - -fn highlight_names() -> &'static [&'static str] { - static NAMES: OnceLock<[&'static str; BashHighlight::ALL.len()]> = OnceLock::new(); - NAMES - .get_or_init(|| BashHighlight::ALL.map(BashHighlight::as_str)) - .as_slice() -} - -fn highlight_config() -> &'static HighlightConfiguration { - HIGHLIGHT_CONFIG.get_or_init(|| { - let language = tree_sitter_bash::LANGUAGE.into(); - #[expect(clippy::expect_used)] - let mut config = HighlightConfiguration::new( - language, - "bash", - tree_sitter_bash::HIGHLIGHT_QUERY, - "", - "", - ) - .expect("load bash highlight query"); - config.configure(highlight_names()); - config - }) -} - -fn highlight_for(highlight: Highlight) -> BashHighlight { - BashHighlight::ALL[highlight.0] -} - -fn push_segment(lines: &mut Vec>, segment: &str, style: Option", + "", + "
", + "

{}

{}

", + "
", + "{}
", + "
" + ), + html_escape(&title), + preview_css(), + html_escape(&self.name), + options.performance_mode, + html_escape(&title), + html_escape(&viewport.to_a1()), + viewport_style(options), + render_table(self, &viewport, options), + )) + } +} + +impl SpreadsheetArtifact { + pub fn render_workbook_previews( + &self, + cwd: &Path, + options: &SpreadsheetRenderOptions, + ) -> Result, SpreadsheetArtifactError> { + let sheets = if self.sheets.is_empty() { + vec![SpreadsheetSheet::new("Sheet1".to_string())] + } else { + self.sheets.clone() + }; + let output_paths = workbook_output_paths(self, cwd, options, &sheets); + sheets + .iter() + .zip(output_paths) + .map(|(sheet, path)| { + let html = sheet.render_html(None, options)?; + write_rendered_output(&path, &html)?; + Ok(SpreadsheetRenderedOutput { path, html }) + }) + .collect() + } + + pub fn render_sheet_preview( + &self, + cwd: &Path, + sheet: &SpreadsheetSheet, + options: &SpreadsheetRenderOptions, + ) -> Result { + let path = single_output_path( + cwd, + self, + options.output_path.as_deref(), + &format!("render_{}", sanitize_file_component(&sheet.name)), + ); + let html = sheet.render_html(None, options)?; + write_rendered_output(&path, &html)?; + Ok(SpreadsheetRenderedOutput { path, html }) + } + + pub fn render_range_preview( + &self, + cwd: &Path, + sheet: &SpreadsheetSheet, + range: &CellRange, + options: &SpreadsheetRenderOptions, + ) -> Result { + let path = single_output_path( + cwd, + self, + options.output_path.as_deref(), + &format!( + "render_{}_{}", + sanitize_file_component(&sheet.name), + sanitize_file_component(&range.to_a1()) + ), + ); + let html = sheet.render_html(Some(range), options)?; + write_rendered_output(&path, &html)?; + Ok(SpreadsheetRenderedOutput { path, html }) + } +} + +fn render_viewport( + sheet: &SpreadsheetSheet, + range: Option<&CellRange>, + center: Option, + options: &SpreadsheetRenderOptions, +) -> Result { + let base = range + .cloned() + .or_else(|| sheet.minimum_range()) + .unwrap_or_else(|| { + CellRange::from_start_end( + CellAddress { column: 1, row: 1 }, + CellAddress { column: 1, row: 1 }, + ) + }); + let Some(center) = center else { + return Ok(base); + }; + let visible_columns = options + .width + .map(|width| estimated_visible_count(width, 96.0, options.scale)) + .unwrap_or(base.width() as u32); + let visible_rows = options + .height + .map(|height| estimated_visible_count(height, 28.0, options.scale)) + .unwrap_or(base.height() as u32); + + let half_columns = visible_columns / 2; + let half_rows = visible_rows / 2; + let start_column = center + .column + .saturating_sub(half_columns) + .max(base.start.column); + let start_row = center.row.saturating_sub(half_rows).max(base.start.row); + let end_column = (start_column + visible_columns.saturating_sub(1)).min(base.end.column); + let end_row = (start_row + visible_rows.saturating_sub(1)).min(base.end.row); + Ok(CellRange::from_start_end( + CellAddress { + column: start_column, + row: start_row, + }, + CellAddress { + column: end_column.max(start_column), + row: end_row.max(start_row), + }, + )) +} + +fn estimated_visible_count(dimension: u32, cell_size: f64, scale: f64) -> u32 { + ((dimension as f64 / (cell_size * scale.max(0.1))).floor() as u32).max(1) +} + +fn render_table( + sheet: &SpreadsheetSheet, + range: &CellRange, + options: &SpreadsheetRenderOptions, +) -> String { + let mut rows = Vec::new(); + if options.include_headers { + let mut header = vec!["".to_string()]; + for column in range.start.column..=range.end.column { + header.push(format!( + "{}", + crate::column_index_to_letters(column) + )); + } + header.push("".to_string()); + rows.push(header.join("")); + } + for row in range.start.row..=range.end.row { + let mut cells = Vec::new(); + if options.include_headers { + cells.push(format!("{row}")); + } + for column in range.start.column..=range.end.column { + let address = CellAddress { column, row }; + let view = sheet.get_cell_view(address); + let value = view + .data + .as_ref() + .map(render_data_value) + .unwrap_or_default(); + cells.push(format!( + "{}", + address.to_a1(), + view.style_index, + html_escape(&value) + )); + } + rows.push(format!("{}", cells.join(""))); + } + rows.join("") +} + +fn render_data_value(value: &serde_json::Value) -> String { + match value { + serde_json::Value::String(value) => value.clone(), + serde_json::Value::Bool(value) => value.to_string(), + serde_json::Value::Number(value) => value.to_string(), + serde_json::Value::Null => String::new(), + other => other.to_string(), + } +} + +fn viewport_style(options: &SpreadsheetRenderOptions) -> String { + let mut style = vec![ + format!("--scale: {}", options.scale.max(0.1)), + format!( + "--headers: {}", + if options.include_headers { "1" } else { "0" } + ), + ]; + if let Some(width) = options.width { + style.push(format!("width: {width}px")); + } + if let Some(height) = options.height { + style.push(format!("height: {height}px")); + } + style.push("overflow: auto".to_string()); + style.join("; ") +} + +fn preview_css() -> &'static str { + concat!( + "body{margin:0;padding:24px;background:#f5f3ee;color:#1e1e1e;font-family:Georgia,serif;}", + ".spreadsheet-preview{display:flex;flex-direction:column;gap:16px;}", + "header h1{margin:0;font-size:24px;}header p{margin:0;color:#6b6257;font-size:13px;}", + ".viewport{border:1px solid #d6d0c7;background:#fff;box-shadow:0 12px 30px rgba(0,0,0,.08);}", + "table{border-collapse:collapse;transform:scale(var(--scale));transform-origin:top left;}", + "th,td{border:1px solid #ddd3c6;padding:6px 10px;min-width:72px;max-width:240px;font-size:13px;text-align:left;vertical-align:top;}", + "th{background:#f0ebe3;font-weight:600;position:sticky;top:0;z-index:1;}", + ".corner{background:#e7e0d6;left:0;z-index:2;}", + "td{white-space:pre-wrap;}" + ) +} + +fn write_rendered_output(path: &Path, html: &str) -> Result<(), SpreadsheetArtifactError> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + } + fs::write(path, html).map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + }) +} + +fn workbook_output_paths( + artifact: &SpreadsheetArtifact, + cwd: &Path, + options: &SpreadsheetRenderOptions, + sheets: &[SpreadsheetSheet], +) -> Vec { + if let Some(output_path) = options.output_path.as_deref() { + if output_path.extension().is_some_and(|ext| ext == "html") { + let stem = output_path + .file_stem() + .and_then(|value| value.to_str()) + .unwrap_or("render"); + let parent = output_path.parent().unwrap_or(cwd); + return sheets + .iter() + .map(|sheet| { + parent.join(format!( + "{}_{}.html", + stem, + sanitize_file_component(&sheet.name) + )) + }) + .collect(); + } + return sheets + .iter() + .map(|sheet| output_path.join(format!("{}.html", sanitize_file_component(&sheet.name)))) + .collect(); + } + sheets + .iter() + .map(|sheet| { + cwd.join(format!( + "{}_render_{}.html", + artifact.artifact_id, + sanitize_file_component(&sheet.name) + )) + }) + .collect() +} + +fn single_output_path( + cwd: &Path, + artifact: &SpreadsheetArtifact, + output_path: Option<&Path>, + suffix: &str, +) -> PathBuf { + if let Some(output_path) = output_path { + return if output_path.extension().is_some_and(|ext| ext == "html") { + output_path.to_path_buf() + } else { + output_path.join(format!("{suffix}.html")) + }; + } + cwd.join(format!("{}_{}.html", artifact.artifact_id, suffix)) +} + +fn sanitize_file_component(value: &str) -> String { + value + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() { + character + } else { + '_' + } + }) + .collect() +} + +fn html_escape(value: &str) -> String { + value + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} diff --git a/codex-rs/artifact-spreadsheet/src/table.rs b/codex-rs/artifact-spreadsheet/src/table.rs new file mode 100644 index 0000000000..b714a20c21 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/table.rs @@ -0,0 +1,619 @@ +use std::collections::BTreeMap; +use std::collections::BTreeSet; + +use serde::Deserialize; +use serde::Serialize; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetCellValue; +use crate::SpreadsheetSheet; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetTableColumn { + pub id: u32, + pub name: String, + pub totals_row_label: Option, + pub totals_row_function: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetTable { + pub id: u32, + pub name: String, + pub display_name: String, + pub range: String, + pub header_row_count: u32, + pub totals_row_count: u32, + pub style_name: Option, + pub show_first_column: bool, + pub show_last_column: bool, + pub show_row_stripes: bool, + pub show_column_stripes: bool, + #[serde(default)] + pub columns: Vec, + #[serde(default)] + pub filters: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetTableView { + pub id: u32, + pub name: String, + pub display_name: String, + pub address: String, + pub full_range: String, + pub header_row_count: u32, + pub totals_row_count: u32, + pub totals_row_visible: bool, + pub header_row_range: Option, + pub data_body_range: Option, + pub totals_row_range: Option, + pub style_name: Option, + pub show_first_column: bool, + pub show_last_column: bool, + pub show_row_stripes: bool, + pub show_column_stripes: bool, + pub columns: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct SpreadsheetTableLookup<'a> { + pub name: Option<&'a str>, + pub display_name: Option<&'a str>, + pub id: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetCreateTableOptions { + pub name: Option, + pub display_name: Option, + pub header_row_count: u32, + pub totals_row_count: u32, + pub style_name: Option, + pub show_first_column: bool, + pub show_last_column: bool, + pub show_row_stripes: bool, + pub show_column_stripes: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetTableStyleOptions { + pub style_name: Option, + pub show_first_column: Option, + pub show_last_column: Option, + pub show_row_stripes: Option, + pub show_column_stripes: Option, +} + +impl SpreadsheetTable { + pub fn range(&self) -> Result { + CellRange::parse(&self.range) + } + + pub fn address(&self) -> String { + self.range.clone() + } + + pub fn full_range(&self) -> String { + self.range.clone() + } + + pub fn totals_row_visible(&self) -> bool { + self.totals_row_count > 0 + } + + pub fn header_row_range(&self) -> Result, SpreadsheetArtifactError> { + if self.header_row_count == 0 { + return Ok(None); + } + let range = self.range()?; + Ok(Some(CellRange::from_start_end( + range.start, + CellAddress { + column: range.end.column, + row: range.start.row + self.header_row_count - 1, + }, + ))) + } + + pub fn data_body_range(&self) -> Result, SpreadsheetArtifactError> { + let range = self.range()?; + let start_row = range.start.row + self.header_row_count; + let end_row = range.end.row.saturating_sub(self.totals_row_count); + if start_row > end_row { + return Ok(None); + } + Ok(Some(CellRange::from_start_end( + CellAddress { + column: range.start.column, + row: start_row, + }, + CellAddress { + column: range.end.column, + row: end_row, + }, + ))) + } + + pub fn totals_row_range(&self) -> Result, SpreadsheetArtifactError> { + if self.totals_row_count == 0 { + return Ok(None); + } + let range = self.range()?; + Ok(Some(CellRange::from_start_end( + CellAddress { + column: range.start.column, + row: range.end.row - self.totals_row_count + 1, + }, + range.end, + ))) + } + + pub fn view(&self) -> Result { + Ok(SpreadsheetTableView { + id: self.id, + name: self.name.clone(), + display_name: self.display_name.clone(), + address: self.address(), + full_range: self.full_range(), + header_row_count: self.header_row_count, + totals_row_count: self.totals_row_count, + totals_row_visible: self.totals_row_visible(), + header_row_range: self.header_row_range()?.map(|range| range.to_a1()), + data_body_range: self.data_body_range()?.map(|range| range.to_a1()), + totals_row_range: self.totals_row_range()?.map(|range| range.to_a1()), + style_name: self.style_name.clone(), + show_first_column: self.show_first_column, + show_last_column: self.show_last_column, + show_row_stripes: self.show_row_stripes, + show_column_stripes: self.show_column_stripes, + columns: self.columns.clone(), + }) + } +} + +impl SpreadsheetSheet { + pub fn create_table( + &mut self, + action: &str, + range: &CellRange, + options: SpreadsheetCreateTableOptions, + ) -> Result { + validate_table_geometry(action, range, options.header_row_count, options.totals_row_count)?; + for table in &self.tables { + let table_range = table.range()?; + if table_range.intersects(range) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "table range `{}` intersects existing table `{}`", + range.to_a1(), + table.name + ), + }); + } + } + + let next_id = self.tables.iter().map(|table| table.id).max().unwrap_or(0) + 1; + let name = options.name.unwrap_or_else(|| format!("Table{next_id}")); + if name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table name cannot be empty".to_string(), + }); + } + let display_name = options.display_name.unwrap_or_else(|| name.clone()); + if display_name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table display_name cannot be empty".to_string(), + }); + } + ensure_unique_table_name(&self.tables, action, &name, &display_name, None)?; + + let columns = build_table_columns(self, range, options.header_row_count); + self.tables.push(SpreadsheetTable { + id: next_id, + name, + display_name, + range: range.to_a1(), + header_row_count: options.header_row_count, + totals_row_count: options.totals_row_count, + style_name: options.style_name, + show_first_column: options.show_first_column, + show_last_column: options.show_last_column, + show_row_stripes: options.show_row_stripes, + show_column_stripes: options.show_column_stripes, + columns, + filters: BTreeMap::new(), + }); + Ok(next_id) + } + + pub fn list_tables( + &self, + range: Option<&CellRange>, + ) -> Result, SpreadsheetArtifactError> { + self.tables + .iter() + .filter(|table| { + range.is_none_or(|target| { + table + .range() + .map(|table_range| table_range.intersects(target)) + .unwrap_or(false) + }) + }) + .map(SpreadsheetTable::view) + .collect() + } + + pub fn get_table( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<&SpreadsheetTable, SpreadsheetArtifactError> { + self.table_lookup_internal(action, lookup) + } + + pub fn get_table_view( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result { + self.get_table(action, lookup)?.view() + } + + pub fn delete_table( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<(), SpreadsheetArtifactError> { + let index = self.table_index(action, lookup)?; + self.tables.remove(index); + Ok(()) + } + + pub fn set_table_style( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + options: SpreadsheetTableStyleOptions, + ) -> Result<(), SpreadsheetArtifactError> { + let table = self.table_lookup_mut(action, lookup)?; + table.style_name = options.style_name; + if let Some(value) = options.show_first_column { + table.show_first_column = value; + } + if let Some(value) = options.show_last_column { + table.show_last_column = value; + } + if let Some(value) = options.show_row_stripes { + table.show_row_stripes = value; + } + if let Some(value) = options.show_column_stripes { + table.show_column_stripes = value; + } + Ok(()) + } + + pub fn clear_table_filters( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<(), SpreadsheetArtifactError> { + self.table_lookup_mut(action, lookup)?.filters.clear(); + Ok(()) + } + + pub fn reapply_table_filters( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<(), SpreadsheetArtifactError> { + let _ = self.table_lookup_mut(action, lookup)?; + Ok(()) + } + + pub fn rename_table_column( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + column_id: Option, + column_name: Option<&str>, + new_name: String, + ) -> Result { + if new_name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table column name cannot be empty".to_string(), + }); + } + let table = self.table_lookup_mut(action, lookup)?; + if table + .columns + .iter() + .any(|column| column.name == new_name && Some(column.id) != column_id) + { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table column `{new_name}` already exists"), + }); + } + let column = table_column_lookup_mut(&mut table.columns, action, column_id, column_name)?; + column.name = new_name; + Ok(column.clone()) + } + + pub fn set_table_column_totals( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + column_id: Option, + column_name: Option<&str>, + totals_row_label: Option, + totals_row_function: Option, + ) -> Result { + let table = self.table_lookup_mut(action, lookup)?; + let column = table_column_lookup_mut(&mut table.columns, action, column_id, column_name)?; + column.totals_row_label = totals_row_label; + column.totals_row_function = totals_row_function; + Ok(column.clone()) + } + + pub fn validate_tables(&self, action: &str) -> Result<(), SpreadsheetArtifactError> { + let mut seen_names = BTreeSet::new(); + let mut seen_display_names = BTreeSet::new(); + for table in &self.tables { + let range = table.range()?; + validate_table_geometry(action, &range, table.header_row_count, table.totals_row_count)?; + if !seen_names.insert(table.name.clone()) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("duplicate table name `{}`", table.name), + }); + } + if !seen_display_names.insert(table.display_name.clone()) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("duplicate table display_name `{}`", table.display_name), + }); + } + let column_names = table + .columns + .iter() + .map(|column| column.name.clone()) + .collect::>(); + if column_names.len() != table.columns.len() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table `{}` has duplicate column names", table.name), + }); + } + } + + for index in 0..self.tables.len() { + for other in index + 1..self.tables.len() { + if self.tables[index] + .range()? + .intersects(&self.tables[other].range()?) + { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "table `{}` intersects table `{}`", + self.tables[index].name, self.tables[other].name + ), + }); + } + } + } + Ok(()) + } + + fn table_index( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result { + self.tables + .iter() + .position(|table| table_matches_lookup(table, lookup.clone())) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: describe_missing_table(lookup), + }) + } + + fn table_lookup_internal( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<&SpreadsheetTable, SpreadsheetArtifactError> { + self.tables + .iter() + .find(|table| table_matches_lookup(table, lookup.clone())) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: describe_missing_table(lookup), + }) + } + + fn table_lookup_mut( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<&mut SpreadsheetTable, SpreadsheetArtifactError> { + let index = self.table_index(action, lookup)?; + Ok(&mut self.tables[index]) + } +} + +fn table_matches_lookup(table: &SpreadsheetTable, lookup: SpreadsheetTableLookup<'_>) -> bool { + if let Some(name) = lookup.name { + table.name == name + } else if let Some(display_name) = lookup.display_name { + table.display_name == display_name + } else if let Some(id) = lookup.id { + table.id == id + } else { + false + } +} + +fn describe_missing_table(lookup: SpreadsheetTableLookup<'_>) -> String { + if let Some(name) = lookup.name { + format!("table name `{name}` was not found") + } else if let Some(display_name) = lookup.display_name { + format!("table display_name `{display_name}` was not found") + } else if let Some(id) = lookup.id { + format!("table id `{id}` was not found") + } else { + "table name, display_name, or id is required".to_string() + } +} + +fn ensure_unique_table_name( + tables: &[SpreadsheetTable], + action: &str, + name: &str, + display_name: &str, + exclude_id: Option, +) -> Result<(), SpreadsheetArtifactError> { + if tables.iter().any(|table| { + Some(table.id) != exclude_id && (table.name == name || table.display_name == name) + }) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table name `{name}` already exists"), + }); + } + if tables.iter().any(|table| { + Some(table.id) != exclude_id + && (table.display_name == display_name || table.name == display_name) + }) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table display_name `{display_name}` already exists"), + }); + } + Ok(()) +} + +fn validate_table_geometry( + action: &str, + range: &CellRange, + header_row_count: u32, + totals_row_count: u32, +) -> Result<(), SpreadsheetArtifactError> { + if range.width() == 0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table range must include at least one column".to_string(), + }); + } + if header_row_count + totals_row_count > range.height() as u32 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table range is smaller than header and totals rows".to_string(), + }); + } + Ok(()) +} + +fn build_table_columns( + sheet: &SpreadsheetSheet, + range: &CellRange, + header_row_count: u32, +) -> Vec { + let header_row = range.start.row + header_row_count.saturating_sub(1); + let default_names = (0..range.width()) + .map(|index| format!("Column{}", index + 1)) + .collect::>(); + let names = unique_table_column_names( + (range.start.column..=range.end.column) + .enumerate() + .map(|(index, column)| { + if header_row_count == 0 { + return default_names[index].clone(); + } + sheet + .get_cell(CellAddress { + column, + row: header_row, + }) + .and_then(|cell| cell.value.as_ref()) + .map(cell_value_to_table_header) + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| default_names[index].clone()) + }) + .collect::>(), + ); + names + .into_iter() + .enumerate() + .map(|(index, name)| SpreadsheetTableColumn { + id: index as u32 + 1, + name, + totals_row_label: None, + totals_row_function: None, + }) + .collect() +} + +fn unique_table_column_names(names: Vec) -> Vec { + let mut seen = BTreeMap::::new(); + names.into_iter() + .map(|name| { + let entry = seen.entry(name.clone()).or_insert(0); + *entry += 1; + if *entry == 1 { + name + } else { + format!("{name}_{}", *entry) + } + }) + .collect() +} + +fn cell_value_to_table_header(value: &SpreadsheetCellValue) -> String { + match value { + SpreadsheetCellValue::Bool(value) => value.to_string(), + SpreadsheetCellValue::Integer(value) => value.to_string(), + SpreadsheetCellValue::Float(value) => value.to_string(), + SpreadsheetCellValue::String(value) + | SpreadsheetCellValue::DateTime(value) + | SpreadsheetCellValue::Error(value) => value.clone(), + } +} + +fn table_column_lookup_mut<'a>( + columns: &'a mut [SpreadsheetTableColumn], + action: &str, + column_id: Option, + column_name: Option<&str>, +) -> Result<&'a mut SpreadsheetTableColumn, SpreadsheetArtifactError> { + columns + .iter_mut() + .find(|column| { + if let Some(column_id) = column_id { + column.id == column_id + } else if let Some(column_name) = column_name { + column.name == column_name + } else { + false + } + }) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: if let Some(column_id) = column_id { + format!("table column id `{column_id}` was not found") + } else if let Some(column_name) = column_name { + format!("table column `{column_name}` was not found") + } else { + "table column id or name is required".to_string() + }, + }) +} diff --git a/codex-rs/artifact-spreadsheet/src/tests.rs b/codex-rs/artifact-spreadsheet/src/tests.rs index 8e7a378616..608ac7b392 100644 --- a/codex-rs/artifact-spreadsheet/src/tests.rs +++ b/codex-rs/artifact-spreadsheet/src/tests.rs @@ -15,6 +15,7 @@ use crate::SpreadsheetFileType; use crate::SpreadsheetFill; use crate::SpreadsheetFontFace; use crate::SpreadsheetNumberFormat; +use crate::SpreadsheetRenderOptions; use crate::SpreadsheetSheet; use crate::SpreadsheetSheetReference; use crate::SpreadsheetTextStyle; @@ -164,6 +165,72 @@ fn path_accesses_cover_import_and_export() -> Result<(), Box Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut artifact = SpreadsheetArtifact::new(Some("Preview".to_string())); + artifact.create_sheet("Sheet 1".to_string())?; + { + let sheet = artifact + .get_sheet_mut(Some("Sheet 1"), None) + .expect("sheet"); + sheet.set_value( + CellAddress::parse("A1")?, + Some(SpreadsheetCellValue::String("Name".to_string())), + )?; + sheet.set_value( + CellAddress::parse("B1")?, + Some(SpreadsheetCellValue::String("Value".to_string())), + )?; + sheet.set_value( + CellAddress::parse("A2")?, + Some(SpreadsheetCellValue::String("Alpha".to_string())), + )?; + sheet.set_value( + CellAddress::parse("B2")?, + Some(SpreadsheetCellValue::Integer(42)), + )?; + } + + let rendered = artifact.render_range_preview( + temp_dir.path(), + artifact.get_sheet(Some("Sheet 1"), None).expect("sheet"), + &CellRange::parse("A1:B2")?, + &SpreadsheetRenderOptions { + output_path: Some(temp_dir.path().join("range-preview.html")), + width: Some(320), + height: Some(200), + include_headers: true, + scale: 1.25, + performance_mode: true, + ..Default::default() + }, + )?; + assert!(rendered.path.exists()); + assert_eq!(std::fs::read_to_string(&rendered.path)?, rendered.html); + assert!(rendered.html.contains("")); + assert!(rendered.html.contains("data-performance-mode=\"true\"")); + assert!(rendered.html.contains( + "style=\"--scale: 1.25; --headers: 1; width: 320px; height: 200px; overflow: auto\"" + )); + assert!(rendered.html.contains("A")); + assert!(rendered.html.contains("data-address=\"B2\"")); + assert!(rendered.html.contains(">42")); + + let workbook = artifact.render_workbook_previews( + temp_dir.path(), + &SpreadsheetRenderOptions { + output_path: Some(temp_dir.path().join("workbook")), + include_headers: false, + ..Default::default() + }, + )?; + assert_eq!(workbook.len(), 1); + assert!(workbook[0].path.ends_with("Sheet_1.html")); + assert!(!workbook[0].html.contains("A")); + Ok(()) +} + #[test] fn sheet_refs_support_handle_and_field_apis() -> Result<(), Box> { let mut artifact = SpreadsheetArtifact::new(Some("Handles".to_string())); @@ -1049,3 +1116,113 @@ fn manager_get_reference_and_xlsx_import_preserve_workbook_name() ); Ok(()) } + +#[test] +fn manager_render_actions_support_workbook_sheet_and_range() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = SpreadsheetArtifactManager::default(); + let created = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Render" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_sheet".to_string(), + args: serde_json::json!({ "name": "Sheet1" }), + }, + temp_dir.path(), + )?; + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_range_values".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "A1:C4", + "values": [ + ["h1", "h2", "h3"], + ["a", 1, 2], + ["b", 3, 4], + ["c", 5, 6] + ] + }), + }, + temp_dir.path(), + )?; + + let workbook = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "render_workbook".to_string(), + args: serde_json::json!({ + "output_path": temp_dir.path().join("workbook-previews"), + "include_headers": false + }), + }, + temp_dir.path(), + )?; + assert_eq!(workbook.exported_paths.len(), 1); + assert!(workbook.exported_paths[0].exists()); + + let sheet = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "render_sheet".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "output_path": temp_dir.path().join("sheet-preview.html"), + "center_address": "B3", + "width": 220, + "height": 90, + "scale": 1.5, + "performance_mode": true + }), + }, + temp_dir.path(), + )?; + assert_eq!(sheet.exported_paths.len(), 1); + assert!(sheet.exported_paths[0].exists()); + assert!( + sheet + .rendered_html + .as_ref() + .is_some_and(|html| html.contains("data-performance-mode=\"true\"")) + ); + + let range = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id), + action: "render_range".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "A2:C4", + "output_path": temp_dir.path().join("range-preview.html"), + "include_headers": true + }), + }, + temp_dir.path(), + )?; + assert_eq!(range.exported_paths.len(), 1); + assert_eq!( + range + .range_ref + .as_ref() + .map(|range_ref| range_ref.address.clone()), + Some("A2:C4".to_string()) + ); + assert!( + range + .rendered_html + .as_ref() + .is_some_and(|html| html.contains("A")) + ); + Ok(()) +} diff --git a/codex-rs/core/src/tools/handlers/presentation_artifact.rs b/codex-rs/core/src/tools/handlers/presentation_artifact.rs index 866d90de88..d89e5d7f14 100644 --- a/codex-rs/core/src/tools/handlers/presentation_artifact.rs +++ b/codex-rs/core/src/tools/handlers/presentation_artifact.rs @@ -49,6 +49,10 @@ impl ToolHandler for PresentationArtifactHandler { | "list_slide_placeholders" | "inspect" | "resolve" + | "to_proto" + | "get_style" + | "describe_styles" + | "record_patch" ) } diff --git a/codex-rs/core/templates/tools/presentation_artifact.md b/codex-rs/core/templates/tools/presentation_artifact.md index 1659ae7b1a..9b30390726 100644 --- a/codex-rs/core/templates/tools/presentation_artifact.md +++ b/codex-rs/core/templates/tools/presentation_artifact.md @@ -17,11 +17,19 @@ Supported actions: - `list_slide_placeholders` - `inspect` - `resolve` +- `to_proto` +- `record_patch` +- `apply_patch` +- `undo` +- `redo` - `create_layout` - `add_layout_placeholder` - `set_slide_layout` - `update_placeholder_text` - `set_theme` +- `add_style` +- `get_style` +- `describe_styles` - `set_notes` - `append_notes` - `clear_notes` @@ -77,14 +85,51 @@ Example layout flow: `{"artifact_id":"presentation_x","action":"list_slide_placeholders","args":{"slide_index":0}}` +Layout references in `create_layout.parent_layout_id`, `add_layout_placeholder.layout_id`, `add_slide`, `insert_slide`, `set_slide_layout`, and `list_layout_placeholders` accept either a layout id or a layout name. Name matching prefers exact id, then exact name, then case-insensitive name. + +`insert_slide` accepts `index` or `after_slide_index`. If neither is provided, the new slide is inserted immediately after the active slide, or appended if no active slide is set yet. + Example inspect: -`{"artifact_id":"presentation_x","action":"inspect","args":{"kind":"deck,slide,textbox,shape,table,chart,image,notes,layoutList","max_chars":12000}}` +`{"artifact_id":"presentation_x","action":"inspect","args":{"include":"deck,slide,textbox,shape,table,chart,image,notes,layoutList","exclude":"notes","search":"roadmap","max_chars":12000}}` + +Example inspect target window: +`{"artifact_id":"presentation_x","action":"inspect","args":{"include":"textbox","target":{"id":"sh/element_3","before_lines":1,"after_lines":1}}}` Example resolve: `{"artifact_id":"presentation_x","action":"resolve","args":{"id":"sh/element_3"}}` +Example proto export: +`{"artifact_id":"presentation_x","action":"to_proto","args":{}}` + +`to_proto` returns a full JSON snapshot of the current in-memory presentation document, including slide/layout records, anchors, notes, theme state, and typed element payloads. + +Example patch recording: +`{"artifact_id":"presentation_x","action":"record_patch","args":{"operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}` + +Example patch application: +`{"artifact_id":"presentation_x","action":"apply_patch","args":{"patch":{"version":1,"artifactId":"presentation_x","operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}}` + +Patch payloads are single-artifact and currently support existing in-memory editing actions like slide/element/layout/theme/text updates. Lifecycle, import/export, and nested history actions are intentionally excluded. + +Example undo/redo: +`{"artifact_id":"presentation_x","action":"undo","args":{}}` + +`{"artifact_id":"presentation_x","action":"redo","args":{}}` + Deck summaries, slide listings, `inspect`, and `resolve` now include active-slide metadata. Use `set_active_slide` to change it explicitly. +Theme snapshots and `to_proto` both expose the deck theme hex color map via `hex_color_map` / `hexColorMap`. + +Named text styles are supported through `add_style`, `get_style`, and `describe_styles`. Built-in styles include `title`, `heading1`, `body`, `list`, and `numberedList`. + +Example style creation: +`{"artifact_id":"presentation_x","action":"add_style","args":{"name":"callout","font_size":18,"color":"#336699","italic":true,"underline":true}}` + +Example style lookup: +`{"artifact_id":"presentation_x","action":"get_style","args":{"name":"title"}}` + +Text styling payloads on `add_text_shape`, `add_shape.text_style`, `update_text.styling`, and `update_table_cell.styling` accept `style` and `underline` in addition to the existing whole-element fields. + Text-bearing elements also support literal `replace_text` and `insert_text_after` helpers for in-place edits without resending the full string. Text boxes and shapes support whole-element hyperlinks via `set_hyperlink`. Supported `link_type` values are `url`, `slide`, `first_slide`, `last_slide`, `next_slide`, `previous_slide`, `end_show`, `email`, and `file`. Use `clear: true` to remove an existing hyperlink. @@ -93,7 +138,9 @@ Notes visibility is honored on export: `set_notes_visibility` controls whether s Image placeholders can be prompt-only. `add_image` accepts `prompt` without `path`/`data_url`, and unresolved placeholders export as a visible placeholder box instead of failing. -Remote images are supported. `add_image` and `replace_image` accept `uri` in addition to local `path` and `data_url`. +Layout placeholders with `placeholder_type: "picture"` or `"image"` materialize as placeholder image elements on slides, so they appear in `list_slide_placeholders`, `inspect`, and `resolve` as `image` records rather than generic shapes. + +Remote images are supported. `add_image` and `replace_image` accept `uri` in addition to local `path`, raw base64 `blob`, and `data_url`. Image edits can target inspect/resolve anchors like `im/element_3`, and `update_shape_style` now accepts image `fit`, `crop`, `rotation`, `flip_horizontal`, `flip_vertical`, and `lock_aspect_ratio` updates. @@ -101,12 +148,16 @@ Image edits can target inspect/resolve anchors like `im/element_3`, and `update_ `update_shape_style.position` accepts partial updates, so you can move or resize an element without resending the full rect. +Shape strokes accept an optional `style` field such as `solid`, `dashed`, `dotted`, `dash-dot`, `dash-dot-dot`, `long-dash`, or `long-dash-dot`. This applies to ordinary shapes via `add_shape.stroke` and `update_shape_style.stroke`. + +`add_shape` also accepts optional `rotation`, `flip_horizontal`, and `flip_vertical` fields. Those same transform fields can also be provided inside the `position` object for `add_shape`, `add_image`, and `update_shape_style`. + Connectors are supported via `add_connector`, with straight/elbow/curved types plus dash styles and arrow heads. Example preview: `{"artifact_id":"presentation_x","action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.png"}}` -`export_preview` also accepts `format`, `scale`, and `quality` for rendered previews. `format` currently supports `png` and `jpeg`. +`export_preview` also accepts `format`, `scale`, and `quality` for rendered previews. `format` currently supports `png`, `jpeg`, and `svg`. Example JPEG preview: `{"artifact_id":"presentation_x","action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.jpg","format":"jpeg","scale":0.75,"quality":85}}` From 1df040e62bdc1e96b69eaf53639b638050a3eeb1 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 3 Mar 2026 14:37:26 +0000 Subject: [PATCH 329/385] feat: add multi-actions to presentation tool (#13357) --- .../src/presentation_artifact/api.rs | 72 +++++++++++++++++ .../src/presentation_artifact/manager.rs | 42 ++++++++++ .../src/presentation_artifact/response.rs | 5 +- codex-rs/artifact-presentation/src/tests.rs | 79 +++++++++++++++++++ codex-rs/core/src/codex.rs | 6 +- .../tools/handlers/presentation_artifact.rs | 28 +++---- codex-rs/core/src/tools/spec.rs | 39 ++++++--- .../templates/tools/presentation_artifact.md | 46 ++++++----- 8 files changed, 262 insertions(+), 55 deletions(-) diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/api.rs b/codex-rs/artifact-presentation/src/presentation_artifact/api.rs index 1b36392cd9..5680bf97fe 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/api.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/api.rs @@ -85,6 +85,27 @@ pub struct PresentationArtifactRequest { pub args: Value, } +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PresentationArtifactToolRequest { + pub artifact_id: Option, + pub actions: Vec, +} + +#[derive(Debug, Clone)] +pub struct PresentationArtifactExecutionRequest { + pub artifact_id: Option, + pub requests: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PresentationArtifactToolAction { + pub action: String, + #[serde(default)] + pub args: Value, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PathAccessKind { Read, @@ -99,6 +120,10 @@ pub struct PathAccessRequirement { } impl PresentationArtifactRequest { + pub fn is_mutating(&self) -> bool { + !is_read_only_action(&self.action) + } + pub fn required_path_accesses( &self, cwd: &Path, @@ -175,3 +200,50 @@ impl PresentationArtifactRequest { Ok(access) } } + +impl PresentationArtifactToolRequest { + pub fn is_mutating(&self) -> Result { + Ok(self.actions.iter().any(|request| !is_read_only_action(&request.action))) + } + + pub fn into_execution_request( + self, + ) -> Result { + if self.actions.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: "presentation_artifact".to_string(), + message: "`actions` must contain at least one item".to_string(), + }); + } + Ok(PresentationArtifactExecutionRequest { + artifact_id: self.artifact_id, + requests: self + .actions + .into_iter() + .map(|request| PresentationArtifactRequest { + artifact_id: None, + action: request.action, + args: request.args, + }) + .collect(), + }) + } + + pub fn required_path_accesses( + &self, + cwd: &Path, + ) -> Result, PresentationArtifactError> { + let mut accesses = Vec::new(); + for request in &self.actions { + accesses.extend( + PresentationArtifactRequest { + artifact_id: None, + action: request.action.clone(), + args: request.args.clone(), + } + .required_path_accesses(cwd)?, + ); + } + Ok(accesses) + } +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs b/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs index 67e190ee51..28682cb916 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs @@ -14,6 +14,47 @@ struct HistoryEntry { } impl PresentationArtifactManager { + pub fn execute_requests( + &mut self, + request: PresentationArtifactExecutionRequest, + cwd: &Path, + ) -> Result { + let PresentationArtifactExecutionRequest { + artifact_id, + requests, + } = request; + let request_count = requests.len(); + let mut current_artifact_id = artifact_id; + let mut executed_actions = Vec::with_capacity(request_count); + let mut exported_paths = Vec::new(); + let mut last_response = None; + + for mut request in requests { + if request.artifact_id.is_none() { + request.artifact_id = current_artifact_id.clone(); + } + let response = self.execute(request, cwd)?; + current_artifact_id = Some(response.artifact_id.clone()); + exported_paths.extend(response.exported_paths.iter().cloned()); + executed_actions.push(response.action.clone()); + last_response = Some(response); + } + + let mut response = last_response.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: "presentation_artifact".to_string(), + message: "request sequence must contain at least one action".to_string(), + })?; + if request_count > 1 { + let final_summary = response.summary.clone(); + response.action = "batch".to_string(); + response.summary = + format!("Executed {request_count} actions sequentially. {final_summary}"); + response.executed_actions = Some(executed_actions); + response.exported_paths = exported_paths; + } + Ok(response) + } + pub fn execute( &mut self, request: PresentationArtifactRequest, @@ -2163,6 +2204,7 @@ impl PresentationArtifactManager { removed.artifact_id, removed.slides.len() ), + executed_actions: None, exported_paths: Vec::new(), artifact_snapshot: None, slide_list: None, diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/response.rs b/codex-rs/artifact-presentation/src/presentation_artifact/response.rs index 303f0b5695..241cce570d 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/response.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/response.rs @@ -3,6 +3,8 @@ pub struct PresentationArtifactResponse { pub artifact_id: String, pub action: String, pub summary: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub executed_actions: Option>, #[serde(skip_serializing_if = "Vec::is_empty")] pub exported_paths: Vec, #[serde(skip_serializing_if = "Option::is_none")] @@ -38,6 +40,7 @@ impl PresentationArtifactResponse { artifact_id, action, summary, + executed_actions: None, exported_paths: Vec::new(), artifact_snapshot: Some(artifact_snapshot), slide_list: None, @@ -63,6 +66,7 @@ fn response_for_document_state( artifact_id, action, summary, + executed_actions: None, exported_paths: Vec::new(), artifact_snapshot: document.map(snapshot_for_document), slide_list: None, @@ -132,4 +136,3 @@ pub struct ThemeSnapshot { pub major_font: Option, pub minor_font: Option, } - diff --git a/codex-rs/artifact-presentation/src/tests.rs b/codex-rs/artifact-presentation/src/tests.rs index e9d0a75b6d..493e67a175 100644 --- a/codex-rs/artifact-presentation/src/tests.rs +++ b/codex-rs/artifact-presentation/src/tests.rs @@ -258,6 +258,85 @@ fn exported_images_are_real_pictures_with_media_parts() -> Result<(), Box Result<(), Box> { + let request: PresentationArtifactToolRequest = serde_json::from_value(serde_json::json!({ + "actions": [ + { + "action": "create", + "args": { "name": "Batch Deck" } + }, + { + "action": "export_pptx", + "args": { "path": "deck.pptx" } + } + ] + }))?; + + let execution = request.into_execution_request()?; + assert_eq!(execution.artifact_id, None); + assert_eq!(execution.requests.len(), 2); + assert_eq!(execution.requests[0].action, "create"); + assert_eq!(execution.requests[1].action, "export_pptx"); + Ok(()) +} + +#[test] +fn manager_can_execute_sequential_actions() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let response = manager.execute_requests( + PresentationArtifactExecutionRequest { + artifact_id: None, + requests: vec![ + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Batch Deck" }), + }, + PresentationArtifactRequest { + artifact_id: None, + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + PresentationArtifactRequest { + artifact_id: None, + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "hello", + "position": { "left": 40, "top": 40, "width": 200, "height": 80 } + }), + }, + ], + }, + temp_dir.path(), + )?; + + assert_eq!(response.action, "batch"); + assert_eq!( + response.executed_actions, + Some(vec![ + "create".to_string(), + "add_slide".to_string(), + "add_text_shape".to_string(), + ]) + ); + assert_eq!( + response + .artifact_snapshot + .as_ref() + .map(|snapshot| snapshot.slide_count), + Some(1) + ); + assert!( + response + .summary + .contains("Executed 3 actions sequentially.") + ); + Ok(()) +} + #[test] fn imported_pptx_surfaces_image_elements() -> Result<(), Box> { let temp_dir = tempfile::tempdir()?; diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 23f658cf28..1e6c72c0c6 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -56,7 +56,7 @@ use async_channel::Sender; use chrono::Local; use chrono::Utc; use codex_artifact_presentation::PresentationArtifactError; -use codex_artifact_presentation::PresentationArtifactRequest; +use codex_artifact_presentation::PresentationArtifactExecutionRequest; use codex_artifact_presentation::PresentationArtifactResponse; use codex_hooks::HookEvent; use codex_hooks::HookEventAfterAgent; @@ -1782,11 +1782,11 @@ impl Session { pub(crate) async fn execute_presentation_artifact( &self, - request: PresentationArtifactRequest, + request: PresentationArtifactExecutionRequest, cwd: &Path, ) -> Result { let mut state = self.state.lock().await; - state.presentation_artifacts.execute(request, cwd) + state.presentation_artifacts.execute_requests(request, cwd) } async fn record_initial_history(&self, conversation_history: InitialHistory) { diff --git a/codex-rs/core/src/tools/handlers/presentation_artifact.rs b/codex-rs/core/src/tools/handlers/presentation_artifact.rs index d89e5d7f14..23b80d6912 100644 --- a/codex-rs/core/src/tools/handlers/presentation_artifact.rs +++ b/codex-rs/core/src/tools/handlers/presentation_artifact.rs @@ -2,7 +2,7 @@ use async_trait::async_trait; use codex_artifact_presentation::PathAccessKind; use codex_artifact_presentation::PathAccessRequirement; use codex_artifact_presentation::PresentationArtifactError; -use codex_artifact_presentation::PresentationArtifactRequest; +use codex_artifact_presentation::PresentationArtifactToolRequest; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::ReviewDecision; use serde_json::to_string; @@ -37,23 +37,10 @@ impl ToolHandler for PresentationArtifactHandler { let ToolPayload::Function { arguments } = &invocation.payload else { return true; }; - let Ok(request) = parse_arguments::(arguments) else { + let Ok(request) = parse_arguments::(arguments) else { return true; }; - !matches!( - request.action.as_str(), - "get_summary" - | "list_slides" - | "list_layouts" - | "list_layout_placeholders" - | "list_slide_placeholders" - | "inspect" - | "resolve" - | "to_proto" - | "get_style" - | "describe_styles" - | "record_patch" - ) + request.is_mutating().unwrap_or(true) } async fn handle(&self, invocation: ToolInvocation) -> Result { @@ -80,7 +67,7 @@ impl ToolHandler for PresentationArtifactHandler { } }; - let request: PresentationArtifactRequest = parse_arguments(&arguments)?; + let request: PresentationArtifactToolRequest = parse_arguments(&arguments)?; for access in request .required_path_accesses(&turn.cwd) .map_err(presentation_error)? @@ -89,7 +76,12 @@ impl ToolHandler for PresentationArtifactHandler { } let response = session - .execute_presentation_artifact(request, &turn.cwd) + .execute_presentation_artifact( + request + .into_execution_request() + .map_err(presentation_error)?, + &turn.cwd, + ) .await .map_err(presentation_error)?; diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 6b36cdca45..267be909fb 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -567,6 +567,26 @@ fn create_view_image_tool() -> ToolSpec { } fn create_presentation_artifact_tool() -> ToolSpec { + let action_step_schema = JsonSchema::Object { + properties: BTreeMap::from([ + ( + "action".to_string(), + JsonSchema::String { + description: Some("Action name to run for this step.".to_string()), + }, + ), + ( + "args".to_string(), + JsonSchema::Object { + properties: BTreeMap::new(), + required: None, + additional_properties: Some(true.into()), + }, + ), + ]), + required: Some(vec!["action".to_string(), "args".to_string()]), + additional_properties: Some(false.into()), + }; let properties = BTreeMap::from([ ( "artifact_id".to_string(), @@ -577,17 +597,12 @@ fn create_presentation_artifact_tool() -> ToolSpec { }, ), ( - "action".to_string(), - JsonSchema::String { - description: Some("Action name to run against the artifact.".to_string()), - }, - ), - ( - "args".to_string(), - JsonSchema::Object { - properties: BTreeMap::new(), - required: None, - additional_properties: Some(true.into()), + "actions".to_string(), + JsonSchema::Array { + items: Box::new(action_step_schema), + description: Some( + "Array of `(action, args)` steps to execute sequentially.".to_string(), + ), }, ), ]); @@ -598,7 +613,7 @@ fn create_presentation_artifact_tool() -> ToolSpec { strict: false, parameters: JsonSchema::Object { properties, - required: Some(vec!["action".to_string(), "args".to_string()]), + required: Some(vec!["actions".to_string()]), additional_properties: Some(false.into()), }, }) diff --git a/codex-rs/core/templates/tools/presentation_artifact.md b/codex-rs/core/templates/tools/presentation_artifact.md index 9b30390726..5c63c2e044 100644 --- a/codex-rs/core/templates/tools/presentation_artifact.md +++ b/codex-rs/core/templates/tools/presentation_artifact.md @@ -4,6 +4,7 @@ Create and edit PowerPoint presentation artifacts inside the current thread. - Resume and fork do not restore live artifact state. Export files if you need a durable handoff. - Relative paths resolve from the current working directory. - Position and size values are in slide points. +- Every tool call uses a top-level `actions` array of sequential steps. Each call operates on a single top-level `artifact_id` when one is needed. If a call starts with `create` or `import_pptx`, later steps in the same call automatically reuse the returned artifact id. Supported actions: - `create` @@ -61,60 +62,63 @@ Supported actions: - `delete_artifact` Example create: -`{"action":"create","args":{"name":"Quarterly Update"}}` +`{"actions":[{"action":"create","args":{"name":"Quarterly Update"}}]}` Example create with custom slide size: -`{"action":"create","args":{"name":"Quarterly Update","slide_size":{"width":960,"height":540}}}` +`{"actions":[{"action":"create","args":{"name":"Quarterly Update","slide_size":{"width":960,"height":540}}}]}` Example edit: -`{"artifact_id":"presentation_x","action":"add_text_shape","args":{"slide_index":0,"text":"Revenue up 24%","position":{"left":48,"top":72,"width":260,"height":80}}}` +`{"artifact_id":"presentation_x","actions":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Revenue up 24%","position":{"left":48,"top":72,"width":260,"height":80}}}]}` + +Example sequential batch: +`{"actions":[{"action":"create","args":{"name":"Quarterly Update"}},{"action":"add_slide","args":{}},{"action":"add_text_shape","args":{"slide_index":0,"text":"Revenue up 24%","position":{"left":48,"top":72,"width":260,"height":80}}}]}` Table creation also accepts optional `column_widths` and `row_heights` arrays in points when you need explicit table sizing instead of even splits. Example export: -`{"artifact_id":"presentation_x","action":"export_pptx","args":{"path":"artifacts/q2-update.pptx"}}` +`{"artifact_id":"presentation_x","actions":[{"action":"export_pptx","args":{"path":"artifacts/q2-update.pptx"}}]}` Example layout flow: -`{"artifact_id":"presentation_x","action":"create_layout","args":{"name":"Title Slide"}}` +`{"artifact_id":"presentation_x","actions":[{"action":"create_layout","args":{"name":"Title Slide"}}]}` -`{"artifact_id":"presentation_x","action":"add_layout_placeholder","args":{"layout_id":"layout_1","name":"title","placeholder_type":"title","text":"Click to add title","position":{"left":48,"top":48,"width":624,"height":72}}}` +`{"artifact_id":"presentation_x","actions":[{"action":"add_layout_placeholder","args":{"layout_id":"layout_1","name":"title","placeholder_type":"title","text":"Click to add title","position":{"left":48,"top":48,"width":624,"height":72}}}]}` -`{"artifact_id":"presentation_x","action":"set_slide_layout","args":{"slide_index":0,"layout_id":"layout_1"}}` +`{"artifact_id":"presentation_x","actions":[{"action":"set_slide_layout","args":{"slide_index":0,"layout_id":"layout_1"}}]}` -`{"artifact_id":"presentation_x","action":"list_layout_placeholders","args":{"layout_id":"layout_1"}}` +`{"artifact_id":"presentation_x","actions":[{"action":"list_layout_placeholders","args":{"layout_id":"layout_1"}}]}` -`{"artifact_id":"presentation_x","action":"list_slide_placeholders","args":{"slide_index":0}}` +`{"artifact_id":"presentation_x","actions":[{"action":"list_slide_placeholders","args":{"slide_index":0}}]}` Layout references in `create_layout.parent_layout_id`, `add_layout_placeholder.layout_id`, `add_slide`, `insert_slide`, `set_slide_layout`, and `list_layout_placeholders` accept either a layout id or a layout name. Name matching prefers exact id, then exact name, then case-insensitive name. `insert_slide` accepts `index` or `after_slide_index`. If neither is provided, the new slide is inserted immediately after the active slide, or appended if no active slide is set yet. Example inspect: -`{"artifact_id":"presentation_x","action":"inspect","args":{"include":"deck,slide,textbox,shape,table,chart,image,notes,layoutList","exclude":"notes","search":"roadmap","max_chars":12000}}` +`{"artifact_id":"presentation_x","actions":[{"action":"inspect","args":{"include":"deck,slide,textbox,shape,table,chart,image,notes,layoutList","exclude":"notes","search":"roadmap","max_chars":12000}}]}` Example inspect target window: -`{"artifact_id":"presentation_x","action":"inspect","args":{"include":"textbox","target":{"id":"sh/element_3","before_lines":1,"after_lines":1}}}` +`{"artifact_id":"presentation_x","actions":[{"action":"inspect","args":{"include":"textbox","target":{"id":"sh/element_3","before_lines":1,"after_lines":1}}}]}` Example resolve: -`{"artifact_id":"presentation_x","action":"resolve","args":{"id":"sh/element_3"}}` +`{"artifact_id":"presentation_x","actions":[{"action":"resolve","args":{"id":"sh/element_3"}}]}` Example proto export: -`{"artifact_id":"presentation_x","action":"to_proto","args":{}}` +`{"artifact_id":"presentation_x","actions":[{"action":"to_proto","args":{}}]}` `to_proto` returns a full JSON snapshot of the current in-memory presentation document, including slide/layout records, anchors, notes, theme state, and typed element payloads. Example patch recording: -`{"artifact_id":"presentation_x","action":"record_patch","args":{"operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}` +`{"artifact_id":"presentation_x","actions":[{"action":"record_patch","args":{"operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}]}` Example patch application: -`{"artifact_id":"presentation_x","action":"apply_patch","args":{"patch":{"version":1,"artifactId":"presentation_x","operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}}` +`{"artifact_id":"presentation_x","actions":[{"action":"apply_patch","args":{"patch":{"version":1,"artifactId":"presentation_x","operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}}]}` Patch payloads are single-artifact and currently support existing in-memory editing actions like slide/element/layout/theme/text updates. Lifecycle, import/export, and nested history actions are intentionally excluded. Example undo/redo: -`{"artifact_id":"presentation_x","action":"undo","args":{}}` +`{"artifact_id":"presentation_x","actions":[{"action":"undo","args":{}}]}` -`{"artifact_id":"presentation_x","action":"redo","args":{}}` +`{"artifact_id":"presentation_x","actions":[{"action":"redo","args":{}}]}` Deck summaries, slide listings, `inspect`, and `resolve` now include active-slide metadata. Use `set_active_slide` to change it explicitly. @@ -123,10 +127,10 @@ Theme snapshots and `to_proto` both expose the deck theme hex color map via `hex Named text styles are supported through `add_style`, `get_style`, and `describe_styles`. Built-in styles include `title`, `heading1`, `body`, `list`, and `numberedList`. Example style creation: -`{"artifact_id":"presentation_x","action":"add_style","args":{"name":"callout","font_size":18,"color":"#336699","italic":true,"underline":true}}` +`{"artifact_id":"presentation_x","actions":[{"action":"add_style","args":{"name":"callout","font_size":18,"color":"#336699","italic":true,"underline":true}}]}` Example style lookup: -`{"artifact_id":"presentation_x","action":"get_style","args":{"name":"title"}}` +`{"artifact_id":"presentation_x","actions":[{"action":"get_style","args":{"name":"title"}}]}` Text styling payloads on `add_text_shape`, `add_shape.text_style`, `update_text.styling`, and `update_table_cell.styling` accept `style` and `underline` in addition to the existing whole-element fields. @@ -155,9 +159,9 @@ Shape strokes accept an optional `style` field such as `solid`, `dashed`, `dotte Connectors are supported via `add_connector`, with straight/elbow/curved types plus dash styles and arrow heads. Example preview: -`{"artifact_id":"presentation_x","action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.png"}}` +`{"artifact_id":"presentation_x","actions":[{"action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.png"}}]}` `export_preview` also accepts `format`, `scale`, and `quality` for rendered previews. `format` currently supports `png`, `jpeg`, and `svg`. Example JPEG preview: -`{"artifact_id":"presentation_x","action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.jpg","format":"jpeg","scale":0.75,"quality":85}}` +`{"artifact_id":"presentation_x","actions":[{"action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.jpg","format":"jpeg","scale":0.75,"quality":85}}]}` From 24ba01b9dabb28d426dccf903bc62f81e2741de8 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 3 Mar 2026 15:03:25 +0000 Subject: [PATCH 330/385] feat: artifact presentation part 7 (#13360) --- .../src/presentation_artifact/args.rs | 265 +++++- .../src/presentation_artifact/inspect.rs | 264 +++++- .../src/presentation_artifact/manager.rs | 897 +++++++++++++++++- .../src/presentation_artifact/model.rs | 311 +++++- .../src/presentation_artifact/parsing.rs | 411 +++++++- .../src/presentation_artifact/pptx.rs | 31 +- .../src/presentation_artifact/proto.rs | 260 ++++- .../src/presentation_artifact/snapshot.rs | 3 +- codex-rs/artifact-presentation/src/tests.rs | 624 +++++++++--- .../templates/tools/presentation_artifact.md | 37 +- 10 files changed, 2883 insertions(+), 220 deletions(-) diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/args.rs b/codex-rs/artifact-presentation/src/presentation_artifact/args.rs index b85bcdff81..a139dcb055 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/args.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/args.rs @@ -225,7 +225,7 @@ struct PartialPositionArgs { flip_vertical: Option, } -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Clone, Default, Deserialize)] struct TextStylingArgs { style: Option, font_size: Option, @@ -238,6 +238,57 @@ struct TextStylingArgs { underline: Option, } +#[derive(Debug, Clone, Default, Deserialize)] +struct TextLayoutArgs { + insets: Option, + wrap: Option, + auto_fit: Option, + vertical_alignment: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct TextInsetsArgs { + left: u32, + right: u32, + top: u32, + bottom: u32, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +enum RichTextInput { + Plain(String), + Paragraphs(Vec), +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +enum RichParagraphInput { + Plain(String), + Runs(Vec), +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +enum RichRunInput { + Plain(String), + Styled(RichRunObjectInput), +} + +#[derive(Debug, Clone, Deserialize)] +struct RichRunObjectInput { + run: String, + #[serde(default)] + text_style: TextStylingArgs, + link: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct RichTextLinkInput { + uri: Option, + is_external: Option, +} + #[derive(Debug, Deserialize)] struct AddTextShapeArgs { slide_index: u32, @@ -245,6 +296,8 @@ struct AddTextShapeArgs { position: PositionArgs, #[serde(flatten)] styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, } #[derive(Debug, Clone, Default, Deserialize)] @@ -267,6 +320,8 @@ struct AddShapeArgs { flip_vertical: Option, #[serde(default)] text_style: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, } #[derive(Debug, Clone, Default, Deserialize)] @@ -276,7 +331,7 @@ struct ConnectorLineArgs { style: Option, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct PointArgs { left: u32, top: u32, @@ -355,6 +410,9 @@ struct AddTableArgs { column_widths: Option>, row_heights: Option>, style: Option, + style_options: Option, + borders: Option, + right_to_left: Option, } #[derive(Debug, Deserialize)] @@ -365,12 +423,55 @@ struct AddChartArgs { categories: Vec, series: Vec, title: Option, + style_index: Option, + has_legend: Option, + legend_position: Option, + #[serde(default)] + legend_text_style: TextStylingArgs, + x_axis_title: Option, + y_axis_title: Option, + data_labels: Option, + chart_fill: Option, + plot_area_fill: Option, } #[derive(Debug, Deserialize)] struct ChartSeriesArgs { name: String, values: Vec, + categories: Option>, + x_values: Option>, + fill: Option, + stroke: Option, + marker: Option, + data_label_overrides: Option>, +} + +#[derive(Debug, Clone, Deserialize)] +struct ChartMarkerArgs { + symbol: Option, + size: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct ChartDataLabelsArgs { + show_value: Option, + show_category_name: Option, + show_leader_lines: Option, + position: Option, + #[serde(default)] + text_style: TextStylingArgs, +} + +#[derive(Debug, Clone, Deserialize)] +struct ChartDataLabelOverrideArgs { + idx: u32, + text: Option, + position: Option, + #[serde(default)] + text_style: TextStylingArgs, + fill: Option, + stroke: Option, } #[derive(Debug, Deserialize)] @@ -379,6 +480,43 @@ struct UpdateTextArgs { text: String, #[serde(default)] styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, +} + +#[derive(Debug, Deserialize)] +struct SetRichTextArgs { + element_id: Option, + slide_index: Option, + row: Option, + column: Option, + notes: Option, + text: RichTextInput, + #[serde(default)] + styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, +} + +#[derive(Debug, Deserialize)] +struct FormatTextRangeArgs { + element_id: Option, + slide_index: Option, + row: Option, + column: Option, + notes: Option, + query: Option, + occurrence: Option, + start_cp: Option, + length: Option, + #[serde(default)] + styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, + link: Option, + spacing_before: Option, + spacing_after: Option, + line_spacing: Option, } #[derive(Debug, Deserialize)] @@ -422,6 +560,8 @@ struct UpdateShapeStyleArgs { crop: Option, lock_aspect_ratio: Option, z_order: Option, + #[serde(default)] + text_layout: TextLayoutArgs, } #[derive(Debug, Deserialize)] @@ -458,6 +598,55 @@ struct UpdateTableCellArgs { alignment: Option, } +#[derive(Debug, Clone, Deserialize)] +struct TableStyleOptionsArgs { + header_row: Option, + banded_rows: Option, + banded_columns: Option, + first_column: Option, + last_column: Option, + total_row: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct TableBorderArgs { + color: String, + width: u32, +} + +#[derive(Debug, Clone, Deserialize)] +struct TableBordersArgs { + outside: Option, + inside: Option, + top: Option, + bottom: Option, + left: Option, + right: Option, +} + +#[derive(Debug, Deserialize)] +struct UpdateTableStyleArgs { + element_id: String, + style: Option, + style_options: Option, + borders: Option, + right_to_left: Option, +} + +#[derive(Debug, Deserialize)] +struct StyleTableBlockArgs { + element_id: String, + row: u32, + column: u32, + row_count: u32, + column_count: u32, + #[serde(default)] + styling: TextStylingArgs, + background_fill: Option, + alignment: Option, + borders: Option, +} + #[derive(Debug, Deserialize)] struct MergeTableCellsArgs { element_id: String, @@ -466,3 +655,75 @@ struct MergeTableCellsArgs { start_column: u32, end_column: u32, } + +#[derive(Debug, Deserialize)] +struct UpdateChartArgs { + element_id: String, + title: Option, + categories: Option>, + style_index: Option, + has_legend: Option, + legend_position: Option, + #[serde(default)] + legend_text_style: TextStylingArgs, + x_axis_title: Option, + y_axis_title: Option, + data_labels: Option, + chart_fill: Option, + plot_area_fill: Option, +} + +#[derive(Debug, Deserialize)] +struct AddChartSeriesArgs { + element_id: String, + name: String, + values: Vec, + categories: Option>, + x_values: Option>, + fill: Option, + stroke: Option, + marker: Option, +} + +#[derive(Debug, Deserialize)] +struct SetCommentAuthorArgs { + display_name: String, + initials: String, + email: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct CommentPositionArgs { + x: u32, + y: u32, +} + +#[derive(Debug, Deserialize)] +struct AddCommentThreadArgs { + slide_index: Option, + element_id: Option, + query: Option, + occurrence: Option, + start_cp: Option, + length: Option, + text: String, + position: Option, +} + +#[derive(Debug, Deserialize)] +struct AddCommentReplyArgs { + thread_id: String, + text: String, +} + +#[derive(Debug, Deserialize)] +struct ToggleCommentReactionArgs { + thread_id: String, + message_id: Option, + emoji: String, +} + +#[derive(Debug, Deserialize)] +struct CommentThreadIdArgs { + thread_id: String, +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs b/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs index c270926f3c..608e0734ee 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs @@ -3,7 +3,9 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri .include .as_deref() .or(args.kind.as_deref()) - .unwrap_or("deck,slide,textbox,shape,connector,table,chart,image,notes,layoutList"); + .unwrap_or( + "deck,slide,textbox,shape,connector,table,chart,image,notes,layoutList,textRange,comment", + ); let included_kinds = include_kinds .split(',') .map(str::trim) @@ -33,6 +35,11 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri .collect::>(), "activeSlideIndex": document.active_slide_index, "activeSlideId": document.active_slide_index.and_then(|index| document.slides.get(index)).map(|slide| format!("sl/{}", slide.slide_id)), + "commentThreadIds": document + .comment_threads + .iter() + .map(|thread| format!("th/{}", thread.thread_id)) + .collect::>(), }), None, )); @@ -97,10 +104,29 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri "textPreview": slide.notes.text.replace('\n', " | "), "textChars": slide.notes.text.chars().count(), "textLines": slide.notes.text.lines().count(), + "richText": rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text), }), Some(slide_id.clone()), )); } + if include("textRange") { + records.extend( + slide + .notes + .rich_text + .ranges + .iter() + .map(|range| { + let mut record = text_range_to_proto(&slide.notes.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!("nt/{}", slide.slide_id)); + record["hostKind"] = Value::String("notes".to_string()); + (record, Some(slide_id.clone())) + }), + ); + } for element in &slide.elements { let mut record = match element { PresentationElement::Text(text) => { @@ -116,6 +142,7 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri "textPreview": text.text.replace('\n', " | "), "textChars": text.text.chars().count(), "textLines": text.text.lines().count(), + "richText": rich_text_to_proto(&text.text, &text.rich_text), "bbox": [text.frame.left, text.frame.top, text.frame.width, text.frame.height], "bboxUnit": "points", }) @@ -136,6 +163,12 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri "geometry": format!("{:?}", shape.geometry), "text": shape.text, "textStyle": text_style_to_proto(&shape.text_style), + "richText": shape + .text + .as_ref() + .zip(shape.rich_text.as_ref()) + .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) + .unwrap_or(Value::Null), "rotation": shape.rotation_degrees, "flipHorizontal": shape.flip_horizontal, "flipVertical": shape.flip_vertical, @@ -178,11 +211,19 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri "rowHeights": table.row_heights, "preview": table.rows.first().map(|row| row.iter().map(|cell| cell.text.clone()).collect::>().join(" | ")), "style": table.style, + "styleOptions": table_style_options_to_proto(&table.style_options), + "borders": table.borders.as_ref().map(table_borders_to_proto), + "rightToLeft": table.right_to_left, "cellTextStyles": table .rows .iter() .map(|row| row.iter().map(|cell| text_style_to_proto(&cell.text_style)).collect::>()) .collect::>(), + "rowsData": table + .rows + .iter() + .map(|row| row.iter().map(table_cell_to_proto).collect::>()) + .collect::>(), "bbox": [table.frame.left, table.frame.top, table.frame.width, table.frame.height], "bboxUnit": "points", }) @@ -197,6 +238,32 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri "slide": index + 1, "chartType": format!("{:?}", chart.chart_type), "title": chart.title, + "styleIndex": chart.style_index, + "hasLegend": chart.has_legend, + "legend": chart.legend.as_ref().map(chart_legend_to_proto), + "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), + "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), + "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), + "chartFill": chart.chart_fill, + "plotAreaFill": chart.plot_area_fill, + "series": chart + .series + .iter() + .map(|series| serde_json::json!({ + "name": series.name, + "values": series.values, + "categories": series.categories, + "xValues": series.x_values, + "fill": series.fill, + "stroke": series.stroke.as_ref().map(stroke_to_proto), + "marker": series.marker.as_ref().map(chart_marker_to_proto), + "dataLabelOverrides": series + .data_label_overrides + .iter() + .map(chart_data_label_override_to_proto) + .collect::>(), + })) + .collect::>(), "bbox": [chart.frame.left, chart.frame.top, chart.frame.width, chart.frame.height], "bboxUnit": "points", }) @@ -261,8 +328,64 @@ fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> Stri record["hyperlink"] = hyperlink.to_json(); } records.push((record, Some(slide_id.clone()))); + if include("textRange") { + match element { + PresentationElement::Text(text) => { + records.extend(text.rich_text.ranges.iter().map(|range| { + let mut record = text_range_to_proto(&text.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!("sh/{}", text.element_id)); + record["hostKind"] = Value::String("textbox".to_string()); + (record, Some(slide_id.clone())) + })); + } + PresentationElement::Shape(shape) => { + if let Some((text, rich_text)) = shape.text.as_ref().zip(shape.rich_text.as_ref()) { + records.extend(rich_text.ranges.iter().map(|range| { + let mut record = text_range_to_proto(text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!("sh/{}", shape.element_id)); + record["hostKind"] = Value::String("textbox".to_string()); + (record, Some(slide_id.clone())) + })); + } + } + PresentationElement::Table(table) => { + for (row_index, row) in table.rows.iter().enumerate() { + for (column_index, cell) in row.iter().enumerate() { + records.extend(cell.rich_text.ranges.iter().map(|range| { + let mut record = text_range_to_proto(&cell.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!( + "tb/{}#cell/{row_index}/{column_index}", + table.element_id + )); + record["hostKind"] = Value::String("tableCell".to_string()); + (record, Some(slide_id.clone())) + })); + } + } + } + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Chart(_) => {} + } + } } } + if include("comment") { + records.extend(document.comment_threads.iter().map(|thread| { + let mut record = comment_thread_to_proto(thread); + record["id"] = Value::String(format!("th/{}", thread.thread_id)); + (record, None) + })); + } if let Some(target_id) = args.target_id.as_deref() { records.retain(|(record, slide_id)| { @@ -442,6 +565,27 @@ fn resolve_anchor( "text": slide.notes.text, }); add_text_metadata(&mut record, &slide.notes.text); + record["richText"] = rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text); + return Ok(record); + } + if let Some(range_id) = id.strip_prefix("tr/") + && let Some(record) = slide + .notes + .rich_text + .ranges + .iter() + .find(|range| range.range_id == range_id) + .map(|range| { + let mut record = text_range_to_proto(&slide.notes.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["id"] = Value::String(id.to_string()); + record["slide"] = Value::from(slide_index + 1); + record["slideIndex"] = Value::from(slide_index); + record["hostAnchor"] = Value::String(notes_id.clone()); + record["hostKind"] = Value::String("notes".to_string()); + record + }) + { return Ok(record); } for element in &slide.elements { @@ -455,6 +599,7 @@ fn resolve_anchor( "slideIndex": slide_index, "text": text.text, "textStyle": text_style_to_proto(&text.style), + "richText": rich_text_to_proto(&text.text, &text.rich_text), "bbox": [text.frame.left, text.frame.top, text.frame.width, text.frame.height], "bboxUnit": "points", }); @@ -471,6 +616,12 @@ fn resolve_anchor( "geometry": format!("{:?}", shape.geometry), "text": shape.text, "textStyle": text_style_to_proto(&shape.text_style), + "richText": shape + .text + .as_ref() + .zip(shape.rich_text.as_ref()) + .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) + .unwrap_or(Value::Null), "rotation": shape.rotation_degrees, "flipHorizontal": shape.flip_horizontal, "flipVertical": shape.flip_vertical, @@ -527,11 +678,20 @@ fn resolve_anchor( "cols": table.rows.iter().map(std::vec::Vec::len).max().unwrap_or(0), "columnWidths": table.column_widths, "rowHeights": table.row_heights, + "style": table.style, + "styleOptions": table_style_options_to_proto(&table.style_options), + "borders": table.borders.as_ref().map(table_borders_to_proto), + "rightToLeft": table.right_to_left, "cellTextStyles": table .rows .iter() .map(|row| row.iter().map(|cell| text_style_to_proto(&cell.text_style)).collect::>()) .collect::>(), + "rowsData": table + .rows + .iter() + .map(|row| row.iter().map(table_cell_to_proto).collect::>()) + .collect::>(), "bbox": [table.frame.left, table.frame.top, table.frame.width, table.frame.height], "bboxUnit": "points", }), @@ -543,6 +703,32 @@ fn resolve_anchor( "slideIndex": slide_index, "chartType": format!("{:?}", chart.chart_type), "title": chart.title, + "styleIndex": chart.style_index, + "hasLegend": chart.has_legend, + "legend": chart.legend.as_ref().map(chart_legend_to_proto), + "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), + "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), + "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), + "chartFill": chart.chart_fill, + "plotAreaFill": chart.plot_area_fill, + "series": chart + .series + .iter() + .map(|series| serde_json::json!({ + "name": series.name, + "values": series.values, + "categories": series.categories, + "xValues": series.x_values, + "fill": series.fill, + "stroke": series.stroke.as_ref().map(stroke_to_proto), + "marker": series.marker.as_ref().map(chart_marker_to_proto), + "dataLabelOverrides": series + .data_label_overrides + .iter() + .map(chart_data_label_override_to_proto) + .collect::>(), + })) + .collect::>(), "bbox": [chart.frame.left, chart.frame.top, chart.frame.width, chart.frame.height], "bboxUnit": "points", }), @@ -582,9 +768,84 @@ fn resolve_anchor( if record.get("id").and_then(Value::as_str) == Some(id) { return Ok(record); } + if let Some(range_id) = id.strip_prefix("tr/") { + match element { + PresentationElement::Text(text) => { + if let Some(range) = + text.rich_text.ranges.iter().find(|range| range.range_id == range_id) + { + let mut range_record = text_range_to_proto(&text.text, range); + range_record["kind"] = Value::String("textRange".to_string()); + range_record["id"] = Value::String(id.to_string()); + range_record["slide"] = Value::from(slide_index + 1); + range_record["slideIndex"] = Value::from(slide_index); + range_record["hostAnchor"] = + Value::String(format!("sh/{}", text.element_id)); + range_record["hostKind"] = Value::String("textbox".to_string()); + return Ok(range_record); + } + } + PresentationElement::Shape(shape) => { + if let Some((text, rich_text)) = + shape.text.as_ref().zip(shape.rich_text.as_ref()) + && let Some(range) = + rich_text.ranges.iter().find(|range| range.range_id == range_id) + { + let mut range_record = text_range_to_proto(text, range); + range_record["kind"] = Value::String("textRange".to_string()); + range_record["id"] = Value::String(id.to_string()); + range_record["slide"] = Value::from(slide_index + 1); + range_record["slideIndex"] = Value::from(slide_index); + range_record["hostAnchor"] = + Value::String(format!("sh/{}", shape.element_id)); + range_record["hostKind"] = Value::String("textbox".to_string()); + return Ok(range_record); + } + } + PresentationElement::Table(table) => { + for (row_index, row) in table.rows.iter().enumerate() { + for (column_index, cell) in row.iter().enumerate() { + if let Some(range) = cell + .rich_text + .ranges + .iter() + .find(|range| range.range_id == range_id) + { + let mut range_record = text_range_to_proto(&cell.text, range); + range_record["kind"] = Value::String("textRange".to_string()); + range_record["id"] = Value::String(id.to_string()); + range_record["slide"] = Value::from(slide_index + 1); + range_record["slideIndex"] = Value::from(slide_index); + range_record["hostAnchor"] = Value::String(format!( + "tb/{}#cell/{row_index}/{column_index}", + table.element_id + )); + range_record["hostKind"] = + Value::String("tableCell".to_string()); + return Ok(range_record); + } + } + } + } + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Chart(_) => {} + } + } } } + if let Some(thread_id) = id.strip_prefix("th/") + && let Some(thread) = document + .comment_threads + .iter() + .find(|thread| thread.thread_id == thread_id) + { + let mut record = comment_thread_to_proto(thread); + record["id"] = Value::String(id.to_string()); + return Ok(record); + } + for layout in &document.layouts { let layout_id = format!("ly/{}", layout.layout_id); if id == layout_id { @@ -608,4 +869,3 @@ fn resolve_anchor( message: format!("unknown resolve id `{id}`"), }) } - diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs b/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs index 28682cb916..8539b62c76 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs @@ -122,6 +122,7 @@ impl PresentationArtifactManager { "get_style" => self.get_style(request), "describe_styles" => self.describe_styles(request), "set_notes" => self.set_notes(request), + "set_notes_rich_text" => self.set_notes_rich_text(request), "append_notes" => self.append_notes(request), "clear_notes" => self.clear_notes(request), "set_notes_visibility" => self.set_notes_visibility(request), @@ -133,13 +134,25 @@ impl PresentationArtifactManager { "add_image" => self.add_image(request, cwd), "replace_image" => self.replace_image(request, cwd), "add_table" => self.add_table(request), + "update_table_style" => self.update_table_style(request), + "style_table_block" => self.style_table_block(request), "update_table_cell" => self.update_table_cell(request), "merge_table_cells" => self.merge_table_cells(request), "add_chart" => self.add_chart(request), + "update_chart" => self.update_chart(request), + "add_chart_series" => self.add_chart_series(request), "update_text" => self.update_text(request), + "set_rich_text" => self.set_rich_text(request), + "format_text_range" => self.format_text_range(request), "replace_text" => self.replace_text(request), "insert_text_after" => self.insert_text_after(request), "set_hyperlink" => self.set_hyperlink(request), + "set_comment_author" => self.set_comment_author(request), + "add_comment_thread" => self.add_comment_thread(request), + "add_comment_reply" => self.add_comment_reply(request), + "toggle_comment_reaction" => self.toggle_comment_reaction(request), + "resolve_comment_thread" => self.resolve_comment_thread(request), + "reopen_comment_thread" => self.reopen_comment_thread(request), "update_shape_style" => self.update_shape_style(request), "bring_to_front" => self.bring_to_front(request), "send_to_back" => self.send_to_back(request), @@ -187,14 +200,24 @@ impl PresentationArtifactManager { ) -> Result { let args: ImportPptxArgs = parse_args(&request.action, &request.args)?; let path = resolve_path(cwd, &args.path); - let imported = Presentation::from_path(&path).map_err(|error| { - PresentationArtifactError::ImportFailed { + let document = if let Some(document) = import_codex_metadata_document(&path) + .map_err(|message| PresentationArtifactError::ImportFailed { path: path.clone(), - message: error.to_string(), - } - })?; - let mut document = PresentationDocument::from_ppt_rs(imported); - import_pptx_images(&path, &mut document, &request.action)?; + message, + })? + { + document + } else { + let imported = Presentation::from_path(&path).map_err(|error| { + PresentationArtifactError::ImportFailed { + path: path.clone(), + message: error.to_string(), + } + })?; + let mut document = PresentationDocument::from_ppt_rs(imported); + import_pptx_images(&path, &mut document, &request.action)?; + document + }; let artifact_id = document.artifact_id.clone(); let slide_count = document.slides.len(); let snapshot = snapshot_for_document(&document); @@ -287,6 +310,7 @@ impl PresentationArtifactManager { .ok_or_else(|| { index_out_of_range(&request.action, slide_index as usize, document.slides.len()) })?; + let slide_id = slide.slide_id.clone(); PresentationDocument { artifact_id: document.artifact_id.clone(), name: document.name.clone(), @@ -296,9 +320,25 @@ impl PresentationArtifactManager { layouts: Vec::new(), slides: vec![slide], active_slide_index: Some(0), + comment_self: document.comment_self.clone(), + comment_threads: document + .comment_threads + .iter() + .filter(|thread| match &thread.target { + CommentTarget::Slide { slide_id: target_slide_id } + | CommentTarget::Element { slide_id: target_slide_id, .. } + | CommentTarget::TextRange { slide_id: target_slide_id, .. } => { + target_slide_id == &slide_id + } + }) + .cloned() + .collect(), next_slide_seq: 1, next_element_seq: 1, next_layout_seq: 1, + next_text_range_seq: document.next_text_range_seq, + next_comment_thread_seq: document.next_comment_thread_seq, + next_comment_message_seq: document.next_comment_message_seq, } } else { document.clone() @@ -993,6 +1033,7 @@ impl PresentationArtifactManager { let document = self.get_document_mut(&artifact_id, &request.action)?; let slide = document.get_slide_mut(args.slide_index, &request.action)?; slide.notes.text = args.text.unwrap_or_default(); + slide.notes.rich_text = RichTextState::default(); Ok(PresentationArtifactResponse::new( artifact_id, request.action, @@ -1001,6 +1042,31 @@ impl PresentationArtifactManager { )) } + fn set_notes_rich_text( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetRichTextArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`slide_index` is required for notes rich text".to_string(), + })?; + let (text, mut rich_text) = + normalize_rich_text_input(document, args.text, &request.action)?; + rich_text.layout = normalize_text_layout(&args.text_layout, &request.action)?; + let slide = document.get_slide_mut(slide_index, &request.action)?; + slide.notes.text = text; + slide.notes.rich_text = rich_text; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich notes for slide {slide_index}"), + snapshot_for_document(document), + )) + } + fn append_notes( &mut self, request: PresentationArtifactRequest, @@ -1015,6 +1081,7 @@ impl PresentationArtifactManager { } else { slide.notes.text = format!("{}\n{text}", slide.notes.text); } + slide.notes.rich_text = RichTextState::default(); Ok(PresentationArtifactResponse::new( artifact_id, request.action, @@ -1032,6 +1099,7 @@ impl PresentationArtifactManager { let document = self.get_document_mut(&artifact_id, &request.action)?; let slide = document.get_slide_mut(args.slide_index, &request.action)?; slide.notes.text.clear(); + slide.notes.rich_text = RichTextState::default(); Ok(PresentationArtifactResponse::new( artifact_id, request.action, @@ -1261,6 +1329,7 @@ impl PresentationArtifactManager { .as_deref() .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) .transpose()?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; let element_id = document.next_element_id(); let slide = document.get_slide_mut(args.slide_index, &request.action)?; slide.elements.push(PresentationElement::Text(TextElement { @@ -1270,6 +1339,10 @@ impl PresentationArtifactManager { fill, style, hyperlink: None, + rich_text: RichTextState { + ranges: Vec::new(), + layout: text_layout, + }, placeholder: None, z_order: slide.elements.len(), })); @@ -1299,6 +1372,11 @@ impl PresentationArtifactManager { .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) .transpose()?; let stroke = parse_stroke(document, args.stroke, &request.action)?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; + let rich_text = args.text.as_ref().map(|_| RichTextState { + ranges: Vec::new(), + layout: text_layout, + }); let element_id = document.next_element_id(); let slide = document.get_slide_mut(args.slide_index, &request.action)?; slide @@ -1312,6 +1390,7 @@ impl PresentationArtifactManager { text: args.text, text_style, hyperlink: None, + rich_text, placeholder: None, rotation_degrees: args.rotation.or(args.position.rotation), flip_horizontal: args @@ -1552,6 +1631,8 @@ impl PresentationArtifactManager { let artifact_id = required_artifact_id(&request)?; let document = self.get_document_mut(&artifact_id, &request.action)?; let rows = coerce_table_rows(args.rows, &request.action)?; + let borders = parse_table_borders(document, args.borders, &request.action)?; + let style_options = parse_table_style_options(args.style_options); let mut frame: Rect = args.position.into(); let (column_widths, row_heights) = normalize_table_dimensions( &rows, @@ -1573,6 +1654,9 @@ impl PresentationArtifactManager { column_widths, row_heights, style: args.style, + style_options, + borders, + right_to_left: args.right_to_left.unwrap_or(false), merges: Vec::new(), z_order: slide.elements.len(), })); @@ -1622,6 +1706,7 @@ impl PresentationArtifactManager { cell.text = cell_value_to_string(args.value); cell.text_style = text_style; cell.background_fill = background_fill; + cell.rich_text = RichTextState::default(); cell.alignment = args .alignment .as_deref() @@ -1635,6 +1720,137 @@ impl PresentationArtifactManager { )) } + fn update_table_style( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdateTableStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let borders = parse_table_borders(document, args.borders, &request.action)?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a table", args.element_id), + }); + }; + table.style = args.style; + if let Some(borders) = borders { + if let Some(existing) = table.borders.as_mut() { + if borders.outside.is_some() { + existing.outside = borders.outside; + } + if borders.inside.is_some() { + existing.inside = borders.inside; + } + if borders.top.is_some() { + existing.top = borders.top; + } + if borders.bottom.is_some() { + existing.bottom = borders.bottom; + } + if borders.left.is_some() { + existing.left = borders.left; + } + if borders.right.is_some() { + existing.right = borders.right; + } + } else { + table.borders = Some(borders); + } + } + if let Some(style_options) = args.style_options { + if let Some(value) = style_options.header_row { + table.style_options.header_row = value; + } + if let Some(value) = style_options.banded_rows { + table.style_options.banded_rows = value; + } + if let Some(value) = style_options.banded_columns { + table.style_options.banded_columns = value; + } + if let Some(value) = style_options.first_column { + table.style_options.first_column = value; + } + if let Some(value) = style_options.last_column { + table.style_options.last_column = value; + } + if let Some(value) = style_options.total_row { + table.style_options.total_row = value; + } + } + if let Some(right_to_left) = args.right_to_left { + table.right_to_left = right_to_left; + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated table style for `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn style_table_block( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: StyleTableBlockArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let text_style = + normalize_text_style_with_document(document, &args.styling, &request.action)?; + let background_fill = args + .background_fill + .as_deref() + .map(|fill| { + normalize_color_with_document(document, fill, &request.action, "background_fill") + }) + .transpose()?; + let borders = parse_table_borders(document, args.borders, &request.action)?; + let alignment = args + .alignment + .as_deref() + .map(|value| parse_alignment(value, &request.action)) + .transpose()?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a table", args.element_id), + }); + }; + let end_row = (args.row + args.row_count) as usize; + let end_column = (args.column + args.column_count) as usize; + for row_index in args.row as usize..end_row { + if row_index >= table.rows.len() { + break; + } + for column_index in args.column as usize..end_column { + if column_index >= table.rows[row_index].len() { + break; + } + let cell = &mut table.rows[row_index][column_index]; + cell.text_style = text_style.clone(); + if let Some(fill) = background_fill.clone() { + cell.background_fill = Some(fill); + } + if let Some(alignment) = alignment { + cell.alignment = Some(alignment); + } + if let Some(borders) = borders.clone() { + cell.borders = Some(borders); + } + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Styled table block for `{}`", args.element_id), + snapshot_for_document(document), + )) + } + fn merge_table_cells( &mut self, request: PresentationArtifactRequest, @@ -1672,22 +1888,24 @@ impl PresentationArtifactManager { let artifact_id = required_artifact_id(&request)?; let document = self.get_document_mut(&artifact_id, &request.action)?; let chart_type = parse_chart_type(&args.chart_type, &request.action)?; - let series = args - .series - .into_iter() - .map(|entry| { - if entry.values.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("series `{}` must contain at least one value", entry.name), - }); - } - Ok(ChartSeriesSpec { - name: entry.name, - values: entry.values, - }) + let series = parse_chart_series(document, args.series, &request.action)?; + let legend_text_style = + normalize_text_style_with_document(document, &args.legend_text_style, &request.action)?; + let data_labels = parse_chart_data_labels(document, args.data_labels, &request.action)?; + let chart_fill = args + .chart_fill + .as_deref() + .map(|value| { + normalize_color_with_document(document, value, &request.action, "chart_fill") }) - .collect::, _>>()?; + .transpose()?; + let plot_area_fill = args + .plot_area_fill + .as_deref() + .map(|value| { + normalize_color_with_document(document, value, &request.action, "plot_area_fill") + }) + .transpose()?; let element_id = document.next_element_id(); let slide = document.get_slide_mut(args.slide_index, &request.action)?; slide @@ -1699,6 +1917,21 @@ impl PresentationArtifactManager { categories: args.categories, series, title: args.title, + style_index: args.style_index, + has_legend: args.has_legend.unwrap_or(false), + legend: Some(ChartLegend { + position: args.legend_position, + text_style: legend_text_style, + }), + x_axis: Some(ChartAxisSpec { + title: args.x_axis_title, + }), + y_axis: Some(ChartAxisSpec { + title: args.y_axis_title, + }), + data_labels, + chart_fill, + plot_area_fill, z_order: slide.elements.len(), })); Ok(PresentationArtifactResponse::new( @@ -1712,6 +1945,115 @@ impl PresentationArtifactManager { )) } + fn update_chart( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdateChartArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let legend_text_style = + normalize_text_style_with_document(document, &args.legend_text_style, &request.action)?; + let data_labels = parse_chart_data_labels(document, args.data_labels, &request.action)?; + let chart_fill = args + .chart_fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "chart_fill")) + .transpose()?; + let plot_area_fill = args + .plot_area_fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "plot_area_fill")) + .transpose()?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Chart(chart) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a chart", args.element_id), + }); + }; + if let Some(title) = args.title { + chart.title = Some(title); + } + if let Some(categories) = args.categories { + chart.categories = categories; + } + if let Some(style_index) = args.style_index { + chart.style_index = Some(style_index); + } + if let Some(has_legend) = args.has_legend { + chart.has_legend = has_legend; + } + if args.legend_position.is_some() || !text_style_is_empty(&legend_text_style) { + chart.legend = Some(ChartLegend { + position: args.legend_position, + text_style: legend_text_style, + }); + } + if args.x_axis_title.is_some() { + chart.x_axis = Some(ChartAxisSpec { + title: args.x_axis_title, + }); + } + if args.y_axis_title.is_some() { + chart.y_axis = Some(ChartAxisSpec { + title: args.y_axis_title, + }); + } + if data_labels.is_some() { + chart.data_labels = data_labels; + } + if chart_fill.is_some() { + chart.chart_fill = chart_fill; + } + if plot_area_fill.is_some() { + chart.plot_area_fill = plot_area_fill; + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated chart `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn add_chart_series( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddChartSeriesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let series = parse_chart_series( + document, + vec![ChartSeriesArgs { + name: args.name, + values: args.values, + categories: args.categories, + x_values: args.x_values, + fill: args.fill, + stroke: args.stroke, + marker: args.marker, + data_label_overrides: None, + }], + &request.action, + )?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Chart(chart) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a chart", args.element_id), + }); + }; + chart.series.extend(series); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added chart series to `{}`", args.element_id), + snapshot_for_document(document), + )) + } + fn update_text( &mut self, request: PresentationArtifactRequest, @@ -1726,6 +2068,7 @@ impl PresentationArtifactManager { .as_deref() .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) .transpose()?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; let element = document.find_element_mut(&args.element_id, &request.action)?; match element { PresentationElement::Text(text) => { @@ -1734,6 +2077,10 @@ impl PresentationArtifactManager { text.fill = Some(fill); } text.style = style; + text.rich_text = RichTextState { + ranges: Vec::new(), + layout: text_layout, + }; } PresentationElement::Shape(shape) => { if shape.text.is_none() { @@ -1750,6 +2097,10 @@ impl PresentationArtifactManager { shape.fill = Some(fill); } shape.text_style = style; + shape.rich_text = Some(RichTextState { + ranges: Vec::new(), + layout: text_layout, + }); } other => { return Err(PresentationArtifactError::UnsupportedFeature { @@ -1770,6 +2121,228 @@ impl PresentationArtifactManager { )) } + fn set_rich_text( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetRichTextArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let (text, mut rich_text) = + normalize_rich_text_input(document, args.text, &request.action)?; + rich_text.layout = normalize_text_layout(&args.text_layout, &request.action)?; + let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; + if args.notes.unwrap_or(false) { + let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`slide_index` is required for notes rich text".to_string(), + })?; + let slide = document.get_slide_mut(slide_index, &request.action)?; + slide.notes.text = text; + slide.notes.rich_text = rich_text; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich text for notes on slide {slide_index}"), + snapshot_for_document(document), + )); + } + if let Some(element_id) = args.element_id { + if let (Some(row), Some(column)) = (args.row, args.column) { + let element = document.find_element_mut(&element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{element_id}` is not a table"), + }); + }; + let row = row as usize; + let column = column as usize; + if row >= table.rows.len() || column >= table.rows[row].len() { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!("cell ({row}, {column}) is out of bounds"), + }); + } + let cell = &mut table.rows[row][column]; + cell.text = text; + cell.text_style = style; + cell.rich_text = rich_text; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich text for table cell ({row}, {column})"), + snapshot_for_document(document), + )); + } + let element = document.find_element_mut(&element_id, &request.action)?; + match element { + PresentationElement::Text(text_element) => { + text_element.text = text; + text_element.style = style; + text_element.rich_text = rich_text; + } + PresentationElement::Shape(shape) => { + if shape.text.is_none() { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{element_id}` does not contain editable text" + ), + }); + } + shape.text = Some(text); + shape.text_style = style; + shape.rich_text = Some(rich_text); + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{element_id}` is `{}`; only text-bearing elements support `set_rich_text`", + other.kind() + ), + }); + } + } + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich text for element `{element_id}`"), + snapshot_for_document(document), + )); + } + Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: "provide `element_id` or `slide_index` with `notes: true`".to_string(), + }) + } + + fn format_text_range( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: FormatTextRangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; + let hyperlink = args + .link + .as_ref() + .map(|link| parse_rich_text_link(link, &request.action)) + .transpose()?; + let layout = normalize_text_layout(&args.text_layout, &request.action)?; + let apply_annotation = + |range_id: String, + text: &str, + rich_text: &mut RichTextState| + -> Result<(), PresentationArtifactError> { + let (start_cp, length, _) = resolve_text_range_selector( + text, + args.query.as_deref(), + args.occurrence, + args.start_cp, + args.length, + &request.action, + )?; + rich_text.ranges.push(TextRangeAnnotation { + range_id, + start_cp, + length, + style: style.clone(), + hyperlink: hyperlink.clone(), + spacing_before: args.spacing_before.map(|value| value * 100), + spacing_after: args.spacing_after.map(|value| value * 100), + line_spacing: args.line_spacing, + }); + if layout.insets.is_some() + || layout.wrap.is_some() + || layout.auto_fit.is_some() + || layout.vertical_alignment.is_some() + { + rich_text.layout = layout.clone(); + } + Ok(()) + }; + if args.notes.unwrap_or(false) { + let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`slide_index` is required for notes text ranges".to_string(), + })?; + let range_id = document.next_text_range_id(); + let slide = document.get_slide_mut(slide_index, &request.action)?; + apply_annotation(range_id, &slide.notes.text, &mut slide.notes.rich_text)?; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Formatted notes text range on slide {slide_index}"), + snapshot_for_document(document), + )); + } + let element_id = args.element_id.clone().ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`element_id` is required unless formatting notes".to_string(), + })?; + if let (Some(row), Some(column)) = (args.row, args.column) { + let range_id = document.next_text_range_id(); + let element = document.find_element_mut(&element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{element_id}` is not a table"), + }); + }; + let row = row as usize; + let column = column as usize; + if row >= table.rows.len() || column >= table.rows[row].len() { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!("cell ({row}, {column}) is out of bounds"), + }); + } + let cell = &mut table.rows[row][column]; + apply_annotation(range_id, &cell.text, &mut cell.rich_text)?; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Formatted table cell text range ({row}, {column})"), + snapshot_for_document(document), + )); + } + let range_id = document.next_text_range_id(); + let element = document.find_element_mut(&element_id, &request.action)?; + match element { + PresentationElement::Text(text) => { + apply_annotation(range_id, &text.text, &mut text.rich_text)?; + } + PresentationElement::Shape(shape) => { + let text_value = shape.text.as_ref().ok_or_else(|| { + PresentationArtifactError::UnsupportedFeature { + action: request.action.clone(), + message: format!("element `{element_id}` does not contain editable text"), + } + })?; + let rich_text = shape.rich_text.get_or_insert_with(RichTextState::default); + apply_annotation(range_id, text_value, rich_text)?; + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{element_id}` is `{}`; only text-bearing elements support `format_text_range`", + other.kind() + ), + }); + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Formatted text range on element `{element_id}`"), + snapshot_for_document(document), + )) + } + fn replace_text( &mut self, request: PresentationArtifactRequest, @@ -1934,6 +2507,234 @@ impl PresentationArtifactManager { )) } + fn set_comment_author( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetCommentAuthorArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + document.comment_self = Some(CommentAuthorProfile { + display_name: args.display_name, + initials: args.initials, + email: args.email, + }); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + "Updated comment author".to_string(), + snapshot_for_document(document), + )) + } + + fn add_comment_thread( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddCommentThreadArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let author = document.comment_self.clone().ok_or_else(|| { + PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "set a comment author first with `set_comment_author`".to_string(), + } + })?; + let target = if let Some(slide_index) = args.slide_index { + let slide = document.get_slide_mut(slide_index, &request.action)?; + if let Some(element_id) = args.element_id { + if args.query.is_some() || args.start_cp.is_some() { + let (text, _rich_text) = lookup_text_target( + slide, + &element_id, + None, + None, + &request.action, + )?; + let (start_cp, length, context) = resolve_text_range_selector( + text, + args.query.as_deref(), + args.occurrence, + args.start_cp, + args.length, + &request.action, + )?; + CommentTarget::TextRange { + slide_id: slide.slide_id.clone(), + element_id: normalize_element_lookup_id(&element_id).to_string(), + start_cp, + length, + context, + } + } else { + CommentTarget::Element { + slide_id: slide.slide_id.clone(), + element_id: normalize_element_lookup_id(&element_id).to_string(), + } + } + } else { + CommentTarget::Slide { + slide_id: slide.slide_id.clone(), + } + } + } else { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: "`slide_index` is required for comment threads".to_string(), + }); + }; + let thread_id = document.next_comment_thread_id(); + let message_id = document.next_comment_message_id(); + document.comment_threads.push(CommentThread { + thread_id: thread_id.clone(), + target, + position: args.position.map(|position| CommentPosition { + x: position.x, + y: position.y, + }), + status: CommentThreadStatus::Active, + messages: vec![CommentMessage { + message_id, + author, + text: args.text, + created_at: "2026-03-03T00:00:00Z".to_string(), + reactions: Vec::new(), + }], + }); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added comment thread `{thread_id}`"), + snapshot_for_document(document), + )) + } + + fn add_comment_reply( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddCommentReplyArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let author = document.comment_self.clone().ok_or_else(|| { + PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "set a comment author first with `set_comment_author`".to_string(), + } + })?; + let message_id = document.next_comment_message_id(); + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + thread.messages.push(CommentMessage { + message_id, + author, + text: args.text, + created_at: "2026-03-03T00:00:00Z".to_string(), + reactions: Vec::new(), + }); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added reply to `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + + fn toggle_comment_reaction( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ToggleCommentReactionArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + let target_message_id = args + .message_id + .clone() + .or_else(|| thread.messages.last().map(|message| message.message_id.clone())) + .unwrap_or_default(); + let message = thread + .messages + .iter_mut() + .find(|message| message.message_id == target_message_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment message `{target_message_id}`"), + })?; + if let Some(index) = message.reactions.iter().position(|emoji| emoji == &args.emoji) { + message.reactions.remove(index); + } else { + message.reactions.push(args.emoji.clone()); + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Toggled reaction on `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + + fn resolve_comment_thread( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: CommentThreadIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + thread.status = CommentThreadStatus::Resolved; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Resolved `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + + fn reopen_comment_thread( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: CommentThreadIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + thread.status = CommentThreadStatus::Active; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Reopened `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + fn update_shape_style( &mut self, request: PresentationArtifactRequest, @@ -1951,6 +2752,11 @@ impl PresentationArtifactManager { .clone() .map(|value| parse_required_stroke(document, value, &request.action)) .transpose()?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; + let has_text_layout = text_layout.insets.is_some() + || text_layout.wrap.is_some() + || text_layout.auto_fit.is_some() + || text_layout.vertical_alignment.is_some(); let element = document.find_element_mut(&args.element_id, &request.action)?; match element { PresentationElement::Text(text) => { @@ -1960,6 +2766,9 @@ impl PresentationArtifactManager { if let Some(fill) = fill.clone() { text.fill = Some(fill); } + if has_text_layout { + text.rich_text.layout = text_layout; + } if args.stroke.is_some() || args.rotation.is_some() || args.flip_horizontal.is_some() @@ -2004,6 +2813,12 @@ impl PresentationArtifactManager { if let Some(flip_vertical) = args.flip_vertical.or(position_flip_vertical) { shape.flip_vertical = flip_vertical; } + if shape.text.is_some() && has_text_layout { + shape.rich_text = Some(RichTextState { + ranges: shape.rich_text.take().unwrap_or_default().ranges, + layout: text_layout, + }); + } } PresentationElement::Connector(connector) => { if args.fill.is_some() @@ -2348,3 +3163,41 @@ impl PresentationArtifactManager { Ok(patch) } } + +fn lookup_text_target<'a>( + slide: &'a PresentationSlide, + element_id: &str, + _row: Option, + _column: Option, + action: &str, +) -> Result<(&'a str, Option<&'a RichTextState>), PresentationArtifactError> { + let normalized_element_id = normalize_element_lookup_id(element_id); + let element = slide + .elements + .iter() + .find(|element| element.element_id() == normalized_element_id) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown element `{element_id}` on slide `{}`", slide.slide_id), + })?; + match element { + PresentationElement::Text(text) => Ok((&text.text, Some(&text.rich_text))), + PresentationElement::Shape(shape) => shape + .text + .as_deref() + .map(|text| (text, shape.rich_text.as_ref())) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("element `{element_id}` does not contain editable text"), + }), + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!( + "element `{element_id}` does not support text-range comments" + ), + }), + } +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/model.rs b/codex-rs/artifact-presentation/src/presentation_artifact/model.rs index 80a8566fa7..b5cd5d00a3 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/model.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/model.rs @@ -1,4 +1,4 @@ -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] struct ThemeState { color_scheme: HashMap, major_font: Option, @@ -27,13 +27,13 @@ impl ThemeState { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] enum LayoutKind { Layout, Master, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct LayoutDocument { layout_id: String, name: String, @@ -42,7 +42,7 @@ struct LayoutDocument { placeholders: Vec, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct PlaceholderDefinition { name: String, placeholder_type: String, @@ -52,19 +52,21 @@ struct PlaceholderDefinition { frame: Rect, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct ResolvedPlaceholder { source_layout_id: String, definition: PlaceholderDefinition, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] struct NotesState { text: String, visible: bool, + #[serde(default)] + rich_text: RichTextState, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] struct TextStyle { style_name: Option, font_size: Option, @@ -76,21 +78,21 @@ struct TextStyle { underline: bool, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct NamedTextStyle { name: String, style: TextStyle, built_in: bool, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct HyperlinkState { target: HyperlinkTarget, tooltip: Option, highlight_click: bool, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] enum HyperlinkTarget { Url(String), Slide(u32), @@ -217,7 +219,7 @@ impl HyperlinkState { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] enum TextAlignment { Left, @@ -226,14 +228,188 @@ enum TextAlignment { Justify, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct RichTextState { + #[serde(default)] + ranges: Vec, + #[serde(default)] + layout: TextLayoutState, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TextRangeAnnotation { + range_id: String, + start_cp: usize, + length: usize, + style: TextStyle, + hyperlink: Option, + spacing_before: Option, + spacing_after: Option, + line_spacing: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct TextLayoutState { + insets: Option, + wrap: Option, + auto_fit: Option, + vertical_alignment: Option, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +struct TextInsets { + left: u32, + right: u32, + top: u32, + bottom: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum TextWrapMode { + Square, + None, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum TextAutoFitMode { + None, + ShrinkText, + ResizeShapeToFitText, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum TextVerticalAlignment { + Top, + Middle, + Bottom, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentAuthorProfile { + display_name: String, + initials: String, + email: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentPosition { + x: u32, + y: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum CommentThreadStatus { + Active, + Resolved, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentMessage { + message_id: String, + author: CommentAuthorProfile, + text: String, + created_at: String, + #[serde(default)] + reactions: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +enum CommentTarget { + Slide { + slide_id: String, + }, + Element { + slide_id: String, + element_id: String, + }, + TextRange { + slide_id: String, + element_id: String, + start_cp: usize, + length: usize, + context: Option, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentThread { + thread_id: String, + target: CommentTarget, + position: Option, + status: CommentThreadStatus, + messages: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TableBorder { + color: String, + width: u32, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct TableBorders { + outside: Option, + inside: Option, + top: Option, + bottom: Option, + left: Option, + right: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct TableStyleOptions { + header_row: bool, + banded_rows: bool, + banded_columns: bool, + first_column: bool, + last_column: bool, + total_row: bool, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartMarkerStyle { + symbol: Option, + size: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartDataLabels { + show_value: bool, + show_category_name: bool, + show_leader_lines: bool, + position: Option, + text_style: TextStyle, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartLegend { + position: Option, + text_style: TextStyle, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartAxisSpec { + title: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartDataLabelOverride { + idx: usize, + text: Option, + position: Option, + text_style: TextStyle, + fill: Option, + stroke: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct PlaceholderRef { name: String, placeholder_type: String, index: Option, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct TableMergeRegion { start_row: usize, end_row: usize, @@ -241,15 +417,18 @@ struct TableMergeRegion { end_column: usize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct TableCellSpec { text: String, text_style: TextStyle, background_fill: Option, alignment: Option, + #[serde(default)] + rich_text: RichTextState, + borders: Option, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct PresentationDocument { artifact_id: String, name: Option, @@ -259,9 +438,16 @@ struct PresentationDocument { layouts: Vec, slides: Vec, active_slide_index: Option, + #[serde(default)] + comment_self: Option, + #[serde(default)] + comment_threads: Vec, next_slide_seq: u32, next_element_seq: u32, next_layout_seq: u32, + next_text_range_seq: u32, + next_comment_thread_seq: u32, + next_comment_message_seq: u32, } impl PresentationDocument { @@ -280,9 +466,14 @@ impl PresentationDocument { layouts: Vec::new(), slides: Vec::new(), active_slide_index: None, + comment_self: None, + comment_threads: Vec::new(), next_slide_seq: 1, next_element_seq: 1, next_layout_seq: 1, + next_text_range_seq: 1, + next_comment_thread_seq: 1, + next_comment_message_seq: 1, } } @@ -296,6 +487,7 @@ impl PresentationDocument { notes: NotesState { text: imported_slide.notes.clone().unwrap_or_default(), visible: true, + rich_text: RichTextState::default(), }, background_fill: None, layout_id: None, @@ -316,6 +508,7 @@ impl PresentationDocument { fill: None, style: TextStyle::default(), hyperlink: None, + rich_text: RichTextState::default(), placeholder: None, z_order: slide.elements.len(), })); @@ -334,6 +527,7 @@ impl PresentationDocument { fill: None, style: TextStyle::default(), hyperlink: None, + rich_text: RichTextState::default(), placeholder: None, z_order: slide.elements.len(), })); @@ -360,6 +554,10 @@ impl PresentationDocument { text: imported_shape.text.clone(), text_style: TextStyle::default(), hyperlink: None, + rich_text: imported_shape + .text + .as_ref() + .map(|_| RichTextState::default()), placeholder: None, rotation_degrees: imported_shape.rotation, flip_horizontal: false, @@ -390,6 +588,8 @@ impl PresentationDocument { text_style: TextStyle::default(), background_fill: None, alignment: None, + rich_text: RichTextState::default(), + borders: None, }) .collect() }) @@ -407,6 +607,9 @@ impl PresentationDocument { .map(emu_to_points) .collect(), style: None, + style_options: TableStyleOptions::default(), + borders: None, + right_to_left: false, merges: Vec::new(), z_order: slide.elements.len(), })); @@ -434,6 +637,7 @@ impl PresentationDocument { notes: NotesState { text: notes.unwrap_or_default(), visible: true, + rich_text: RichTextState::default(), }, background_fill: normalized_fill, layout_id: None, @@ -468,6 +672,24 @@ impl PresentationDocument { element_id } + fn next_text_range_id(&mut self) -> String { + let range_id = format!("range_{}", self.next_text_range_seq); + self.next_text_range_seq += 1; + range_id + } + + fn next_comment_thread_id(&mut self) -> String { + let thread_id = format!("thread_{}", self.next_comment_thread_seq); + self.next_comment_thread_seq += 1; + thread_id + } + + fn next_comment_message_id(&mut self) -> String { + let message_id = format!("message_{}", self.next_comment_message_seq); + self.next_comment_message_seq += 1; + message_id + } + fn total_element_count(&self) -> usize { self.slides.iter().map(|slide| slide.elements.len()).sum() } @@ -717,7 +939,7 @@ impl PresentationDocument { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct PresentationSlide { slide_id: String, notes: NotesState, @@ -1190,7 +1412,7 @@ impl PresentationSlide { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] enum PresentationElement { Text(TextElement), Shape(ShapeElement), @@ -1257,7 +1479,7 @@ impl PresentationElement { } } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct TextElement { element_id: String, text: String, @@ -1265,11 +1487,13 @@ struct TextElement { fill: Option, style: TextStyle, hyperlink: Option, + #[serde(default)] + rich_text: RichTextState, placeholder: Option, z_order: usize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct ShapeElement { element_id: String, geometry: ShapeGeometry, @@ -1279,6 +1503,7 @@ struct ShapeElement { text: Option, text_style: TextStyle, hyperlink: Option, + rich_text: Option, placeholder: Option, rotation_degrees: Option, flip_horizontal: bool, @@ -1286,7 +1511,7 @@ struct ShapeElement { z_order: usize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct ConnectorElement { element_id: String, connector_type: ConnectorKind, @@ -1301,7 +1526,7 @@ struct ConnectorElement { z_order: usize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct ImageElement { pub(crate) element_id: String, pub(crate) frame: Rect, @@ -1319,7 +1544,7 @@ pub(crate) struct ImageElement { pub(crate) z_order: usize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct TableElement { element_id: String, frame: Rect, @@ -1327,11 +1552,14 @@ struct TableElement { column_widths: Vec, row_heights: Vec, style: Option, + style_options: TableStyleOptions, + borders: Option, + right_to_left: bool, merges: Vec, z_order: usize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct ChartElement { element_id: String, frame: Rect, @@ -1339,10 +1567,18 @@ struct ChartElement { categories: Vec, series: Vec, title: Option, + style_index: Option, + has_legend: bool, + legend: Option, + x_axis: Option, + y_axis: Option, + data_labels: Option, + chart_fill: Option, + plot_area_fill: Option, z_order: usize, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct ImagePayload { pub(crate) bytes: Vec, pub(crate) format: String, @@ -1350,13 +1586,20 @@ pub(crate) struct ImagePayload { pub(crate) height_px: u32, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct ChartSeriesSpec { name: String, values: Vec, + categories: Option>, + x_values: Option>, + fill: Option, + stroke: Option, + marker: Option, + #[serde(default)] + data_label_overrides: Vec, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] enum ShapeGeometry { Rectangle, RoundedRectangle, @@ -1456,7 +1699,7 @@ impl ShapeGeometry { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] enum ChartTypeSpec { Bar, BarHorizontal, @@ -1580,7 +1823,7 @@ impl LineStyle { } } -#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub(crate) enum ImageFitMode { Stretch, @@ -1588,21 +1831,21 @@ pub(crate) enum ImageFitMode { Cover, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] struct StrokeStyle { color: String, width: u32, style: LineStyle, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] enum ConnectorKind { Straight, Elbow, Curved, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] enum ConnectorArrowKind { None, Triangle, @@ -1612,14 +1855,14 @@ enum ConnectorArrowKind { Open, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] enum ConnectorArrowScale { Small, Medium, Large, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] enum LineStyle { Solid, Dashed, @@ -1630,7 +1873,7 @@ enum LineStyle { LongDashDot, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub(crate) struct Rect { pub(crate) left: u32, pub(crate) top: u32, diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs b/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs index a5bc361e32..efca31a99b 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs @@ -169,6 +169,134 @@ fn parse_chart_type( } } +fn parse_chart_marker(marker: Option) -> ChartMarkerStyle { + marker + .map(|marker| ChartMarkerStyle { + symbol: marker.symbol, + size: marker.size, + }) + .unwrap_or_default() +} + +fn parse_chart_data_labels( + document: &PresentationDocument, + data_labels: Option, + action: &str, +) -> Result, PresentationArtifactError> { + data_labels + .map(|data_labels| { + Ok(ChartDataLabels { + show_value: data_labels.show_value.unwrap_or(false), + show_category_name: data_labels.show_category_name.unwrap_or(false), + show_leader_lines: data_labels.show_leader_lines.unwrap_or(false), + position: data_labels.position, + text_style: normalize_text_style_with_document( + document, + &data_labels.text_style, + action, + )?, + }) + }) + .transpose() +} + +fn parse_chart_series( + document: &PresentationDocument, + series: Vec, + action: &str, +) -> Result, PresentationArtifactError> { + series + .into_iter() + .map(|entry| { + if entry.values.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("series `{}` must contain at least one value", entry.name), + }); + } + let fill = entry + .fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, action, "series.fill")) + .transpose()?; + let stroke = entry + .stroke + .map(|stroke| { + Ok(StrokeStyle { + color: normalize_color_with_document( + document, + &stroke.color, + action, + "series.stroke.color", + )?, + width: stroke.width, + style: stroke + .style + .as_deref() + .map(|value| parse_line_style(value, action)) + .transpose()? + .unwrap_or(LineStyle::Solid), + }) + }) + .transpose()?; + let data_label_overrides = entry + .data_label_overrides + .unwrap_or_default() + .into_iter() + .map(|override_args| { + Ok(ChartDataLabelOverride { + idx: override_args.idx as usize, + text: override_args.text, + position: override_args.position, + text_style: normalize_text_style_with_document( + document, + &override_args.text_style, + action, + )?, + fill: override_args + .fill + .as_deref() + .map(|value| { + normalize_color_with_document(document, value, action, "fill") + }) + .transpose()?, + stroke: override_args + .stroke + .map(|stroke| { + Ok(StrokeStyle { + color: normalize_color_with_document( + document, + &stroke.color, + action, + "stroke.color", + )?, + width: stroke.width, + style: stroke + .style + .as_deref() + .map(|value| parse_line_style(value, action)) + .transpose()? + .unwrap_or(LineStyle::Solid), + }) + }) + .transpose()?, + }) + }) + .collect::, _>>()?; + Ok(ChartSeriesSpec { + name: entry.name, + values: entry.values, + categories: entry.categories, + x_values: entry.x_values, + fill, + stroke, + marker: Some(parse_chart_marker(entry.marker)), + data_label_overrides, + }) + }) + .collect() +} + fn parse_stroke( document: &PresentationDocument, stroke: Option, @@ -299,6 +427,216 @@ fn normalize_text_style_with_document( }) } +fn normalize_text_layout( + layout: &TextLayoutArgs, + action: &str, +) -> Result { + let wrap = layout + .wrap + .as_deref() + .map(|value| match value { + "square" => Ok(TextWrapMode::Square), + "none" => Ok(TextWrapMode::None), + _ => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported wrap `{value}`"), + }), + }) + .transpose()?; + let auto_fit = layout + .auto_fit + .as_deref() + .map(|value| match value { + "none" => Ok(TextAutoFitMode::None), + "shrinkText" | "shrink_text" => Ok(TextAutoFitMode::ShrinkText), + "resizeShapeToFitText" | "resize_shape_to_fit_text" => { + Ok(TextAutoFitMode::ResizeShapeToFitText) + } + _ => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported auto_fit `{value}`"), + }), + }) + .transpose()?; + let vertical_alignment = layout + .vertical_alignment + .as_deref() + .map(|value| match value { + "top" => Ok(TextVerticalAlignment::Top), + "middle" | "center" => Ok(TextVerticalAlignment::Middle), + "bottom" => Ok(TextVerticalAlignment::Bottom), + _ => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported vertical_alignment `{value}`"), + }), + }) + .transpose()?; + Ok(TextLayoutState { + insets: layout.insets.as_ref().map(|insets| TextInsets { + left: insets.left, + right: insets.right, + top: insets.top, + bottom: insets.bottom, + }), + wrap, + auto_fit, + vertical_alignment, + }) +} + +fn normalize_rich_text_input( + document: &PresentationDocument, + input: RichTextInput, + action: &str, +) -> Result<(String, RichTextState), PresentationArtifactError> { + let mut text = String::new(); + let mut ranges = Vec::new(); + let paragraphs = match input { + RichTextInput::Plain(value) => vec![RichParagraphInput::Plain(value)], + RichTextInput::Paragraphs(paragraphs) => paragraphs, + }; + for (paragraph_index, paragraph) in paragraphs.into_iter().enumerate() { + if paragraph_index > 0 { + text.push('\n'); + } + let paragraph_start = text.chars().count(); + match paragraph { + RichParagraphInput::Plain(value) => text.push_str(&value), + RichParagraphInput::Runs(runs) => { + for run in runs { + match run { + RichRunInput::Plain(value) => text.push_str(&value), + RichRunInput::Styled(value) => { + let start_cp = text.chars().count(); + text.push_str(&value.run); + let length = value.run.chars().count(); + let style = normalize_text_style_with_document( + document, + &value.text_style, + action, + )?; + let hyperlink = value + .link + .as_ref() + .map(|link| parse_rich_text_link(link, action)) + .transpose()?; + if length > 0 + && (!text_style_is_empty(&style) || hyperlink.is_some()) + { + ranges.push(TextRangeAnnotation { + range_id: format!("inline_{paragraph_index}_{start_cp}"), + start_cp, + length, + style, + hyperlink, + spacing_before: None, + spacing_after: None, + line_spacing: None, + }); + } + } + } + } + } + } + let paragraph_len = text.chars().count() - paragraph_start; + if paragraph_len == 0 { + continue; + } + } + Ok(( + text, + RichTextState { + ranges, + layout: TextLayoutState::default(), + }, + )) +} + +fn parse_rich_text_link( + link: &RichTextLinkInput, + action: &str, +) -> Result { + let uri = link + .uri + .as_ref() + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`link.uri` is required".to_string(), + })?; + let target = if link.is_external.unwrap_or(true) { + HyperlinkTarget::Url(uri.clone()) + } else { + HyperlinkTarget::File(uri.clone()) + }; + Ok(HyperlinkState { + target, + tooltip: None, + highlight_click: true, + }) +} + +fn text_style_is_empty(style: &TextStyle) -> bool { + style.style_name.is_none() + && style.font_size.is_none() + && style.font_family.is_none() + && style.color.is_none() + && style.alignment.is_none() + && !style.bold + && !style.italic + && !style.underline +} + +fn resolve_text_range_selector( + text: &str, + query: Option<&str>, + occurrence: Option, + start_cp: Option, + length: Option, + action: &str, +) -> Result<(usize, usize, Option), PresentationArtifactError> { + if let Some(query) = query { + let occurrence = occurrence.unwrap_or(0); + let haystack = text.chars().collect::>(); + let needle = query.chars().collect::>(); + if needle.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`query` must not be empty".to_string(), + }); + } + let mut matches = Vec::new(); + for start in 0..=haystack.len().saturating_sub(needle.len()) { + if haystack[start..start + needle.len()] == needle[..] { + matches.push(start); + } + } + let Some(found) = matches.get(occurrence).copied() else { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("query `{query}` occurrence {occurrence} was not found"), + }); + }; + return Ok((found, needle.len(), Some(query.to_string()))); + } + let start_cp = start_cp.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "provide either `query` or `start_cp`".to_string(), + })?; + let length = length.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`length` is required with `start_cp`".to_string(), + })?; + if start_cp + length > text.chars().count() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "text range is out of bounds".to_string(), + }); + } + Ok((start_cp, length, None)) +} + fn normalize_text_style_with_palette( theme: Option<&ThemeState>, styling: &TextStylingArgs, @@ -423,12 +761,82 @@ fn coerce_table_rows( text_style: TextStyle::default(), background_fill: None, alignment: None, + rich_text: RichTextState::default(), + borders: None, }) .collect() }) .collect()) } +fn parse_table_border( + document: &PresentationDocument, + border: &TableBorderArgs, + action: &str, + field: &str, +) -> Result { + Ok(TableBorder { + color: normalize_color_with_document(document, &border.color, action, field)?, + width: border.width, + }) +} + +fn parse_table_borders( + document: &PresentationDocument, + borders: Option, + action: &str, +) -> Result, PresentationArtifactError> { + borders + .map(|borders| { + Ok(TableBorders { + outside: borders + .outside + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.outside")) + .transpose()?, + inside: borders + .inside + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.inside")) + .transpose()?, + top: borders + .top + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.top")) + .transpose()?, + bottom: borders + .bottom + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.bottom")) + .transpose()?, + left: borders + .left + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.left")) + .transpose()?, + right: borders + .right + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.right")) + .transpose()?, + }) + }) + .transpose() +} + +fn parse_table_style_options(style_options: Option) -> TableStyleOptions { + style_options + .map(|style_options| TableStyleOptions { + header_row: style_options.header_row.unwrap_or(false), + banded_rows: style_options.banded_rows.unwrap_or(false), + banded_columns: style_options.banded_columns.unwrap_or(false), + first_column: style_options.first_column.unwrap_or(false), + last_column: style_options.last_column.unwrap_or(false), + total_row: style_options.total_row.unwrap_or(false), + }) + .unwrap_or_default() +} + fn normalize_table_dimensions( rows: &[Vec], frame: Rect, @@ -685,6 +1093,7 @@ fn materialize_placeholder_element( fill: None, style: TextStyle::default(), hyperlink: None, + rich_text: RichTextState::default(), placeholder: placeholder_ref, z_order, }) @@ -698,6 +1107,7 @@ fn materialize_placeholder_element( text: placeholder.text, text_style: TextStyle::default(), hyperlink: None, + rich_text: None, placeholder: placeholder_ref, rotation_degrees: None, flip_horizontal: false, @@ -861,4 +1271,3 @@ fn slide_placeholder_list( }) .collect() } - diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs b/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs index 1343ee84f6..a06abc7017 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs @@ -1,3 +1,21 @@ +const CODEX_METADATA_ENTRY: &str = "ppt/codex-document.json"; + +fn import_codex_metadata_document(path: &Path) -> Result, String> { + let file = std::fs::File::open(path).map_err(|error| error.to_string())?; + let mut archive = ZipArchive::new(file).map_err(|error| error.to_string())?; + let mut entry = match archive.by_name(CODEX_METADATA_ENTRY) { + Ok(entry) => entry, + Err(zip::result::ZipError::FileNotFound) => return Ok(None), + Err(error) => return Err(error.to_string()), + }; + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|error| error.to_string()) +} + fn build_pptx_bytes(document: &PresentationDocument, action: &str) -> Result, String> { let bytes = document .to_ppt_rs() @@ -211,6 +229,9 @@ fn patch_pptx_package( continue; } let name = file.name().to_string(); + if name == CODEX_METADATA_ENTRY { + continue; + } let options = file.options(); let mut bytes = Vec::new(); file.read_to_end(&mut bytes) @@ -282,6 +303,15 @@ fn patch_pptx_package( .map_err(|error| error.to_string())?; } + writer + .start_file(CODEX_METADATA_ENTRY, SimpleFileOptions::default()) + .map_err(|error| error.to_string())?; + writer + .write_all( + &serde_json::to_vec(document).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + writer .finish() .map_err(|error| error.to_string()) @@ -919,4 +949,3 @@ fn normalize_preview_quality( } Ok(quality) } - diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs b/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs index 23b6f7e2eb..05741303ac 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs @@ -35,6 +35,12 @@ fn document_to_proto( "masters": document.layouts.iter().filter(|layout| layout.kind == LayoutKind::Master).map(|layout| layout.layout_id.clone()).collect::>(), "layouts": layouts, "slides": slides, + "commentAuthor": document.comment_self.as_ref().map(comment_author_to_proto), + "commentThreads": document + .comment_threads + .iter() + .map(comment_thread_to_proto) + .collect::>(), })) } @@ -95,6 +101,7 @@ fn slide_to_proto(slide: &PresentationSlide, slide_index: usize) -> Value { "textPreview": slide.notes.text.replace('\n', " | "), "textChars": slide.notes.text.chars().count(), "textLines": slide.notes.text.lines().count(), + "richText": rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text), }), "elements": slide.elements.iter().map(element_to_proto).collect::>(), }) @@ -114,6 +121,7 @@ fn element_to_proto(element: &PresentationElement) -> Value { "textLines": text.text.lines().count(), "fill": text.fill, "style": text_style_to_proto(&text.style), + "richText": rich_text_to_proto(&text.text, &text.rich_text), "zOrder": text.z_order, }); if let Some(placeholder) = &text.placeholder { @@ -135,6 +143,12 @@ fn element_to_proto(element: &PresentationElement) -> Value { "stroke": shape.stroke.as_ref().map(stroke_to_proto), "text": shape.text, "textStyle": text_style_to_proto(&shape.text_style), + "richText": shape + .text + .as_ref() + .zip(shape.rich_text.as_ref()) + .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) + .unwrap_or(Value::Null), "rotation": shape.rotation_degrees, "flipHorizontal": shape.flip_horizontal, "flipVertical": shape.flip_vertical, @@ -215,6 +229,9 @@ fn element_to_proto(element: &PresentationElement) -> Value { "columnWidths": table.column_widths, "rowHeights": table.row_heights, "style": table.style, + "styleOptions": table_style_options_to_proto(&table.style_options), + "borders": table.borders.as_ref().map(table_borders_to_proto), + "rightToLeft": table.right_to_left, "merges": table.merges.iter().map(|merge| serde_json::json!({ "startRow": merge.start_row, "endRow": merge.end_row, @@ -231,9 +248,27 @@ fn element_to_proto(element: &PresentationElement) -> Value { "chartType": format!("{:?}", chart.chart_type), "title": chart.title, "categories": chart.categories, + "styleIndex": chart.style_index, + "hasLegend": chart.has_legend, + "legend": chart.legend.as_ref().map(chart_legend_to_proto), + "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), + "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), + "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), + "chartFill": chart.chart_fill, + "plotAreaFill": chart.plot_area_fill, "series": chart.series.iter().map(|series| serde_json::json!({ "name": series.name, "values": series.values, + "categories": series.categories, + "xValues": series.x_values, + "fill": series.fill, + "stroke": series.stroke.as_ref().map(stroke_to_proto), + "marker": series.marker.as_ref().map(chart_marker_to_proto), + "dataLabelOverrides": series + .data_label_overrides + .iter() + .map(chart_data_label_override_to_proto) + .collect::>(), })).collect::>(), "zOrder": chart.z_order, }), @@ -272,6 +307,72 @@ fn text_style_to_proto(style: &TextStyle) -> Value { }) } +fn rich_text_to_proto(text: &str, rich_text: &RichTextState) -> Value { + serde_json::json!({ + "layout": text_layout_to_proto(&rich_text.layout), + "ranges": rich_text + .ranges + .iter() + .map(|range| text_range_to_proto(text, range)) + .collect::>(), + }) +} + +fn text_range_to_proto(text: &str, range: &TextRangeAnnotation) -> Value { + serde_json::json!({ + "rangeId": range.range_id, + "anchor": format!("tr/{}", range.range_id), + "startCp": range.start_cp, + "length": range.length, + "text": text_slice_by_codepoint_range(text, range.start_cp, range.length), + "style": text_style_to_proto(&range.style), + "hyperlink": range.hyperlink.as_ref().map(HyperlinkState::to_json), + "spacingBefore": range.spacing_before, + "spacingAfter": range.spacing_after, + "lineSpacing": range.line_spacing, + }) +} + +fn text_layout_to_proto(layout: &TextLayoutState) -> Value { + serde_json::json!({ + "insets": layout.insets.map(|insets| serde_json::json!({ + "left": insets.left, + "right": insets.right, + "top": insets.top, + "bottom": insets.bottom, + "unit": "points", + })), + "wrap": layout.wrap.map(text_wrap_mode_to_proto), + "autoFit": layout.auto_fit.map(text_auto_fit_mode_to_proto), + "verticalAlignment": layout + .vertical_alignment + .map(text_vertical_alignment_to_proto), + }) +} + +fn text_wrap_mode_to_proto(mode: TextWrapMode) -> &'static str { + match mode { + TextWrapMode::Square => "square", + TextWrapMode::None => "none", + } +} + +fn text_auto_fit_mode_to_proto(mode: TextAutoFitMode) -> &'static str { + match mode { + TextAutoFitMode::None => "none", + TextAutoFitMode::ShrinkText => "shrinkText", + TextAutoFitMode::ResizeShapeToFitText => "resizeShapeToFitText", + } +} + +fn text_vertical_alignment_to_proto(alignment: TextVerticalAlignment) -> &'static str { + match alignment { + TextVerticalAlignment::Top => "top", + TextVerticalAlignment::Middle => "middle", + TextVerticalAlignment::Bottom => "bottom", + } +} + fn placeholder_ref_to_proto(placeholder: &PlaceholderRef) -> Value { serde_json::json!({ "name": placeholder.name, @@ -293,11 +394,169 @@ fn table_cell_to_proto(cell: &TableCellSpec) -> Value { serde_json::json!({ "text": cell.text, "textStyle": text_style_to_proto(&cell.text_style), + "richText": rich_text_to_proto(&cell.text, &cell.rich_text), "backgroundFill": cell.background_fill, "alignment": cell.alignment, + "borders": cell.borders.as_ref().map(table_borders_to_proto), }) } +fn table_style_options_to_proto(style_options: &TableStyleOptions) -> Value { + serde_json::json!({ + "headerRow": style_options.header_row, + "bandedRows": style_options.banded_rows, + "bandedColumns": style_options.banded_columns, + "firstColumn": style_options.first_column, + "lastColumn": style_options.last_column, + "totalRow": style_options.total_row, + }) +} + +fn table_borders_to_proto(borders: &TableBorders) -> Value { + serde_json::json!({ + "outside": borders.outside.as_ref().map(table_border_to_proto), + "inside": borders.inside.as_ref().map(table_border_to_proto), + "top": borders.top.as_ref().map(table_border_to_proto), + "bottom": borders.bottom.as_ref().map(table_border_to_proto), + "left": borders.left.as_ref().map(table_border_to_proto), + "right": borders.right.as_ref().map(table_border_to_proto), + }) +} + +fn table_border_to_proto(border: &TableBorder) -> Value { + serde_json::json!({ + "color": border.color, + "width": border.width, + "unit": "points", + }) +} + +fn chart_marker_to_proto(marker: &ChartMarkerStyle) -> Value { + serde_json::json!({ + "symbol": marker.symbol, + "size": marker.size, + }) +} + +fn chart_data_labels_to_proto(data_labels: &ChartDataLabels) -> Value { + serde_json::json!({ + "showValue": data_labels.show_value, + "showCategoryName": data_labels.show_category_name, + "showLeaderLines": data_labels.show_leader_lines, + "position": data_labels.position, + "textStyle": text_style_to_proto(&data_labels.text_style), + }) +} + +fn chart_legend_to_proto(legend: &ChartLegend) -> Value { + serde_json::json!({ + "position": legend.position, + "textStyle": text_style_to_proto(&legend.text_style), + }) +} + +fn chart_axis_to_proto(axis: &ChartAxisSpec) -> Value { + serde_json::json!({ + "title": axis.title, + }) +} + +fn chart_data_label_override_to_proto(override_spec: &ChartDataLabelOverride) -> Value { + serde_json::json!({ + "idx": override_spec.idx, + "text": override_spec.text, + "position": override_spec.position, + "textStyle": text_style_to_proto(&override_spec.text_style), + "fill": override_spec.fill, + "stroke": override_spec.stroke.as_ref().map(stroke_to_proto), + }) +} + +fn comment_author_to_proto(author: &CommentAuthorProfile) -> Value { + serde_json::json!({ + "displayName": author.display_name, + "initials": author.initials, + "email": author.email, + }) +} + +fn comment_thread_to_proto(thread: &CommentThread) -> Value { + serde_json::json!({ + "kind": "comment", + "threadId": thread.thread_id, + "anchor": format!("th/{}", thread.thread_id), + "target": comment_target_to_proto(&thread.target), + "position": thread.position.as_ref().map(comment_position_to_proto), + "status": comment_status_to_proto(thread.status), + "messages": thread.messages.iter().map(comment_message_to_proto).collect::>(), + }) +} + +fn comment_target_to_proto(target: &CommentTarget) -> Value { + match target { + CommentTarget::Slide { slide_id } => serde_json::json!({ + "type": "slide", + "slideId": slide_id, + "slideAnchor": format!("sl/{slide_id}"), + }), + CommentTarget::Element { + slide_id, + element_id, + } => serde_json::json!({ + "type": "element", + "slideId": slide_id, + "slideAnchor": format!("sl/{slide_id}"), + "elementId": element_id, + "elementAnchor": format!("sh/{element_id}"), + }), + CommentTarget::TextRange { + slide_id, + element_id, + start_cp, + length, + context, + } => serde_json::json!({ + "type": "textRange", + "slideId": slide_id, + "slideAnchor": format!("sl/{slide_id}"), + "elementId": element_id, + "elementAnchor": format!("sh/{element_id}"), + "startCp": start_cp, + "length": length, + "context": context, + }), + } +} + +fn comment_position_to_proto(position: &CommentPosition) -> Value { + serde_json::json!({ + "x": position.x, + "y": position.y, + "unit": "points", + }) +} + +fn comment_message_to_proto(message: &CommentMessage) -> Value { + serde_json::json!({ + "messageId": message.message_id, + "author": comment_author_to_proto(&message.author), + "text": message.text, + "createdAt": message.created_at, + "reactions": message.reactions, + }) +} + +fn comment_status_to_proto(status: CommentThreadStatus) -> &'static str { + match status { + CommentThreadStatus::Active => "active", + CommentThreadStatus::Resolved => "resolved", + } +} + +fn text_slice_by_codepoint_range(text: &str, start_cp: usize, length: usize) -> String { + text.chars().skip(start_cp).take(length).collect() +} + fn build_table_cell( cell: TableCellSpec, merges: &[TableMergeRegion], @@ -353,4 +612,3 @@ fn build_table_cell( } table_cell } - diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs b/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs index fde1ce85e3..8606649c38 100644 --- a/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs +++ b/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs @@ -42,7 +42,8 @@ fn slide_list(document: &PresentationDocument) -> Vec { slide_id: slide.slide_id.clone(), index, is_active: document.active_slide_index == Some(index), - notes: (!slide.notes.text.is_empty()).then(|| slide.notes.text.clone()), + notes: (slide.notes.visible && !slide.notes.text.is_empty()) + .then(|| slide.notes.text.clone()), notes_visible: slide.notes.visible, background_fill: slide.background_fill.clone(), layout_id: slide.layout_id.clone(), diff --git a/codex-rs/artifact-presentation/src/tests.rs b/codex-rs/artifact-presentation/src/tests.rs index 493e67a175..2ced6ad642 100644 --- a/codex-rs/artifact-presentation/src/tests.rs +++ b/codex-rs/artifact-presentation/src/tests.rs @@ -1954,6 +1954,15 @@ fn inspect_supports_filters_target_windows_and_shape_text_metadata() "italic": false, "underline": false }, + "richText": { + "layout": { + "insets": serde_json::Value::Null, + "wrap": serde_json::Value::Null, + "autoFit": serde_json::Value::Null, + "verticalAlignment": serde_json::Value::Null + }, + "ranges": [] + }, "rotation": serde_json::Value::Null, "flipHorizontal": false, "flipVertical": false, @@ -2816,6 +2825,441 @@ fn manager_supports_table_cell_updates_and_merges() -> Result<(), Box Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Parity Roundtrip" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + + let text_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Placeholder", + "position": { "left": 32, "top": 28, "width": 280, "height": 72 } + }), + }, + temp_dir.path(), + )?; + let text_id = text_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("text id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_rich_text".to_string(), + args: serde_json::json!({ + "element_id": text_id, + "text": [[ + { + "run": "Quarterly ", + "text_style": { "bold": true, "color": "#114488" } + }, + "update pipeline" + ]], + "text_layout": { + "wrap": "square", + "auto_fit": "shrinkText", + "vertical_alignment": "middle", + "insets": { "left": 6, "right": 6, "top": 4, "bottom": 4 } + } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "format_text_range".to_string(), + args: serde_json::json!({ + "element_id": text_id, + "query": "update", + "styling": { "italic": true }, + "link": { "uri": "https://example.com/update", "is_external": true } + }), + }, + temp_dir.path(), + )?; + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_comment_author".to_string(), + args: serde_json::json!({ + "display_name": "Jamie Fox", + "initials": "JF", + "email": "jamie@example.com" + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_comment_thread".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "element_id": text_id, + "query": "Quarterly", + "text": "Tighten this headline", + "position": { "x": 240, "y": 44 } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_comment_reply".to_string(), + args: serde_json::json!({ + "thread_id": "thread_1", + "text": "Applied to the slide draft." + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "toggle_comment_reaction".to_string(), + args: serde_json::json!({ + "thread_id": "thread_1", + "emoji": "eyes" + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve_comment_thread".to_string(), + args: serde_json::json!({ "thread_id": "thread_1" }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "reopen_comment_thread".to_string(), + args: serde_json::json!({ "thread_id": "thread_1" }), + }, + temp_dir.path(), + )?; + + let table_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_table".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 32, "top": 124, "width": 320, "height": 120 }, + "rows": [["Metric", "Value"], ["Status", "Beta"]], + "style": "TableStyleMedium2", + "style_options": { + "header_row": true, + "banded_rows": true, + "first_column": true + }, + "borders": { + "outside": { "color": "#222222", "width": 2 } + }, + "right_to_left": true + }), + }, + temp_dir.path(), + )?; + let table_id = table_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("table id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_table_style".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "style_options": { "last_column": true, "total_row": true }, + "borders": { + "inside": { "color": "#999999", "width": 1 } + } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "style_table_block".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "row": 1, + "column": 0, + "row_count": 1, + "column_count": 2, + "background_fill": "#FFF2CC", + "alignment": "center", + "styling": { "bold": true } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "format_text_range".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "row": 1, + "column": 1, + "query": "Beta", + "styling": { "italic": true, "color": "#AA0000" } + }), + }, + temp_dir.path(), + )?; + + let chart_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_chart".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 372, "top": 120, "width": 280, "height": 210 }, + "chart_type": "bar", + "categories": ["Q1", "Q2"], + "series": [{ + "name": "Revenue", + "values": [10.0, 12.0], + "fill": "#4472C4", + "stroke": { "color": "#1F4E79", "width": 2 }, + "marker": { "symbol": "circle", "size": 7 }, + "data_label_overrides": [{ + "idx": 1, + "text": "12M", + "position": "outsideEnd", + "fill": "#FFFFFF" + }] + }], + "title": "Revenue", + "style_index": 7, + "has_legend": true, + "legend_position": "right", + "legend_text_style": { "italic": true }, + "x_axis_title": "Quarter", + "y_axis_title": "USD", + "data_labels": { + "show_value": true, + "position": "outsideEnd", + "text_style": { "bold": true } + }, + "chart_fill": "#F8F8F8", + "plot_area_fill": "#FFFFFF" + }), + }, + temp_dir.path(), + )?; + let chart_id = chart_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("chart id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_chart".to_string(), + args: serde_json::json!({ + "element_id": chart_id, + "title": "Revenue outlook", + "style_index": 12, + "legend_position": "bottom", + "y_axis_title": "USD (millions)" + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_chart_series".to_string(), + args: serde_json::json!({ + "element_id": chart_id, + "name": "Target", + "values": [11.0, 13.0], + "fill": "#70AD47", + "marker": { "symbol": "diamond", "size": 6 } + }), + }, + temp_dir.path(), + )?; + + let export_path = temp_dir.path().join("parity-roundtrip.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + let metadata = zip_entry_text( + &temp_dir.path().join("parity-roundtrip.pptx"), + "ppt/codex-document.json", + )?; + assert!(metadata.contains("\"thread_id\":\"thread_1\"")); + assert!(metadata.contains("\"style_index\":12")); + assert!(metadata.contains("\"right_to_left\":true")); + + let imported = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "import_pptx".to_string(), + args: serde_json::json!({ "path": "parity-roundtrip.pptx" }), + }, + temp_dir.path(), + )?; + let imported_artifact_id = imported.artifact_id; + + let proto = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id.clone()), + action: "to_proto".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let proto = proto.proto_json.expect("proto"); + let comments = proto["commentThreads"].as_array().expect("comments"); + assert_eq!(comments.len(), 1); + assert_eq!(comments[0]["status"], "active"); + assert_eq!(comments[0]["messages"].as_array().map(Vec::len), Some(2)); + assert_eq!( + comments[0]["messages"][1]["reactions"], + serde_json::json!(["eyes"]) + ); + + let elements = proto["slides"][0]["elements"].as_array().expect("elements"); + let text_record = elements + .iter() + .find(|element| element["elementId"] == text_id) + .expect("text record"); + assert_eq!(text_record["richText"]["layout"]["wrap"], "square"); + assert_eq!(text_record["richText"]["layout"]["autoFit"], "shrinkText"); + assert_eq!( + text_record["richText"]["layout"]["verticalAlignment"], + "middle" + ); + assert_eq!( + text_record["richText"]["ranges"].as_array().map(Vec::len), + Some(2) + ); + assert!( + text_record["richText"]["ranges"] + .as_array() + .expect("text ranges") + .iter() + .any(|range| range["text"] == "update") + ); + + let table_record = elements + .iter() + .find(|element| element["elementId"] == table_id) + .expect("table record"); + assert_eq!(table_record["styleOptions"]["headerRow"], true); + assert_eq!(table_record["styleOptions"]["lastColumn"], true); + assert_eq!(table_record["rightToLeft"], true); + assert_eq!(table_record["borders"]["outside"]["color"], "222222"); + assert_eq!( + table_record["rows"][1][1]["richText"]["ranges"] + .as_array() + .map(Vec::len), + Some(1) + ); + + let chart_record = elements + .iter() + .find(|element| element["elementId"] == chart_id) + .expect("chart record"); + assert_eq!(chart_record["styleIndex"], 12); + assert_eq!(chart_record["legend"]["position"], "bottom"); + assert_eq!(chart_record["series"].as_array().map(Vec::len), Some(2)); + assert_eq!(chart_record["series"][1]["name"], "Target"); + + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let inspect_ndjson = inspect.inspect_ndjson.expect("inspect"); + assert!(inspect_ndjson.contains("\"kind\":\"comment\"")); + assert!(inspect_ndjson.contains("\"kind\":\"textRange\"")); + assert!(inspect_ndjson.contains("\"chartType\":\"Bar\"")); + + let resolved_thread = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": "th/thread_1" }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_thread + .resolved_record + .as_ref() + .and_then(|record| record.get("target")) + .and_then(|target| target.get("type")), + Some(&serde_json::json!("textRange")) + ); + + let resolved_range = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": "tr/range_1" }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_range + .resolved_record + .as_ref() + .and_then(|record| record.get("text")), + Some(&serde_json::json!("update")) + ); + Ok(()) +} + #[test] fn history_can_undo_and_redo_created_artifact() -> Result<(), Box> { let temp_dir = tempfile::tempdir()?; @@ -2971,160 +3415,32 @@ fn proto_and_patch_actions_work_and_patch_history_is_atomic() }, temp_dir.path(), )?; + let proto = proto.proto_json.expect("proto"); + assert_eq!(proto["kind"], "presentation"); + assert_eq!(proto["artifactId"], artifact_id); + assert_eq!(proto["activeSlideId"], slide_id); + assert_eq!(proto["commentAuthor"], serde_json::Value::Null); + assert_eq!(proto["commentThreads"], serde_json::json!([])); + assert_eq!(proto["masters"], serde_json::json!([])); + assert_eq!(proto["layouts"], serde_json::json!([])); + assert_eq!(proto["theme"]["hexColorMap"], serde_json::json!({})); + assert_eq!(proto["styles"].as_array().map(Vec::len), Some(5)); + assert_eq!(proto["slides"].as_array().map(Vec::len), Some(1)); + assert_eq!(proto["slides"][0]["slideId"], slide_id); + assert_eq!(proto["slides"][0]["backgroundFill"], "FFEECC"); assert_eq!( - proto.proto_json, - Some(serde_json::json!({ - "kind": "presentation", - "artifactId": artifact_id, - "anchor": format!("pr/{artifact_id}"), - "name": "Proto Patch", - "slideSize": { - "left": 0, - "top": 0, - "width": 720, - "height": 540, - "unit": "points" - }, - "activeSlideIndex": 0, - "activeSlideId": slide_id, - "theme": { - "colorScheme": {}, - "hexColorMap": {}, - "majorFont": serde_json::Value::Null, - "minorFont": serde_json::Value::Null - }, - "styles": [ - { - "kind": "textStyle", - "id": "st/body", - "name": "body", - "builtIn": true, - "style": { - "styleName": "body", - "fontSize": 14, - "fontFamily": serde_json::Value::Null, - "color": serde_json::Value::Null, - "alignment": "left", - "bold": false, - "italic": false, - "underline": false - } - }, - { - "kind": "textStyle", - "id": "st/heading1", - "name": "heading1", - "builtIn": true, - "style": { - "styleName": "heading1", - "fontSize": 22, - "fontFamily": serde_json::Value::Null, - "color": serde_json::Value::Null, - "alignment": "left", - "bold": true, - "italic": false, - "underline": false - } - }, - { - "kind": "textStyle", - "id": "st/list", - "name": "list", - "builtIn": true, - "style": { - "styleName": "list", - "fontSize": 14, - "fontFamily": serde_json::Value::Null, - "color": serde_json::Value::Null, - "alignment": "left", - "bold": false, - "italic": false, - "underline": false - } - }, - { - "kind": "textStyle", - "id": "st/numberedlist", - "name": "numberedlist", - "builtIn": true, - "style": { - "styleName": "numberedlist", - "fontSize": 14, - "fontFamily": serde_json::Value::Null, - "color": serde_json::Value::Null, - "alignment": "left", - "bold": false, - "italic": false, - "underline": false - } - }, - { - "kind": "textStyle", - "id": "st/title", - "name": "title", - "builtIn": true, - "style": { - "styleName": "title", - "fontSize": 28, - "fontFamily": serde_json::Value::Null, - "color": serde_json::Value::Null, - "alignment": "left", - "bold": true, - "italic": false, - "underline": false - } - } - ], - "masters": [], - "layouts": [], - "slides": [ - { - "slideId": slide_id, - "anchor": format!("sl/{slide_id}"), - "index": 0, - "layoutId": serde_json::Value::Null, - "backgroundFill": "FFEECC", - "notes": { - "anchor": format!("nt/{slide_id}"), - "text": "", - "visible": true, - "textPreview": "", - "textChars": 0, - "textLines": 0 - }, - "elements": [ - { - "kind": "text", - "elementId": element_id, - "anchor": format!("sh/{element_id}"), - "frame": { - "left": 40, - "top": 60, - "width": 180, - "height": 50, - "unit": "points" - }, - "text": "Patch text", - "textPreview": "Patch text", - "textChars": 10, - "textLines": 1, - "fill": serde_json::Value::Null, - "style": { - "styleName": serde_json::Value::Null, - "fontSize": serde_json::Value::Null, - "fontFamily": serde_json::Value::Null, - "color": serde_json::Value::Null, - "alignment": serde_json::Value::Null, - "bold": false, - "italic": false, - "underline": false - }, - "zOrder": 0 - } - ] - } - ] - })) + proto["slides"][0]["notes"]["richText"]["ranges"], + serde_json::json!([]) + ); + assert_eq!( + proto["slides"][0]["elements"].as_array().map(Vec::len), + Some(1) + ); + assert_eq!(proto["slides"][0]["elements"][0]["elementId"], element_id); + assert_eq!(proto["slides"][0]["elements"][0]["text"], "Patch text"); + assert_eq!( + proto["slides"][0]["elements"][0]["richText"]["ranges"], + serde_json::json!([]) ); let undone = manager.execute( @@ -3191,6 +3507,6 @@ fn proto_and_patch_actions_work_and_patch_history_is_atomic() }, temp_dir.path(), )?; - assert_eq!(redone_proto.proto_json, proto.proto_json); + assert_eq!(redone_proto.proto_json, Some(proto)); Ok(()) } diff --git a/codex-rs/core/templates/tools/presentation_artifact.md b/codex-rs/core/templates/tools/presentation_artifact.md index 5c63c2e044..45a91bc43b 100644 --- a/codex-rs/core/templates/tools/presentation_artifact.md +++ b/codex-rs/core/templates/tools/presentation_artifact.md @@ -32,6 +32,7 @@ Supported actions: - `get_style` - `describe_styles` - `set_notes` +- `set_notes_rich_text` - `append_notes` - `clear_notes` - `set_notes_visibility` @@ -48,13 +49,25 @@ Supported actions: - `add_image` - `replace_image` - `add_table` +- `update_table_style` +- `style_table_block` - `update_table_cell` - `merge_table_cells` - `add_chart` +- `update_chart` +- `add_chart_series` - `update_text` +- `set_rich_text` +- `format_text_range` - `replace_text` - `insert_text_after` - `set_hyperlink` +- `set_comment_author` +- `add_comment_thread` +- `add_comment_reply` +- `toggle_comment_reaction` +- `resolve_comment_thread` +- `reopen_comment_thread` - `update_shape_style` - `bring_to_front` - `send_to_back` @@ -73,7 +86,7 @@ Example edit: Example sequential batch: `{"actions":[{"action":"create","args":{"name":"Quarterly Update"}},{"action":"add_slide","args":{}},{"action":"add_text_shape","args":{"slide_index":0,"text":"Revenue up 24%","position":{"left":48,"top":72,"width":260,"height":80}}}]}` -Table creation also accepts optional `column_widths` and `row_heights` arrays in points when you need explicit table sizing instead of even splits. +Table creation also accepts optional `column_widths` and `row_heights` arrays in points when you need explicit table sizing instead of even splits. Tables also support `style_options`, `borders`, and `right_to_left`, with `update_table_style` and `style_table_block` available for incremental styling after creation. Example export: `{"artifact_id":"presentation_x","actions":[{"action":"export_pptx","args":{"path":"artifacts/q2-update.pptx"}}]}` @@ -94,7 +107,7 @@ Layout references in `create_layout.parent_layout_id`, `add_layout_placeholder.l `insert_slide` accepts `index` or `after_slide_index`. If neither is provided, the new slide is inserted immediately after the active slide, or appended if no active slide is set yet. Example inspect: -`{"artifact_id":"presentation_x","actions":[{"action":"inspect","args":{"include":"deck,slide,textbox,shape,table,chart,image,notes,layoutList","exclude":"notes","search":"roadmap","max_chars":12000}}]}` +`{"artifact_id":"presentation_x","actions":[{"action":"inspect","args":{"include":"deck,slide,textbox,shape,table,chart,image,notes,layoutList,textRange,comment","exclude":"notes","search":"roadmap","max_chars":12000}}]}` Example inspect target window: `{"artifact_id":"presentation_x","actions":[{"action":"inspect","args":{"include":"textbox","target":{"id":"sh/element_3","before_lines":1,"after_lines":1}}}]}` @@ -107,6 +120,14 @@ Example proto export: `to_proto` returns a full JSON snapshot of the current in-memory presentation document, including slide/layout records, anchors, notes, theme state, and typed element payloads. +Rich text is supported on notes, text boxes, shapes with text, and table cells. Use `set_rich_text` to replace a full rich-text payload, `set_notes_rich_text` for speaker notes, and `format_text_range` to annotate a substring by `query` or explicit codepoint range. `inspect`, `resolve`, and `to_proto` surface text-range anchors as `tr/`. + +Comment threads are supported through `set_comment_author`, `add_comment_thread`, `add_comment_reply`, `toggle_comment_reaction`, `resolve_comment_thread`, and `reopen_comment_thread`. Thread anchors resolve as `th/`, and comment records appear in both `inspect` and `to_proto`. + +Charts support richer series metadata plus `update_chart` and `add_chart_series`, including legend, axis, data-label, marker, fill, and per-point override state. + +Exported PPTX files embed Codex metadata so rich text, comment threads, and advanced table/chart state round-trip through `export_pptx` and `import_pptx` even when the base OOXML representation is lossy. + Example patch recording: `{"artifact_id":"presentation_x","actions":[{"action":"record_patch","args":{"operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}]}` @@ -136,10 +157,19 @@ Text styling payloads on `add_text_shape`, `add_shape.text_style`, `update_text. Text-bearing elements also support literal `replace_text` and `insert_text_after` helpers for in-place edits without resending the full string. +Example rich text update: +`{"artifact_id":"presentation_x","actions":[{"action":"set_rich_text","args":{"element_id":"element_3","text":[[{"run":"Quarterly ","text_style":{"bold":true}},"update pipeline"]],"text_layout":{"wrap":"square","auto_fit":"shrinkText","vertical_alignment":"middle","insets":{"left":6,"right":6,"top":4,"bottom":4}}}}]}` + +Example substring formatting: +`{"artifact_id":"presentation_x","actions":[{"action":"format_text_range","args":{"element_id":"element_3","query":"update","styling":{"italic":true},"link":{"uri":"https://example.com/update","is_external":true}}}]}` + Text boxes and shapes support whole-element hyperlinks via `set_hyperlink`. Supported `link_type` values are `url`, `slide`, `first_slide`, `last_slide`, `next_slide`, `previous_slide`, `end_show`, `email`, and `file`. Use `clear: true` to remove an existing hyperlink. Notes visibility is honored on export: `set_notes_visibility` controls whether speaker notes are emitted into exported PPTX output. +Example comment thread: +`{"artifact_id":"presentation_x","actions":[{"action":"set_comment_author","args":{"display_name":"Jamie Fox","initials":"JF"}},{"action":"add_comment_thread","args":{"slide_index":0,"element_id":"element_3","query":"Quarterly","text":"Tighten this headline"}},{"action":"add_comment_reply","args":{"thread_id":"thread_1","text":"Applied to the draft."}}]}` + Image placeholders can be prompt-only. `add_image` accepts `prompt` without `path`/`data_url`, and unresolved placeholders export as a visible placeholder box instead of failing. Layout placeholders with `placeholder_type: "picture"` or `"image"` materialize as placeholder image elements on slides, so they appear in `list_slide_placeholders`, `inspect`, and `resolve` as `image` records rather than generic shapes. @@ -158,6 +188,9 @@ Shape strokes accept an optional `style` field such as `solid`, `dashed`, `dotte Connectors are supported via `add_connector`, with straight/elbow/curved types plus dash styles and arrow heads. +Example chart update: +`{"artifact_id":"presentation_x","actions":[{"action":"update_chart","args":{"element_id":"element_7","style_index":12,"legend_position":"bottom","y_axis_title":"USD (millions)"}},{"action":"add_chart_series","args":{"element_id":"element_7","name":"Target","values":[11,13],"fill":"#70AD47","marker":{"symbol":"diamond","size":6}}}]}` + Example preview: `{"artifact_id":"presentation_x","actions":[{"action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.png"}}]}` From 8159f05dfd1e2ce70a9dbc043fbbfe1da8782860 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 3 Mar 2026 15:27:37 +0000 Subject: [PATCH 331/385] feat: wire spreadsheet artifact (#13362) --- codex-rs/Cargo.lock | 1 + codex-rs/artifact-spreadsheet/src/chart.rs | 16 +- .../artifact-spreadsheet/src/conditional.rs | 12 + codex-rs/artifact-spreadsheet/src/lib.rs | 8 + codex-rs/artifact-spreadsheet/src/manager.rs | 788 ++++++++++++++++++ codex-rs/artifact-spreadsheet/src/model.rs | 42 +- codex-rs/artifact-spreadsheet/src/table.rs | 17 +- codex-rs/core/Cargo.toml | 1 + codex-rs/core/src/codex.rs | 14 +- codex-rs/core/src/state/session.rs | 11 +- codex-rs/core/src/tools/handlers/mod.rs | 2 + .../tools/handlers/spreadsheet_artifact.rs | 235 ++++++ codex-rs/core/src/tools/spec.rs | 56 +- 13 files changed, 1180 insertions(+), 23 deletions(-) create mode 100644 codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 77dcbd75c0..62d2ffae3b 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1802,6 +1802,7 @@ dependencies = [ "codex-apply-patch", "codex-arg0", "codex-artifact-presentation", + "codex-artifact-spreadsheet", "codex-async-utils", "codex-client", "codex-config", diff --git a/codex-rs/artifact-spreadsheet/src/chart.rs b/codex-rs/artifact-spreadsheet/src/chart.rs index 34f6dd7c9a..83b02b6be1 100644 --- a/codex-rs/artifact-spreadsheet/src/chart.rs +++ b/codex-rs/artifact-spreadsheet/src/chart.rs @@ -64,7 +64,7 @@ pub struct SpreadsheetChart { } #[derive(Debug, Clone, Default)] -pub struct SpreadsheetChartLookup<'a> { +pub struct SpreadsheetChartLookup { pub id: Option, pub index: Option, } @@ -101,7 +101,6 @@ impl SpreadsheetSheet { .transpose() .ok() .flatten() - .flatten() .is_some_and(|chart_range| chart_range.intersects(target)) }) }) @@ -112,7 +111,7 @@ impl SpreadsheetSheet { pub fn get_chart( &self, action: &str, - lookup: SpreadsheetChartLookup<'_>, + lookup: SpreadsheetChartLookup, ) -> Result<&SpreadsheetChart, SpreadsheetArtifactError> { if let Some(id) = lookup.id { return self @@ -221,7 +220,7 @@ impl SpreadsheetSheet { pub fn add_chart_series( &mut self, action: &str, - lookup: SpreadsheetChartLookup<'_>, + lookup: SpreadsheetChartLookup, mut series: SpreadsheetChartSeries, ) -> Result { validate_chart_series(action, &series)?; @@ -235,7 +234,7 @@ impl SpreadsheetSheet { pub fn delete_chart( &mut self, action: &str, - lookup: SpreadsheetChartLookup<'_>, + lookup: SpreadsheetChartLookup, ) -> Result<(), SpreadsheetArtifactError> { let index = if let Some(id) = lookup.id { self.charts @@ -267,7 +266,7 @@ impl SpreadsheetSheet { pub fn set_chart_properties( &mut self, action: &str, - lookup: SpreadsheetChartLookup<'_>, + lookup: SpreadsheetChartLookup, properties: SpreadsheetChartProperties, ) -> Result<(), SpreadsheetArtifactError> { let chart = self.get_chart_mut(action, lookup)?; @@ -307,7 +306,7 @@ impl SpreadsheetSheet { fn get_chart_mut( &mut self, action: &str, - lookup: SpreadsheetChartLookup<'_>, + lookup: SpreadsheetChartLookup, ) -> Result<&mut SpreadsheetChart, SpreadsheetArtifactError> { if let Some(id) = lookup.id { return self @@ -320,11 +319,12 @@ impl SpreadsheetSheet { }); } if let Some(index) = lookup.index { + let len = self.charts.len(); return self.charts.get_mut(index).ok_or_else(|| { SpreadsheetArtifactError::IndexOutOfRange { action: action.to_string(), index, - len: self.charts.len(), + len, } }); } diff --git a/codex-rs/artifact-spreadsheet/src/conditional.rs b/codex-rs/artifact-spreadsheet/src/conditional.rs index be6e9cd5b1..96c0c8ebd8 100644 --- a/codex-rs/artifact-spreadsheet/src/conditional.rs +++ b/codex-rs/artifact-spreadsheet/src/conditional.rs @@ -128,6 +128,18 @@ impl SpreadsheetConditionalFormatCollection { } impl SpreadsheetArtifact { + pub fn validate_conditional_formats( + &self, + action: &str, + sheet_name: &str, + ) -> Result<(), SpreadsheetArtifactError> { + let sheet = self.sheet_lookup(action, Some(sheet_name), None)?; + for format in &sheet.conditional_formats { + validate_conditional_format(self, format, action)?; + } + Ok(()) + } + pub fn add_conditional_format( &mut self, action: &str, diff --git a/codex-rs/artifact-spreadsheet/src/lib.rs b/codex-rs/artifact-spreadsheet/src/lib.rs index f39c9cd42b..bd9f6ed8fb 100644 --- a/codex-rs/artifact-spreadsheet/src/lib.rs +++ b/codex-rs/artifact-spreadsheet/src/lib.rs @@ -1,18 +1,26 @@ mod address; +mod chart; +mod conditional; mod error; mod formula; mod manager; mod model; +mod pivot; mod render; mod style; +mod table; mod xlsx; #[cfg(test)] mod tests; pub use address::*; +pub use chart::*; +pub use conditional::*; pub use error::*; pub use manager::*; pub use model::*; +pub use pivot::*; pub use render::*; pub use style::*; +pub use table::*; diff --git a/codex-rs/artifact-spreadsheet/src/manager.rs b/codex-rs/artifact-spreadsheet/src/manager.rs index 98a2a045a7..392b685c48 100644 --- a/codex-rs/artifact-spreadsheet/src/manager.rs +++ b/codex-rs/artifact-spreadsheet/src/manager.rs @@ -113,6 +113,26 @@ impl SpreadsheetArtifactManager { "list_sheets" => self.list_sheets(request), "get_sheet" => self.get_sheet(request), "inspect" => self.inspect(request), + "list_charts" => self.list_charts(request), + "get_chart" => self.get_chart(request), + "create_chart" => self.create_chart(request), + "add_chart_series" => self.add_chart_series(request), + "set_chart_properties" => self.set_chart_properties(request), + "delete_chart" => self.delete_chart(request), + "list_tables" => self.list_tables(request), + "get_table" => self.get_table(request), + "create_table" => self.create_table(request), + "set_table_style" => self.set_table_style(request), + "clear_table_filters" => self.clear_table_filters(request), + "reapply_table_filters" => self.reapply_table_filters(request), + "rename_table_column" => self.rename_table_column(request), + "set_table_column_totals" => self.set_table_column_totals(request), + "delete_table" => self.delete_table(request), + "list_conditional_formats" => self.list_conditional_formats(request), + "add_conditional_format" => self.add_conditional_format(request), + "delete_conditional_format" => self.delete_conditional_format(request), + "list_pivot_tables" => self.list_pivot_tables(request), + "get_pivot_table" => self.get_pivot_table(request), "create_sheet" => self.create_sheet(request), "rename_sheet" => self.rename_sheet(request), "delete_sheet" => self.delete_sheet(request), @@ -493,6 +513,632 @@ impl SpreadsheetArtifactManager { Ok(response) } + fn list_charts( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let charts = sheet.list_charts(range.as_ref())?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} charts on `{}`", charts.len(), sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.chart_list = Some(charts); + Ok(response) + } + + fn get_chart( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: ChartLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let chart = sheet + .get_chart(&request.action, chart_lookup_from_args(&args))? + .clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved chart `{}` from `{}`", chart.id, sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn create_chart( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateChartArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + if let Some(source_sheet_name) = args.source_sheet_name.as_deref() { + artifact.sheet_lookup(&request.action, Some(source_sheet_name), None)?; + } + let source_range = CellRange::parse(&args.source_range)?; + let chart = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let chart_id = sheet.create_chart( + &request.action, + args.chart_type, + args.source_sheet_name.or_else(|| Some(sheet.name.clone())), + &source_range, + args.options.unwrap_or_default(), + )?; + sheet + .get_chart( + &request.action, + crate::SpreadsheetChartLookup { + id: Some(chart_id), + index: None, + }, + )? + .clone() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created chart `{}`", chart.id), + snapshot_for_artifact(artifact), + ); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn add_chart_series( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: AddChartSeriesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let chart = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let series_id = sheet.add_chart_series( + &request.action, + crate::SpreadsheetChartLookup { + id: args.chart_id, + index: args.chart_index.map(|value| value as usize), + }, + args.series, + )?; + let chart = sheet.get_chart( + &request.action, + crate::SpreadsheetChartLookup { + id: args.chart_id.or(Some(series_id).and(None)), + index: args.chart_index.map(|value| value as usize), + }, + ); + match chart { + Ok(chart) => chart.clone(), + Err(_) => sheet + .get_chart( + &request.action, + crate::SpreadsheetChartLookup { + id: None, + index: args.chart_index.map(|value| value as usize), + }, + )? + .clone(), + } + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Added chart series to chart `{}`", chart.id), + snapshot_for_artifact(artifact), + ); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn set_chart_properties( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetChartPropertiesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let chart = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + let lookup = chart_lookup_from_args(&args.lookup); + sheet.set_chart_properties(&request.action, lookup.clone(), args.properties)?; + sheet.get_chart(&request.action, lookup)?.clone() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Updated chart `{}`", chart.id), + snapshot_for_artifact(artifact), + ); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn delete_chart( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: ChartLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let name = sheet.name.clone(); + sheet.delete_chart(&request.action, chart_lookup_from_args(&args))?; + name + }; + let action = request.action.clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Deleted chart from `{sheet_name}`"), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![ + artifact + .sheet_lookup(&action, Some(&sheet_name), None)? + .summary(), + ]); + Ok(response) + } + + fn list_tables( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let tables = sheet.list_tables(range.as_ref())?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} tables on `{}`", tables.len(), sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.table_list = Some(tables); + Ok(response) + } + + fn get_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let table = sheet.get_table_view(&request.action, table_lookup_from_args(&args))?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved table `{}` from `{}`", table.name, sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn create_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateTableArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let table_id = sheet.create_table(&request.action, &range, args.options)?; + sheet.get_table_view( + &request.action, + crate::SpreadsheetTableLookup { + name: None, + display_name: None, + id: Some(table_id), + }, + )? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created table `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn set_table_style( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetTableStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + let lookup = table_lookup_from_args(&args.lookup); + sheet.set_table_style(&request.action, lookup.clone(), args.options)?; + sheet.get_table_view(&request.action, lookup)? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Updated table style for `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn clear_table_filters( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let lookup = table_lookup_from_args(&args); + sheet.clear_table_filters(&request.action, lookup.clone())?; + sheet.get_table_view(&request.action, lookup)? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Cleared table filters for `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn reapply_table_filters( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let lookup = table_lookup_from_args(&args); + sheet.reapply_table_filters(&request.action, lookup.clone())?; + sheet.get_table_view(&request.action, lookup)? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Reapplied table filters for `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn rename_table_column( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: RenameTableColumnArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let column = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + sheet.rename_table_column( + &request.action, + table_lookup_from_args(&args.lookup), + args.column_id, + args.column_name.as_deref(), + args.new_name, + )? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Renamed table column to `{}`", column.name), + snapshot_for_artifact(artifact), + ); + response.serialized_dict = Some(to_serialized_value(column)?); + Ok(response) + } + + fn set_table_column_totals( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetTableColumnTotalsArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let column = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + sheet.set_table_column_totals( + &request.action, + table_lookup_from_args(&args.lookup), + args.column_id, + args.column_name.as_deref(), + args.totals_row_label, + args.totals_row_function, + )? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Updated totals metadata for column `{}`", column.name), + snapshot_for_artifact(artifact), + ); + response.serialized_dict = Some(to_serialized_value(column)?); + Ok(response) + } + + fn delete_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let name = sheet.name.clone(); + sheet.delete_table(&request.action, table_lookup_from_args(&args))?; + name + }; + let action = request.action.clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Deleted table from `{sheet_name}`"), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![ + artifact + .sheet_lookup(&action, Some(&sheet_name), None)? + .summary(), + ]); + Ok(response) + } + + fn list_conditional_formats( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let formats = sheet.list_conditional_formats(range.as_ref()); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Listed {} conditional formats on `{}`", + formats.len(), + sheet.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.conditional_format_list = Some(formats); + Ok(response) + } + + fn add_conditional_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: AddConditionalFormatArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = artifact + .sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )? + .name + .clone(); + let format_id = + artifact.add_conditional_format(&request.action, &sheet_name, args.format)?; + let format = artifact + .sheet_lookup(&request.action, Some(&sheet_name), None)? + .conditional_formats + .iter() + .find(|entry| entry.id == format_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::Serialization { + message: format!("created conditional format `{format_id}` was not available"), + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created conditional format `{format_id}`"), + snapshot_for_artifact(artifact), + ); + response.conditional_format_list = Some(vec![format]); + Ok(response) + } + + fn delete_conditional_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: DeleteConditionalFormatArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = artifact + .sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )? + .name + .clone(); + artifact.delete_conditional_format(&request.action, &sheet_name, args.id)?; + let action = request.action.clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Deleted conditional format `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![ + artifact + .sheet_lookup(&action, Some(&sheet_name), None)? + .summary(), + ]); + Ok(response) + } + + fn list_pivot_tables( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let pivots = sheet.list_pivot_tables(range.as_ref())?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} pivot tables on `{}`", pivots.len(), sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.pivot_table_list = Some(pivots); + Ok(response) + } + + fn get_pivot_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: PivotTableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let pivot = sheet + .get_pivot_table(&request.action, pivot_lookup_from_args(&args))? + .clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Retrieved pivot table `{}` from `{}`", + pivot.name, sheet.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.pivot_table_list = Some(vec![pivot]); + Ok(response) + } + fn rename_sheet( &mut self, request: SpreadsheetArtifactRequest, @@ -776,6 +1422,7 @@ impl SpreadsheetArtifactManager { sheet.cleanup_and_validate_sheet()?; sheet.summary() }; + artifact.validate_conditional_formats(&request.action, &sheet_summary.name)?; let mut response = SpreadsheetArtifactResponse::new( artifact_id, request.action, @@ -2006,6 +2653,14 @@ pub struct SpreadsheetArtifactResponse { #[serde(skip_serializing_if = "Option::is_none")] pub sheet_list: Option>, #[serde(skip_serializing_if = "Option::is_none")] + pub chart_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub table_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub conditional_format_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub pivot_table_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] pub sheet_ref: Option, #[serde(skip_serializing_if = "Option::is_none")] pub cell_ref: Option, @@ -2056,6 +2711,10 @@ impl SpreadsheetArtifactResponse { artifact_snapshot: Some(artifact_snapshot), workbook_summary: None, sheet_list: None, + chart_list: None, + table_list: None, + conditional_format_list: None, + pivot_table_list: None, sheet_ref: None, cell_ref: None, range_ref: None, @@ -2097,6 +2756,10 @@ pub struct SpreadsheetSheetSnapshot { pub filled_columns: usize, pub minimum_range_filled: String, pub merged_range_count: usize, + pub chart_count: usize, + pub table_count: usize, + pub conditional_format_count: usize, + pub pivot_table_count: usize, } #[derive(Debug, Deserialize)] @@ -2137,6 +2800,105 @@ struct SheetLookupArgs { range: Option, } +#[derive(Debug, Deserialize)] +struct ChartLookupArgs { + sheet_name: Option, + sheet_index: Option, + chart_id: Option, + chart_index: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateChartArgs { + sheet_name: Option, + sheet_index: Option, + chart_type: crate::SpreadsheetChartType, + source_sheet_name: Option, + source_range: String, + options: Option, +} + +#[derive(Debug, Deserialize)] +struct AddChartSeriesArgs { + sheet_name: Option, + sheet_index: Option, + chart_id: Option, + chart_index: Option, + series: crate::SpreadsheetChartSeries, +} + +#[derive(Debug, Deserialize)] +struct SetChartPropertiesArgs { + #[serde(flatten)] + lookup: ChartLookupArgs, + properties: crate::SpreadsheetChartProperties, +} + +#[derive(Debug, Deserialize)] +struct TableLookupArgs { + sheet_name: Option, + sheet_index: Option, + name: Option, + display_name: Option, + id: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateTableArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + options: crate::SpreadsheetCreateTableOptions, +} + +#[derive(Debug, Deserialize)] +struct SetTableStyleArgs { + #[serde(flatten)] + lookup: TableLookupArgs, + options: crate::SpreadsheetTableStyleOptions, +} + +#[derive(Debug, Deserialize)] +struct RenameTableColumnArgs { + #[serde(flatten)] + lookup: TableLookupArgs, + column_id: Option, + column_name: Option, + new_name: String, +} + +#[derive(Debug, Deserialize)] +struct SetTableColumnTotalsArgs { + #[serde(flatten)] + lookup: TableLookupArgs, + column_id: Option, + column_name: Option, + totals_row_label: Option, + totals_row_function: Option, +} + +#[derive(Debug, Deserialize)] +struct AddConditionalFormatArgs { + sheet_name: Option, + sheet_index: Option, + format: crate::SpreadsheetConditionalFormat, +} + +#[derive(Debug, Deserialize)] +struct DeleteConditionalFormatArgs { + sheet_name: Option, + sheet_index: Option, + id: u32, +} + +#[derive(Debug, Deserialize)] +struct PivotTableLookupArgs { + sheet_name: Option, + sheet_index: Option, + name: Option, + index: Option, +} + #[derive(Debug, Deserialize)] struct CreateSheetArgs { name: String, @@ -2444,11 +3206,37 @@ fn snapshot_for_artifact(artifact: &SpreadsheetArtifact) -> SpreadsheetArtifactS filled_columns: sheet.filled_columns(), minimum_range_filled: sheet.minimum_range_filled(), merged_range_count: sheet.merged_ranges.len(), + chart_count: sheet.charts.len(), + table_count: sheet.tables.len(), + conditional_format_count: sheet.conditional_formats.len(), + pivot_table_count: sheet.pivot_tables.len(), }) .collect(), } } +fn chart_lookup_from_args(args: &ChartLookupArgs) -> crate::SpreadsheetChartLookup { + crate::SpreadsheetChartLookup { + id: args.chart_id, + index: args.chart_index.map(|value| value as usize), + } +} + +fn table_lookup_from_args(args: &TableLookupArgs) -> crate::SpreadsheetTableLookup<'_> { + crate::SpreadsheetTableLookup { + name: args.name.as_deref(), + display_name: args.display_name.as_deref(), + id: args.id, + } +} + +fn pivot_lookup_from_args(args: &PivotTableLookupArgs) -> crate::SpreadsheetPivotTableLookup<'_> { + crate::SpreadsheetPivotTableLookup { + name: args.name.as_deref(), + index: args.index.map(|value| value as usize), + } +} + fn sheet_reference(sheet: &crate::SpreadsheetSheet) -> SpreadsheetSheetRef { SpreadsheetSheetRef { sheet_name: sheet.name.clone(), diff --git a/codex-rs/artifact-spreadsheet/src/model.rs b/codex-rs/artifact-spreadsheet/src/model.rs index 228943a566..747eedbcea 100644 --- a/codex-rs/artifact-spreadsheet/src/model.rs +++ b/codex-rs/artifact-spreadsheet/src/model.rs @@ -457,6 +457,10 @@ pub struct SpreadsheetSheetSummary { pub default_column_width: Option, pub show_grid_lines: bool, pub merged_range_count: usize, + pub chart_count: usize, + pub table_count: usize, + pub conditional_format_count: usize, + pub pivot_table_count: usize, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -504,6 +508,14 @@ pub struct SpreadsheetSheet { pub cells: BTreeMap, #[serde(default)] pub merged_ranges: Vec, + #[serde(default)] + pub charts: Vec, + #[serde(default)] + pub tables: Vec, + #[serde(default)] + pub conditional_formats: Vec, + #[serde(default)] + pub pivot_tables: Vec, pub default_row_height: Option, pub default_column_width: Option, pub show_grid_lines: bool, @@ -569,6 +581,10 @@ impl SpreadsheetSheet { name, cells: BTreeMap::new(), merged_ranges: Vec::new(), + charts: Vec::new(), + tables: Vec::new(), + conditional_formats: Vec::new(), + pivot_tables: Vec::new(), default_row_height: None, default_column_width: None, show_grid_lines: true, @@ -679,6 +695,10 @@ impl SpreadsheetSheet { default_column_width: self.default_column_width, show_grid_lines: self.show_grid_lines, merged_range_count: self.merged_ranges.len(), + chart_count: self.charts.len(), + table_count: self.tables.len(), + conditional_format_count: self.conditional_formats.len(), + pivot_table_count: self.pivot_tables.len(), } } @@ -1303,6 +1323,9 @@ impl SpreadsheetSheet { } } } + self.validate_tables("cleanup_and_validate_sheet")?; + self.validate_charts("cleanup_and_validate_sheet")?; + self.validate_pivot_tables("cleanup_and_validate_sheet")?; Ok(()) } @@ -1718,7 +1741,24 @@ impl SpreadsheetArtifact { } match selected.as_str() { - "xlsx" => write_xlsx(self, path), + "xlsx" => { + for sheet in &self.sheets { + if !sheet.charts.is_empty() + || !sheet.tables.is_empty() + || !sheet.conditional_formats.is_empty() + || !sheet.pivot_tables.is_empty() + { + return Err(SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: format!( + "xlsx export does not yet support charts, tables, conditional formats, or pivot tables on sheet `{}`; use json or bin export instead", + sheet.name + ), + }); + } + } + write_xlsx(self, path) + } "json" => { let json = self.to_json()?; std::fs::write(path, json).map_err(|error| { diff --git a/codex-rs/artifact-spreadsheet/src/table.rs b/codex-rs/artifact-spreadsheet/src/table.rs index b714a20c21..be04c188e2 100644 --- a/codex-rs/artifact-spreadsheet/src/table.rs +++ b/codex-rs/artifact-spreadsheet/src/table.rs @@ -181,7 +181,12 @@ impl SpreadsheetSheet { range: &CellRange, options: SpreadsheetCreateTableOptions, ) -> Result { - validate_table_geometry(action, range, options.header_row_count, options.totals_row_count)?; + validate_table_geometry( + action, + range, + options.header_row_count, + options.totals_row_count, + )?; for table in &self.tables { let table_range = table.range()?; if table_range.intersects(range) { @@ -368,7 +373,12 @@ impl SpreadsheetSheet { let mut seen_display_names = BTreeSet::new(); for table in &self.tables { let range = table.range()?; - validate_table_geometry(action, &range, table.header_row_count, table.totals_row_count)?; + validate_table_geometry( + action, + &range, + table.header_row_count, + table.totals_row_count, + )?; if !seen_names.insert(table.name.clone()) { return Err(SpreadsheetArtifactError::InvalidArgs { action: action.to_string(), @@ -565,7 +575,8 @@ fn build_table_columns( fn unique_table_column_names(names: Vec) -> Vec { let mut seen = BTreeMap::::new(); - names.into_iter() + names + .into_iter() .map(|name| { let entry = seen.entry(name.clone()).or_insert(0); *entry += 1; diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 9eb88c66c3..c3a37bb989 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -43,6 +43,7 @@ codex-keyring-store = { workspace = true } codex-network-proxy = { workspace = true } codex-otel = { workspace = true } codex-artifact-presentation = { workspace = true } +codex-artifact-spreadsheet = { workspace = true } codex-protocol = { workspace = true } codex-rmcp-client = { workspace = true } codex-state = { workspace = true } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 1e6c72c0c6..7b540aa4d8 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -58,6 +58,9 @@ use chrono::Utc; use codex_artifact_presentation::PresentationArtifactError; use codex_artifact_presentation::PresentationArtifactExecutionRequest; use codex_artifact_presentation::PresentationArtifactResponse; +use codex_artifact_spreadsheet::SpreadsheetArtifactError; +use codex_artifact_spreadsheet::SpreadsheetArtifactRequest; +use codex_artifact_spreadsheet::SpreadsheetArtifactResponse; use codex_hooks::HookEvent; use codex_hooks::HookEventAfterAgent; use codex_hooks::HookPayload; @@ -1786,7 +1789,16 @@ impl Session { cwd: &Path, ) -> Result { let mut state = self.state.lock().await; - state.presentation_artifacts.execute_requests(request, cwd) + state.artifacts.presentation.execute_requests(request, cwd) + } + + pub(crate) async fn execute_spreadsheet_artifact( + &self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let mut state = self.state.lock().await; + state.artifacts.spreadsheet.execute(request, cwd) } async fn record_initial_history(&self, conversation_history: InitialHistory) { diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 822af421b2..babfb044d8 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -1,6 +1,7 @@ //! Session-wide mutable state. use codex_artifact_presentation::PresentationArtifactManager; +use codex_artifact_spreadsheet::SpreadsheetArtifactManager; use codex_protocol::models::ResponseItem; use std::collections::HashMap; use std::collections::HashSet; @@ -17,6 +18,12 @@ use crate::tasks::RegularTask; use crate::truncate::TruncationPolicy; use codex_protocol::protocol::TurnContextItem; +#[derive(Default)] +pub(crate) struct SessionArtifacts { + pub(crate) presentation: PresentationArtifactManager, + pub(crate) spreadsheet: SpreadsheetArtifactManager, +} + /// Persistent, session-scoped state previously stored directly on `Session`. pub(crate) struct SessionState { pub(crate) session_configuration: SessionConfiguration, @@ -33,7 +40,7 @@ pub(crate) struct SessionState { pub(crate) startup_regular_task: Option>>, pub(crate) active_mcp_tool_selection: Option>, pub(crate) active_connector_selection: HashSet, - pub(crate) presentation_artifacts: PresentationArtifactManager, + pub(crate) artifacts: SessionArtifacts, } impl SessionState { @@ -51,7 +58,7 @@ impl SessionState { startup_regular_task: None, active_mcp_tool_selection: None, active_connector_selection: HashSet::new(), - presentation_artifacts: PresentationArtifactManager::default(), + artifacts: SessionArtifacts::default(), } } diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index 49127df10d..908f3d18d0 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -13,6 +13,7 @@ mod read_file; mod request_user_input; mod search_tool_bm25; mod shell; +mod spreadsheet_artifact; mod test_sync; pub(crate) mod unified_exec; mod view_image; @@ -48,6 +49,7 @@ pub(crate) use search_tool_bm25::SEARCH_TOOL_BM25_TOOL_NAME; pub use search_tool_bm25::SearchToolBm25Handler; pub use shell::ShellCommandHandler; pub use shell::ShellHandler; +pub use spreadsheet_artifact::SpreadsheetArtifactHandler; pub use test_sync::TestSyncHandler; pub use unified_exec::UnifiedExecHandler; pub use view_image::ViewImageHandler; diff --git a/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs b/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs new file mode 100644 index 0000000000..be4eb7fc58 --- /dev/null +++ b/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs @@ -0,0 +1,235 @@ +use async_trait::async_trait; +use codex_artifact_spreadsheet::PathAccessKind; +use codex_artifact_spreadsheet::PathAccessRequirement; +use codex_artifact_spreadsheet::SpreadsheetArtifactError; +use codex_artifact_spreadsheet::SpreadsheetArtifactRequest; +use codex_protocol::models::FunctionCallOutputBody; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::ReviewDecision; +use serde_json::to_string; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use crate::codex::Session; +use crate::codex::TurnContext; +use crate::features::Feature; +use crate::function_tool::FunctionCallError; +use crate::path_utils::normalize_for_path_comparison; +use crate::path_utils::resolve_symlink_write_paths; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolOutput; +use crate::tools::context::ToolPayload; +use crate::tools::handlers::parse_arguments; +use crate::tools::registry::ToolHandler; +use crate::tools::registry::ToolKind; +use crate::tools::sandboxing::with_cached_approval; + +pub struct SpreadsheetArtifactHandler; + +#[async_trait] +impl ToolHandler for SpreadsheetArtifactHandler { + fn kind(&self) -> ToolKind { + ToolKind::Function + } + + async fn is_mutating(&self, _invocation: &ToolInvocation) -> bool { + true + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + + if !session.enabled(Feature::Artifact) { + return Err(FunctionCallError::RespondToModel( + "spreadsheet_artifact is disabled by feature flag".to_string(), + )); + } + + let arguments = match payload { + ToolPayload::Function { arguments } => arguments, + _ => { + return Err(FunctionCallError::RespondToModel( + "spreadsheet_artifact handler received unsupported payload".to_string(), + )); + } + }; + + let request: SpreadsheetArtifactRequest = parse_arguments(&arguments)?; + for access in request + .required_path_accesses(&turn.cwd) + .map_err(spreadsheet_error)? + { + authorize_path_access(session.as_ref(), turn.as_ref(), &call_id, &access).await?; + } + + let response = session + .execute_spreadsheet_artifact(request, &turn.cwd) + .await + .map_err(spreadsheet_error)?; + + Ok(ToolOutput::Function { + body: FunctionCallOutputBody::Text(to_string(&response).map_err(|error| { + FunctionCallError::RespondToModel(format!( + "failed to serialize spreadsheet_artifact response: {error}" + )) + })?), + success: Some(true), + }) + } +} + +fn spreadsheet_error(error: SpreadsheetArtifactError) -> FunctionCallError { + FunctionCallError::RespondToModel(error.to_string()) +} + +async fn authorize_path_access( + session: &Session, + turn: &TurnContext, + call_id: &str, + access: &PathAccessRequirement, +) -> Result<(), FunctionCallError> { + let effective_path = match access.kind { + PathAccessKind::Read => effective_read_path(&access.path), + PathAccessKind::Write => effective_write_path(&access.path), + }; + let allowed = match access.kind { + PathAccessKind::Read => path_is_readable(turn, &effective_path), + PathAccessKind::Write => path_is_writable(turn, &effective_path), + }; + if allowed { + return Ok(()); + } + + let approval_policy = turn.approval_policy.value(); + if !matches!( + approval_policy, + AskForApproval::OnRequest | AskForApproval::UnlessTrusted + ) { + return Err(FunctionCallError::RespondToModel(format!( + "{} path `{}` is outside the current sandbox policy", + access_kind_label(access.kind), + access.path.display() + ))); + } + + let key = format!( + "spreadsheet_artifact:{:?}:{}", + access.kind, + effective_path.display() + ); + let path = access.path.clone(); + let action = access.action.clone(); + let decision = + with_cached_approval(&session.services, "spreadsheet_artifact", vec![key], || { + let path = path.clone(); + let action = action.clone(); + async move { + session + .request_command_approval( + turn, + call_id.to_string(), + None, + vec![ + "spreadsheet_artifact".to_string(), + action, + path.display().to_string(), + ], + turn.cwd.clone(), + Some(format!( + "Allow spreadsheet_artifact to {} `{}`?", + access_kind_verb(access.kind), + path.display() + )), + None, + None, + None, + None, + ) + .await + } + }) + .await; + + if matches!( + decision, + ReviewDecision::Approved + | ReviewDecision::ApprovedForSession + | ReviewDecision::ApprovedExecpolicyAmendment { .. } + ) { + return Ok(()); + } + + Err(FunctionCallError::RespondToModel(format!( + "{} path `{}` was not approved", + access_kind_label(access.kind), + access.path.display() + ))) +} + +fn path_is_readable(turn: &TurnContext, path: &Path) -> bool { + if turn.sandbox_policy.has_full_disk_read_access() { + return true; + } + + turn.sandbox_policy + .get_readable_roots_with_cwd(&turn.cwd) + .iter() + .any(|root| path.starts_with(root.as_path())) +} + +fn path_is_writable(turn: &TurnContext, path: &Path) -> bool { + if turn.sandbox_policy.has_full_disk_write_access() { + return true; + } + + turn.sandbox_policy + .get_writable_roots_with_cwd(&turn.cwd) + .iter() + .any(|root| root.is_path_writable(path)) +} + +fn effective_read_path(path: &Path) -> PathBuf { + normalize_for_path_comparison(path).unwrap_or_else(|_| normalize_without_fs(path)) +} + +fn effective_write_path(path: &Path) -> PathBuf { + let write_path = resolve_symlink_write_paths(path) + .map(|paths| paths.write_path) + .unwrap_or_else(|_| path.to_path_buf()); + normalize_for_path_comparison(&write_path).unwrap_or_else(|_| normalize_without_fs(&write_path)) +} + +fn normalize_without_fs(path: &Path) -> PathBuf { + let mut normalized = PathBuf::new(); + for component in path.components() { + match component { + Component::ParentDir => { + normalized.pop(); + } + Component::CurDir => {} + other => normalized.push(other.as_os_str()), + } + } + normalized +} + +fn access_kind_label(kind: PathAccessKind) -> &'static str { + match kind { + PathAccessKind::Read => "read", + PathAccessKind::Write => "write", + } +} + +fn access_kind_verb(kind: PathAccessKind) -> &'static str { + match kind { + PathAccessKind::Read => "read from", + PathAccessKind::Write => "write to", + } +} diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 267be909fb..0e53670750 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -35,8 +35,6 @@ use std::collections::HashMap; const SEARCH_TOOL_BM25_DESCRIPTION_TEMPLATE: &str = include_str!("../../templates/search_tool/tool_description.md"); -const PRESENTATION_ARTIFACT_DESCRIPTION_TEMPLATE: &str = - include_str!("../../templates/tools/presentation_artifact.md"); #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum ShellCommandBackendConfig { @@ -57,7 +55,7 @@ pub(crate) struct ToolsConfig { pub js_repl_enabled: bool, pub js_repl_tools_only: bool, pub collab_tools: bool, - pub presentation_artifact: bool, + pub artifact_tools: bool, pub default_mode_request_user_input: bool, pub experimental_supported_tools: Vec, pub agent_jobs_tools: bool, @@ -87,7 +85,7 @@ impl ToolsConfig { let include_default_mode_request_user_input = features.enabled(Feature::DefaultModeRequestUserInput); let include_search_tool = features.enabled(Feature::Apps); - let include_presentation_artifact = features.enabled(Feature::Artifact); + let include_artifact_tools = features.enabled(Feature::Artifact); let include_agent_jobs = include_collab_tools && features.enabled(Feature::Sqlite); let request_permission_enabled = features.enabled(Feature::RequestPermissions); let shell_command_backend = @@ -143,7 +141,7 @@ impl ToolsConfig { js_repl_enabled: include_js_repl, js_repl_tools_only: include_js_repl_tools_only, collab_tools: include_collab_tools, - presentation_artifact: include_presentation_artifact, + artifact_tools: include_artifact_tools, default_mode_request_user_input: include_default_mode_request_user_input, experimental_supported_tools: model_info.experimental_supported_tools.clone(), agent_jobs_tools: include_agent_jobs, @@ -609,7 +607,7 @@ fn create_presentation_artifact_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "presentation_artifact".to_string(), - description: PRESENTATION_ARTIFACT_DESCRIPTION_TEMPLATE.to_string(), + description: "Create or edit a presentation artifact for the current thread.".to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -619,6 +617,44 @@ fn create_presentation_artifact_tool() -> ToolSpec { }) } +fn create_spreadsheet_artifact_tool() -> ToolSpec { + let properties = BTreeMap::from([ + ( + "artifact_id".to_string(), + JsonSchema::String { + description: Some( + "Artifact id returned by an earlier spreadsheet_artifact call.".to_string(), + ), + }, + ), + ( + "action".to_string(), + JsonSchema::String { + description: Some("Action name to run for this request.".to_string()), + }, + ), + ( + "args".to_string(), + JsonSchema::Object { + properties: BTreeMap::new(), + required: None, + additional_properties: Some(true.into()), + }, + ), + ]); + + ToolSpec::Function(ResponsesApiTool { + name: "spreadsheet_artifact".to_string(), + description: "Create or edit a spreadsheet artifact for the current thread.".to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["action".to_string(), "args".to_string()]), + additional_properties: Some(false.into()), + }, + }) +} + fn create_collab_input_items_schema() -> JsonSchema { let properties = BTreeMap::from([ ( @@ -1722,6 +1758,7 @@ pub(crate) fn build_specs( use crate::tools::handlers::SearchToolBm25Handler; use crate::tools::handlers::ShellCommandHandler; use crate::tools::handlers::ShellHandler; + use crate::tools::handlers::SpreadsheetArtifactHandler; use crate::tools::handlers::TestSyncHandler; use crate::tools::handlers::UnifiedExecHandler; use crate::tools::handlers::ViewImageHandler; @@ -1745,6 +1782,7 @@ pub(crate) fn build_specs( let js_repl_handler = Arc::new(JsReplHandler); let js_repl_reset_handler = Arc::new(JsReplResetHandler); let presentation_artifact_handler = Arc::new(PresentationArtifactHandler); + let spreadsheet_artifact_handler = Arc::new(SpreadsheetArtifactHandler); let request_permission_enabled = config.request_permission_enabled; match &config.shell_type { @@ -1882,9 +1920,11 @@ pub(crate) fn build_specs( builder.push_spec_with_parallel_support(create_view_image_tool(), true); builder.register_handler("view_image", view_image_handler); - if config.presentation_artifact { + if config.artifact_tools { builder.push_spec(create_presentation_artifact_tool()); + builder.push_spec(create_spreadsheet_artifact_tool()); builder.register_handler("presentation_artifact", presentation_artifact_handler); + builder.register_handler("spreadsheet_artifact", spreadsheet_artifact_handler); } if config.collab_tools { @@ -2201,7 +2241,7 @@ mod tests { session_source: SessionSource::Cli, }); let (tools, _) = build_specs(&tools_config, None, None, &[]).build(); - assert_contains_tool_names(&tools, &["presentation_artifact"]); + assert_contains_tool_names(&tools, &["presentation_artifact", "spreadsheet_artifact"]); } #[test] From 168e35b6f237678ced5eaf8766e1c83c83259b29 Mon Sep 17 00:00:00 2001 From: EFRAZER-oai Date: Tue, 3 Mar 2026 09:25:50 -0800 Subject: [PATCH 332/385] Add Windows direct install script (#12741) ## Summary - add a direct install script for Windows at `scripts/install/install.ps1` - extend release staging so `install.ps1` is published alongside `install.sh` - install the Windows runtime payload (`codex.exe`, `rg.exe`, and helper binaries) from the existing platform npm package ## Dependencies - Depends on https://github.com/openai/codex/pull/12740 ## Testing - Smoke-tested with powershell --- .github/workflows/rust-release.yml | 3 +- scripts/install/install.ps1 | 196 +++++++++++++++++++++++++++++ 2 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 scripts/install/install.ps1 diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 2d137de6ff..5d6d3f7ca0 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -494,9 +494,10 @@ jobs: --package codex-responses-api-proxy \ --package codex-sdk - - name: Stage macOS and Linux installer script + - name: Stage installer scripts run: | cp scripts/install/install.sh dist/install.sh + cp scripts/install/install.ps1 dist/install.ps1 - name: Create GitHub Release uses: softprops/action-gh-release@v2 diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1 new file mode 100644 index 0000000000..40328db700 --- /dev/null +++ b/scripts/install/install.ps1 @@ -0,0 +1,196 @@ +param( + [Parameter(Position=0)] + [string]$Version = "latest" +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" + +function Write-Step { + param( + [string]$Message + ) + + Write-Host "==> $Message" +} + +function Normalize-Version { + param( + [string]$RawVersion + ) + + if ([string]::IsNullOrWhiteSpace($RawVersion) -or $RawVersion -eq "latest") { + return "latest" + } + + if ($RawVersion.StartsWith("rust-v")) { + return $RawVersion.Substring(6) + } + + if ($RawVersion.StartsWith("v")) { + return $RawVersion.Substring(1) + } + + return $RawVersion +} + +function Get-ReleaseUrl { + param( + [string]$AssetName, + [string]$ResolvedVersion + ) + + return "https://github.com/openai/codex/releases/download/rust-v$ResolvedVersion/$AssetName" +} + +function Path-Contains { + param( + [string]$PathValue, + [string]$Entry + ) + + if ([string]::IsNullOrWhiteSpace($PathValue)) { + return $false + } + + $needle = $Entry.TrimEnd("\") + foreach ($segment in $PathValue.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries)) { + if ($segment.TrimEnd("\") -ieq $needle) { + return $true + } + } + + return $false +} + +function Resolve-Version { + $normalizedVersion = Normalize-Version -RawVersion $Version + if ($normalizedVersion -ne "latest") { + return $normalizedVersion + } + + $release = Invoke-RestMethod -Uri "https://api.github.com/repos/openai/codex/releases/latest" + if (-not $release.tag_name) { + Write-Error "Failed to resolve the latest Codex release version." + exit 1 + } + + return (Normalize-Version -RawVersion $release.tag_name) +} + +if ($env:OS -ne "Windows_NT") { + Write-Error "install.ps1 supports Windows only. Use install.sh on macOS or Linux." + exit 1 +} + +if (-not [Environment]::Is64BitOperatingSystem) { + Write-Error "Codex requires a 64-bit version of Windows." + exit 1 +} + +$architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture +$target = $null +$platformLabel = $null +$npmTag = $null +switch ($architecture) { + "Arm64" { + $target = "aarch64-pc-windows-msvc" + $platformLabel = "Windows (ARM64)" + $npmTag = "win32-arm64" + } + "X64" { + $target = "x86_64-pc-windows-msvc" + $platformLabel = "Windows (x64)" + $npmTag = "win32-x64" + } + default { + Write-Error "Unsupported architecture: $architecture" + exit 1 + } +} + +if ([string]::IsNullOrWhiteSpace($env:CODEX_INSTALL_DIR)) { + $installDir = Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin" +} else { + $installDir = $env:CODEX_INSTALL_DIR +} + +$codexPath = Join-Path $installDir "codex.exe" +$installMode = if (Test-Path $codexPath) { "Updating" } else { "Installing" } + +Write-Step "$installMode Codex CLI" +Write-Step "Detected platform: $platformLabel" + +New-Item -ItemType Directory -Force -Path $installDir | Out-Null + +$resolvedVersion = Resolve-Version +Write-Step "Resolved version: $resolvedVersion" +$packageAsset = "codex-npm-$npmTag-$resolvedVersion.tgz" + +$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("codex-install-" + [System.Guid]::NewGuid().ToString("N")) +New-Item -ItemType Directory -Force -Path $tempDir | Out-Null + +try { + $archivePath = Join-Path $tempDir $packageAsset + $extractDir = Join-Path $tempDir "extract" + $url = Get-ReleaseUrl -AssetName $packageAsset -ResolvedVersion $resolvedVersion + + Write-Step "Downloading Codex CLI" + Invoke-WebRequest -Uri $url -OutFile $archivePath + + New-Item -ItemType Directory -Force -Path $extractDir | Out-Null + tar -xzf $archivePath -C $extractDir + + $vendorRoot = Join-Path $extractDir "package/vendor/$target" + Write-Step "Installing to $installDir" + $copyMap = @{ + "codex/codex.exe" = "codex.exe" + "codex/codex-command-runner.exe" = "codex-command-runner.exe" + "codex/codex-windows-sandbox-setup.exe" = "codex-windows-sandbox-setup.exe" + "path/rg.exe" = "rg.exe" + } + + foreach ($relativeSource in $copyMap.Keys) { + $sourcePath = Join-Path $vendorRoot $relativeSource + $destinationPath = Join-Path $installDir $copyMap[$relativeSource] + Move-Item -Force $sourcePath $destinationPath + } +} finally { + Remove-Item -Recurse -Force $tempDir -ErrorAction SilentlyContinue +} + +$userPath = [Environment]::GetEnvironmentVariable("Path", "User") +$pathNeedsNewShell = $false +if (-not (Path-Contains -PathValue $userPath -Entry $installDir)) { + if ([string]::IsNullOrWhiteSpace($userPath)) { + $newUserPath = $installDir + } else { + $newUserPath = "$installDir;$userPath" + } + + [Environment]::SetEnvironmentVariable("Path", $newUserPath, "User") + if (-not (Path-Contains -PathValue $env:Path -Entry $installDir)) { + if ([string]::IsNullOrWhiteSpace($env:Path)) { + $env:Path = $installDir + } else { + $env:Path = "$installDir;$env:Path" + } + } + Write-Step "PATH updated for future PowerShell sessions." + $pathNeedsNewShell = $true +} elseif (Path-Contains -PathValue $env:Path -Entry $installDir) { + Write-Step "$installDir is already on PATH." +} else { + Write-Step "PATH is already configured for future PowerShell sessions." + $pathNeedsNewShell = $true +} + +if ($pathNeedsNewShell) { + Write-Step ('Run now: $env:Path = "{0};$env:Path"; codex' -f $installDir) + Write-Step "Or open a new PowerShell window and run: codex" +} else { + Write-Step "Run: codex" +} + +Write-Host "Codex CLI $resolvedVersion installed successfully." From f6288248f48425e971c7a0d3898bcd0685bfccc2 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 3 Mar 2026 10:13:14 -0800 Subject: [PATCH 333/385] realtime prompt changes (#13376) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. --- codex-rs/protocol/src/prompts/realtime/realtime_end.md | 4 +--- codex-rs/protocol/src/prompts/realtime/realtime_start.md | 3 +-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_end.md b/codex-rs/protocol/src/prompts/realtime/realtime_end.md index 07ccae5286..abec16da03 100644 --- a/codex-rs/protocol/src/prompts/realtime/realtime_end.md +++ b/codex-rs/protocol/src/prompts/realtime/realtime_end.md @@ -1,5 +1,3 @@ Realtime conversation ended. -You are still operating behind an intermediary rather than speaking to the user directly. Use the conversation transcript and current context to decide whether backend help is actually needed, and avoid verbose responses that only add latency. - -Subsequent user input may return to typed text rather than transcript-style text. Do not assume recognition errors or missing punctuation once realtime has ended. Resume normal chat behavior. +Subsequent user input will return to typed text rather than transcript-style text. Do not assume recognition errors or missing punctuation once realtime has ended. Resume normal chat behavior. diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_start.md b/codex-rs/protocol/src/prompts/realtime/realtime_start.md index c7d363eff7..3159a2b07f 100644 --- a/codex-rs/protocol/src/prompts/realtime/realtime_start.md +++ b/codex-rs/protocol/src/prompts/realtime/realtime_start.md @@ -6,5 +6,4 @@ When invoked, you receive the latest conversation transcript and any relevant mo When user text is routed from realtime, treat it as a transcript. It may be unpunctuated or contain recognition errors. -- Ask brief clarification questions when needed. -- Keep responses concise and action-oriented. +- Keep responses concise and action-oriented. Your updates should help the intermediary respond to the user. From 8da7e4bdae61881b2241b6e6225aa8d44c67789f Mon Sep 17 00:00:00 2001 From: Anton Panasenko Date: Tue, 3 Mar 2026 10:25:51 -0800 Subject: [PATCH 334/385] app-server-protocol: export flat v2 schema bundle (#13324) ## Summary - add an `--experimental` flag to the export binary and thread the option through TypeScript and JSON schema generation - flatten the v2 schema bundle into a datamodel-code-generator-friendly `codex_app_server_protocol.v2.schemas.json` export - retarget shared helper refs to namespaced v2 definitions, add coverage for the new export behavior, and vendor the generated schema fixtures ## Validation - `cargo test -p codex-app-server-protocol` (71 unit tests and bin targets passed locally; the final schema fixture integration target was revalidated via fresh schema regeneration and a tree diff) - `./target/debug/write_schema_fixtures --schema-root ` - `diff -rq app-server-protocol/schema ` ## Tickets - None --- .../codex_app_server_protocol.schemas.json | 18 +- .../codex_app_server_protocol.v2.schemas.json | 13958 ++++++++++++++++ .../app-server-protocol/src/bin/export.rs | 14 +- codex-rs/app-server-protocol/src/export.rs | 635 +- 4 files changed, 14607 insertions(+), 18 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 4cf3933e75..ddeee0ce73 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -5,7 +5,7 @@ "properties": { "read": { "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -14,7 +14,7 @@ }, "write": { "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -1382,7 +1382,7 @@ "thread_id": { "allOf": [ { - "$ref": "#/definitions/ThreadId" + "$ref": "#/definitions/v2/ThreadId" } ], "description": "Thread ID of the receiver/new agent." @@ -1420,7 +1420,7 @@ "thread_id": { "allOf": [ { - "$ref": "#/definitions/ThreadId" + "$ref": "#/definitions/v2/ThreadId" } ], "description": "Thread ID of the receiver/new agent." @@ -4732,7 +4732,7 @@ "properties": { "read": { "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -4741,7 +4741,7 @@ }, "write": { "items": { - "$ref": "#/definitions/AbsolutePathBuf" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -7131,7 +7131,7 @@ "properties": { "content": { "items": { - "$ref": "#/definitions/UserInput" + "$ref": "#/definitions/v2/UserInput" }, "type": "array" }, @@ -7169,7 +7169,7 @@ "phase": { "anyOf": [ { - "$ref": "#/definitions/MessagePhase" + "$ref": "#/definitions/v2/MessagePhase" }, { "type": "null" @@ -7254,7 +7254,7 @@ { "properties": { "action": { - "$ref": "#/definitions/WebSearchAction" + "$ref": "#/definitions/v2/WebSearchAction" }, "id": { "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json new file mode 100644 index 0000000000..0f8e83d572 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -0,0 +1,13958 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "AbsolutePathBuf": { + "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + "type": "string" + }, + "Account": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "apiKey" + ], + "title": "ApiKeyAccountType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ApiKeyAccount", + "type": "object" + }, + { + "properties": { + "email": { + "type": "string" + }, + "planType": { + "$ref": "#/definitions/PlanType" + }, + "type": { + "enum": [ + "chatgpt" + ], + "title": "ChatgptAccountType", + "type": "string" + } + }, + "required": [ + "email", + "planType", + "type" + ], + "title": "ChatgptAccount", + "type": "object" + } + ] + }, + "AccountLoginCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, + "loginId": { + "type": [ + "string", + "null" + ] + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "success" + ], + "title": "AccountLoginCompletedNotification", + "type": "object" + }, + "AccountRateLimitsUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "rateLimits": { + "$ref": "#/definitions/RateLimitSnapshot" + } + }, + "required": [ + "rateLimits" + ], + "title": "AccountRateLimitsUpdatedNotification", + "type": "object" + }, + "AccountUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "authMode": { + "anyOf": [ + { + "$ref": "#/definitions/AuthMode" + }, + { + "type": "null" + } + ] + }, + "planType": { + "anyOf": [ + { + "$ref": "#/definitions/PlanType" + }, + { + "type": "null" + } + ] + } + }, + "title": "AccountUpdatedNotification", + "type": "object" + }, + "AgentMessageContent": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "Text" + ], + "title": "TextAgentMessageContentType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "TextAgentMessageContent", + "type": "object" + } + ] + }, + "AgentMessageDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "AgentMessageDeltaNotification", + "type": "object" + }, + "AgentStatus": { + "description": "Agent lifecycle status, derived from emitted events.", + "oneOf": [ + { + "description": "Agent is waiting for initialization.", + "enum": [ + "pending_init" + ], + "type": "string" + }, + { + "description": "Agent is currently running.", + "enum": [ + "running" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "Agent is done. Contains the final assistant message.", + "properties": { + "completed": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "completed" + ], + "title": "CompletedAgentStatus", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Agent encountered an error.", + "properties": { + "errored": { + "type": "string" + } + }, + "required": [ + "errored" + ], + "title": "ErroredAgentStatus", + "type": "object" + }, + { + "description": "Agent has been shutdown.", + "enum": [ + "shutdown" + ], + "type": "string" + }, + { + "description": "Agent is not found.", + "enum": [ + "not_found" + ], + "type": "string" + } + ] + }, + "AnalyticsConfig": { + "additionalProperties": true, + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "AppBranding": { + "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", + "properties": { + "category": { + "type": [ + "string", + "null" + ] + }, + "developer": { + "type": [ + "string", + "null" + ] + }, + "isDiscoverableApp": { + "type": "boolean" + }, + "privacyPolicy": { + "type": [ + "string", + "null" + ] + }, + "termsOfService": { + "type": [ + "string", + "null" + ] + }, + "website": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "isDiscoverableApp" + ], + "type": "object" + }, + "AppConfig": { + "properties": { + "default_tools_approval_mode": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolApproval" + }, + { + "type": "null" + } + ] + }, + "default_tools_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "destructive_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "enabled": { + "default": true, + "type": "boolean" + }, + "open_world_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "tools": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolsConfig" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "AppInfo": { + "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", + "properties": { + "appMetadata": { + "anyOf": [ + { + "$ref": "#/definitions/AppMetadata" + }, + { + "type": "null" + } + ] + }, + "branding": { + "anyOf": [ + { + "$ref": "#/definitions/AppBranding" + }, + { + "type": "null" + } + ] + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "distributionChannel": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string" + }, + "installUrl": { + "type": [ + "string", + "null" + ] + }, + "isAccessible": { + "default": false, + "type": "boolean" + }, + "isEnabled": { + "default": true, + "description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + "type": "boolean" + }, + "labels": { + "additionalProperties": { + "type": "string" + }, + "type": [ + "object", + "null" + ] + }, + "logoUrl": { + "type": [ + "string", + "null" + ] + }, + "logoUrlDark": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "AppListUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - notification emitted when the app list changes.", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/AppInfo" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "AppListUpdatedNotification", + "type": "object" + }, + "AppMetadata": { + "properties": { + "categories": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "developer": { + "type": [ + "string", + "null" + ] + }, + "firstPartyRequiresInstall": { + "type": [ + "boolean", + "null" + ] + }, + "firstPartyType": { + "type": [ + "string", + "null" + ] + }, + "review": { + "anyOf": [ + { + "$ref": "#/definitions/AppReview" + }, + { + "type": "null" + } + ] + }, + "screenshots": { + "items": { + "$ref": "#/definitions/AppScreenshot" + }, + "type": [ + "array", + "null" + ] + }, + "seoDescription": { + "type": [ + "string", + "null" + ] + }, + "showInComposerWhenUnlinked": { + "type": [ + "boolean", + "null" + ] + }, + "subCategories": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "version": { + "type": [ + "string", + "null" + ] + }, + "versionId": { + "type": [ + "string", + "null" + ] + }, + "versionNotes": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "AppReview": { + "properties": { + "status": { + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "AppScreenshot": { + "properties": { + "fileId": { + "type": [ + "string", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "userPrompt": { + "type": "string" + } + }, + "required": [ + "userPrompt" + ], + "type": "object" + }, + "AppToolApproval": { + "enum": [ + "auto", + "prompt", + "approve" + ], + "type": "string" + }, + "AppToolConfig": { + "properties": { + "approval_mode": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolApproval" + }, + { + "type": "null" + } + ] + }, + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "AppToolsConfig": { + "type": "object" + }, + "AppsConfig": { + "properties": { + "_default": { + "anyOf": [ + { + "$ref": "#/definitions/AppsDefaultConfig" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "AppsDefaultConfig": { + "properties": { + "destructive_enabled": { + "default": true, + "type": "boolean" + }, + "enabled": { + "default": true, + "type": "boolean" + }, + "open_world_enabled": { + "default": true, + "type": "boolean" + } + }, + "type": "object" + }, + "AppsListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - list available apps/connectors.", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "forceRefetch": { + "description": "When true, bypass app caches and fetch the latest data from sources.", + "type": "boolean" + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "threadId": { + "description": "Optional thread id used to evaluate app feature gating from that thread's config.", + "type": [ + "string", + "null" + ] + } + }, + "title": "AppsListParams", + "type": "object" + }, + "AppsListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - app list response.", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/AppInfo" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "AppsListResponse", + "type": "object" + }, + "AskForApproval": { + "oneOf": [ + { + "enum": [ + "untrusted", + "on-failure", + "on-request", + "never" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "reject": { + "properties": { + "mcp_elicitations": { + "type": "boolean" + }, + "rules": { + "type": "boolean" + }, + "sandbox_approval": { + "type": "boolean" + } + }, + "required": [ + "mcp_elicitations", + "rules", + "sandbox_approval" + ], + "type": "object" + } + }, + "required": [ + "reject" + ], + "title": "RejectAskForApproval", + "type": "object" + } + ] + }, + "AuthMode": { + "description": "Authentication mode for OpenAI-backed providers.", + "oneOf": [ + { + "description": "OpenAI API key provided by the caller and stored by Codex.", + "enum": [ + "apikey" + ], + "type": "string" + }, + { + "description": "ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex).", + "enum": [ + "chatgpt" + ], + "type": "string" + }, + { + "description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.\n\nChatGPT auth tokens are supplied by an external host app and are only stored in memory. Token refresh must be handled by the external host app.", + "enum": [ + "chatgptAuthTokens" + ], + "type": "string" + } + ] + }, + "ByteRange": { + "properties": { + "end": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "start": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "end", + "start" + ], + "type": "object" + }, + "CallToolResult": { + "description": "The server's response to a tool call.", + "properties": { + "_meta": true, + "content": { + "items": true, + "type": "array" + }, + "isError": { + "type": [ + "boolean", + "null" + ] + }, + "structuredContent": true + }, + "required": [ + "content" + ], + "type": "object" + }, + "CancelLoginAccountParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "loginId": { + "type": "string" + } + }, + "required": [ + "loginId" + ], + "title": "CancelLoginAccountParams", + "type": "object" + }, + "CancelLoginAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "status": { + "$ref": "#/definitions/CancelLoginAccountStatus" + } + }, + "required": [ + "status" + ], + "title": "CancelLoginAccountResponse", + "type": "object" + }, + "CancelLoginAccountStatus": { + "enum": [ + "canceled", + "notFound" + ], + "type": "string" + }, + "ClientInfo": { + "properties": { + "name": { + "type": "string" + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "version": { + "type": "string" + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, + "ClientRequest": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Request from the client to the server.", + "oneOf": [ + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "initialize" + ], + "title": "InitializeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/InitializeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "InitializeRequest", + "type": "object" + }, + { + "description": "NEW APIs", + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/start" + ], + "title": "Thread/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/resume" + ], + "title": "Thread/resumeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadResumeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/resumeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/fork" + ], + "title": "Thread/forkRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadForkParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/forkRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/archive" + ], + "title": "Thread/archiveRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadArchiveParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/archiveRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/unsubscribe" + ], + "title": "Thread/unsubscribeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadUnsubscribeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/unsubscribeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/name/set" + ], + "title": "Thread/name/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadSetNameParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/name/setRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/unarchive" + ], + "title": "Thread/unarchiveRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadUnarchiveParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/unarchiveRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/compact/start" + ], + "title": "Thread/compact/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadCompactStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/compact/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/rollback" + ], + "title": "Thread/rollbackRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRollbackParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/rollbackRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/list" + ], + "title": "Thread/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/loaded/list" + ], + "title": "Thread/loaded/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadLoadedListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/loaded/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/read" + ], + "title": "Thread/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/list" + ], + "title": "Skills/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/remote/list" + ], + "title": "Skills/remote/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsRemoteReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/remote/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/remote/export" + ], + "title": "Skills/remote/exportRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsRemoteWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/remote/exportRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "app/list" + ], + "title": "App/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AppsListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "App/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/config/write" + ], + "title": "Skills/config/writeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsConfigWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/config/writeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "turn/start" + ], + "title": "Turn/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Turn/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "turn/steer" + ], + "title": "Turn/steerRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnSteerParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Turn/steerRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "turn/interrupt" + ], + "title": "Turn/interruptRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnInterruptParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Turn/interruptRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "review/start" + ], + "title": "Review/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReviewStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Review/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "model/list" + ], + "title": "Model/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ModelListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Model/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "experimentalFeature/list" + ], + "title": "ExperimentalFeature/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ExperimentalFeatureListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "ExperimentalFeature/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "mcpServer/oauth/login" + ], + "title": "McpServer/oauth/loginRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/McpServerOauthLoginParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "McpServer/oauth/loginRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/mcpServer/reload" + ], + "title": "Config/mcpServer/reloadRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "Config/mcpServer/reloadRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "mcpServerStatus/list" + ], + "title": "McpServerStatus/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ListMcpServerStatusParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "McpServerStatus/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "windowsSandbox/setupStart" + ], + "title": "WindowsSandbox/setupStartRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WindowsSandboxSetupStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "WindowsSandbox/setupStartRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/login/start" + ], + "title": "Account/login/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/LoginAccountParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Account/login/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/login/cancel" + ], + "title": "Account/login/cancelRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CancelLoginAccountParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Account/login/cancelRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/logout" + ], + "title": "Account/logoutRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "Account/logoutRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/rateLimits/read" + ], + "title": "Account/rateLimits/readRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "Account/rateLimits/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "feedback/upload" + ], + "title": "Feedback/uploadRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FeedbackUploadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Feedback/uploadRequest", + "type": "object" + }, + { + "description": "Execute a command (argv vector) under the server's sandbox.", + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "command/exec" + ], + "title": "Command/execRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CommandExecParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Command/execRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/read" + ], + "title": "Config/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Config/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "externalAgentConfig/detect" + ], + "title": "ExternalAgentConfig/detectRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ExternalAgentConfigDetectParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "ExternalAgentConfig/detectRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "externalAgentConfig/import" + ], + "title": "ExternalAgentConfig/importRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ExternalAgentConfigImportParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "ExternalAgentConfig/importRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/value/write" + ], + "title": "Config/value/writeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigValueWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Config/value/writeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/batchWrite" + ], + "title": "Config/batchWriteRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigBatchWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Config/batchWriteRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "configRequirements/read" + ], + "title": "ConfigRequirements/readRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "ConfigRequirements/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/read" + ], + "title": "Account/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/GetAccountParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Account/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "fuzzyFileSearch" + ], + "title": "FuzzyFileSearchRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FuzzyFileSearchParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "FuzzyFileSearchRequest", + "type": "object" + } + ], + "title": "ClientRequest" + }, + "CodexErrorInfo": { + "description": "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", + "oneOf": [ + { + "enum": [ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "httpConnectionFailed": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "httpConnectionFailed" + ], + "title": "HttpConnectionFailedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Failed to connect to the response SSE stream.", + "properties": { + "responseStreamConnectionFailed": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseStreamConnectionFailed" + ], + "title": "ResponseStreamConnectionFailedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "The response SSE stream disconnected in the middle of a turn before completion.", + "properties": { + "responseStreamDisconnected": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseStreamDisconnected" + ], + "title": "ResponseStreamDisconnectedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Reached the retry limit for responses.", + "properties": { + "responseTooManyFailedAttempts": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseTooManyFailedAttempts" + ], + "title": "ResponseTooManyFailedAttemptsCodexErrorInfo", + "type": "object" + } + ] + }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, + "CollabAgentState": { + "properties": { + "message": { + "type": [ + "string", + "null" + ] + }, + "status": { + "$ref": "#/definitions/CollabAgentStatus" + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "CollabAgentStatus": { + "enum": [ + "pendingInit", + "running", + "completed", + "errored", + "shutdown", + "notFound" + ], + "type": "string" + }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, + "CollabAgentTool": { + "enum": [ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent" + ], + "type": "string" + }, + "CollabAgentToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "CollaborationMode": { + "description": "Collaboration mode for a Codex session.", + "properties": { + "mode": { + "$ref": "#/definitions/ModeKind" + }, + "settings": { + "$ref": "#/definitions/Settings" + } + }, + "required": [ + "mode", + "settings" + ], + "type": "object" + }, + "CollaborationModeMask": { + "description": "EXPERIMENTAL - collaboration mode preset metadata for clients.", + "properties": { + "mode": { + "anyOf": [ + { + "$ref": "#/definitions/ModeKind" + }, + { + "type": "null" + } + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "reasoning_effort": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "CommandAction": { + "oneOf": [ + { + "properties": { + "command": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "read" + ], + "title": "ReadCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "name", + "path", + "type" + ], + "title": "ReadCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "listFiles" + ], + "title": "ListFilesCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "ListFilesCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "SearchCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "type": { + "enum": [ + "unknown" + ], + "title": "UnknownCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "UnknownCommandAction", + "type": "object" + } + ] + }, + "CommandExecParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "command": { + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "sandboxPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxPolicy" + }, + { + "type": "null" + } + ] + }, + "timeoutMs": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "command" + ], + "title": "CommandExecParams", + "type": "object" + }, + "CommandExecResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "exitCode": { + "format": "int32", + "type": "integer" + }, + "stderr": { + "type": "string" + }, + "stdout": { + "type": "string" + } + }, + "required": [ + "exitCode", + "stderr", + "stdout" + ], + "title": "CommandExecResponse", + "type": "object" + }, + "CommandExecutionOutputDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "CommandExecutionOutputDeltaNotification", + "type": "object" + }, + "CommandExecutionStatus": { + "enum": [ + "inProgress", + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "Config": { + "additionalProperties": true, + "properties": { + "analytics": { + "anyOf": [ + { + "$ref": "#/definitions/AnalyticsConfig" + }, + { + "type": "null" + } + ] + }, + "approval_policy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "compact_prompt": { + "type": [ + "string", + "null" + ] + }, + "developer_instructions": { + "type": [ + "string", + "null" + ] + }, + "forced_chatgpt_workspace_id": { + "type": [ + "string", + "null" + ] + }, + "forced_login_method": { + "anyOf": [ + { + "$ref": "#/definitions/ForcedLoginMethod" + }, + { + "type": "null" + } + ] + }, + "instructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "model_auto_compact_token_limit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "model_context_window": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "model_provider": { + "type": [ + "string", + "null" + ] + }, + "model_reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "model_reasoning_summary": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningSummary" + }, + { + "type": "null" + } + ] + }, + "model_verbosity": { + "anyOf": [ + { + "$ref": "#/definitions/Verbosity" + }, + { + "type": "null" + } + ] + }, + "profile": { + "type": [ + "string", + "null" + ] + }, + "profiles": { + "additionalProperties": { + "$ref": "#/definitions/ProfileV2" + }, + "default": {}, + "type": "object" + }, + "review_model": { + "type": [ + "string", + "null" + ] + }, + "sandbox_mode": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "sandbox_workspace_write": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxWorkspaceWrite" + }, + { + "type": "null" + } + ] + }, + "tools": { + "anyOf": [ + { + "$ref": "#/definitions/ToolsV2" + }, + { + "type": "null" + } + ] + }, + "web_search": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchMode" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "ConfigBatchWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "edits": { + "items": { + "$ref": "#/definitions/ConfigEdit" + }, + "type": "array" + }, + "expectedVersion": { + "type": [ + "string", + "null" + ] + }, + "filePath": { + "description": "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "edits" + ], + "title": "ConfigBatchWriteParams", + "type": "object" + }, + "ConfigEdit": { + "properties": { + "keyPath": { + "type": "string" + }, + "mergeStrategy": { + "$ref": "#/definitions/MergeStrategy" + }, + "value": true + }, + "required": [ + "keyPath", + "mergeStrategy", + "value" + ], + "type": "object" + }, + "ConfigLayer": { + "properties": { + "config": true, + "disabledReason": { + "type": [ + "string", + "null" + ] + }, + "name": { + "$ref": "#/definitions/ConfigLayerSource" + }, + "version": { + "type": "string" + } + }, + "required": [ + "config", + "name", + "version" + ], + "type": "object" + }, + "ConfigLayerMetadata": { + "properties": { + "name": { + "$ref": "#/definitions/ConfigLayerSource" + }, + "version": { + "type": "string" + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, + "ConfigLayerSource": { + "oneOf": [ + { + "description": "Managed preferences layer delivered by MDM (macOS only).", + "properties": { + "domain": { + "type": "string" + }, + "key": { + "type": "string" + }, + "type": { + "enum": [ + "mdm" + ], + "title": "MdmConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "domain", + "key", + "type" + ], + "title": "MdmConfigLayerSource", + "type": "object" + }, + { + "description": "Managed config layer from a file (usually `managed_config.toml`).", + "properties": { + "file": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "This is the path to the system config.toml file, though it is not guaranteed to exist." + }, + "type": { + "enum": [ + "system" + ], + "title": "SystemConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "file", + "type" + ], + "title": "SystemConfigLayerSource", + "type": "object" + }, + { + "description": "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory", + "properties": { + "file": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "This is the path to the user's config.toml file, though it is not guaranteed to exist." + }, + "type": { + "enum": [ + "user" + ], + "title": "UserConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "file", + "type" + ], + "title": "UserConfigLayerSource", + "type": "object" + }, + { + "description": "Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.", + "properties": { + "dotCodexFolder": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": { + "enum": [ + "project" + ], + "title": "ProjectConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "dotCodexFolder", + "type" + ], + "title": "ProjectConfigLayerSource", + "type": "object" + }, + { + "description": "Session-layer overrides supplied via `-c`/`--config`.", + "properties": { + "type": { + "enum": [ + "sessionFlags" + ], + "title": "SessionFlagsConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SessionFlagsConfigLayerSource", + "type": "object" + }, + { + "description": "`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a \"best effort\" while we phase out `managed_config.toml` in favor of `requirements.toml`.", + "properties": { + "file": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": { + "enum": [ + "legacyManagedConfigTomlFromFile" + ], + "title": "LegacyManagedConfigTomlFromFileConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "file", + "type" + ], + "title": "LegacyManagedConfigTomlFromFileConfigLayerSource", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "legacyManagedConfigTomlFromMdm" + ], + "title": "LegacyManagedConfigTomlFromMdmConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "LegacyManagedConfigTomlFromMdmConfigLayerSource", + "type": "object" + } + ] + }, + "ConfigReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cwd": { + "description": "Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).", + "type": [ + "string", + "null" + ] + }, + "includeLayers": { + "default": false, + "type": "boolean" + } + }, + "title": "ConfigReadParams", + "type": "object" + }, + "ConfigReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "config": { + "$ref": "#/definitions/Config" + }, + "layers": { + "items": { + "$ref": "#/definitions/ConfigLayer" + }, + "type": [ + "array", + "null" + ] + }, + "origins": { + "additionalProperties": { + "$ref": "#/definitions/ConfigLayerMetadata" + }, + "type": "object" + } + }, + "required": [ + "config", + "origins" + ], + "title": "ConfigReadResponse", + "type": "object" + }, + "ConfigRequirements": { + "properties": { + "allowedApprovalPolicies": { + "items": { + "$ref": "#/definitions/AskForApproval" + }, + "type": [ + "array", + "null" + ] + }, + "allowedSandboxModes": { + "items": { + "$ref": "#/definitions/SandboxMode" + }, + "type": [ + "array", + "null" + ] + }, + "allowedWebSearchModes": { + "items": { + "$ref": "#/definitions/WebSearchMode" + }, + "type": [ + "array", + "null" + ] + }, + "enforceResidency": { + "anyOf": [ + { + "$ref": "#/definitions/ResidencyRequirement" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "ConfigRequirementsReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "requirements": { + "anyOf": [ + { + "$ref": "#/definitions/ConfigRequirements" + }, + { + "type": "null" + } + ], + "description": "Null if no requirements are configured (e.g. no requirements.toml/MDM entries)." + } + }, + "title": "ConfigRequirementsReadResponse", + "type": "object" + }, + "ConfigValueWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "expectedVersion": { + "type": [ + "string", + "null" + ] + }, + "filePath": { + "description": "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + "type": [ + "string", + "null" + ] + }, + "keyPath": { + "type": "string" + }, + "mergeStrategy": { + "$ref": "#/definitions/MergeStrategy" + }, + "value": true + }, + "required": [ + "keyPath", + "mergeStrategy", + "value" + ], + "title": "ConfigValueWriteParams", + "type": "object" + }, + "ConfigWarningNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "details": { + "description": "Optional extra guidance or error details.", + "type": [ + "string", + "null" + ] + }, + "path": { + "description": "Optional path to the config file that triggered the warning.", + "type": [ + "string", + "null" + ] + }, + "range": { + "anyOf": [ + { + "$ref": "#/definitions/TextRange" + }, + { + "type": "null" + } + ], + "description": "Optional range for the error location inside the config file." + }, + "summary": { + "description": "Concise summary of the warning.", + "type": "string" + } + }, + "required": [ + "summary" + ], + "title": "ConfigWarningNotification", + "type": "object" + }, + "ConfigWriteResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "filePath": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "Canonical path to the config file that was written." + }, + "overriddenMetadata": { + "anyOf": [ + { + "$ref": "#/definitions/OverriddenMetadata" + }, + { + "type": "null" + } + ] + }, + "status": { + "$ref": "#/definitions/WriteStatus" + }, + "version": { + "type": "string" + } + }, + "required": [ + "filePath", + "status", + "version" + ], + "title": "ConfigWriteResponse", + "type": "object" + }, + "ContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "input_text" + ], + "title": "InputTextContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextContentItem", + "type": "object" + }, + { + "properties": { + "image_url": { + "type": "string" + }, + "type": { + "enum": [ + "input_image" + ], + "title": "InputImageContentItemType", + "type": "string" + } + }, + "required": [ + "image_url", + "type" + ], + "title": "InputImageContentItem", + "type": "object" + }, + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "output_text" + ], + "title": "OutputTextContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "OutputTextContentItem", + "type": "object" + } + ] + }, + "ContextCompactedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Deprecated: Use `ContextCompaction` item type instead.", + "properties": { + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "threadId", + "turnId" + ], + "title": "ContextCompactedNotification", + "type": "object" + }, + "CreditsSnapshot": { + "properties": { + "balance": { + "type": [ + "string", + "null" + ] + }, + "hasCredits": { + "type": "boolean" + }, + "unlimited": { + "type": "boolean" + } + }, + "required": [ + "hasCredits", + "unlimited" + ], + "type": "object" + }, + "CustomPrompt": { + "properties": { + "argument_hint": { + "type": [ + "string", + "null" + ] + }, + "content": { + "type": "string" + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "content", + "name", + "path" + ], + "type": "object" + }, + "DeprecationNoticeNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "details": { + "description": "Optional extra guidance, such as migration steps or rationale.", + "type": [ + "string", + "null" + ] + }, + "summary": { + "description": "Concise summary of what is deprecated.", + "type": "string" + } + }, + "required": [ + "summary" + ], + "title": "DeprecationNoticeNotification", + "type": "object" + }, + "Duration": { + "properties": { + "nanos": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "secs": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "nanos", + "secs" + ], + "type": "object" + }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "DynamicToolSpec": { + "properties": { + "description": { + "type": "string" + }, + "inputSchema": true, + "name": { + "type": "string" + } + }, + "required": [ + "description", + "inputSchema", + "name" + ], + "type": "object" + }, + "ErrorNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "$ref": "#/definitions/TurnError" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + }, + "willRetry": { + "type": "boolean" + } + }, + "required": [ + "error", + "threadId", + "turnId", + "willRetry" + ], + "title": "ErrorNotification", + "type": "object" + }, + "EventMsg": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Response event from the agent NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.", + "oneOf": [ + { + "description": "Error while executing a submission", + "properties": { + "codex_error_info": { + "anyOf": [ + { + "$ref": "#/definitions/CodexErrorInfo" + }, + { + "type": "null" + } + ], + "default": null + }, + "message": { + "type": "string" + }, + "type": { + "enum": [ + "error" + ], + "title": "ErrorEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "ErrorEventMsg", + "type": "object" + }, + { + "description": "Warning issued while processing a submission. Unlike `Error`, this indicates the turn continued but the user should still be notified.", + "properties": { + "message": { + "type": "string" + }, + "type": { + "enum": [ + "warning" + ], + "title": "WarningEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "WarningEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, + { + "description": "Model routing changed from the requested model to a different model.", + "properties": { + "from_model": { + "type": "string" + }, + "reason": { + "$ref": "#/definitions/ModelRerouteReason" + }, + "to_model": { + "type": "string" + }, + "type": { + "enum": [ + "model_reroute" + ], + "title": "ModelRerouteEventMsgType", + "type": "string" + } + }, + "required": [ + "from_model", + "reason", + "to_model", + "type" + ], + "title": "ModelRerouteEventMsg", + "type": "object" + }, + { + "description": "Conversation history was compacted (either automatically or manually).", + "properties": { + "type": { + "enum": [ + "context_compacted" + ], + "title": "ContextCompactedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ContextCompactedEventMsg", + "type": "object" + }, + { + "description": "Conversation history was rolled back by dropping the last N user turns.", + "properties": { + "num_turns": { + "description": "Number of user turns that were removed from context.", + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "type": { + "enum": [ + "thread_rolled_back" + ], + "title": "ThreadRolledBackEventMsgType", + "type": "string" + } + }, + "required": [ + "num_turns", + "type" + ], + "title": "ThreadRolledBackEventMsg", + "type": "object" + }, + { + "description": "Agent has started a turn. v1 wire format uses `task_started`; accept `turn_started` for v2 interop.", + "properties": { + "collaboration_mode_kind": { + "allOf": [ + { + "$ref": "#/definitions/ModeKind" + } + ], + "default": "default" + }, + "model_context_window": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "task_started" + ], + "title": "TaskStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "turn_id", + "type" + ], + "title": "TaskStartedEventMsg", + "type": "object" + }, + { + "description": "Agent has completed all actions. v1 wire format uses `task_complete`; accept `turn_complete` for v2 interop.", + "properties": { + "last_agent_message": { + "type": [ + "string", + "null" + ] + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "task_complete" + ], + "title": "TaskCompleteEventMsgType", + "type": "string" + } + }, + "required": [ + "turn_id", + "type" + ], + "title": "TaskCompleteEventMsg", + "type": "object" + }, + { + "description": "Usage update for the current session, including totals and last turn. Optional means unknown — UIs should not display when `None`.", + "properties": { + "info": { + "anyOf": [ + { + "$ref": "#/definitions/TokenUsageInfo" + }, + { + "type": "null" + } + ] + }, + "rate_limits": { + "anyOf": [ + { + "$ref": "#/definitions/RateLimitSnapshot" + }, + { + "type": "null" + } + ] + }, + "type": { + "enum": [ + "token_count" + ], + "title": "TokenCountEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "TokenCountEventMsg", + "type": "object" + }, + { + "description": "Agent text output message", + "properties": { + "message": { + "type": "string" + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, + "type": { + "enum": [ + "agent_message" + ], + "title": "AgentMessageEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "AgentMessageEventMsg", + "type": "object" + }, + { + "description": "User/system input message (what was sent to the model)", + "properties": { + "images": { + "description": "Image URLs sourced from `UserInput::Image`. These are safe to replay in legacy UI history events and correspond to images sent to the model.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "local_images": { + "default": [], + "description": "Local file paths sourced from `UserInput::LocalImage`. These are kept so the UI can reattach images when editing history, and should not be sent to the model or treated as API-ready URLs.", + "items": { + "type": "string" + }, + "type": "array" + }, + "message": { + "type": "string" + }, + "text_elements": { + "default": [], + "description": "UI-defined spans within `message` used to render or persist special elements.", + "items": { + "$ref": "#/definitions/TextElement" + }, + "type": "array" + }, + "type": { + "enum": [ + "user_message" + ], + "title": "UserMessageEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "UserMessageEventMsg", + "type": "object" + }, + { + "description": "Agent text output delta message", + "properties": { + "delta": { + "type": "string" + }, + "type": { + "enum": [ + "agent_message_delta" + ], + "title": "AgentMessageDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "type" + ], + "title": "AgentMessageDeltaEventMsg", + "type": "object" + }, + { + "description": "Reasoning event from agent.", + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning" + ], + "title": "AgentReasoningEventMsgType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "AgentReasoningEventMsg", + "type": "object" + }, + { + "description": "Agent reasoning delta event from agent.", + "properties": { + "delta": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning_delta" + ], + "title": "AgentReasoningDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "type" + ], + "title": "AgentReasoningDeltaEventMsg", + "type": "object" + }, + { + "description": "Raw chain-of-thought from agent.", + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning_raw_content" + ], + "title": "AgentReasoningRawContentEventMsgType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "AgentReasoningRawContentEventMsg", + "type": "object" + }, + { + "description": "Agent reasoning content delta event from agent.", + "properties": { + "delta": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning_raw_content_delta" + ], + "title": "AgentReasoningRawContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "type" + ], + "title": "AgentReasoningRawContentDeltaEventMsg", + "type": "object" + }, + { + "description": "Signaled when the model begins a new reasoning summary section (e.g., a new titled block).", + "properties": { + "item_id": { + "default": "", + "type": "string" + }, + "summary_index": { + "default": 0, + "format": "int64", + "type": "integer" + }, + "type": { + "enum": [ + "agent_reasoning_section_break" + ], + "title": "AgentReasoningSectionBreakEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AgentReasoningSectionBreakEventMsg", + "type": "object" + }, + { + "description": "Ack the client's configure message.", + "properties": { + "approval_policy": { + "allOf": [ + { + "$ref": "#/definitions/AskForApproval" + } + ], + "description": "When to escalate for approval for execution" + }, + "cwd": { + "description": "Working directory that should be treated as the *root* of the session.", + "type": "string" + }, + "forked_from_id": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadId" + }, + { + "type": "null" + } + ] + }, + "history_entry_count": { + "description": "Current number of entries in the history log.", + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "history_log_id": { + "description": "Identifier of the history log file (inode on Unix, 0 otherwise).", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "initial_messages": { + "description": "Optional initial messages (as events) for resumed sessions. When present, UIs can use these to seed the history.", + "items": { + "$ref": "#/definitions/EventMsg" + }, + "type": [ + "array", + "null" + ] + }, + "model": { + "description": "Tell the client what model is being queried.", + "type": "string" + }, + "model_provider_id": { + "type": "string" + }, + "network_proxy": { + "anyOf": [ + { + "$ref": "#/definitions/SessionNetworkProxyRuntime" + }, + { + "type": "null" + } + ], + "description": "Runtime proxy bind addresses, when the managed proxy was started for this session." + }, + "reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ], + "description": "The effort the model is putting into reasoning about the user's request." + }, + "rollout_path": { + "description": "Path in which the rollout is stored. Can be `None` for ephemeral threads", + "type": [ + "string", + "null" + ] + }, + "sandbox_policy": { + "allOf": [ + { + "$ref": "#/definitions/SandboxPolicy" + } + ], + "description": "How to sandbox commands executed in the system" + }, + "session_id": { + "$ref": "#/definitions/ThreadId" + }, + "thread_name": { + "description": "Optional user-facing thread name (may be unset).", + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "session_configured" + ], + "title": "SessionConfiguredEventMsgType", + "type": "string" + } + }, + "required": [ + "approval_policy", + "cwd", + "history_entry_count", + "history_log_id", + "model", + "model_provider_id", + "sandbox_policy", + "session_id", + "type" + ], + "title": "SessionConfiguredEventMsg", + "type": "object" + }, + { + "description": "Updated session metadata (e.g., thread name changes).", + "properties": { + "thread_id": { + "$ref": "#/definitions/ThreadId" + }, + "thread_name": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "thread_name_updated" + ], + "title": "ThreadNameUpdatedEventMsgType", + "type": "string" + } + }, + "required": [ + "thread_id", + "type" + ], + "title": "ThreadNameUpdatedEventMsg", + "type": "object" + }, + { + "description": "Incremental MCP startup progress updates.", + "properties": { + "server": { + "description": "Server name being started.", + "type": "string" + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/McpStartupStatus" + } + ], + "description": "Current startup status." + }, + "type": { + "enum": [ + "mcp_startup_update" + ], + "title": "McpStartupUpdateEventMsgType", + "type": "string" + } + }, + "required": [ + "server", + "status", + "type" + ], + "title": "McpStartupUpdateEventMsg", + "type": "object" + }, + { + "description": "Aggregate MCP startup completion summary.", + "properties": { + "cancelled": { + "items": { + "type": "string" + }, + "type": "array" + }, + "failed": { + "items": { + "$ref": "#/definitions/McpStartupFailure" + }, + "type": "array" + }, + "ready": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "enum": [ + "mcp_startup_complete" + ], + "title": "McpStartupCompleteEventMsgType", + "type": "string" + } + }, + "required": [ + "cancelled", + "failed", + "ready", + "type" + ], + "title": "McpStartupCompleteEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Identifier so this can be paired with the McpToolCallEnd event.", + "type": "string" + }, + "invocation": { + "$ref": "#/definitions/McpInvocation" + }, + "type": { + "enum": [ + "mcp_tool_call_begin" + ], + "title": "McpToolCallBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "invocation", + "type" + ], + "title": "McpToolCallBeginEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Identifier for the corresponding McpToolCallBegin that finished.", + "type": "string" + }, + "duration": { + "$ref": "#/definitions/Duration" + }, + "invocation": { + "$ref": "#/definitions/McpInvocation" + }, + "result": { + "allOf": [ + { + "$ref": "#/definitions/Result_of_CallToolResult_or_String" + } + ], + "description": "Result of the tool call. Note this could be an error." + }, + "type": { + "enum": [ + "mcp_tool_call_end" + ], + "title": "McpToolCallEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "duration", + "invocation", + "result", + "type" + ], + "title": "McpToolCallEndEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "type": { + "enum": [ + "web_search_begin" + ], + "title": "WebSearchBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "type" + ], + "title": "WebSearchBeginEventMsg", + "type": "object" + }, + { + "properties": { + "action": { + "$ref": "#/definitions/WebSearchAction" + }, + "call_id": { + "type": "string" + }, + "query": { + "type": "string" + }, + "type": { + "enum": [ + "web_search_end" + ], + "title": "WebSearchEndEventMsgType", + "type": "string" + } + }, + "required": [ + "action", + "call_id", + "query", + "type" + ], + "title": "WebSearchEndEventMsg", + "type": "object" + }, + { + "description": "Notification that the server is about to execute a command.", + "properties": { + "call_id": { + "description": "Identifier so this can be paired with the ExecCommandEnd event.", + "type": "string" + }, + "command": { + "description": "The command to be executed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory if not the default cwd for the agent.", + "type": "string" + }, + "interaction_input": { + "description": "Raw input sent to a unified exec session (if this is an interaction event).", + "type": [ + "string", + "null" + ] + }, + "parsed_cmd": { + "items": { + "$ref": "#/definitions/ParsedCommand" + }, + "type": "array" + }, + "process_id": { + "description": "Identifier for the underlying PTY process (when available).", + "type": [ + "string", + "null" + ] + }, + "source": { + "allOf": [ + { + "$ref": "#/definitions/ExecCommandSource" + } + ], + "default": "agent", + "description": "Where the command originated. Defaults to Agent for backward compatibility." + }, + "turn_id": { + "description": "Turn ID that this command belongs to.", + "type": "string" + }, + "type": { + "enum": [ + "exec_command_begin" + ], + "title": "ExecCommandBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "command", + "cwd", + "parsed_cmd", + "turn_id", + "type" + ], + "title": "ExecCommandBeginEventMsg", + "type": "object" + }, + { + "description": "Incremental chunk of output from a running command.", + "properties": { + "call_id": { + "description": "Identifier for the ExecCommandBegin that produced this chunk.", + "type": "string" + }, + "chunk": { + "description": "Raw bytes from the stream (may not be valid UTF-8).", + "type": "string" + }, + "stream": { + "allOf": [ + { + "$ref": "#/definitions/ExecOutputStream" + } + ], + "description": "Which stream produced this chunk." + }, + "type": { + "enum": [ + "exec_command_output_delta" + ], + "title": "ExecCommandOutputDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "chunk", + "stream", + "type" + ], + "title": "ExecCommandOutputDeltaEventMsg", + "type": "object" + }, + { + "description": "Terminal interaction for an in-progress command (stdin sent and stdout observed).", + "properties": { + "call_id": { + "description": "Identifier for the ExecCommandBegin that produced this chunk.", + "type": "string" + }, + "process_id": { + "description": "Process id associated with the running command.", + "type": "string" + }, + "stdin": { + "description": "Stdin sent to the running session.", + "type": "string" + }, + "type": { + "enum": [ + "terminal_interaction" + ], + "title": "TerminalInteractionEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "process_id", + "stdin", + "type" + ], + "title": "TerminalInteractionEventMsg", + "type": "object" + }, + { + "properties": { + "aggregated_output": { + "default": "", + "description": "Captured aggregated output", + "type": "string" + }, + "call_id": { + "description": "Identifier for the ExecCommandBegin that finished.", + "type": "string" + }, + "command": { + "description": "The command that was executed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory if not the default cwd for the agent.", + "type": "string" + }, + "duration": { + "allOf": [ + { + "$ref": "#/definitions/Duration" + } + ], + "description": "The duration of the command execution." + }, + "exit_code": { + "description": "The command's exit code.", + "format": "int32", + "type": "integer" + }, + "formatted_output": { + "description": "Formatted output from the command, as seen by the model.", + "type": "string" + }, + "interaction_input": { + "description": "Raw input sent to a unified exec session (if this is an interaction event).", + "type": [ + "string", + "null" + ] + }, + "parsed_cmd": { + "items": { + "$ref": "#/definitions/ParsedCommand" + }, + "type": "array" + }, + "process_id": { + "description": "Identifier for the underlying PTY process (when available).", + "type": [ + "string", + "null" + ] + }, + "source": { + "allOf": [ + { + "$ref": "#/definitions/ExecCommandSource" + } + ], + "default": "agent", + "description": "Where the command originated. Defaults to Agent for backward compatibility." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/ExecCommandStatus" + } + ], + "description": "Completion status for this command execution." + }, + "stderr": { + "description": "Captured stderr", + "type": "string" + }, + "stdout": { + "description": "Captured stdout", + "type": "string" + }, + "turn_id": { + "description": "Turn ID that this command belongs to.", + "type": "string" + }, + "type": { + "enum": [ + "exec_command_end" + ], + "title": "ExecCommandEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "command", + "cwd", + "duration", + "exit_code", + "formatted_output", + "parsed_cmd", + "status", + "stderr", + "stdout", + "turn_id", + "type" + ], + "title": "ExecCommandEndEventMsg", + "type": "object" + }, + { + "description": "Notification that the agent attached a local image via the view_image tool.", + "properties": { + "call_id": { + "description": "Identifier for the originating tool call.", + "type": "string" + }, + "path": { + "description": "Local filesystem path provided to the tool.", + "type": "string" + }, + "type": { + "enum": [ + "view_image_tool_call" + ], + "title": "ViewImageToolCallEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "path", + "type" + ], + "title": "ViewImageToolCallEventMsg", + "type": "object" + }, + { + "properties": { + "additional_permissions": { + "anyOf": [ + { + "$ref": "#/definitions/PermissionProfile" + }, + { + "type": "null" + } + ], + "description": "Optional additional filesystem permissions requested for this command." + }, + "approval_id": { + "description": "Identifier for this specific approval callback.\n\nWhen absent, the approval is for the command item itself (`call_id`). This is present for subcommand approvals (via execve intercept).", + "type": [ + "string", + "null" + ] + }, + "available_decisions": { + "description": "Ordered list of decisions the client may present for this prompt.\n\nWhen absent, clients should derive the legacy default set from the other fields on this request.", + "items": { + "$ref": "#/definitions/ReviewDecision" + }, + "type": [ + "array", + "null" + ] + }, + "call_id": { + "description": "Identifier for the associated command execution item.", + "type": "string" + }, + "command": { + "description": "The command to be executed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory.", + "type": "string" + }, + "network_approval_context": { + "anyOf": [ + { + "$ref": "#/definitions/NetworkApprovalContext" + }, + { + "type": "null" + } + ], + "description": "Optional network context for a blocked request that can be approved." + }, + "parsed_cmd": { + "items": { + "$ref": "#/definitions/ParsedCommand" + }, + "type": "array" + }, + "proposed_execpolicy_amendment": { + "description": "Proposed execpolicy amendment that can be applied to allow future runs.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "proposed_network_policy_amendments": { + "description": "Proposed network policy amendments (for example allow/deny this host in future).", + "items": { + "$ref": "#/definitions/NetworkPolicyAmendment" + }, + "type": [ + "array", + "null" + ] + }, + "reason": { + "description": "Optional human-readable reason for the approval (e.g. retry without sandbox).", + "type": [ + "string", + "null" + ] + }, + "turn_id": { + "default": "", + "description": "Turn ID that this command belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "exec_approval_request" + ], + "title": "ExecApprovalRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "command", + "cwd", + "parsed_cmd", + "type" + ], + "title": "ExecApprovalRequestEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Responses API call id for the associated tool call, if available.", + "type": "string" + }, + "questions": { + "items": { + "$ref": "#/definitions/RequestUserInputQuestion" + }, + "type": "array" + }, + "turn_id": { + "default": "", + "description": "Turn ID that this request belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "request_user_input" + ], + "title": "RequestUserInputEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "questions", + "type" + ], + "title": "RequestUserInputEventMsg", + "type": "object" + }, + { + "properties": { + "arguments": true, + "callId": { + "type": "string" + }, + "tool": { + "type": "string" + }, + "turnId": { + "type": "string" + }, + "type": { + "enum": [ + "dynamic_tool_call_request" + ], + "title": "DynamicToolCallRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "arguments", + "callId", + "tool", + "turnId", + "type" + ], + "title": "DynamicToolCallRequestEventMsg", + "type": "object" + }, + { + "properties": { + "arguments": { + "description": "Dynamic tool call arguments." + }, + "call_id": { + "description": "Identifier for the corresponding DynamicToolCallRequest.", + "type": "string" + }, + "content_items": { + "description": "Dynamic tool response content items.", + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": "array" + }, + "duration": { + "allOf": [ + { + "$ref": "#/definitions/Duration" + } + ], + "description": "The duration of the dynamic tool call." + }, + "error": { + "description": "Optional error text when the tool call failed before producing a response.", + "type": [ + "string", + "null" + ] + }, + "success": { + "description": "Whether the tool call succeeded.", + "type": "boolean" + }, + "tool": { + "description": "Dynamic tool name.", + "type": "string" + }, + "turn_id": { + "description": "Turn ID that this dynamic tool call belongs to.", + "type": "string" + }, + "type": { + "enum": [ + "dynamic_tool_call_response" + ], + "title": "DynamicToolCallResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "arguments", + "call_id", + "content_items", + "duration", + "success", + "tool", + "turn_id", + "type" + ], + "title": "DynamicToolCallResponseEventMsg", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "message": { + "type": "string" + }, + "server_name": { + "type": "string" + }, + "type": { + "enum": [ + "elicitation_request" + ], + "title": "ElicitationRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "id", + "message", + "server_name", + "type" + ], + "title": "ElicitationRequestEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Responses API call id for the associated patch apply call, if available.", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/definitions/FileChange" + }, + "type": "object" + }, + "grant_root": { + "description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session.", + "type": [ + "string", + "null" + ] + }, + "reason": { + "description": "Optional explanatory reason (e.g. request for extra write access).", + "type": [ + "string", + "null" + ] + }, + "turn_id": { + "default": "", + "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility with older senders.", + "type": "string" + }, + "type": { + "enum": [ + "apply_patch_approval_request" + ], + "title": "ApplyPatchApprovalRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "changes", + "type" + ], + "title": "ApplyPatchApprovalRequestEventMsg", + "type": "object" + }, + { + "description": "Notification advising the user that something they are using has been deprecated and should be phased out.", + "properties": { + "details": { + "description": "Optional extra guidance, such as migration steps or rationale.", + "type": [ + "string", + "null" + ] + }, + "summary": { + "description": "Concise summary of what is deprecated.", + "type": "string" + }, + "type": { + "enum": [ + "deprecation_notice" + ], + "title": "DeprecationNoticeEventMsgType", + "type": "string" + } + }, + "required": [ + "summary", + "type" + ], + "title": "DeprecationNoticeEventMsg", + "type": "object" + }, + { + "properties": { + "message": { + "type": "string" + }, + "type": { + "enum": [ + "background_event" + ], + "title": "BackgroundEventEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "BackgroundEventEventMsg", + "type": "object" + }, + { + "properties": { + "message": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "undo_started" + ], + "title": "UndoStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UndoStartedEventMsg", + "type": "object" + }, + { + "properties": { + "message": { + "type": [ + "string", + "null" + ] + }, + "success": { + "type": "boolean" + }, + "type": { + "enum": [ + "undo_completed" + ], + "title": "UndoCompletedEventMsgType", + "type": "string" + } + }, + "required": [ + "success", + "type" + ], + "title": "UndoCompletedEventMsg", + "type": "object" + }, + { + "description": "Notification that a model stream experienced an error or disconnect and the system is handling it (e.g., retrying with backoff).", + "properties": { + "additional_details": { + "default": null, + "description": "Optional details about the underlying stream failure (often the same human-readable message that is surfaced as the terminal error if retries are exhausted).", + "type": [ + "string", + "null" + ] + }, + "codex_error_info": { + "anyOf": [ + { + "$ref": "#/definitions/CodexErrorInfo" + }, + { + "type": "null" + } + ], + "default": null + }, + "message": { + "type": "string" + }, + "type": { + "enum": [ + "stream_error" + ], + "title": "StreamErrorEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "StreamErrorEventMsg", + "type": "object" + }, + { + "description": "Notification that the agent is about to apply a code patch. Mirrors `ExecCommandBegin` so front‑ends can show progress indicators.", + "properties": { + "auto_approved": { + "description": "If true, there was no ApplyPatchApprovalRequest for this patch.", + "type": "boolean" + }, + "call_id": { + "description": "Identifier so this can be paired with the PatchApplyEnd event.", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/definitions/FileChange" + }, + "description": "The changes to be applied.", + "type": "object" + }, + "turn_id": { + "default": "", + "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "patch_apply_begin" + ], + "title": "PatchApplyBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "auto_approved", + "call_id", + "changes", + "type" + ], + "title": "PatchApplyBeginEventMsg", + "type": "object" + }, + { + "description": "Notification that a patch application has finished.", + "properties": { + "call_id": { + "description": "Identifier for the PatchApplyBegin that finished.", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/definitions/FileChange" + }, + "default": {}, + "description": "The changes that were applied (mirrors PatchApplyBeginEvent::changes).", + "type": "object" + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/PatchApplyStatus" + } + ], + "description": "Completion status for this patch application." + }, + "stderr": { + "description": "Captured stderr (parser errors, IO failures, etc.).", + "type": "string" + }, + "stdout": { + "description": "Captured stdout (summary printed by apply_patch).", + "type": "string" + }, + "success": { + "description": "Whether the patch was applied successfully.", + "type": "boolean" + }, + "turn_id": { + "default": "", + "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "patch_apply_end" + ], + "title": "PatchApplyEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "status", + "stderr", + "stdout", + "success", + "type" + ], + "title": "PatchApplyEndEventMsg", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "turn_diff" + ], + "title": "TurnDiffEventMsgType", + "type": "string" + }, + "unified_diff": { + "type": "string" + } + }, + "required": [ + "type", + "unified_diff" + ], + "title": "TurnDiffEventMsg", + "type": "object" + }, + { + "description": "Response to GetHistoryEntryRequest.", + "properties": { + "entry": { + "anyOf": [ + { + "$ref": "#/definitions/HistoryEntry" + }, + { + "type": "null" + } + ], + "description": "The entry at the requested offset, if available and parseable." + }, + "log_id": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "offset": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "type": { + "enum": [ + "get_history_entry_response" + ], + "title": "GetHistoryEntryResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "log_id", + "offset", + "type" + ], + "title": "GetHistoryEntryResponseEventMsg", + "type": "object" + }, + { + "description": "List of MCP tools available to the agent.", + "properties": { + "auth_statuses": { + "additionalProperties": { + "$ref": "#/definitions/McpAuthStatus" + }, + "description": "Authentication status for each configured MCP server.", + "type": "object" + }, + "resource_templates": { + "additionalProperties": { + "items": { + "$ref": "#/definitions/ResourceTemplate" + }, + "type": "array" + }, + "description": "Known resource templates grouped by server name.", + "type": "object" + }, + "resources": { + "additionalProperties": { + "items": { + "$ref": "#/definitions/Resource" + }, + "type": "array" + }, + "description": "Known resources grouped by server name.", + "type": "object" + }, + "tools": { + "additionalProperties": { + "$ref": "#/definitions/Tool" + }, + "description": "Fully qualified tool name -> tool definition.", + "type": "object" + }, + "type": { + "enum": [ + "mcp_list_tools_response" + ], + "title": "McpListToolsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "auth_statuses", + "resource_templates", + "resources", + "tools", + "type" + ], + "title": "McpListToolsResponseEventMsg", + "type": "object" + }, + { + "description": "List of custom prompts available to the agent.", + "properties": { + "custom_prompts": { + "items": { + "$ref": "#/definitions/CustomPrompt" + }, + "type": "array" + }, + "type": { + "enum": [ + "list_custom_prompts_response" + ], + "title": "ListCustomPromptsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "custom_prompts", + "type" + ], + "title": "ListCustomPromptsResponseEventMsg", + "type": "object" + }, + { + "description": "List of skills available to the agent.", + "properties": { + "skills": { + "items": { + "$ref": "#/definitions/SkillsListEntry" + }, + "type": "array" + }, + "type": { + "enum": [ + "list_skills_response" + ], + "title": "ListSkillsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "skills", + "type" + ], + "title": "ListSkillsResponseEventMsg", + "type": "object" + }, + { + "description": "List of remote skills available to the agent.", + "properties": { + "skills": { + "items": { + "$ref": "#/definitions/RemoteSkillSummary" + }, + "type": "array" + }, + "type": { + "enum": [ + "list_remote_skills_response" + ], + "title": "ListRemoteSkillsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "skills", + "type" + ], + "title": "ListRemoteSkillsResponseEventMsg", + "type": "object" + }, + { + "description": "Remote skill downloaded to local cache.", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "remote_skill_downloaded" + ], + "title": "RemoteSkillDownloadedEventMsgType", + "type": "string" + } + }, + "required": [ + "id", + "name", + "path", + "type" + ], + "title": "RemoteSkillDownloadedEventMsg", + "type": "object" + }, + { + "description": "Notification that skill data may have been updated and clients may want to reload.", + "properties": { + "type": { + "enum": [ + "skills_update_available" + ], + "title": "SkillsUpdateAvailableEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SkillsUpdateAvailableEventMsg", + "type": "object" + }, + { + "properties": { + "explanation": { + "default": null, + "description": "Arguments for the `update_plan` todo/checklist tool (not plan mode).", + "type": [ + "string", + "null" + ] + }, + "plan": { + "items": { + "$ref": "#/definitions/PlanItemArg" + }, + "type": "array" + }, + "type": { + "enum": [ + "plan_update" + ], + "title": "PlanUpdateEventMsgType", + "type": "string" + } + }, + "required": [ + "plan", + "type" + ], + "title": "PlanUpdateEventMsg", + "type": "object" + }, + { + "properties": { + "reason": { + "$ref": "#/definitions/TurnAbortReason" + }, + "turn_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "turn_aborted" + ], + "title": "TurnAbortedEventMsgType", + "type": "string" + } + }, + "required": [ + "reason", + "type" + ], + "title": "TurnAbortedEventMsg", + "type": "object" + }, + { + "description": "Notification that the agent is shutting down.", + "properties": { + "type": { + "enum": [ + "shutdown_complete" + ], + "title": "ShutdownCompleteEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ShutdownCompleteEventMsg", + "type": "object" + }, + { + "description": "Entered review mode.", + "properties": { + "target": { + "$ref": "#/definitions/ReviewTarget" + }, + "type": { + "enum": [ + "entered_review_mode" + ], + "title": "EnteredReviewModeEventMsgType", + "type": "string" + }, + "user_facing_hint": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "target", + "type" + ], + "title": "EnteredReviewModeEventMsg", + "type": "object" + }, + { + "description": "Exited review mode with an optional final result to apply.", + "properties": { + "review_output": { + "anyOf": [ + { + "$ref": "#/definitions/ReviewOutputEvent" + }, + { + "type": "null" + } + ] + }, + "type": { + "enum": [ + "exited_review_mode" + ], + "title": "ExitedReviewModeEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ExitedReviewModeEventMsg", + "type": "object" + }, + { + "properties": { + "item": { + "$ref": "#/definitions/ResponseItem" + }, + "type": { + "enum": [ + "raw_response_item" + ], + "title": "RawResponseItemEventMsgType", + "type": "string" + } + }, + "required": [ + "item", + "type" + ], + "title": "RawResponseItemEventMsg", + "type": "object" + }, + { + "properties": { + "item": { + "$ref": "#/definitions/TurnItem" + }, + "thread_id": { + "$ref": "#/definitions/ThreadId" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "item_started" + ], + "title": "ItemStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "item", + "thread_id", + "turn_id", + "type" + ], + "title": "ItemStartedEventMsg", + "type": "object" + }, + { + "properties": { + "item": { + "$ref": "#/definitions/TurnItem" + }, + "thread_id": { + "$ref": "#/definitions/ThreadId" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "item_completed" + ], + "title": "ItemCompletedEventMsgType", + "type": "string" + } + }, + "required": [ + "item", + "thread_id", + "turn_id", + "type" + ], + "title": "ItemCompletedEventMsg", + "type": "object" + }, + { + "properties": { + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "agent_message_content_delta" + ], + "title": "AgentMessageContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "AgentMessageContentDeltaEventMsg", + "type": "object" + }, + { + "properties": { + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "plan_delta" + ], + "title": "PlanDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "PlanDeltaEventMsg", + "type": "object" + }, + { + "properties": { + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "summary_index": { + "default": 0, + "format": "int64", + "type": "integer" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "reasoning_content_delta" + ], + "title": "ReasoningContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "ReasoningContentDeltaEventMsg", + "type": "object" + }, + { + "properties": { + "content_index": { + "default": 0, + "format": "int64", + "type": "integer" + }, + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "reasoning_raw_content_delta" + ], + "title": "ReasoningRawContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "ReasoningRawContentDeltaEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent spawn begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_agent_spawn_begin" + ], + "title": "CollabAgentSpawnBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "sender_thread_id", + "type" + ], + "title": "CollabAgentSpawnBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent spawn end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_thread_id": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadId" + }, + { + "type": "null" + } + ], + "description": "Thread ID of the newly spawned agent, if it was created." + }, + "prompt": { + "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the new agent reported to the sender agent." + }, + "type": { + "enum": [ + "collab_agent_spawn_end" + ], + "title": "CollabAgentSpawnEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabAgentSpawnEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent interaction begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_agent_interaction_begin" + ], + "title": "CollabAgentInteractionBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "receiver_thread_id", + "sender_thread_id", + "type" + ], + "title": "CollabAgentInteractionBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent interaction end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the receiver agent reported to the sender agent." + }, + "type": { + "enum": [ + "collab_agent_interaction_end" + ], + "title": "CollabAgentInteractionEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "receiver_thread_id", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabAgentInteractionEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: waiting begin.", + "properties": { + "call_id": { + "description": "ID of the waiting call.", + "type": "string" + }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, + "receiver_thread_ids": { + "description": "Thread ID of the receivers.", + "items": { + "$ref": "#/definitions/ThreadId" + }, + "type": "array" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_waiting_begin" + ], + "title": "CollabWaitingBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_ids", + "sender_thread_id", + "type" + ], + "title": "CollabWaitingBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: waiting end.", + "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, + "call_id": { + "description": "ID of the waiting call.", + "type": "string" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "statuses": { + "additionalProperties": { + "$ref": "#/definitions/AgentStatus" + }, + "description": "Last known status of the receiver agents reported to the sender agent.", + "type": "object" + }, + "type": { + "enum": [ + "collab_waiting_end" + ], + "title": "CollabWaitingEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "sender_thread_id", + "statuses", + "type" + ], + "title": "CollabWaitingEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: close begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_close_begin" + ], + "title": "CollabCloseBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "type" + ], + "title": "CollabCloseBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: close end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the receiver agent reported to the sender agent before the close." + }, + "type": { + "enum": [ + "collab_close_end" + ], + "title": "CollabCloseEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabCloseEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: resume begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_resume_begin" + ], + "title": "CollabResumeBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "type" + ], + "title": "CollabResumeBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: resume end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the receiver agent reported to the sender agent after resume." + }, + "type": { + "enum": [ + "collab_resume_end" + ], + "title": "CollabResumeEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabResumeEndEventMsg", + "type": "object" + } + ], + "title": "EventMsg" + }, + "ExecCommandSource": { + "enum": [ + "agent", + "user_shell", + "unified_exec_startup", + "unified_exec_interaction" + ], + "type": "string" + }, + "ExecCommandStatus": { + "enum": [ + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "ExecOutputStream": { + "enum": [ + "stdout", + "stderr" + ], + "type": "string" + }, + "ExperimentalFeature": { + "properties": { + "announcement": { + "description": "Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.", + "type": [ + "string", + "null" + ] + }, + "defaultEnabled": { + "description": "Whether this feature is enabled by default.", + "type": "boolean" + }, + "description": { + "description": "Short summary describing what the feature does. Null when this feature is not in beta.", + "type": [ + "string", + "null" + ] + }, + "displayName": { + "description": "User-facing display name shown in the experimental features UI. Null when this feature is not in beta.", + "type": [ + "string", + "null" + ] + }, + "enabled": { + "description": "Whether this feature is currently enabled in the loaded config.", + "type": "boolean" + }, + "name": { + "description": "Stable key used in config.toml and CLI flag toggles.", + "type": "string" + }, + "stage": { + "allOf": [ + { + "$ref": "#/definitions/ExperimentalFeatureStage" + } + ], + "description": "Lifecycle stage of this feature flag." + } + }, + "required": [ + "defaultEnabled", + "enabled", + "name", + "stage" + ], + "type": "object" + }, + "ExperimentalFeatureListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ExperimentalFeatureListParams", + "type": "object" + }, + "ExperimentalFeatureListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/ExperimentalFeature" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ExperimentalFeatureListResponse", + "type": "object" + }, + "ExperimentalFeatureStage": { + "oneOf": [ + { + "description": "Feature is available for user testing and feedback.", + "enum": [ + "beta" + ], + "type": "string" + }, + { + "description": "Feature is still being built and not ready for broad use.", + "enum": [ + "underDevelopment" + ], + "type": "string" + }, + { + "description": "Feature is production-ready.", + "enum": [ + "stable" + ], + "type": "string" + }, + { + "description": "Feature is deprecated and should be avoided.", + "enum": [ + "deprecated" + ], + "type": "string" + }, + { + "description": "Feature flag is retained only for backwards compatibility.", + "enum": [ + "removed" + ], + "type": "string" + } + ] + }, + "ExternalAgentConfigDetectParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cwds": { + "description": "Zero or more working directories to include for repo-scoped detection.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "includeHome": { + "description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).", + "type": "boolean" + } + }, + "title": "ExternalAgentConfigDetectParams", + "type": "object" + }, + "ExternalAgentConfigDetectResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "items": { + "items": { + "$ref": "#/definitions/ExternalAgentConfigMigrationItem" + }, + "type": "array" + } + }, + "required": [ + "items" + ], + "title": "ExternalAgentConfigDetectResponse", + "type": "object" + }, + "ExternalAgentConfigImportParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "migrationItems": { + "items": { + "$ref": "#/definitions/ExternalAgentConfigMigrationItem" + }, + "type": "array" + } + }, + "required": [ + "migrationItems" + ], + "title": "ExternalAgentConfigImportParams", + "type": "object" + }, + "ExternalAgentConfigImportResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ExternalAgentConfigImportResponse", + "type": "object" + }, + "ExternalAgentConfigMigrationItem": { + "properties": { + "cwd": { + "description": "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + "type": [ + "string", + "null" + ] + }, + "description": { + "type": "string" + }, + "itemType": { + "$ref": "#/definitions/ExternalAgentConfigMigrationItemType" + } + }, + "required": [ + "description", + "itemType" + ], + "type": "object" + }, + "ExternalAgentConfigMigrationItemType": { + "enum": [ + "AGENTS_MD", + "CONFIG", + "SKILLS", + "MCP_SERVER_CONFIG" + ], + "type": "string" + }, + "FeedbackUploadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "classification": { + "type": "string" + }, + "extraLogFiles": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "includeLogs": { + "type": "boolean" + }, + "reason": { + "type": [ + "string", + "null" + ] + }, + "threadId": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "classification", + "includeLogs" + ], + "title": "FeedbackUploadParams", + "type": "object" + }, + "FeedbackUploadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "FeedbackUploadResponse", + "type": "object" + }, + "FileChange": { + "oneOf": [ + { + "properties": { + "content": { + "type": "string" + }, + "type": { + "enum": [ + "add" + ], + "title": "AddFileChangeType", + "type": "string" + } + }, + "required": [ + "content", + "type" + ], + "title": "AddFileChange", + "type": "object" + }, + { + "properties": { + "content": { + "type": "string" + }, + "type": { + "enum": [ + "delete" + ], + "title": "DeleteFileChangeType", + "type": "string" + } + }, + "required": [ + "content", + "type" + ], + "title": "DeleteFileChange", + "type": "object" + }, + { + "properties": { + "move_path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "update" + ], + "title": "UpdateFileChangeType", + "type": "string" + }, + "unified_diff": { + "type": "string" + } + }, + "required": [ + "type", + "unified_diff" + ], + "title": "UpdateFileChange", + "type": "object" + } + ] + }, + "FileChangeOutputDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "FileChangeOutputDeltaNotification", + "type": "object" + }, + "FileSystemPermissions": { + "properties": { + "read": { + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": [ + "array", + "null" + ] + }, + "write": { + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": [ + "array", + "null" + ] + } + }, + "type": "object" + }, + "FileUpdateChange": { + "properties": { + "diff": { + "type": "string" + }, + "kind": { + "$ref": "#/definitions/PatchChangeKind" + }, + "path": { + "type": "string" + } + }, + "required": [ + "diff", + "kind", + "path" + ], + "type": "object" + }, + "ForcedLoginMethod": { + "enum": [ + "chatgpt", + "api" + ], + "type": "string" + }, + "FunctionCallOutputBody": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "$ref": "#/definitions/FunctionCallOutputContentItem" + }, + "type": "array" + } + ] + }, + "FunctionCallOutputContentItem": { + "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "input_text" + ], + "title": "InputTextFunctionCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextFunctionCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "image_url": { + "type": "string" + }, + "type": { + "enum": [ + "input_image" + ], + "title": "InputImageFunctionCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "image_url", + "type" + ], + "title": "InputImageFunctionCallOutputContentItem", + "type": "object" + } + ] + }, + "FunctionCallOutputPayload": { + "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", + "properties": { + "body": { + "$ref": "#/definitions/FunctionCallOutputBody" + }, + "success": { + "type": [ + "boolean", + "null" + ] + } + }, + "required": [ + "body" + ], + "type": "object" + }, + "FuzzyFileSearchParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cancellationToken": { + "type": [ + "string", + "null" + ] + }, + "query": { + "type": "string" + }, + "roots": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "query", + "roots" + ], + "title": "FuzzyFileSearchParams", + "type": "object" + }, + "FuzzyFileSearchResult": { + "description": "Superset of [`codex_file_search::FileMatch`]", + "properties": { + "file_name": { + "type": "string" + }, + "indices": { + "items": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "type": [ + "array", + "null" + ] + }, + "path": { + "type": "string" + }, + "root": { + "type": "string" + }, + "score": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "file_name", + "path", + "root", + "score" + ], + "type": "object" + }, + "FuzzyFileSearchSessionCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "sessionId": { + "type": "string" + } + }, + "required": [ + "sessionId" + ], + "title": "FuzzyFileSearchSessionCompletedNotification", + "type": "object" + }, + "FuzzyFileSearchSessionUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "files": { + "items": { + "$ref": "#/definitions/FuzzyFileSearchResult" + }, + "type": "array" + }, + "query": { + "type": "string" + }, + "sessionId": { + "type": "string" + } + }, + "required": [ + "files", + "query", + "sessionId" + ], + "title": "FuzzyFileSearchSessionUpdatedNotification", + "type": "object" + }, + "GetAccountParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "refreshToken": { + "default": false, + "description": "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.", + "type": "boolean" + } + }, + "title": "GetAccountParams", + "type": "object" + }, + "GetAccountRateLimitsResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "rateLimits": { + "allOf": [ + { + "$ref": "#/definitions/RateLimitSnapshot" + } + ], + "description": "Backward-compatible single-bucket view; mirrors the historical payload." + }, + "rateLimitsByLimitId": { + "additionalProperties": { + "$ref": "#/definitions/RateLimitSnapshot" + }, + "description": "Multi-bucket view keyed by metered `limit_id` (for example, `codex`).", + "type": [ + "object", + "null" + ] + } + }, + "required": [ + "rateLimits" + ], + "title": "GetAccountRateLimitsResponse", + "type": "object" + }, + "GetAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "account": { + "anyOf": [ + { + "$ref": "#/definitions/Account" + }, + { + "type": "null" + } + ] + }, + "requiresOpenaiAuth": { + "type": "boolean" + } + }, + "required": [ + "requiresOpenaiAuth" + ], + "title": "GetAccountResponse", + "type": "object" + }, + "GhostCommit": { + "description": "Details of a ghost commit created from a repository state.", + "properties": { + "id": { + "type": "string" + }, + "parent": { + "type": [ + "string", + "null" + ] + }, + "preexisting_untracked_dirs": { + "items": { + "type": "string" + }, + "type": "array" + }, + "preexisting_untracked_files": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "id", + "preexisting_untracked_dirs", + "preexisting_untracked_files" + ], + "type": "object" + }, + "GitInfo": { + "properties": { + "branch": { + "type": [ + "string", + "null" + ] + }, + "originUrl": { + "type": [ + "string", + "null" + ] + }, + "sha": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "HazelnutScope": { + "enum": [ + "example", + "workspace-shared", + "all-shared", + "personal" + ], + "type": "string" + }, + "HistoryEntry": { + "properties": { + "conversation_id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "ts": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "conversation_id", + "text", + "ts" + ], + "type": "object" + }, + "InitializeCapabilities": { + "description": "Client-declared capabilities negotiated during initialize.", + "properties": { + "experimentalApi": { + "default": false, + "description": "Opt into receiving experimental API methods and fields.", + "type": "boolean" + }, + "optOutNotificationMethods": { + "description": "Exact notification method names that should be suppressed for this connection (for example `codex/event/session_configured`).", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + } + }, + "type": "object" + }, + "InitializeParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "capabilities": { + "anyOf": [ + { + "$ref": "#/definitions/InitializeCapabilities" + }, + { + "type": "null" + } + ] + }, + "clientInfo": { + "$ref": "#/definitions/ClientInfo" + } + }, + "required": [ + "clientInfo" + ], + "title": "InitializeParams", + "type": "object" + }, + "InputModality": { + "description": "Canonical user-input modality tags advertised by a model.", + "oneOf": [ + { + "description": "Plain text turns and tool payloads.", + "enum": [ + "text" + ], + "type": "string" + }, + { + "description": "Image attachments included in user turns.", + "enum": [ + "image" + ], + "type": "string" + } + ] + }, + "ItemCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "item": { + "$ref": "#/definitions/ThreadItem" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId", + "turnId" + ], + "title": "ItemCompletedNotification", + "type": "object" + }, + "ItemStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "item": { + "$ref": "#/definitions/ThreadItem" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId", + "turnId" + ], + "title": "ItemStartedNotification", + "type": "object" + }, + "ListMcpServerStatusParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a server-defined value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ListMcpServerStatusParams", + "type": "object" + }, + "ListMcpServerStatusResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/McpServerStatus" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ListMcpServerStatusResponse", + "type": "object" + }, + "LocalShellAction": { + "oneOf": [ + { + "properties": { + "command": { + "items": { + "type": "string" + }, + "type": "array" + }, + "env": { + "additionalProperties": { + "type": "string" + }, + "type": [ + "object", + "null" + ] + }, + "timeout_ms": { + "format": "uint64", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "type": { + "enum": [ + "exec" + ], + "title": "ExecLocalShellActionType", + "type": "string" + }, + "user": { + "type": [ + "string", + "null" + ] + }, + "working_directory": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "command", + "type" + ], + "title": "ExecLocalShellAction", + "type": "object" + } + ] + }, + "LocalShellStatus": { + "enum": [ + "completed", + "in_progress", + "incomplete" + ], + "type": "string" + }, + "LoginAccountParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "oneOf": [ + { + "properties": { + "apiKey": { + "type": "string" + }, + "type": { + "enum": [ + "apiKey" + ], + "title": "ApiKeyv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "apiKey", + "type" + ], + "title": "ApiKeyv2::LoginAccountParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "chatgpt" + ], + "title": "Chatgptv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "Chatgptv2::LoginAccountParams", + "type": "object" + }, + { + "description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.", + "properties": { + "accessToken": { + "description": "Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.", + "type": "string" + }, + "chatgptAccountId": { + "description": "Workspace/account identifier supplied by the client.", + "type": "string" + }, + "chatgptPlanType": { + "description": "Optional plan type supplied by the client.\n\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.", + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "chatgptAuthTokens" + ], + "title": "ChatgptAuthTokensv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "accessToken", + "chatgptAccountId", + "type" + ], + "title": "ChatgptAuthTokensv2::LoginAccountParams", + "type": "object" + } + ], + "title": "LoginAccountParams" + }, + "LoginAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "apiKey" + ], + "title": "ApiKeyv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ApiKeyv2::LoginAccountResponse", + "type": "object" + }, + { + "properties": { + "authUrl": { + "description": "URL the client should open in a browser to initiate the OAuth flow.", + "type": "string" + }, + "loginId": { + "type": "string" + }, + "type": { + "enum": [ + "chatgpt" + ], + "title": "Chatgptv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "authUrl", + "loginId", + "type" + ], + "title": "Chatgptv2::LoginAccountResponse", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "chatgptAuthTokens" + ], + "title": "ChatgptAuthTokensv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ChatgptAuthTokensv2::LoginAccountResponse", + "type": "object" + } + ], + "title": "LoginAccountResponse" + }, + "LogoutAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "LogoutAccountResponse", + "type": "object" + }, + "MacOsAutomationValue": { + "anyOf": [ + { + "type": "boolean" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ] + }, + "MacOsPermissions": { + "properties": { + "accessibility": { + "type": [ + "boolean", + "null" + ] + }, + "automations": { + "anyOf": [ + { + "$ref": "#/definitions/MacOsAutomationValue" + }, + { + "type": "null" + } + ] + }, + "calendar": { + "type": [ + "boolean", + "null" + ] + }, + "preferences": { + "anyOf": [ + { + "$ref": "#/definitions/MacOsPreferencesValue" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "MacOsPreferencesValue": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string" + } + ] + }, + "McpAuthStatus": { + "enum": [ + "unsupported", + "notLoggedIn", + "bearerToken", + "oAuth" + ], + "type": "string" + }, + "McpInvocation": { + "properties": { + "arguments": { + "description": "Arguments to the tool call." + }, + "server": { + "description": "Name of the MCP server as defined in the config.", + "type": "string" + }, + "tool": { + "description": "Name of the tool as given by the MCP server.", + "type": "string" + } + }, + "required": [ + "server", + "tool" + ], + "type": "object" + }, + "McpServerOauthLoginCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "name", + "success" + ], + "title": "McpServerOauthLoginCompletedNotification", + "type": "object" + }, + "McpServerOauthLoginParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "name": { + "type": "string" + }, + "scopes": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "timeoutSecs": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "name" + ], + "title": "McpServerOauthLoginParams", + "type": "object" + }, + "McpServerOauthLoginResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "authorizationUrl": { + "type": "string" + } + }, + "required": [ + "authorizationUrl" + ], + "title": "McpServerOauthLoginResponse", + "type": "object" + }, + "McpServerRefreshResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "McpServerRefreshResponse", + "type": "object" + }, + "McpServerStatus": { + "properties": { + "authStatus": { + "$ref": "#/definitions/McpAuthStatus" + }, + "name": { + "type": "string" + }, + "resourceTemplates": { + "items": { + "$ref": "#/definitions/ResourceTemplate" + }, + "type": "array" + }, + "resources": { + "items": { + "$ref": "#/definitions/Resource" + }, + "type": "array" + }, + "tools": { + "additionalProperties": { + "$ref": "#/definitions/Tool" + }, + "type": "object" + } + }, + "required": [ + "authStatus", + "name", + "resourceTemplates", + "resources", + "tools" + ], + "type": "object" + }, + "McpStartupFailure": { + "properties": { + "error": { + "type": "string" + }, + "server": { + "type": "string" + } + }, + "required": [ + "error", + "server" + ], + "type": "object" + }, + "McpStartupStatus": { + "oneOf": [ + { + "properties": { + "state": { + "enum": [ + "starting" + ], + "type": "string" + } + }, + "required": [ + "state" + ], + "title": "StartingMcpStartupStatus", + "type": "object" + }, + { + "properties": { + "state": { + "enum": [ + "ready" + ], + "type": "string" + } + }, + "required": [ + "state" + ], + "title": "ReadyMcpStartupStatus", + "type": "object" + }, + { + "properties": { + "error": { + "type": "string" + }, + "state": { + "enum": [ + "failed" + ], + "type": "string" + } + }, + "required": [ + "error", + "state" + ], + "type": "object" + }, + { + "properties": { + "state": { + "enum": [ + "cancelled" + ], + "type": "string" + } + }, + "required": [ + "state" + ], + "title": "CancelledMcpStartupStatus", + "type": "object" + } + ] + }, + "McpToolCallError": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "McpToolCallProgressNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "itemId": { + "type": "string" + }, + "message": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "itemId", + "message", + "threadId", + "turnId" + ], + "title": "McpToolCallProgressNotification", + "type": "object" + }, + "McpToolCallResult": { + "properties": { + "content": { + "items": true, + "type": "array" + }, + "structuredContent": true + }, + "required": [ + "content" + ], + "type": "object" + }, + "McpToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "MergeStrategy": { + "enum": [ + "replace", + "upsert" + ], + "type": "string" + }, + "MessagePhase": { + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] + }, + "ModeKind": { + "description": "Initial collaboration mode to use when the TUI starts.", + "enum": [ + "plan", + "default" + ], + "type": "string" + }, + "Model": { + "properties": { + "availabilityNux": { + "anyOf": [ + { + "$ref": "#/definitions/ModelAvailabilityNux" + }, + { + "type": "null" + } + ] + }, + "defaultReasoningEffort": { + "$ref": "#/definitions/ReasoningEffort" + }, + "description": { + "type": "string" + }, + "displayName": { + "type": "string" + }, + "hidden": { + "type": "boolean" + }, + "id": { + "type": "string" + }, + "inputModalities": { + "default": [ + "text", + "image" + ], + "items": { + "$ref": "#/definitions/InputModality" + }, + "type": "array" + }, + "isDefault": { + "type": "boolean" + }, + "model": { + "type": "string" + }, + "supportedReasoningEfforts": { + "items": { + "$ref": "#/definitions/ReasoningEffortOption" + }, + "type": "array" + }, + "supportsPersonality": { + "default": false, + "type": "boolean" + }, + "upgrade": { + "type": [ + "string", + "null" + ] + }, + "upgradeInfo": { + "anyOf": [ + { + "$ref": "#/definitions/ModelUpgradeInfo" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "defaultReasoningEffort", + "description", + "displayName", + "hidden", + "id", + "isDefault", + "model", + "supportedReasoningEfforts" + ], + "type": "object" + }, + "ModelAvailabilityNux": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "ModelListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "includeHidden": { + "description": "When true, include models that are hidden from the default picker list.", + "type": [ + "boolean", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ModelListParams", + "type": "object" + }, + "ModelListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/Model" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ModelListResponse", + "type": "object" + }, + "ModelRerouteReason": { + "enum": [ + "highRiskCyberActivity" + ], + "type": "string" + }, + "ModelReroutedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "fromModel": { + "type": "string" + }, + "reason": { + "$ref": "#/definitions/ModelRerouteReason" + }, + "threadId": { + "type": "string" + }, + "toModel": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "fromModel", + "reason", + "threadId", + "toModel", + "turnId" + ], + "title": "ModelReroutedNotification", + "type": "object" + }, + "ModelUpgradeInfo": { + "properties": { + "migrationMarkdown": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": "string" + }, + "modelLink": { + "type": [ + "string", + "null" + ] + }, + "upgradeCopy": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "model" + ], + "type": "object" + }, + "NetworkAccess": { + "enum": [ + "restricted", + "enabled" + ], + "type": "string" + }, + "NetworkApprovalContext": { + "properties": { + "host": { + "type": "string" + }, + "protocol": { + "$ref": "#/definitions/NetworkApprovalProtocol" + } + }, + "required": [ + "host", + "protocol" + ], + "type": "object" + }, + "NetworkApprovalProtocol": { + "enum": [ + "http", + "https", + "socks5Tcp", + "socks5Udp" + ], + "type": "string" + }, + "NetworkPolicyAmendment": { + "properties": { + "action": { + "$ref": "#/definitions/NetworkPolicyRuleAction" + }, + "host": { + "type": "string" + } + }, + "required": [ + "action", + "host" + ], + "type": "object" + }, + "NetworkPolicyRuleAction": { + "enum": [ + "allow", + "deny" + ], + "type": "string" + }, + "NetworkRequirements": { + "properties": { + "allowLocalBinding": { + "type": [ + "boolean", + "null" + ] + }, + "allowUnixSockets": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "allowUpstreamProxy": { + "type": [ + "boolean", + "null" + ] + }, + "allowedDomains": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "dangerouslyAllowAllUnixSockets": { + "type": [ + "boolean", + "null" + ] + }, + "dangerouslyAllowNonLoopbackAdmin": { + "type": [ + "boolean", + "null" + ] + }, + "dangerouslyAllowNonLoopbackProxy": { + "type": [ + "boolean", + "null" + ] + }, + "deniedDomains": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "enabled": { + "type": [ + "boolean", + "null" + ] + }, + "httpPort": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "socksPort": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + }, + "OverriddenMetadata": { + "properties": { + "effectiveValue": true, + "message": { + "type": "string" + }, + "overridingLayer": { + "$ref": "#/definitions/ConfigLayerMetadata" + } + }, + "required": [ + "effectiveValue", + "message", + "overridingLayer" + ], + "type": "object" + }, + "ParsedCommand": { + "oneOf": [ + { + "properties": { + "cmd": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", + "type": "string" + }, + "type": { + "enum": [ + "read" + ], + "title": "ReadParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "name", + "path", + "type" + ], + "title": "ReadParsedCommand", + "type": "object" + }, + { + "properties": { + "cmd": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "list_files" + ], + "title": "ListFilesParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "type" + ], + "title": "ListFilesParsedCommand", + "type": "object" + }, + { + "properties": { + "cmd": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "type" + ], + "title": "SearchParsedCommand", + "type": "object" + }, + { + "properties": { + "cmd": { + "type": "string" + }, + "type": { + "enum": [ + "unknown" + ], + "title": "UnknownParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "type" + ], + "title": "UnknownParsedCommand", + "type": "object" + } + ] + }, + "PatchApplyStatus": { + "enum": [ + "inProgress", + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "PatchChangeKind": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "add" + ], + "title": "AddPatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AddPatchChangeKind", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "delete" + ], + "title": "DeletePatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DeletePatchChangeKind", + "type": "object" + }, + { + "properties": { + "move_path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "update" + ], + "title": "UpdatePatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UpdatePatchChangeKind", + "type": "object" + } + ] + }, + "PermissionProfile": { + "properties": { + "file_system": { + "anyOf": [ + { + "$ref": "#/definitions/FileSystemPermissions" + }, + { + "type": "null" + } + ] + }, + "macos": { + "anyOf": [ + { + "$ref": "#/definitions/MacOsPermissions" + }, + { + "type": "null" + } + ] + }, + "network": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "Personality": { + "enum": [ + "none", + "friendly", + "pragmatic" + ], + "type": "string" + }, + "PlanDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "PlanDeltaNotification", + "type": "object" + }, + "PlanItemArg": { + "additionalProperties": false, + "properties": { + "status": { + "$ref": "#/definitions/StepStatus" + }, + "step": { + "type": "string" + } + }, + "required": [ + "status", + "step" + ], + "type": "object" + }, + "PlanType": { + "enum": [ + "free", + "go", + "plus", + "pro", + "team", + "business", + "enterprise", + "edu", + "unknown" + ], + "type": "string" + }, + "ProductSurface": { + "enum": [ + "chatgpt", + "codex", + "api", + "atlas" + ], + "type": "string" + }, + "ProfileV2": { + "additionalProperties": true, + "properties": { + "approval_policy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "chatgpt_base_url": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "model_provider": { + "type": [ + "string", + "null" + ] + }, + "model_reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "model_reasoning_summary": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningSummary" + }, + { + "type": "null" + } + ] + }, + "model_verbosity": { + "anyOf": [ + { + "$ref": "#/definitions/Verbosity" + }, + { + "type": "null" + } + ] + }, + "web_search": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchMode" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "RateLimitSnapshot": { + "properties": { + "credits": { + "anyOf": [ + { + "$ref": "#/definitions/CreditsSnapshot" + }, + { + "type": "null" + } + ] + }, + "limitId": { + "type": [ + "string", + "null" + ] + }, + "limitName": { + "type": [ + "string", + "null" + ] + }, + "planType": { + "anyOf": [ + { + "$ref": "#/definitions/PlanType" + }, + { + "type": "null" + } + ] + }, + "primary": { + "anyOf": [ + { + "$ref": "#/definitions/RateLimitWindow" + }, + { + "type": "null" + } + ] + }, + "secondary": { + "anyOf": [ + { + "$ref": "#/definitions/RateLimitWindow" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "RateLimitWindow": { + "properties": { + "resetsAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "usedPercent": { + "format": "int32", + "type": "integer" + }, + "windowDurationMins": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "usedPercent" + ], + "type": "object" + }, + "RawResponseItemCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "item": { + "$ref": "#/definitions/ResponseItem" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId", + "turnId" + ], + "title": "RawResponseItemCompletedNotification", + "type": "object" + }, + "ReadOnlyAccess": { + "oneOf": [ + { + "properties": { + "includePlatformDefaults": { + "default": true, + "type": "boolean" + }, + "readableRoots": { + "default": [], + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": "array" + }, + "type": { + "enum": [ + "restricted" + ], + "title": "RestrictedReadOnlyAccessType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RestrictedReadOnlyAccess", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "fullAccess" + ], + "title": "FullAccessReadOnlyAccessType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "FullAccessReadOnlyAccess", + "type": "object" + } + ] + }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "instructions": { + "type": [ + "string", + "null" + ] + }, + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemDone": { + "properties": { + "item_id": { + "type": "string" + } + }, + "required": [ + "item_id" + ], + "type": "object" + } + }, + "required": [ + "ConversationItemDone" + ], + "title": "ConversationItemDoneRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "HandoffRequested": { + "$ref": "#/definitions/RealtimeHandoffRequested" + } + }, + "required": [ + "HandoffRequested" + ], + "title": "HandoffRequestedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, + "RealtimeHandoffMessage": { + "properties": { + "role": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "role", + "text" + ], + "type": "object" + }, + "RealtimeHandoffRequested": { + "properties": { + "handoff_id": { + "type": "string" + }, + "input_transcript": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "messages": { + "items": { + "$ref": "#/definitions/RealtimeHandoffMessage" + }, + "type": "array" + } + }, + "required": [ + "handoff_id", + "input_transcript", + "item_id", + "messages" + ], + "type": "object" + }, + "ReasoningEffort": { + "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", + "enum": [ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh" + ], + "type": "string" + }, + "ReasoningEffortOption": { + "properties": { + "description": { + "type": "string" + }, + "reasoningEffort": { + "$ref": "#/definitions/ReasoningEffort" + } + }, + "required": [ + "description", + "reasoningEffort" + ], + "type": "object" + }, + "ReasoningItemContent": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "reasoning_text" + ], + "title": "ReasoningTextReasoningItemContentType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "ReasoningTextReasoningItemContent", + "type": "object" + }, + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "text" + ], + "title": "TextReasoningItemContentType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "TextReasoningItemContent", + "type": "object" + } + ] + }, + "ReasoningItemReasoningSummary": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "summary_text" + ], + "title": "SummaryTextReasoningItemReasoningSummaryType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "SummaryTextReasoningItemReasoningSummary", + "type": "object" + } + ] + }, + "ReasoningSummary": { + "description": "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", + "oneOf": [ + { + "enum": [ + "auto", + "concise", + "detailed" + ], + "type": "string" + }, + { + "description": "Option to disable reasoning summaries.", + "enum": [ + "none" + ], + "type": "string" + } + ] + }, + "ReasoningSummaryPartAddedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "itemId": { + "type": "string" + }, + "summaryIndex": { + "format": "int64", + "type": "integer" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "itemId", + "summaryIndex", + "threadId", + "turnId" + ], + "title": "ReasoningSummaryPartAddedNotification", + "type": "object" + }, + "ReasoningSummaryTextDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "summaryIndex": { + "format": "int64", + "type": "integer" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "summaryIndex", + "threadId", + "turnId" + ], + "title": "ReasoningSummaryTextDeltaNotification", + "type": "object" + }, + "ReasoningTextDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "contentIndex": { + "format": "int64", + "type": "integer" + }, + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "contentIndex", + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "ReasoningTextDeltaNotification", + "type": "object" + }, + "RemoteSkillSummary": { + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "description", + "id", + "name" + ], + "type": "object" + }, + "RequestId": { + "anyOf": [ + { + "type": "string" + }, + { + "format": "int64", + "type": "integer" + } + ] + }, + "RequestUserInputQuestion": { + "properties": { + "header": { + "type": "string" + }, + "id": { + "type": "string" + }, + "isOther": { + "default": false, + "type": "boolean" + }, + "isSecret": { + "default": false, + "type": "boolean" + }, + "options": { + "items": { + "$ref": "#/definitions/RequestUserInputQuestionOption" + }, + "type": [ + "array", + "null" + ] + }, + "question": { + "type": "string" + } + }, + "required": [ + "header", + "id", + "question" + ], + "type": "object" + }, + "RequestUserInputQuestionOption": { + "properties": { + "description": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "description", + "label" + ], + "type": "object" + }, + "ResidencyRequirement": { + "enum": [ + "us" + ], + "type": "string" + }, + "Resource": { + "description": "A known resource that the server is capable of reading.", + "properties": { + "_meta": true, + "annotations": true, + "description": { + "type": [ + "string", + "null" + ] + }, + "icons": { + "items": true, + "type": [ + "array", + "null" + ] + }, + "mimeType": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "size": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "uri": { + "type": "string" + } + }, + "required": [ + "name", + "uri" + ], + "type": "object" + }, + "ResourceTemplate": { + "description": "A template description for resources available on the server.", + "properties": { + "annotations": true, + "description": { + "type": [ + "string", + "null" + ] + }, + "mimeType": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "uriTemplate": { + "type": "string" + } + }, + "required": [ + "name", + "uriTemplate" + ], + "type": "object" + }, + "ResponseItem": { + "oneOf": [ + { + "properties": { + "content": { + "items": { + "$ref": "#/definitions/ContentItem" + }, + "type": "array" + }, + "end_turn": { + "type": [ + "boolean", + "null" + ] + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ] + }, + "role": { + "type": "string" + }, + "type": { + "enum": [ + "message" + ], + "title": "MessageResponseItemType", + "type": "string" + } + }, + "required": [ + "content", + "role", + "type" + ], + "title": "MessageResponseItem", + "type": "object" + }, + { + "properties": { + "content": { + "default": null, + "items": { + "$ref": "#/definitions/ReasoningItemContent" + }, + "type": [ + "array", + "null" + ] + }, + "encrypted_content": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string", + "writeOnly": true + }, + "summary": { + "items": { + "$ref": "#/definitions/ReasoningItemReasoningSummary" + }, + "type": "array" + }, + "type": { + "enum": [ + "reasoning" + ], + "title": "ReasoningResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "summary", + "type" + ], + "title": "ReasoningResponseItem", + "type": "object" + }, + { + "properties": { + "action": { + "$ref": "#/definitions/LocalShellAction" + }, + "call_id": { + "description": "Set when using the Responses API.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Legacy id field retained for compatibility with older payloads.", + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "status": { + "$ref": "#/definitions/LocalShellStatus" + }, + "type": { + "enum": [ + "local_shell_call" + ], + "title": "LocalShellCallResponseItemType", + "type": "string" + } + }, + "required": [ + "action", + "status", + "type" + ], + "title": "LocalShellCallResponseItem", + "type": "object" + }, + { + "properties": { + "arguments": { + "type": "string" + }, + "call_id": { + "type": "string" + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "name": { + "type": "string" + }, + "type": { + "enum": [ + "function_call" + ], + "title": "FunctionCallResponseItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "call_id", + "name", + "type" + ], + "title": "FunctionCallResponseItem", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "output": { + "$ref": "#/definitions/FunctionCallOutputPayload" + }, + "type": { + "enum": [ + "function_call_output" + ], + "title": "FunctionCallOutputResponseItemType", + "type": "string" + } + }, + "required": [ + "call_id", + "output", + "type" + ], + "title": "FunctionCallOutputResponseItem", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "input": { + "type": "string" + }, + "name": { + "type": "string" + }, + "status": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "custom_tool_call" + ], + "title": "CustomToolCallResponseItemType", + "type": "string" + } + }, + "required": [ + "call_id", + "input", + "name", + "type" + ], + "title": "CustomToolCallResponseItem", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "output": { + "$ref": "#/definitions/FunctionCallOutputPayload" + }, + "type": { + "enum": [ + "custom_tool_call_output" + ], + "title": "CustomToolCallOutputResponseItemType", + "type": "string" + } + }, + "required": [ + "call_id", + "output", + "type" + ], + "title": "CustomToolCallOutputResponseItem", + "type": "object" + }, + { + "properties": { + "action": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchAction" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "status": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "web_search_call" + ], + "title": "WebSearchCallResponseItemType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "WebSearchCallResponseItem", + "type": "object" + }, + { + "properties": { + "ghost_commit": { + "$ref": "#/definitions/GhostCommit" + }, + "type": { + "enum": [ + "ghost_snapshot" + ], + "title": "GhostSnapshotResponseItemType", + "type": "string" + } + }, + "required": [ + "ghost_commit", + "type" + ], + "title": "GhostSnapshotResponseItem", + "type": "object" + }, + { + "properties": { + "encrypted_content": { + "type": "string" + }, + "type": { + "enum": [ + "compaction" + ], + "title": "CompactionResponseItemType", + "type": "string" + } + }, + "required": [ + "encrypted_content", + "type" + ], + "title": "CompactionResponseItem", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "other" + ], + "title": "OtherResponseItemType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "OtherResponseItem", + "type": "object" + } + ] + }, + "Result_of_CallToolResult_or_String": { + "oneOf": [ + { + "properties": { + "Ok": { + "$ref": "#/definitions/CallToolResult" + } + }, + "required": [ + "Ok" + ], + "title": "OkResult_of_CallToolResult_or_String", + "type": "object" + }, + { + "properties": { + "Err": { + "type": "string" + } + }, + "required": [ + "Err" + ], + "title": "ErrResult_of_CallToolResult_or_String", + "type": "object" + } + ] + }, + "ReviewCodeLocation": { + "description": "Location of the code related to a review finding.", + "properties": { + "absolute_file_path": { + "type": "string" + }, + "line_range": { + "$ref": "#/definitions/ReviewLineRange" + } + }, + "required": [ + "absolute_file_path", + "line_range" + ], + "type": "object" + }, + "ReviewDecision": { + "description": "User's decision in response to an ExecApprovalRequest.", + "oneOf": [ + { + "description": "User has approved this command and the agent should execute it.", + "enum": [ + "approved" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.", + "properties": { + "approved_execpolicy_amendment": { + "properties": { + "proposed_execpolicy_amendment": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "proposed_execpolicy_amendment" + ], + "type": "object" + } + }, + "required": [ + "approved_execpolicy_amendment" + ], + "title": "ApprovedExecpolicyAmendmentReviewDecision", + "type": "object" + }, + { + "description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", + "enum": [ + "approved_for_session" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User chose to persist a network policy rule (allow/deny) for future requests to the same host.", + "properties": { + "network_policy_amendment": { + "properties": { + "network_policy_amendment": { + "$ref": "#/definitions/NetworkPolicyAmendment" + } + }, + "required": [ + "network_policy_amendment" + ], + "type": "object" + } + }, + "required": [ + "network_policy_amendment" + ], + "title": "NetworkPolicyAmendmentReviewDecision", + "type": "object" + }, + { + "description": "User has denied this command and the agent should not execute it, but it should continue the session and try something else.", + "enum": [ + "denied" + ], + "type": "string" + }, + { + "description": "User has denied this command and the agent should not do anything until the user's next command.", + "enum": [ + "abort" + ], + "type": "string" + } + ] + }, + "ReviewDelivery": { + "enum": [ + "inline", + "detached" + ], + "type": "string" + }, + "ReviewFinding": { + "description": "A single review finding describing an observed issue or recommendation.", + "properties": { + "body": { + "type": "string" + }, + "code_location": { + "$ref": "#/definitions/ReviewCodeLocation" + }, + "confidence_score": { + "format": "float", + "type": "number" + }, + "priority": { + "format": "int32", + "type": "integer" + }, + "title": { + "type": "string" + } + }, + "required": [ + "body", + "code_location", + "confidence_score", + "priority", + "title" + ], + "type": "object" + }, + "ReviewLineRange": { + "description": "Inclusive line range in a file associated with the finding.", + "properties": { + "end": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "start": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "end", + "start" + ], + "type": "object" + }, + "ReviewOutputEvent": { + "description": "Structured review result produced by a child review session.", + "properties": { + "findings": { + "items": { + "$ref": "#/definitions/ReviewFinding" + }, + "type": "array" + }, + "overall_confidence_score": { + "format": "float", + "type": "number" + }, + "overall_correctness": { + "type": "string" + }, + "overall_explanation": { + "type": "string" + } + }, + "required": [ + "findings", + "overall_confidence_score", + "overall_correctness", + "overall_explanation" + ], + "type": "object" + }, + "ReviewStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delivery": { + "anyOf": [ + { + "$ref": "#/definitions/ReviewDelivery" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`)." + }, + "target": { + "$ref": "#/definitions/ReviewTarget" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "target", + "threadId" + ], + "title": "ReviewStartParams", + "type": "object" + }, + "ReviewStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "reviewThreadId": { + "description": "Identifies the thread where the review runs.\n\nFor inline reviews, this is the original thread id. For detached reviews, this is the id of the new review thread.", + "type": "string" + }, + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "reviewThreadId", + "turn" + ], + "title": "ReviewStartResponse", + "type": "object" + }, + "ReviewTarget": { + "oneOf": [ + { + "description": "Review the working tree: staged, unstaged, and untracked files.", + "properties": { + "type": { + "enum": [ + "uncommittedChanges" + ], + "title": "UncommittedChangesReviewTargetType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UncommittedChangesReviewTarget", + "type": "object" + }, + { + "description": "Review changes between the current branch and the given base branch.", + "properties": { + "branch": { + "type": "string" + }, + "type": { + "enum": [ + "baseBranch" + ], + "title": "BaseBranchReviewTargetType", + "type": "string" + } + }, + "required": [ + "branch", + "type" + ], + "title": "BaseBranchReviewTarget", + "type": "object" + }, + { + "description": "Review the changes introduced by a specific commit.", + "properties": { + "sha": { + "type": "string" + }, + "title": { + "description": "Optional human-readable label (e.g., commit subject) for UIs.", + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "commit" + ], + "title": "CommitReviewTargetType", + "type": "string" + } + }, + "required": [ + "sha", + "type" + ], + "title": "CommitReviewTarget", + "type": "object" + }, + { + "description": "Arbitrary instructions, equivalent to the old free-form prompt.", + "properties": { + "instructions": { + "type": "string" + }, + "type": { + "enum": [ + "custom" + ], + "title": "CustomReviewTargetType", + "type": "string" + } + }, + "required": [ + "instructions", + "type" + ], + "title": "CustomReviewTarget", + "type": "object" + } + ] + }, + "SandboxMode": { + "enum": [ + "read-only", + "workspace-write", + "danger-full-access" + ], + "type": "string" + }, + "SandboxPolicy": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "dangerFullAccess" + ], + "title": "DangerFullAccessSandboxPolicyType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DangerFullAccessSandboxPolicy", + "type": "object" + }, + { + "properties": { + "access": { + "allOf": [ + { + "$ref": "#/definitions/ReadOnlyAccess" + } + ], + "default": { + "type": "fullAccess" + } + }, + "type": { + "enum": [ + "readOnly" + ], + "title": "ReadOnlySandboxPolicyType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ReadOnlySandboxPolicy", + "type": "object" + }, + { + "properties": { + "networkAccess": { + "allOf": [ + { + "$ref": "#/definitions/NetworkAccess" + } + ], + "default": "restricted" + }, + "type": { + "enum": [ + "externalSandbox" + ], + "title": "ExternalSandboxSandboxPolicyType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ExternalSandboxSandboxPolicy", + "type": "object" + }, + { + "properties": { + "excludeSlashTmp": { + "default": false, + "type": "boolean" + }, + "excludeTmpdirEnvVar": { + "default": false, + "type": "boolean" + }, + "networkAccess": { + "default": false, + "type": "boolean" + }, + "readOnlyAccess": { + "allOf": [ + { + "$ref": "#/definitions/ReadOnlyAccess" + } + ], + "default": { + "type": "fullAccess" + } + }, + "type": { + "enum": [ + "workspaceWrite" + ], + "title": "WorkspaceWriteSandboxPolicyType", + "type": "string" + }, + "writableRoots": { + "default": [], + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": "array" + } + }, + "required": [ + "type" + ], + "title": "WorkspaceWriteSandboxPolicy", + "type": "object" + } + ] + }, + "SandboxWorkspaceWrite": { + "properties": { + "exclude_slash_tmp": { + "default": false, + "type": "boolean" + }, + "exclude_tmpdir_env_var": { + "default": false, + "type": "boolean" + }, + "network_access": { + "default": false, + "type": "boolean" + }, + "writable_roots": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "ServerNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Notification sent from the server to the client.", + "oneOf": [ + { + "description": "NEW NOTIFICATIONS", + "properties": { + "method": { + "enum": [ + "error" + ], + "title": "ErrorNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ErrorNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ErrorNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/started" + ], + "title": "Thread/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/status/changed" + ], + "title": "Thread/status/changedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadStatusChangedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/status/changedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/archived" + ], + "title": "Thread/archivedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadArchivedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/archivedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/unarchived" + ], + "title": "Thread/unarchivedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadUnarchivedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/unarchivedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/closed" + ], + "title": "Thread/closedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadClosedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/closedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/name/updated" + ], + "title": "Thread/name/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadNameUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/name/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/tokenUsage/updated" + ], + "title": "Thread/tokenUsage/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadTokenUsageUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/tokenUsage/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/started" + ], + "title": "Turn/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/completed" + ], + "title": "Turn/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/completedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/diff/updated" + ], + "title": "Turn/diff/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnDiffUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/diff/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/plan/updated" + ], + "title": "Turn/plan/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnPlanUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/plan/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/started" + ], + "title": "Item/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ItemStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/completed" + ], + "title": "Item/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ItemCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/completedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/agentMessage/delta" + ], + "title": "Item/agentMessage/deltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AgentMessageDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/agentMessage/deltaNotification", + "type": "object" + }, + { + "description": "EXPERIMENTAL - proposed plan streaming deltas for plan items.", + "properties": { + "method": { + "enum": [ + "item/plan/delta" + ], + "title": "Item/plan/deltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/PlanDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/plan/deltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/commandExecution/outputDelta" + ], + "title": "Item/commandExecution/outputDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CommandExecutionOutputDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/commandExecution/outputDeltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/commandExecution/terminalInteraction" + ], + "title": "Item/commandExecution/terminalInteractionNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TerminalInteractionNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/commandExecution/terminalInteractionNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/fileChange/outputDelta" + ], + "title": "Item/fileChange/outputDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FileChangeOutputDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/fileChange/outputDeltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "serverRequest/resolved" + ], + "title": "ServerRequest/resolvedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ServerRequestResolvedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ServerRequest/resolvedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/mcpToolCall/progress" + ], + "title": "Item/mcpToolCall/progressNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/McpToolCallProgressNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/mcpToolCall/progressNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "mcpServer/oauthLogin/completed" + ], + "title": "McpServer/oauthLogin/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/McpServerOauthLoginCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "McpServer/oauthLogin/completedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "account/updated" + ], + "title": "Account/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AccountUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Account/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "account/rateLimits/updated" + ], + "title": "Account/rateLimits/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AccountRateLimitsUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Account/rateLimits/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "app/list/updated" + ], + "title": "App/list/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AppListUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "App/list/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/reasoning/summaryTextDelta" + ], + "title": "Item/reasoning/summaryTextDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReasoningSummaryTextDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/reasoning/summaryTextDeltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/reasoning/summaryPartAdded" + ], + "title": "Item/reasoning/summaryPartAddedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReasoningSummaryPartAddedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/reasoning/summaryPartAddedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/reasoning/textDelta" + ], + "title": "Item/reasoning/textDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReasoningTextDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/reasoning/textDeltaNotification", + "type": "object" + }, + { + "description": "Deprecated: Use `ContextCompaction` item type instead.", + "properties": { + "method": { + "enum": [ + "thread/compacted" + ], + "title": "Thread/compactedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ContextCompactedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/compactedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "model/rerouted" + ], + "title": "Model/reroutedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ModelReroutedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Model/reroutedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "deprecationNotice" + ], + "title": "DeprecationNoticeNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeprecationNoticeNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "DeprecationNoticeNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "configWarning" + ], + "title": "ConfigWarningNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigWarningNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ConfigWarningNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "fuzzyFileSearch/sessionUpdated" + ], + "title": "FuzzyFileSearch/sessionUpdatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FuzzyFileSearchSessionUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "FuzzyFileSearch/sessionUpdatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "fuzzyFileSearch/sessionCompleted" + ], + "title": "FuzzyFileSearch/sessionCompletedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FuzzyFileSearchSessionCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "FuzzyFileSearch/sessionCompletedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/started" + ], + "title": "Thread/realtime/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/itemAdded" + ], + "title": "Thread/realtime/itemAddedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeItemAddedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/itemAddedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/outputAudio/delta" + ], + "title": "Thread/realtime/outputAudio/deltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeOutputAudioDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/outputAudio/deltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/error" + ], + "title": "Thread/realtime/errorNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeErrorNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/errorNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/closed" + ], + "title": "Thread/realtime/closedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeClosedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/closedNotification", + "type": "object" + }, + { + "description": "Notifies the user of world-writable directories on Windows, which cannot be protected by the sandbox.", + "properties": { + "method": { + "enum": [ + "windows/worldWritableWarning" + ], + "title": "Windows/worldWritableWarningNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WindowsWorldWritableWarningNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Windows/worldWritableWarningNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "windowsSandbox/setupCompleted" + ], + "title": "WindowsSandbox/setupCompletedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WindowsSandboxSetupCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "WindowsSandbox/setupCompletedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "account/login/completed" + ], + "title": "Account/login/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AccountLoginCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Account/login/completedNotification", + "type": "object" + } + ], + "title": "ServerNotification" + }, + "ServerRequestResolvedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "requestId": { + "$ref": "#/definitions/RequestId" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "requestId", + "threadId" + ], + "title": "ServerRequestResolvedNotification", + "type": "object" + }, + "SessionNetworkProxyRuntime": { + "properties": { + "admin_addr": { + "type": "string" + }, + "http_addr": { + "type": "string" + }, + "socks_addr": { + "type": "string" + } + }, + "required": [ + "admin_addr", + "http_addr", + "socks_addr" + ], + "type": "object" + }, + "SessionSource": { + "oneOf": [ + { + "enum": [ + "cli", + "vscode", + "exec", + "appServer", + "unknown" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "subAgent": { + "$ref": "#/definitions/SubAgentSource" + } + }, + "required": [ + "subAgent" + ], + "title": "SubAgentSessionSource", + "type": "object" + } + ] + }, + "Settings": { + "description": "Settings for a collaboration mode.", + "properties": { + "developer_instructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": "string" + }, + "reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "model" + ], + "type": "object" + }, + "SkillDependencies": { + "properties": { + "tools": { + "items": { + "$ref": "#/definitions/SkillToolDependency" + }, + "type": "array" + } + }, + "required": [ + "tools" + ], + "type": "object" + }, + "SkillErrorInfo": { + "properties": { + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "message", + "path" + ], + "type": "object" + }, + "SkillInterface": { + "properties": { + "brandColor": { + "type": [ + "string", + "null" + ] + }, + "defaultPrompt": { + "type": [ + "string", + "null" + ] + }, + "displayName": { + "type": [ + "string", + "null" + ] + }, + "iconLarge": { + "type": [ + "string", + "null" + ] + }, + "iconSmall": { + "type": [ + "string", + "null" + ] + }, + "shortDescription": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "SkillMetadata": { + "properties": { + "dependencies": { + "anyOf": [ + { + "$ref": "#/definitions/SkillDependencies" + }, + { + "type": "null" + } + ] + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "interface": { + "anyOf": [ + { + "$ref": "#/definitions/SkillInterface" + }, + { + "type": "null" + } + ] + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "scope": { + "$ref": "#/definitions/SkillScope" + }, + "shortDescription": { + "description": "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "description", + "enabled", + "name", + "path", + "scope" + ], + "type": "object" + }, + "SkillScope": { + "enum": [ + "user", + "repo", + "system", + "admin" + ], + "type": "string" + }, + "SkillToolDependency": { + "properties": { + "command": { + "type": [ + "string", + "null" + ] + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "transport": { + "type": [ + "string", + "null" + ] + }, + "type": { + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "value": { + "type": "string" + } + }, + "required": [ + "type", + "value" + ], + "type": "object" + }, + "SkillsConfigWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "enabled": { + "type": "boolean" + }, + "path": { + "type": "string" + } + }, + "required": [ + "enabled", + "path" + ], + "title": "SkillsConfigWriteParams", + "type": "object" + }, + "SkillsConfigWriteResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "effectiveEnabled": { + "type": "boolean" + } + }, + "required": [ + "effectiveEnabled" + ], + "title": "SkillsConfigWriteResponse", + "type": "object" + }, + "SkillsListEntry": { + "properties": { + "cwd": { + "type": "string" + }, + "errors": { + "items": { + "$ref": "#/definitions/SkillErrorInfo" + }, + "type": "array" + }, + "skills": { + "items": { + "$ref": "#/definitions/SkillMetadata" + }, + "type": "array" + } + }, + "required": [ + "cwd", + "errors", + "skills" + ], + "type": "object" + }, + "SkillsListExtraRootsForCwd": { + "properties": { + "cwd": { + "type": "string" + }, + "extraUserRoots": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "cwd", + "extraUserRoots" + ], + "type": "object" + }, + "SkillsListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cwds": { + "description": "When empty, defaults to the current session working directory.", + "items": { + "type": "string" + }, + "type": "array" + }, + "forceReload": { + "description": "When true, bypass the skills cache and re-scan skills from disk.", + "type": "boolean" + }, + "perCwdExtraUserRoots": { + "default": null, + "description": "Optional per-cwd extra roots to scan as user-scoped skills.", + "items": { + "$ref": "#/definitions/SkillsListExtraRootsForCwd" + }, + "type": [ + "array", + "null" + ] + } + }, + "title": "SkillsListParams", + "type": "object" + }, + "SkillsListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/SkillsListEntry" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "SkillsListResponse", + "type": "object" + }, + "SkillsRemoteReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "enabled": { + "default": false, + "type": "boolean" + }, + "hazelnutScope": { + "allOf": [ + { + "$ref": "#/definitions/HazelnutScope" + } + ], + "default": "example" + }, + "productSurface": { + "allOf": [ + { + "$ref": "#/definitions/ProductSurface" + } + ], + "default": "codex" + } + }, + "title": "SkillsRemoteReadParams", + "type": "object" + }, + "SkillsRemoteReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/RemoteSkillSummary" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "SkillsRemoteReadResponse", + "type": "object" + }, + "SkillsRemoteWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "hazelnutId": { + "type": "string" + } + }, + "required": [ + "hazelnutId" + ], + "title": "SkillsRemoteWriteParams", + "type": "object" + }, + "SkillsRemoteWriteResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "id", + "path" + ], + "title": "SkillsRemoteWriteResponse", + "type": "object" + }, + "StepStatus": { + "enum": [ + "pending", + "in_progress", + "completed" + ], + "type": "string" + }, + "SubAgentSource": { + "oneOf": [ + { + "enum": [ + "review", + "compact", + "memory_consolidation" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "thread_spawn": { + "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "depth": { + "format": "int32", + "type": "integer" + }, + "parent_thread_id": { + "$ref": "#/definitions/ThreadId" + } + }, + "required": [ + "depth", + "parent_thread_id" + ], + "type": "object" + } + }, + "required": [ + "thread_spawn" + ], + "title": "ThreadSpawnSubAgentSource", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "other": { + "type": "string" + } + }, + "required": [ + "other" + ], + "title": "OtherSubAgentSource", + "type": "object" + } + ] + }, + "TerminalInteractionNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "itemId": { + "type": "string" + }, + "processId": { + "type": "string" + }, + "stdin": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "itemId", + "processId", + "stdin", + "threadId", + "turnId" + ], + "title": "TerminalInteractionNotification", + "type": "object" + }, + "TextElement": { + "properties": { + "byteRange": { + "allOf": [ + { + "$ref": "#/definitions/ByteRange" + } + ], + "description": "Byte range in the parent `text` buffer that this element occupies." + }, + "placeholder": { + "description": "Optional human-readable placeholder for the element, displayed in the UI.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "byteRange" + ], + "type": "object" + }, + "TextPosition": { + "properties": { + "column": { + "description": "1-based column number (in Unicode scalar values).", + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "line": { + "description": "1-based line number.", + "format": "uint", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "column", + "line" + ], + "type": "object" + }, + "TextRange": { + "properties": { + "end": { + "$ref": "#/definitions/TextPosition" + }, + "start": { + "$ref": "#/definitions/TextPosition" + } + }, + "required": [ + "end", + "start" + ], + "type": "object" + }, + "Thread": { + "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "cliVersion": { + "description": "Version of the CLI that created the thread.", + "type": "string" + }, + "createdAt": { + "description": "Unix timestamp (in seconds) when the thread was created.", + "format": "int64", + "type": "integer" + }, + "cwd": { + "description": "Working directory captured for the thread.", + "type": "string" + }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, + "gitInfo": { + "anyOf": [ + { + "$ref": "#/definitions/GitInfo" + }, + { + "type": "null" + } + ], + "description": "Optional Git metadata captured when the thread was created." + }, + "id": { + "type": "string" + }, + "modelProvider": { + "description": "Model provider used for this thread (for example, 'openai').", + "type": "string" + }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, + "path": { + "description": "[UNSTABLE] Path to the thread on disk.", + "type": [ + "string", + "null" + ] + }, + "preview": { + "description": "Usually the first user message in the thread, if available.", + "type": "string" + }, + "source": { + "allOf": [ + { + "$ref": "#/definitions/SessionSource" + } + ], + "description": "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.)." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/ThreadStatus" + } + ], + "description": "Current runtime status for the thread." + }, + "turns": { + "description": "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + "items": { + "$ref": "#/definitions/Turn" + }, + "type": "array" + }, + "updatedAt": { + "description": "Unix timestamp (in seconds) when the thread was last updated.", + "format": "int64", + "type": "integer" + } + }, + "required": [ + "cliVersion", + "createdAt", + "cwd", + "ephemeral", + "id", + "modelProvider", + "preview", + "source", + "status", + "turns", + "updatedAt" + ], + "type": "object" + }, + "ThreadActiveFlag": { + "enum": [ + "waitingOnApproval", + "waitingOnUserInput" + ], + "type": "string" + }, + "ThreadArchiveParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadArchiveParams", + "type": "object" + }, + "ThreadArchiveResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ThreadArchiveResponse", + "type": "object" + }, + "ThreadArchivedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadArchivedNotification", + "type": "object" + }, + "ThreadClosedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadClosedNotification", + "type": "object" + }, + "ThreadCompactStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadCompactStartParams", + "type": "object" + }, + "ThreadCompactStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ThreadCompactStartResponse", + "type": "object" + }, + "ThreadForkParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "baseInstructions": { + "type": [ + "string", + "null" + ] + }, + "config": { + "additionalProperties": true, + "type": [ + "object", + "null" + ] + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "developerInstructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "description": "Configuration overrides for the forked thread, if any.", + "type": [ + "string", + "null" + ] + }, + "modelProvider": { + "type": [ + "string", + "null" + ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadForkParams", + "type": "object" + }, + "ThreadForkResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "$ref": "#/definitions/AskForApproval" + }, + "cwd": { + "type": "string" + }, + "model": { + "type": "string" + }, + "modelProvider": { + "type": "string" + }, + "reasoningEffort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "$ref": "#/definitions/SandboxPolicy" + }, + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "approvalPolicy", + "cwd", + "model", + "modelProvider", + "sandbox", + "thread" + ], + "title": "ThreadForkResponse", + "type": "object" + }, + "ThreadId": { + "type": "string" + }, + "ThreadItem": { + "oneOf": [ + { + "properties": { + "content": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "type": { + "enum": [ + "userMessage" + ], + "title": "UserMessageThreadItemType", + "type": "string" + } + }, + "required": [ + "content", + "id", + "type" + ], + "title": "UserMessageThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "agentMessage" + ], + "title": "AgentMessageThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "AgentMessageThreadItem", + "type": "object" + }, + { + "description": "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + "properties": { + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "plan" + ], + "title": "PlanThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "PlanThreadItem", + "type": "object" + }, + { + "properties": { + "content": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "summary": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "enum": [ + "reasoning" + ], + "title": "ReasoningThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ReasoningThreadItem", + "type": "object" + }, + { + "properties": { + "aggregatedOutput": { + "description": "The command's output, aggregated from stdout and stderr.", + "type": [ + "string", + "null" + ] + }, + "command": { + "description": "The command to be executed.", + "type": "string" + }, + "commandActions": { + "description": "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + "items": { + "$ref": "#/definitions/CommandAction" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory.", + "type": "string" + }, + "durationMs": { + "description": "The duration of the command execution in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "exitCode": { + "description": "The command's exit code.", + "format": "int32", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "processId": { + "description": "Identifier for the underlying PTY process (when available).", + "type": [ + "string", + "null" + ] + }, + "status": { + "$ref": "#/definitions/CommandExecutionStatus" + }, + "type": { + "enum": [ + "commandExecution" + ], + "title": "CommandExecutionThreadItemType", + "type": "string" + } + }, + "required": [ + "command", + "commandActions", + "cwd", + "id", + "status", + "type" + ], + "title": "CommandExecutionThreadItem", + "type": "object" + }, + { + "properties": { + "changes": { + "items": { + "$ref": "#/definitions/FileUpdateChange" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/PatchApplyStatus" + }, + "type": { + "enum": [ + "fileChange" + ], + "title": "FileChangeThreadItemType", + "type": "string" + } + }, + "required": [ + "changes", + "id", + "status", + "type" + ], + "title": "FileChangeThreadItem", + "type": "object" + }, + { + "properties": { + "arguments": true, + "durationMs": { + "description": "The duration of the MCP tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "error": { + "anyOf": [ + { + "$ref": "#/definitions/McpToolCallError" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "result": { + "anyOf": [ + { + "$ref": "#/definitions/McpToolCallResult" + }, + { + "type": "null" + } + ] + }, + "server": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/McpToolCallStatus" + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "mcpToolCall" + ], + "title": "McpToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "server", + "status", + "tool", + "type" + ], + "title": "McpToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "agentsStates": { + "additionalProperties": { + "$ref": "#/definitions/CollabAgentState" + }, + "description": "Last known status of the target agents, when available.", + "type": "object" + }, + "id": { + "description": "Unique identifier for this collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Prompt text sent as part of the collab tool call, when available.", + "type": [ + "string", + "null" + ] + }, + "receiverThreadIds": { + "description": "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + "items": { + "type": "string" + }, + "type": "array" + }, + "senderThreadId": { + "description": "Thread ID of the agent issuing the collab request.", + "type": "string" + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/CollabAgentToolCallStatus" + } + ], + "description": "Current status of the collab tool call." + }, + "tool": { + "allOf": [ + { + "$ref": "#/definitions/CollabAgentTool" + } + ], + "description": "Name of the collab tool that was invoked." + }, + "type": { + "enum": [ + "collabAgentToolCall" + ], + "title": "CollabAgentToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "agentsStates", + "id", + "receiverThreadIds", + "senderThreadId", + "status", + "tool", + "type" + ], + "title": "CollabAgentToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "action": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchAction" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "query": { + "type": "string" + }, + "type": { + "enum": [ + "webSearch" + ], + "title": "WebSearchThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "query", + "type" + ], + "title": "WebSearchThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "imageView" + ], + "title": "ImageViewThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "path", + "type" + ], + "title": "ImageViewThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "review": { + "type": "string" + }, + "type": { + "enum": [ + "enteredReviewMode" + ], + "title": "EnteredReviewModeThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "review", + "type" + ], + "title": "EnteredReviewModeThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "review": { + "type": "string" + }, + "type": { + "enum": [ + "exitedReviewMode" + ], + "title": "ExitedReviewModeThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "review", + "type" + ], + "title": "ExitedReviewModeThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "type": { + "enum": [ + "contextCompaction" + ], + "title": "ContextCompactionThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ContextCompactionThreadItem", + "type": "object" + } + ] + }, + "ThreadListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "archived": { + "description": "Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.", + "type": [ + "boolean", + "null" + ] + }, + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "cwd": { + "description": "Optional cwd filter; when set, only threads whose session cwd exactly matches this path are returned.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "modelProviders": { + "description": "Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "searchTerm": { + "description": "Optional substring filter for the extracted thread title.", + "type": [ + "string", + "null" + ] + }, + "sortKey": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadSortKey" + }, + { + "type": "null" + } + ], + "description": "Optional sort key; defaults to created_at." + }, + "sourceKinds": { + "description": "Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.", + "items": { + "$ref": "#/definitions/ThreadSourceKind" + }, + "type": [ + "array", + "null" + ] + } + }, + "title": "ThreadListParams", + "type": "object" + }, + "ThreadListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/Thread" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ThreadListResponse", + "type": "object" + }, + "ThreadLoadedListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to no limit.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ThreadLoadedListParams", + "type": "object" + }, + "ThreadLoadedListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "description": "Thread ids for sessions currently loaded in memory.", + "items": { + "type": "string" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ThreadLoadedListResponse", + "type": "object" + }, + "ThreadNameUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "threadName": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "threadId" + ], + "title": "ThreadNameUpdatedNotification", + "type": "object" + }, + "ThreadReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "includeTurns": { + "default": false, + "description": "When true, include turns and their items from rollout history.", + "type": "boolean" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadReadParams", + "type": "object" + }, + "ThreadReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadReadResponse", + "type": "object" + }, + "ThreadRealtimeAudioChunk": { + "description": "EXPERIMENTAL - thread realtime audio chunk.", + "properties": { + "data": { + "type": "string" + }, + "numChannels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sampleRate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samplesPerChannel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "numChannels", + "sampleRate" + ], + "type": "object" + }, + "ThreadRealtimeClosedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - emitted when thread realtime transport closes.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadRealtimeClosedNotification", + "type": "object" + }, + "ThreadRealtimeErrorNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - emitted when thread realtime encounters an error.", + "properties": { + "message": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "message", + "threadId" + ], + "title": "ThreadRealtimeErrorNotification", + "type": "object" + }, + "ThreadRealtimeItemAddedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.", + "properties": { + "item": true, + "threadId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId" + ], + "title": "ThreadRealtimeItemAddedNotification", + "type": "object" + }, + "ThreadRealtimeOutputAudioDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - streamed output audio emitted by thread realtime.", + "properties": { + "audio": { + "$ref": "#/definitions/ThreadRealtimeAudioChunk" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "audio", + "threadId" + ], + "title": "ThreadRealtimeOutputAudioDeltaNotification", + "type": "object" + }, + "ThreadRealtimeStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - emitted when thread realtime startup is accepted.", + "properties": { + "sessionId": { + "type": [ + "string", + "null" + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadRealtimeStartedNotification", + "type": "object" + }, + "ThreadResumeParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\n\nThe precedence is: history > path > thread_id. If using history or path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "baseInstructions": { + "type": [ + "string", + "null" + ] + }, + "config": { + "additionalProperties": true, + "type": [ + "object", + "null" + ] + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "developerInstructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "description": "Configuration overrides for the resumed thread, if any.", + "type": [ + "string", + "null" + ] + }, + "modelProvider": { + "type": [ + "string", + "null" + ] + }, + "personality": { + "anyOf": [ + { + "$ref": "#/definitions/Personality" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadResumeParams", + "type": "object" + }, + "ThreadResumeResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "$ref": "#/definitions/AskForApproval" + }, + "cwd": { + "type": "string" + }, + "model": { + "type": "string" + }, + "modelProvider": { + "type": "string" + }, + "reasoningEffort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "$ref": "#/definitions/SandboxPolicy" + }, + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "approvalPolicy", + "cwd", + "model", + "modelProvider", + "sandbox", + "thread" + ], + "title": "ThreadResumeResponse", + "type": "object" + }, + "ThreadRollbackParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "numTurns": { + "description": "The number of turns to drop from the end of the thread. Must be >= 1.\n\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.", + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "numTurns", + "threadId" + ], + "title": "ThreadRollbackParams", + "type": "object" + }, + "ThreadRollbackResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "allOf": [ + { + "$ref": "#/definitions/Thread" + } + ], + "description": "The updated thread after applying the rollback, with `turns` populated.\n\nThe ThreadItems stored in each Turn are lossy since we explicitly do not persist all agent interactions, such as command executions. This is the same behavior as `thread/resume`." + } + }, + "required": [ + "thread" + ], + "title": "ThreadRollbackResponse", + "type": "object" + }, + "ThreadSetNameParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "name": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "name", + "threadId" + ], + "title": "ThreadSetNameParams", + "type": "object" + }, + "ThreadSetNameResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ThreadSetNameResponse", + "type": "object" + }, + "ThreadSortKey": { + "enum": [ + "created_at", + "updated_at" + ], + "type": "string" + }, + "ThreadSourceKind": { + "enum": [ + "cli", + "vscode", + "exec", + "appServer", + "subAgent", + "subAgentReview", + "subAgentCompact", + "subAgentThreadSpawn", + "subAgentOther", + "unknown" + ], + "type": "string" + }, + "ThreadStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "baseInstructions": { + "type": [ + "string", + "null" + ] + }, + "config": { + "additionalProperties": true, + "type": [ + "object", + "null" + ] + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "developerInstructions": { + "type": [ + "string", + "null" + ] + }, + "ephemeral": { + "type": [ + "boolean", + "null" + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "modelProvider": { + "type": [ + "string", + "null" + ] + }, + "personality": { + "anyOf": [ + { + "$ref": "#/definitions/Personality" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "serviceName": { + "type": [ + "string", + "null" + ] + } + }, + "title": "ThreadStartParams", + "type": "object" + }, + "ThreadStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "$ref": "#/definitions/AskForApproval" + }, + "cwd": { + "type": "string" + }, + "model": { + "type": "string" + }, + "modelProvider": { + "type": "string" + }, + "reasoningEffort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "$ref": "#/definitions/SandboxPolicy" + }, + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "approvalPolicy", + "cwd", + "model", + "modelProvider", + "sandbox", + "thread" + ], + "title": "ThreadStartResponse", + "type": "object" + }, + "ThreadStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadStartedNotification", + "type": "object" + }, + "ThreadStatus": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "notLoaded" + ], + "title": "NotLoadedThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "NotLoadedThreadStatus", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "idle" + ], + "title": "IdleThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "IdleThreadStatus", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "systemError" + ], + "title": "SystemErrorThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SystemErrorThreadStatus", + "type": "object" + }, + { + "properties": { + "activeFlags": { + "items": { + "$ref": "#/definitions/ThreadActiveFlag" + }, + "type": "array" + }, + "type": { + "enum": [ + "active" + ], + "title": "ActiveThreadStatusType", + "type": "string" + } + }, + "required": [ + "activeFlags", + "type" + ], + "title": "ActiveThreadStatus", + "type": "object" + } + ] + }, + "ThreadStatusChangedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "status": { + "$ref": "#/definitions/ThreadStatus" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "status", + "threadId" + ], + "title": "ThreadStatusChangedNotification", + "type": "object" + }, + "ThreadTokenUsage": { + "properties": { + "last": { + "$ref": "#/definitions/TokenUsageBreakdown" + }, + "modelContextWindow": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "total": { + "$ref": "#/definitions/TokenUsageBreakdown" + } + }, + "required": [ + "last", + "total" + ], + "type": "object" + }, + "ThreadTokenUsageUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "tokenUsage": { + "$ref": "#/definitions/ThreadTokenUsage" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "threadId", + "tokenUsage", + "turnId" + ], + "title": "ThreadTokenUsageUpdatedNotification", + "type": "object" + }, + "ThreadUnarchiveParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnarchiveParams", + "type": "object" + }, + "ThreadUnarchiveResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadUnarchiveResponse", + "type": "object" + }, + "ThreadUnarchivedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnarchivedNotification", + "type": "object" + }, + "ThreadUnsubscribeParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnsubscribeParams", + "type": "object" + }, + "ThreadUnsubscribeResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "status": { + "$ref": "#/definitions/ThreadUnsubscribeStatus" + } + }, + "required": [ + "status" + ], + "title": "ThreadUnsubscribeResponse", + "type": "object" + }, + "ThreadUnsubscribeStatus": { + "enum": [ + "notLoaded", + "notSubscribed", + "unsubscribed" + ], + "type": "string" + }, + "TokenUsage": { + "properties": { + "cached_input_tokens": { + "format": "int64", + "type": "integer" + }, + "input_tokens": { + "format": "int64", + "type": "integer" + }, + "output_tokens": { + "format": "int64", + "type": "integer" + }, + "reasoning_output_tokens": { + "format": "int64", + "type": "integer" + }, + "total_tokens": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "cached_input_tokens", + "input_tokens", + "output_tokens", + "reasoning_output_tokens", + "total_tokens" + ], + "type": "object" + }, + "TokenUsageBreakdown": { + "properties": { + "cachedInputTokens": { + "format": "int64", + "type": "integer" + }, + "inputTokens": { + "format": "int64", + "type": "integer" + }, + "outputTokens": { + "format": "int64", + "type": "integer" + }, + "reasoningOutputTokens": { + "format": "int64", + "type": "integer" + }, + "totalTokens": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "cachedInputTokens", + "inputTokens", + "outputTokens", + "reasoningOutputTokens", + "totalTokens" + ], + "type": "object" + }, + "TokenUsageInfo": { + "properties": { + "last_token_usage": { + "$ref": "#/definitions/TokenUsage" + }, + "model_context_window": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "total_token_usage": { + "$ref": "#/definitions/TokenUsage" + } + }, + "required": [ + "last_token_usage", + "total_token_usage" + ], + "type": "object" + }, + "Tool": { + "description": "Definition for a tool the client can call.", + "properties": { + "_meta": true, + "annotations": true, + "description": { + "type": [ + "string", + "null" + ] + }, + "icons": { + "items": true, + "type": [ + "array", + "null" + ] + }, + "inputSchema": true, + "name": { + "type": "string" + }, + "outputSchema": true, + "title": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "inputSchema", + "name" + ], + "type": "object" + }, + "ToolsV2": { + "properties": { + "view_image": { + "type": [ + "boolean", + "null" + ] + }, + "web_search": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "Turn": { + "properties": { + "error": { + "anyOf": [ + { + "$ref": "#/definitions/TurnError" + }, + { + "type": "null" + } + ], + "description": "Only populated when the Turn's status is failed." + }, + "id": { + "type": "string" + }, + "items": { + "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "items": { + "$ref": "#/definitions/ThreadItem" + }, + "type": "array" + }, + "status": { + "$ref": "#/definitions/TurnStatus" + } + }, + "required": [ + "id", + "items", + "status" + ], + "type": "object" + }, + "TurnAbortReason": { + "enum": [ + "interrupted", + "replaced", + "review_ended" + ], + "type": "string" + }, + "TurnCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "threadId", + "turn" + ], + "title": "TurnCompletedNotification", + "type": "object" + }, + "TurnDiffUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.", + "properties": { + "diff": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "diff", + "threadId", + "turnId" + ], + "title": "TurnDiffUpdatedNotification", + "type": "object" + }, + "TurnError": { + "properties": { + "additionalDetails": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "codexErrorInfo": { + "anyOf": [ + { + "$ref": "#/definitions/CodexErrorInfo" + }, + { + "type": "null" + } + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "TurnInterruptParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "threadId", + "turnId" + ], + "title": "TurnInterruptParams", + "type": "object" + }, + "TurnInterruptResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "TurnInterruptResponse", + "type": "object" + }, + "TurnItem": { + "oneOf": [ + { + "properties": { + "content": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "type": { + "enum": [ + "UserMessage" + ], + "title": "UserMessageTurnItemType", + "type": "string" + } + }, + "required": [ + "content", + "id", + "type" + ], + "title": "UserMessageTurnItem", + "type": "object" + }, + { + "description": "Assistant-authored message payload used in turn-item streams.\n\n`phase` is optional because not all providers/models emit it. Consumers should use it when present, but retain legacy completion semantics when it is `None`.", + "properties": { + "content": { + "items": { + "$ref": "#/definitions/AgentMessageContent" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "description": "Optional phase metadata carried through from `ResponseItem::Message`.\n\nThis is currently used by TUI rendering to distinguish mid-turn commentary from a final answer and avoid status-indicator jitter." + }, + "type": { + "enum": [ + "AgentMessage" + ], + "title": "AgentMessageTurnItemType", + "type": "string" + } + }, + "required": [ + "content", + "id", + "type" + ], + "title": "AgentMessageTurnItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "Plan" + ], + "title": "PlanTurnItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "PlanTurnItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "raw_content": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "summary_text": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "enum": [ + "Reasoning" + ], + "title": "ReasoningTurnItemType", + "type": "string" + } + }, + "required": [ + "id", + "summary_text", + "type" + ], + "title": "ReasoningTurnItem", + "type": "object" + }, + { + "properties": { + "action": { + "$ref": "#/definitions/WebSearchAction" + }, + "id": { + "type": "string" + }, + "query": { + "type": "string" + }, + "type": { + "enum": [ + "WebSearch" + ], + "title": "WebSearchTurnItemType", + "type": "string" + } + }, + "required": [ + "action", + "id", + "query", + "type" + ], + "title": "WebSearchTurnItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "type": { + "enum": [ + "ContextCompaction" + ], + "title": "ContextCompactionTurnItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ContextCompactionTurnItem", + "type": "object" + } + ] + }, + "TurnPlanStep": { + "properties": { + "status": { + "$ref": "#/definitions/TurnPlanStepStatus" + }, + "step": { + "type": "string" + } + }, + "required": [ + "status", + "step" + ], + "type": "object" + }, + "TurnPlanStepStatus": { + "enum": [ + "pending", + "inProgress", + "completed" + ], + "type": "string" + }, + "TurnPlanUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "explanation": { + "type": [ + "string", + "null" + ] + }, + "plan": { + "items": { + "$ref": "#/definitions/TurnPlanStep" + }, + "type": "array" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "plan", + "threadId", + "turnId" + ], + "title": "TurnPlanUpdatedNotification", + "type": "object" + }, + "TurnStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ], + "description": "Override the approval policy for this turn and subsequent turns." + }, + "cwd": { + "description": "Override the working directory for this turn and subsequent turns.", + "type": [ + "string", + "null" + ] + }, + "effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ], + "description": "Override the reasoning effort for this turn and subsequent turns." + }, + "input": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "model": { + "description": "Override the model for this turn and subsequent turns.", + "type": [ + "string", + "null" + ] + }, + "outputSchema": { + "description": "Optional JSON Schema used to constrain the final assistant message for this turn." + }, + "personality": { + "anyOf": [ + { + "$ref": "#/definitions/Personality" + }, + { + "type": "null" + } + ], + "description": "Override the personality for this turn and subsequent turns." + }, + "sandboxPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxPolicy" + }, + { + "type": "null" + } + ], + "description": "Override the sandbox policy for this turn and subsequent turns." + }, + "summary": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningSummary" + }, + { + "type": "null" + } + ], + "description": "Override the reasoning summary for this turn and subsequent turns." + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "input", + "threadId" + ], + "title": "TurnStartParams", + "type": "object" + }, + "TurnStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "turn" + ], + "title": "TurnStartResponse", + "type": "object" + }, + "TurnStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "threadId", + "turn" + ], + "title": "TurnStartedNotification", + "type": "object" + }, + "TurnStatus": { + "enum": [ + "completed", + "interrupted", + "failed", + "inProgress" + ], + "type": "string" + }, + "TurnSteerParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "expectedTurnId": { + "description": "Required active turn id precondition. The request fails when it does not match the currently active turn.", + "type": "string" + }, + "input": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "expectedTurnId", + "input", + "threadId" + ], + "title": "TurnSteerParams", + "type": "object" + }, + "TurnSteerResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "turnId": { + "type": "string" + } + }, + "required": [ + "turnId" + ], + "title": "TurnSteerResponse", + "type": "object" + }, + "UserInput": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "text_elements": { + "default": [], + "description": "UI-defined spans within `text` used to render or persist special elements.", + "items": { + "$ref": "#/definitions/TextElement" + }, + "type": "array" + }, + "type": { + "enum": [ + "text" + ], + "title": "TextUserInputType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "TextUserInput", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "image" + ], + "title": "ImageUserInputType", + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "type", + "url" + ], + "title": "ImageUserInput", + "type": "object" + }, + { + "properties": { + "path": { + "type": "string" + }, + "type": { + "enum": [ + "localImage" + ], + "title": "LocalImageUserInputType", + "type": "string" + } + }, + "required": [ + "path", + "type" + ], + "title": "LocalImageUserInput", + "type": "object" + }, + { + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "skill" + ], + "title": "SkillUserInputType", + "type": "string" + } + }, + "required": [ + "name", + "path", + "type" + ], + "title": "SkillUserInput", + "type": "object" + }, + { + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "mention" + ], + "title": "MentionUserInputType", + "type": "string" + } + }, + "required": [ + "name", + "path", + "type" + ], + "title": "MentionUserInput", + "type": "object" + } + ] + }, + "Verbosity": { + "description": "Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.", + "enum": [ + "low", + "medium", + "high" + ], + "type": "string" + }, + "WebSearchAction": { + "oneOf": [ + { + "properties": { + "queries": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchWebSearchActionType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SearchWebSearchAction", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "open_page" + ], + "title": "OpenPageWebSearchActionType", + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "type" + ], + "title": "OpenPageWebSearchAction", + "type": "object" + }, + { + "properties": { + "pattern": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "find_in_page" + ], + "title": "FindInPageWebSearchActionType", + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "type" + ], + "title": "FindInPageWebSearchAction", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "other" + ], + "title": "OtherWebSearchActionType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "OtherWebSearchAction", + "type": "object" + } + ] + }, + "WebSearchMode": { + "enum": [ + "disabled", + "cached", + "live" + ], + "type": "string" + }, + "WindowsSandboxSetupCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, + "mode": { + "$ref": "#/definitions/WindowsSandboxSetupMode" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "mode", + "success" + ], + "title": "WindowsSandboxSetupCompletedNotification", + "type": "object" + }, + "WindowsSandboxSetupMode": { + "enum": [ + "elevated", + "unelevated" + ], + "type": "string" + }, + "WindowsSandboxSetupStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "mode": { + "$ref": "#/definitions/WindowsSandboxSetupMode" + } + }, + "required": [ + "mode" + ], + "title": "WindowsSandboxSetupStartParams", + "type": "object" + }, + "WindowsSandboxSetupStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "started": { + "type": "boolean" + } + }, + "required": [ + "started" + ], + "title": "WindowsSandboxSetupStartResponse", + "type": "object" + }, + "WindowsWorldWritableWarningNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "extraCount": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "failedScan": { + "type": "boolean" + }, + "samplePaths": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "extraCount", + "failedScan", + "samplePaths" + ], + "title": "WindowsWorldWritableWarningNotification", + "type": "object" + }, + "WriteStatus": { + "enum": [ + "ok", + "okOverridden" + ], + "type": "string" + } + }, + "title": "CodexAppServerProtocolV2", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/src/bin/export.rs b/codex-rs/app-server-protocol/src/bin/export.rs index d029ecbffa..10541d1fcb 100644 --- a/codex-rs/app-server-protocol/src/bin/export.rs +++ b/codex-rs/app-server-protocol/src/bin/export.rs @@ -14,9 +14,21 @@ struct Args { /// Optional Prettier executable path to format generated TypeScript files #[arg(short = 'p', long = "prettier", value_name = "PRETTIER_BIN")] prettier: Option, + + /// Include experimental API methods and fields in generated output. + #[arg(long = "experimental")] + experimental: bool, } fn main() -> Result<()> { let args = Args::parse(); - codex_app_server_protocol::generate_types(&args.out_dir, args.prettier.as_deref()) + codex_app_server_protocol::generate_ts_with_options( + &args.out_dir, + args.prettier.as_deref(), + codex_app_server_protocol::GenerateTsOptions { + experimental_api: args.experimental, + ..codex_app_server_protocol::GenerateTsOptions::default() + }, + )?; + codex_app_server_protocol::generate_json_with_experimental(&args.out_dir, args.experimental) } diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index b48651c03c..78d5507277 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -37,6 +37,14 @@ use ts_rs::TS; const HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n"; const IGNORED_DEFINITIONS: &[&str] = &["Option<()>"]; const JSON_V1_ALLOWLIST: &[&str] = &["InitializeParams", "InitializeResponse"]; +const SPECIAL_DEFINITIONS: &[&str] = &[ + "ClientNotification", + "ClientRequest", + "EventMsg", + "ServerNotification", + "ServerRequest", +]; +const FLAT_V2_SHARED_DEFINITIONS: &[&str] = &["ClientRequest", "EventMsg", "ServerNotification"]; const V1_CLIENT_REQUEST_METHODS: &[&str] = &[ "newConversation", "getConversationSummary", @@ -223,6 +231,11 @@ pub fn generate_json_with_experimental(out_dir: &Path, experimental_api: bool) - out_dir.join("codex_app_server_protocol.schemas.json"), &bundle, )?; + let flat_v2_bundle = build_flat_v2_schema(&bundle)?; + write_pretty_json( + out_dir.join("codex_app_server_protocol.v2.schemas.json"), + &flat_v2_bundle, + )?; if !experimental_api { filter_experimental_json_files(out_dir)?; @@ -870,14 +883,6 @@ impl Depth { } fn build_schema_bundle(schemas: Vec) -> Result { - const SPECIAL_DEFINITIONS: &[&str] = &[ - "ClientNotification", - "ClientRequest", - "EventMsg", - "ServerNotification", - "ServerRequest", - ]; - let namespaced_types = collect_namespaced_types(&schemas); let mut definitions = Map::new(); @@ -895,6 +900,8 @@ fn build_schema_bundle(schemas: Vec) -> Result { if let Some(ref ns) = namespace { rewrite_refs_to_namespace(&mut value, ns); + } else { + rewrite_refs_to_known_namespaces(&mut value, &namespaced_types); } let mut forced_namespace_refs: Vec<(String, String)> = Vec::new(); @@ -958,6 +965,210 @@ fn build_schema_bundle(schemas: Vec) -> Result { Ok(Value::Object(root)) } +/// Build a datamodel-code-generator-friendly v2 bundle from the mixed export. +/// +/// The full bundle keeps v2 schemas nested under `definitions.v2`, plus a few +/// shared root definitions like `ClientRequest`, `EventMsg`, and +/// `ServerNotification`. Python codegen only walks one definitions map level, so +/// a direct feed would treat `v2` itself as a schema and miss unreferenced v2 +/// leaves. This helper flattens all v2 definitions to the root definitions map, +/// then pulls in the shared root schemas and any non-v2 transitive deps they +/// still reference. Keep the shared root unions intact here: some valid +/// request/notification/event variants are inline or only reference shared root +/// helpers, so filtering them by the presence of a `#/definitions/v2/` ref +/// would silently drop real API surface from the flat bundle. +fn build_flat_v2_schema(bundle: &Value) -> Result { + let Value::Object(root) = bundle else { + return Err(anyhow!("expected bundle root to be an object")); + }; + let definitions = root + .get("definitions") + .and_then(Value::as_object) + .ok_or_else(|| anyhow!("expected bundle definitions map"))?; + let v2_definitions = definitions + .get("v2") + .and_then(Value::as_object) + .ok_or_else(|| anyhow!("expected v2 namespace in bundle definitions"))?; + + let mut flat_root = root.clone(); + let title = root + .get("title") + .and_then(Value::as_str) + .unwrap_or("CodexAppServerProtocol"); + let mut flat_definitions = v2_definitions.clone(); + let mut shared_definitions = Map::new(); + let mut non_v2_refs = HashSet::new(); + + for shared in FLAT_V2_SHARED_DEFINITIONS { + let Some(shared_schema) = definitions.get(*shared) else { + continue; + }; + let shared_schema = shared_schema.clone(); + non_v2_refs.extend(collect_non_v2_refs(&shared_schema)); + shared_definitions.insert((*shared).to_string(), shared_schema); + } + + for name in collect_definition_dependencies(definitions, non_v2_refs) { + if name == "v2" || flat_definitions.contains_key(&name) { + continue; + } + if let Some(schema) = definitions.get(&name) { + flat_definitions.insert(name, schema.clone()); + } + } + + flat_definitions.extend(shared_definitions); + flat_root.insert("title".to_string(), Value::String(format!("{title}V2"))); + flat_root.insert("definitions".to_string(), Value::Object(flat_definitions)); + let mut flat_bundle = Value::Object(flat_root); + rewrite_ref_prefix(&mut flat_bundle, "#/definitions/v2/", "#/definitions/"); + ensure_no_ref_prefix(&flat_bundle, "#/definitions/v2/", "flat v2")?; + ensure_referenced_definitions_present(&flat_bundle, "flat v2")?; + Ok(flat_bundle) +} + +fn collect_non_v2_refs(value: &Value) -> HashSet { + let mut refs = HashSet::new(); + collect_non_v2_refs_inner(value, &mut refs); + refs +} + +fn collect_non_v2_refs_inner(value: &Value, refs: &mut HashSet) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get("$ref") + && let Some(name) = reference.strip_prefix("#/definitions/") + && !reference.starts_with("#/definitions/v2/") + { + refs.insert(name.to_string()); + } + for child in obj.values() { + collect_non_v2_refs_inner(child, refs); + } + } + Value::Array(items) => { + for child in items { + collect_non_v2_refs_inner(child, refs); + } + } + _ => {} + } +} + +fn collect_definition_dependencies( + definitions: &Map, + names: HashSet, +) -> HashSet { + let mut seen = HashSet::new(); + let mut to_process: Vec = names.into_iter().collect(); + while let Some(name) = to_process.pop() { + if !seen.insert(name.clone()) { + continue; + } + let Some(schema) = definitions.get(&name) else { + continue; + }; + for dep in collect_non_v2_refs(schema) { + if !seen.contains(&dep) { + to_process.push(dep); + } + } + } + seen +} + +fn rewrite_ref_prefix(value: &mut Value, prefix: &str, replacement: &str) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get_mut("$ref") { + *reference = reference.replace(prefix, replacement); + } + for child in obj.values_mut() { + rewrite_ref_prefix(child, prefix, replacement); + } + } + Value::Array(items) => { + for child in items { + rewrite_ref_prefix(child, prefix, replacement); + } + } + _ => {} + } +} + +fn ensure_no_ref_prefix(value: &Value, prefix: &str, label: &str) -> Result<()> { + if let Some(reference) = first_ref_with_prefix(value, prefix) { + return Err(anyhow!( + "{label} schema still references namespaced definitions; found {reference}" + )); + } + Ok(()) +} + +fn first_ref_with_prefix(value: &Value, prefix: &str) -> Option { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get("$ref") + && reference.starts_with(prefix) + { + return Some(reference.clone()); + } + obj.values() + .find_map(|child| first_ref_with_prefix(child, prefix)) + } + Value::Array(items) => items + .iter() + .find_map(|child| first_ref_with_prefix(child, prefix)), + _ => None, + } +} + +fn ensure_referenced_definitions_present(schema: &Value, label: &str) -> Result<()> { + let definitions = schema + .get("definitions") + .and_then(Value::as_object) + .ok_or_else(|| anyhow!("expected definitions map in {label} schema"))?; + let mut missing = HashSet::new(); + collect_missing_definitions(schema, definitions, &mut missing); + if missing.is_empty() { + return Ok(()); + } + let mut missing_names: Vec = missing.into_iter().collect(); + missing_names.sort(); + Err(anyhow!( + "{label} schema missing definitions: {}", + missing_names.join(", ") + )) +} + +fn collect_missing_definitions( + value: &Value, + definitions: &Map, + missing: &mut HashSet, +) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get("$ref") + && let Some(name) = reference.strip_prefix("#/definitions/") + { + let name = name.split('/').next().unwrap_or(name); + if !definitions.contains_key(name) { + missing.insert(name.to_string()); + } + } + for child in obj.values() { + collect_missing_definitions(child, definitions, missing); + } + } + Value::Array(items) => { + for child in items { + collect_missing_definitions(child, definitions, missing); + } + } + _ => {} + } +} + fn insert_into_namespace( definitions: &mut Map, namespace: &str, @@ -1230,6 +1441,43 @@ fn rewrite_refs_to_namespace(value: &mut Value, ns: &str) { } } +/// Recursively rewrite bare root definition refs to the namespace that owns the +/// referenced type in the bundle. +/// +/// The mixed export contains shared root helper schemas that are intentionally +/// left outside the `v2` namespace, but some of their extracted child +/// definitions still contain refs like `#/definitions/ThreadId`. When the real +/// schema only exists under `#/definitions/v2/ThreadId`, those refs become +/// dangling and downstream codegen falls back to placeholder `Any` models. This +/// rewrite keeps the shared helpers at the root while retargeting their refs to +/// the namespaced definitions that actually exist. +fn rewrite_refs_to_known_namespaces(value: &mut Value, types: &HashMap) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get_mut("$ref") + && let Some(suffix) = reference.strip_prefix("#/definitions/") + { + let (name, tail) = suffix + .split_once('/') + .map_or((suffix, None), |(name, tail)| (name, Some(tail))); + if let Some(ns) = namespace_for_definition(name, types) { + let tail = tail.map_or(String::new(), |rest| format!("/{rest}")); + *reference = format!("#/definitions/{ns}/{name}{tail}"); + } + } + for v in obj.values_mut() { + rewrite_refs_to_known_namespaces(v, types); + } + } + Value::Array(items) => { + for v in items.iter_mut() { + rewrite_refs_to_known_namespaces(v, types); + } + } + _ => {} + } +} + fn collect_namespaced_types(schemas: &[GeneratedSchema]) -> HashMap { let mut types = HashMap::new(); for schema in schemas { @@ -1986,6 +2234,284 @@ mod tests { Ok(()) } + #[test] + fn build_schema_bundle_rewrites_root_helper_refs_to_namespaced_defs() -> Result<()> { + let bundle = build_schema_bundle(vec![ + GeneratedSchema { + namespace: None, + logical_name: "LegacyEnvelope".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "LegacyEnvelope", + "type": "object", + "properties": { + "current_thread": { "$ref": "#/definitions/ThreadId" }, + "turn_item": { "$ref": "#/definitions/TurnItem" } + }, + "definitions": { + "TurnItem": { + "type": "object", + "properties": { + "thread_id": { "$ref": "#/definitions/ThreadId" }, + "phase": { "$ref": "#/definitions/MessagePhase" }, + "content": { + "type": "array", + "items": { "$ref": "#/definitions/UserInput" } + } + } + } + } + }), + }, + GeneratedSchema { + namespace: Some("v2".to_string()), + logical_name: "ThreadId".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "ThreadId", + "type": "string" + }), + }, + GeneratedSchema { + namespace: Some("v2".to_string()), + logical_name: "MessagePhase".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "MessagePhase", + "type": "string" + }), + }, + GeneratedSchema { + namespace: Some("v2".to_string()), + logical_name: "UserInput".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "UserInput", + "type": "string" + }), + }, + ])?; + + assert_eq!( + bundle["definitions"]["LegacyEnvelope"]["properties"]["current_thread"]["$ref"], + serde_json::json!("#/definitions/v2/ThreadId") + ); + assert_eq!( + bundle["definitions"]["LegacyEnvelope"]["properties"]["turn_item"]["$ref"], + serde_json::json!("#/definitions/TurnItem") + ); + assert_eq!( + bundle["definitions"]["TurnItem"]["properties"]["thread_id"]["$ref"], + serde_json::json!("#/definitions/v2/ThreadId") + ); + assert_eq!( + bundle["definitions"]["TurnItem"]["properties"]["phase"]["$ref"], + serde_json::json!("#/definitions/v2/MessagePhase") + ); + assert_eq!( + bundle["definitions"]["TurnItem"]["properties"]["content"]["items"]["$ref"], + serde_json::json!("#/definitions/v2/UserInput") + ); + + Ok(()) + } + + #[test] + fn build_flat_v2_schema_keeps_shared_root_schemas_and_dependencies() -> Result<()> { + let bundle = serde_json::json!({ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "CodexAppServerProtocol", + "type": "object", + "definitions": { + "ClientRequest": { + "oneOf": [ + { + "title": "StartRequest", + "type": "object", + "properties": { + "params": { "$ref": "#/definitions/v2/ThreadStartParams" }, + "shared": { "$ref": "#/definitions/SharedHelper" } + } + }, + { + "title": "InitializeRequest", + "type": "object", + "properties": { + "params": { "$ref": "#/definitions/InitializeParams" } + } + }, + { + "title": "LogoutRequest", + "type": "object", + "properties": { + "params": { "type": "null" } + } + } + ] + }, + "EventMsg": { + "oneOf": [ + { "$ref": "#/definitions/v2/ThreadStartedEventMsg" }, + { + "title": "WarningEventMsg", + "type": "object", + "properties": { + "message": { "type": "string" }, + "type": { + "enum": ["warning"], + "type": "string" + } + }, + "required": ["message", "type"] + } + ] + }, + "ServerNotification": { + "oneOf": [ + { "$ref": "#/definitions/v2/ThreadStartedNotification" }, + { + "title": "ServerRequestResolvedNotification", + "type": "object", + "properties": { + "params": { "$ref": "#/definitions/ServerRequestResolvedNotificationPayload" } + } + } + ] + }, + "SharedHelper": { + "type": "object", + "properties": { + "leaf": { "$ref": "#/definitions/SharedLeaf" } + } + }, + "SharedLeaf": { + "title": "SharedLeaf", + "type": "string" + }, + "InitializeParams": { + "title": "InitializeParams", + "type": "string" + }, + "ServerRequestResolvedNotificationPayload": { + "title": "ServerRequestResolvedNotificationPayload", + "type": "string" + }, + "v2": { + "ThreadStartParams": { + "title": "ThreadStartParams", + "type": "object", + "properties": { + "cwd": { "type": "string" } + } + }, + "ThreadStartResponse": { + "title": "ThreadStartResponse", + "type": "object", + "properties": { + "ok": { "type": "boolean" } + } + }, + "ThreadStartedEventMsg": { + "title": "ThreadStartedEventMsg", + "type": "object", + "properties": { + "thread_id": { "type": "string" } + } + }, + "ThreadStartedNotification": { + "title": "ThreadStartedNotification", + "type": "object", + "properties": { + "thread_id": { "type": "string" } + } + } + } + } + }); + + let flat_bundle = build_flat_v2_schema(&bundle)?; + let definitions = flat_bundle["definitions"] + .as_object() + .expect("flat v2 schema should include definitions"); + + assert_eq!( + flat_bundle["title"], + serde_json::json!("CodexAppServerProtocolV2") + ); + assert_eq!(definitions.contains_key("v2"), false); + assert_eq!(definitions.contains_key("ThreadStartParams"), true); + assert_eq!(definitions.contains_key("ThreadStartResponse"), true); + assert_eq!(definitions.contains_key("ThreadStartedEventMsg"), true); + assert_eq!(definitions.contains_key("ThreadStartedNotification"), true); + assert_eq!(definitions.contains_key("SharedHelper"), true); + assert_eq!(definitions.contains_key("SharedLeaf"), true); + assert_eq!(definitions.contains_key("InitializeParams"), true); + assert_eq!( + definitions.contains_key("ServerRequestResolvedNotificationPayload"), + true + ); + let client_request_titles: BTreeSet = definitions["ClientRequest"]["oneOf"] + .as_array() + .expect("ClientRequest should remain a oneOf") + .iter() + .map(|variant| { + variant["title"] + .as_str() + .expect("ClientRequest variant should have a title") + .to_string() + }) + .collect(); + assert_eq!( + client_request_titles, + BTreeSet::from([ + "InitializeRequest".to_string(), + "LogoutRequest".to_string(), + "StartRequest".to_string(), + ]) + ); + let event_titles: BTreeSet = definitions["EventMsg"]["oneOf"] + .as_array() + .expect("EventMsg should remain a oneOf") + .iter() + .map(|variant| { + variant + .get("title") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }) + .collect(); + assert_eq!( + event_titles, + BTreeSet::from(["".to_string(), "WarningEventMsg".to_string(),]) + ); + let notification_titles: BTreeSet = definitions["ServerNotification"]["oneOf"] + .as_array() + .expect("ServerNotification should remain a oneOf") + .iter() + .map(|variant| { + variant + .get("title") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }) + .collect(); + assert_eq!( + notification_titles, + BTreeSet::from([ + "".to_string(), + "ServerRequestResolvedNotification".to_string(), + ]) + ); + assert_eq!( + first_ref_with_prefix(&flat_bundle, "#/definitions/v2/").is_none(), + true + ); + + Ok(()) + } + #[test] fn experimental_type_fields_ts_filter_handles_interface_shape() -> Result<()> { let output_dir = std::env::temp_dir().join(format!("codex_ts_filter_{}", Uuid::now_v7())); @@ -2114,6 +2640,99 @@ export type Config = { stableField: Keep, unstableField: string | null } & ({ [k bundle_json.contains("MockExperimentalMethodResponse"), false ); + let flat_v2_bundle_json = + fs::read_to_string(output_dir.join("codex_app_server_protocol.v2.schemas.json"))?; + assert_eq!(flat_v2_bundle_json.contains("mockExperimentalField"), false); + assert_eq!(flat_v2_bundle_json.contains("additionalPermissions"), false); + assert_eq!( + flat_v2_bundle_json.contains("MockExperimentalMethodParams"), + false + ); + assert_eq!( + flat_v2_bundle_json.contains("MockExperimentalMethodResponse"), + false + ); + assert_eq!(flat_v2_bundle_json.contains("#/definitions/v2/"), false); + assert_eq!( + flat_v2_bundle_json.contains("\"title\": \"CodexAppServerProtocolV2\""), + true + ); + let flat_v2_bundle = + read_json_value(&output_dir.join("codex_app_server_protocol.v2.schemas.json"))?; + let definitions = flat_v2_bundle["definitions"] + .as_object() + .expect("flat v2 bundle should include definitions"); + let client_request_methods: BTreeSet = definitions["ClientRequest"]["oneOf"] + .as_array() + .expect("flat v2 ClientRequest should remain a oneOf") + .iter() + .filter_map(|variant| { + variant["properties"]["method"]["enum"] + .as_array() + .and_then(|values| values.first()) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect(); + let missing_client_request_methods: Vec = [ + "account/logout", + "account/rateLimits/read", + "config/mcpServer/reload", + "configRequirements/read", + "fuzzyFileSearch", + "initialize", + ] + .into_iter() + .filter(|method| !client_request_methods.contains(*method)) + .map(str::to_string) + .collect(); + assert_eq!(missing_client_request_methods, Vec::::new()); + let server_notification_methods: BTreeSet = + definitions["ServerNotification"]["oneOf"] + .as_array() + .expect("flat v2 ServerNotification should remain a oneOf") + .iter() + .filter_map(|variant| { + variant["properties"]["method"]["enum"] + .as_array() + .and_then(|values| values.first()) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect(); + let missing_server_notification_methods: Vec = [ + "fuzzyFileSearch/sessionCompleted", + "fuzzyFileSearch/sessionUpdated", + "serverRequest/resolved", + ] + .into_iter() + .filter(|method| !server_notification_methods.contains(*method)) + .map(str::to_string) + .collect(); + assert_eq!(missing_server_notification_methods, Vec::::new()); + let event_types: BTreeSet = definitions["EventMsg"]["oneOf"] + .as_array() + .expect("flat v2 EventMsg should remain a oneOf") + .iter() + .filter_map(|variant| { + variant["properties"]["type"]["enum"] + .as_array() + .and_then(|values| values.first()) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect(); + let missing_event_types: Vec = [ + "agent_message_delta", + "task_complete", + "warning", + "web_search_begin", + ] + .into_iter() + .filter(|event_type| !event_types.contains(*event_type)) + .map(str::to_string) + .collect(); + assert_eq!(missing_event_types, Vec::::new()); assert_eq!( output_dir .join("v2") From 69df12efb35d07387165f48103e238f4f32044fa Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Tue, 3 Mar 2026 11:32:53 -0700 Subject: [PATCH 335/385] Remove Responses V1 websocket implementation (#13364) V2 is the way to go! --- codex-rs/codex-api/src/common.rs | 10 -- codex-rs/codex-api/src/lib.rs | 1 - codex-rs/codex-api/src/sse/responses.rs | 107 +------------ codex-rs/codex-api/tests/sse_end_to_end.rs | 2 - codex-rs/core/src/client.rs | 141 +++++------------- codex-rs/core/src/codex.rs | 9 +- codex-rs/core/src/compact.rs | 3 +- codex-rs/core/src/lib.rs | 1 - codex-rs/core/tests/common/responses.rs | 19 --- codex-rs/core/tests/responses_headers.rs | 7 +- codex-rs/core/tests/suite/agent_websocket.rs | 77 +++++----- codex-rs/core/tests/suite/client.rs | 3 +- .../core/tests/suite/client_websockets.rs | 97 +++++------- codex-rs/core/tests/suite/turn_state.rs | 3 +- .../core/tests/suite/websocket_fallback.rs | 6 +- 15 files changed, 133 insertions(+), 353 deletions(-) diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index b6126840d9..31b4dcdb44 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -67,8 +67,6 @@ pub enum ResponseEvent { Completed { response_id: String, token_usage: Option, - /// Whether the client can append more items to a long-running websocket response. - can_append: bool, }, OutputTextDelta(String), ReasoningSummaryDelta { @@ -211,20 +209,12 @@ pub struct ResponseCreateWsRequest { pub client_metadata: Option>, } -#[derive(Debug, Serialize)] -pub struct ResponseAppendWsRequest { - pub input: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub client_metadata: Option>, -} #[derive(Debug, Serialize)] #[serde(tag = "type")] #[allow(clippy::large_enum_variant)] pub enum ResponsesWsRequest { #[serde(rename = "response.create")] ResponseCreate(ResponseCreateWsRequest), - #[serde(rename = "response.append")] - ResponseAppend(ResponseAppendWsRequest), } pub fn create_text_param_for_request( diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs index b9152ec576..138929602b 100644 --- a/codex-rs/codex-api/src/lib.rs +++ b/codex-rs/codex-api/src/lib.rs @@ -19,7 +19,6 @@ pub use crate::common::MemorySummarizeInput; pub use crate::common::MemorySummarizeOutput; pub use crate::common::RawMemory; pub use crate::common::RawMemoryMetadata; -pub use crate::common::ResponseAppendWsRequest; pub use crate::common::ResponseCreateWsRequest; pub use crate::common::ResponseEvent; pub use crate::common::ResponseStream; diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 3c039380c9..d01e1d918a 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -118,14 +118,6 @@ struct ResponseCompleted { usage: Option, } -#[derive(Debug, Deserialize)] -struct ResponseDone { - #[serde(default)] - id: Option, - #[serde(default)] - usage: Option, -} - #[derive(Debug, Deserialize)] struct ResponseCompletedUsage { input_tokens: i64, @@ -324,7 +316,6 @@ pub fn process_responses_event( return Ok(Some(ResponseEvent::Completed { response_id: resp.id, token_usage: resp.usage.map(Into::into), - can_append: false, })); } Err(err) => { @@ -335,31 +326,6 @@ pub fn process_responses_event( } } } - "response.done" => { - if let Some(resp_val) = event.response { - match serde_json::from_value::(resp_val) { - Ok(resp) => { - return Ok(Some(ResponseEvent::Completed { - response_id: resp.id.unwrap_or_default(), - token_usage: resp.usage.map(Into::into), - can_append: true, - })); - } - Err(err) => { - let error = format!("failed to parse ResponseCompleted: {err}"); - debug!("{error}"); - return Err(ResponsesEventError::Api(ApiError::Stream(error))); - } - } - } - - debug!("response.done missing response payload"); - return Ok(Some(ResponseEvent::Completed { - response_id: String::new(), - token_usage: None, - can_append: true, - })); - } "response.output_item.added" => { if let Some(item_val) = event.item { if let Ok(item) = serde_json::from_value::(item_val) { @@ -639,11 +605,9 @@ mod tests { Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, }) => { assert_eq!(response_id, "resp1"); assert!(token_usage.is_none()); - assert!(!can_append); } other => panic!("unexpected third event: {other:?}"), } @@ -677,69 +641,6 @@ mod tests { } } - #[tokio::test] - async fn response_done_emits_incremental_completed() { - let done = json!({ - "type": "response.done", - "response": { - "usage": { - "input_tokens": 1, - "input_tokens_details": null, - "output_tokens": 2, - "output_tokens_details": null, - "total_tokens": 3 - } - } - }) - .to_string(); - - let sse1 = format!("event: response.done\ndata: {done}\n\n"); - - let events = collect_events(&[sse1.as_bytes()]).await; - - assert_eq!(events.len(), 1); - - match &events[0] { - Ok(ResponseEvent::Completed { - response_id, - token_usage, - can_append, - }) => { - assert_eq!(response_id, ""); - assert!(token_usage.is_some()); - assert!(*can_append); - } - other => panic!("unexpected event: {other:?}"), - } - } - - #[tokio::test] - async fn response_done_without_payload_emits_completed() { - let done = json!({ - "type": "response.done" - }) - .to_string(); - - let sse1 = format!("event: response.done\ndata: {done}\n\n"); - - let events = collect_events(&[sse1.as_bytes()]).await; - - assert_eq!(events.len(), 1); - - match &events[0] { - Ok(ResponseEvent::Completed { - response_id, - token_usage, - can_append, - }) => { - assert_eq!(response_id, ""); - assert!(token_usage.is_none()); - assert!(*can_append); - } - other => panic!("unexpected event: {other:?}"), - } - } - #[tokio::test] async fn emits_completed_without_stream_end() { let completed = json!({ @@ -770,11 +671,9 @@ mod tests { Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, }) => { assert_eq!(response_id, "resp1"); assert!(token_usage.is_none()); - assert!(!can_append); } other => panic!("unexpected event: {other:?}"), } @@ -996,8 +895,7 @@ mod tests { &events[1], ResponseEvent::Completed { response_id, - token_usage: None, - can_append: false + token_usage: None } if response_id == "resp-1" ); } @@ -1033,8 +931,7 @@ mod tests { &events[2], ResponseEvent::Completed { response_id, - token_usage: None, - can_append: false + token_usage: None } if response_id == "resp-1" ); } diff --git a/codex-rs/codex-api/tests/sse_end_to_end.rs b/codex-rs/codex-api/tests/sse_end_to_end.rs index ca840d1b9f..f625fdcd9d 100644 --- a/codex-rs/codex-api/tests/sse_end_to_end.rs +++ b/codex-rs/codex-api/tests/sse_end_to_end.rs @@ -159,11 +159,9 @@ async fn responses_stream_parses_items_and_completed_end_to_end() -> Result<()> ResponseEvent::Completed { response_id, token_usage, - can_append, } => { assert_eq!(response_id, "resp1"); assert!(token_usage.is_none()); - assert!(!can_append); } other => panic!("unexpected third event: {other:?}"), } diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 534b1ec5e4..9e5974b487 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -20,9 +20,8 @@ //! //! ## Retry-Budget Tradeoff //! -//! V2 request prewarm is treated as the first websocket connection attempt for a turn. If it -//! fails, normal stream retry/fallback logic handles recovery on the same turn. V1 prewarm -//! remains connection-only. +//! WebSocket prewarm is treated as the first websocket connection attempt for a turn. If it +//! fails, normal stream retry/fallback logic handles recovery on the same turn. use std::collections::HashMap; use std::sync::Arc; @@ -43,7 +42,6 @@ use codex_api::MemorySummarizeOutput as ApiMemorySummarizeOutput; use codex_api::RawMemory as ApiRawMemory; use codex_api::RequestTelemetry; use codex_api::ReqwestTransport; -use codex_api::ResponseAppendWsRequest; use codex_api::ResponseCreateWsRequest; use codex_api::ResponsesApiRequest; use codex_api::ResponsesClient as ApiResponsesClient; @@ -101,32 +99,19 @@ use crate::model_provider_info::WireApi; use crate::tools::spec::create_tools_json_for_responses_api; pub const OPENAI_BETA_HEADER: &str = "OpenAI-Beta"; -pub const OPENAI_BETA_RESPONSES_WEBSOCKETS: &str = "responses_websockets=2026-02-04"; pub const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state"; pub const X_CODEX_TURN_METADATA_HEADER: &str = "x-codex-turn-metadata"; pub const X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER: &str = "x-responsesapi-include-timing-metrics"; const RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06"; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ResponsesWebsocketVersion { - V1, - V2, -} - -pub fn ws_version_from_features(config: &Config) -> Option { - match ( - config +pub fn ws_version_from_features(config: &Config) -> bool { + config + .features + .enabled(crate::features::Feature::ResponsesWebsockets) + || config .features - .enabled(crate::features::Feature::ResponsesWebsockets), - config - .features - .enabled(crate::features::Feature::ResponsesWebsocketsV2), - ) { - (_, true) => Some(ResponsesWebsocketVersion::V2), - (true, false) => Some(ResponsesWebsocketVersion::V1), - (false, false) => None, - } + .enabled(crate::features::Feature::ResponsesWebsocketsV2) } /// Session-scoped state shared by all [`ModelClient`] clones. @@ -140,7 +125,7 @@ struct ModelClientState { provider: ModelProviderInfo, session_source: SessionSource, model_verbosity: Option, - responses_websocket_version: Option, + responses_websockets_enabled_by_feature: bool, enable_request_compression: bool, include_timing_metrics: bool, beta_features_header: Option, @@ -180,8 +165,8 @@ pub struct ModelClient { /// The session establishes a Responses WebSocket connection lazily and reuses it across multiple /// requests within the turn. It also caches per-turn state: /// -/// - The last full request, so subsequent calls can use `response.append` only when the current -/// request is an incremental extension of the previous one. +/// - The last full request, so subsequent calls can reuse incremental websocket request payloads +/// only when the current request is an incremental extension of the previous one. /// - The `x-codex-turn-state` sticky-routing token, which must be replayed for all requests within /// the same turn. /// @@ -208,7 +193,6 @@ pub struct ModelClientSession { struct LastResponse { response_id: String, items_added: Vec, - can_append: bool, } #[derive(Debug, Default)] @@ -235,7 +219,7 @@ impl ModelClient { provider: ModelProviderInfo, session_source: SessionSource, model_verbosity: Option, - responses_websocket_version: Option, + responses_websockets_enabled_by_feature: bool, enable_request_compression: bool, include_timing_metrics: bool, beta_features_header: Option, @@ -247,7 +231,7 @@ impl ModelClient { provider, session_source, model_verbosity, - responses_websocket_version, + responses_websockets_enabled_by_feature, enable_request_compression, include_timing_metrics, beta_features_header, @@ -391,25 +375,21 @@ impl ModelClient { request_telemetry } - /// Returns the active Responses-over-WebSocket version for this session. + /// Returns whether the Responses-over-WebSocket transport is active for this session. /// /// This combines provider capability and feature gating; both must be true for websocket paths /// to be eligible. /// /// If websockets are only enabled via model preference (no explicit feature flag), prefer the /// current v2 behavior. - pub fn active_ws_version(&self, model_info: &ModelInfo) -> Option { + pub fn responses_websocket_enabled(&self, model_info: &ModelInfo) -> bool { if !self.state.provider.supports_websockets || self.state.disable_websockets.load(Ordering::Relaxed) { - return None; + return false; } - match self.state.responses_websocket_version { - Some(version) => Some(version), - None if model_info.prefer_websockets => Some(ResponsesWebsocketVersion::V2), - None => None, - } + self.state.responses_websockets_enabled_by_feature || model_info.prefer_websockets } /// Returns auth + provider configuration resolved from the current session auth state. @@ -442,12 +422,10 @@ impl ModelClient { otel_manager: &OtelManager, api_provider: codex_api::Provider, api_auth: CoreAuthProvider, - ws_version: ResponsesWebsocketVersion, turn_state: Option>>, turn_metadata_header: Option<&str>, ) -> std::result::Result { - let headers = - self.build_websocket_headers(ws_version, turn_state.as_ref(), turn_metadata_header); + let headers = self.build_websocket_headers(turn_state.as_ref(), turn_metadata_header); let websocket_telemetry = ModelClientSession::build_websocket_telemetry(otel_manager); ApiWebSocketResponsesClient::new(api_provider, api_auth) .connect( @@ -465,7 +443,6 @@ impl ModelClient { /// replayed on reconnect within the same turn. fn build_websocket_headers( &self, - ws_version: ResponsesWebsocketVersion, turn_state: Option<&Arc>>, turn_metadata_header: Option<&str>, ) -> ApiHeaderMap { @@ -478,13 +455,9 @@ impl ModelClient { headers.extend(build_conversation_headers(Some( self.state.conversation_id.to_string(), ))); - let responses_websockets_beta_header = match ws_version { - ResponsesWebsocketVersion::V2 => RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE, - ResponsesWebsocketVersion::V1 => OPENAI_BETA_RESPONSES_WEBSOCKETS, - }; headers.insert( OPENAI_BETA_HEADER, - HeaderValue::from_static(responses_websockets_beta_header), + HeaderValue::from_static(RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE), ); if self.state.include_timing_metrics { headers.insert( @@ -613,8 +586,9 @@ impl ModelClientSession { last_response: Option<&LastResponse>, allow_empty_delta: bool, ) -> Option> { - // Checks whether the current request is an incremental append to the previous request. - // We only append when non-input request fields are unchanged and `input` is a strict + // Checks whether the current request is an incremental extension of the previous request. + // We only reuse an incremental input delta when non-input request fields are unchanged and + // `input` is a strict // extension of the previous known input. Server-returned output items are treated as part // of the baseline so we do not resend them. let previous_request = self.websocket_session.last_request.as_ref()?; @@ -659,42 +633,26 @@ impl ModelClientSession { &mut self, payload: ResponseCreateWsRequest, request: &ResponsesApiRequest, - ws_version: ResponsesWebsocketVersion, ) -> ResponsesWsRequest { let Some(last_response) = self.get_last_response() else { return ResponsesWsRequest::ResponseCreate(payload); }; - let allow_empty_delta = matches!(ws_version, ResponsesWebsocketVersion::V2); - let Some(append_items) = - self.get_incremental_items(request, Some(&last_response), allow_empty_delta) + let Some(incremental_items) = + self.get_incremental_items(request, Some(&last_response), true) else { return ResponsesWsRequest::ResponseCreate(payload); }; - match ws_version { - ResponsesWebsocketVersion::V2 => { - if last_response.response_id.is_empty() { - trace!("incremental request failed, no previous response id"); - return ResponsesWsRequest::ResponseCreate(payload); - } - - ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest { - previous_response_id: Some(last_response.response_id), - input: append_items, - ..payload - }) - } - ResponsesWebsocketVersion::V1 => { - if !last_response.can_append { - trace!("incremental request failed, can't append"); - return ResponsesWsRequest::ResponseCreate(payload); - } - ResponsesWsRequest::ResponseAppend(ResponseAppendWsRequest { - input: append_items, - client_metadata: payload.client_metadata, - }) - } + if last_response.response_id.is_empty() { + trace!("incremental request failed, no previous response id"); + return ResponsesWsRequest::ResponseCreate(payload); } + + ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest { + previous_response_id: Some(last_response.response_id), + input: incremental_items, + ..payload + }) } /// Opportunistically preconnects a websocket for this turn-scoped client session. @@ -705,9 +663,9 @@ impl ModelClientSession { otel_manager: &OtelManager, model_info: &ModelInfo, ) -> std::result::Result<(), ApiError> { - let Some(ws_version) = self.client.active_ws_version(model_info) else { + if !self.client.responses_websocket_enabled(model_info) { return Ok(()); - }; + } if self.websocket_session.connection.is_some() { return Ok(()); } @@ -724,7 +682,6 @@ impl ModelClientSession { otel_manager, client_setup.api_provider, client_setup.api_auth, - ws_version, Some(Arc::clone(&self.turn_state)), None, ) @@ -738,7 +695,6 @@ impl ModelClientSession { otel_manager: &OtelManager, api_provider: codex_api::Provider, api_auth: CoreAuthProvider, - ws_version: ResponsesWebsocketVersion, turn_metadata_header: Option<&str>, options: &ApiResponsesOptions, ) -> std::result::Result<&ApiWebSocketConnection, ApiError> { @@ -760,7 +716,6 @@ impl ModelClientSession { otel_manager, api_provider, api_auth, - ws_version, Some(turn_state), turn_metadata_header, ) @@ -862,7 +817,6 @@ impl ModelClientSession { &mut self, prompt: &Prompt, model_info: &ModelInfo, - ws_version: ResponsesWebsocketVersion, otel_manager: &OtelManager, effort: Option, summary: ReasoningSummaryConfig, @@ -901,7 +855,6 @@ impl ModelClientSession { otel_manager, client_setup.api_provider, client_setup.api_auth, - ws_version, turn_metadata_header, &options, ) @@ -922,7 +875,7 @@ impl ModelClientSession { Err(err) => return Err(map_api_error(err)), } - let ws_request = self.prepare_websocket_request(ws_payload, &request, ws_version); + let ws_request = self.prepare_websocket_request(ws_payload, &request); self.websocket_session.last_request = Some(request); let stream_result = self .websocket_session @@ -971,17 +924,10 @@ impl ModelClientSession { service_tier: Option, turn_metadata_header: Option<&str>, ) -> Result<()> { - let Some(ws_version) = self.client.active_ws_version(model_info) else { - return Ok(()); - }; - if self.websocket_session.last_request.is_some() { + if !self.client.responses_websocket_enabled(model_info) { return Ok(()); } - - if matches!(ws_version, ResponsesWebsocketVersion::V1) { - self.preconnect_websocket(otel_manager, model_info) - .await - .map_err(map_api_error)?; + if self.websocket_session.last_request.is_some() { return Ok(()); } @@ -989,7 +935,6 @@ impl ModelClientSession { .stream_responses_websocket( prompt, model_info, - ws_version, otel_manager, effort, summary, @@ -1038,12 +983,11 @@ impl ModelClientSession { let wire_api = self.client.state.provider.wire_api; match wire_api { WireApi::Responses => { - if let Some(ws_version) = self.client.active_ws_version(model_info) { + if self.client.responses_websocket_enabled(model_info) { match self .stream_responses_websocket( prompt, model_info, - ws_version, otel_manager, effort, summary, @@ -1085,7 +1029,7 @@ impl ModelClientSession { otel_manager: &OtelManager, model_info: &ModelInfo, ) -> bool { - let websocket_enabled = self.client.active_ws_version(model_info).is_some(); + let websocket_enabled = self.client.responses_websocket_enabled(model_info); let activated = self.activate_http_fallback(websocket_enabled); if activated { warn!("falling back to HTTP"); @@ -1183,7 +1127,6 @@ where Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, }) => { if let Some(usage) = &token_usage { otel_manager.sse_event_completed( @@ -1198,14 +1141,12 @@ where let _ = sender.send(LastResponse { response_id: response_id.clone(), items_added: std::mem::take(&mut items_added), - can_append, }); } if tx_event .send(Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, })) .await .is_err() @@ -1335,7 +1276,7 @@ mod tests { provider, session_source, None, - None, + false, false, false, None, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 7b540aa4d8..3a28a3e83b 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -5572,12 +5572,10 @@ async fn run_sampling_request( // transient reconnect messages. In debug builds, keep full visibility for diagnosis. let report_error = retries > 1 || cfg!(debug_assertions) - || sess + || !sess .services .model_client - .active_ws_version(&turn_context.model_info) - .is_none(); - + .responses_websocket_enabled(&turn_context.model_info); if report_error { // Surface retry information to any UI/front‑end so the // user understands what is happening instead of staring @@ -6418,7 +6416,6 @@ async fn try_run_sampling_request( ResponseEvent::Completed { response_id: _, token_usage, - can_append: _, } => { flush_assistant_text_segments_all( &sess, @@ -9194,7 +9191,7 @@ mod tests { handlers::run_user_shell_command(&session, "sub-id".to_string(), "echo shell".to_string()) .await; - let deadline = StdDuration::from_secs(5); + let deadline = StdDuration::from_secs(15); let start = std::time::Instant::now(); loop { let remaining = deadline.saturating_sub(start.elapsed()); diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index baabf8a42f..6c7dbb1050 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -109,7 +109,8 @@ async fn run_compact_task_inner( let max_retries = turn_context.provider.stream_max_retries(); let mut retries = 0; let mut client_session = sess.services.model_client.new_session(); - // Reuse one client session so turn-scoped state (sticky routing, websocket append tracking) + // Reuse one client session so turn-scoped state (sticky routing, websocket incremental + // request tracking) // survives retries within this compact turn. loop { diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index ef988f1c52..828bbe214a 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -147,7 +147,6 @@ pub(crate) use codex_shell_command::powershell; pub use client::ModelClient; pub use client::ModelClientSession; -pub use client::ResponsesWebsocketVersion; pub use client::X_CODEX_TURN_METADATA_HEADER; pub use client::ws_version_from_features; pub use client_common::Prompt; diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index c1a40e90fc..4f2e89636e 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -582,25 +582,6 @@ pub fn ev_completed(id: &str) -> Value { }) } -pub fn ev_done() -> Value { - serde_json::json!({ - "type": "response.done", - "response": { - "usage": {"input_tokens":0,"input_tokens_details":null,"output_tokens":0,"output_tokens_details":null,"total_tokens":0} - } - }) -} - -pub fn ev_done_with_id(id: &str) -> Value { - serde_json::json!({ - "type": "response.done", - "response": { - "id": id, - "usage": {"input_tokens":0,"input_tokens_details":null,"output_tokens":0,"output_tokens_details":null,"total_tokens":0} - } - }) -} - /// Convenience: SSE event for a created response with a specific id. pub fn ev_response_created(id: &str) -> Value { serde_json::json!({ diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index a46c45f234..be41a25a0f 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -6,7 +6,6 @@ use codex_core::ModelClient; use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; -use codex_core::ResponsesWebsocketVersion; use codex_core::WireApi; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; @@ -92,7 +91,7 @@ async fn responses_stream_includes_subagent_header_on_review() { provider.clone(), session_source, config.model_verbosity, - None::, + false, false, false, None, @@ -205,7 +204,7 @@ async fn responses_stream_includes_subagent_header_on_other() { provider.clone(), session_source, config.model_verbosity, - None::, + false, false, false, None, @@ -317,7 +316,7 @@ async fn responses_respects_model_info_overrides_from_config() { provider.clone(), session_source, config.model_verbosity, - None::, + false, false, false, None, diff --git a/codex-rs/core/tests/suite/agent_websocket.rs b/codex-rs/core/tests/suite/agent_websocket.rs index fdd9f316d6..0db3cf61ad 100644 --- a/codex-rs/core/tests/suite/agent_websocket.rs +++ b/codex-rs/core/tests/suite/agent_websocket.rs @@ -4,8 +4,6 @@ use codex_protocol::config_types::ServiceTier; use core_test_support::responses::WebSocketConnectionConfig; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_done; -use core_test_support::responses::ev_done_with_id; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_shell_command_call; use core_test_support::responses::start_websocket_server; @@ -27,7 +25,7 @@ async fn websocket_test_codex_shell_chain() -> Result<()> { vec![ ev_response_created("resp-1"), ev_shell_command_call(call_id, "echo websocket"), - ev_done(), + ev_completed("resp-1"), ], vec![ ev_response_created("resp-2"), @@ -59,36 +57,30 @@ async fn websocket_test_codex_shell_chain() -> Result<()> { .body_json(); assert_eq!(first_turn["type"].as_str(), Some("response.create")); - assert_eq!(second_turn["type"].as_str(), Some("response.append")); + assert_eq!(second_turn["type"].as_str(), Some("response.create")); - let append_items = second_turn + let input_items = second_turn .get("input") .and_then(Value::as_array) - .expect("response.append input array"); - assert!(!append_items.is_empty()); - - let output_item = append_items - .iter() - .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output")) - .expect("function_call_output in append"); - assert_eq!( - output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); + .expect("second response.create input array"); + assert!(!input_items.is_empty()); server.shutdown().await; Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn websocket_first_turn_uses_preconnect_and_create() -> Result<()> { +async fn websocket_first_turn_uses_startup_prewarm_and_create() -> Result<()> { skip_if_no_network!(Ok(())); - let server = start_websocket_server(vec![vec![vec![ - ev_response_created("resp-1"), - ev_assistant_message("msg-1", "hello"), - ev_completed("resp-1"), - ]]]) + let server = start_websocket_server(vec![vec![ + vec![ev_response_created("warm-1"), ev_completed("warm-1")], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "hello"), + ev_completed("resp-1"), + ], + ]]) .await; let mut builder = test_codex(); @@ -101,11 +93,14 @@ async fn websocket_first_turn_uses_preconnect_and_create() -> Result<()> { assert_eq!(server.handshakes().len(), 1); let connection = server.single_connection(); - assert_eq!(connection.len(), 1); - let turn = connection + assert_eq!(connection.len(), 2); + let warmup = connection .first() - .expect("missing turn request") + .expect("missing warmup request") .body_json(); + let turn = connection.get(1).expect("missing turn request").body_json(); + assert_eq!(warmup["type"].as_str(), Some("response.create")); + assert_eq!(warmup["generate"].as_bool(), Some(false)); assert!( turn["tools"] .as_array() @@ -119,15 +114,18 @@ async fn websocket_first_turn_uses_preconnect_and_create() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn websocket_first_turn_handles_handshake_delay_with_preconnect() -> Result<()> { +async fn websocket_first_turn_handles_handshake_delay_with_startup_prewarm() -> Result<()> { skip_if_no_network!(Ok(())); let server = start_websocket_server_with_headers(vec![WebSocketConnectionConfig { - requests: vec![vec![ - ev_response_created("resp-1"), - ev_assistant_message("msg-1", "hello"), - ev_completed("resp-1"), - ]], + requests: vec![ + vec![ev_response_created("warm-1"), ev_completed("warm-1")], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "hello"), + ev_completed("resp-1"), + ], + ], response_headers: Vec::new(), // Delay handshake so turn processing must tolerate websocket startup latency. accept_delay: Some(Duration::from_millis(150)), @@ -144,11 +142,14 @@ async fn websocket_first_turn_handles_handshake_delay_with_preconnect() -> Resul assert_eq!(server.handshakes().len(), 1); let connection = server.single_connection(); - assert_eq!(connection.len(), 1); - let turn = connection + assert_eq!(connection.len(), 2); + let warmup = connection .first() - .expect("missing turn request") + .expect("missing warmup request") .body_json(); + let turn = connection.get(1).expect("missing turn request").body_json(); + assert_eq!(warmup["type"].as_str(), Some("response.create")); + assert_eq!(warmup["generate"].as_bool(), Some(false)); assert!( turn["tools"] .as_array() @@ -167,7 +168,7 @@ async fn websocket_v2_test_codex_shell_chain() -> Result<()> { let call_id = "shell-command-call"; let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ ev_response_created("resp-1"), ev_shell_command_call(call_id, "echo websocket"), @@ -251,7 +252,7 @@ async fn websocket_v2_first_turn_uses_updated_fast_tier_after_startup_prewarm() skip_if_no_network!(Ok(())); let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "fast"), @@ -300,7 +301,7 @@ async fn websocket_v2_first_turn_drops_fast_tier_after_startup_prewarm() -> Resu skip_if_no_network!(Ok(())); let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "standard"), @@ -349,7 +350,7 @@ async fn websocket_v2_next_turn_uses_updated_service_tier() -> Result<()> { skip_if_no_network!(Ok(())); let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "fast"), diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 8521c91eb1..d4a8ce9f3e 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -4,7 +4,6 @@ use codex_core::ModelProviderInfo; use codex_core::NewThread; use codex_core::Prompt; use codex_core::ResponseEvent; -use codex_core::ResponsesWebsocketVersion; use codex_core::ThreadManager; use codex_core::WireApi; use codex_core::auth::AuthCredentialsStoreMode; @@ -1643,7 +1642,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { provider.clone(), SessionSource::Exec, config.model_verbosity, - None::, + false, false, false, None, diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 2c2dc7c7cf..b2098c039c 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -31,8 +31,6 @@ use core_test_support::responses::WebSocketConnectionConfig; use core_test_support::responses::WebSocketTestServer; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_done; -use core_test_support::responses::ev_done_with_id; use core_test_support::responses::ev_response_created; use core_test_support::responses::start_websocket_server; use core_test_support::responses::start_websocket_server_with_headers; @@ -50,7 +48,6 @@ use tracing_test::traced_test; const MODEL: &str = "gpt-5.2-codex"; const OPENAI_BETA_HEADER: &str = "OpenAI-Beta"; -const OPENAI_BETA_RESPONSES_WEBSOCKETS: &str = "responses_websockets=2026-02-04"; const WS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06"; struct WebsocketTestHarness { @@ -89,7 +86,7 @@ async fn responses_websocket_streams_request() { let handshake = server.single_handshake(); assert_eq!( handshake.header(OPENAI_BETA_HEADER), - Some(OPENAI_BETA_RESPONSES_WEBSOCKETS.to_string()) + Some(WS_V2_BETA_HEADER_VALUE.to_string()) ); server.shutdown().await; @@ -125,7 +122,7 @@ async fn responses_websocket_request_prewarm_reuses_connection() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ev_response_created("resp-1"), ev_completed("resp-1")], ]]) .await; @@ -244,7 +241,7 @@ async fn responses_websocket_request_prewarm_is_reused_even_with_header_changes( skip_if_no_network!(); let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ev_response_created("resp-1"), ev_completed("resp-1")], ]]) .await; @@ -344,13 +341,6 @@ async fn responses_websocket_prewarm_uses_v2_when_model_prefers_websockets_and_f .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - stream_until_complete(&mut client_session, &harness, &prompt).await; assert_eq!(server.handshakes().len(), 1); let connection = server.single_connection(); @@ -404,13 +394,6 @@ async fn responses_websocket_preconnect_runs_when_only_v2_feature_enabled() { .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } @@ -422,7 +405,7 @@ async fn responses_websocket_v2_requests_use_v2_when_model_prefers_websockets() vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -460,13 +443,6 @@ async fn responses_websocket_v2_requests_use_v2_when_model_prefers_websockets() .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } @@ -478,7 +454,7 @@ async fn responses_websocket_v2_incremental_requests_are_reused_across_turns() { vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -522,7 +498,7 @@ async fn responses_websocket_v2_wins_when_both_features_enabled() { vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -560,13 +536,6 @@ async fn responses_websocket_v2_wins_when_both_features_enabled() { .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } @@ -835,7 +804,14 @@ async fn responses_websocket_usage_limit_error_emits_rate_limit_event() { } }); - let server = start_websocket_server(vec![vec![vec![usage_limit_error]]]).await; + let server = start_websocket_server(vec![vec![ + vec![ + ev_response_created("resp-prewarm"), + ev_completed("resp-prewarm"), + ], + vec![usage_limit_error], + ]]) + .await; let mut builder = test_codex().with_config(|config| { config.model_provider.request_max_retries = Some(0); config.model_provider.stream_max_retries = Some(0); @@ -913,7 +889,14 @@ async fn responses_websocket_invalid_request_error_with_status_is_forwarded() { } }); - let server = start_websocket_server(vec![vec![vec![invalid_request_error]]]).await; + let server = start_websocket_server(vec![vec![ + vec![ + ev_response_created("resp-prewarm"), + ev_completed("resp-prewarm"), + ], + vec![invalid_request_error], + ]]) + .await; let mut builder = test_codex().with_config(|config| { config.model_provider.request_max_retries = Some(0); config.model_provider.stream_max_retries = Some(0); @@ -990,14 +973,14 @@ async fn responses_websocket_connection_limit_error_reconnects_and_completes() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn responses_websocket_appends_on_prefix() { +async fn responses_websocket_uses_incremental_create_on_prefix() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done(), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -1024,24 +1007,25 @@ async fn responses_websocket_appends_on_prefix() { assert_eq!(first["model"].as_str(), Some(MODEL)); assert_eq!(first["stream"], serde_json::Value::Bool(true)); assert_eq!(first["input"].as_array().map(Vec::len), Some(1)); - let expected_append = serde_json::json!({ - "type": "response.append", - "input": serde_json::to_value(&prompt_two.input[2..]).expect("serialize append items"), - }); - assert_eq!(second, expected_append); + assert_eq!(second["type"].as_str(), Some("response.create")); + assert_eq!(second["previous_response_id"].as_str(), Some("resp-1")); + assert_eq!( + second["input"], + serde_json::to_value(&prompt_two.input[2..]).expect("serialize incremental items") + ); server.shutdown().await; } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { +async fn responses_websocket_forwards_turn_metadata_on_initial_and_incremental_create() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done(), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -1085,7 +1069,8 @@ async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { first["client_metadata"]["x-codex-turn-metadata"].as_str(), Some(first_turn_metadata) ); - assert_eq!(second["type"].as_str(), Some("response.append")); + assert_eq!(second["type"].as_str(), Some("response.create")); + assert_eq!(second["previous_response_id"].as_str(), Some("resp-1")); assert_eq!( second["client_metadata"]["x-codex-turn-metadata"].as_str(), Some(enriched_turn_metadata) @@ -1107,7 +1092,7 @@ async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn responses_websocket_creates_on_prefix_when_previous_completion_cannot_append() { +async fn responses_websocket_uses_previous_response_id_when_prefix_after_completed() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ @@ -1137,9 +1122,10 @@ async fn responses_websocket_creates_on_prefix_when_previous_completion_cannot_a let second = connection.get(1).expect("missing request").body_json(); assert_eq!(second["type"].as_str(), Some("response.create")); + assert_eq!(second["previous_response_id"].as_str(), Some("resp-1")); assert_eq!( second["input"], - serde_json::to_value(&prompt_two.input).expect("serialize full input") + serde_json::to_value(&prompt_two.input[2..]).expect("serialize incremental input") ); server.shutdown().await; @@ -1222,7 +1208,7 @@ async fn responses_websocket_v2_creates_with_previous_response_id_on_prefix() { vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -1409,13 +1395,6 @@ async fn responses_websocket_v2_sets_openai_beta_header() { .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } diff --git a/codex-rs/core/tests/suite/turn_state.rs b/codex-rs/core/tests/suite/turn_state.rs index 62bd974393..c068cfafb1 100644 --- a/codex-rs/core/tests/suite/turn_state.rs +++ b/codex-rs/core/tests/suite/turn_state.rs @@ -4,7 +4,6 @@ use anyhow::Result; use core_test_support::responses::WebSocketConnectionConfig; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_done; use core_test_support::responses::ev_reasoning_item; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_shell_command_call; @@ -100,7 +99,7 @@ async fn websocket_turn_state_persists_within_turn_and_resets_after() -> Result< ev_response_created("resp-1"), ev_reasoning_item("rsn-1", &["thinking"], &[]), ev_shell_command_call(call_id, "echo websocket"), - ev_done(), + ev_completed("resp-1"), ]], response_headers: vec![(TURN_STATE_HEADER.to_string(), "ts-1".to_string())], accept_delay: None, diff --git a/codex-rs/core/tests/suite/websocket_fallback.rs b/codex-rs/core/tests/suite/websocket_fallback.rs index 5be4bc9109..fadd427c16 100644 --- a/codex-rs/core/tests/suite/websocket_fallback.rs +++ b/codex-rs/core/tests/suite/websocket_fallback.rs @@ -66,9 +66,9 @@ async fn websocket_fallback_switches_to_http_on_upgrade_required_connect() -> Re .filter(|req| req.method == Method::POST && req.url.path().ends_with("/responses")) .count(); - // Startup prewarm now only preconnects for v1 (one websocket GET with no request body). - // The first turn then attempts websocket once, sees 426, and falls back to HTTP. - assert_eq!(websocket_attempts, 2); + // The startup prewarm request sees 426 and immediately switches the session to HTTP fallback, + // so the first turn goes straight to HTTP with no additional websocket connect attempt. + assert_eq!(websocket_attempts, 1); assert_eq!(http_attempts, 1); assert_eq!(response_mock.requests().len(), 1); From c4bd0aa3b914f0e7e3f09990363521fb60d67706 Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Tue, 3 Mar 2026 11:17:06 -0800 Subject: [PATCH 336/385] app-server: source /feedback logs from sqlite at trace level (#12969) ## Summary - write app-server SQLite logs at TRACE level when SQLite is enabled - source app-server `/feedback` log attachments from SQLite for the requested thread when available - flush buffered SQLite log writes before `/feedback` queries them so newly emitted events are not lost behind the async inserter - include same-process threadless SQLite rows in those `/feedback` logs so the attachment matches the process-wide feedback buffer more closely - keep the existing in-memory ring buffer fallback unchanged, including when the SQLite query returns no rows ## Details - add a byte-bounded `query_feedback_logs` helper in `codex-state` so `/feedback` does not fetch all rows before truncating - scope SQLite feedback logs to the requested thread plus threadless rows from the same `process_uuid` - format exported SQLite feedback lines with the log level prefix to better match the in-memory feedback formatter - add an explicit `LogDbLayer::flush()` control path and await it in app-server before querying SQLite for feedback logs - pass optional SQLite log bytes through `codex-feedback` as the `codex-logs.log` attachment override - leave TUI behavior unchanged apart from the updated `upload_feedback` call signature - add regression coverage for: - newest-within-budget ordering - excluding oversized newest rows - including same-process threadless rows - keeping the newest suffix across mixed thread and threadless rows - matching the feedback formatter shape aside from span prefixes - falling back to the in-memory snapshot when SQLite returns no logs - flushing buffered SQLite rows before querying ## Follow-up - SQLite feedback exports still do not reproduce span prefixes like `feedback-thread{thread_id=...}:`; there is a `TODO(ccunningham)` in `codex-rs/state/src/log_db.rs` for that follow-up. ## Testing - `cd codex-rs && cargo test -p codex-state` - `cd codex-rs && cargo test -p codex-app-server` - `cd codex-rs && just fmt` --- codex-rs/app-server/Cargo.toml | 1 + .../app-server/src/codex_message_processor.rs | 30 ++ codex-rs/app-server/src/lib.rs | 21 + codex-rs/app-server/src/message_processor.rs | 4 + codex-rs/feedback/src/lib.rs | 3 +- codex-rs/state/src/log_db.rs | 187 ++++++++- codex-rs/state/src/runtime/logs.rs | 391 ++++++++++++++++++ codex-rs/tui/src/bottom_pane/feedback_view.rs | 1 + 8 files changed, 631 insertions(+), 7 deletions(-) diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 8a4ec05fd3..3efc7140af 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -32,6 +32,7 @@ codex-protocol = { workspace = true } codex-app-server-protocol = { workspace = true } codex-feedback = { workspace = true } codex-rmcp-client = { workspace = true } +codex-state = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-json-to-toml = { workspace = true } chrono = { workspace = true } diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 3c1c29ecab..ca9eb374c6 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -274,6 +274,7 @@ use codex_protocol::protocol::USER_MESSAGE_BEGIN; use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use codex_protocol::user_input::UserInput as CoreInputItem; use codex_rmcp_client::perform_oauth_login_return_url; +use codex_state::log_db::LogDbLayer; use codex_utils_json_to_toml::json_to_toml; use std::collections::HashMap; use std::collections::HashSet; @@ -383,6 +384,7 @@ pub(crate) struct CodexMessageProcessor { pending_fuzzy_searches: Arc>>>, fuzzy_search_sessions: Arc>>, feedback: CodexFeedback, + log_db: Option, } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] @@ -417,6 +419,7 @@ pub(crate) struct CodexMessageProcessorArgs { pub(crate) cli_overrides: Vec<(String, TomlValue)>, pub(crate) cloud_requirements: Arc>, pub(crate) feedback: CodexFeedback, + pub(crate) log_db: Option, } impl CodexMessageProcessor { @@ -461,6 +464,7 @@ impl CodexMessageProcessor { cli_overrides, cloud_requirements, feedback, + log_db, } = args; Self { auth_manager, @@ -477,6 +481,7 @@ impl CodexMessageProcessor { pending_fuzzy_searches: Arc::new(Mutex::new(HashMap::new())), fuzzy_search_sessions: Arc::new(Mutex::new(HashMap::new())), feedback, + log_db, } } @@ -6944,6 +6949,30 @@ impl CodexMessageProcessor { let snapshot = self.feedback.snapshot(conversation_id); let thread_id = snapshot.thread_id.clone(); + let sqlite_feedback_logs = if include_logs { + if let Some(log_db) = self.log_db.as_ref() { + log_db.flush().await; + } + let state_db_ctx = get_state_db(&self.config, None).await; + match (state_db_ctx.as_ref(), conversation_id) { + (Some(state_db_ctx), Some(conversation_id)) => { + let thread_id_text = conversation_id.to_string(); + match state_db_ctx.query_feedback_logs(&thread_id_text).await { + Ok(logs) if logs.is_empty() => None, + Ok(logs) => Some(logs), + Err(err) => { + warn!( + "failed to query feedback logs from sqlite for thread_id={thread_id_text}: {err}" + ); + None + } + } + } + _ => None, + } + } else { + None + }; let validated_rollout_path = if include_logs { match conversation_id { @@ -6967,6 +6996,7 @@ impl CodexMessageProcessor { include_logs, &attachment_paths, Some(session_source), + sqlite_feedback_logs, ) }) .await; diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index a84712ea05..580282d5d3 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -38,16 +38,20 @@ use codex_core::ExecPolicyError; use codex_core::check_execpolicy_for_warnings; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::TextRange as CoreTextRange; +use codex_core::features::Feature; use codex_feedback::CodexFeedback; +use codex_state::log_db; use tokio::sync::mpsc; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use toml::Value as TomlValue; +use tracing::Level; use tracing::error; use tracing::info; use tracing::warn; use tracing_subscriber::EnvFilter; use tracing_subscriber::Layer; +use tracing_subscriber::filter::Targets; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::registry::Registry; use tracing_subscriber::util::SubscriberInitExt; @@ -477,6 +481,21 @@ pub async fn run_main_with_transport( let feedback_layer = feedback.logger_layer(); let feedback_metadata_layer = feedback.metadata_layer(); + let log_db = if config.features.enabled(Feature::Sqlite) { + codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.model_provider_id.clone(), + None, + ) + .await + .ok() + .map(log_db::start) + } else { + None + }; + let log_db_layer = log_db + .clone() + .map(|layer| layer.with_filter(Targets::new().with_default(Level::TRACE))); let otel_logger_layer = otel.as_ref().and_then(|o| o.logger_layer()); let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); @@ -484,6 +503,7 @@ pub async fn run_main_with_transport( .with(stderr_fmt) .with(feedback_layer) .with(feedback_metadata_layer) + .with(log_db_layer) .with(otel_logger_layer) .with(otel_tracing_layer) .try_init(); @@ -562,6 +582,7 @@ pub async fn run_main_with_transport( loader_overrides, cloud_requirements: cloud_requirements.clone(), feedback: feedback.clone(), + log_db, config_warnings, }); let mut thread_created_rx = processor.thread_created_receiver(); diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 48f2f69e87..f56e12467f 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -54,6 +54,7 @@ use codex_core::models_manager::collaboration_mode_presets::CollaborationModesCo use codex_feedback::CodexFeedback; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; +use codex_state::log_db::LogDbLayer; use futures::FutureExt; use tokio::sync::broadcast; use tokio::sync::watch; @@ -154,6 +155,7 @@ pub(crate) struct MessageProcessorArgs { pub(crate) loader_overrides: LoaderOverrides, pub(crate) cloud_requirements: CloudRequirementsLoader, pub(crate) feedback: CodexFeedback, + pub(crate) log_db: Option, pub(crate) config_warnings: Vec, } @@ -169,6 +171,7 @@ impl MessageProcessor { loader_overrides, cloud_requirements, feedback, + log_db, config_warnings, } = args; let auth_manager = AuthManager::shared( @@ -201,6 +204,7 @@ impl MessageProcessor { cli_overrides: cli_overrides.clone(), cloud_requirements: cloud_requirements.clone(), feedback, + log_db, }); let config_api = ConfigApi::new( config.codex_home.clone(), diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index a4fe6cc185..ee8e98c39e 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -226,6 +226,7 @@ impl CodexLogSnapshot { include_logs: bool, extra_log_files: &[PathBuf], session_source: Option, + logs_override: Option>, ) -> Result<()> { use std::collections::BTreeMap; use std::fs; @@ -310,7 +311,7 @@ impl CodexLogSnapshot { if include_logs { envelope.add_item(EnvelopeItem::Attachment(Attachment { - buffer: self.bytes.clone(), + buffer: logs_override.unwrap_or_else(|| self.bytes.clone()), filename: String::from("codex-logs.log"), content_type: Some("text/plain".to_string()), ty: None, diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index 64deeef2ad..e646828bda 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -26,6 +26,7 @@ use std::time::SystemTime; use std::time::UNIX_EPOCH; use tokio::sync::mpsc; +use tokio::sync::oneshot; use tracing::Event; use tracing::field::Field; use tracing::field::Visit; @@ -45,7 +46,7 @@ const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(250); const LOG_RETENTION_DAYS: i64 = 90; pub struct LogDbLayer { - sender: mpsc::Sender, + sender: mpsc::Sender, process_uuid: String, } @@ -61,6 +62,24 @@ pub fn start(state_db: std::sync::Arc) -> LogDbLayer { } } +impl Clone for LogDbLayer { + fn clone(&self) -> Self { + Self { + sender: self.sender.clone(), + process_uuid: self.process_uuid.clone(), + } + } +} + +impl LogDbLayer { + pub async fn flush(&self) { + let (tx, rx) = oneshot::channel(); + if self.sender.send(LogDbCommand::Flush(tx)).await.is_ok() { + let _ = rx.await; + } + } +} + impl Layer for LogDbLayer where S: tracing::Subscriber + for<'a> LookupSpan<'a>, @@ -131,10 +150,15 @@ where line: metadata.line().map(|line| line as i64), }; - let _ = self.sender.try_send(entry); + let _ = self.sender.try_send(LogDbCommand::Entry(entry)); } } +enum LogDbCommand { + Entry(LogEntry), + Flush(oneshot::Sender<()>), +} + #[derive(Clone, Debug, Default)] struct SpanLogContext { thread_id: Option, @@ -215,20 +239,24 @@ fn current_process_log_uuid() -> &'static str { async fn run_inserter( state_db: std::sync::Arc, - mut receiver: mpsc::Receiver, + mut receiver: mpsc::Receiver, ) { let mut buffer = Vec::with_capacity(LOG_BATCH_SIZE); let mut ticker = tokio::time::interval(LOG_FLUSH_INTERVAL); loop { tokio::select! { - maybe_entry = receiver.recv() => { - match maybe_entry { - Some(entry) => { + maybe_command = receiver.recv() => { + match maybe_command { + Some(LogDbCommand::Entry(entry)) => { buffer.push(entry); if buffer.len() >= LOG_BATCH_SIZE { flush(&state_db, &mut buffer).await; } } + Some(LogDbCommand::Flush(reply)) => { + flush(&state_db, &mut buffer).await; + let _ = reply.send(()); + } None => { flush(&state_db, &mut buffer).await; break; @@ -304,3 +332,150 @@ impl Visit for MessageVisitor { self.record_field(field, format!("{value:?}")); } } + +#[cfg(test)] +mod tests { + use std::io; + use std::sync::Arc; + use std::sync::Mutex; + use std::time::Duration; + + use tokio::time::Instant; + use tracing_subscriber::filter::Targets; + use tracing_subscriber::fmt::writer::MakeWriter; + use tracing_subscriber::layer::SubscriberExt; + use tracing_subscriber::util::SubscriberInitExt; + + use super::*; + + #[derive(Clone, Default)] + struct SharedWriter { + bytes: Arc>>, + } + + impl SharedWriter { + fn snapshot(&self) -> String { + String::from_utf8(self.bytes.lock().expect("writer mutex poisoned").clone()) + .expect("valid utf-8") + } + } + + struct SharedWriterGuard { + bytes: Arc>>, + } + + impl<'a> MakeWriter<'a> for SharedWriter { + type Writer = SharedWriterGuard; + + fn make_writer(&'a self) -> Self::Writer { + SharedWriterGuard { + bytes: Arc::clone(&self.bytes), + } + } + } + + impl io::Write for SharedWriterGuard { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.bytes + .lock() + .expect("writer mutex poisoned") + .extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + #[tokio::test] + async fn sqlite_feedback_logs_match_feedback_formatter_shape() { + let codex_home = + std::env::temp_dir().join(format!("codex-state-log-db-{}", Uuid::new_v4())); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let writer = SharedWriter::default(); + + let subscriber = tracing_subscriber::registry() + .with( + tracing_subscriber::fmt::layer() + .with_writer(writer.clone()) + .without_time() + .with_ansi(false) + .with_target(false) + .with_filter(Targets::new().with_default(tracing::Level::TRACE)), + ) + .with( + start(runtime.clone()) + .with_filter(Targets::new().with_default(tracing::Level::TRACE)), + ); + let guard = subscriber.set_default(); + + tracing::trace!("threadless-before"); + tracing::info_span!("feedback-thread", thread_id = "thread-1").in_scope(|| { + tracing::info!("thread-scoped"); + }); + tracing::debug!("threadless-after"); + + drop(guard); + + // TODO(ccunningham): Store enough span metadata in SQLite to reproduce span + // prefixes like `feedback-thread{thread_id="thread-1"}:` in feedback exports. + let feedback_logs = writer + .snapshot() + .replace("feedback-thread{thread_id=\"thread-1\"}: ", ""); + let deadline = Instant::now() + Duration::from_secs(2); + loop { + let sqlite_logs = String::from_utf8( + runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"), + ) + .expect("valid utf-8"); + if sqlite_logs == feedback_logs { + break; + } + assert!( + Instant::now() < deadline, + "sqlite feedback logs did not match feedback formatter output before timeout\nsqlite:\n{sqlite_logs}\nfeedback:\n{feedback_logs}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn flush_persists_logs_for_query() { + let codex_home = + std::env::temp_dir().join(format!("codex-state-log-db-{}", Uuid::new_v4())); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let layer = start(runtime.clone()); + + let guard = tracing_subscriber::registry() + .with( + layer + .clone() + .with_filter(Targets::new().with_default(tracing::Level::TRACE)), + ) + .set_default(); + + tracing::info!("buffered-log"); + + layer.flush().await; + drop(guard); + + let after_flush = runtime + .query_logs(&crate::LogQuery::default()) + .await + .expect("query logs after flush"); + assert_eq!(after_flush.len(), 1); + assert_eq!(after_flush[0].message.as_deref(), Some("buffered-log")); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } +} diff --git a/codex-rs/state/src/runtime/logs.rs b/codex-rs/state/src/runtime/logs.rs index 762f68f1a9..2ee8940afd 100644 --- a/codex-rs/state/src/runtime/logs.rs +++ b/codex-rs/state/src/runtime/logs.rs @@ -285,6 +285,67 @@ WHERE id IN ( Ok(rows) } + /// Query per-thread feedback logs, capped to the per-thread SQLite retention budget. + pub async fn query_feedback_logs(&self, thread_id: &str) -> anyhow::Result> { + let max_bytes = LOG_PARTITION_SIZE_LIMIT_BYTES; + let lines = sqlx::query_scalar::<_, String>( + r#" +WITH latest_process AS ( + SELECT process_uuid + FROM logs + WHERE thread_id = ? AND process_uuid IS NOT NULL + ORDER BY ts DESC, ts_nanos DESC, id DESC + LIMIT 1 +), +feedback_logs AS ( + SELECT + printf('%5s %s', level, message) || CASE + WHEN substr(message, -1, 1) = char(10) THEN '' + ELSE char(10) + END AS line, + length(CAST( + printf('%5s %s', level, message) || CASE + WHEN substr(message, -1, 1) = char(10) THEN '' + ELSE char(10) + END AS BLOB + )) AS line_bytes, + ts, + ts_nanos, + id + FROM logs + WHERE message IS NOT NULL AND ( + thread_id = ? + OR ( + thread_id IS NULL + AND process_uuid IN (SELECT process_uuid FROM latest_process) + ) + ) +) +SELECT line +FROM ( + SELECT + line, + ts, + ts_nanos, + id, + SUM(line_bytes) OVER ( + ORDER BY ts DESC, ts_nanos DESC, id DESC + ) AS cumulative_bytes + FROM feedback_logs +) +WHERE cumulative_bytes <= ? +ORDER BY ts ASC, ts_nanos ASC, id ASC +"#, + ) + .bind(thread_id) + .bind(thread_id) + .bind(max_bytes) + .fetch_all(self.pool.as_ref()) + .await?; + + Ok(lines.concat().into_bytes()) + } + /// Return the max log id matching optional filters. pub async fn max_log_id(&self, query: &LogQuery) -> anyhow::Result { let mut builder = @@ -712,4 +773,334 @@ mod tests { let _ = tokio::fs::remove_dir_all(codex_home).await; } + + #[tokio::test] + async fn query_feedback_logs_returns_newest_lines_within_limit_in_order() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("alpha".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("bravo".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("charlie".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + + assert_eq!( + String::from_utf8(bytes).expect("valid utf-8"), + " INFO alpha\n INFO bravo\n INFO charlie\n" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_excludes_oversized_newest_row() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let eleven_mebibytes = "z".repeat(11 * 1024 * 1024); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("small".to_string()), + thread_id: Some("thread-oversized".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(eleven_mebibytes), + thread_id: Some("thread-oversized".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-oversized") + .await + .expect("query feedback logs"); + + assert_eq!(bytes, Vec::::new()); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_includes_threadless_rows_from_same_process() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("threadless-before".to_string()), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("thread-scoped".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("threadless-after".to_string()), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 4, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("other-process-threadless".to_string()), + thread_id: None, + process_uuid: Some("proc-2".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + + assert_eq!( + String::from_utf8(bytes).expect("valid utf-8"), + " INFO threadless-before\n INFO thread-scoped\n INFO threadless-after\n" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_excludes_threadless_rows_from_prior_processes() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("old-process-threadless".to_string()), + thread_id: None, + process_uuid: Some("proc-old".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("old-process-thread".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-old".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("new-process-thread".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-new".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 4, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("new-process-threadless".to_string()), + thread_id: None, + process_uuid: Some("proc-new".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + + assert_eq!( + String::from_utf8(bytes).expect("valid utf-8"), + " INFO old-process-thread\n INFO new-process-thread\n INFO new-process-threadless\n" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_keeps_newest_suffix_across_thread_and_threadless_logs() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let thread_marker = "thread-scoped-oldest"; + let threadless_older_marker = "threadless-older"; + let threadless_newer_marker = "threadless-newer"; + let five_mebibytes = format!("{threadless_older_marker} {}", "a".repeat(5 * 1024 * 1024)); + let four_and_half_mebibytes = format!( + "{threadless_newer_marker} {}", + "b".repeat((9 * 1024 * 1024) / 2) + ); + let one_mebibyte = format!("{thread_marker} {}", "c".repeat(1024 * 1024)); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(one_mebibyte.clone()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(five_mebibytes), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(four_and_half_mebibytes), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + let logs = String::from_utf8(bytes).expect("valid utf-8"); + + assert!(!logs.contains(thread_marker)); + assert!(logs.contains(threadless_older_marker)); + assert!(logs.contains(threadless_newer_marker)); + assert_eq!(logs.matches('\n').count(), 2); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } } diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index 4144c87f97..33368faa45 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -102,6 +102,7 @@ impl FeedbackNoteView { self.include_logs, &log_file_paths, Some(SessionSource::Cli), + None, ); match result { From 39f00f2a06d9c8a5b5fb14998d8880ceb489f9ff Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Tue, 3 Mar 2026 11:44:54 -0800 Subject: [PATCH 337/385] chore: rm --all-features flag from rust-analyzer (#13381) follows up on #12429; rm `--all-features` from flags used with `rust-analyzer` on save to prevent disk space bloat under `target/`. --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 5adec04a83..1e857367cb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,7 @@ { "rust-analyzer.checkOnSave": true, "rust-analyzer.check.command": "clippy", - "rust-analyzer.check.extraArgs": ["--all-features", "--tests"], + "rust-analyzer.check.extraArgs": ["--tests"], "rust-analyzer.rustfmt.extraArgs": ["--config", "imports_granularity=Item"], "rust-analyzer.cargo.targetDir": "${workspaceFolder}/codex-rs/target/rust-analyzer", "[rust]": { From c2d008aca59697aff3a65949e7ffed06bd715dea Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Tue, 3 Mar 2026 11:45:34 -0800 Subject: [PATCH 338/385] Collapse parsed command summaries when any stage is unknown (#13043) ## Summary - collapse parsed command output to a single `Unknown` whenever the normal parse includes any unknown entry - preserve the existing parsing flow and existing `cd` handling, including the current `cd && ...` collapse behavior - trim redundant tests and add focused coverage for collapse-on-unknown cases ## Testing - `cargo test -p codex-shell-command` --- codex-rs/shell-command/src/parse_command.rs | 163 +++++++------------- 1 file changed, 53 insertions(+), 110 deletions(-) diff --git a/codex-rs/shell-command/src/parse_command.rs b/codex-rs/shell-command/src/parse_command.rs index 71018a53d1..1c8ac99485 100644 --- a/codex-rs/shell-command/src/parse_command.rs +++ b/codex-rs/shell-command/src/parse_command.rs @@ -37,7 +37,26 @@ pub fn parse_command(command: &[String]) -> Vec { } deduped.push(cmd); } - deduped + if deduped + .iter() + .any(|cmd| matches!(cmd, ParsedCommand::Unknown { .. })) + { + vec![single_unknown_for_command(command)] + } else { + deduped + } +} + +fn single_unknown_for_command(command: &[String]) -> ParsedCommand { + if let Some((_, shell_command)) = extract_shell_command(command) { + ParsedCommand::Unknown { + cmd: shell_command.to_string(), + } + } else { + ParsedCommand::Unknown { + cmd: shlex_join(command), + } + } } #[cfg(test)] @@ -119,7 +138,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Unknown { - cmd: "git status".to_string(), + cmd: inner.to_string(), }], ); } @@ -141,24 +160,9 @@ mod tests { "rg --version && node -v && pnpm -v && rg --files | wc -l && rg --files | head -n 40"; assert_parsed( &vec_str(&["bash", "-lc", inner]), - vec![ - // Expect commands in left-to-right execution order - ParsedCommand::Search { - cmd: "rg --version".to_string(), - query: None, - path: None, - }, - ParsedCommand::Unknown { - cmd: "node -v".to_string(), - }, - ParsedCommand::Unknown { - cmd: "pnpm -v".to_string(), - }, - ParsedCommand::ListFiles { - cmd: "rg --files".to_string(), - path: None, - }, - ], + vec![ParsedCommand::Unknown { + cmd: inner.to_string(), + }], ); } @@ -218,16 +222,33 @@ mod tests { let inner = r#"rg -l QkBindingController presentation/src/main/java | xargs perl -pi -e 's/QkBindingController/QkController/g'"#; assert_parsed( &vec_str(&["bash", "-lc", inner]), - vec![ - ParsedCommand::Search { - cmd: "rg -l QkBindingController presentation/src/main/java".to_string(), - query: Some("QkBindingController".to_string()), - path: Some("java".to_string()), - }, - ParsedCommand::Unknown { - cmd: "xargs perl -pi -e s/QkBindingController/QkController/g".to_string(), - }, - ], + vec![ParsedCommand::Unknown { + cmd: inner.to_string(), + }], + ); + } + + #[test] + fn collapses_plain_pipeline_when_any_stage_is_unknown() { + let command = shlex_split_safe( + "rg -l QkBindingController presentation/src/main/java | xargs perl -pi -e 's/QkBindingController/QkController/g'", + ); + assert_parsed( + &command, + vec![ParsedCommand::Unknown { + cmd: shlex_join(&command), + }], + ); + } + + #[test] + fn collapses_pipeline_with_helper_when_later_stage_is_unknown() { + let command = shlex_split_safe("rg --files | nl -ba | foo"); + assert_parsed( + &command, + vec![ParsedCommand::Unknown { + cmd: shlex_join(&command), + }], ); } @@ -395,7 +416,7 @@ mod tests { assert_parsed( &shlex_split_safe("bash -lc 'cd foo && bar'"), vec![ParsedCommand::Unknown { - cmd: "bar".to_string(), + cmd: "cd foo && bar".to_string(), }], ); } @@ -922,85 +943,6 @@ mod tests { ); } - #[test] - fn trim_on_semicolon() { - assert_parsed( - &shlex_split_safe("rg foo ; echo done"), - vec![ - ParsedCommand::Search { - cmd: "rg foo".to_string(), - query: Some("foo".to_string()), - path: None, - }, - ParsedCommand::Unknown { - cmd: "echo done".to_string(), - }, - ], - ); - } - - #[test] - fn split_on_or_connector() { - // Ensure we split commands on the logical OR operator as well. - assert_parsed( - &shlex_split_safe("rg foo || echo done"), - vec![ - ParsedCommand::Search { - cmd: "rg foo".to_string(), - query: Some("foo".to_string()), - path: None, - }, - ParsedCommand::Unknown { - cmd: "echo done".to_string(), - }, - ], - ); - } - - #[test] - fn parses_mixed_sequence_with_pipes_semicolons_and_or() { - // Provided long command sequence combining sequencing, pipelines, and ORs. - let inner = "pwd; ls -la; rg --files -g '!target' | wc -l; rg -n '^\\[workspace\\]' -n Cargo.toml || true; rg -n '^\\[package\\]' -n */Cargo.toml || true; cargo --version; rustc --version; cargo clippy --workspace --all-targets --all-features -q"; - let args = vec_str(&["bash", "-lc", inner]); - - let expected = vec![ - ParsedCommand::Unknown { - cmd: "pwd".to_string(), - }, - ParsedCommand::ListFiles { - cmd: shlex_join(&shlex_split_safe("ls -la")), - path: None, - }, - ParsedCommand::ListFiles { - cmd: shlex_join(&shlex_split_safe("rg --files -g '!target'")), - path: None, - }, - ParsedCommand::Search { - cmd: shlex_join(&shlex_split_safe("rg -n '^\\[workspace\\]' -n Cargo.toml")), - query: Some("^\\[workspace\\]".to_string()), - path: Some("Cargo.toml".to_string()), - }, - ParsedCommand::Search { - cmd: shlex_join(&shlex_split_safe("rg -n '^\\[package\\]' -n */Cargo.toml")), - query: Some("^\\[package\\]".to_string()), - path: Some("Cargo.toml".to_string()), - }, - ParsedCommand::Unknown { - cmd: shlex_join(&shlex_split_safe("cargo --version")), - }, - ParsedCommand::Unknown { - cmd: shlex_join(&shlex_split_safe("rustc --version")), - }, - ParsedCommand::Unknown { - cmd: shlex_join(&shlex_split_safe( - "cargo clippy --workspace --all-targets --all-features -q", - )), - }, - ]; - - assert_parsed(&args, expected); - } - #[test] fn strips_true_in_sequence() { // `true` should be dropped from parsed sequences @@ -1926,6 +1868,7 @@ fn parse_shell_lc_commands(original: &[String]) -> Option> { }; commands.push(parsed); } + if commands.len() > 1 { commands.retain(|pc| !matches!(pc, ParsedCommand::Unknown { cmd } if cmd == "true")); // Apply the same simplifications used for non-bash parsing, e.g., drop leading `cd`. From 8afe2127dcc022bf8fdc0d6a80f957a50652c113 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 3 Mar 2026 12:30:37 -0800 Subject: [PATCH 339/385] Revert "realtime prompt changes" (#13385) Reverts openai/codex#13376 --- codex-rs/protocol/src/prompts/realtime/realtime_end.md | 4 +++- codex-rs/protocol/src/prompts/realtime/realtime_start.md | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_end.md b/codex-rs/protocol/src/prompts/realtime/realtime_end.md index abec16da03..07ccae5286 100644 --- a/codex-rs/protocol/src/prompts/realtime/realtime_end.md +++ b/codex-rs/protocol/src/prompts/realtime/realtime_end.md @@ -1,3 +1,5 @@ Realtime conversation ended. -Subsequent user input will return to typed text rather than transcript-style text. Do not assume recognition errors or missing punctuation once realtime has ended. Resume normal chat behavior. +You are still operating behind an intermediary rather than speaking to the user directly. Use the conversation transcript and current context to decide whether backend help is actually needed, and avoid verbose responses that only add latency. + +Subsequent user input may return to typed text rather than transcript-style text. Do not assume recognition errors or missing punctuation once realtime has ended. Resume normal chat behavior. diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_start.md b/codex-rs/protocol/src/prompts/realtime/realtime_start.md index 3159a2b07f..c7d363eff7 100644 --- a/codex-rs/protocol/src/prompts/realtime/realtime_start.md +++ b/codex-rs/protocol/src/prompts/realtime/realtime_start.md @@ -6,4 +6,5 @@ When invoked, you receive the latest conversation transcript and any relevant mo When user text is routed from realtime, treat it as a transcript. It may be unpunctuated or contain recognition errors. -- Keep responses concise and action-oriented. Your updates should help the intermediary respond to the user. +- Ask brief clarification questions when needed. +- Keep responses concise and action-oriented. From 72d368e03aab573ff03785720da28e05337fd9c8 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 3 Mar 2026 12:48:16 -0800 Subject: [PATCH 340/385] fix (#13389) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. --- .../codex_app_server_protocol.v2.schemas.json | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 0f8e83d572..1bd5733364 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -2499,6 +2499,16 @@ } ] }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "tools": { "anyOf": [ { @@ -3839,6 +3849,16 @@ ], "description": "How to sandbox commands executed in the system" }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "session_id": { "$ref": "#/definitions/ThreadId" }, @@ -8218,6 +8238,16 @@ } ] }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "web_search": { "anyOf": [ { @@ -10647,6 +10677,12 @@ "title": "ServerRequestResolvedNotification", "type": "object" }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "SessionNetworkProxyRuntime": { "properties": { "admin_addr": { @@ -11489,6 +11525,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } @@ -11527,6 +11580,16 @@ "sandbox": { "$ref": "#/definitions/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/Thread" } @@ -12472,6 +12535,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } @@ -12510,6 +12590,16 @@ "sandbox": { "$ref": "#/definitions/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/Thread" } @@ -12688,6 +12778,23 @@ "string", "null" ] + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] } }, "title": "ThreadStartParams", @@ -12721,6 +12828,16 @@ "sandbox": { "$ref": "#/definitions/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/Thread" } @@ -13526,6 +13643,24 @@ ], "description": "Override the sandbox policy for this turn and subsequent turns." }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ], + "description": "Override the service tier for this turn and subsequent turns." + }, "summary": { "anyOf": [ { From 167158f93ce96cc554ab0a75aaed97f743ecb1ed Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 3 Mar 2026 13:18:25 -0800 Subject: [PATCH 341/385] chore(app-server): delete v1 RPC methods and notifications (#13375) ## Summary This removes the old app-server v1 methods and notifications we no longer need, while keeping the small set the main codex app client still depends on for now. The remaining legacy surface is: - `initialize` - `getConversationSummary` - `getAuthStatus` - `gitDiffToRemote` - `fuzzyFileSearch` - `fuzzyFileSearch/sessionStart` - `fuzzyFileSearch/sessionUpdate` - `fuzzyFileSearch/sessionStop` And the raw `codex/event/*` notifications emitted from core. These notifications will be removed in a followup PR. ## What changed - removed deprecated v1 request variants from the protocol and app-server dispatcher - removed deprecated typed notifications: `authStatusChange`, `loginChatGptComplete`, and `sessionConfigured` - updated the app-server test client to use v2 flows instead of deleted v1 flows - deleted legacy-only app-server test suites and added focused coverage for `getConversationSummary` - regenerated app-server schema fixtures and updated the MCP interface docs to match the remaining compatibility surface ## Testing - `just write-app-server-schema` - `cargo test -p codex-app-server-protocol` - `cargo test -p codex-app-server` --- codex-rs/Cargo.lock | 2 - .../AddConversationListenerParams.ts | 6 - .../AddConversationSubscriptionResponse.ts | 5 - .../schema/typescript/AgentMessageContent.ts | 5 - .../AgentMessageContentDeltaEvent.ts | 5 - .../typescript/AgentMessageDeltaEvent.ts | 5 - .../schema/typescript/AgentMessageEvent.ts | 6 - .../schema/typescript/AgentMessageItem.ts | 21 - .../typescript/AgentReasoningDeltaEvent.ts | 5 - .../schema/typescript/AgentReasoningEvent.ts | 5 - .../AgentReasoningRawContentDeltaEvent.ts | 5 - .../AgentReasoningRawContentEvent.ts | 5 - .../AgentReasoningSectionBreakEvent.ts | 5 - .../schema/typescript/AgentStatus.ts | 8 - .../ApplyPatchApprovalRequestEvent.ts | 23 - .../typescript/ArchiveConversationParams.ts | 6 - .../typescript/ArchiveConversationResponse.ts | 5 - .../schema/typescript/AskForApproval.ts | 10 - .../AuthStatusChangeNotification.ts | 9 - .../schema/typescript/BackgroundEventEvent.ts | 5 - .../schema/typescript/ByteRange.ts | 13 - .../schema/typescript/CallToolResult.ts | 9 - .../typescript/CancelLoginChatGptParams.ts | 5 - .../typescript/CancelLoginChatGptResponse.ts | 5 - .../schema/typescript/ClientRequest.ts | 16 +- .../schema/typescript/CodexErrorInfo.ts | 8 - .../CollabAgentInteractionBeginEvent.ts | 23 - .../CollabAgentInteractionEndEvent.ts | 36 - .../schema/typescript/CollabAgentRef.ts | 18 - .../typescript/CollabAgentSpawnBeginEvent.ts | 19 - .../typescript/CollabAgentSpawnEndEvent.ts | 36 - .../typescript/CollabAgentStatusEntry.ts | 23 - .../typescript/CollabCloseBeginEvent.ts | 18 - .../schema/typescript/CollabCloseEndEvent.ts | 32 - .../typescript/CollabResumeBeginEvent.ts | 26 - .../schema/typescript/CollabResumeEndEvent.ts | 32 - .../typescript/CollabWaitingBeginEvent.ts | 23 - .../typescript/CollabWaitingEndEvent.ts | 24 - .../typescript/ContextCompactedEvent.ts | 5 - .../typescript/ContextCompactionItem.ts | 5 - .../schema/typescript/CreditsSnapshot.ts | 5 - .../schema/typescript/CustomPrompt.ts | 5 - .../typescript/DeprecationNoticeEvent.ts | 13 - .../DynamicToolCallOutputContentItem.ts | 5 - .../typescript/DynamicToolCallRequest.ts | 6 - .../DynamicToolCallResponseEvent.ts | 39 - .../typescript/ElicitationRequestEvent.ts | 5 - .../schema/typescript/ErrorEvent.ts | 6 - .../schema/typescript/EventMsg.ts | 82 - .../typescript/ExecApprovalRequestEvent.ts | 62 - .../typescript/ExecCommandBeginEvent.ts | 35 - .../schema/typescript/ExecCommandEndEvent.ts | 64 - .../typescript/ExecCommandOutputDeltaEvent.ts | 18 - .../schema/typescript/ExecCommandSource.ts | 5 - .../schema/typescript/ExecCommandStatus.ts | 5 - .../typescript/ExecOneOffCommandParams.ts | 6 - .../typescript/ExecOneOffCommandResponse.ts | 5 - .../schema/typescript/ExecOutputStream.ts | 5 - .../typescript/ExitedReviewModeEvent.ts | 6 - .../typescript/FileSystemPermissions.ts | 6 - .../typescript/ForkConversationParams.ts | 7 - .../typescript/ForkConversationResponse.ts | 7 - .../GetHistoryEntryResponseEvent.ts | 10 - .../schema/typescript/GetUserAgentResponse.ts | 5 - .../typescript/GetUserSavedConfigResponse.ts | 6 - .../schema/typescript/HistoryEntry.ts | 5 - .../schema/typescript/InputItem.ts | 10 - .../typescript/InterruptConversationParams.ts | 6 - .../InterruptConversationResponse.ts | 6 - .../schema/typescript/ItemCompletedEvent.ts | 7 - .../schema/typescript/ItemStartedEvent.ts | 7 - .../typescript/ListConversationsParams.ts | 5 - .../typescript/ListConversationsResponse.ts | 6 - .../ListCustomPromptsResponseEvent.ts | 9 - .../ListRemoteSkillsResponseEvent.ts | 9 - .../typescript/ListSkillsResponseEvent.ts | 9 - .../schema/typescript/LoginApiKeyParams.ts | 5 - .../schema/typescript/LoginApiKeyResponse.ts | 5 - .../LoginChatGptCompleteNotification.ts | 8 - .../schema/typescript/LoginChatGptResponse.ts | 5 - .../typescript/LogoutChatGptResponse.ts | 5 - .../schema/typescript/MacOsPermissions.ts | 7 - .../schema/typescript/McpAuthStatus.ts | 5 - .../schema/typescript/McpInvocation.ts | 18 - .../typescript/McpListToolsResponseEvent.ts | 25 - .../typescript/McpStartupCompleteEvent.ts | 6 - .../schema/typescript/McpStartupFailure.ts | 5 - .../schema/typescript/McpStartupStatus.ts | 5 - .../typescript/McpStartupUpdateEvent.ts | 14 - .../typescript/McpToolCallBeginEvent.ts | 10 - .../schema/typescript/McpToolCallEndEvent.ts | 15 - .../schema/typescript/ModelRerouteEvent.ts | 6 - .../schema/typescript/ModelRerouteReason.ts | 5 - .../schema/typescript/NetworkAccess.ts | 8 - .../typescript/NetworkApprovalContext.ts | 6 - .../typescript/NetworkApprovalProtocol.ts | 5 - .../typescript/NewConversationParams.ts | 8 - .../typescript/NewConversationResponse.ts | 7 - .../schema/typescript/PatchApplyBeginEvent.ts | 23 - .../schema/typescript/PatchApplyEndEvent.ts | 36 - .../schema/typescript/PatchApplyStatus.ts | 5 - .../schema/typescript/PermissionProfile.ts | 7 - .../schema/typescript/PlanDeltaEvent.ts | 5 - .../schema/typescript/PlanItem.ts | 5 - .../schema/typescript/PlanItemArg.ts | 6 - .../schema/typescript/Profile.ts | 9 - .../schema/typescript/RateLimitSnapshot.ts | 8 - .../schema/typescript/RateLimitWindow.ts | 17 - .../schema/typescript/RawResponseItemEvent.ts | 6 - .../schema/typescript/ReadOnlyAccess.ts | 19 - .../schema/typescript/RealtimeAudioFrame.ts | 5 - .../RealtimeConversationClosedEvent.ts | 5 - .../RealtimeConversationRealtimeEvent.ts | 6 - .../RealtimeConversationStartedEvent.ts | 5 - .../schema/typescript/RealtimeEvent.ts | 8 - .../typescript/RealtimeHandoffMessage.ts | 5 - .../typescript/RealtimeHandoffRequested.ts | 6 - .../typescript/ReasoningContentDeltaEvent.ts | 5 - .../schema/typescript/ReasoningItem.ts | 5 - .../ReasoningRawContentDeltaEvent.ts | 5 - .../schema/typescript/RejectConfig.ts | 17 - .../typescript/RemoteSkillDownloadedEvent.ts | 8 - .../schema/typescript/RemoteSkillSummary.ts | 5 - .../RemoveConversationListenerParams.ts | 5 - .../RemoveConversationSubscriptionResponse.ts | 5 - .../typescript/RequestUserInputEvent.ts | 15 - .../typescript/RequestUserInputQuestion.ts | 6 - .../RequestUserInputQuestionOption.ts | 5 - .../typescript/ResumeConversationParams.ts | 8 - .../typescript/ResumeConversationResponse.ts | 7 - .../schema/typescript/ReviewCodeLocation.ts | 9 - .../schema/typescript/ReviewFinding.ts | 9 - .../schema/typescript/ReviewLineRange.ts | 8 - .../schema/typescript/ReviewOutputEvent.ts | 9 - .../schema/typescript/ReviewRequest.ts | 9 - .../schema/typescript/ReviewTarget.ts | 9 - .../schema/typescript/SandboxMode.ts | 5 - .../schema/typescript/SandboxPolicy.ts | 44 - .../schema/typescript/SandboxSettings.ts | 6 - .../typescript/SendUserMessageParams.ts | 7 - .../typescript/SendUserMessageResponse.ts | 5 - .../schema/typescript/SendUserTurnParams.ts | 17 - .../schema/typescript/SendUserTurnResponse.ts | 5 - .../schema/typescript/ServerNotification.ts | 5 +- .../typescript/SessionConfiguredEvent.ts | 58 - .../SessionConfiguredNotification.ts | 9 - .../typescript/SessionNetworkProxyRuntime.ts | 5 - .../typescript/SetDefaultModelParams.ts | 6 - .../typescript/SetDefaultModelResponse.ts | 5 - .../schema/typescript/SkillDependencies.ts | 6 - .../schema/typescript/SkillErrorInfo.ts | 5 - .../schema/typescript/SkillInterface.ts | 5 - .../schema/typescript/SkillMetadata.ts | 12 - .../schema/typescript/SkillScope.ts | 5 - .../schema/typescript/SkillToolDependency.ts | 5 - .../schema/typescript/SkillsListEntry.ts | 7 - .../schema/typescript/StepStatus.ts | 5 - .../schema/typescript/StreamErrorEvent.ts | 12 - .../typescript/TerminalInteractionEvent.ts | 17 - .../schema/typescript/TextElement.ts | 14 - .../typescript/ThreadNameUpdatedEvent.ts | 6 - .../typescript/ThreadRolledBackEvent.ts | 9 - .../schema/typescript/TokenCountEvent.ts | 7 - .../schema/typescript/TokenUsage.ts | 5 - .../schema/typescript/TokenUsageInfo.ts | 6 - .../schema/typescript/Tools.ts | 5 - .../schema/typescript/TurnAbortReason.ts | 5 - .../schema/typescript/TurnAbortedEvent.ts | 6 - .../schema/typescript/TurnCompleteEvent.ts | 5 - .../schema/typescript/TurnDiffEvent.ts | 5 - .../schema/typescript/TurnItem.ts | 11 - .../schema/typescript/TurnStartedEvent.ts | 6 - .../schema/typescript/UndoCompletedEvent.ts | 5 - .../schema/typescript/UndoStartedEvent.ts | 5 - .../schema/typescript/UpdatePlanArgs.ts | 10 - .../schema/typescript/UserInfoResponse.ts | 5 - .../schema/typescript/UserInput.ts | 16 - .../schema/typescript/UserMessageEvent.ts | 22 - .../schema/typescript/UserMessageItem.ts | 6 - .../schema/typescript/UserSavedConfig.ts | 14 - .../typescript/ViewImageToolCallEvent.ts | 13 - .../schema/typescript/WarningEvent.ts | 5 - .../schema/typescript/WebSearchBeginEvent.ts | 5 - .../schema/typescript/WebSearchEndEvent.ts | 6 - .../schema/typescript/WebSearchItem.ts | 6 - .../schema/typescript/index.ts | 182 --- codex-rs/app-server-protocol/src/export.rs | 33 +- .../src/protocol/common.rs | 118 +- .../app-server-protocol/src/protocol/v1.rs | 31 - codex-rs/app-server-test-client/src/lib.rs | 221 +-- codex-rs/app-server/Cargo.toml | 2 - .../app-server/src/codex_message_processor.rs | 1379 +---------------- codex-rs/app-server/src/outgoing_message.rs | 9 +- codex-rs/app-server/src/thread_state.rs | 117 -- .../app-server/tests/common/mcp_process.rs | 163 +- .../app-server/tests/suite/archive_thread.rs | 154 -- codex-rs/app-server/tests/suite/auth.rs | 16 +- .../suite/codex_message_processor_flow.rs | 550 ------- codex-rs/app-server/tests/suite/config.rs | 158 -- .../tests/suite/conversation_summary.rs | 113 ++ .../app-server/tests/suite/create_thread.rs | 142 -- .../app-server/tests/suite/fork_thread.rs | 140 -- codex-rs/app-server/tests/suite/interrupt.rs | 163 -- .../app-server/tests/suite/list_resume.rs | 440 ------ codex-rs/app-server/tests/suite/login.rs | 161 -- codex-rs/app-server/tests/suite/mod.rs | 14 +- .../app-server/tests/suite/output_schema.rs | 372 ----- .../app-server/tests/suite/send_message.rs | 645 -------- .../tests/suite/set_default_model.rs | 64 - codex-rs/app-server/tests/suite/user_agent.rs | 43 - codex-rs/app-server/tests/suite/user_info.rs | 46 - .../app-server/tests/suite/v2/rate_limits.rs | 13 +- .../tests/suite/v2/realtime_conversation.rs | 13 +- codex-rs/docs/codex_mcp_interface.md | 151 +- 214 files changed, 241 insertions(+), 7413 deletions(-) delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AddConversationListenerParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AddConversationSubscriptionResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ArchiveConversationParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ArchiveConversationResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/AuthStatusChangeNotification.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ByteRange.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/EventMsg.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ForkConversationParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ForkConversationResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/GetUserAgentResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/GetUserSavedConfigResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/InputItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/InterruptConversationParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/InterruptConversationResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ListConversationsParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ListConversationsResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/LoginApiKeyParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/LoginApiKeyResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/LoginChatGptCompleteNotification.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/LoginChatGptResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/LogoutChatGptResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/NewConversationParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/NewConversationResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/PlanItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/Profile.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RemoveConversationListenerParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RemoveConversationSubscriptionResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ResumeConversationParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ResumeConversationResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SandboxMode.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SandboxSettings.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SendUserMessageParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SendUserMessageResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SendUserTurnParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SendUserTurnResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SessionConfiguredNotification.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SetDefaultModelParams.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SetDefaultModelResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillScope.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/StepStatus.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TextElement.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/Tools.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UserInfoResponse.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UserInput.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/UserSavedConfig.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts delete mode 100644 codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts delete mode 100644 codex-rs/app-server/tests/suite/archive_thread.rs delete mode 100644 codex-rs/app-server/tests/suite/codex_message_processor_flow.rs delete mode 100644 codex-rs/app-server/tests/suite/config.rs create mode 100644 codex-rs/app-server/tests/suite/conversation_summary.rs delete mode 100644 codex-rs/app-server/tests/suite/create_thread.rs delete mode 100644 codex-rs/app-server/tests/suite/fork_thread.rs delete mode 100644 codex-rs/app-server/tests/suite/interrupt.rs delete mode 100644 codex-rs/app-server/tests/suite/list_resume.rs delete mode 100644 codex-rs/app-server/tests/suite/login.rs delete mode 100644 codex-rs/app-server/tests/suite/output_schema.rs delete mode 100644 codex-rs/app-server/tests/suite/send_message.rs delete mode 100644 codex-rs/app-server/tests/suite/set_default_model.rs delete mode 100644 codex-rs/app-server/tests/suite/user_agent.rs delete mode 100644 codex-rs/app-server/tests/suite/user_info.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 62d2ffae3b..d9ee0f608b 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1434,7 +1434,6 @@ dependencies = [ "codex-chatgpt", "codex-cloud-requirements", "codex-core", - "codex-execpolicy", "codex-feedback", "codex-file-search", "codex-login", @@ -1449,7 +1448,6 @@ dependencies = [ "codex-utils-json-to-toml", "core_test_support", "futures", - "os_info", "owo-colors", "pretty_assertions", "rmcp", diff --git a/codex-rs/app-server-protocol/schema/typescript/AddConversationListenerParams.ts b/codex-rs/app-server-protocol/schema/typescript/AddConversationListenerParams.ts deleted file mode 100644 index 6441bed68a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AddConversationListenerParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type AddConversationListenerParams = { conversationId: ThreadId, experimentalRawEvents: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AddConversationSubscriptionResponse.ts b/codex-rs/app-server-protocol/schema/typescript/AddConversationSubscriptionResponse.ts deleted file mode 100644 index f7e34ef658..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AddConversationSubscriptionResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AddConversationSubscriptionResponse = { subscriptionId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts deleted file mode 100644 index dc2cfb77e3..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentMessageContent = { "type": "Text", text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts deleted file mode 100644 index 1473a4f2bc..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentMessageContentDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts deleted file mode 100644 index 1e12d85fbb..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentMessageDeltaEvent = { delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts deleted file mode 100644 index b32680055f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { MessagePhase } from "./MessagePhase"; - -export type AgentMessageEvent = { message: string, phase: MessagePhase | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts deleted file mode 100644 index ee67a3e23b..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts +++ /dev/null @@ -1,21 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentMessageContent } from "./AgentMessageContent"; -import type { MessagePhase } from "./MessagePhase"; - -/** - * Assistant-authored message payload used in turn-item streams. - * - * `phase` is optional because not all providers/models emit it. Consumers - * should use it when present, but retain legacy completion semantics when it - * is `None`. - */ -export type AgentMessageItem = { id: string, content: Array, -/** - * Optional phase metadata carried through from `ResponseItem::Message`. - * - * This is currently used by TUI rendering to distinguish mid-turn - * commentary from a final answer and avoid status-indicator jitter. - */ -phase?: MessagePhase, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts deleted file mode 100644 index fc2c221937..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentReasoningDeltaEvent = { delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts deleted file mode 100644 index bf0062cd43..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentReasoningEvent = { text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts deleted file mode 100644 index fcfa816f5d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentReasoningRawContentDeltaEvent = { delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts deleted file mode 100644 index 364c278229..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentReasoningRawContentEvent = { text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts deleted file mode 100644 index 604aceed93..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type AgentReasoningSectionBreakEvent = { item_id: string, summary_index: bigint, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts b/codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts deleted file mode 100644 index ddf6789c78..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Agent lifecycle status, derived from emitted events. - */ -export type AgentStatus = "pending_init" | "running" | { "completed": string | null } | { "errored": string } | "shutdown" | "not_found"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts deleted file mode 100644 index 0c53cf50b8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts +++ /dev/null @@ -1,23 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { FileChange } from "./FileChange"; - -export type ApplyPatchApprovalRequestEvent = { -/** - * Responses API call id for the associated patch apply call, if available. - */ -call_id: string, -/** - * Turn ID that this patch belongs to. - * Uses `#[serde(default)]` for backwards compatibility with older senders. - */ -turn_id: string, changes: { [key in string]?: FileChange }, -/** - * Optional explanatory reason (e.g. request for extra write access). - */ -reason: string | null, -/** - * When set, the agent is asking the user to allow writes under this root for the remainder of the session. - */ -grant_root: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationParams.ts deleted file mode 100644 index 61fbcc9fc8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type ArchiveConversationParams = { conversationId: ThreadId, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationResponse.ts deleted file mode 100644 index 24900592b2..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ArchiveConversationResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts b/codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts deleted file mode 100644 index 227eb44e77..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts +++ /dev/null @@ -1,10 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RejectConfig } from "./RejectConfig"; - -/** - * Determines the conditions under which the user is consulted to approve - * running the command proposed by Codex. - */ -export type AskForApproval = "untrusted" | "on-failure" | "on-request" | { "reject": RejectConfig } | "never"; diff --git a/codex-rs/app-server-protocol/schema/typescript/AuthStatusChangeNotification.ts b/codex-rs/app-server-protocol/schema/typescript/AuthStatusChangeNotification.ts deleted file mode 100644 index 17cb442fe0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AuthStatusChangeNotification.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AuthMode } from "./AuthMode"; - -/** - * Deprecated notification. Use AccountUpdatedNotification instead. - */ -export type AuthStatusChangeNotification = { authMethod: AuthMode | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts b/codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts deleted file mode 100644 index 236b1dd888..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type BackgroundEventEvent = { message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ByteRange.ts b/codex-rs/app-server-protocol/schema/typescript/ByteRange.ts deleted file mode 100644 index ab36a79acd..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ByteRange.ts +++ /dev/null @@ -1,13 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ByteRange = { -/** - * Start byte offset (inclusive) within the UTF-8 text buffer. - */ -start: number, -/** - * End byte offset (exclusive) within the UTF-8 text buffer. - */ -end: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts b/codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts deleted file mode 100644 index e7a471d465..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { JsonValue } from "./serde_json/JsonValue"; - -/** - * The server's response to a tool call. - */ -export type CallToolResult = { content: Array, structuredContent?: JsonValue, isError?: boolean, _meta?: JsonValue, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptParams.ts b/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptParams.ts deleted file mode 100644 index dae8e8c784..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type CancelLoginChatGptParams = { loginId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptResponse.ts b/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptResponse.ts deleted file mode 100644 index 004e6f8ea2..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type CancelLoginChatGptResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index 9707644002..f6df83b6e4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -1,26 +1,12 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AddConversationListenerParams } from "./AddConversationListenerParams"; -import type { ArchiveConversationParams } from "./ArchiveConversationParams"; -import type { CancelLoginChatGptParams } from "./CancelLoginChatGptParams"; -import type { ExecOneOffCommandParams } from "./ExecOneOffCommandParams"; -import type { ForkConversationParams } from "./ForkConversationParams"; import type { FuzzyFileSearchParams } from "./FuzzyFileSearchParams"; import type { GetAuthStatusParams } from "./GetAuthStatusParams"; import type { GetConversationSummaryParams } from "./GetConversationSummaryParams"; import type { GitDiffToRemoteParams } from "./GitDiffToRemoteParams"; import type { InitializeParams } from "./InitializeParams"; -import type { InterruptConversationParams } from "./InterruptConversationParams"; -import type { ListConversationsParams } from "./ListConversationsParams"; -import type { LoginApiKeyParams } from "./LoginApiKeyParams"; -import type { NewConversationParams } from "./NewConversationParams"; -import type { RemoveConversationListenerParams } from "./RemoveConversationListenerParams"; import type { RequestId } from "./RequestId"; -import type { ResumeConversationParams } from "./ResumeConversationParams"; -import type { SendUserMessageParams } from "./SendUserMessageParams"; -import type { SendUserTurnParams } from "./SendUserTurnParams"; -import type { SetDefaultModelParams } from "./SetDefaultModelParams"; import type { AppsListParams } from "./v2/AppsListParams"; import type { CancelLoginAccountParams } from "./v2/CancelLoginAccountParams"; import type { CommandExecParams } from "./v2/CommandExecParams"; @@ -61,4 +47,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta /** * Request from the client to the server. */ -export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/remote/list", id: RequestId, params: SkillsRemoteReadParams, } | { "method": "skills/remote/export", id: RequestId, params: SkillsRemoteWriteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "newConversation", id: RequestId, params: NewConversationParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "listConversations", id: RequestId, params: ListConversationsParams, } | { "method": "resumeConversation", id: RequestId, params: ResumeConversationParams, } | { "method": "forkConversation", id: RequestId, params: ForkConversationParams, } | { "method": "archiveConversation", id: RequestId, params: ArchiveConversationParams, } | { "method": "sendUserMessage", id: RequestId, params: SendUserMessageParams, } | { "method": "sendUserTurn", id: RequestId, params: SendUserTurnParams, } | { "method": "interruptConversation", id: RequestId, params: InterruptConversationParams, } | { "method": "addConversationListener", id: RequestId, params: AddConversationListenerParams, } | { "method": "removeConversationListener", id: RequestId, params: RemoveConversationListenerParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "loginApiKey", id: RequestId, params: LoginApiKeyParams, } | { "method": "loginChatGpt", id: RequestId, params: undefined, } | { "method": "cancelLoginChatGpt", id: RequestId, params: CancelLoginChatGptParams, } | { "method": "logoutChatGpt", id: RequestId, params: undefined, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "getUserSavedConfig", id: RequestId, params: undefined, } | { "method": "setDefaultModel", id: RequestId, params: SetDefaultModelParams, } | { "method": "getUserAgent", id: RequestId, params: undefined, } | { "method": "userInfo", id: RequestId, params: undefined, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, } | { "method": "execOneOffCommand", id: RequestId, params: ExecOneOffCommandParams, }; +export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/remote/list", id: RequestId, params: SkillsRemoteReadParams, } | { "method": "skills/remote/export", id: RequestId, params: SkillsRemoteWriteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts b/codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts deleted file mode 100644 index 522b91ce20..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Codex errors that we expose to clients. - */ -export type CodexErrorInfo = "context_window_exceeded" | "usage_limit_exceeded" | "server_overloaded" | { "http_connection_failed": { http_status_code: number | null, } } | { "response_stream_connection_failed": { http_status_code: number | null, } } | "internal_server_error" | "unauthorized" | "bad_request" | "sandbox_error" | { "response_stream_disconnected": { http_status_code: number | null, } } | { "response_too_many_failed_attempts": { http_status_code: number | null, } } | "thread_rollback_failed" | "other"; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts deleted file mode 100644 index 7109741999..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts +++ /dev/null @@ -1,23 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type CollabAgentInteractionBeginEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the receiver. - */ -receiver_thread_id: ThreadId, -/** - * Prompt sent from the sender to the receiver. Can be empty to prevent CoT - * leaking at the beginning. - */ -prompt: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts deleted file mode 100644 index 5458e06dce..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts +++ /dev/null @@ -1,36 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentStatus } from "./AgentStatus"; -import type { ThreadId } from "./ThreadId"; - -export type CollabAgentInteractionEndEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the receiver. - */ -receiver_thread_id: ThreadId, -/** - * Optional nickname assigned to the receiver agent. - */ -receiver_agent_nickname?: string | null, -/** - * Optional role assigned to the receiver agent. - */ -receiver_agent_role?: string | null, -/** - * Prompt sent from the sender to the receiver. Can be empty to prevent CoT - * leaking at the beginning. - */ -prompt: string, -/** - * Last known status of the receiver agent reported to the sender agent. - */ -status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts deleted file mode 100644 index cae7bf88b8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts +++ /dev/null @@ -1,18 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type CollabAgentRef = { -/** - * Thread ID of the receiver/new agent. - */ -thread_id: ThreadId, -/** - * Optional nickname assigned to an AgentControl-spawned sub-agent. - */ -agent_nickname?: string | null, -/** - * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. - */ -agent_role?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts deleted file mode 100644 index a86598e20c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts +++ /dev/null @@ -1,19 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type CollabAgentSpawnBeginEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the - * beginning. - */ -prompt: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts deleted file mode 100644 index 34753c8e08..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts +++ /dev/null @@ -1,36 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentStatus } from "./AgentStatus"; -import type { ThreadId } from "./ThreadId"; - -export type CollabAgentSpawnEndEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the newly spawned agent, if it was created. - */ -new_thread_id: ThreadId | null, -/** - * Optional nickname assigned to the new agent. - */ -new_agent_nickname?: string | null, -/** - * Optional role assigned to the new agent. - */ -new_agent_role?: string | null, -/** - * Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the - * beginning. - */ -prompt: string, -/** - * Last known status of the new agent reported to the sender agent. - */ -status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts deleted file mode 100644 index 286d19423d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts +++ /dev/null @@ -1,23 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentStatus } from "./AgentStatus"; -import type { ThreadId } from "./ThreadId"; - -export type CollabAgentStatusEntry = { -/** - * Thread ID of the receiver/new agent. - */ -thread_id: ThreadId, -/** - * Optional nickname assigned to an AgentControl-spawned sub-agent. - */ -agent_nickname?: string | null, -/** - * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. - */ -agent_role?: string | null, -/** - * Last known status of the agent. - */ -status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts deleted file mode 100644 index 355d59523a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts +++ /dev/null @@ -1,18 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type CollabCloseBeginEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the receiver. - */ -receiver_thread_id: ThreadId, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts deleted file mode 100644 index 171886f1ef..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts +++ /dev/null @@ -1,32 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentStatus } from "./AgentStatus"; -import type { ThreadId } from "./ThreadId"; - -export type CollabCloseEndEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the receiver. - */ -receiver_thread_id: ThreadId, -/** - * Optional nickname assigned to the receiver agent. - */ -receiver_agent_nickname?: string | null, -/** - * Optional role assigned to the receiver agent. - */ -receiver_agent_role?: string | null, -/** - * Last known status of the receiver agent reported to the sender agent before - * the close. - */ -status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts deleted file mode 100644 index e6c1c3d5cd..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts +++ /dev/null @@ -1,26 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type CollabResumeBeginEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the receiver. - */ -receiver_thread_id: ThreadId, -/** - * Optional nickname assigned to the receiver agent. - */ -receiver_agent_nickname?: string | null, -/** - * Optional role assigned to the receiver agent. - */ -receiver_agent_role?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts deleted file mode 100644 index caf970ec28..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts +++ /dev/null @@ -1,32 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentStatus } from "./AgentStatus"; -import type { ThreadId } from "./ThreadId"; - -export type CollabResumeEndEvent = { -/** - * Identifier for the collab tool call. - */ -call_id: string, -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the receiver. - */ -receiver_thread_id: ThreadId, -/** - * Optional nickname assigned to the receiver agent. - */ -receiver_agent_nickname?: string | null, -/** - * Optional role assigned to the receiver agent. - */ -receiver_agent_role?: string | null, -/** - * Last known status of the receiver agent reported to the sender agent after - * resume. - */ -status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts deleted file mode 100644 index f2f07f87ea..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts +++ /dev/null @@ -1,23 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CollabAgentRef } from "./CollabAgentRef"; -import type { ThreadId } from "./ThreadId"; - -export type CollabWaitingBeginEvent = { -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * Thread ID of the receivers. - */ -receiver_thread_ids: Array, -/** - * Optional nicknames/roles for receivers. - */ -receiver_agents?: Array, -/** - * ID of the waiting call. - */ -call_id: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts deleted file mode 100644 index 929d59c611..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts +++ /dev/null @@ -1,24 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentStatus } from "./AgentStatus"; -import type { CollabAgentStatusEntry } from "./CollabAgentStatusEntry"; -import type { ThreadId } from "./ThreadId"; - -export type CollabWaitingEndEvent = { -/** - * Thread ID of the sender. - */ -sender_thread_id: ThreadId, -/** - * ID of the waiting call. - */ -call_id: string, -/** - * Optional receiver metadata paired with final statuses. - */ -agent_statuses?: Array, -/** - * Last known status of the receiver agents reported to the sender agent. - */ -statuses: { [key in ThreadId]?: AgentStatus }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts deleted file mode 100644 index 538ca7a1bc..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ContextCompactedEvent = null; diff --git a/codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts b/codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts deleted file mode 100644 index dc3ab6388e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ContextCompactionItem = { id: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts b/codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts deleted file mode 100644 index 737bf99bef..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type CreditsSnapshot = { has_credits: boolean, unlimited: boolean, balance: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts b/codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts deleted file mode 100644 index 96fe75e969..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type CustomPrompt = { name: string, path: string, content: string, description: string | null, argument_hint: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts deleted file mode 100644 index c1a7d81314..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts +++ /dev/null @@ -1,13 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type DeprecationNoticeEvent = { -/** - * Concise summary of what is deprecated. - */ -summary: string, -/** - * Optional extra guidance, such as migration steps or rationale. - */ -details: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts deleted file mode 100644 index 8f432109d1..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type DynamicToolCallOutputContentItem = { "type": "inputText", text: string, } | { "type": "inputImage", imageUrl: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts deleted file mode 100644 index 94b0c65c66..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { JsonValue } from "./serde_json/JsonValue"; - -export type DynamicToolCallRequest = { callId: string, turnId: string, tool: string, arguments: JsonValue, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts deleted file mode 100644 index 442c0ce6f3..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts +++ /dev/null @@ -1,39 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; -import type { JsonValue } from "./serde_json/JsonValue"; - -export type DynamicToolCallResponseEvent = { -/** - * Identifier for the corresponding DynamicToolCallRequest. - */ -call_id: string, -/** - * Turn ID that this dynamic tool call belongs to. - */ -turn_id: string, -/** - * Dynamic tool name. - */ -tool: string, -/** - * Dynamic tool call arguments. - */ -arguments: JsonValue, -/** - * Dynamic tool response content items. - */ -content_items: Array, -/** - * Whether the tool call succeeded. - */ -success: boolean, -/** - * Optional error text when the tool call failed before producing a response. - */ -error: string | null, -/** - * The duration of the dynamic tool call. - */ -duration: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts deleted file mode 100644 index 045e304bdc..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ElicitationRequestEvent = { server_name: string, id: string | number, message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts deleted file mode 100644 index fafde767e0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CodexErrorInfo } from "./CodexErrorInfo"; - -export type ErrorEvent = { message: string, codex_error_info: CodexErrorInfo | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts b/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts deleted file mode 100644 index 5ccbe1e697..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts +++ /dev/null @@ -1,82 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentMessageContentDeltaEvent } from "./AgentMessageContentDeltaEvent"; -import type { AgentMessageDeltaEvent } from "./AgentMessageDeltaEvent"; -import type { AgentMessageEvent } from "./AgentMessageEvent"; -import type { AgentReasoningDeltaEvent } from "./AgentReasoningDeltaEvent"; -import type { AgentReasoningEvent } from "./AgentReasoningEvent"; -import type { AgentReasoningRawContentDeltaEvent } from "./AgentReasoningRawContentDeltaEvent"; -import type { AgentReasoningRawContentEvent } from "./AgentReasoningRawContentEvent"; -import type { AgentReasoningSectionBreakEvent } from "./AgentReasoningSectionBreakEvent"; -import type { ApplyPatchApprovalRequestEvent } from "./ApplyPatchApprovalRequestEvent"; -import type { BackgroundEventEvent } from "./BackgroundEventEvent"; -import type { CollabAgentInteractionBeginEvent } from "./CollabAgentInteractionBeginEvent"; -import type { CollabAgentInteractionEndEvent } from "./CollabAgentInteractionEndEvent"; -import type { CollabAgentSpawnBeginEvent } from "./CollabAgentSpawnBeginEvent"; -import type { CollabAgentSpawnEndEvent } from "./CollabAgentSpawnEndEvent"; -import type { CollabCloseBeginEvent } from "./CollabCloseBeginEvent"; -import type { CollabCloseEndEvent } from "./CollabCloseEndEvent"; -import type { CollabResumeBeginEvent } from "./CollabResumeBeginEvent"; -import type { CollabResumeEndEvent } from "./CollabResumeEndEvent"; -import type { CollabWaitingBeginEvent } from "./CollabWaitingBeginEvent"; -import type { CollabWaitingEndEvent } from "./CollabWaitingEndEvent"; -import type { ContextCompactedEvent } from "./ContextCompactedEvent"; -import type { DeprecationNoticeEvent } from "./DeprecationNoticeEvent"; -import type { DynamicToolCallRequest } from "./DynamicToolCallRequest"; -import type { DynamicToolCallResponseEvent } from "./DynamicToolCallResponseEvent"; -import type { ElicitationRequestEvent } from "./ElicitationRequestEvent"; -import type { ErrorEvent } from "./ErrorEvent"; -import type { ExecApprovalRequestEvent } from "./ExecApprovalRequestEvent"; -import type { ExecCommandBeginEvent } from "./ExecCommandBeginEvent"; -import type { ExecCommandEndEvent } from "./ExecCommandEndEvent"; -import type { ExecCommandOutputDeltaEvent } from "./ExecCommandOutputDeltaEvent"; -import type { ExitedReviewModeEvent } from "./ExitedReviewModeEvent"; -import type { GetHistoryEntryResponseEvent } from "./GetHistoryEntryResponseEvent"; -import type { ItemCompletedEvent } from "./ItemCompletedEvent"; -import type { ItemStartedEvent } from "./ItemStartedEvent"; -import type { ListCustomPromptsResponseEvent } from "./ListCustomPromptsResponseEvent"; -import type { ListRemoteSkillsResponseEvent } from "./ListRemoteSkillsResponseEvent"; -import type { ListSkillsResponseEvent } from "./ListSkillsResponseEvent"; -import type { McpListToolsResponseEvent } from "./McpListToolsResponseEvent"; -import type { McpStartupCompleteEvent } from "./McpStartupCompleteEvent"; -import type { McpStartupUpdateEvent } from "./McpStartupUpdateEvent"; -import type { McpToolCallBeginEvent } from "./McpToolCallBeginEvent"; -import type { McpToolCallEndEvent } from "./McpToolCallEndEvent"; -import type { ModelRerouteEvent } from "./ModelRerouteEvent"; -import type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent"; -import type { PatchApplyEndEvent } from "./PatchApplyEndEvent"; -import type { PlanDeltaEvent } from "./PlanDeltaEvent"; -import type { RawResponseItemEvent } from "./RawResponseItemEvent"; -import type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent"; -import type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent"; -import type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent"; -import type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent"; -import type { ReasoningRawContentDeltaEvent } from "./ReasoningRawContentDeltaEvent"; -import type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent"; -import type { RequestUserInputEvent } from "./RequestUserInputEvent"; -import type { ReviewRequest } from "./ReviewRequest"; -import type { SessionConfiguredEvent } from "./SessionConfiguredEvent"; -import type { StreamErrorEvent } from "./StreamErrorEvent"; -import type { TerminalInteractionEvent } from "./TerminalInteractionEvent"; -import type { ThreadNameUpdatedEvent } from "./ThreadNameUpdatedEvent"; -import type { ThreadRolledBackEvent } from "./ThreadRolledBackEvent"; -import type { TokenCountEvent } from "./TokenCountEvent"; -import type { TurnAbortedEvent } from "./TurnAbortedEvent"; -import type { TurnCompleteEvent } from "./TurnCompleteEvent"; -import type { TurnDiffEvent } from "./TurnDiffEvent"; -import type { TurnStartedEvent } from "./TurnStartedEvent"; -import type { UndoCompletedEvent } from "./UndoCompletedEvent"; -import type { UndoStartedEvent } from "./UndoStartedEvent"; -import type { UpdatePlanArgs } from "./UpdatePlanArgs"; -import type { UserMessageEvent } from "./UserMessageEvent"; -import type { ViewImageToolCallEvent } from "./ViewImageToolCallEvent"; -import type { WarningEvent } from "./WarningEvent"; -import type { WebSearchBeginEvent } from "./WebSearchBeginEvent"; -import type { WebSearchEndEvent } from "./WebSearchEndEvent"; - -/** - * Response event from the agent - * NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen. - */ -export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "realtime_conversation_started" } & RealtimeConversationStartedEvent | { "type": "realtime_conversation_realtime" } & RealtimeConversationRealtimeEvent | { "type": "realtime_conversation_closed" } & RealtimeConversationClosedEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "dynamic_tool_call_response" } & DynamicToolCallResponseEvent | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts deleted file mode 100644 index cc13400900..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts +++ /dev/null @@ -1,62 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; -import type { NetworkApprovalContext } from "./NetworkApprovalContext"; -import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; -import type { ParsedCommand } from "./ParsedCommand"; -import type { PermissionProfile } from "./PermissionProfile"; -import type { ReviewDecision } from "./ReviewDecision"; - -export type ExecApprovalRequestEvent = { -/** - * Identifier for the associated command execution item. - */ -call_id: string, -/** - * Identifier for this specific approval callback. - * - * When absent, the approval is for the command item itself (`call_id`). - * This is present for subcommand approvals (via execve intercept). - */ -approval_id?: string, -/** - * Turn ID that this command belongs to. - * Uses `#[serde(default)]` for backwards compatibility. - */ -turn_id: string, -/** - * The command to be executed. - */ -command: Array, -/** - * The command's working directory. - */ -cwd: string, -/** - * Optional human-readable reason for the approval (e.g. retry without sandbox). - */ -reason: string | null, -/** - * Optional network context for a blocked request that can be approved. - */ -network_approval_context?: NetworkApprovalContext, -/** - * Proposed execpolicy amendment that can be applied to allow future runs. - */ -proposed_execpolicy_amendment?: ExecPolicyAmendment, -/** - * Proposed network policy amendments (for example allow/deny this host in future). - */ -proposed_network_policy_amendments?: Array, -/** - * Optional additional filesystem permissions requested for this command. - */ -additional_permissions?: PermissionProfile, -/** - * Ordered list of decisions the client may present for this prompt. - * - * When absent, clients should derive the legacy default set from the - * other fields on this request. - */ -available_decisions?: Array, parsed_cmd: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts deleted file mode 100644 index a9b4bc9393..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts +++ /dev/null @@ -1,35 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ExecCommandSource } from "./ExecCommandSource"; -import type { ParsedCommand } from "./ParsedCommand"; - -export type ExecCommandBeginEvent = { -/** - * Identifier so this can be paired with the ExecCommandEnd event. - */ -call_id: string, -/** - * Identifier for the underlying PTY process (when available). - */ -process_id?: string, -/** - * Turn ID that this command belongs to. - */ -turn_id: string, -/** - * The command to be executed. - */ -command: Array, -/** - * The command's working directory if not the default cwd for the agent. - */ -cwd: string, parsed_cmd: Array, -/** - * Where the command originated. Defaults to Agent for backward compatibility. - */ -source: ExecCommandSource, -/** - * Raw input sent to a unified exec session (if this is an interaction event). - */ -interaction_input?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts deleted file mode 100644 index 0bfc41ea81..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts +++ /dev/null @@ -1,64 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ExecCommandSource } from "./ExecCommandSource"; -import type { ExecCommandStatus } from "./ExecCommandStatus"; -import type { ParsedCommand } from "./ParsedCommand"; - -export type ExecCommandEndEvent = { -/** - * Identifier for the ExecCommandBegin that finished. - */ -call_id: string, -/** - * Identifier for the underlying PTY process (when available). - */ -process_id?: string, -/** - * Turn ID that this command belongs to. - */ -turn_id: string, -/** - * The command that was executed. - */ -command: Array, -/** - * The command's working directory if not the default cwd for the agent. - */ -cwd: string, parsed_cmd: Array, -/** - * Where the command originated. Defaults to Agent for backward compatibility. - */ -source: ExecCommandSource, -/** - * Raw input sent to a unified exec session (if this is an interaction event). - */ -interaction_input?: string, -/** - * Captured stdout - */ -stdout: string, -/** - * Captured stderr - */ -stderr: string, -/** - * Captured aggregated output - */ -aggregated_output: string, -/** - * The command's exit code. - */ -exit_code: number, -/** - * The duration of the command execution. - */ -duration: string, -/** - * Formatted output from the command, as seen by the model. - */ -formatted_output: string, -/** - * Completion status for this command execution. - */ -status: ExecCommandStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts deleted file mode 100644 index 0930bdd827..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts +++ /dev/null @@ -1,18 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ExecOutputStream } from "./ExecOutputStream"; - -export type ExecCommandOutputDeltaEvent = { -/** - * Identifier for the ExecCommandBegin that produced this chunk. - */ -call_id: string, -/** - * Which stream produced this chunk. - */ -stream: ExecOutputStream, -/** - * Raw bytes from the stream (may not be valid UTF-8). - */ -chunk: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts deleted file mode 100644 index b665441bc2..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ExecCommandSource = "agent" | "user_shell" | "unified_exec_startup" | "unified_exec_interaction"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts deleted file mode 100644 index d8d91fb19f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ExecCommandStatus = "completed" | "failed" | "declined"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandParams.ts b/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandParams.ts deleted file mode 100644 index ca28ad775c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { SandboxPolicy } from "./SandboxPolicy"; - -export type ExecOneOffCommandParams = { command: Array, timeoutMs: bigint | null, cwd: string | null, sandboxPolicy: SandboxPolicy | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandResponse.ts deleted file mode 100644 index ff43ec4ca2..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ExecOneOffCommandResponse = { exitCode: number, stdout: string, stderr: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts b/codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts deleted file mode 100644 index 96aa74483d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ExecOutputStream = "stdout" | "stderr"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts deleted file mode 100644 index 7271f07a3f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ReviewOutputEvent } from "./ReviewOutputEvent"; - -export type ExitedReviewModeEvent = { review_output: ReviewOutputEvent | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts deleted file mode 100644 index aedf84de80..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AbsolutePathBuf } from "./AbsolutePathBuf"; - -export type FileSystemPermissions = { read: Array | null, write: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ForkConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/ForkConversationParams.ts deleted file mode 100644 index 4ca548fbff..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ForkConversationParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { NewConversationParams } from "./NewConversationParams"; -import type { ThreadId } from "./ThreadId"; - -export type ForkConversationParams = { path: string | null, conversationId: ThreadId | null, overrides: NewConversationParams | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ForkConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ForkConversationResponse.ts deleted file mode 100644 index 80d6e7947c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ForkConversationResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { EventMsg } from "./EventMsg"; -import type { ThreadId } from "./ThreadId"; - -export type ForkConversationResponse = { conversationId: ThreadId, model: string, initialMessages: Array | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts deleted file mode 100644 index d46019c1dc..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts +++ /dev/null @@ -1,10 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { HistoryEntry } from "./HistoryEntry"; - -export type GetHistoryEntryResponseEvent = { offset: number, log_id: bigint, -/** - * The entry at the requested offset, if available and parseable. - */ -entry: HistoryEntry | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/GetUserAgentResponse.ts b/codex-rs/app-server-protocol/schema/typescript/GetUserAgentResponse.ts deleted file mode 100644 index a74aba5da6..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/GetUserAgentResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type GetUserAgentResponse = { userAgent: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/GetUserSavedConfigResponse.ts b/codex-rs/app-server-protocol/schema/typescript/GetUserSavedConfigResponse.ts deleted file mode 100644 index f8dcf2e67c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/GetUserSavedConfigResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { UserSavedConfig } from "./UserSavedConfig"; - -export type GetUserSavedConfigResponse = { config: UserSavedConfig, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts b/codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts deleted file mode 100644 index da5bc37c21..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type HistoryEntry = { conversation_id: string, ts: bigint, text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/InputItem.ts b/codex-rs/app-server-protocol/schema/typescript/InputItem.ts deleted file mode 100644 index 3ac72d31d8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/InputItem.ts +++ /dev/null @@ -1,10 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TextElement } from "./TextElement"; - -export type InputItem = { "type": "text", "data": { text: string, -/** - * UI-defined spans within `text` used to render or persist special elements. - */ -text_elements: Array, } } | { "type": "image", "data": { image_url: string, } } | { "type": "localImage", "data": { path: string, } }; diff --git a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/InterruptConversationParams.ts deleted file mode 100644 index 8db162c97c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type InterruptConversationParams = { conversationId: ThreadId, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/InterruptConversationResponse.ts deleted file mode 100644 index 375604eef3..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TurnAbortReason } from "./TurnAbortReason"; - -export type InterruptConversationResponse = { abortReason: TurnAbortReason, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts deleted file mode 100644 index 97de348dff..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; -import type { TurnItem } from "./TurnItem"; - -export type ItemCompletedEvent = { thread_id: ThreadId, turn_id: string, item: TurnItem, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts deleted file mode 100644 index e82f78f965..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; -import type { TurnItem } from "./TurnItem"; - -export type ItemStartedEvent = { thread_id: ThreadId, turn_id: string, item: TurnItem, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListConversationsParams.ts b/codex-rs/app-server-protocol/schema/typescript/ListConversationsParams.ts deleted file mode 100644 index 27c9f3172a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ListConversationsParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ListConversationsParams = { pageSize: number | null, cursor: string | null, modelProviders: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListConversationsResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ListConversationsResponse.ts deleted file mode 100644 index 0e26443a5f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ListConversationsResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ConversationSummary } from "./ConversationSummary"; - -export type ListConversationsResponse = { items: Array, nextCursor: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts deleted file mode 100644 index 9ebb43afb7..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CustomPrompt } from "./CustomPrompt"; - -/** - * Response payload for `Op::ListCustomPrompts`. - */ -export type ListCustomPromptsResponseEvent = { custom_prompts: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts deleted file mode 100644 index e3b277f4d6..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RemoteSkillSummary } from "./RemoteSkillSummary"; - -/** - * Response payload for `Op::ListRemoteSkills`. - */ -export type ListRemoteSkillsResponseEvent = { skills: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts deleted file mode 100644 index efdd547596..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { SkillsListEntry } from "./SkillsListEntry"; - -/** - * Response payload for `Op::ListSkills`. - */ -export type ListSkillsResponseEvent = { skills: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyParams.ts b/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyParams.ts deleted file mode 100644 index 3638553d3e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type LoginApiKeyParams = { apiKey: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyResponse.ts b/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyResponse.ts deleted file mode 100644 index a67347aeb7..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type LoginApiKeyResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptCompleteNotification.ts b/codex-rs/app-server-protocol/schema/typescript/LoginChatGptCompleteNotification.ts deleted file mode 100644 index 82c07bfa2d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptCompleteNotification.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Deprecated in favor of AccountLoginCompletedNotification. - */ -export type LoginChatGptCompleteNotification = { loginId: string, success: boolean, error: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptResponse.ts b/codex-rs/app-server-protocol/schema/typescript/LoginChatGptResponse.ts deleted file mode 100644 index 4147280117..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type LoginChatGptResponse = { loginId: string, authUrl: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LogoutChatGptResponse.ts b/codex-rs/app-server-protocol/schema/typescript/LogoutChatGptResponse.ts deleted file mode 100644 index ad5dbd9105..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LogoutChatGptResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type LogoutChatGptResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts deleted file mode 100644 index 5c0792412c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { MacOsAutomationValue } from "./MacOsAutomationValue"; -import type { MacOsPreferencesValue } from "./MacOsPreferencesValue"; - -export type MacOsPermissions = { preferences: MacOsPreferencesValue | null, automations: MacOsAutomationValue | null, accessibility: boolean | null, calendar: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts b/codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts deleted file mode 100644 index 919ae85fd0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type McpAuthStatus = "unsupported" | "not_logged_in" | "bearer_token" | "o_auth"; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts b/codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts deleted file mode 100644 index 5b7103a60c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts +++ /dev/null @@ -1,18 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { JsonValue } from "./serde_json/JsonValue"; - -export type McpInvocation = { -/** - * Name of the MCP server as defined in the config. - */ -server: string, -/** - * Name of the tool as given by the MCP server. - */ -tool: string, -/** - * Arguments to the tool call. - */ -arguments: JsonValue | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts deleted file mode 100644 index 945959431a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts +++ /dev/null @@ -1,25 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { McpAuthStatus } from "./McpAuthStatus"; -import type { Resource } from "./Resource"; -import type { ResourceTemplate } from "./ResourceTemplate"; -import type { Tool } from "./Tool"; - -export type McpListToolsResponseEvent = { -/** - * Fully qualified tool name -> tool definition. - */ -tools: { [key in string]?: Tool }, -/** - * Known resources grouped by server name. - */ -resources: { [key in string]?: Array }, -/** - * Known resource templates grouped by server name. - */ -resource_templates: { [key in string]?: Array }, -/** - * Authentication status for each configured MCP server. - */ -auth_statuses: { [key in string]?: McpAuthStatus }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts deleted file mode 100644 index 67354adfbe..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { McpStartupFailure } from "./McpStartupFailure"; - -export type McpStartupCompleteEvent = { ready: Array, failed: Array, cancelled: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts deleted file mode 100644 index b12009b15b..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type McpStartupFailure = { server: string, error: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts deleted file mode 100644 index 48c08226f4..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type McpStartupStatus = { "state": "starting" } | { "state": "ready" } | { "state": "failed", error: string, } | { "state": "cancelled" }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts deleted file mode 100644 index ecfe7d551e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts +++ /dev/null @@ -1,14 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { McpStartupStatus } from "./McpStartupStatus"; - -export type McpStartupUpdateEvent = { -/** - * Server name being started. - */ -server: string, -/** - * Current startup status. - */ -status: McpStartupStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts deleted file mode 100644 index feb7ca7c21..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts +++ /dev/null @@ -1,10 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { McpInvocation } from "./McpInvocation"; - -export type McpToolCallBeginEvent = { -/** - * Identifier so this can be paired with the McpToolCallEnd event. - */ -call_id: string, invocation: McpInvocation, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts deleted file mode 100644 index 0ca82b2bc6..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts +++ /dev/null @@ -1,15 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CallToolResult } from "./CallToolResult"; -import type { McpInvocation } from "./McpInvocation"; - -export type McpToolCallEndEvent = { -/** - * Identifier for the corresponding McpToolCallBegin that finished. - */ -call_id: string, invocation: McpInvocation, duration: string, -/** - * Result of the tool call. Note this could be an error. - */ -result: { Ok : CallToolResult } | { Err : string }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts deleted file mode 100644 index 23a4e1efb6..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ModelRerouteReason } from "./ModelRerouteReason"; - -export type ModelRerouteEvent = { from_model: string, to_model: string, reason: ModelRerouteReason, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts b/codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts deleted file mode 100644 index f5e1abf1e3..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ModelRerouteReason = "high_risk_cyber_activity"; diff --git a/codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts b/codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts deleted file mode 100644 index f259e67b99..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Represents whether outbound network access is available to the agent. - */ -export type NetworkAccess = "restricted" | "enabled"; diff --git a/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts b/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts deleted file mode 100644 index b4b78e473c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; - -export type NetworkApprovalContext = { host: string, protocol: NetworkApprovalProtocol, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts b/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts deleted file mode 100644 index a33eab566f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type NetworkApprovalProtocol = "http" | "https" | "socks5_tcp" | "socks5_udp"; diff --git a/codex-rs/app-server-protocol/schema/typescript/NewConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/NewConversationParams.ts deleted file mode 100644 index e1113c27e2..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/NewConversationParams.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AskForApproval } from "./AskForApproval"; -import type { SandboxMode } from "./SandboxMode"; -import type { JsonValue } from "./serde_json/JsonValue"; - -export type NewConversationParams = { model: string | null, modelProvider: string | null, profile: string | null, cwd: string | null, approvalPolicy: AskForApproval | null, sandbox: SandboxMode | null, config: { [key in string]?: JsonValue } | null, baseInstructions: string | null, developerInstructions: string | null, compactPrompt: string | null, includeApplyPatchTool: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/NewConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/NewConversationResponse.ts deleted file mode 100644 index 608c2ac110..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/NewConversationResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ThreadId } from "./ThreadId"; - -export type NewConversationResponse = { conversationId: ThreadId, model: string, reasoningEffort: ReasoningEffort | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts deleted file mode 100644 index 19ff0d5754..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts +++ /dev/null @@ -1,23 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { FileChange } from "./FileChange"; - -export type PatchApplyBeginEvent = { -/** - * Identifier so this can be paired with the PatchApplyEnd event. - */ -call_id: string, -/** - * Turn ID that this patch belongs to. - * Uses `#[serde(default)]` for backwards compatibility. - */ -turn_id: string, -/** - * If true, there was no ApplyPatchApprovalRequest for this patch. - */ -auto_approved: boolean, -/** - * The changes to be applied. - */ -changes: { [key in string]?: FileChange }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts deleted file mode 100644 index 9dacb00e44..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts +++ /dev/null @@ -1,36 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { FileChange } from "./FileChange"; -import type { PatchApplyStatus } from "./PatchApplyStatus"; - -export type PatchApplyEndEvent = { -/** - * Identifier for the PatchApplyBegin that finished. - */ -call_id: string, -/** - * Turn ID that this patch belongs to. - * Uses `#[serde(default)]` for backwards compatibility. - */ -turn_id: string, -/** - * Captured stdout (summary printed by apply_patch). - */ -stdout: string, -/** - * Captured stderr (parser errors, IO failures, etc.). - */ -stderr: string, -/** - * Whether the patch was applied successfully. - */ -success: boolean, -/** - * The changes that were applied (mirrors PatchApplyBeginEvent::changes). - */ -changes: { [key in string]?: FileChange }, -/** - * Completion status for this patch application. - */ -status: PatchApplyStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts b/codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts deleted file mode 100644 index 721fcd9b1f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type PatchApplyStatus = "completed" | "failed" | "declined"; diff --git a/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts b/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts deleted file mode 100644 index bfc0de27b7..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { FileSystemPermissions } from "./FileSystemPermissions"; -import type { MacOsPermissions } from "./MacOsPermissions"; - -export type PermissionProfile = { network: boolean | null, file_system: FileSystemPermissions | null, macos: MacOsPermissions | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts deleted file mode 100644 index f2ff588442..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type PlanDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PlanItem.ts b/codex-rs/app-server-protocol/schema/typescript/PlanItem.ts deleted file mode 100644 index 909ab40e64..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/PlanItem.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type PlanItem = { id: string, text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts b/codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts deleted file mode 100644 index a9c8acfa75..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { StepStatus } from "./StepStatus"; - -export type PlanItemArg = { step: string, status: StepStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/Profile.ts b/codex-rs/app-server-protocol/schema/typescript/Profile.ts deleted file mode 100644 index 53d16e4a33..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/Profile.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AskForApproval } from "./AskForApproval"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ReasoningSummary } from "./ReasoningSummary"; -import type { Verbosity } from "./Verbosity"; - -export type Profile = { model: string | null, modelProvider: string | null, approvalPolicy: AskForApproval | null, modelReasoningEffort: ReasoningEffort | null, modelReasoningSummary: ReasoningSummary | null, modelVerbosity: Verbosity | null, chatgptBaseUrl: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts b/codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts deleted file mode 100644 index 8604128b4e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CreditsSnapshot } from "./CreditsSnapshot"; -import type { PlanType } from "./PlanType"; -import type { RateLimitWindow } from "./RateLimitWindow"; - -export type RateLimitSnapshot = { limit_id: string | null, limit_name: string | null, primary: RateLimitWindow | null, secondary: RateLimitWindow | null, credits: CreditsSnapshot | null, plan_type: PlanType | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts b/codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts deleted file mode 100644 index 4a85062bf7..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts +++ /dev/null @@ -1,17 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RateLimitWindow = { -/** - * Percentage (0-100) of the window that has been consumed. - */ -used_percent: number, -/** - * Rolling window duration, in minutes. - */ -window_minutes: number | null, -/** - * Unix timestamp (seconds since epoch) when the window resets. - */ -resets_at: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts deleted file mode 100644 index 62dd4f0018..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ResponseItem } from "./ResponseItem"; - -export type RawResponseItemEvent = { item: ResponseItem, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts b/codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts deleted file mode 100644 index c01bdd37c6..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts +++ /dev/null @@ -1,19 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AbsolutePathBuf } from "./AbsolutePathBuf"; - -/** - * Determines how read-only file access is granted inside a restricted - * sandbox. - */ -export type ReadOnlyAccess = { "type": "restricted", -/** - * Include built-in platform read roots required for basic process - * execution. - */ -include_platform_defaults: boolean, -/** - * Additional absolute roots that should be readable. - */ -readable_roots?: Array, } | { "type": "full-access" }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts deleted file mode 100644 index 99c0c1063c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RealtimeAudioFrame = { data: string, sample_rate: number, num_channels: number, samples_per_channel: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts deleted file mode 100644 index c73e6833ae..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RealtimeConversationClosedEvent = { reason: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts deleted file mode 100644 index 4ff24a8281..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RealtimeEvent } from "./RealtimeEvent"; - -export type RealtimeConversationRealtimeEvent = { payload: RealtimeEvent, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts deleted file mode 100644 index f2894fcb1e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RealtimeConversationStartedEvent = { session_id: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts deleted file mode 100644 index 8286f34cad..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RealtimeAudioFrame } from "./RealtimeAudioFrame"; -import type { RealtimeHandoffRequested } from "./RealtimeHandoffRequested"; -import type { JsonValue } from "./serde_json/JsonValue"; - -export type RealtimeEvent = { "SessionUpdated": { session_id: string, instructions: string | null, } } | { "AudioOut": RealtimeAudioFrame } | { "ConversationItemAdded": JsonValue } | { "ConversationItemDone": { item_id: string, } } | { "HandoffRequested": RealtimeHandoffRequested } | { "Error": string }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts deleted file mode 100644 index 39b77cfdf1..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RealtimeHandoffMessage = { role: string, text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts deleted file mode 100644 index f3426706aa..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RealtimeHandoffMessage } from "./RealtimeHandoffMessage"; - -export type RealtimeHandoffRequested = { handoff_id: string, item_id: string, input_transcript: string, messages: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts deleted file mode 100644 index 70dfc01d24..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ReasoningContentDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, summary_index: bigint, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts b/codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts deleted file mode 100644 index 80bcb65fd1..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ReasoningItem = { id: string, summary_text: Array, raw_content: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts deleted file mode 100644 index ef3a792caf..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ReasoningRawContentDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, content_index: bigint, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts b/codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts deleted file mode 100644 index 320f1096b0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts +++ /dev/null @@ -1,17 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RejectConfig = { -/** - * Reject approval prompts related to sandbox escalation. - */ -sandbox_approval: boolean, -/** - * Reject prompts triggered by execpolicy `prompt` rules. - */ -rules: boolean, -/** - * Reject MCP elicitation prompts. - */ -mcp_elicitations: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts deleted file mode 100644 index 83082f2a57..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Response payload for `Op::DownloadRemoteSkill`. - */ -export type RemoteSkillDownloadedEvent = { id: string, name: string, path: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts b/codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts deleted file mode 100644 index 7bf57b3b09..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RemoteSkillSummary = { id: string, name: string, description: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationListenerParams.ts b/codex-rs/app-server-protocol/schema/typescript/RemoveConversationListenerParams.ts deleted file mode 100644 index e9628b6341..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationListenerParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RemoveConversationListenerParams = { subscriptionId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationSubscriptionResponse.ts b/codex-rs/app-server-protocol/schema/typescript/RemoveConversationSubscriptionResponse.ts deleted file mode 100644 index 8053d7e4b4..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationSubscriptionResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RemoveConversationSubscriptionResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts deleted file mode 100644 index 8ea6453de9..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts +++ /dev/null @@ -1,15 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RequestUserInputQuestion } from "./RequestUserInputQuestion"; - -export type RequestUserInputEvent = { -/** - * Responses API call id for the associated tool call, if available. - */ -call_id: string, -/** - * Turn ID that this request belongs to. - * Uses `#[serde(default)]` for backwards compatibility. - */ -turn_id: string, questions: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts deleted file mode 100644 index 2a68f7b4c8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RequestUserInputQuestionOption } from "./RequestUserInputQuestionOption"; - -export type RequestUserInputQuestion = { id: string, header: string, question: string, isOther: boolean, isSecret: boolean, options: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts deleted file mode 100644 index b2d2a0db48..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type RequestUserInputQuestionOption = { label: string, description: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ResumeConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/ResumeConversationParams.ts deleted file mode 100644 index f2fe9d47c8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ResumeConversationParams.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { NewConversationParams } from "./NewConversationParams"; -import type { ResponseItem } from "./ResponseItem"; -import type { ThreadId } from "./ThreadId"; - -export type ResumeConversationParams = { path: string | null, conversationId: ThreadId | null, history: Array | null, overrides: NewConversationParams | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ResumeConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ResumeConversationResponse.ts deleted file mode 100644 index 1af5b68599..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ResumeConversationResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { EventMsg } from "./EventMsg"; -import type { ThreadId } from "./ThreadId"; - -export type ResumeConversationResponse = { conversationId: ThreadId, model: string, initialMessages: Array | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts deleted file mode 100644 index 752589fe55..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ReviewLineRange } from "./ReviewLineRange"; - -/** - * Location of the code related to a review finding. - */ -export type ReviewCodeLocation = { absolute_file_path: string, line_range: ReviewLineRange, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts deleted file mode 100644 index e7c96bd170..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ReviewCodeLocation } from "./ReviewCodeLocation"; - -/** - * A single review finding describing an observed issue or recommendation. - */ -export type ReviewFinding = { title: string, body: string, confidence_score: number, priority: number, code_location: ReviewCodeLocation, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts deleted file mode 100644 index c57ec6ed60..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Inclusive line range in a file associated with the finding. - */ -export type ReviewLineRange = { start: number, end: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts deleted file mode 100644 index c45747424b..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ReviewFinding } from "./ReviewFinding"; - -/** - * Structured review result produced by a child review session. - */ -export type ReviewOutputEvent = { findings: Array, overall_correctness: string, overall_explanation: string, overall_confidence_score: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts deleted file mode 100644 index 1e9b8ad2ee..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ReviewTarget } from "./ReviewTarget"; - -/** - * Review request sent to the review session. - */ -export type ReviewRequest = { target: ReviewTarget, user_facing_hint?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts deleted file mode 100644 index a79f1e993c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ReviewTarget = { "type": "uncommittedChanges" } | { "type": "baseBranch", branch: string, } | { "type": "commit", sha: string, -/** - * Optional human-readable label (e.g., commit subject) for UIs. - */ -title: string | null, } | { "type": "custom", instructions: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SandboxMode.ts b/codex-rs/app-server-protocol/schema/typescript/SandboxMode.ts deleted file mode 100644 index b8cf4326b9..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SandboxMode.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access"; diff --git a/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts b/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts deleted file mode 100644 index 743ad22229..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts +++ /dev/null @@ -1,44 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AbsolutePathBuf } from "./AbsolutePathBuf"; -import type { NetworkAccess } from "./NetworkAccess"; -import type { ReadOnlyAccess } from "./ReadOnlyAccess"; - -/** - * Determines execution restrictions for model shell commands. - */ -export type SandboxPolicy = { "type": "danger-full-access" } | { "type": "read-only", -/** - * Read access granted while running under this policy. - */ -access?: ReadOnlyAccess, } | { "type": "external-sandbox", -/** - * Whether the external sandbox permits outbound network traffic. - */ -network_access: NetworkAccess, } | { "type": "workspace-write", -/** - * Additional folders (beyond cwd and possibly TMPDIR) that should be - * writable from within the sandbox. - */ -writable_roots?: Array, -/** - * Read access granted while running under this policy. - */ -read_only_access?: ReadOnlyAccess, -/** - * When set to `true`, outbound network access is allowed. `false` by - * default. - */ -network_access: boolean, -/** - * When set to `true`, will NOT include the per-user `TMPDIR` - * environment variable among the default writable roots. Defaults to - * `false`. - */ -exclude_tmpdir_env_var: boolean, -/** - * When set to `true`, will NOT include the `/tmp` among the default - * writable roots on UNIX. Defaults to `false`. - */ -exclude_slash_tmp: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SandboxSettings.ts b/codex-rs/app-server-protocol/schema/typescript/SandboxSettings.ts deleted file mode 100644 index 94139b0e5d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SandboxSettings.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AbsolutePathBuf } from "./AbsolutePathBuf"; - -export type SandboxSettings = { writableRoots: Array, networkAccess: boolean | null, excludeTmpdirEnvVar: boolean | null, excludeSlashTmp: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageParams.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserMessageParams.ts deleted file mode 100644 index 6aee538eb0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { InputItem } from "./InputItem"; -import type { ThreadId } from "./ThreadId"; - -export type SendUserMessageParams = { conversationId: ThreadId, items: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageResponse.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserMessageResponse.ts deleted file mode 100644 index 1a03e043a6..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SendUserMessageResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnParams.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserTurnParams.ts deleted file mode 100644 index 063191649a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnParams.ts +++ /dev/null @@ -1,17 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AskForApproval } from "./AskForApproval"; -import type { InputItem } from "./InputItem"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ReasoningSummary } from "./ReasoningSummary"; -import type { SandboxPolicy } from "./SandboxPolicy"; -import type { ServiceTier } from "./ServiceTier"; -import type { ThreadId } from "./ThreadId"; -import type { JsonValue } from "./serde_json/JsonValue"; - -export type SendUserTurnParams = { conversationId: ThreadId, items: Array, cwd: string, approvalPolicy: AskForApproval, sandboxPolicy: SandboxPolicy, model: string, serviceTier?: ServiceTier | null | null, effort: ReasoningEffort | null, summary: ReasoningSummary, -/** - * Optional JSON Schema used to constrain the final assistant message for this turn. - */ -outputSchema: JsonValue | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnResponse.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserTurnResponse.ts deleted file mode 100644 index cffd0ac398..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SendUserTurnResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts index 43345d9093..d7f70d3558 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts @@ -1,11 +1,8 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AuthStatusChangeNotification } from "./AuthStatusChangeNotification"; import type { FuzzyFileSearchSessionCompletedNotification } from "./FuzzyFileSearchSessionCompletedNotification"; import type { FuzzyFileSearchSessionUpdatedNotification } from "./FuzzyFileSearchSessionUpdatedNotification"; -import type { LoginChatGptCompleteNotification } from "./LoginChatGptCompleteNotification"; -import type { SessionConfiguredNotification } from "./SessionConfiguredNotification"; import type { AccountLoginCompletedNotification } from "./v2/AccountLoginCompletedNotification"; import type { AccountRateLimitsUpdatedNotification } from "./v2/AccountRateLimitsUpdatedNotification"; import type { AccountUpdatedNotification } from "./v2/AccountUpdatedNotification"; @@ -51,4 +48,4 @@ import type { WindowsWorldWritableWarningNotification } from "./v2/WindowsWorldW /** * Notification sent from the server to the client. */ -export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification } | { "method": "authStatusChange", "params": AuthStatusChangeNotification } | { "method": "loginChatGptComplete", "params": LoginChatGptCompleteNotification } | { "method": "sessionConfigured", "params": SessionConfiguredNotification }; +export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts b/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts deleted file mode 100644 index b4696a0e4c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts +++ /dev/null @@ -1,58 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AskForApproval } from "./AskForApproval"; -import type { EventMsg } from "./EventMsg"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { SandboxPolicy } from "./SandboxPolicy"; -import type { ServiceTier } from "./ServiceTier"; -import type { SessionNetworkProxyRuntime } from "./SessionNetworkProxyRuntime"; -import type { ThreadId } from "./ThreadId"; - -export type SessionConfiguredEvent = { session_id: ThreadId, forked_from_id: ThreadId | null, -/** - * Optional user-facing thread name (may be unset). - */ -thread_name?: string, -/** - * Tell the client what model is being queried. - */ -model: string, model_provider_id: string, service_tier: ServiceTier | null, -/** - * When to escalate for approval for execution - */ -approval_policy: AskForApproval, -/** - * How to sandbox commands executed in the system - */ -sandbox_policy: SandboxPolicy, -/** - * Working directory that should be treated as the *root* of the - * session. - */ -cwd: string, -/** - * The effort the model is putting into reasoning about the user's request. - */ -reasoning_effort: ReasoningEffort | null, -/** - * Identifier of the history log file (inode on Unix, 0 otherwise). - */ -history_log_id: bigint, -/** - * Current number of entries in the history log. - */ -history_entry_count: number, -/** - * Optional initial messages (as events) for resumed sessions. - * When present, UIs can use these to seed the history. - */ -initial_messages: Array | null, -/** - * Runtime proxy bind addresses, when the managed proxy was started for this session. - */ -network_proxy?: SessionNetworkProxyRuntime, -/** - * Path in which the rollout is stored. Can be `None` for ephemeral threads - */ -rollout_path: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredNotification.ts b/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredNotification.ts deleted file mode 100644 index 0fd5edcb3b..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredNotification.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { EventMsg } from "./EventMsg"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ServiceTier } from "./ServiceTier"; -import type { ThreadId } from "./ThreadId"; - -export type SessionConfiguredNotification = { sessionId: ThreadId, model: string, serviceTier: ServiceTier | null, reasoningEffort: ReasoningEffort | null, historyLogId: bigint, historyEntryCount: number, initialMessages: Array | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts b/codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts deleted file mode 100644 index 3f0c6d857e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SessionNetworkProxyRuntime = { http_addr: string, socks_addr: string, admin_addr: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelParams.ts b/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelParams.ts deleted file mode 100644 index b9e4e7d901..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ReasoningEffort } from "./ReasoningEffort"; - -export type SetDefaultModelParams = { model: string | null, reasoningEffort: ReasoningEffort | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelResponse.ts b/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelResponse.ts deleted file mode 100644 index 1639601e0c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SetDefaultModelResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts b/codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts deleted file mode 100644 index e2dd4f4241..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { SkillToolDependency } from "./SkillToolDependency"; - -export type SkillDependencies = { tools: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts b/codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts deleted file mode 100644 index 6eaf035d8c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SkillErrorInfo = { path: string, message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts b/codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts deleted file mode 100644 index 30250b9383..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SkillInterface = { display_name?: string, short_description?: string, icon_small?: string, icon_large?: string, brand_color?: string, default_prompt?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts b/codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts deleted file mode 100644 index 088abc406a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts +++ /dev/null @@ -1,12 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { SkillDependencies } from "./SkillDependencies"; -import type { SkillInterface } from "./SkillInterface"; -import type { SkillScope } from "./SkillScope"; - -export type SkillMetadata = { name: string, description: string, -/** - * Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description. - */ -short_description?: string, interface?: SkillInterface, dependencies?: SkillDependencies, path: string, scope: SkillScope, enabled: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillScope.ts b/codex-rs/app-server-protocol/schema/typescript/SkillScope.ts deleted file mode 100644 index 997006f5b8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillScope.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SkillScope = "user" | "repo" | "system" | "admin"; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts b/codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts deleted file mode 100644 index a5da45e178..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type SkillToolDependency = { type: string, value: string, description?: string, transport?: string, command?: string, url?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts b/codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts deleted file mode 100644 index 3f46c98a4a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { SkillErrorInfo } from "./SkillErrorInfo"; -import type { SkillMetadata } from "./SkillMetadata"; - -export type SkillsListEntry = { cwd: string, skills: Array, errors: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/StepStatus.ts b/codex-rs/app-server-protocol/schema/typescript/StepStatus.ts deleted file mode 100644 index 8494a76e0b..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/StepStatus.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type StepStatus = "pending" | "in_progress" | "completed"; diff --git a/codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts b/codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts deleted file mode 100644 index b88993a344..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts +++ /dev/null @@ -1,12 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CodexErrorInfo } from "./CodexErrorInfo"; - -export type StreamErrorEvent = { message: string, codex_error_info: CodexErrorInfo | null, -/** - * Optional details about the underlying stream failure (often the same - * human-readable message that is surfaced as the terminal error if retries - * are exhausted). - */ -additional_details: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts deleted file mode 100644 index 5f300e6ca5..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts +++ /dev/null @@ -1,17 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type TerminalInteractionEvent = { -/** - * Identifier for the ExecCommandBegin that produced this chunk. - */ -call_id: string, -/** - * Process id associated with the running command. - */ -process_id: string, -/** - * Stdin sent to the running session. - */ -stdin: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TextElement.ts b/codex-rs/app-server-protocol/schema/typescript/TextElement.ts deleted file mode 100644 index 8841d00499..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TextElement.ts +++ /dev/null @@ -1,14 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ByteRange } from "./ByteRange"; - -export type TextElement = { -/** - * Byte range in the parent `text` buffer that this element occupies. - */ -byteRange: ByteRange, -/** - * Optional human-readable placeholder for the element, displayed in the UI. - */ -placeholder: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts deleted file mode 100644 index 639e29f9d7..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ThreadId } from "./ThreadId"; - -export type ThreadNameUpdatedEvent = { thread_id: ThreadId, thread_name?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts deleted file mode 100644 index 30bc64c9c1..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts +++ /dev/null @@ -1,9 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ThreadRolledBackEvent = { -/** - * Number of user turns that were removed from context. - */ -num_turns: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts deleted file mode 100644 index f58b574641..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts +++ /dev/null @@ -1,7 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { RateLimitSnapshot } from "./RateLimitSnapshot"; -import type { TokenUsageInfo } from "./TokenUsageInfo"; - -export type TokenCountEvent = { info: TokenUsageInfo | null, rate_limits: RateLimitSnapshot | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts b/codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts deleted file mode 100644 index 41186b25b9..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type TokenUsage = { input_tokens: number, cached_input_tokens: number, output_tokens: number, reasoning_output_tokens: number, total_tokens: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts b/codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts deleted file mode 100644 index cb15de42e7..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TokenUsage } from "./TokenUsage"; - -export type TokenUsageInfo = { total_token_usage: TokenUsage, last_token_usage: TokenUsage, model_context_window: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/Tools.ts b/codex-rs/app-server-protocol/schema/typescript/Tools.ts deleted file mode 100644 index 0387022966..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/Tools.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type Tools = { webSearch: boolean | null, viewImage: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts b/codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts deleted file mode 100644 index f07cde6292..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type TurnAbortReason = "interrupted" | "replaced" | "review_ended"; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts deleted file mode 100644 index 0b4e9075b3..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TurnAbortReason } from "./TurnAbortReason"; - -export type TurnAbortedEvent = { turn_id: string | null, reason: TurnAbortReason, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts deleted file mode 100644 index 6987d59f98..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type TurnCompleteEvent = { turn_id: string, last_agent_message: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts deleted file mode 100644 index 52e3df09b0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type TurnDiffEvent = { unified_diff: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnItem.ts b/codex-rs/app-server-protocol/schema/typescript/TurnItem.ts deleted file mode 100644 index 0f2ea12a21..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TurnItem.ts +++ /dev/null @@ -1,11 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AgentMessageItem } from "./AgentMessageItem"; -import type { ContextCompactionItem } from "./ContextCompactionItem"; -import type { PlanItem } from "./PlanItem"; -import type { ReasoningItem } from "./ReasoningItem"; -import type { UserMessageItem } from "./UserMessageItem"; -import type { WebSearchItem } from "./WebSearchItem"; - -export type TurnItem = { "type": "UserMessage" } & UserMessageItem | { "type": "AgentMessage" } & AgentMessageItem | { "type": "Plan" } & PlanItem | { "type": "Reasoning" } & ReasoningItem | { "type": "WebSearch" } & WebSearchItem | { "type": "ContextCompaction" } & ContextCompactionItem; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts deleted file mode 100644 index 14c0d76707..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ModeKind } from "./ModeKind"; - -export type TurnStartedEvent = { turn_id: string, model_context_window: bigint | null, collaboration_mode_kind: ModeKind, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts deleted file mode 100644 index 2d94e2e18d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type UndoCompletedEvent = { success: boolean, message: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts deleted file mode 100644 index 712082adff..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type UndoStartedEvent = { message: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts b/codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts deleted file mode 100644 index 61613fcb5f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts +++ /dev/null @@ -1,10 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { PlanItemArg } from "./PlanItemArg"; - -export type UpdatePlanArgs = { -/** - * Arguments for the `update_plan` todo/checklist tool (not plan mode). - */ -explanation: string | null, plan: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserInfoResponse.ts b/codex-rs/app-server-protocol/schema/typescript/UserInfoResponse.ts deleted file mode 100644 index 3d257a1c5e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UserInfoResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type UserInfoResponse = { allegedUserEmail: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserInput.ts b/codex-rs/app-server-protocol/schema/typescript/UserInput.ts deleted file mode 100644 index e6a9c3a580..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UserInput.ts +++ /dev/null @@ -1,16 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TextElement } from "./TextElement"; - -/** - * User input - */ -export type UserInput = { "type": "text", text: string, -/** - * UI-defined spans within `text` that should be treated as special elements. - * These are byte ranges into the UTF-8 `text` buffer and are used to render - * or persist rich input markers (e.g., image placeholders) across history - * and resume without mutating the literal text. - */ -text_elements: Array, } | { "type": "image", image_url: string, } | { "type": "local_image", path: string, } | { "type": "skill", name: string, path: string, } | { "type": "mention", name: string, path: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts b/codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts deleted file mode 100644 index 2fde364d67..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts +++ /dev/null @@ -1,22 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TextElement } from "./TextElement"; - -export type UserMessageEvent = { message: string, -/** - * Image URLs sourced from `UserInput::Image`. These are safe - * to replay in legacy UI history events and correspond to images sent to - * the model. - */ -images: Array | null, -/** - * Local file paths sourced from `UserInput::LocalImage`. These are kept so - * the UI can reattach images when editing history, and should not be sent - * to the model or treated as API-ready URLs. - */ -local_images: Array, -/** - * UI-defined spans within `message` used to render or persist special elements. - */ -text_elements: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts b/codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts deleted file mode 100644 index df856287a5..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { UserInput } from "./UserInput"; - -export type UserMessageItem = { id: string, content: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserSavedConfig.ts b/codex-rs/app-server-protocol/schema/typescript/UserSavedConfig.ts deleted file mode 100644 index e70107f31e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UserSavedConfig.ts +++ /dev/null @@ -1,14 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AskForApproval } from "./AskForApproval"; -import type { ForcedLoginMethod } from "./ForcedLoginMethod"; -import type { Profile } from "./Profile"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ReasoningSummary } from "./ReasoningSummary"; -import type { SandboxMode } from "./SandboxMode"; -import type { SandboxSettings } from "./SandboxSettings"; -import type { Tools } from "./Tools"; -import type { Verbosity } from "./Verbosity"; - -export type UserSavedConfig = { approvalPolicy: AskForApproval | null, sandboxMode: SandboxMode | null, sandboxSettings: SandboxSettings | null, forcedChatgptWorkspaceId: string | null, forcedLoginMethod: ForcedLoginMethod | null, model: string | null, modelReasoningEffort: ReasoningEffort | null, modelReasoningSummary: ReasoningSummary | null, modelVerbosity: Verbosity | null, tools: Tools | null, profile: string | null, profiles: { [key in string]?: Profile }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts deleted file mode 100644 index 76541a773a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts +++ /dev/null @@ -1,13 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type ViewImageToolCallEvent = { -/** - * Identifier for the originating tool call. - */ -call_id: string, -/** - * Local filesystem path provided to the tool. - */ -path: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts b/codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts deleted file mode 100644 index 35ec40f7cd..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type WarningEvent = { message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts deleted file mode 100644 index 4a8d881914..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -export type WebSearchBeginEvent = { call_id: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts deleted file mode 100644 index 5b8b67c28b..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { WebSearchAction } from "./WebSearchAction"; - -export type WebSearchEndEvent = { call_id: string, query: string, action: WebSearchAction, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts b/codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts deleted file mode 100644 index 46b1406519..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts +++ /dev/null @@ -1,6 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { WebSearchAction } from "./WebSearchAction"; - -export type WebSearchItem = { id: string, query: string, action: WebSearchAction, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index 81e08b1596..fa1284843d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -1,81 +1,21 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! export type { AbsolutePathBuf } from "./AbsolutePathBuf"; -export type { AddConversationListenerParams } from "./AddConversationListenerParams"; -export type { AddConversationSubscriptionResponse } from "./AddConversationSubscriptionResponse"; -export type { AgentMessageContent } from "./AgentMessageContent"; -export type { AgentMessageContentDeltaEvent } from "./AgentMessageContentDeltaEvent"; -export type { AgentMessageDeltaEvent } from "./AgentMessageDeltaEvent"; -export type { AgentMessageEvent } from "./AgentMessageEvent"; -export type { AgentMessageItem } from "./AgentMessageItem"; -export type { AgentReasoningDeltaEvent } from "./AgentReasoningDeltaEvent"; -export type { AgentReasoningEvent } from "./AgentReasoningEvent"; -export type { AgentReasoningRawContentDeltaEvent } from "./AgentReasoningRawContentDeltaEvent"; -export type { AgentReasoningRawContentEvent } from "./AgentReasoningRawContentEvent"; -export type { AgentReasoningSectionBreakEvent } from "./AgentReasoningSectionBreakEvent"; -export type { AgentStatus } from "./AgentStatus"; export type { ApplyPatchApprovalParams } from "./ApplyPatchApprovalParams"; -export type { ApplyPatchApprovalRequestEvent } from "./ApplyPatchApprovalRequestEvent"; export type { ApplyPatchApprovalResponse } from "./ApplyPatchApprovalResponse"; -export type { ArchiveConversationParams } from "./ArchiveConversationParams"; -export type { ArchiveConversationResponse } from "./ArchiveConversationResponse"; -export type { AskForApproval } from "./AskForApproval"; export type { AuthMode } from "./AuthMode"; -export type { AuthStatusChangeNotification } from "./AuthStatusChangeNotification"; -export type { BackgroundEventEvent } from "./BackgroundEventEvent"; -export type { ByteRange } from "./ByteRange"; -export type { CallToolResult } from "./CallToolResult"; -export type { CancelLoginChatGptParams } from "./CancelLoginChatGptParams"; -export type { CancelLoginChatGptResponse } from "./CancelLoginChatGptResponse"; export type { ClientInfo } from "./ClientInfo"; export type { ClientNotification } from "./ClientNotification"; export type { ClientRequest } from "./ClientRequest"; -export type { CodexErrorInfo } from "./CodexErrorInfo"; -export type { CollabAgentInteractionBeginEvent } from "./CollabAgentInteractionBeginEvent"; -export type { CollabAgentInteractionEndEvent } from "./CollabAgentInteractionEndEvent"; -export type { CollabAgentRef } from "./CollabAgentRef"; -export type { CollabAgentSpawnBeginEvent } from "./CollabAgentSpawnBeginEvent"; -export type { CollabAgentSpawnEndEvent } from "./CollabAgentSpawnEndEvent"; -export type { CollabAgentStatusEntry } from "./CollabAgentStatusEntry"; -export type { CollabCloseBeginEvent } from "./CollabCloseBeginEvent"; -export type { CollabCloseEndEvent } from "./CollabCloseEndEvent"; -export type { CollabResumeBeginEvent } from "./CollabResumeBeginEvent"; -export type { CollabResumeEndEvent } from "./CollabResumeEndEvent"; -export type { CollabWaitingBeginEvent } from "./CollabWaitingBeginEvent"; -export type { CollabWaitingEndEvent } from "./CollabWaitingEndEvent"; export type { CollaborationMode } from "./CollaborationMode"; export type { ContentItem } from "./ContentItem"; -export type { ContextCompactedEvent } from "./ContextCompactedEvent"; -export type { ContextCompactionItem } from "./ContextCompactionItem"; export type { ConversationGitInfo } from "./ConversationGitInfo"; export type { ConversationSummary } from "./ConversationSummary"; -export type { CreditsSnapshot } from "./CreditsSnapshot"; -export type { CustomPrompt } from "./CustomPrompt"; -export type { DeprecationNoticeEvent } from "./DeprecationNoticeEvent"; -export type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; -export type { DynamicToolCallRequest } from "./DynamicToolCallRequest"; -export type { DynamicToolCallResponseEvent } from "./DynamicToolCallResponseEvent"; -export type { ElicitationRequestEvent } from "./ElicitationRequestEvent"; -export type { ErrorEvent } from "./ErrorEvent"; -export type { EventMsg } from "./EventMsg"; -export type { ExecApprovalRequestEvent } from "./ExecApprovalRequestEvent"; export type { ExecCommandApprovalParams } from "./ExecCommandApprovalParams"; export type { ExecCommandApprovalResponse } from "./ExecCommandApprovalResponse"; -export type { ExecCommandBeginEvent } from "./ExecCommandBeginEvent"; -export type { ExecCommandEndEvent } from "./ExecCommandEndEvent"; -export type { ExecCommandOutputDeltaEvent } from "./ExecCommandOutputDeltaEvent"; -export type { ExecCommandSource } from "./ExecCommandSource"; -export type { ExecCommandStatus } from "./ExecCommandStatus"; -export type { ExecOneOffCommandParams } from "./ExecOneOffCommandParams"; -export type { ExecOneOffCommandResponse } from "./ExecOneOffCommandResponse"; -export type { ExecOutputStream } from "./ExecOutputStream"; export type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; -export type { ExitedReviewModeEvent } from "./ExitedReviewModeEvent"; export type { FileChange } from "./FileChange"; -export type { FileSystemPermissions } from "./FileSystemPermissions"; export type { ForcedLoginMethod } from "./ForcedLoginMethod"; -export type { ForkConversationParams } from "./ForkConversationParams"; -export type { ForkConversationResponse } from "./ForkConversationResponse"; export type { FunctionCallOutputBody } from "./FunctionCallOutputBody"; export type { FunctionCallOutputContentItem } from "./FunctionCallOutputContentItem"; export type { FunctionCallOutputPayload } from "./FunctionCallOutputPayload"; @@ -88,166 +28,44 @@ export type { GetAuthStatusParams } from "./GetAuthStatusParams"; export type { GetAuthStatusResponse } from "./GetAuthStatusResponse"; export type { GetConversationSummaryParams } from "./GetConversationSummaryParams"; export type { GetConversationSummaryResponse } from "./GetConversationSummaryResponse"; -export type { GetHistoryEntryResponseEvent } from "./GetHistoryEntryResponseEvent"; -export type { GetUserAgentResponse } from "./GetUserAgentResponse"; -export type { GetUserSavedConfigResponse } from "./GetUserSavedConfigResponse"; export type { GhostCommit } from "./GhostCommit"; export type { GitDiffToRemoteParams } from "./GitDiffToRemoteParams"; export type { GitDiffToRemoteResponse } from "./GitDiffToRemoteResponse"; export type { GitSha } from "./GitSha"; -export type { HistoryEntry } from "./HistoryEntry"; export type { InitializeCapabilities } from "./InitializeCapabilities"; export type { InitializeParams } from "./InitializeParams"; export type { InitializeResponse } from "./InitializeResponse"; -export type { InputItem } from "./InputItem"; export type { InputModality } from "./InputModality"; -export type { InterruptConversationParams } from "./InterruptConversationParams"; -export type { InterruptConversationResponse } from "./InterruptConversationResponse"; -export type { ItemCompletedEvent } from "./ItemCompletedEvent"; -export type { ItemStartedEvent } from "./ItemStartedEvent"; -export type { ListConversationsParams } from "./ListConversationsParams"; -export type { ListConversationsResponse } from "./ListConversationsResponse"; -export type { ListCustomPromptsResponseEvent } from "./ListCustomPromptsResponseEvent"; -export type { ListRemoteSkillsResponseEvent } from "./ListRemoteSkillsResponseEvent"; -export type { ListSkillsResponseEvent } from "./ListSkillsResponseEvent"; export type { LocalShellAction } from "./LocalShellAction"; export type { LocalShellExecAction } from "./LocalShellExecAction"; export type { LocalShellStatus } from "./LocalShellStatus"; -export type { LoginApiKeyParams } from "./LoginApiKeyParams"; -export type { LoginApiKeyResponse } from "./LoginApiKeyResponse"; -export type { LoginChatGptCompleteNotification } from "./LoginChatGptCompleteNotification"; -export type { LoginChatGptResponse } from "./LoginChatGptResponse"; -export type { LogoutChatGptResponse } from "./LogoutChatGptResponse"; export type { MacOsAutomationValue } from "./MacOsAutomationValue"; -export type { MacOsPermissions } from "./MacOsPermissions"; export type { MacOsPreferencesValue } from "./MacOsPreferencesValue"; -export type { McpAuthStatus } from "./McpAuthStatus"; -export type { McpInvocation } from "./McpInvocation"; -export type { McpListToolsResponseEvent } from "./McpListToolsResponseEvent"; -export type { McpStartupCompleteEvent } from "./McpStartupCompleteEvent"; -export type { McpStartupFailure } from "./McpStartupFailure"; -export type { McpStartupStatus } from "./McpStartupStatus"; -export type { McpStartupUpdateEvent } from "./McpStartupUpdateEvent"; -export type { McpToolCallBeginEvent } from "./McpToolCallBeginEvent"; -export type { McpToolCallEndEvent } from "./McpToolCallEndEvent"; export type { MessagePhase } from "./MessagePhase"; export type { ModeKind } from "./ModeKind"; -export type { ModelRerouteEvent } from "./ModelRerouteEvent"; -export type { ModelRerouteReason } from "./ModelRerouteReason"; -export type { NetworkAccess } from "./NetworkAccess"; -export type { NetworkApprovalContext } from "./NetworkApprovalContext"; -export type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; export type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; export type { NetworkPolicyRuleAction } from "./NetworkPolicyRuleAction"; -export type { NewConversationParams } from "./NewConversationParams"; -export type { NewConversationResponse } from "./NewConversationResponse"; export type { ParsedCommand } from "./ParsedCommand"; -export type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent"; -export type { PatchApplyEndEvent } from "./PatchApplyEndEvent"; -export type { PatchApplyStatus } from "./PatchApplyStatus"; -export type { PermissionProfile } from "./PermissionProfile"; export type { Personality } from "./Personality"; -export type { PlanDeltaEvent } from "./PlanDeltaEvent"; -export type { PlanItem } from "./PlanItem"; -export type { PlanItemArg } from "./PlanItemArg"; export type { PlanType } from "./PlanType"; -export type { Profile } from "./Profile"; -export type { RateLimitSnapshot } from "./RateLimitSnapshot"; -export type { RateLimitWindow } from "./RateLimitWindow"; -export type { RawResponseItemEvent } from "./RawResponseItemEvent"; -export type { ReadOnlyAccess } from "./ReadOnlyAccess"; -export type { RealtimeAudioFrame } from "./RealtimeAudioFrame"; -export type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent"; -export type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent"; -export type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent"; -export type { RealtimeEvent } from "./RealtimeEvent"; -export type { RealtimeHandoffMessage } from "./RealtimeHandoffMessage"; -export type { RealtimeHandoffRequested } from "./RealtimeHandoffRequested"; -export type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent"; export type { ReasoningEffort } from "./ReasoningEffort"; -export type { ReasoningItem } from "./ReasoningItem"; export type { ReasoningItemContent } from "./ReasoningItemContent"; export type { ReasoningItemReasoningSummary } from "./ReasoningItemReasoningSummary"; -export type { ReasoningRawContentDeltaEvent } from "./ReasoningRawContentDeltaEvent"; export type { ReasoningSummary } from "./ReasoningSummary"; -export type { RejectConfig } from "./RejectConfig"; -export type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent"; -export type { RemoteSkillSummary } from "./RemoteSkillSummary"; -export type { RemoveConversationListenerParams } from "./RemoveConversationListenerParams"; -export type { RemoveConversationSubscriptionResponse } from "./RemoveConversationSubscriptionResponse"; export type { RequestId } from "./RequestId"; -export type { RequestUserInputEvent } from "./RequestUserInputEvent"; -export type { RequestUserInputQuestion } from "./RequestUserInputQuestion"; -export type { RequestUserInputQuestionOption } from "./RequestUserInputQuestionOption"; export type { Resource } from "./Resource"; export type { ResourceTemplate } from "./ResourceTemplate"; export type { ResponseItem } from "./ResponseItem"; -export type { ResumeConversationParams } from "./ResumeConversationParams"; -export type { ResumeConversationResponse } from "./ResumeConversationResponse"; -export type { ReviewCodeLocation } from "./ReviewCodeLocation"; export type { ReviewDecision } from "./ReviewDecision"; -export type { ReviewFinding } from "./ReviewFinding"; -export type { ReviewLineRange } from "./ReviewLineRange"; -export type { ReviewOutputEvent } from "./ReviewOutputEvent"; -export type { ReviewRequest } from "./ReviewRequest"; -export type { ReviewTarget } from "./ReviewTarget"; -export type { SandboxMode } from "./SandboxMode"; -export type { SandboxPolicy } from "./SandboxPolicy"; -export type { SandboxSettings } from "./SandboxSettings"; -export type { SendUserMessageParams } from "./SendUserMessageParams"; -export type { SendUserMessageResponse } from "./SendUserMessageResponse"; -export type { SendUserTurnParams } from "./SendUserTurnParams"; -export type { SendUserTurnResponse } from "./SendUserTurnResponse"; export type { ServerNotification } from "./ServerNotification"; export type { ServerRequest } from "./ServerRequest"; export type { ServiceTier } from "./ServiceTier"; -export type { SessionConfiguredEvent } from "./SessionConfiguredEvent"; -export type { SessionConfiguredNotification } from "./SessionConfiguredNotification"; -export type { SessionNetworkProxyRuntime } from "./SessionNetworkProxyRuntime"; export type { SessionSource } from "./SessionSource"; -export type { SetDefaultModelParams } from "./SetDefaultModelParams"; -export type { SetDefaultModelResponse } from "./SetDefaultModelResponse"; export type { Settings } from "./Settings"; -export type { SkillDependencies } from "./SkillDependencies"; -export type { SkillErrorInfo } from "./SkillErrorInfo"; -export type { SkillInterface } from "./SkillInterface"; -export type { SkillMetadata } from "./SkillMetadata"; -export type { SkillScope } from "./SkillScope"; -export type { SkillToolDependency } from "./SkillToolDependency"; -export type { SkillsListEntry } from "./SkillsListEntry"; -export type { StepStatus } from "./StepStatus"; -export type { StreamErrorEvent } from "./StreamErrorEvent"; export type { SubAgentSource } from "./SubAgentSource"; -export type { TerminalInteractionEvent } from "./TerminalInteractionEvent"; -export type { TextElement } from "./TextElement"; export type { ThreadId } from "./ThreadId"; -export type { ThreadNameUpdatedEvent } from "./ThreadNameUpdatedEvent"; -export type { ThreadRolledBackEvent } from "./ThreadRolledBackEvent"; -export type { TokenCountEvent } from "./TokenCountEvent"; -export type { TokenUsage } from "./TokenUsage"; -export type { TokenUsageInfo } from "./TokenUsageInfo"; export type { Tool } from "./Tool"; -export type { Tools } from "./Tools"; -export type { TurnAbortReason } from "./TurnAbortReason"; -export type { TurnAbortedEvent } from "./TurnAbortedEvent"; -export type { TurnCompleteEvent } from "./TurnCompleteEvent"; -export type { TurnDiffEvent } from "./TurnDiffEvent"; -export type { TurnItem } from "./TurnItem"; -export type { TurnStartedEvent } from "./TurnStartedEvent"; -export type { UndoCompletedEvent } from "./UndoCompletedEvent"; -export type { UndoStartedEvent } from "./UndoStartedEvent"; -export type { UpdatePlanArgs } from "./UpdatePlanArgs"; -export type { UserInfoResponse } from "./UserInfoResponse"; -export type { UserInput } from "./UserInput"; -export type { UserMessageEvent } from "./UserMessageEvent"; -export type { UserMessageItem } from "./UserMessageItem"; -export type { UserSavedConfig } from "./UserSavedConfig"; export type { Verbosity } from "./Verbosity"; -export type { ViewImageToolCallEvent } from "./ViewImageToolCallEvent"; -export type { WarningEvent } from "./WarningEvent"; export type { WebSearchAction } from "./WebSearchAction"; -export type { WebSearchBeginEvent } from "./WebSearchBeginEvent"; -export type { WebSearchEndEvent } from "./WebSearchEndEvent"; -export type { WebSearchItem } from "./WebSearchItem"; export type { WebSearchMode } from "./WebSearchMode"; export * as v2 from "./v2"; diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 78d5507277..2802a87480 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -45,36 +45,9 @@ const SPECIAL_DEFINITIONS: &[&str] = &[ "ServerRequest", ]; const FLAT_V2_SHARED_DEFINITIONS: &[&str] = &["ClientRequest", "EventMsg", "ServerNotification"]; -const V1_CLIENT_REQUEST_METHODS: &[&str] = &[ - "newConversation", - "getConversationSummary", - "listConversations", - "resumeConversation", - "forkConversation", - "archiveConversation", - "sendUserMessage", - "sendUserTurn", - "interruptConversation", - "addConversationListener", - "removeConversationListener", - "gitDiffToRemote", - "loginApiKey", - "loginChatGpt", - "cancelLoginChatGpt", - "logoutChatGpt", - "getAuthStatus", - "getUserSavedConfig", - "setDefaultModel", - "getUserAgent", - "userInfo", - "execOneOffCommand", -]; -const EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON: &[&str] = &[ - "authStatusChange", - "loginChatGptComplete", - "sessionConfigured", - "rawResponseItem/completed", -]; +const V1_CLIENT_REQUEST_METHODS: &[&str] = + &["getConversationSummary", "gitDiffToRemote", "getAuthStatus"]; +const EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON: &[&str] = &["rawResponseItem/completed"]; #[derive(Clone)] pub struct GeneratedSchema { diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index f63ebd37a2..98efcdd290 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -403,95 +403,19 @@ client_request_definitions! { }, /// DEPRECATED APIs below - NewConversation { - params: v1::NewConversationParams, - response: v1::NewConversationResponse, - }, GetConversationSummary { params: v1::GetConversationSummaryParams, response: v1::GetConversationSummaryResponse, }, - /// List recorded Codex conversations (rollouts) with optional pagination and search. - ListConversations { - params: v1::ListConversationsParams, - response: v1::ListConversationsResponse, - }, - /// Resume a recorded Codex conversation from a rollout file. - ResumeConversation { - params: v1::ResumeConversationParams, - response: v1::ResumeConversationResponse, - }, - /// Fork a recorded Codex conversation into a new session. - ForkConversation { - params: v1::ForkConversationParams, - response: v1::ForkConversationResponse, - }, - ArchiveConversation { - params: v1::ArchiveConversationParams, - response: v1::ArchiveConversationResponse, - }, - SendUserMessage { - params: v1::SendUserMessageParams, - response: v1::SendUserMessageResponse, - }, - SendUserTurn { - params: v1::SendUserTurnParams, - response: v1::SendUserTurnResponse, - }, - InterruptConversation { - params: v1::InterruptConversationParams, - response: v1::InterruptConversationResponse, - }, - AddConversationListener { - params: v1::AddConversationListenerParams, - response: v1::AddConversationSubscriptionResponse, - }, - RemoveConversationListener { - params: v1::RemoveConversationListenerParams, - response: v1::RemoveConversationSubscriptionResponse, - }, GitDiffToRemote { params: v1::GitDiffToRemoteParams, response: v1::GitDiffToRemoteResponse, }, - LoginApiKey { - params: v1::LoginApiKeyParams, - response: v1::LoginApiKeyResponse, - }, - LoginChatGpt { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::LoginChatGptResponse, - }, - // DEPRECATED in favor of CancelLoginAccount - CancelLoginChatGpt { - params: v1::CancelLoginChatGptParams, - response: v1::CancelLoginChatGptResponse, - }, - LogoutChatGpt { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::LogoutChatGptResponse, - }, /// DEPRECATED in favor of GetAccount GetAuthStatus { params: v1::GetAuthStatusParams, response: v1::GetAuthStatusResponse, }, - GetUserSavedConfig { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::GetUserSavedConfigResponse, - }, - SetDefaultModel { - params: v1::SetDefaultModelParams, - response: v1::SetDefaultModelResponse, - }, - GetUserAgent { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::GetUserAgentResponse, - }, - UserInfo { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::UserInfoResponse, - }, FuzzyFileSearch { params: FuzzyFileSearchParams, response: FuzzyFileSearchResponse, @@ -511,11 +435,6 @@ client_request_definitions! { params: FuzzyFileSearchSessionStopParams, response: FuzzyFileSearchSessionStopResponse, }, - /// Execute a command (argv vector) under the server's sandbox. - ExecOneOffCommand { - params: v1::ExecOneOffCommandParams, - response: v1::ExecOneOffCommandResponse, - }, } /// Generates an `enum ServerRequest` where each variant is a request that the @@ -882,12 +801,6 @@ server_notification_definitions! { #[strum(serialize = "account/login/completed")] AccountLoginCompleted(v2::AccountLoginCompletedNotification), - /// DEPRECATED NOTIFICATIONS below - AuthStatusChange(v1::AuthStatusChangeNotification), - - /// Deprecated: use `account/login/completed` instead. - LoginChatGptComplete(v1::LoginChatGptCompleteNotification), - SessionConfigured(v1::SessionConfiguredNotification), } client_notification_definitions! { @@ -901,7 +814,6 @@ mod tests { use codex_protocol::ThreadId; use codex_protocol::account::PlanType; use codex_protocol::parse_command::ParsedCommand; - use codex_protocol::protocol::AskForApproval; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use serde_json::json; @@ -912,37 +824,19 @@ mod tests { } #[test] - fn serialize_new_conversation() -> Result<()> { - let request = ClientRequest::NewConversation { + fn serialize_get_conversation_summary() -> Result<()> { + let request = ClientRequest::GetConversationSummary { request_id: RequestId::Integer(42), - params: v1::NewConversationParams { - model: Some("gpt-5.1-codex-max".to_string()), - model_provider: None, - profile: None, - cwd: None, - approval_policy: Some(AskForApproval::OnRequest), - sandbox: None, - config: None, - base_instructions: None, - developer_instructions: None, - compact_prompt: None, - include_apply_patch_tool: None, + params: v1::GetConversationSummaryParams::ThreadId { + conversation_id: ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8")?, }, }; assert_eq!( json!({ - "method": "newConversation", + "method": "getConversationSummary", "id": 42, "params": { - "model": "gpt-5.1-codex-max", - "modelProvider": null, - "profile": null, - "cwd": null, - "approvalPolicy": "on-request", - "sandbox": null, - "config": null, - "baseInstructions": null, - "includeApplyPatchTool": null + "conversationId": "67e55044-10b1-426f-9247-bb680e5fe0c8" } }), serde_json::to_value(&request)?, diff --git a/codex-rs/app-server-protocol/src/protocol/v1.rs b/codex-rs/app-server-protocol/src/protocol/v1.rs index ed1ca86229..d393f97f72 100644 --- a/codex-rs/app-server-protocol/src/protocol/v1.rs +++ b/codex-rs/app-server-protocol/src/protocol/v1.rs @@ -596,34 +596,3 @@ impl InputItem { } } } - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -/// Deprecated in favor of AccountLoginCompletedNotification. -pub struct LoginChatGptCompleteNotification { - #[schemars(with = "String")] - pub login_id: Uuid, - pub success: bool, - pub error: Option, -} - -#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -pub struct SessionConfiguredNotification { - pub session_id: ThreadId, - pub model: String, - pub service_tier: Option, - pub reasoning_effort: Option, - pub history_log_id: u64, - #[ts(type = "number")] - pub history_entry_count: usize, - pub initial_messages: Option>, - pub rollout_path: PathBuf, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -/// Deprecated notification. Use AccountUpdatedNotification instead. -pub struct AuthStatusChangeNotification { - pub auth_method: Option, -} diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index d8f06be421..7baad9be66 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -23,8 +23,7 @@ use anyhow::bail; use clap::ArgAction; use clap::Parser; use clap::Subcommand; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; +use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientRequest; @@ -40,22 +39,16 @@ use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::InitializeParams; use codex_app_server_protocol::InitializeResponse; -use codex_app_server_protocol::InputItem; use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCRequest; use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginChatGptCompleteNotification; -use codex_app_server_protocol::LoginChatGptResponse; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; use codex_app_server_protocol::ReadOnlyAccess; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SandboxPolicy; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::ThreadItem; @@ -69,9 +62,6 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as V2UserInput; -use codex_protocol::ThreadId; -use codex_protocol::protocol::Event; -use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::W3cTraceContext; use serde::Serialize; use serde::de::DeserializeOwned; @@ -502,26 +492,16 @@ fn send_message( config_overrides: &[String], user_message: String, ) -> Result<()> { - with_client(endpoint, config_overrides, |client| { - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); - - let conversation = client.start_thread()?; - println!("< newConversation response: {conversation:?}"); - - let subscription = client.add_conversation_listener(&conversation.conversation_id)?; - println!("< addConversationListener response: {subscription:?}"); - - let send_response = - client.send_user_message(&conversation.conversation_id, &user_message)?; - println!("< sendUserMessage response: {send_response:?}"); - - client.stream_conversation(&conversation.conversation_id)?; - - client.remove_thread_listener(subscription.subscription_id)?; - - Ok(()) - }) + let dynamic_tools = None; + send_message_v2_with_policies( + endpoint, + config_overrides, + user_message, + false, + None, + None, + &dynamic_tools, + ) } pub fn send_message_v2( @@ -877,15 +857,15 @@ fn test_login(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { let initialize = client.initialize()?; println!("< initialize response: {initialize:?}"); - let login_response = client.login_chat_gpt()?; - println!("< loginChatGpt response: {login_response:?}"); - println!( - "Open the following URL in your browser to continue:\n{}", - login_response.auth_url - ); + let login_response = client.login_account_chatgpt()?; + println!("< account/login/start response: {login_response:?}"); + let LoginAccountResponse::Chatgpt { login_id, auth_url } = login_response else { + bail!("expected chatgpt login response"); + }; + println!("Open the following URL in your browser to continue:\n{auth_url}"); - let completion = client.wait_for_login_completion(&login_response.login_id)?; - println!("< loginChatGptComplete notification: {completion:?}"); + let completion = client.wait_for_account_login_completion(&login_id)?; + println!("< account/login/completed notification: {completion:?}"); if completion.success { println!("Login succeeded."); @@ -896,7 +876,7 @@ fn test_login(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { completion .error .as_deref() - .unwrap_or("unknown error from loginChatGptComplete") + .unwrap_or("unknown error from account/login/completed") ); } }) @@ -1142,69 +1122,6 @@ impl CodexClient { Ok(response) } - fn start_thread(&mut self) -> Result { - let request_id = self.request_id(); - let request = ClientRequest::NewConversation { - request_id: request_id.clone(), - params: NewConversationParams::default(), - }; - - self.send_request(request, request_id, "newConversation") - } - - fn add_conversation_listener( - &mut self, - conversation_id: &ThreadId, - ) -> Result { - let request_id = self.request_id(); - let request = ClientRequest::AddConversationListener { - request_id: request_id.clone(), - params: AddConversationListenerParams { - conversation_id: *conversation_id, - experimental_raw_events: false, - }, - }; - - self.send_request(request, request_id, "addConversationListener") - } - - fn remove_thread_listener(&mut self, subscription_id: Uuid) -> Result<()> { - let request_id = self.request_id(); - let request = ClientRequest::RemoveConversationListener { - request_id: request_id.clone(), - params: codex_app_server_protocol::RemoveConversationListenerParams { subscription_id }, - }; - - self.send_request::( - request, - request_id, - "removeConversationListener", - )?; - - Ok(()) - } - - fn send_user_message( - &mut self, - conversation_id: &ThreadId, - message: &str, - ) -> Result { - let request_id = self.request_id(); - let request = ClientRequest::SendUserMessage { - request_id: request_id.clone(), - params: SendUserMessageParams { - conversation_id: *conversation_id, - items: vec![InputItem::Text { - text: message.to_string(), - // Test client sends plain text without UI element ranges. - text_elements: Vec::new(), - }], - }, - }; - - self.send_request(request, request_id, "sendUserMessage") - } - fn thread_start(&mut self, params: ThreadStartParams) -> Result { let request_id = self.request_id(); let request = ClientRequest::ThreadStart { @@ -1235,14 +1152,14 @@ impl CodexClient { self.send_request(request, request_id, "turn/start") } - fn login_chat_gpt(&mut self) -> Result { + fn login_account_chatgpt(&mut self) -> Result { let request_id = self.request_id(); - let request = ClientRequest::LoginChatGpt { + let request = ClientRequest::LoginAccount { request_id: request_id.clone(), - params: None, + params: codex_app_server_protocol::LoginAccountParams::Chatgpt, }; - self.send_request(request, request_id, "loginChatGpt") + self.send_request(request, request_id, "account/login/start") } fn get_account_rate_limits(&mut self) -> Result { @@ -1275,77 +1192,31 @@ impl CodexClient { self.send_request(request, request_id, "thread/list") } - fn stream_conversation(&mut self, conversation_id: &ThreadId) -> Result<()> { - loop { - let notification = self.next_notification()?; - - if !notification.method.starts_with("codex/event/") { - continue; - } - - if let Some(event) = self.extract_event(notification, conversation_id)? { - match &event.msg { - EventMsg::AgentMessage(event) => { - println!("{}", event.message); - } - EventMsg::AgentMessageDelta(event) => { - print!("{}", event.delta); - std::io::stdout().flush().ok(); - } - EventMsg::TurnComplete(event) => { - println!("\n[task complete: {event:?}]"); - break; - } - EventMsg::TurnAborted(event) => { - println!("\n[turn aborted: {:?}]", event.reason); - break; - } - EventMsg::Error(event) => { - println!("[error] {event:?}"); - } - _ => { - println!("[UNKNOWN EVENT] {:?}", event.msg); - } - } - } - } - - Ok(()) - } - - fn wait_for_login_completion( + fn wait_for_account_login_completion( &mut self, - expected_login_id: &Uuid, - ) -> Result { + expected_login_id: &str, + ) -> Result { loop { let notification = self.next_notification()?; if let Ok(server_notification) = ServerNotification::try_from(notification) { match server_notification { - ServerNotification::LoginChatGptComplete(completion) => { - if &completion.login_id == expected_login_id { + ServerNotification::AccountLoginCompleted(completion) => { + if completion.login_id.as_deref() == Some(expected_login_id) { return Ok(completion); } println!( - "[ignoring loginChatGptComplete for unexpected login_id: {}]", + "[ignoring account/login/completed for unexpected login_id: {:?}]", completion.login_id ); } - ServerNotification::AuthStatusChange(status) => { - println!("< authStatusChange notification: {status:?}"); - } ServerNotification::AccountRateLimitsUpdated(snapshot) => { println!("< accountRateLimitsUpdated notification: {snapshot:?}"); } - ServerNotification::SessionConfigured(_) => { - // SessionConfigured notifications are unrelated to login; skip. - } _ => {} } } - - // Not a server notification (likely a conversation event); keep waiting. } } @@ -1419,36 +1290,6 @@ impl CodexClient { } } - fn extract_event( - &self, - notification: JSONRPCNotification, - conversation_id: &ThreadId, - ) -> Result> { - let params = notification - .params - .context("event notification missing params")?; - - let mut map = match params { - Value::Object(map) => map, - other => bail!("unexpected params shape: {other:?}"), - }; - - let conversation_value = map - .remove("conversationId") - .context("event missing conversationId")?; - let notification_conversation: ThreadId = serde_json::from_value(conversation_value) - .context("conversationId was not a valid UUID")?; - - if ¬ification_conversation != conversation_id { - return Ok(None); - } - - let event_value = Value::Object(map); - let event: Event = - serde_json::from_value(event_value).context("failed to decode event payload")?; - Ok(Some(event)) - } - fn send_request( &mut self, request: ClientRequest, diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 3efc7140af..ba2355f675 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -65,11 +65,9 @@ axum = { workspace = true, default-features = false, features = [ "tokio", ] } base64 = { workspace = true } -codex-execpolicy = { workspace = true } core_test_support = { workspace = true } codex-state = { workspace = true } codex-utils-cargo-bin = { workspace = true } -os_info = { workspace = true } pretty_assertions = { workspace = true } rmcp = { workspace = true, default-features = false, features = [ "server", diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index ca9eb374c6..1c18345559 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -20,21 +20,15 @@ use chrono::Utc; use codex_app_server_protocol::Account; use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AccountUpdatedNotification; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; use codex_app_server_protocol::AppInfo; use codex_app_server_protocol::AppListUpdatedNotification; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::ArchiveConversationParams; -use codex_app_server_protocol::ArchiveConversationResponse; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::AuthMode; -use codex_app_server_protocol::AuthStatusChangeNotification; use codex_app_server_protocol::CancelLoginAccountParams; use codex_app_server_protocol::CancelLoginAccountResponse; use codex_app_server_protocol::CancelLoginAccountStatus; -use codex_app_server_protocol::CancelLoginChatGptResponse; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::CollaborationModeListParams; use codex_app_server_protocol::CollaborationModeListResponse; @@ -49,8 +43,6 @@ use codex_app_server_protocol::ExperimentalFeatureListResponse; use codex_app_server_protocol::ExperimentalFeatureStage as ApiExperimentalFeatureStage; use codex_app_server_protocol::FeedbackUploadParams; use codex_app_server_protocol::FeedbackUploadResponse; -use codex_app_server_protocol::ForkConversationParams; -use codex_app_server_protocol::ForkConversationResponse; use codex_app_server_protocol::FuzzyFileSearchParams; use codex_app_server_protocol::FuzzyFileSearchResponse; use codex_app_server_protocol::FuzzyFileSearchSessionStartParams; @@ -66,26 +58,16 @@ use codex_app_server_protocol::GetAuthStatusParams; use codex_app_server_protocol::GetAuthStatusResponse; use codex_app_server_protocol::GetConversationSummaryParams; use codex_app_server_protocol::GetConversationSummaryResponse; -use codex_app_server_protocol::GetUserAgentResponse; -use codex_app_server_protocol::GetUserSavedConfigResponse; use codex_app_server_protocol::GitDiffToRemoteResponse; use codex_app_server_protocol::GitInfo as ApiGitInfo; use codex_app_server_protocol::HazelnutScope as ApiHazelnutScope; -use codex_app_server_protocol::InputItem as WireInputItem; -use codex_app_server_protocol::InterruptConversationParams; use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::ListConversationsParams; -use codex_app_server_protocol::ListConversationsResponse; use codex_app_server_protocol::ListMcpServerStatusParams; use codex_app_server_protocol::ListMcpServerStatusResponse; use codex_app_server_protocol::LoginAccountParams; use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::LoginApiKeyParams; -use codex_app_server_protocol::LoginApiKeyResponse; -use codex_app_server_protocol::LoginChatGptCompleteNotification; -use codex_app_server_protocol::LoginChatGptResponse; use codex_app_server_protocol::LogoutAccountResponse; -use codex_app_server_protocol::LogoutChatGptResponse; use codex_app_server_protocol::McpServerOauthLoginCompletedNotification; use codex_app_server_protocol::McpServerOauthLoginParams; use codex_app_server_protocol::McpServerOauthLoginResponse; @@ -95,28 +77,15 @@ use codex_app_server_protocol::MockExperimentalMethodParams; use codex_app_server_protocol::MockExperimentalMethodResponse; use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; use codex_app_server_protocol::ProductSurface as ApiProductSurface; -use codex_app_server_protocol::RemoveConversationListenerParams; -use codex_app_server_protocol::RemoveConversationSubscriptionResponse; use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ResumeConversationParams; -use codex_app_server_protocol::ResumeConversationResponse; use codex_app_server_protocol::ReviewDelivery as ApiReviewDelivery; use codex_app_server_protocol::ReviewStartParams; use codex_app_server_protocol::ReviewStartResponse; use codex_app_server_protocol::ReviewTarget as ApiReviewTarget; use codex_app_server_protocol::SandboxMode; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_app_server_protocol::SendUserTurnParams; -use codex_app_server_protocol::SendUserTurnResponse; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestResolvedNotification; -use codex_app_server_protocol::SessionConfiguredNotification; -use codex_app_server_protocol::SetDefaultModelParams; -use codex_app_server_protocol::SetDefaultModelResponse; use codex_app_server_protocol::SkillsConfigWriteParams; use codex_app_server_protocol::SkillsConfigWriteResponse; use codex_app_server_protocol::SkillsListParams; @@ -176,9 +145,7 @@ use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::TurnSteerParams; use codex_app_server_protocol::TurnSteerResponse; -use codex_app_server_protocol::UserInfoResponse; use codex_app_server_protocol::UserInput as V2UserInput; -use codex_app_server_protocol::UserSavedConfig; use codex_app_server_protocol::WindowsSandboxSetupCompletedNotification; use codex_app_server_protocol::WindowsSandboxSetupMode; use codex_app_server_protocol::WindowsSandboxSetupStartParams; @@ -205,13 +172,11 @@ use codex_core::auth::login_with_api_key; use codex_core::auth::login_with_chatgpt_auth_tokens; use codex_core::config::Config; use codex_core::config::ConfigOverrides; -use codex_core::config::ConfigService; use codex_core::config::NetworkProxyAuditMetadata; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::types::McpServerTransportConfig; use codex_core::config_loader::CloudRequirementsLoader; -use codex_core::default_client::get_codex_user_agent; use codex_core::default_client::set_default_client_residency_requirement; use codex_core::error::CodexErr; use codex_core::exec::ExecParams; @@ -330,7 +295,7 @@ struct ActiveLogin { #[derive(Clone, Copy, Debug)] enum CancelLoginError { - NotFound(Uuid), + NotFound, } enum AppListLoadResult { @@ -389,6 +354,7 @@ pub(crate) struct CodexMessageProcessor { #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub(crate) enum ApiVersion { + #[allow(dead_code)] V1, #[default] V2, @@ -718,21 +684,10 @@ impl CodexMessageProcessor { self.review_start(to_connection_request_id(request_id), params) .await; } - ClientRequest::NewConversation { request_id, params } => { - // Do not tokio::spawn() to process new_conversation() - // asynchronously because we need to ensure the conversation is - // created before processing any subsequent messages. - self.process_new_conversation(to_connection_request_id(request_id), params) - .await; - } ClientRequest::GetConversationSummary { request_id, params } => { self.get_thread_summary(to_connection_request_id(request_id), params) .await; } - ClientRequest::ListConversations { request_id, params } => { - self.handle_list_conversations(to_connection_request_id(request_id), params) - .await; - } ClientRequest::ModelList { request_id, params } => { let outgoing = self.outgoing.clone(); let thread_manager = self.thread_manager.clone(); @@ -794,100 +749,14 @@ impl CodexMessageProcessor { self.get_account(to_connection_request_id(request_id), params) .await; } - ClientRequest::ResumeConversation { request_id, params } => { - self.handle_resume_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::ForkConversation { request_id, params } => { - self.handle_fork_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::ArchiveConversation { request_id, params } => { - self.archive_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::SendUserMessage { request_id, params } => { - self.send_user_message( - to_connection_request_id(request_id), - params, - app_server_client_name.clone(), - ) - .await; - } - ClientRequest::SendUserTurn { request_id, params } => { - self.send_user_turn( - to_connection_request_id(request_id), - params, - app_server_client_name.clone(), - ) - .await; - } - ClientRequest::InterruptConversation { request_id, params } => { - self.interrupt_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::AddConversationListener { request_id, params } => { - self.add_conversation_listener(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::RemoveConversationListener { request_id, params } => { - self.remove_thread_listener(to_connection_request_id(request_id), params) - .await; - } ClientRequest::GitDiffToRemote { request_id, params } => { self.git_diff_to_origin(to_connection_request_id(request_id), params.cwd) .await; } - ClientRequest::LoginApiKey { request_id, params } => { - self.login_api_key_v1(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::LoginChatGpt { - request_id, - params: _, - } => { - self.login_chatgpt_v1(to_connection_request_id(request_id)) - .await; - } - ClientRequest::CancelLoginChatGpt { request_id, params } => { - self.cancel_login_chatgpt(to_connection_request_id(request_id), params.login_id) - .await; - } - ClientRequest::LogoutChatGpt { - request_id, - params: _, - } => { - self.logout_v1(to_connection_request_id(request_id)).await; - } ClientRequest::GetAuthStatus { request_id, params } => { self.get_auth_status(to_connection_request_id(request_id), params) .await; } - ClientRequest::GetUserSavedConfig { - request_id, - params: _, - } => { - self.get_user_saved_config(to_connection_request_id(request_id)) - .await; - } - ClientRequest::SetDefaultModel { request_id, params } => { - self.set_default_model(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::GetUserAgent { - request_id, - params: _, - } => { - self.get_user_agent(to_connection_request_id(request_id)) - .await; - } - ClientRequest::UserInfo { - request_id, - params: _, - } => { - self.get_user_info(to_connection_request_id(request_id)) - .await; - } ClientRequest::FuzzyFileSearch { request_id, params } => { self.fuzzy_file_search(to_connection_request_id(request_id), params) .await; @@ -908,10 +777,6 @@ impl CodexMessageProcessor { self.exec_one_off_command(to_connection_request_id(request_id), params) .await; } - ClientRequest::ExecOneOffCommand { request_id, params } => { - self.exec_one_off_command(to_connection_request_id(request_id), params.into()) - .await; - } ClientRequest::ConfigRead { .. } | ClientRequest::ConfigValueWrite { .. } | ClientRequest::ConfigBatchWrite { .. } => { @@ -1016,34 +881,6 @@ impl CodexMessageProcessor { } } - async fn login_api_key_v1( - &mut self, - request_id: ConnectionRequestId, - params: LoginApiKeyParams, - ) { - match self.login_api_key_common(¶ms).await { - Ok(()) => { - self.outgoing - .send_response(request_id, LoginApiKeyResponse {}) - .await; - - let payload = AuthStatusChangeNotification { - auth_method: self - .auth_manager - .auth_cached() - .as_ref() - .map(CodexAuth::api_auth_mode), - }; - self.outgoing - .send_server_notification(ServerNotification::AuthStatusChange(payload)) - .await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn login_api_key_v2( &mut self, request_id: ConnectionRequestId, @@ -1106,115 +943,6 @@ impl CodexMessageProcessor { }) } - // Deprecated in favor of login_chatgpt_v2. - async fn login_chatgpt_v1(&mut self, request_id: ConnectionRequestId) { - match self.login_chatgpt_common().await { - Ok(opts) => match run_login_server(opts) { - Ok(server) => { - let login_id = Uuid::new_v4(); - let shutdown_handle = server.cancel_handle(); - - // Replace active login if present. - { - let mut guard = self.active_login.lock().await; - if let Some(existing) = guard.take() { - drop(existing); - } - *guard = Some(ActiveLogin { - shutdown_handle: shutdown_handle.clone(), - login_id, - }); - } - - // Spawn background task to monitor completion. - let outgoing_clone = self.outgoing.clone(); - let active_login = self.active_login.clone(); - let auth_manager = self.auth_manager.clone(); - let cloud_requirements = self.cloud_requirements.clone(); - let chatgpt_base_url = self.config.chatgpt_base_url.clone(); - let codex_home = self.config.codex_home.clone(); - let cli_overrides = self.cli_overrides.clone(); - let auth_url = server.auth_url.clone(); - tokio::spawn(async move { - let (success, error_msg) = match tokio::time::timeout( - LOGIN_CHATGPT_TIMEOUT, - server.block_until_done(), - ) - .await - { - Ok(Ok(())) => (true, None), - Ok(Err(err)) => (false, Some(format!("Login server error: {err}"))), - Err(_elapsed) => { - shutdown_handle.shutdown(); - (false, Some("Login timed out".to_string())) - } - }; - - let payload = LoginChatGptCompleteNotification { - login_id, - success, - error: error_msg.clone(), - }; - outgoing_clone - .send_server_notification(ServerNotification::LoginChatGptComplete( - payload, - )) - .await; - - if success { - auth_manager.reload(); - replace_cloud_requirements_loader( - cloud_requirements.as_ref(), - auth_manager.clone(), - chatgpt_base_url, - codex_home, - ); - sync_default_client_residency_requirement( - &cli_overrides, - cloud_requirements.as_ref(), - ) - .await; - - // Notify clients with the actual current auth mode. - let current_auth_method = auth_manager - .auth_cached() - .as_ref() - .map(CodexAuth::api_auth_mode); - let payload = AuthStatusChangeNotification { - auth_method: current_auth_method, - }; - outgoing_clone - .send_server_notification(ServerNotification::AuthStatusChange( - payload, - )) - .await; - } - - // Clear the active login if it matches this attempt. It may have been replaced or cancelled. - let mut guard = active_login.lock().await; - if guard.as_ref().map(|l| l.login_id) == Some(login_id) { - *guard = None; - } - }); - - let response = LoginChatGptResponse { login_id, auth_url }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to start login server: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - }, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - } - } - } - async fn login_chatgpt_v2(&mut self, request_id: ConnectionRequestId) { match self.login_chatgpt_common().await { Ok(opts) => match run_login_server(opts) { @@ -1335,25 +1063,7 @@ impl CodexMessageProcessor { } Ok(()) } else { - Err(CancelLoginError::NotFound(login_id)) - } - } - - async fn cancel_login_chatgpt(&mut self, request_id: ConnectionRequestId, login_id: Uuid) { - match self.cancel_login_chatgpt_common(login_id).await { - Ok(()) => { - self.outgoing - .send_response(request_id, CancelLoginChatGptResponse {}) - .await; - } - Err(CancelLoginError::NotFound(missing_login_id)) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("login id not found: {missing_login_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } + Err(CancelLoginError::NotFound) } } @@ -1367,7 +1077,7 @@ impl CodexMessageProcessor { Ok(uuid) => { let status = match self.cancel_login_chatgpt_common(uuid).await { Ok(()) => CancelLoginAccountStatus::Canceled, - Err(CancelLoginError::NotFound(_)) => CancelLoginAccountStatus::NotFound, + Err(CancelLoginError::NotFound) => CancelLoginAccountStatus::NotFound, }; let response = CancelLoginAccountResponse { status }; self.outgoing.send_response(request_id, response).await; @@ -1500,26 +1210,6 @@ impl CodexMessageProcessor { .map(CodexAuth::api_auth_mode)) } - async fn logout_v1(&mut self, request_id: ConnectionRequestId) { - match self.logout_common().await { - Ok(current_auth_method) => { - self.outgoing - .send_response(request_id, LogoutChatGptResponse {}) - .await; - - let payload = AuthStatusChangeNotification { - auth_method: current_auth_method, - }; - self.outgoing - .send_server_notification(ServerNotification::AuthStatusChange(payload)) - .await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn logout_v2(&mut self, request_id: ConnectionRequestId) { match self.logout_common().await { Ok(current_auth_method) => { @@ -1651,12 +1341,6 @@ impl CodexMessageProcessor { self.outgoing.send_response(request_id, response).await; } - async fn get_user_agent(&self, request_id: ConnectionRequestId) { - let user_agent = get_codex_user_agent(); - let response = GetUserAgentResponse { user_agent }; - self.outgoing.send_response(request_id, response).await; - } - async fn get_account_rate_limits(&self, request_id: ConnectionRequestId) { match self.fetch_account_rate_limits().await { Ok((rate_limits, rate_limits_by_limit_id)) => { @@ -1746,69 +1430,6 @@ impl CodexMessageProcessor { Ok((primary, rate_limits_by_limit_id)) } - async fn get_user_saved_config(&self, request_id: ConnectionRequestId) { - let service = ConfigService::new_with_defaults(self.config.codex_home.clone()); - let user_saved_config: UserSavedConfig = match service.load_user_saved_config().await { - Ok(config) => config, - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: err.to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let response = GetUserSavedConfigResponse { - config: user_saved_config, - }; - self.outgoing.send_response(request_id, response).await; - } - - async fn get_user_info(&self, request_id: ConnectionRequestId) { - // Read alleged user email from cached auth (best-effort; not verified). - let alleged_user_email = self - .auth_manager - .auth_cached() - .and_then(|a| a.get_account_email()); - - let response = UserInfoResponse { alleged_user_email }; - self.outgoing.send_response(request_id, response).await; - } - - async fn set_default_model( - &self, - request_id: ConnectionRequestId, - params: SetDefaultModelParams, - ) { - let SetDefaultModelParams { - model, - reasoning_effort, - } = params; - - match ConfigEditsBuilder::new(&self.config.codex_home) - .with_profile(self.config.active_profile.as_deref()) - .set_model(model.as_deref(), reasoning_effort) - .apply() - .await - { - Ok(()) => { - let response = SetDefaultModelResponse {}; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to persist model selection: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn exec_one_off_command( &self, request_id: ConnectionRequestId, @@ -1930,119 +1551,6 @@ impl CodexMessageProcessor { }); } - async fn process_new_conversation( - &mut self, - request_id: ConnectionRequestId, - params: NewConversationParams, - ) { - let NewConversationParams { - model, - model_provider, - profile, - cwd, - approval_policy, - sandbox: sandbox_mode, - config: request_overrides, - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - } = params; - - let typesafe_overrides = ConfigOverrides { - model, - config_profile: profile, - cwd: cwd.clone().map(PathBuf::from), - approval_policy, - sandbox_mode, - model_provider, - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - ..Default::default() - }; - - // Persist Windows sandbox mode. - // TODO: persist default config in general. - let mut request_overrides = request_overrides.unwrap_or_default(); - if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { - WindowsSandboxLevel::Elevated => { - request_overrides - .insert("windows.sandbox".to_string(), serde_json::json!("elevated")); - } - WindowsSandboxLevel::RestrictedToken => { - request_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("unelevated"), - ); - } - WindowsSandboxLevel::Disabled => {} - } - } - - let cloud_requirements = self.current_cloud_requirements(); - let config = match derive_config_from_params( - &self.cli_overrides, - Some(request_overrides), - typesafe_overrides, - &cloud_requirements, - ) - .await - { - Ok(config) => config, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("error deriving config: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - match self.thread_manager.start_thread(config).await { - Ok(new_thread) => { - let NewThread { - thread_id, - session_configured, - .. - } = new_thread; - let rollout_path = match session_configured.rollout_path { - Some(path) => path, - None => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "rollout path missing for v1 conversation".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - let response = NewConversationResponse { - conversation_id: thread_id, - model: session_configured.model, - reasoning_effort: session_configured.reasoning_effort, - rollout_path, - }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("error creating conversation: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn thread_start(&self, request_id: ConnectionRequestId, params: ThreadStartParams) { let ThreadStartParams { model, @@ -3814,45 +3322,6 @@ impl CodexMessageProcessor { } } - async fn handle_list_conversations( - &self, - request_id: ConnectionRequestId, - params: ListConversationsParams, - ) { - let ListConversationsParams { - page_size, - cursor, - model_providers, - } = params; - let requested_page_size = page_size - .unwrap_or(THREAD_LIST_DEFAULT_LIMIT) - .clamp(1, THREAD_LIST_MAX_LIMIT); - - match self - .list_threads_common( - requested_page_size, - cursor, - CoreThreadSortKey::UpdatedAt, - ThreadListFilters { - model_providers, - source_kinds: None, - archived: false, - cwd: None, - search_term: None, - }, - ) - .await - { - Ok((items, next_cursor)) => { - let response = ListConversationsResponse { items, next_cursor }; - self.outgoing.send_response(request_id, response).await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - }; - } - async fn list_threads_common( &self, requested_page_size: usize, @@ -4453,440 +3922,6 @@ impl CodexMessageProcessor { outgoing.send_response(request_id, response).await; } - async fn handle_resume_conversation( - &self, - request_id: ConnectionRequestId, - params: ResumeConversationParams, - ) { - let ResumeConversationParams { - path, - conversation_id, - history, - overrides, - } = params; - - let thread_history = if let Some(path) = path { - match RolloutRecorder::get_rollout_history(&path).await { - Ok(initial_history) => initial_history, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to load rollout `{}`: {err}", path.display()), - ) - .await; - return; - } - } - } else if let Some(conversation_id) = conversation_id { - match find_thread_path_by_id_str(&self.config.codex_home, &conversation_id.to_string()) - .await - { - Ok(Some(found_path)) => { - match RolloutRecorder::get_rollout_history(&found_path).await { - Ok(initial_history) => initial_history, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!( - "failed to load rollout `{}` for conversation {conversation_id}: {err}", - found_path.display() - ), - ).await; - return; - } - } - } - Ok(None) => { - self.send_invalid_request_error( - request_id, - format!("no rollout found for conversation id {conversation_id}"), - ) - .await; - return; - } - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to locate conversation id {conversation_id}: {err}"), - ) - .await; - return; - } - } - } else { - match history { - Some(history) if !history.is_empty() => InitialHistory::Forked( - history.into_iter().map(RolloutItem::ResponseItem).collect(), - ), - Some(_) | None => { - self.send_invalid_request_error( - request_id, - "either path, conversation id or non empty history must be provided" - .to_string(), - ) - .await; - return; - } - } - }; - - let history_cwd = thread_history.session_cwd(); - let (typesafe_overrides, request_overrides) = match overrides { - Some(overrides) => { - let NewConversationParams { - model, - model_provider, - profile, - cwd, - approval_policy, - sandbox: sandbox_mode, - config: request_overrides, - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - } = overrides; - - // Persist Windows sandbox mode. - let mut request_overrides = request_overrides.unwrap_or_default(); - if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { - WindowsSandboxLevel::Elevated => { - request_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("elevated"), - ); - } - WindowsSandboxLevel::RestrictedToken => { - request_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("unelevated"), - ); - } - WindowsSandboxLevel::Disabled => {} - } - } - - let typesafe_overrides = ConfigOverrides { - model, - config_profile: profile, - cwd: cwd.map(PathBuf::from), - approval_policy, - sandbox_mode, - model_provider, - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - ..Default::default() - }; - (typesafe_overrides, Some(request_overrides)) - } - None => ( - ConfigOverrides { - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - ..Default::default() - }, - None, - ), - }; - - let cloud_requirements = self.current_cloud_requirements(); - let config = match derive_config_for_cwd( - &self.cli_overrides, - request_overrides, - typesafe_overrides, - history_cwd, - &cloud_requirements, - ) - .await - { - Ok(cfg) => cfg, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("error deriving config: {err}"), - ) - .await; - return; - } - }; - - match self - .thread_manager - .resume_thread_with_history(config, thread_history, self.auth_manager.clone(), false) - .await - { - Ok(NewThread { - thread_id, - session_configured, - .. - }) => { - let rollout_path = match session_configured.rollout_path.clone() { - Some(path) => path, - None => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "rollout path missing for resumed conversation".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - self.outgoing - .send_server_notification(ServerNotification::SessionConfigured( - SessionConfiguredNotification { - session_id: session_configured.session_id, - model: session_configured.model.clone(), - service_tier: session_configured.service_tier, - reasoning_effort: session_configured.reasoning_effort, - history_log_id: session_configured.history_log_id, - history_entry_count: session_configured.history_entry_count, - initial_messages: session_configured.initial_messages.clone(), - rollout_path: rollout_path.clone(), - }, - )) - .await; - let initial_messages = session_configured - .initial_messages - .map(|msgs| msgs.into_iter().collect()); - - // Reply with thread id + model and initial messages (when present) - let response = ResumeConversationResponse { - conversation_id: thread_id, - model: session_configured.model.clone(), - initial_messages, - rollout_path, - }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("error resuming conversation: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - - async fn handle_fork_conversation( - &self, - request_id: ConnectionRequestId, - params: ForkConversationParams, - ) { - let ForkConversationParams { - path, - conversation_id, - overrides, - } = params; - - // Derive a Config using the same logic as new conversation, honoring overrides if provided. - let (rollout_path, source_thread_id) = if let Some(path) = path { - (path, None) - } else if let Some(conversation_id) = conversation_id { - match find_thread_path_by_id_str(&self.config.codex_home, &conversation_id.to_string()) - .await - { - Ok(Some(found_path)) => (found_path, Some(conversation_id)), - Ok(None) => { - self.send_invalid_request_error( - request_id, - format!("no rollout found for conversation id {conversation_id}"), - ) - .await; - return; - } - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to locate conversation id {conversation_id}: {err}"), - ) - .await; - return; - } - } - } else { - self.send_invalid_request_error( - request_id, - "either path or conversation id must be provided".to_string(), - ) - .await; - return; - }; - - let history_cwd = - read_history_cwd_from_state_db(&self.config, source_thread_id, rollout_path.as_path()) - .await; - - let (typesafe_overrides, request_overrides) = match overrides { - Some(overrides) => { - let NewConversationParams { - model, - model_provider, - profile, - cwd, - approval_policy, - sandbox: sandbox_mode, - config: cli_overrides, - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - } = overrides; - - // Persist Windows sandbox mode. - let mut cli_overrides = cli_overrides.unwrap_or_default(); - if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { - WindowsSandboxLevel::Elevated => { - cli_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("elevated"), - ); - } - WindowsSandboxLevel::RestrictedToken => { - cli_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("unelevated"), - ); - } - WindowsSandboxLevel::Disabled => {} - } - } - let request_overrides = if cli_overrides.is_empty() { - None - } else { - Some(cli_overrides) - }; - - let overrides = ConfigOverrides { - model, - config_profile: profile, - cwd: cwd.map(PathBuf::from), - approval_policy, - sandbox_mode, - model_provider, - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - ..Default::default() - }; - - (overrides, request_overrides) - } - None => ( - ConfigOverrides { - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - ..Default::default() - }, - None, - ), - }; - - let cloud_requirements = self.current_cloud_requirements(); - let config = match derive_config_for_cwd( - &self.cli_overrides, - request_overrides, - typesafe_overrides, - history_cwd, - &cloud_requirements, - ) - .await - { - Ok(cfg) => cfg, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("error deriving config: {err}"), - ) - .await; - return; - } - }; - - let NewThread { - thread_id, - session_configured, - .. - } = match self - .thread_manager - .fork_thread(usize::MAX, config, rollout_path.clone(), false) - .await - { - Ok(thread) => thread, - Err(err) => { - let (code, message) = match err { - CodexErr::Io(_) | CodexErr::Json(_) => ( - INVALID_REQUEST_ERROR_CODE, - format!("failed to load rollout `{}`: {err}", rollout_path.display()), - ), - CodexErr::InvalidRequest(message) => (INVALID_REQUEST_ERROR_CODE, message), - _ => ( - INTERNAL_ERROR_CODE, - format!("error forking conversation: {err}"), - ), - }; - let error = JSONRPCErrorError { - code, - message, - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let rollout_path = match session_configured.rollout_path.clone() { - Some(path) => path, - None => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "rollout path missing for forked conversation".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - self.outgoing - .send_server_notification(ServerNotification::SessionConfigured( - SessionConfiguredNotification { - session_id: session_configured.session_id, - model: session_configured.model.clone(), - service_tier: session_configured.service_tier, - reasoning_effort: session_configured.reasoning_effort, - history_log_id: session_configured.history_log_id, - history_entry_count: session_configured.history_entry_count, - initial_messages: session_configured.initial_messages.clone(), - rollout_path: rollout_path.clone(), - }, - )) - .await; - let initial_messages = session_configured - .initial_messages - .map(|msgs| msgs.into_iter().collect()); - - // Reply with conversation id + model and initial messages (when present) - let response = ForkConversationResponse { - conversation_id: thread_id, - model: session_configured.model.clone(), - initial_messages, - rollout_path, - }; - self.outgoing.send_response(request_id, response).await; - } - async fn send_invalid_request_error(&self, request_id: ConnectionRequestId, message: String) { let error = JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, @@ -4910,14 +3945,6 @@ impl CodexMessageProcessor { } } - fn validate_v1_input_limit(items: &[WireInputItem]) -> Result<(), JSONRPCErrorError> { - let actual_chars: usize = items.iter().map(WireInputItem::text_char_count).sum(); - if actual_chars > MAX_USER_INPUT_TEXT_CHARS { - return Err(Self::input_too_large_error(actual_chars)); - } - Ok(()) - } - fn validate_v2_input_limit(items: &[V2UserInput]) -> Result<(), JSONRPCErrorError> { let actual_chars: usize = items.iter().map(V2UserInput::text_char_count).sum(); if actual_chars > MAX_USER_INPUT_TEXT_CHARS { @@ -4935,29 +3962,6 @@ impl CodexMessageProcessor { self.outgoing.send_error(request_id, error).await; } - async fn archive_conversation( - &mut self, - request_id: ConnectionRequestId, - params: ArchiveConversationParams, - ) { - let ArchiveConversationParams { - conversation_id: thread_id, - rollout_path, - } = params; - - match self.archive_thread_common(thread_id, &rollout_path).await { - Ok(()) => { - tracing::info!("thread/archive succeeded for {thread_id}"); - let response = ArchiveConversationResponse {}; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - tracing::warn!("thread/archive failed for {thread_id}: {}", err.message); - self.outgoing.send_error(request_id, err).await; - } - } - } - async fn wait_for_thread_shutdown(thread: &Arc) -> ThreadShutdownResult { match thread.submit(Op::Shutdown).await { Ok(_) => { @@ -5220,140 +4224,6 @@ impl CodexMessageProcessor { }) } - async fn send_user_message( - &self, - request_id: ConnectionRequestId, - params: SendUserMessageParams, - app_server_client_name: Option, - ) { - let SendUserMessageParams { - conversation_id, - items, - } = params; - if let Err(error) = Self::validate_v1_input_limit(&items) { - self.outgoing.send_error(request_id, error).await; - return; - } - let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("conversation not found: {conversation_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - }; - if let Err(error) = - Self::set_app_server_client_name(conversation.as_ref(), app_server_client_name).await - { - self.outgoing.send_error(request_id, error).await; - return; - } - - let mapped_items: Vec = items - .into_iter() - .map(|item| match item { - WireInputItem::Text { - text, - text_elements, - } => CoreInputItem::Text { - text, - text_elements: text_elements.into_iter().map(Into::into).collect(), - }, - WireInputItem::Image { image_url } => CoreInputItem::Image { image_url }, - WireInputItem::LocalImage { path } => CoreInputItem::LocalImage { path }, - }) - .collect(); - - // Submit user input to the conversation. - let _ = conversation - .submit(Op::UserInput { - items: mapped_items, - final_output_json_schema: None, - }) - .await; - - // Acknowledge with an empty result. - self.outgoing - .send_response(request_id, SendUserMessageResponse {}) - .await; - } - - async fn send_user_turn( - &self, - request_id: ConnectionRequestId, - params: SendUserTurnParams, - app_server_client_name: Option, - ) { - let SendUserTurnParams { - conversation_id, - items, - cwd, - approval_policy, - sandbox_policy, - model, - service_tier, - effort, - summary, - output_schema, - } = params; - if let Err(error) = Self::validate_v1_input_limit(&items) { - self.outgoing.send_error(request_id, error).await; - return; - } - - let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("conversation not found: {conversation_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - }; - if let Err(error) = - Self::set_app_server_client_name(conversation.as_ref(), app_server_client_name).await - { - self.outgoing.send_error(request_id, error).await; - return; - } - - let mapped_items: Vec = items - .into_iter() - .map(|item| match item { - WireInputItem::Text { - text, - text_elements, - } => CoreInputItem::Text { - text, - text_elements: text_elements.into_iter().map(Into::into).collect(), - }, - WireInputItem::Image { image_url } => CoreInputItem::Image { image_url }, - WireInputItem::LocalImage { path } => CoreInputItem::LocalImage { path }, - }) - .collect(); - - let _ = conversation - .submit(Op::UserTurn { - items: mapped_items, - cwd, - approval_policy, - sandbox_policy, - model, - effort, - summary: Some(summary), - service_tier, - final_output_json_schema: output_schema, - collaboration_mode: None, - personality: None, - }) - .await; - - self.outgoing - .send_response(request_id, SendUserTurnResponse {}) - .await; - } - async fn apps_list(&self, request_id: ConnectionRequestId, params: AppsListParams) { let mut config = match self.load_latest_config().await { Ok(config) => config, @@ -5808,40 +4678,6 @@ impl CodexMessageProcessor { } } - async fn interrupt_conversation( - &mut self, - request_id: ConnectionRequestId, - params: InterruptConversationParams, - ) { - let InterruptConversationParams { conversation_id } = params; - let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("conversation not found: {conversation_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - }; - - let request = request_id.clone(); - - // Record the pending interrupt so we can reply when TurnAborted arrives. - { - let pending_interrupts = self - .thread_state_manager - .thread_state(conversation_id) - .await; - let mut thread_state = pending_interrupts.lock().await; - thread_state - .pending_interrupts - .push((request, ApiVersion::V1)); - } - - // Submit the interrupt; we'll respond upon TurnAborted. - let _ = conversation.submit(Op::Interrupt).await; - } - async fn turn_start( &self, request_id: ConnectionRequestId, @@ -6447,76 +5283,6 @@ impl CodexMessageProcessor { let _ = thread.submit(Op::Interrupt).await; } - async fn add_conversation_listener( - &mut self, - request_id: ConnectionRequestId, - params: AddConversationListenerParams, - ) { - let AddConversationListenerParams { - conversation_id, - experimental_raw_events, - } = params; - let conversation = match self.thread_manager.get_thread(conversation_id).await { - Ok(conv) => conv, - Err(_) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("thread not found: {conversation_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - let subscription_id = Uuid::new_v4(); - let thread_state = self - .thread_state_manager - .set_listener( - subscription_id, - conversation_id, - request_id.connection_id, - experimental_raw_events, - ) - .await; - self.ensure_listener_task_running( - conversation_id, - conversation, - thread_state, - ApiVersion::V1, - ) - .await; - - let response = AddConversationSubscriptionResponse { subscription_id }; - self.outgoing.send_response(request_id, response).await; - } - - async fn remove_thread_listener( - &mut self, - request_id: ConnectionRequestId, - params: RemoveConversationListenerParams, - ) { - let RemoveConversationListenerParams { subscription_id } = params; - match self - .thread_state_manager - .remove_listener(subscription_id) - .await - { - Some(thread_id) => { - info!("removed listener for thread {thread_id}"); - let response = RemoveConversationSubscriptionResponse {}; - self.outgoing.send_response(request_id, response).await; - } - None => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("subscription not found: {subscription_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn ensure_conversation_listener( &self, conversation_id: ThreadId, @@ -8290,143 +7056,6 @@ mod tests { Ok(()) } - #[tokio::test] - async fn removing_listeners_retains_thread_listener_when_last_subscriber_leaves() -> Result<()> - { - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener_a = Uuid::new_v4(); - let listener_b = Uuid::new_v4(); - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - let (cancel_tx, mut cancel_rx) = oneshot::channel(); - - manager - .set_listener(listener_a, thread_id, connection_a, false) - .await; - manager - .set_listener(listener_b, thread_id, connection_b, false) - .await; - { - let state = manager.thread_state(thread_id).await; - state.lock().await.cancel_tx = Some(cancel_tx); - } - - assert_eq!(manager.remove_listener(listener_a).await, Some(thread_id)); - assert!( - tokio::time::timeout(Duration::from_millis(20), &mut cancel_rx) - .await - .is_err() - ); - assert_eq!(manager.remove_listener(listener_b).await, Some(thread_id)); - assert!( - tokio::time::timeout(Duration::from_millis(20), &mut cancel_rx) - .await - .is_err() - ); - assert!( - manager - .subscribed_connection_ids(thread_id) - .await - .is_empty() - ); - Ok(()) - } - - #[tokio::test] - async fn removing_listener_unsubscribes_its_connection() -> Result<()> { - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener_a = Uuid::new_v4(); - let listener_b = Uuid::new_v4(); - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - - manager - .set_listener(listener_a, thread_id, connection_a, false) - .await; - manager - .set_listener(listener_b, thread_id, connection_b, false) - .await; - - assert_eq!(manager.remove_listener(listener_a).await, Some(thread_id)); - let subscribed_connection_ids = manager.subscribed_connection_ids(thread_id).await; - assert_eq!(subscribed_connection_ids, vec![connection_b]); - Ok(()) - } - - #[tokio::test] - async fn set_listener_uses_last_write_for_raw_events() -> Result<()> { - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener_a = Uuid::new_v4(); - let listener_b = Uuid::new_v4(); - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - - manager - .set_listener(listener_a, thread_id, connection_a, true) - .await; - { - let state = manager.thread_state(thread_id).await; - assert!(state.lock().await.experimental_raw_events); - } - manager - .set_listener(listener_b, thread_id, connection_b, false) - .await; - let state = manager.thread_state(thread_id).await; - assert!(!state.lock().await.experimental_raw_events); - Ok(()) - } - - #[tokio::test] - async fn removing_connection_retains_listener_and_active_turn_when_last_subscriber_disconnects() - -> Result<()> { - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener = Uuid::new_v4(); - let connection = ConnectionId(1); - let (cancel_tx, mut cancel_rx) = oneshot::channel(); - - manager - .set_listener(listener, thread_id, connection, false) - .await; - { - let state = manager.thread_state(thread_id).await; - let mut state = state.lock().await; - state.cancel_tx = Some(cancel_tx); - state.track_current_turn_event(&EventMsg::TurnStarted( - codex_protocol::protocol::TurnStartedEvent { - turn_id: "turn-1".to_string(), - model_context_window: None, - collaboration_mode_kind: Default::default(), - }, - )); - } - - manager.remove_connection(connection).await; - assert!( - tokio::time::timeout(Duration::from_millis(20), &mut cancel_rx) - .await - .is_err() - ); - assert_eq!(manager.remove_listener(listener).await, None); - - let state = manager.thread_state(thread_id).await; - let state = state.lock().await; - assert!( - manager - .subscribed_connection_ids(thread_id) - .await - .is_empty() - ); - assert!(state.cancel_tx.is_some()); - let active_turn = state.active_turn_snapshot().expect("active turn snapshot"); - assert_eq!(active_turn.id, "turn-1"); - assert_eq!(active_turn.status, TurnStatus::InProgress); - Ok(()) - } - #[tokio::test] async fn removing_thread_state_clears_listener_and_active_turn_history() -> Result<()> { let manager = ThreadStateManager::new(); diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index 5f56c81c57..368d5d21a0 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -500,7 +500,6 @@ mod tests { use codex_app_server_protocol::ConfigWarningNotification; use codex_app_server_protocol::DynamicToolCallParams; use codex_app_server_protocol::FileChangeRequestApprovalParams; - use codex_app_server_protocol::LoginChatGptCompleteNotification; use codex_app_server_protocol::ModelRerouteReason; use codex_app_server_protocol::ModelReroutedNotification; use codex_app_server_protocol::RateLimitSnapshot; @@ -518,8 +517,8 @@ mod tests { #[test] fn verify_server_notification_serialization() { let notification = - ServerNotification::LoginChatGptComplete(LoginChatGptCompleteNotification { - login_id: Uuid::nil(), + ServerNotification::AccountLoginCompleted(AccountLoginCompletedNotification { + login_id: Some(Uuid::nil().to_string()), success: true, error: None, }); @@ -527,9 +526,9 @@ mod tests { let jsonrpc_notification = OutgoingMessage::AppServerNotification(notification); assert_eq!( json!({ - "method": "loginChatGptComplete", + "method": "account/login/completed", "params": { - "loginId": Uuid::nil(), + "loginId": Uuid::nil().to_string(), "success": true, "error": null, }, diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index a60dc07b51..915cc0fd77 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -16,7 +16,6 @@ use std::sync::Weak; use tokio::sync::Mutex; use tokio::sync::mpsc; use tokio::sync::oneshot; -use uuid::Uuid; type PendingInterruptQueue = Vec<( ConnectionRequestId, @@ -116,12 +115,6 @@ impl ThreadState { } } -#[derive(Clone, Copy)] -struct SubscriptionState { - thread_id: ThreadId, - connection_id: ConnectionId, -} - struct ThreadEntry { state: Arc>, connection_ids: HashSet, @@ -140,7 +133,6 @@ impl Default for ThreadEntry { struct ThreadStateManagerInner { live_connections: HashSet, threads: HashMap, - subscription_state_by_id: HashMap, thread_ids_by_connection: HashMap>, } @@ -176,70 +168,6 @@ impl ThreadStateManager { state.threads.entry(thread_id).or_default().state.clone() } - pub(crate) async fn remove_listener(&self, subscription_id: Uuid) -> Option { - let (subscription_state, connection_still_subscribed_to_thread, thread_state) = { - let mut state = self.state.lock().await; - let subscription_state = state.subscription_state_by_id.remove(&subscription_id)?; - let thread_id = subscription_state.thread_id; - - let connection_still_subscribed_to_thread = state - .subscription_state_by_id - .values() - .any(|subscription_state_entry| { - subscription_state_entry.thread_id == thread_id - && subscription_state_entry.connection_id - == subscription_state.connection_id - }); - if !connection_still_subscribed_to_thread { - let mut remove_connection_entry = false; - if let Some(thread_ids) = state - .thread_ids_by_connection - .get_mut(&subscription_state.connection_id) - { - thread_ids.remove(&thread_id); - remove_connection_entry = thread_ids.is_empty(); - } - if remove_connection_entry { - state - .thread_ids_by_connection - .remove(&subscription_state.connection_id); - } - if let Some(thread_entry) = state.threads.get_mut(&thread_id) { - thread_entry - .connection_ids - .remove(&subscription_state.connection_id); - } - } - - let thread_state = state.threads.get(&thread_id).map(|thread_entry| { - ( - thread_entry.connection_ids.is_empty(), - thread_entry.state.clone(), - ) - }); - ( - subscription_state, - connection_still_subscribed_to_thread, - thread_state, - ) - }; - let thread_id = subscription_state.thread_id; - - if let Some((no_subscribers, thread_state)) = thread_state { - let thread_state = thread_state.lock().await; - if !connection_still_subscribed_to_thread && no_subscribers { - tracing::debug!( - thread_id = %thread_id, - subscription_id = %subscription_id, - connection_id = ?subscription_state.connection_id, - listener_generation = thread_state.listener_generation, - "retaining thread listener after last subscription removed" - ); - } - } - Some(thread_id) - } - pub(crate) async fn remove_thread_state(&self, thread_id: ThreadId) { let thread_state = { let mut state = self.state.lock().await; @@ -247,9 +175,6 @@ impl ThreadStateManager { .threads .remove(&thread_id) .map(|thread_entry| thread_entry.state); - state - .subscription_state_by_id - .retain(|_, state| state.thread_id != thread_id); state.thread_ids_by_connection.retain(|_, thread_ids| { thread_ids.remove(&thread_id); !thread_ids.is_empty() @@ -298,13 +223,6 @@ impl ThreadStateManager { if let Some(thread_entry) = state.threads.get_mut(&thread_id) { thread_entry.connection_ids.remove(&connection_id); } - - state - .subscription_state_by_id - .retain(|_, subscription_state| { - !(subscription_state.thread_id == thread_id - && subscription_state.connection_id == connection_id) - }); }; true @@ -319,38 +237,6 @@ impl ThreadStateManager { .is_some_and(|thread_entry| !thread_entry.connection_ids.is_empty()) } - pub(crate) async fn set_listener( - &self, - subscription_id: Uuid, - thread_id: ThreadId, - connection_id: ConnectionId, - experimental_raw_events: bool, - ) -> Arc> { - let thread_state = { - let mut state = self.state.lock().await; - state.subscription_state_by_id.insert( - subscription_id, - SubscriptionState { - thread_id, - connection_id, - }, - ); - state - .thread_ids_by_connection - .entry(connection_id) - .or_default() - .insert(thread_id); - let thread_entry = state.threads.entry(thread_id).or_default(); - thread_entry.connection_ids.insert(connection_id); - thread_entry.state.clone() - }; - { - let mut thread_state_guard = thread_state.lock().await; - thread_state_guard.set_experimental_raw_events(experimental_raw_events); - } - thread_state - } - pub(crate) async fn try_ensure_connection_subscribed( &self, thread_id: ThreadId, @@ -411,9 +297,6 @@ impl ThreadStateManager { .thread_ids_by_connection .remove(&connection_id) .unwrap_or_default(); - state - .subscription_state_by_id - .retain(|_, state| state.connection_id != connection_id); for thread_id in &thread_ids { if let Some(thread_entry) = state.threads.get_mut(thread_id) { thread_entry.connection_ids.remove(&connection_id); diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index 9f0fb31cb4..4b525878b8 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -11,11 +11,8 @@ use tokio::process::ChildStdin; use tokio::process::ChildStdout; use anyhow::Context; -use codex_app_server_protocol::AddConversationListenerParams; use codex_app_server_protocol::AppsListParams; -use codex_app_server_protocol::ArchiveConversationParams; use codex_app_server_protocol::CancelLoginAccountParams; -use codex_app_server_protocol::CancelLoginChatGptParams; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientNotification; use codex_app_server_protocol::CollaborationModeListParams; @@ -24,32 +21,23 @@ use codex_app_server_protocol::ConfigReadParams; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::ExperimentalFeatureListParams; use codex_app_server_protocol::FeedbackUploadParams; -use codex_app_server_protocol::ForkConversationParams; use codex_app_server_protocol::GetAccountParams; use codex_app_server_protocol::GetAuthStatusParams; +use codex_app_server_protocol::GetConversationSummaryParams; use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::InterruptConversationParams; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCRequest; use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::ListConversationsParams; use codex_app_server_protocol::LoginAccountParams; -use codex_app_server_protocol::LoginApiKeyParams; use codex_app_server_protocol::MockExperimentalMethodParams; use codex_app_server_protocol::ModelListParams; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::RemoveConversationListenerParams; use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ResumeConversationParams; use codex_app_server_protocol::ReviewStartParams; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserTurnParams; use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::SetDefaultModelParams; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::ThreadArchiveParams; use codex_app_server_protocol::ThreadCompactStartParams; @@ -243,71 +231,6 @@ impl McpProcess { } } - /// Send a `newConversation` JSON-RPC request. - pub async fn send_new_conversation_request( - &mut self, - params: NewConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("newConversation", params).await - } - - /// Send an `archiveConversation` JSON-RPC request. - pub async fn send_archive_conversation_request( - &mut self, - params: ArchiveConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("archiveConversation", params).await - } - - /// Send an `addConversationListener` JSON-RPC request. - pub async fn send_add_conversation_listener_request( - &mut self, - params: AddConversationListenerParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("addConversationListener", params).await - } - - /// Send a `sendUserMessage` JSON-RPC request with a single text item. - pub async fn send_send_user_message_request( - &mut self, - params: SendUserMessageParams, - ) -> anyhow::Result { - // Wire format expects variants in camelCase; text item uses external tagging. - let params = Some(serde_json::to_value(params)?); - self.send_request("sendUserMessage", params).await - } - - /// Send a `removeConversationListener` JSON-RPC request. - pub async fn send_remove_thread_listener_request( - &mut self, - params: RemoveConversationListenerParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("removeConversationListener", params) - .await - } - - /// Send a `sendUserTurn` JSON-RPC request. - pub async fn send_send_user_turn_request( - &mut self, - params: SendUserTurnParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("sendUserTurn", params).await - } - - /// Send a `interruptConversation` JSON-RPC request. - pub async fn send_interrupt_conversation_request( - &mut self, - params: InterruptConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("interruptConversation", params).await - } - /// Send a `getAuthStatus` JSON-RPC request. pub async fn send_get_auth_status_request( &mut self, @@ -317,14 +240,13 @@ impl McpProcess { self.send_request("getAuthStatus", params).await } - /// Send a `getUserSavedConfig` JSON-RPC request. - pub async fn send_get_user_saved_config_request(&mut self) -> anyhow::Result { - self.send_request("getUserSavedConfig", None).await - } - - /// Send a `getUserAgent` JSON-RPC request. - pub async fn send_get_user_agent_request(&mut self) -> anyhow::Result { - self.send_request("getUserAgent", None).await + /// Send a `getConversationSummary` JSON-RPC request. + pub async fn send_get_conversation_summary_request( + &mut self, + params: GetConversationSummaryParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("getConversationSummary", params).await } /// Send an `account/rateLimits/read` JSON-RPC request. @@ -366,29 +288,6 @@ impl McpProcess { self.send_request("feedback/upload", params).await } - /// Send a `userInfo` JSON-RPC request. - pub async fn send_user_info_request(&mut self) -> anyhow::Result { - self.send_request("userInfo", None).await - } - - /// Send a `setDefaultModel` JSON-RPC request. - pub async fn send_set_default_model_request( - &mut self, - params: SetDefaultModelParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("setDefaultModel", params).await - } - - /// Send a `listConversations` JSON-RPC request. - pub async fn send_list_conversations_request( - &mut self, - params: ListConversationsParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("listConversations", params).await - } - /// Send a `thread/start` JSON-RPC request. pub async fn send_thread_start_request( &mut self, @@ -548,38 +447,6 @@ impl McpProcess { self.send_request("mock/experimentalMethod", params).await } - /// Send a `resumeConversation` JSON-RPC request. - pub async fn send_resume_conversation_request( - &mut self, - params: ResumeConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("resumeConversation", params).await - } - - /// Send a `forkConversation` JSON-RPC request. - pub async fn send_fork_conversation_request( - &mut self, - params: ForkConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("forkConversation", params).await - } - - /// Send a `loginApiKey` JSON-RPC request. - pub async fn send_login_api_key_request( - &mut self, - params: LoginApiKeyParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("loginApiKey", params).await - } - - /// Send a `loginChatGpt` JSON-RPC request. - pub async fn send_login_chat_gpt_request(&mut self) -> anyhow::Result { - self.send_request("loginChatGpt", None).await - } - /// Send a `turn/start` JSON-RPC request (v2). pub async fn send_turn_start_request( &mut self, @@ -719,20 +586,6 @@ impl McpProcess { self.send_request("windowsSandbox/setupStart", params).await } - /// Send a `cancelLoginChatGpt` JSON-RPC request. - pub async fn send_cancel_login_chat_gpt_request( - &mut self, - params: CancelLoginChatGptParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("cancelLoginChatGpt", params).await - } - - /// Send a `logoutChatGpt` JSON-RPC request. - pub async fn send_logout_chat_gpt_request(&mut self) -> anyhow::Result { - self.send_request("logoutChatGpt", None).await - } - pub async fn send_config_read_request( &mut self, params: ConfigReadParams, diff --git a/codex-rs/app-server/tests/suite/archive_thread.rs b/codex-rs/app-server/tests/suite/archive_thread.rs deleted file mode 100644 index a47b247bfd..0000000000 --- a/codex-rs/app-server/tests/suite/archive_thread.rs +++ /dev/null @@ -1,154 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_mock_responses_server_repeating_assistant; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::ArchiveConversationParams; -use codex_app_server_protocol::ArchiveConversationResponse; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_core::ARCHIVED_SESSIONS_SUBDIR; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn archive_conversation_moves_rollout_into_archived_directory() -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_request_id = mcp - .send_new_conversation_request(NewConversationParams { - model: Some("mock-model".to_string()), - ..Default::default() - }) - .await?; - let new_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_request_id)), - ) - .await??; - - let NewConversationResponse { - conversation_id, - rollout_path, - .. - } = to_response::(new_response)?; - - assert!( - !rollout_path.exists(), - "expected rollout path {} to be deferred until first user message", - rollout_path.display() - ); - - let add_listener_request_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_request_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::(add_listener_response)?; - - let send_request_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: "materialize".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_request_id)), - ) - .await??; - let _: SendUserMessageResponse = to_response::(send_response)?; - let _: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - assert!( - rollout_path.exists(), - "expected rollout path {} to exist after first user message", - rollout_path.display() - ); - - let archive_request_id = mcp - .send_archive_conversation_request(ArchiveConversationParams { - conversation_id, - rollout_path: rollout_path.clone(), - }) - .await?; - let archive_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(archive_request_id)), - ) - .await??; - - let _: ArchiveConversationResponse = - to_response::(archive_response)?; - - let archived_directory = codex_home.path().join(ARCHIVED_SESSIONS_SUBDIR); - let archived_rollout_path = - archived_directory.join(rollout_path.file_name().unwrap_or_else(|| { - panic!("rollout path {} missing file name", rollout_path.display()) - })); - - assert!( - !rollout_path.exists(), - "expected rollout path {} to be moved", - rollout_path.display() - ); - assert!( - archived_rollout_path.exists(), - "expected archived rollout path {} to exist", - archived_rollout_path.display() - ); - - Ok(()) -} - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write(config_toml, config_contents(server_uri)) -} - -fn config_contents(server_uri: &str) -> String { - format!( - r#"model = "mock-model" -approval_policy = "never" -sandbox_mode = "read-only" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ) -} diff --git a/codex-rs/app-server/tests/suite/auth.rs b/codex-rs/app-server/tests/suite/auth.rs index 4693158611..2bbdeff400 100644 --- a/codex-rs/app-server/tests/suite/auth.rs +++ b/codex-rs/app-server/tests/suite/auth.rs @@ -6,8 +6,7 @@ use codex_app_server_protocol::GetAuthStatusParams; use codex_app_server_protocol::GetAuthStatusResponse; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginApiKeyParams; -use codex_app_server_protocol::LoginApiKeyResponse; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::RequestId; use pretty_assertions::assert_eq; use std::path::Path; @@ -72,18 +71,15 @@ forced_login_method = "{forced_method}" } async fn login_with_api_key_via_request(mcp: &mut McpProcess, api_key: &str) -> Result<()> { - let request_id = mcp - .send_login_api_key_request(LoginApiKeyParams { - api_key: api_key.to_string(), - }) - .await?; + let request_id = mcp.send_login_account_api_key_request(api_key).await?; let resp: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_response_message(RequestId::Integer(request_id)), ) .await??; - let _: LoginApiKeyResponse = to_response(resp)?; + let response: LoginAccountResponse = to_response(resp)?; + assert_eq!(response, LoginAccountResponse::ApiKey {}); Ok(()) } @@ -211,9 +207,7 @@ async fn login_api_key_rejected_when_forced_chatgpt() -> Result<()> { timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; let request_id = mcp - .send_login_api_key_request(LoginApiKeyParams { - api_key: "sk-test-key".to_string(), - }) + .send_login_account_api_key_request("sk-test-key") .await?; let err: JSONRPCError = timeout( diff --git a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs deleted file mode 100644 index b5176886bd..0000000000 --- a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs +++ /dev/null @@ -1,550 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_final_assistant_message_sse_response; -use app_test_support::create_mock_responses_server_sequence; -use app_test_support::create_shell_command_sse_response; -use app_test_support::format_with_current_shell; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::ExecCommandApprovalParams; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RemoveConversationListenerParams; -use codex_app_server_protocol::RemoveConversationSubscriptionResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_app_server_protocol::SendUserTurnParams; -use codex_app_server_protocol::SendUserTurnResponse; -use codex_app_server_protocol::ServerRequest; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::config_types::SandboxMode; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::parse_command::ParsedCommand; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::Event; -use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::SandboxPolicy; -use pretty_assertions::assert_eq; -use std::env; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(45); - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn test_codex_jsonrpc_conversation_flow() -> Result<()> { - if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } - - let tmp = TempDir::new()?; - // Temporary Codex home with config pointing at the mock server. - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let working_directory = tmp.path().join("workdir"); - std::fs::create_dir(&working_directory)?; - - // Create a mock model server that immediately ends each turn. - // Two turns are expected: initial session configure + one user message. - let responses = vec![ - create_shell_command_sse_response( - vec!["ls".to_string()], - Some(&working_directory), - Some(5000), - "call1234", - )?, - create_final_assistant_message_sse_response("Enjoy your new git repo!")?, - ]; - let server = create_mock_responses_server_sequence(responses).await; - create_config_toml(&codex_home, &server.uri())?; - - // Start MCP server and initialize. - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // 1) newConversation - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(working_directory.to_string_lossy().into_owned()), - sandbox: Some(SandboxMode::DangerFullAccess), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let new_conv_resp = to_response::(new_conv_resp)?; - let NewConversationResponse { - conversation_id, - model, - reasoning_effort: _, - rollout_path: _, - } = new_conv_resp; - assert_eq!(model, "mock-model"); - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id } = - to_response::(add_listener_resp)?; - - // Drop any buffered events from conversation setup to avoid - // matching an earlier task_complete. - mcp.clear_message_buffer(); - - // 3) sendUserMessage (should trigger notifications; we only validate an OK response) - let send_user_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "text".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_user_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_user_id)), - ) - .await??; - let SendUserMessageResponse {} = to_response::(send_user_resp)?; - - let task_started_notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_started"), - ) - .await??; - let task_started_event: Event = serde_json::from_value( - task_started_notification - .params - .clone() - .expect("task_started should have params"), - ) - .expect("task_started should deserialize to Event"); - - // Verify the task_finished notification for this turn is received. - // Note this also ensures that the final request to the server was made. - let task_finished_notification: JSONRPCNotification = loop { - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - let event: Event = serde_json::from_value( - notification - .params - .clone() - .expect("task_complete should have params"), - ) - .expect("task_complete should deserialize to Event"); - if event.id == task_started_event.id { - break notification; - } - }; - let serde_json::Value::Object(map) = task_finished_notification - .params - .expect("notification should have params") - else { - panic!("task_finished_notification should have params"); - }; - assert_eq!( - map.get("conversationId") - .expect("should have conversationId"), - &serde_json::Value::String(conversation_id.to_string()) - ); - - // 4) removeConversationListener - let remove_listener_id = mcp - .send_remove_thread_listener_request(RemoveConversationListenerParams { subscription_id }) - .await?; - let remove_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(remove_listener_id)), - ) - .await??; - let RemoveConversationSubscriptionResponse {} = to_response(remove_listener_resp)?; - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn test_send_user_turn_changes_approval_policy_behavior() -> Result<()> { - if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } - - let tmp = TempDir::new()?; - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let working_directory = tmp.path().join("workdir"); - std::fs::create_dir(&working_directory)?; - - // Mock server will request a python shell call for the first and second turn, then finish. - let responses = vec![ - create_shell_command_sse_response( - vec![ - "python3".to_string(), - "-c".to_string(), - "print(42)".to_string(), - ], - Some(&working_directory), - Some(5000), - "call1", - )?, - create_final_assistant_message_sse_response("done 1")?, - create_shell_command_sse_response( - vec![ - "python3".to_string(), - "-c".to_string(), - "print(42)".to_string(), - ], - Some(&working_directory), - Some(5000), - "call2", - )?, - create_final_assistant_message_sse_response("done 2")?, - ]; - let server = create_mock_responses_server_sequence(responses).await; - create_config_toml(&codex_home, &server.uri())?; - - // Start MCP server and initialize. - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // 1) Start conversation with approval_policy=untrusted - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(working_directory.to_string_lossy().into_owned()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::(new_conv_resp)?; - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let _: AddConversationSubscriptionResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??, - )?; - - // 3) sendUserMessage triggers a shell call; approval policy is Untrusted so we should get an elicitation - let send_user_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "run python".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let _send_user_resp: SendUserMessageResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_user_id)), - ) - .await??, - )?; - - // Expect an ExecCommandApproval request (elicitation) - let request = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_request_message(), - ) - .await??; - let ServerRequest::ExecCommandApproval { request_id, params } = request else { - panic!("expected ExecCommandApproval request, got: {request:?}"); - }; - - assert_eq!( - ExecCommandApprovalParams { - conversation_id, - call_id: "call1".to_string(), - approval_id: None, - command: format_with_current_shell("python3 -c 'print(42)'"), - cwd: working_directory.clone(), - reason: None, - parsed_cmd: vec![ParsedCommand::Unknown { - cmd: "python3 -c 'print(42)'".to_string() - }], - }, - params - ); - - // Approve so the first turn can complete - mcp.send_response( - request_id, - serde_json::json!({ "decision": codex_protocol::protocol::ReviewDecision::Approved }), - ) - .await?; - - // Wait for first TurnComplete - let _ = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - // 4) sendUserTurn with approval_policy=never should run without elicitation - let send_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "run python again".to_string(), - text_elements: Vec::new(), - }], - cwd: working_directory.clone(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - service_tier: None, - output_schema: None, - }) - .await?; - // Acknowledge sendUserTurn - let _send_turn_resp: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id)), - ) - .await??, - )?; - - // Ensure we do NOT receive an ExecCommandApproval request before the task completes. - // If any Request is seen while waiting for task_complete, the helper will error and the test fails. - let _ = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - Ok(()) -} - -// Helper: minimal config.toml pointing at mock provider. - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn test_send_user_turn_updates_sandbox_and_cwd_between_turns() -> Result<()> { - if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } - - let tmp = TempDir::new()?; - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let workspace_root = tmp.path().join("workspace"); - std::fs::create_dir(&workspace_root)?; - let first_cwd = workspace_root.join("turn1"); - let second_cwd = workspace_root.join("turn2"); - std::fs::create_dir(&first_cwd)?; - std::fs::create_dir(&second_cwd)?; - - let responses = vec![ - create_shell_command_sse_response( - vec!["echo".to_string(), "first".to_string(), "turn".to_string()], - None, - Some(5000), - "call-first", - )?, - create_final_assistant_message_sse_response("done first")?, - create_shell_command_sse_response( - vec!["echo".to_string(), "second".to_string(), "turn".to_string()], - None, - Some(5000), - "call-second", - )?, - create_final_assistant_message_sse_response("done second")?, - ]; - let server = create_mock_responses_server_sequence(responses).await; - create_config_toml(&codex_home, &server.uri())?; - - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(first_cwd.to_string_lossy().into_owned()), - approval_policy: Some(AskForApproval::Never), - sandbox: Some(SandboxMode::WorkspaceWrite), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, - model, - .. - } = to_response::(new_conv_resp)?; - - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - - let first_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "first turn".to_string(), - text_elements: Vec::new(), - }], - cwd: first_cwd.clone(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::WorkspaceWrite { - writable_roots: vec![first_cwd.try_into()?], - read_only_access: Default::default(), - network_access: false, - exclude_tmpdir_env_var: false, - exclude_slash_tmp: false, - }, - model: model.clone(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - service_tier: None, - output_schema: None, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(first_turn_id)), - ) - .await??; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - mcp.clear_message_buffer(); - - let second_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "second turn".to_string(), - text_elements: Vec::new(), - }], - cwd: second_cwd.clone(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: model.clone(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - service_tier: None, - output_schema: None, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(second_turn_id)), - ) - .await??; - - let exec_begin_notification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/exec_command_begin"), - ) - .await??; - let params = exec_begin_notification - .params - .clone() - .expect("exec_command_begin params"); - let event: Event = serde_json::from_value(params).expect("deserialize exec begin event"); - let exec_begin = match event.msg { - EventMsg::ExecCommandBegin(exec_begin) => exec_begin, - other => panic!("expected ExecCommandBegin event, got {other:?}"), - }; - assert_eq!( - exec_begin.cwd, second_cwd, - "exec turn should run from updated cwd" - ); - let expected_command = format_with_current_shell("echo second turn"); - assert_eq!( - exec_begin.command, expected_command, - "exec turn should run expected command" - ); - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - Ok(()) -} - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "untrusted" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/config.rs b/codex-rs/app-server/tests/suite/config.rs deleted file mode 100644 index 27a44ef550..0000000000 --- a/codex-rs/app-server/tests/suite/config.rs +++ /dev/null @@ -1,158 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::test_tmp_path; -use app_test_support::to_response; -use codex_app_server_protocol::GetUserSavedConfigResponse; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::Profile; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SandboxSettings; -use codex_app_server_protocol::Tools; -use codex_app_server_protocol::UserSavedConfig; -use codex_protocol::config_types::ForcedLoginMethod; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::config_types::SandboxMode; -use codex_protocol::config_types::Verbosity; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::AskForApproval; -use pretty_assertions::assert_eq; -use std::collections::HashMap; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { - let writable_root = test_tmp_path(); - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "gpt-5.1-codex-max" -approval_policy = "on-request" -sandbox_mode = "workspace-write" -model_reasoning_summary = "detailed" -model_reasoning_effort = "high" -model_verbosity = "medium" -profile = "test" -forced_chatgpt_workspace_id = "12345678-0000-0000-0000-000000000000" -forced_login_method = "chatgpt" - -[sandbox_workspace_write] -writable_roots = [{}] -network_access = true -exclude_tmpdir_env_var = true -exclude_slash_tmp = true - -[tools] -web_search = false -view_image = true - -[profiles.test] -model = "gpt-4o" -approval_policy = "on-request" -model_reasoning_effort = "high" -model_reasoning_summary = "detailed" -model_verbosity = "medium" -model_provider = "openai" -chatgpt_base_url = "https://api.chatgpt.com" -"#, - serde_json::json!(writable_root) - ), - ) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn get_config_toml_parses_all_fields() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_get_user_saved_config_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let config: GetUserSavedConfigResponse = to_response(resp)?; - let writable_root = test_tmp_path(); - let expected = GetUserSavedConfigResponse { - config: UserSavedConfig { - approval_policy: Some(AskForApproval::OnRequest), - sandbox_mode: Some(SandboxMode::WorkspaceWrite), - sandbox_settings: Some(SandboxSettings { - writable_roots: vec![writable_root], - network_access: Some(true), - exclude_tmpdir_env_var: Some(true), - exclude_slash_tmp: Some(true), - }), - forced_chatgpt_workspace_id: Some("12345678-0000-0000-0000-000000000000".into()), - forced_login_method: Some(ForcedLoginMethod::Chatgpt), - model: Some("gpt-5.1-codex-max".into()), - model_reasoning_effort: Some(ReasoningEffort::High), - model_reasoning_summary: Some(ReasoningSummary::Detailed), - model_verbosity: Some(Verbosity::Medium), - tools: Some(Tools { - web_search: Some(false), - view_image: Some(true), - }), - profile: Some("test".to_string()), - profiles: HashMap::from([( - "test".into(), - Profile { - model: Some("gpt-4o".into()), - approval_policy: Some(AskForApproval::OnRequest), - model_reasoning_effort: Some(ReasoningEffort::High), - model_reasoning_summary: Some(ReasoningSummary::Detailed), - model_verbosity: Some(Verbosity::Medium), - model_provider: Some("openai".into()), - chatgpt_base_url: Some("https://api.chatgpt.com".into()), - }, - )]), - }, - }; - - assert_eq!(config, expected); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn get_config_toml_empty() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_get_user_saved_config_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let config: GetUserSavedConfigResponse = to_response(resp)?; - let expected = GetUserSavedConfigResponse { - config: UserSavedConfig { - approval_policy: None, - sandbox_mode: None, - sandbox_settings: None, - forced_chatgpt_workspace_id: None, - forced_login_method: None, - model: None, - model_reasoning_effort: None, - model_reasoning_summary: None, - model_verbosity: None, - tools: None, - profile: None, - profiles: HashMap::new(), - }, - }; - - assert_eq!(config, expected); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/conversation_summary.rs b/codex-rs/app-server/tests/suite/conversation_summary.rs new file mode 100644 index 0000000000..31108a8455 --- /dev/null +++ b/codex-rs/app-server/tests/suite/conversation_summary.rs @@ -0,0 +1,113 @@ +use anyhow::Result; +use app_test_support::McpProcess; +use app_test_support::create_fake_rollout; +use app_test_support::rollout_path; +use app_test_support::to_response; +use codex_app_server_protocol::ConversationSummary; +use codex_app_server_protocol::GetConversationSummaryParams; +use codex_app_server_protocol::GetConversationSummaryResponse; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::RequestId; +use codex_protocol::ThreadId; +use codex_protocol::protocol::SessionSource; +use pretty_assertions::assert_eq; +use std::path::PathBuf; +use tempfile::TempDir; +use tokio::time::timeout; + +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +const FILENAME_TS: &str = "2025-01-02T12-00-00"; +const META_RFC3339: &str = "2025-01-02T12:00:00Z"; +const PREVIEW: &str = "Summarize this conversation"; +const MODEL_PROVIDER: &str = "openai"; + +fn expected_summary(conversation_id: ThreadId, path: PathBuf) -> ConversationSummary { + ConversationSummary { + conversation_id, + path, + preview: PREVIEW.to_string(), + timestamp: Some(META_RFC3339.to_string()), + updated_at: Some(META_RFC3339.to_string()), + model_provider: MODEL_PROVIDER.to_string(), + cwd: PathBuf::from("/"), + cli_version: "0.0.0".to_string(), + source: SessionSource::Cli, + git_info: None, + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn get_conversation_summary_by_thread_id_reads_rollout() -> Result<()> { + let codex_home = TempDir::new()?; + let conversation_id = create_fake_rollout( + codex_home.path(), + FILENAME_TS, + META_RFC3339, + PREVIEW, + Some(MODEL_PROVIDER), + None, + )?; + let thread_id = ThreadId::from_string(&conversation_id)?; + let expected = expected_summary( + thread_id, + std::fs::canonicalize(rollout_path( + codex_home.path(), + FILENAME_TS, + &conversation_id, + ))?, + ); + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_get_conversation_summary_request(GetConversationSummaryParams::ThreadId { + conversation_id: thread_id, + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let received: GetConversationSummaryResponse = to_response(response)?; + + assert_eq!(received.summary, expected); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn get_conversation_summary_by_relative_rollout_path_resolves_from_codex_home() -> Result<()> +{ + let codex_home = TempDir::new()?; + let conversation_id = create_fake_rollout( + codex_home.path(), + FILENAME_TS, + META_RFC3339, + PREVIEW, + Some(MODEL_PROVIDER), + None, + )?; + let thread_id = ThreadId::from_string(&conversation_id)?; + let rollout_path = rollout_path(codex_home.path(), FILENAME_TS, &conversation_id); + let relative_path = rollout_path.strip_prefix(codex_home.path())?.to_path_buf(); + let expected = expected_summary(thread_id, std::fs::canonicalize(rollout_path)?); + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_get_conversation_summary_request(GetConversationSummaryParams::RolloutPath { + rollout_path: relative_path, + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let received: GetConversationSummaryResponse = to_response(response)?; + + assert_eq!(received.summary, expected); + Ok(()) +} diff --git a/codex-rs/app-server/tests/suite/create_thread.rs b/codex-rs/app-server/tests/suite/create_thread.rs deleted file mode 100644 index 8ad3342539..0000000000 --- a/codex-rs/app-server/tests/suite/create_thread.rs +++ /dev/null @@ -1,142 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_final_assistant_message_sse_response; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_conversation_create_and_send_message_ok() -> Result<()> { - // Mock server – we won't strictly rely on it, but provide one to satisfy any model wiring. - let response_body = create_final_assistant_message_sse_response("Done")?; - let server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence(&server, vec![response_body]).await; - - // Temporary Codex home with config pointing at the mock server. - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - // Start MCP server process and initialize. - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // Create a conversation via the new JSON-RPC API. - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, - model, - reasoning_effort: _, - rollout_path: _, - } = to_response::(new_conv_resp)?; - assert_eq!(model, "o3"); - - // Add a listener so we receive notifications for this conversation (not strictly required for this test). - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let _sub: AddConversationSubscriptionResponse = - to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??, - )?; - - // Now send a user message via the wire API and expect an OK (empty object) result. - let send_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_id)), - ) - .await??; - let _ok: SendUserMessageResponse = to_response::(send_resp)?; - - // Avoid race condition by waiting for the mock server to receive the responses request. - let deadline = std::time::Instant::now() + DEFAULT_READ_TIMEOUT; - let requests = loop { - let requests = response_mock.requests(); - if !requests.is_empty() { - break requests; - } - if std::time::Instant::now() >= deadline { - panic!("mock server did not receive the responses request in time"); - } - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - }; - - // Verify the outbound request body matches expectations for Responses. - let request = requests - .first() - .expect("mock server should have received at least one request"); - let body = request.body_json(); - assert_eq!(body["model"], json!("o3")); - let user_texts = request.message_input_texts("user"); - assert!( - user_texts.iter().any(|text| text == "Hello"), - "expected user input to include Hello, got {user_texts:?}" - ); - - drop(server); - Ok(()) -} - -// Helper to create a config.toml pointing at the mock model server. -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/fork_thread.rs b/codex-rs/app-server/tests/suite/fork_thread.rs deleted file mode 100644 index ec282be4a1..0000000000 --- a/codex-rs/app-server/tests/suite/fork_thread.rs +++ /dev/null @@ -1,140 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_fake_rollout; -use app_test_support::to_response; -use codex_app_server_protocol::ForkConversationParams; -use codex_app_server_protocol::ForkConversationResponse; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; // reused for overrides shape -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionConfiguredNotification; -use codex_protocol::protocol::EventMsg; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn fork_conversation_creates_new_rollout() -> Result<()> { - let codex_home = TempDir::new()?; - - let preview = "Hello A"; - let conversation_id = create_fake_rollout( - codex_home.path(), - "2025-01-02T12-00-00", - "2025-01-02T12:00:00Z", - preview, - Some("openai"), - None, - )?; - - let original_path = codex_home - .path() - .join("sessions") - .join("2025") - .join("01") - .join("02") - .join(format!( - "rollout-2025-01-02T12-00-00-{conversation_id}.jsonl" - )); - assert!( - original_path.exists(), - "expected original rollout to exist at {}", - original_path.display() - ); - let original_contents = std::fs::read_to_string(&original_path)?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let fork_req_id = mcp - .send_fork_conversation_request(ForkConversationParams { - path: Some(original_path.clone()), - conversation_id: None, - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - - // Expect a sessionConfigured notification for the forked session. - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - session_id, - rollout_path, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - - assert_eq!(model, "o3"); - assert_ne!( - session_id.to_string(), - conversation_id, - "expected a new conversation id when forking" - ); - assert_ne!( - rollout_path, original_path, - "expected a new rollout path when forking" - ); - assert!( - rollout_path.exists(), - "expected forked rollout to exist at {}", - rollout_path.display() - ); - - let session_initial_messages = - session_initial_messages.expect("expected initial messages when forking from rollout"); - match session_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, preview); - } - other => panic!("unexpected initial messages from rollout fork: {other:#?}"), - } - - // Then the response for forkConversation. - let fork_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(fork_req_id)), - ) - .await??; - let ForkConversationResponse { - conversation_id: forked_id, - model: forked_model, - initial_messages: response_initial_messages, - rollout_path: response_rollout_path, - } = to_response::(fork_resp)?; - - assert_eq!(forked_model, "o3"); - assert_eq!(response_rollout_path, rollout_path); - assert_ne!(forked_id.to_string(), conversation_id); - - let response_initial_messages = - response_initial_messages.expect("expected initial messages in fork response"); - match response_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, preview); - } - other => panic!("unexpected initial messages in fork response: {other:#?}"), - } - - let after_contents = std::fs::read_to_string(&original_path)?; - assert_eq!( - after_contents, original_contents, - "fork should not mutate the original rollout file" - ); - - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/interrupt.rs b/codex-rs/app-server/tests/suite/interrupt.rs deleted file mode 100644 index dd09b832f8..0000000000 --- a/codex-rs/app-server/tests/suite/interrupt.rs +++ /dev/null @@ -1,163 +0,0 @@ -#![cfg(unix)] -// Support code lives in the `app_test_support` crate under tests/common. - -use std::path::Path; - -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::InterruptConversationParams; -use codex_app_server_protocol::InterruptConversationResponse; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_protocol::protocol::TurnAbortReason; -use core_test_support::skip_if_no_network; -use tempfile::TempDir; -use tokio::time::timeout; - -use app_test_support::McpProcess; -use app_test_support::create_mock_responses_server_sequence; -use app_test_support::create_shell_command_sse_response; -use app_test_support::to_response; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_shell_command_interruption() { - skip_if_no_network!(); - - if let Err(err) = shell_command_interruption().await { - panic!("failure: {err}"); - } -} - -async fn shell_command_interruption() -> anyhow::Result<()> { - // Use a cross-platform blocking command. On Windows plain `sleep` is not guaranteed to exist - // (MSYS/GNU coreutils may be absent) and the failure causes the tool call to finish immediately, - // which triggers a second model request before the test sends the explicit follow-up. That - // prematurely consumes the second mocked SSE response and leads to a third POST (panic: no response for 2). - // Powershell Start-Sleep is always available on Windows runners. On Unix we keep using `sleep`. - #[cfg(target_os = "windows")] - let shell_command = vec![ - "powershell".to_string(), - "-Command".to_string(), - "Start-Sleep -Seconds 10".to_string(), - ]; - #[cfg(not(target_os = "windows"))] - let shell_command = vec!["sleep".to_string(), "10".to_string()]; - - let tmp = TempDir::new()?; - // Temporary Codex home with config pointing at the mock server. - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let working_directory = tmp.path().join("workdir"); - std::fs::create_dir(&working_directory)?; - - // Create mock server with a single SSE response: the long sleep command - let server = create_mock_responses_server_sequence(vec![create_shell_command_sse_response( - shell_command.clone(), - Some(&working_directory), - Some(10_000), // 10 seconds timeout in ms - "call_sleep", - )?]) - .await; - create_config_toml(&codex_home, server.uri())?; - - // Start MCP server and initialize. - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // 1) newConversation - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(working_directory.to_string_lossy().into_owned()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let new_conv_resp = to_response::(new_conv_resp)?; - let NewConversationResponse { - conversation_id, .. - } = new_conv_resp; - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let _add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - - // 3) sendUserMessage (should trigger notifications; we only validate an OK response) - let send_user_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "run first sleep command".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_user_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_user_id)), - ) - .await??; - let SendUserMessageResponse {} = to_response::(send_user_resp)?; - - // Give the command a moment to start - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - - // 4) send interrupt request - let interrupt_id = mcp - .send_interrupt_conversation_request(InterruptConversationParams { conversation_id }) - .await?; - let interrupt_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(interrupt_id)), - ) - .await??; - let InterruptConversationResponse { abort_reason } = - to_response::(interrupt_resp)?; - assert_eq!(TurnAbortReason::Interrupted, abort_reason); - - Ok(()) -} - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -fn create_config_toml(codex_home: &Path, server_uri: String) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/list_resume.rs b/codex-rs/app-server/tests/suite/list_resume.rs deleted file mode 100644 index 97c8f41d11..0000000000 --- a/codex-rs/app-server/tests/suite/list_resume.rs +++ /dev/null @@ -1,440 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_fake_rollout; -use app_test_support::to_response; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::ListConversationsParams; -use codex_app_server_protocol::ListConversationsResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ResumeConversationParams; -use codex_app_server_protocol::ResumeConversationResponse; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionConfiguredNotification; -use codex_protocol::models::ContentItem; -use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::EventMsg; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_list_and_resume_conversations() -> Result<()> { - // Prepare a temporary CODEX_HOME with a few fake rollout files. - let codex_home = TempDir::new()?; - create_fake_rollout( - codex_home.path(), - "2025-01-02T12-00-00", - "2025-01-02T12:00:00Z", - "Hello A", - Some("openai"), - None, - )?; - create_fake_rollout( - codex_home.path(), - "2025-01-01T13-00-00", - "2025-01-01T13:00:00Z", - "Hello B", - Some("openai"), - None, - )?; - create_fake_rollout( - codex_home.path(), - "2025-01-01T12-00-00", - "2025-01-01T12:00:00Z", - "Hello C", - None, - None, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // Request first page with size 2 - let req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(2), - cursor: None, - model_providers: None, - }) - .await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(req_id)), - ) - .await??; - let ListConversationsResponse { items, next_cursor } = - to_response::(resp)?; - - assert_eq!(items.len(), 2); - // Newest first; preview text should match - assert_eq!(items[0].preview, "Hello A"); - assert_eq!(items[1].preview, "Hello B"); - assert_eq!(items[0].model_provider, "openai"); - assert_eq!(items[1].model_provider, "openai"); - assert!(items[0].path.is_absolute()); - assert!(next_cursor.is_some()); - - // Request the next page using the cursor - let req_id2 = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(2), - cursor: next_cursor, - model_providers: None, - }) - .await?; - let resp2: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(req_id2)), - ) - .await??; - let ListConversationsResponse { - items: items2, - next_cursor: next2, - .. - } = to_response::(resp2)?; - assert_eq!(items2.len(), 1); - assert_eq!(items2[0].preview, "Hello C"); - assert_eq!(items2[0].model_provider, "openai"); - assert_eq!(next2, None); - - // Add a conversation with an explicit non-OpenAI provider for filter tests. - create_fake_rollout( - codex_home.path(), - "2025-01-01T11-30-00", - "2025-01-01T11:30:00Z", - "Hello TP", - Some("test-provider"), - None, - )?; - - // Filtering by model provider should return only matching sessions. - let filter_req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(10), - cursor: None, - model_providers: Some(vec!["test-provider".to_string()]), - }) - .await?; - let filter_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(filter_req_id)), - ) - .await??; - let ListConversationsResponse { - items: filtered_items, - next_cursor: filtered_next, - } = to_response::(filter_resp)?; - assert_eq!(filtered_items.len(), 1); - assert_eq!(filtered_next, None); - assert_eq!(filtered_items[0].preview, "Hello TP"); - assert_eq!(filtered_items[0].model_provider, "test-provider"); - - // Empty filter should include every session regardless of provider metadata. - let unfiltered_req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(10), - cursor: None, - model_providers: Some(Vec::new()), - }) - .await?; - let unfiltered_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(unfiltered_req_id)), - ) - .await??; - let ListConversationsResponse { - items: unfiltered_items, - next_cursor: unfiltered_next, - } = to_response::(unfiltered_resp)?; - assert_eq!(unfiltered_items.len(), 4); - assert!(unfiltered_next.is_none()); - - let empty_req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(10), - cursor: None, - model_providers: Some(vec!["other".to_string()]), - }) - .await?; - let empty_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(empty_req_id)), - ) - .await??; - let ListConversationsResponse { - items: empty_items, - next_cursor: empty_next, - } = to_response::(empty_resp)?; - assert!(empty_items.is_empty()); - assert!(empty_next.is_none()); - - let first_item = &items[0]; - - // Now resume one of the sessions from an explicit rollout path. - let resume_req_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: Some(first_item.path.clone()), - conversation_id: None, - history: None, - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - - // Expect a codex/event notification with msg.type == sessionConfigured - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - rollout_path, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - assert_eq!(model, "o3"); - assert_eq!(rollout_path, first_item.path.clone()); - let session_initial_messages = session_initial_messages - .expect("expected initial messages when resuming from rollout path"); - match session_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => panic!("unexpected initial messages from rollout resume: {other:#?}"), - } - - // Then the response for resumeConversation - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_req_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id, - model: resume_model, - initial_messages: response_initial_messages, - .. - } = to_response::(resume_resp)?; - // conversation id should be a valid UUID - assert!(!conversation_id.to_string().is_empty()); - assert_eq!(resume_model, "o3"); - let response_initial_messages = - response_initial_messages.expect("expected initial messages in resume response"); - match response_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => panic!("unexpected initial messages in resume response: {other:#?}"), - } - - // Resuming with only a conversation id should locate the rollout automatically. - let resume_by_id_req_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: None, - conversation_id: Some(first_item.conversation_id), - history: None, - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - rollout_path, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - assert_eq!(model, "o3"); - assert_eq!(rollout_path, first_item.path.clone()); - let session_initial_messages = session_initial_messages - .expect("expected initial messages when resuming from conversation id"); - match session_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => panic!("unexpected initial messages from conversation id resume: {other:#?}"), - } - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_by_id_req_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id: by_id_conversation_id, - model: by_id_model, - initial_messages: by_id_initial_messages, - .. - } = to_response::(resume_resp)?; - assert!(!by_id_conversation_id.to_string().is_empty()); - assert_eq!(by_id_model, "o3"); - let by_id_initial_messages = by_id_initial_messages - .expect("expected initial messages when resuming from conversation id response"); - match by_id_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => { - panic!("unexpected initial messages in conversation id resume response: {other:#?}") - } - } - - // Resuming with explicit history should succeed even without a stored rollout. - let fork_history_text = "Hello from history"; - let history = vec![ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: fork_history_text.to_string(), - }], - end_turn: None, - phase: None, - }]; - let resume_with_history_req_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: None, - conversation_id: None, - history: Some(history), - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - assert_eq!(model, "o3"); - assert!( - session_initial_messages.as_ref().is_none_or(Vec::is_empty), - "expected no initial messages when resuming from explicit history but got {session_initial_messages:#?}" - ); - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_with_history_req_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id: history_conversation_id, - model: history_model, - initial_messages: history_initial_messages, - .. - } = to_response::(resume_resp)?; - assert!(!history_conversation_id.to_string().is_empty()); - assert_eq!(history_model, "o3"); - assert!( - history_initial_messages.as_ref().is_none_or(Vec::is_empty), - "expected no initial messages in resume response when history is provided but got {history_initial_messages:#?}" - ); - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn list_conversations_fetches_through_filtered_pages() -> Result<()> { - let codex_home = TempDir::new()?; - - // Only the last 3 conversations match the provider filter; request 3 and - // ensure pagination keeps fetching past non-matching pages. - let cases = [ - ( - "2025-03-04T12-00-00", - "2025-03-04T12:00:00Z", - "skip_provider", - ), - ( - "2025-03-03T12-00-00", - "2025-03-03T12:00:00Z", - "skip_provider", - ), - ( - "2025-03-02T12-00-00", - "2025-03-02T12:00:00Z", - "target_provider", - ), - ( - "2025-03-01T12-00-00", - "2025-03-01T12:00:00Z", - "target_provider", - ), - ( - "2025-02-28T12-00-00", - "2025-02-28T12:00:00Z", - "target_provider", - ), - ]; - - for (ts_file, ts_rfc, provider) in cases { - create_fake_rollout( - codex_home.path(), - ts_file, - ts_rfc, - "Hello", - Some(provider), - None, - )?; - } - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(3), - cursor: None, - model_providers: Some(vec!["target_provider".to_string()]), - }) - .await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(req_id)), - ) - .await??; - let ListConversationsResponse { items, next_cursor } = - to_response::(resp)?; - - assert_eq!( - items.len(), - 3, - "should fetch across pages to satisfy the limit" - ); - assert!( - items - .iter() - .all(|item| item.model_provider == "target_provider") - ); - assert_eq!(next_cursor, None); - - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/login.rs b/codex-rs/app-server/tests/suite/login.rs deleted file mode 100644 index afc69787eb..0000000000 --- a/codex-rs/app-server/tests/suite/login.rs +++ /dev/null @@ -1,161 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::GetAuthStatusParams; -use codex_app_server_protocol::GetAuthStatusResponse; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginChatGptResponse; -use codex_app_server_protocol::LogoutChatGptResponse; -use codex_app_server_protocol::RequestId; -use codex_core::auth::AuthCredentialsStoreMode; -use codex_login::login_with_api_key; -use serial_test::serial; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -// Helper to create a config.toml; mirrors create_conversation.rs -fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "http://127.0.0.1:0/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"#, - ) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn logout_chatgpt_removes_auth() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path())?; - login_with_api_key( - codex_home.path(), - "sk-test-key", - AuthCredentialsStoreMode::File, - )?; - assert!(codex_home.path().join("auth.json").exists()); - - let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let id = mcp.send_logout_chat_gpt_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(id)), - ) - .await??; - let _ok: LogoutChatGptResponse = to_response(resp)?; - - assert!( - !codex_home.path().join("auth.json").exists(), - "auth.json should be deleted" - ); - - // Verify status reflects signed-out state. - let status_id = mcp - .send_get_auth_status_request(GetAuthStatusParams { - include_token: Some(true), - refresh_token: Some(false), - }) - .await?; - let status_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(status_id)), - ) - .await??; - let status: GetAuthStatusResponse = to_response(status_resp)?; - assert_eq!(status.auth_method, None); - assert_eq!(status.auth_token, None); - Ok(()) -} - -fn create_config_toml_forced_login(codex_home: &Path, forced_method: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - let contents = format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" -forced_login_method = "{forced_method}" -"# - ); - std::fs::write(config_toml, contents) -} - -fn create_config_toml_forced_workspace( - codex_home: &Path, - workspace_id: &str, -) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - let contents = format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" -forced_chatgpt_workspace_id = "{workspace_id}" -"# - ); - std::fs::write(config_toml, contents) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn login_chatgpt_rejected_when_forced_api() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml_forced_login(codex_home.path(), "api")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_login_chat_gpt_request().await?; - let err: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!( - err.error.message, - "ChatGPT login is disabled. Use API key login instead." - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -// Serialize tests that launch the login server since it binds to a fixed port. -#[serial(login_port)] -async fn login_chatgpt_includes_forced_workspace_query_param() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml_forced_workspace(codex_home.path(), "ws-forced")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_login_chat_gpt_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let login: LoginChatGptResponse = to_response(resp)?; - assert!( - login.auth_url.contains("allowed_workspace_id=ws-forced"), - "auth URL should include forced workspace" - ); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/mod.rs b/codex-rs/app-server/tests/suite/mod.rs index ae7e0cb438..c60f4a32a1 100644 --- a/codex-rs/app-server/tests/suite/mod.rs +++ b/codex-rs/app-server/tests/suite/mod.rs @@ -1,16 +1,4 @@ -mod archive_thread; mod auth; -mod codex_message_processor_flow; -mod config; -mod create_thread; -mod fork_thread; +mod conversation_summary; mod fuzzy_file_search; -mod interrupt; -mod list_resume; -mod login; -mod output_schema; -mod send_message; -mod set_default_model; -mod user_agent; -mod user_info; mod v2; diff --git a/codex-rs/app-server/tests/suite/output_schema.rs b/codex-rs/app-server/tests/suite/output_schema.rs deleted file mode 100644 index b182e4262e..0000000000 --- a/codex-rs/app-server/tests/suite/output_schema.rs +++ /dev/null @@ -1,372 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE; -use codex_app_server::INVALID_PARAMS_ERROR_CODE; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserTurnParams; -use codex_app_server_protocol::SendUserTurnResponse; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; -use core_test_support::responses; -use core_test_support::skip_if_no_network; -use pretty_assertions::assert_eq; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test] -async fn send_user_turn_accepts_output_schema_v1() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - let body = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let response_mock = responses::mount_sse_once(&server, body).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::(new_conv_resp)?; - - let listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(listener_id)), - ) - .await??; - - let output_schema = serde_json::json!({ - "type": "object", - "properties": { - "answer": { "type": "string" } - }, - "required": ["answer"], - "additionalProperties": false - }); - - let send_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - cwd: codex_home.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - service_tier: None, - output_schema: Some(output_schema.clone()), - }) - .await?; - let _send_turn_resp: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id)), - ) - .await??, - )?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - let request = response_mock.single_request(); - let payload = request.body_json(); - let text = payload.get("text").expect("request missing text field"); - let format = text - .get("format") - .expect("request missing text.format field"); - assert_eq!( - format, - &serde_json::json!({ - "name": "codex_output_schema", - "type": "json_schema", - "strict": true, - "schema": output_schema, - }) - ); - - Ok(()) -} - -#[tokio::test] -async fn send_user_turn_rejects_oversized_input_v1() -> Result<()> { - let server = responses::start_mock_server().await; - let body = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let _response_mock = responses::mount_sse_once(&server, body).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::(new_conv_resp)?; - - let listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(listener_id)), - ) - .await??; - - let oversized_input = "x".repeat(MAX_USER_INPUT_TEXT_CHARS + 1); - let send_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: oversized_input.clone(), - text_elements: Vec::new(), - }], - cwd: codex_home.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Low), - summary: ReasoningSummary::Auto, - service_tier: None, - output_schema: None, - }) - .await?; - - let err: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(send_turn_id)), - ) - .await??; - - assert_eq!(err.error.code, INVALID_PARAMS_ERROR_CODE); - assert_eq!( - err.error.message, - format!("Input exceeds the maximum length of {MAX_USER_INPUT_TEXT_CHARS} characters.") - ); - let data = err.error.data.expect("expected structured error data"); - assert_eq!(data["input_error_code"], INPUT_TOO_LARGE_ERROR_CODE); - assert_eq!(data["max_chars"], MAX_USER_INPUT_TEXT_CHARS); - assert_eq!(data["actual_chars"], oversized_input.chars().count()); - - Ok(()) -} - -#[tokio::test] -async fn send_user_turn_output_schema_is_per_turn_v1() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - let body1 = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let response_mock1 = responses::mount_sse_once(&server, body1).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::(new_conv_resp)?; - - let listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(listener_id)), - ) - .await??; - - let output_schema = serde_json::json!({ - "type": "object", - "properties": { - "answer": { "type": "string" } - }, - "required": ["answer"], - "additionalProperties": false - }); - - let send_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - cwd: codex_home.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - service_tier: None, - output_schema: Some(output_schema.clone()), - }) - .await?; - let _send_turn_resp: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id)), - ) - .await??, - )?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - let payload1 = response_mock1.single_request().body_json(); - assert_eq!( - payload1.pointer("/text/format"), - Some(&serde_json::json!({ - "name": "codex_output_schema", - "type": "json_schema", - "strict": true, - "schema": output_schema, - })) - ); - - let body2 = responses::sse(vec![ - responses::ev_response_created("resp-2"), - responses::ev_assistant_message("msg-2", "Done"), - responses::ev_completed("resp-2"), - ]); - let response_mock2 = responses::mount_sse_once(&server, body2).await; - - let send_turn_id_2 = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello again".to_string(), - text_elements: Vec::new(), - }], - cwd: codex_home.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - service_tier: None, - output_schema: None, - }) - .await?; - let _send_turn_resp_2: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id_2)), - ) - .await??, - )?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - let payload2 = response_mock2.single_request().body_json(); - assert_eq!(payload2.pointer("/text/format"), None); - - Ok(()) -} - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "read-only" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/send_message.rs b/codex-rs/app-server/tests/suite/send_message.rs deleted file mode 100644 index 725f327b4c..0000000000 --- a/codex-rs/app-server/tests/suite/send_message.rs +++ /dev/null @@ -1,645 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_fake_rollout; -use app_test_support::rollout_path; -use app_test_support::to_response; -use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE; -use codex_app_server::INVALID_PARAMS_ERROR_CODE; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ResumeConversationParams; -use codex_app_server_protocol::ResumeConversationResponse; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_execpolicy::Policy; -use codex_protocol::ThreadId; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::models::ContentItem; -use codex_protocol::models::DeveloperInstructions; -use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::RawResponseItemEvent; -use codex_protocol::protocol::RolloutItem; -use codex_protocol::protocol::RolloutLine; -use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::protocol::TurnContextItem; -use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test] -async fn test_send_message_success() -> Result<()> { - // Spin up a mock responses server that immediately ends the Codex turn. - // Two Codex turns hit the mock model (session start + send-user-message). Provide two SSE responses. - let server = responses::start_mock_server().await; - let body1 = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let body2 = responses::sse(vec![ - responses::ev_response_created("resp-2"), - responses::ev_assistant_message("msg-2", "Done"), - responses::ev_completed("resp-2"), - ]); - let _response_mock1 = responses::mount_sse_once(&server, body1).await; - let _response_mock2 = responses::mount_sse_once(&server, body2).await; - - // Create a temporary Codex home with config pointing at the mock server. - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - // Start MCP server process and initialize. - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // Start a conversation using the new wire API. - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::<_>(new_conv_resp)?; - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::<_>(add_listener_resp)?; - - // Now exercise sendUserMessage twice. - send_message("Hello", conversation_id, &mut mcp).await?; - send_message("Hello again", conversation_id, &mut mcp).await?; - Ok(()) -} - -#[expect(clippy::expect_used)] -async fn send_message( - message: &str, - conversation_id: ThreadId, - mcp: &mut McpProcess, -) -> Result<()> { - // Now exercise sendUserMessage. - let send_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: message.to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_id)), - ) - .await??; - - let _ok: SendUserMessageResponse = to_response::(response)?; - - // Verify the task_finished notification is received. - // Note this also ensures that the final request to the server was made. - let task_finished_notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - let serde_json::Value::Object(map) = task_finished_notification - .params - .expect("notification should have params") - else { - panic!("task_finished_notification should have params"); - }; - assert_eq!( - map.get("conversationId") - .expect("should have conversationId"), - &serde_json::Value::String(conversation_id.to_string()) - ); - - let raw_attempt = tokio::time::timeout( - std::time::Duration::from_millis(200), - mcp.read_stream_until_notification_message("codex/event/raw_response_item"), - ) - .await; - assert!( - raw_attempt.is_err(), - "unexpected raw item notification when not opted in" - ); - Ok(()) -} - -#[tokio::test] -async fn test_send_message_raw_notifications_opt_in() -> Result<()> { - let server = responses::start_mock_server().await; - let body = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let _response_mock = responses::mount_sse_once(&server, body).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - developer_instructions: Some("Use the test harness tools.".to_string()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::<_>(new_conv_resp)?; - - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: true, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::<_>(add_listener_resp)?; - - let send_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - - let developer = read_raw_response_item(&mut mcp, conversation_id).await; - assert_permissions_message(&developer); - assert_developer_message(&developer, "Use the test harness tools."); - - let contextual_user = read_raw_response_item(&mut mcp, conversation_id).await; - assert_instructions_message(&contextual_user); - assert_environment_message(&contextual_user); - - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_id)), - ) - .await??; - let _ok: SendUserMessageResponse = to_response::(response)?; - - let user_message = read_raw_response_item(&mut mcp, conversation_id).await; - assert_user_message(&user_message, "Hello"); - - let assistant_message = read_raw_response_item(&mut mcp, conversation_id).await; - assert_assistant_message(&assistant_message, "Done"); - - let _ = tokio::time::timeout( - std::time::Duration::from_millis(250), - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await; - - Ok(()) -} - -#[tokio::test] -async fn test_send_message_session_not_found() -> Result<()> { - // Start MCP without creating a Codex session - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let unknown = ThreadId::new(); - let req_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id: unknown, - items: vec![InputItem::Text { - text: "ping".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - - // Expect an error response for unknown conversation. - let err = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(req_id)), - ) - .await??; - assert_eq!(err.id, RequestId::Integer(req_id)); - Ok(()) -} - -#[tokio::test] -async fn test_send_message_rejects_oversized_input() -> Result<()> { - let server = responses::start_mock_server().await; - let body = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let _response_mock = responses::mount_sse_once(&server, body).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::<_>(new_conv_resp)?; - - let oversized_input = "x".repeat(MAX_USER_INPUT_TEXT_CHARS + 1); - let req_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: oversized_input.clone(), - text_elements: Vec::new(), - }], - }) - .await?; - - let err: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(req_id)), - ) - .await??; - - assert_eq!(err.error.code, INVALID_PARAMS_ERROR_CODE); - assert_eq!( - err.error.message, - format!("Input exceeds the maximum length of {MAX_USER_INPUT_TEXT_CHARS} characters.") - ); - let data = err.error.data.expect("expected structured error data"); - assert_eq!(data["input_error_code"], INPUT_TOO_LARGE_ERROR_CODE); - assert_eq!(data["max_chars"], MAX_USER_INPUT_TEXT_CHARS); - assert_eq!(data["actual_chars"], oversized_input.chars().count()); - - Ok(()) -} - -#[tokio::test] -async fn resume_with_model_mismatch_appends_model_switch_once() -> Result<()> { - let server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence( - &server, - vec![ - responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]), - responses::sse(vec![ - responses::ev_response_created("resp-2"), - responses::ev_assistant_message("msg-2", "Done again"), - responses::ev_completed("resp-2"), - ]), - ], - ) - .await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let filename_ts = "2025-01-02T12-00-00"; - let meta_rfc3339 = "2025-01-02T12:00:00Z"; - let preview = "Resume me"; - let conversation_id = create_fake_rollout( - codex_home.path(), - filename_ts, - meta_rfc3339, - preview, - Some("mock_provider"), - None, - )?; - let rollout_path = rollout_path(codex_home.path(), filename_ts, &conversation_id); - append_rollout_turn_context(&rollout_path, meta_rfc3339, "previous-model")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let resume_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: Some(rollout_path.clone()), - conversation_id: None, - history: None, - overrides: Some(NewConversationParams { - model: Some("gpt-5.2-codex".to_string()), - ..Default::default() - }), - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id, .. - } = to_response::(resume_resp)?; - - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::<_>(add_listener_resp)?; - - send_message("hello after resume", conversation_id, &mut mcp).await?; - send_message("second turn", conversation_id, &mut mcp).await?; - - let requests = response_mock.requests(); - assert_eq!(requests.len(), 2, "expected two model requests"); - - let first_developer_texts = requests[0].message_input_texts("developer"); - let first_model_switch_count = first_developer_texts - .iter() - .filter(|text| text.contains("")) - .count(); - assert!( - first_model_switch_count >= 1, - "expected model switch message on first post-resume turn, got {first_developer_texts:?}" - ); - - let second_developer_texts = requests[1].message_input_texts("developer"); - let second_model_switch_count = second_developer_texts - .iter() - .filter(|text| text.contains("")) - .count(); - assert_eq!( - second_model_switch_count, 1, - "did not expect duplicate model switch message on second post-resume turn, got {second_developer_texts:?}" - ); - - Ok(()) -} - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} - -#[expect(clippy::expect_used)] -async fn read_raw_response_item(mcp: &mut McpProcess, conversation_id: ThreadId) -> ResponseItem { - // TODO: Switch to rawResponseItem/completed once we migrate to app server v2 in codex web. - loop { - let raw_notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/raw_response_item"), - ) - .await - .expect("codex/event/raw_response_item notification timeout") - .expect("codex/event/raw_response_item notification resp"); - - let serde_json::Value::Object(params) = raw_notification - .params - .expect("codex/event/raw_response_item should have params") - else { - panic!("codex/event/raw_response_item should have params"); - }; - - let conversation_id_value = params - .get("conversationId") - .and_then(|value| value.as_str()) - .expect("raw response item should include conversationId"); - - assert_eq!( - conversation_id_value, - conversation_id.to_string(), - "raw response item conversation mismatch" - ); - - let msg_value = params - .get("msg") - .cloned() - .expect("raw response item should include msg payload"); - - // Ghost snapshots are produced concurrently and may arrive before the model reply. - let event: RawResponseItemEvent = - serde_json::from_value(msg_value).expect("deserialize raw response item"); - if !matches!(event.item, ResponseItem::GhostSnapshot { .. }) { - return event.item; - } - } -} - -fn assert_instructions_message(item: &ResponseItem) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "user"); - let texts = content_texts(content); - let is_instructions = texts - .iter() - .any(|text| text.starts_with("# AGENTS.md instructions for ")); - assert!( - is_instructions, - "expected instructions message, got {texts:?}" - ); - } - other => panic!("expected instructions message, got {other:?}"), - } -} - -fn assert_permissions_message(item: &ResponseItem) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "developer"); - let texts = content_texts(content); - let expected = DeveloperInstructions::from_policy( - &SandboxPolicy::DangerFullAccess, - AskForApproval::Never, - &Policy::empty(), - &PathBuf::from("/tmp"), - false, - ) - .into_text(); - assert!( - texts.iter().any(|text| *text == expected), - "expected permissions developer message, got {texts:?}" - ); - } - other => panic!("expected permissions message, got {other:?}"), - } -} - -fn assert_developer_message(item: &ResponseItem, expected_text: &str) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "developer"); - let texts = content_texts(content); - assert!( - texts.contains(&expected_text), - "expected developer instructions message, got {texts:?}" - ); - } - other => panic!("expected developer instructions message, got {other:?}"), - } -} - -fn assert_environment_message(item: &ResponseItem) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "user"); - let texts = content_texts(content); - assert!( - texts - .iter() - .any(|text| text.contains("")), - "expected environment context message, got {texts:?}" - ); - } - other => panic!("expected environment message, got {other:?}"), - } -} - -fn assert_user_message(item: &ResponseItem, expected_text: &str) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "user"); - let texts = content_texts(content); - assert_eq!(texts, vec![expected_text]); - } - other => panic!("expected user message, got {other:?}"), - } -} - -fn assert_assistant_message(item: &ResponseItem, expected_text: &str) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "assistant"); - let texts = content_texts(content); - assert_eq!(texts, vec![expected_text]); - } - other => panic!("expected assistant message, got {other:?}"), - } -} - -fn content_texts(content: &[ContentItem]) -> Vec<&str> { - content - .iter() - .filter_map(|item| match item { - ContentItem::InputText { text, .. } | ContentItem::OutputText { text } => { - Some(text.as_str()) - } - _ => None, - }) - .collect() -} - -fn append_rollout_turn_context(path: &Path, timestamp: &str, model: &str) -> std::io::Result<()> { - let line = RolloutLine { - timestamp: timestamp.to_string(), - item: RolloutItem::TurnContext(TurnContextItem { - turn_id: None, - cwd: PathBuf::from("/"), - current_date: None, - timezone: None, - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - network: None, - model: model.to_string(), - personality: None, - collaboration_mode: None, - realtime_active: Some(false), - effort: None, - summary: ReasoningSummary::Auto, - user_instructions: None, - developer_instructions: None, - final_output_json_schema: None, - truncation_policy: None, - }), - }; - let serialized = serde_json::to_string(&line).map_err(std::io::Error::other)?; - std::fs::OpenOptions::new() - .append(true) - .open(path)? - .write_all(format!("{serialized}\n").as_bytes()) -} diff --git a/codex-rs/app-server/tests/suite/set_default_model.rs b/codex-rs/app-server/tests/suite/set_default_model.rs deleted file mode 100644 index b56c54dbd9..0000000000 --- a/codex-rs/app-server/tests/suite/set_default_model.rs +++ /dev/null @@ -1,64 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SetDefaultModelParams; -use codex_app_server_protocol::SetDefaultModelResponse; -use codex_core::config::ConfigToml; -use pretty_assertions::assert_eq; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn set_default_model_persists_overrides() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let params = SetDefaultModelParams { - model: Some("gpt-4.1".to_string()), - reasoning_effort: None, - }; - - let request_id = mcp.send_set_default_model_request(params).await?; - - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let _: SetDefaultModelResponse = to_response(resp)?; - - let config_path = codex_home.path().join("config.toml"); - let config_contents = tokio::fs::read_to_string(&config_path).await?; - let config_toml: ConfigToml = toml::from_str(&config_contents)?; - - assert_eq!( - ConfigToml { - model: Some("gpt-4.1".to_string()), - model_reasoning_effort: None, - ..Default::default() - }, - config_toml, - ); - Ok(()) -} - -// Helper to create a config.toml; mirrors create_conversation.rs -fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - r#" -model = "gpt-5.1-codex-max" -model_reasoning_effort = "medium" -"#, - ) -} diff --git a/codex-rs/app-server/tests/suite/user_agent.rs b/codex-rs/app-server/tests/suite/user_agent.rs deleted file mode 100644 index 9178a3ef58..0000000000 --- a/codex-rs/app-server/tests/suite/user_agent.rs +++ /dev/null @@ -1,43 +0,0 @@ -use anyhow::Result; -use app_test_support::DEFAULT_CLIENT_NAME; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::GetUserAgentResponse; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn get_user_agent_returns_current_codex_user_agent() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_get_user_agent_request().await?; - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let os_info = os_info::get(); - let originator = DEFAULT_CLIENT_NAME; - let os_type = os_info.os_type(); - let os_version = os_info.version(); - let architecture = os_info.architecture().unwrap_or("unknown"); - let terminal_ua = codex_core::terminal::user_agent(); - let user_agent = format!( - "{originator}/0.0.0 ({os_type} {os_version}; {architecture}) {terminal_ua} ({DEFAULT_CLIENT_NAME}; 0.1.0)" - ); - - let received: GetUserAgentResponse = to_response(response)?; - let expected = GetUserAgentResponse { user_agent }; - - assert_eq!(received, expected); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/user_info.rs b/codex-rs/app-server/tests/suite/user_info.rs deleted file mode 100644 index 6a44f1a3ab..0000000000 --- a/codex-rs/app-server/tests/suite/user_info.rs +++ /dev/null @@ -1,46 +0,0 @@ -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::McpProcess; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::UserInfoResponse; -use codex_core::auth::AuthCredentialsStoreMode; -use pretty_assertions::assert_eq; -use std::time::Duration; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn user_info_returns_email_from_auth_json() -> Result<()> { - let codex_home = TempDir::new()?; - - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("access") - .refresh_token("refresh") - .email("user@example.com"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_user_info_request().await?; - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let received: UserInfoResponse = to_response(response)?; - let expected = UserInfoResponse { - alleged_user_email: Some("user@example.com".to_string()), - }; - - assert_eq!(received, expected); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/rate_limits.rs b/codex-rs/app-server/tests/suite/v2/rate_limits.rs index 6f66d7bff7..51048202f6 100644 --- a/codex-rs/app-server/tests/suite/v2/rate_limits.rs +++ b/codex-rs/app-server/tests/suite/v2/rate_limits.rs @@ -6,7 +6,7 @@ use app_test_support::write_chatgpt_auth; use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginApiKeyParams; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RateLimitWindow; use codex_app_server_protocol::RequestId; @@ -221,17 +221,14 @@ async fn get_account_rate_limits_returns_snapshot() -> Result<()> { } async fn login_with_api_key(mcp: &mut McpProcess, api_key: &str) -> Result<()> { - let request_id = mcp - .send_login_api_key_request(LoginApiKeyParams { - api_key: api_key.to_string(), - }) - .await?; - - timeout( + let request_id = mcp.send_login_account_api_key_request(api_key).await?; + let response: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_response_message(RequestId::Integer(request_id)), ) .await??; + let login: LoginAccountResponse = to_response(response)?; + assert_eq!(login, LoginAccountResponse::ApiKey {}); Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs index 139e8b378a..71150d7126 100644 --- a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs +++ b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs @@ -5,7 +5,7 @@ use app_test_support::create_mock_responses_server_sequence_unchecked; use app_test_support::to_response; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginApiKeyParams; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadRealtimeAppendAudioParams; use codex_app_server_protocol::ThreadRealtimeAppendAudioResponse; @@ -350,17 +350,14 @@ async fn read_notification(mcp: &mut McpProcess, method: &s } async fn login_with_api_key(mcp: &mut McpProcess, api_key: &str) -> Result<()> { - let request_id = mcp - .send_login_api_key_request(LoginApiKeyParams { - api_key: api_key.to_string(), - }) - .await?; - - timeout( + let request_id = mcp.send_login_account_api_key_request(api_key).await?; + let response: JSONRPCResponse = timeout( DEFAULT_TIMEOUT, mcp.read_stream_until_response_message(RequestId::Integer(request_id)), ) .await??; + let login: LoginAccountResponse = to_response(response)?; + assert_eq!(login, LoginAccountResponse::ApiKey {}); Ok(()) } diff --git a/codex-rs/docs/codex_mcp_interface.md b/codex-rs/docs/codex_mcp_interface.md index 763f2602ad..b4e3adfe53 100644 --- a/codex-rs/docs/codex_mcp_interface.md +++ b/codex-rs/docs/codex_mcp_interface.md @@ -1,38 +1,36 @@ # Codex MCP Server Interface [experimental] -This document describes Codex’s experimental MCP server interface: a JSON‑RPC API that runs over the Model Context Protocol (MCP) transport to control a local Codex engine. +This document describes Codex's experimental MCP server interface: a JSON-RPC API that runs over the Model Context Protocol (MCP) transport to control a local Codex engine. - Status: experimental and subject to change without notice - Server binary: `codex mcp-server` (or `codex-mcp-server`) -- Transport: standard MCP over stdio (JSON‑RPC 2.0, line‑delimited) +- Transport: standard MCP over stdio (JSON-RPC 2.0, line-delimited) ## Overview -Codex exposes a small set of MCP‑compatible methods to create and manage conversations, send user input, receive live events, and handle approval prompts. The types are defined in `protocol/src/mcp_protocol.rs` and re‑used by the MCP server implementation in `mcp-server/`. +Codex exposes MCP-compatible methods to manage threads, turns, accounts, config, and approvals. The types live in `app-server-protocol/src/protocol/{common,v1,v2}.rs` and are consumed by the app server implementation in `app-server/`. At a glance: -- Conversations - - `newConversation` → start a Codex session - - `sendUserMessage` / `sendUserTurn` → send user input into a conversation - - `interruptConversation` → stop the current turn - - `listConversations`, `resumeConversation`, `archiveConversation` -- Configuration and info - - `getUserSavedConfig`, `setDefaultModel`, `getUserAgent`, `userInfo` - - `model/list` → enumerate available models and reasoning options - - `collaborationMode/list` → enumerate collaboration mode presets (experimental) -- Auth +- Primary v2 RPCs + - `thread/start`, `thread/resume`, `thread/fork`, `thread/read`, `thread/list` + - `turn/start`, `turn/steer`, `turn/interrupt` - `account/read`, `account/login/start`, `account/login/cancel`, `account/logout`, `account/rateLimits/read` - - notifications: `account/login/completed`, `account/updated`, `account/rateLimits/updated` -- Utilities - - `gitDiffToRemote`, `execOneOffCommand` -- Approvals (server → client requests) + - `config/read`, `config/value/write`, `config/batchWrite` + - `model/list`, `app/list`, `collaborationMode/list` +- Remaining v1 compatibility RPCs + - `getConversationSummary` + - `getAuthStatus` + - `gitDiffToRemote` + - `fuzzyFileSearch`, `fuzzyFileSearch/sessionStart`, `fuzzyFileSearch/sessionUpdate`, `fuzzyFileSearch/sessionStop` +- Notifications + - v2 typed notifications such as `thread/started`, `turn/completed`, `account/login/completed` + - `codex/event/*` stream notifications for live agent events + - `fuzzyFileSearch/sessionUpdated`, `fuzzyFileSearch/sessionCompleted` +- Approvals (server -> client requests) - `applyPatchApproval`, `execCommandApproval` -- Notifications (server → client) - - `loginChatGptComplete`, `authStatusChange` - - `codex/event` stream with agent events -See code for full type definitions and exact shapes: `protocol/src/mcp_protocol.rs`. +See code for full type definitions and exact shapes: `app-server-protocol/src/protocol/{common,v1,v2}.rs`. ## Starting the server @@ -50,73 +48,45 @@ npx @modelcontextprotocol/inspector codex mcp-server Use the separate `codex mcp` subcommand to manage configured MCP server launchers in `config.toml`. -## Conversations +## Threads and turns -Start a new session with optional overrides: +Use the v2 thread and turn APIs for all new integrations. `thread/start` creates a thread, `turn/start` submits user input, `turn/interrupt` stops an in-flight turn, and `thread/list` / `thread/read` expose persisted history. -Request `newConversation` params (subset): +`getConversationSummary` remains as a compatibility helper for clients that still need a summary lookup by `conversationId` or `rolloutPath`. -- `model`: string model id (e.g. "o3", "gpt-5.1", "gpt-5.1-codex") -- `profile`: optional named profile -- `cwd`: optional working directory -- `approvalPolicy`: `untrusted` | `on-request` | `on-failure` (deprecated) | `never` -- `sandbox`: `read-only` | `workspace-write` | `external-sandbox` (honors `networkAccess` restricted/enabled) | `danger-full-access` -- `config`: map of additional config overrides -- `baseInstructions`: optional instruction override -- `compactPrompt`: optional replacement for the default compaction prompt -- `includePlanTool` / `includeApplyPatchTool`: booleans - -Response: `{ conversationId, model, reasoningEffort?, rolloutPath }` - -Send input to the active turn: - -- `sendUserMessage` → enqueue items to the conversation -- `sendUserTurn` → structured turn with explicit `cwd`, `approvalPolicy`, `sandboxPolicy`, `model`, optional `effort`, `summary`, optional `personality`, and optional `outputSchema` (JSON Schema for the final assistant message) - -Valid `personality` values are `friendly`, `pragmatic`, and `none`. When `none` is selected, the personality placeholder is replaced with an empty string. - -For v2 threads, `turn/start` also accepts `outputSchema` to constrain the final assistant message for that turn. - -Interrupt a running turn: `interruptConversation`. - -List/resume/archive: `listConversations`, `resumeConversation`, `archiveConversation`. - -For v2 threads, use `thread/list` with filters such as `archived: true`, `cwd: "/path"`, or -`searchTerm: "needle"` to -narrow results, and `thread/unarchive` to restore archived rollouts to the active sessions -directory (it returns the restored thread summary). +For complete request and response shapes, see the app-server README and the protocol definitions in `app-server-protocol/src/protocol/v2.rs`. ## Models Fetch the catalog of models available in the current Codex build with `model/list`. The request accepts optional pagination inputs: -- `limit` – number of models to return (defaults to a server-selected value) -- `cursor` – opaque string from the previous response’s `nextCursor` +- `limit` - number of models to return (defaults to a server-selected value) +- `cursor` - opaque string from the previous response's `nextCursor` Each response yields: -- `data` – ordered list of models. A model includes: +- `data` - ordered list of models. A model includes: - `id`, `model`, `displayName`, `description` - - `supportedReasoningEfforts` – array of objects with: - - `reasoningEffort` – one of `none|minimal|low|medium|high|xhigh` - - `description` – human-friendly label for the effort - - `defaultReasoningEffort` – suggested effort for the UI - - `inputModalities` – accepted input types for the model - - `supportsPersonality` – whether the model supports personality-specific instructions - - `isDefault` – whether the model is recommended for most users - - `upgrade` – optional recommended upgrade model id - - `upgradeInfo` – optional upgrade metadata object with: - - `model` – recommended upgrade model id - - `upgradeCopy` – optional display copy for the upgrade recommendation - - `modelLink` – optional link for the upgrade recommendation - - `migrationMarkdown` – optional markdown shown when presenting the upgrade -- `nextCursor` – pass into the next request to continue paging (optional) + - `supportedReasoningEfforts` - array of objects with: + - `reasoningEffort` - one of `none|minimal|low|medium|high|xhigh` + - `description` - human-friendly label for the effort + - `defaultReasoningEffort` - suggested effort for the UI + - `inputModalities` - accepted input types for the model + - `supportsPersonality` - whether the model supports personality-specific instructions + - `isDefault` - whether the model is recommended for most users + - `upgrade` - optional recommended upgrade model id + - `upgradeInfo` - optional upgrade metadata object with: + - `model` - recommended upgrade model id + - `upgradeCopy` - optional display copy for the upgrade recommendation + - `modelLink` - optional link for the upgrade recommendation + - `migrationMarkdown` - optional markdown shown when presenting the upgrade +- `nextCursor` - pass into the next request to continue paging (optional) ## Collaboration modes (experimental) Fetch the built-in collaboration mode presets with `collaborationMode/list`. This endpoint does not accept pagination and returns the full list in one response: -- `data` – ordered list of collaboration mode masks (partial settings to apply on top of the base mode) +- `data` - ordered list of collaboration mode masks (partial settings to apply on top of the base mode) - For tri-state fields like `reasoning_effort` and `developer_instructions`, omit the field to keep the current value, set it to `null` to clear it, or set a concrete value to update it. When sending `turn/start` with `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode". @@ -125,16 +95,14 @@ When sending `turn/start` with `collaborationMode`, `settings.developer_instruct While a conversation runs, the server sends notifications: -- `codex/event` with the serialized Codex event payload. The shape matches `core/src/protocol.rs`’s `Event` and `EventMsg` types. Some notifications include a `_meta.requestId` to correlate with the originating request. -- Auth notifications via method names `loginChatGptComplete` and `authStatusChange`. +- `codex/event` with the serialized Codex event payload. The shape matches `core/src/protocol.rs`'s `Event` and `EventMsg` types. Some notifications include a `_meta.requestId` to correlate with the originating request. +- `fuzzyFileSearch/sessionUpdated` and `fuzzyFileSearch/sessionCompleted` for the legacy fuzzy search flow. Clients should render events and, when present, surface approval requests (see next section). ## Tool responses -The `codex` and `codex-reply` tools return standard MCP `CallToolResult` payloads. For -compatibility with MCP clients that prefer `structuredContent`, Codex mirrors the -content blocks inside `structuredContent` alongside the `threadId`. +The `codex` and `codex-reply` tools return standard MCP `CallToolResult` payloads. For compatibility with MCP clients that prefer `structuredContent`, Codex mirrors the content blocks inside `structuredContent` alongside the `threadId`. Example: @@ -148,9 +116,9 @@ Example: } ``` -## Approvals (server → client) +## Approvals (server -> client) -When Codex needs approval to apply changes or run commands, the server issues JSON‑RPC requests to the client: +When Codex needs approval to apply changes or run commands, the server issues JSON-RPC requests to the client: - `applyPatchApproval { conversationId, callId, fileChanges, reason?, grantRoot? }` - `execCommandApproval { conversationId, callId, approvalId?, command, cwd, reason? }` @@ -159,28 +127,17 @@ The client must reply with `{ decision: "allow" | "deny" }` for each request. ## Auth helpers -For the complete request/response shapes and flow examples, see the [“Auth endpoints (v2)” section in the app‑server README](../app-server/README.md#auth-endpoints-v2). +For the complete request/response shapes and flow examples, see the [Auth endpoints (v2) section in the app-server README](../app-server/README.md#auth-endpoints-v2). -## Example: start and send a message +## Legacy compatibility methods -```json -{ "jsonrpc": "2.0", "id": 1, "method": "newConversation", "params": { "model": "gpt-5.1", "approvalPolicy": "on-request" } } -``` +The server still accepts a narrow v1 compatibility surface for existing app clients: -Server responds: - -```json -{ "jsonrpc": "2.0", "id": 1, "result": { "conversationId": "c7b0…", "model": "gpt-5.1", "rolloutPath": "/path/to/rollout.jsonl" } } -``` - -Then send input: - -```json -{ "jsonrpc": "2.0", "id": 2, "method": "sendUserMessage", "params": { "conversationId": "c7b0…", "items": [{ "type": "text", "text": "Hello Codex" }] } } -``` - -While processing, the server emits `codex/event` notifications containing agent output, approvals, and status updates. +- `getConversationSummary` +- `getAuthStatus` +- `gitDiffToRemote` +- `fuzzyFileSearch`, `fuzzyFileSearch/sessionStart`, `fuzzyFileSearch/sessionUpdate`, `fuzzyFileSearch/sessionStop` ## Compatibility and stability -This interface is experimental. Method names, fields, and event shapes may evolve. For the authoritative schema, consult `protocol/src/mcp_protocol.rs` and the corresponding server wiring in `mcp-server/`. +This interface is experimental. Method names, fields, and event shapes may evolve. For the authoritative schema, consult `app-server-protocol/src/protocol/{common,v1,v2}.rs` and the corresponding server wiring in `app-server/`. From d7eb195b62a54d63ddd28e884d0b4aed0276cdd3 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 3 Mar 2026 13:37:40 -0800 Subject: [PATCH 342/385] chore(app-server): restore EventMsg TS types (#13397) Realized EventMsg generated types were unintentionally removed as part of this PR: https://github.com/openai/codex/pull/13375 Turns out our TypeScript export pipeline relied on transitively reaching `EventMsg`. We should still export `EventMsg` explicitly since we're still emitting `codex/event/*` events (for now, but getting dropped soon as well). --- .../schema/typescript/AgentMessageContent.ts | 5 + .../AgentMessageContentDeltaEvent.ts | 5 + .../typescript/AgentMessageDeltaEvent.ts | 5 + .../schema/typescript/AgentMessageEvent.ts | 6 + .../schema/typescript/AgentMessageItem.ts | 21 +++ .../typescript/AgentReasoningDeltaEvent.ts | 5 + .../schema/typescript/AgentReasoningEvent.ts | 5 + .../AgentReasoningRawContentDeltaEvent.ts | 5 + .../AgentReasoningRawContentEvent.ts | 5 + .../AgentReasoningSectionBreakEvent.ts | 5 + .../schema/typescript/AgentStatus.ts | 8 + .../ApplyPatchApprovalRequestEvent.ts | 23 +++ .../schema/typescript/AskForApproval.ts | 10 ++ .../schema/typescript/BackgroundEventEvent.ts | 5 + .../schema/typescript/ByteRange.ts | 13 ++ .../schema/typescript/CallToolResult.ts | 9 ++ .../schema/typescript/CodexErrorInfo.ts | 8 + .../CollabAgentInteractionBeginEvent.ts | 23 +++ .../CollabAgentInteractionEndEvent.ts | 36 +++++ .../schema/typescript/CollabAgentRef.ts | 18 +++ .../typescript/CollabAgentSpawnBeginEvent.ts | 19 +++ .../typescript/CollabAgentSpawnEndEvent.ts | 36 +++++ .../typescript/CollabAgentStatusEntry.ts | 23 +++ .../typescript/CollabCloseBeginEvent.ts | 18 +++ .../schema/typescript/CollabCloseEndEvent.ts | 32 ++++ .../typescript/CollabResumeBeginEvent.ts | 26 ++++ .../schema/typescript/CollabResumeEndEvent.ts | 32 ++++ .../typescript/CollabWaitingBeginEvent.ts | 23 +++ .../typescript/CollabWaitingEndEvent.ts | 24 +++ .../typescript/ContextCompactedEvent.ts | 5 + .../typescript/ContextCompactionItem.ts | 5 + .../schema/typescript/CreditsSnapshot.ts | 5 + .../schema/typescript/CustomPrompt.ts | 5 + .../typescript/DeprecationNoticeEvent.ts | 13 ++ .../DynamicToolCallOutputContentItem.ts | 5 + .../typescript/DynamicToolCallRequest.ts | 6 + .../DynamicToolCallResponseEvent.ts | 39 +++++ .../typescript/ElicitationRequestEvent.ts | 5 + .../schema/typescript/ErrorEvent.ts | 6 + .../schema/typescript/EventMsg.ts | 82 ++++++++++ .../typescript/ExecApprovalRequestEvent.ts | 62 ++++++++ .../typescript/ExecCommandBeginEvent.ts | 35 +++++ .../schema/typescript/ExecCommandEndEvent.ts | 64 ++++++++ .../typescript/ExecCommandOutputDeltaEvent.ts | 18 +++ .../schema/typescript/ExecCommandSource.ts | 5 + .../schema/typescript/ExecCommandStatus.ts | 5 + .../schema/typescript/ExecOutputStream.ts | 5 + .../typescript/ExitedReviewModeEvent.ts | 6 + .../typescript/FileSystemPermissions.ts | 6 + .../GetHistoryEntryResponseEvent.ts | 10 ++ .../schema/typescript/HistoryEntry.ts | 5 + .../schema/typescript/ItemCompletedEvent.ts | 7 + .../schema/typescript/ItemStartedEvent.ts | 7 + .../ListCustomPromptsResponseEvent.ts | 9 ++ .../ListRemoteSkillsResponseEvent.ts | 9 ++ .../typescript/ListSkillsResponseEvent.ts | 9 ++ .../schema/typescript/MacOsPermissions.ts | 7 + .../schema/typescript/McpAuthStatus.ts | 5 + .../schema/typescript/McpInvocation.ts | 18 +++ .../typescript/McpListToolsResponseEvent.ts | 25 ++++ .../typescript/McpStartupCompleteEvent.ts | 6 + .../schema/typescript/McpStartupFailure.ts | 5 + .../schema/typescript/McpStartupStatus.ts | 5 + .../typescript/McpStartupUpdateEvent.ts | 14 ++ .../typescript/McpToolCallBeginEvent.ts | 10 ++ .../schema/typescript/McpToolCallEndEvent.ts | 15 ++ .../schema/typescript/ModelRerouteEvent.ts | 6 + .../schema/typescript/ModelRerouteReason.ts | 5 + .../schema/typescript/NetworkAccess.ts | 8 + .../typescript/NetworkApprovalContext.ts | 6 + .../typescript/NetworkApprovalProtocol.ts | 5 + .../schema/typescript/PatchApplyBeginEvent.ts | 23 +++ .../schema/typescript/PatchApplyEndEvent.ts | 36 +++++ .../schema/typescript/PatchApplyStatus.ts | 5 + .../schema/typescript/PermissionProfile.ts | 7 + .../schema/typescript/PlanDeltaEvent.ts | 5 + .../schema/typescript/PlanItem.ts | 5 + .../schema/typescript/PlanItemArg.ts | 6 + .../schema/typescript/RateLimitSnapshot.ts | 8 + .../schema/typescript/RateLimitWindow.ts | 17 +++ .../schema/typescript/RawResponseItemEvent.ts | 6 + .../schema/typescript/ReadOnlyAccess.ts | 19 +++ .../schema/typescript/RealtimeAudioFrame.ts | 5 + .../RealtimeConversationClosedEvent.ts | 5 + .../RealtimeConversationRealtimeEvent.ts | 6 + .../RealtimeConversationStartedEvent.ts | 5 + .../schema/typescript/RealtimeEvent.ts | 8 + .../typescript/RealtimeHandoffMessage.ts | 5 + .../typescript/RealtimeHandoffRequested.ts | 6 + .../typescript/ReasoningContentDeltaEvent.ts | 5 + .../schema/typescript/ReasoningItem.ts | 5 + .../ReasoningRawContentDeltaEvent.ts | 5 + .../schema/typescript/RejectConfig.ts | 17 +++ .../typescript/RemoteSkillDownloadedEvent.ts | 8 + .../schema/typescript/RemoteSkillSummary.ts | 5 + .../typescript/RequestUserInputEvent.ts | 15 ++ .../typescript/RequestUserInputQuestion.ts | 6 + .../RequestUserInputQuestionOption.ts | 5 + .../schema/typescript/ReviewCodeLocation.ts | 9 ++ .../schema/typescript/ReviewFinding.ts | 9 ++ .../schema/typescript/ReviewLineRange.ts | 8 + .../schema/typescript/ReviewOutputEvent.ts | 9 ++ .../schema/typescript/ReviewRequest.ts | 9 ++ .../schema/typescript/ReviewTarget.ts | 9 ++ .../schema/typescript/SandboxPolicy.ts | 44 ++++++ .../typescript/SessionConfiguredEvent.ts | 58 ++++++++ .../typescript/SessionNetworkProxyRuntime.ts | 5 + .../schema/typescript/SkillDependencies.ts | 6 + .../schema/typescript/SkillErrorInfo.ts | 5 + .../schema/typescript/SkillInterface.ts | 5 + .../schema/typescript/SkillMetadata.ts | 12 ++ .../schema/typescript/SkillScope.ts | 5 + .../schema/typescript/SkillToolDependency.ts | 5 + .../schema/typescript/SkillsListEntry.ts | 7 + .../schema/typescript/StepStatus.ts | 5 + .../schema/typescript/StreamErrorEvent.ts | 12 ++ .../typescript/TerminalInteractionEvent.ts | 17 +++ .../schema/typescript/TextElement.ts | 14 ++ .../typescript/ThreadNameUpdatedEvent.ts | 6 + .../typescript/ThreadRolledBackEvent.ts | 9 ++ .../schema/typescript/TokenCountEvent.ts | 7 + .../schema/typescript/TokenUsage.ts | 5 + .../schema/typescript/TokenUsageInfo.ts | 6 + .../schema/typescript/TurnAbortReason.ts | 5 + .../schema/typescript/TurnAbortedEvent.ts | 6 + .../schema/typescript/TurnCompleteEvent.ts | 5 + .../schema/typescript/TurnDiffEvent.ts | 5 + .../schema/typescript/TurnItem.ts | 11 ++ .../schema/typescript/TurnStartedEvent.ts | 6 + .../schema/typescript/UndoCompletedEvent.ts | 5 + .../schema/typescript/UndoStartedEvent.ts | 5 + .../schema/typescript/UpdatePlanArgs.ts | 10 ++ .../schema/typescript/UserInput.ts | 16 ++ .../schema/typescript/UserMessageEvent.ts | 22 +++ .../schema/typescript/UserMessageItem.ts | 6 + .../typescript/ViewImageToolCallEvent.ts | 13 ++ .../schema/typescript/WarningEvent.ts | 5 + .../schema/typescript/WebSearchBeginEvent.ts | 5 + .../schema/typescript/WebSearchEndEvent.ts | 6 + .../schema/typescript/WebSearchItem.ts | 6 + .../schema/typescript/index.ts | 140 ++++++++++++++++++ codex-rs/app-server-protocol/src/export.rs | 2 + 142 files changed, 1844 insertions(+) create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ByteRange.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/EventMsg.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/PlanItem.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillScope.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/StepStatus.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TextElement.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnItem.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/UserInput.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts new file mode 100644 index 0000000000..dc2cfb77e3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentMessageContent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentMessageContent = { "type": "Text", text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts new file mode 100644 index 0000000000..1473a4f2bc --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentMessageContentDeltaEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentMessageContentDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts new file mode 100644 index 0000000000..1e12d85fbb --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentMessageDeltaEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentMessageDeltaEvent = { delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts new file mode 100644 index 0000000000..b32680055f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { MessagePhase } from "./MessagePhase"; + +export type AgentMessageEvent = { message: string, phase: MessagePhase | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts new file mode 100644 index 0000000000..ee67a3e23b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentMessageItem.ts @@ -0,0 +1,21 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentMessageContent } from "./AgentMessageContent"; +import type { MessagePhase } from "./MessagePhase"; + +/** + * Assistant-authored message payload used in turn-item streams. + * + * `phase` is optional because not all providers/models emit it. Consumers + * should use it when present, but retain legacy completion semantics when it + * is `None`. + */ +export type AgentMessageItem = { id: string, content: Array, +/** + * Optional phase metadata carried through from `ResponseItem::Message`. + * + * This is currently used by TUI rendering to distinguish mid-turn + * commentary from a final answer and avoid status-indicator jitter. + */ +phase?: MessagePhase, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts new file mode 100644 index 0000000000..fc2c221937 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningDeltaEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentReasoningDeltaEvent = { delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts new file mode 100644 index 0000000000..bf0062cd43 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentReasoningEvent = { text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts new file mode 100644 index 0000000000..fcfa816f5d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentDeltaEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentReasoningRawContentDeltaEvent = { delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts new file mode 100644 index 0000000000..364c278229 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningRawContentEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentReasoningRawContentEvent = { text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts new file mode 100644 index 0000000000..604aceed93 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentReasoningSectionBreakEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AgentReasoningSectionBreakEvent = { item_id: string, summary_index: bigint, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts b/codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts new file mode 100644 index 0000000000..ddf6789c78 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AgentStatus.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Agent lifecycle status, derived from emitted events. + */ +export type AgentStatus = "pending_init" | "running" | { "completed": string | null } | { "errored": string } | "shutdown" | "not_found"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts new file mode 100644 index 0000000000..0c53cf50b8 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ApplyPatchApprovalRequestEvent.ts @@ -0,0 +1,23 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { FileChange } from "./FileChange"; + +export type ApplyPatchApprovalRequestEvent = { +/** + * Responses API call id for the associated patch apply call, if available. + */ +call_id: string, +/** + * Turn ID that this patch belongs to. + * Uses `#[serde(default)]` for backwards compatibility with older senders. + */ +turn_id: string, changes: { [key in string]?: FileChange }, +/** + * Optional explanatory reason (e.g. request for extra write access). + */ +reason: string | null, +/** + * When set, the agent is asking the user to allow writes under this root for the remainder of the session. + */ +grant_root: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts b/codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts new file mode 100644 index 0000000000..227eb44e77 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/AskForApproval.ts @@ -0,0 +1,10 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RejectConfig } from "./RejectConfig"; + +/** + * Determines the conditions under which the user is consulted to approve + * running the command proposed by Codex. + */ +export type AskForApproval = "untrusted" | "on-failure" | "on-request" | { "reject": RejectConfig } | "never"; diff --git a/codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts b/codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts new file mode 100644 index 0000000000..236b1dd888 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/BackgroundEventEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BackgroundEventEvent = { message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ByteRange.ts b/codex-rs/app-server-protocol/schema/typescript/ByteRange.ts new file mode 100644 index 0000000000..ab36a79acd --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ByteRange.ts @@ -0,0 +1,13 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ByteRange = { +/** + * Start byte offset (inclusive) within the UTF-8 text buffer. + */ +start: number, +/** + * End byte offset (exclusive) within the UTF-8 text buffer. + */ +end: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts b/codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts new file mode 100644 index 0000000000..e7a471d465 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CallToolResult.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { JsonValue } from "./serde_json/JsonValue"; + +/** + * The server's response to a tool call. + */ +export type CallToolResult = { content: Array, structuredContent?: JsonValue, isError?: boolean, _meta?: JsonValue, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts b/codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts new file mode 100644 index 0000000000..522b91ce20 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CodexErrorInfo.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Codex errors that we expose to clients. + */ +export type CodexErrorInfo = "context_window_exceeded" | "usage_limit_exceeded" | "server_overloaded" | { "http_connection_failed": { http_status_code: number | null, } } | { "response_stream_connection_failed": { http_status_code: number | null, } } | "internal_server_error" | "unauthorized" | "bad_request" | "sandbox_error" | { "response_stream_disconnected": { http_status_code: number | null, } } | { "response_too_many_failed_attempts": { http_status_code: number | null, } } | "thread_rollback_failed" | "other"; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts new file mode 100644 index 0000000000..7109741999 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionBeginEvent.ts @@ -0,0 +1,23 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentInteractionBeginEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the receiver. + */ +receiver_thread_id: ThreadId, +/** + * Prompt sent from the sender to the receiver. Can be empty to prevent CoT + * leaking at the beginning. + */ +prompt: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts new file mode 100644 index 0000000000..5458e06dce --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentInteractionEndEvent.ts @@ -0,0 +1,36 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentStatus } from "./AgentStatus"; +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentInteractionEndEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the receiver. + */ +receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, +/** + * Prompt sent from the sender to the receiver. Can be empty to prevent CoT + * leaking at the beginning. + */ +prompt: string, +/** + * Last known status of the receiver agent reported to the sender agent. + */ +status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts new file mode 100644 index 0000000000..cae7bf88b8 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentRef.ts @@ -0,0 +1,18 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentRef = { +/** + * Thread ID of the receiver/new agent. + */ +thread_id: ThreadId, +/** + * Optional nickname assigned to an AgentControl-spawned sub-agent. + */ +agent_nickname?: string | null, +/** + * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + */ +agent_role?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts new file mode 100644 index 0000000000..a86598e20c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnBeginEvent.ts @@ -0,0 +1,19 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentSpawnBeginEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the + * beginning. + */ +prompt: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts new file mode 100644 index 0000000000..34753c8e08 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentSpawnEndEvent.ts @@ -0,0 +1,36 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentStatus } from "./AgentStatus"; +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentSpawnEndEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the newly spawned agent, if it was created. + */ +new_thread_id: ThreadId | null, +/** + * Optional nickname assigned to the new agent. + */ +new_agent_nickname?: string | null, +/** + * Optional role assigned to the new agent. + */ +new_agent_role?: string | null, +/** + * Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the + * beginning. + */ +prompt: string, +/** + * Last known status of the new agent reported to the sender agent. + */ +status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts b/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts new file mode 100644 index 0000000000..286d19423d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabAgentStatusEntry.ts @@ -0,0 +1,23 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentStatus } from "./AgentStatus"; +import type { ThreadId } from "./ThreadId"; + +export type CollabAgentStatusEntry = { +/** + * Thread ID of the receiver/new agent. + */ +thread_id: ThreadId, +/** + * Optional nickname assigned to an AgentControl-spawned sub-agent. + */ +agent_nickname?: string | null, +/** + * Optional role (agent_role) assigned to an AgentControl-spawned sub-agent. + */ +agent_role?: string | null, +/** + * Last known status of the agent. + */ +status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts new file mode 100644 index 0000000000..355d59523a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabCloseBeginEvent.ts @@ -0,0 +1,18 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; + +export type CollabCloseBeginEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the receiver. + */ +receiver_thread_id: ThreadId, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts new file mode 100644 index 0000000000..171886f1ef --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabCloseEndEvent.ts @@ -0,0 +1,32 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentStatus } from "./AgentStatus"; +import type { ThreadId } from "./ThreadId"; + +export type CollabCloseEndEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the receiver. + */ +receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, +/** + * Last known status of the receiver agent reported to the sender agent before + * the close. + */ +status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts new file mode 100644 index 0000000000..e6c1c3d5cd --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabResumeBeginEvent.ts @@ -0,0 +1,26 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; + +export type CollabResumeBeginEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the receiver. + */ +receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts new file mode 100644 index 0000000000..caf970ec28 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabResumeEndEvent.ts @@ -0,0 +1,32 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentStatus } from "./AgentStatus"; +import type { ThreadId } from "./ThreadId"; + +export type CollabResumeEndEvent = { +/** + * Identifier for the collab tool call. + */ +call_id: string, +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the receiver. + */ +receiver_thread_id: ThreadId, +/** + * Optional nickname assigned to the receiver agent. + */ +receiver_agent_nickname?: string | null, +/** + * Optional role assigned to the receiver agent. + */ +receiver_agent_role?: string | null, +/** + * Last known status of the receiver agent reported to the sender agent after + * resume. + */ +status: AgentStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts new file mode 100644 index 0000000000..f2f07f87ea --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingBeginEvent.ts @@ -0,0 +1,23 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CollabAgentRef } from "./CollabAgentRef"; +import type { ThreadId } from "./ThreadId"; + +export type CollabWaitingBeginEvent = { +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * Thread ID of the receivers. + */ +receiver_thread_ids: Array, +/** + * Optional nicknames/roles for receivers. + */ +receiver_agents?: Array, +/** + * ID of the waiting call. + */ +call_id: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts new file mode 100644 index 0000000000..929d59c611 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CollabWaitingEndEvent.ts @@ -0,0 +1,24 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentStatus } from "./AgentStatus"; +import type { CollabAgentStatusEntry } from "./CollabAgentStatusEntry"; +import type { ThreadId } from "./ThreadId"; + +export type CollabWaitingEndEvent = { +/** + * Thread ID of the sender. + */ +sender_thread_id: ThreadId, +/** + * ID of the waiting call. + */ +call_id: string, +/** + * Optional receiver metadata paired with final statuses. + */ +agent_statuses?: Array, +/** + * Last known status of the receiver agents reported to the sender agent. + */ +statuses: { [key in ThreadId]?: AgentStatus }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts new file mode 100644 index 0000000000..538ca7a1bc --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ContextCompactedEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ContextCompactedEvent = null; diff --git a/codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts b/codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts new file mode 100644 index 0000000000..dc3ab6388e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ContextCompactionItem.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ContextCompactionItem = { id: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts b/codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts new file mode 100644 index 0000000000..737bf99bef --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CreditsSnapshot.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type CreditsSnapshot = { has_credits: boolean, unlimited: boolean, balance: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts b/codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts new file mode 100644 index 0000000000..96fe75e969 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/CustomPrompt.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type CustomPrompt = { name: string, path: string, content: string, description: string | null, argument_hint: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts new file mode 100644 index 0000000000..c1a7d81314 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/DeprecationNoticeEvent.ts @@ -0,0 +1,13 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DeprecationNoticeEvent = { +/** + * Concise summary of what is deprecated. + */ +summary: string, +/** + * Optional extra guidance, such as migration steps or rationale. + */ +details: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts new file mode 100644 index 0000000000..8f432109d1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type DynamicToolCallOutputContentItem = { "type": "inputText", text: string, } | { "type": "inputImage", imageUrl: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts new file mode 100644 index 0000000000..94b0c65c66 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallRequest.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { JsonValue } from "./serde_json/JsonValue"; + +export type DynamicToolCallRequest = { callId: string, turnId: string, tool: string, arguments: JsonValue, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts new file mode 100644 index 0000000000..442c0ce6f3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts @@ -0,0 +1,39 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; +import type { JsonValue } from "./serde_json/JsonValue"; + +export type DynamicToolCallResponseEvent = { +/** + * Identifier for the corresponding DynamicToolCallRequest. + */ +call_id: string, +/** + * Turn ID that this dynamic tool call belongs to. + */ +turn_id: string, +/** + * Dynamic tool name. + */ +tool: string, +/** + * Dynamic tool call arguments. + */ +arguments: JsonValue, +/** + * Dynamic tool response content items. + */ +content_items: Array, +/** + * Whether the tool call succeeded. + */ +success: boolean, +/** + * Optional error text when the tool call failed before producing a response. + */ +error: string | null, +/** + * The duration of the dynamic tool call. + */ +duration: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts new file mode 100644 index 0000000000..045e304bdc --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ElicitationRequestEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ElicitationRequestEvent = { server_name: string, id: string | number, message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts new file mode 100644 index 0000000000..fafde767e0 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ErrorEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CodexErrorInfo } from "./CodexErrorInfo"; + +export type ErrorEvent = { message: string, codex_error_info: CodexErrorInfo | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts b/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts new file mode 100644 index 0000000000..5ccbe1e697 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts @@ -0,0 +1,82 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentMessageContentDeltaEvent } from "./AgentMessageContentDeltaEvent"; +import type { AgentMessageDeltaEvent } from "./AgentMessageDeltaEvent"; +import type { AgentMessageEvent } from "./AgentMessageEvent"; +import type { AgentReasoningDeltaEvent } from "./AgentReasoningDeltaEvent"; +import type { AgentReasoningEvent } from "./AgentReasoningEvent"; +import type { AgentReasoningRawContentDeltaEvent } from "./AgentReasoningRawContentDeltaEvent"; +import type { AgentReasoningRawContentEvent } from "./AgentReasoningRawContentEvent"; +import type { AgentReasoningSectionBreakEvent } from "./AgentReasoningSectionBreakEvent"; +import type { ApplyPatchApprovalRequestEvent } from "./ApplyPatchApprovalRequestEvent"; +import type { BackgroundEventEvent } from "./BackgroundEventEvent"; +import type { CollabAgentInteractionBeginEvent } from "./CollabAgentInteractionBeginEvent"; +import type { CollabAgentInteractionEndEvent } from "./CollabAgentInteractionEndEvent"; +import type { CollabAgentSpawnBeginEvent } from "./CollabAgentSpawnBeginEvent"; +import type { CollabAgentSpawnEndEvent } from "./CollabAgentSpawnEndEvent"; +import type { CollabCloseBeginEvent } from "./CollabCloseBeginEvent"; +import type { CollabCloseEndEvent } from "./CollabCloseEndEvent"; +import type { CollabResumeBeginEvent } from "./CollabResumeBeginEvent"; +import type { CollabResumeEndEvent } from "./CollabResumeEndEvent"; +import type { CollabWaitingBeginEvent } from "./CollabWaitingBeginEvent"; +import type { CollabWaitingEndEvent } from "./CollabWaitingEndEvent"; +import type { ContextCompactedEvent } from "./ContextCompactedEvent"; +import type { DeprecationNoticeEvent } from "./DeprecationNoticeEvent"; +import type { DynamicToolCallRequest } from "./DynamicToolCallRequest"; +import type { DynamicToolCallResponseEvent } from "./DynamicToolCallResponseEvent"; +import type { ElicitationRequestEvent } from "./ElicitationRequestEvent"; +import type { ErrorEvent } from "./ErrorEvent"; +import type { ExecApprovalRequestEvent } from "./ExecApprovalRequestEvent"; +import type { ExecCommandBeginEvent } from "./ExecCommandBeginEvent"; +import type { ExecCommandEndEvent } from "./ExecCommandEndEvent"; +import type { ExecCommandOutputDeltaEvent } from "./ExecCommandOutputDeltaEvent"; +import type { ExitedReviewModeEvent } from "./ExitedReviewModeEvent"; +import type { GetHistoryEntryResponseEvent } from "./GetHistoryEntryResponseEvent"; +import type { ItemCompletedEvent } from "./ItemCompletedEvent"; +import type { ItemStartedEvent } from "./ItemStartedEvent"; +import type { ListCustomPromptsResponseEvent } from "./ListCustomPromptsResponseEvent"; +import type { ListRemoteSkillsResponseEvent } from "./ListRemoteSkillsResponseEvent"; +import type { ListSkillsResponseEvent } from "./ListSkillsResponseEvent"; +import type { McpListToolsResponseEvent } from "./McpListToolsResponseEvent"; +import type { McpStartupCompleteEvent } from "./McpStartupCompleteEvent"; +import type { McpStartupUpdateEvent } from "./McpStartupUpdateEvent"; +import type { McpToolCallBeginEvent } from "./McpToolCallBeginEvent"; +import type { McpToolCallEndEvent } from "./McpToolCallEndEvent"; +import type { ModelRerouteEvent } from "./ModelRerouteEvent"; +import type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent"; +import type { PatchApplyEndEvent } from "./PatchApplyEndEvent"; +import type { PlanDeltaEvent } from "./PlanDeltaEvent"; +import type { RawResponseItemEvent } from "./RawResponseItemEvent"; +import type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent"; +import type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent"; +import type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent"; +import type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent"; +import type { ReasoningRawContentDeltaEvent } from "./ReasoningRawContentDeltaEvent"; +import type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent"; +import type { RequestUserInputEvent } from "./RequestUserInputEvent"; +import type { ReviewRequest } from "./ReviewRequest"; +import type { SessionConfiguredEvent } from "./SessionConfiguredEvent"; +import type { StreamErrorEvent } from "./StreamErrorEvent"; +import type { TerminalInteractionEvent } from "./TerminalInteractionEvent"; +import type { ThreadNameUpdatedEvent } from "./ThreadNameUpdatedEvent"; +import type { ThreadRolledBackEvent } from "./ThreadRolledBackEvent"; +import type { TokenCountEvent } from "./TokenCountEvent"; +import type { TurnAbortedEvent } from "./TurnAbortedEvent"; +import type { TurnCompleteEvent } from "./TurnCompleteEvent"; +import type { TurnDiffEvent } from "./TurnDiffEvent"; +import type { TurnStartedEvent } from "./TurnStartedEvent"; +import type { UndoCompletedEvent } from "./UndoCompletedEvent"; +import type { UndoStartedEvent } from "./UndoStartedEvent"; +import type { UpdatePlanArgs } from "./UpdatePlanArgs"; +import type { UserMessageEvent } from "./UserMessageEvent"; +import type { ViewImageToolCallEvent } from "./ViewImageToolCallEvent"; +import type { WarningEvent } from "./WarningEvent"; +import type { WebSearchBeginEvent } from "./WebSearchBeginEvent"; +import type { WebSearchEndEvent } from "./WebSearchEndEvent"; + +/** + * Response event from the agent + * NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen. + */ +export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "realtime_conversation_started" } & RealtimeConversationStartedEvent | { "type": "realtime_conversation_realtime" } & RealtimeConversationRealtimeEvent | { "type": "realtime_conversation_closed" } & RealtimeConversationClosedEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "dynamic_tool_call_response" } & DynamicToolCallResponseEvent | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts new file mode 100644 index 0000000000..cc13400900 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts @@ -0,0 +1,62 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; +import type { NetworkApprovalContext } from "./NetworkApprovalContext"; +import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; +import type { ParsedCommand } from "./ParsedCommand"; +import type { PermissionProfile } from "./PermissionProfile"; +import type { ReviewDecision } from "./ReviewDecision"; + +export type ExecApprovalRequestEvent = { +/** + * Identifier for the associated command execution item. + */ +call_id: string, +/** + * Identifier for this specific approval callback. + * + * When absent, the approval is for the command item itself (`call_id`). + * This is present for subcommand approvals (via execve intercept). + */ +approval_id?: string, +/** + * Turn ID that this command belongs to. + * Uses `#[serde(default)]` for backwards compatibility. + */ +turn_id: string, +/** + * The command to be executed. + */ +command: Array, +/** + * The command's working directory. + */ +cwd: string, +/** + * Optional human-readable reason for the approval (e.g. retry without sandbox). + */ +reason: string | null, +/** + * Optional network context for a blocked request that can be approved. + */ +network_approval_context?: NetworkApprovalContext, +/** + * Proposed execpolicy amendment that can be applied to allow future runs. + */ +proposed_execpolicy_amendment?: ExecPolicyAmendment, +/** + * Proposed network policy amendments (for example allow/deny this host in future). + */ +proposed_network_policy_amendments?: Array, +/** + * Optional additional filesystem permissions requested for this command. + */ +additional_permissions?: PermissionProfile, +/** + * Ordered list of decisions the client may present for this prompt. + * + * When absent, clients should derive the legacy default set from the + * other fields on this request. + */ +available_decisions?: Array, parsed_cmd: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts new file mode 100644 index 0000000000..a9b4bc9393 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExecCommandBeginEvent.ts @@ -0,0 +1,35 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ExecCommandSource } from "./ExecCommandSource"; +import type { ParsedCommand } from "./ParsedCommand"; + +export type ExecCommandBeginEvent = { +/** + * Identifier so this can be paired with the ExecCommandEnd event. + */ +call_id: string, +/** + * Identifier for the underlying PTY process (when available). + */ +process_id?: string, +/** + * Turn ID that this command belongs to. + */ +turn_id: string, +/** + * The command to be executed. + */ +command: Array, +/** + * The command's working directory if not the default cwd for the agent. + */ +cwd: string, parsed_cmd: Array, +/** + * Where the command originated. Defaults to Agent for backward compatibility. + */ +source: ExecCommandSource, +/** + * Raw input sent to a unified exec session (if this is an interaction event). + */ +interaction_input?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts new file mode 100644 index 0000000000..0bfc41ea81 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExecCommandEndEvent.ts @@ -0,0 +1,64 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ExecCommandSource } from "./ExecCommandSource"; +import type { ExecCommandStatus } from "./ExecCommandStatus"; +import type { ParsedCommand } from "./ParsedCommand"; + +export type ExecCommandEndEvent = { +/** + * Identifier for the ExecCommandBegin that finished. + */ +call_id: string, +/** + * Identifier for the underlying PTY process (when available). + */ +process_id?: string, +/** + * Turn ID that this command belongs to. + */ +turn_id: string, +/** + * The command that was executed. + */ +command: Array, +/** + * The command's working directory if not the default cwd for the agent. + */ +cwd: string, parsed_cmd: Array, +/** + * Where the command originated. Defaults to Agent for backward compatibility. + */ +source: ExecCommandSource, +/** + * Raw input sent to a unified exec session (if this is an interaction event). + */ +interaction_input?: string, +/** + * Captured stdout + */ +stdout: string, +/** + * Captured stderr + */ +stderr: string, +/** + * Captured aggregated output + */ +aggregated_output: string, +/** + * The command's exit code. + */ +exit_code: number, +/** + * The duration of the command execution. + */ +duration: string, +/** + * Formatted output from the command, as seen by the model. + */ +formatted_output: string, +/** + * Completion status for this command execution. + */ +status: ExecCommandStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts new file mode 100644 index 0000000000..0930bdd827 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExecCommandOutputDeltaEvent.ts @@ -0,0 +1,18 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ExecOutputStream } from "./ExecOutputStream"; + +export type ExecCommandOutputDeltaEvent = { +/** + * Identifier for the ExecCommandBegin that produced this chunk. + */ +call_id: string, +/** + * Which stream produced this chunk. + */ +stream: ExecOutputStream, +/** + * Raw bytes from the stream (may not be valid UTF-8). + */ +chunk: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts new file mode 100644 index 0000000000..b665441bc2 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExecCommandSource.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ExecCommandSource = "agent" | "user_shell" | "unified_exec_startup" | "unified_exec_interaction"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts b/codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts new file mode 100644 index 0000000000..d8d91fb19f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExecCommandStatus.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ExecCommandStatus = "completed" | "failed" | "declined"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts b/codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts new file mode 100644 index 0000000000..96aa74483d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExecOutputStream.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ExecOutputStream = "stdout" | "stderr"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts new file mode 100644 index 0000000000..7271f07a3f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ExitedReviewModeEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ReviewOutputEvent } from "./ReviewOutputEvent"; + +export type ExitedReviewModeEvent = { review_output: ReviewOutputEvent | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts new file mode 100644 index 0000000000..aedf84de80 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AbsolutePathBuf } from "./AbsolutePathBuf"; + +export type FileSystemPermissions = { read: Array | null, write: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts new file mode 100644 index 0000000000..d46019c1dc --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/GetHistoryEntryResponseEvent.ts @@ -0,0 +1,10 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { HistoryEntry } from "./HistoryEntry"; + +export type GetHistoryEntryResponseEvent = { offset: number, log_id: bigint, +/** + * The entry at the requested offset, if available and parseable. + */ +entry: HistoryEntry | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts b/codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts new file mode 100644 index 0000000000..da5bc37c21 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/HistoryEntry.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type HistoryEntry = { conversation_id: string, ts: bigint, text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts new file mode 100644 index 0000000000..97de348dff --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ItemCompletedEvent.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; +import type { TurnItem } from "./TurnItem"; + +export type ItemCompletedEvent = { thread_id: ThreadId, turn_id: string, item: TurnItem, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts new file mode 100644 index 0000000000..e82f78f965 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ItemStartedEvent.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; +import type { TurnItem } from "./TurnItem"; + +export type ItemStartedEvent = { thread_id: ThreadId, turn_id: string, item: TurnItem, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts new file mode 100644 index 0000000000..9ebb43afb7 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ListCustomPromptsResponseEvent.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CustomPrompt } from "./CustomPrompt"; + +/** + * Response payload for `Op::ListCustomPrompts`. + */ +export type ListCustomPromptsResponseEvent = { custom_prompts: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts new file mode 100644 index 0000000000..e3b277f4d6 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ListRemoteSkillsResponseEvent.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RemoteSkillSummary } from "./RemoteSkillSummary"; + +/** + * Response payload for `Op::ListRemoteSkills`. + */ +export type ListRemoteSkillsResponseEvent = { skills: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts new file mode 100644 index 0000000000..efdd547596 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ListSkillsResponseEvent.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SkillsListEntry } from "./SkillsListEntry"; + +/** + * Response payload for `Op::ListSkills`. + */ +export type ListSkillsResponseEvent = { skills: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts new file mode 100644 index 0000000000..5c0792412c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/MacOsPermissions.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { MacOsAutomationValue } from "./MacOsAutomationValue"; +import type { MacOsPreferencesValue } from "./MacOsPreferencesValue"; + +export type MacOsPermissions = { preferences: MacOsPreferencesValue | null, automations: MacOsAutomationValue | null, accessibility: boolean | null, calendar: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts b/codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts new file mode 100644 index 0000000000..919ae85fd0 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpAuthStatus.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type McpAuthStatus = "unsupported" | "not_logged_in" | "bearer_token" | "o_auth"; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts b/codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts new file mode 100644 index 0000000000..5b7103a60c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpInvocation.ts @@ -0,0 +1,18 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { JsonValue } from "./serde_json/JsonValue"; + +export type McpInvocation = { +/** + * Name of the MCP server as defined in the config. + */ +server: string, +/** + * Name of the tool as given by the MCP server. + */ +tool: string, +/** + * Arguments to the tool call. + */ +arguments: JsonValue | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts new file mode 100644 index 0000000000..945959431a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpListToolsResponseEvent.ts @@ -0,0 +1,25 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { McpAuthStatus } from "./McpAuthStatus"; +import type { Resource } from "./Resource"; +import type { ResourceTemplate } from "./ResourceTemplate"; +import type { Tool } from "./Tool"; + +export type McpListToolsResponseEvent = { +/** + * Fully qualified tool name -> tool definition. + */ +tools: { [key in string]?: Tool }, +/** + * Known resources grouped by server name. + */ +resources: { [key in string]?: Array }, +/** + * Known resource templates grouped by server name. + */ +resource_templates: { [key in string]?: Array }, +/** + * Authentication status for each configured MCP server. + */ +auth_statuses: { [key in string]?: McpAuthStatus }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts new file mode 100644 index 0000000000..67354adfbe --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpStartupCompleteEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { McpStartupFailure } from "./McpStartupFailure"; + +export type McpStartupCompleteEvent = { ready: Array, failed: Array, cancelled: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts new file mode 100644 index 0000000000..b12009b15b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpStartupFailure.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type McpStartupFailure = { server: string, error: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts new file mode 100644 index 0000000000..48c08226f4 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpStartupStatus.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type McpStartupStatus = { "state": "starting" } | { "state": "ready" } | { "state": "failed", error: string, } | { "state": "cancelled" }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts new file mode 100644 index 0000000000..ecfe7d551e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpStartupUpdateEvent.ts @@ -0,0 +1,14 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { McpStartupStatus } from "./McpStartupStatus"; + +export type McpStartupUpdateEvent = { +/** + * Server name being started. + */ +server: string, +/** + * Current startup status. + */ +status: McpStartupStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts new file mode 100644 index 0000000000..feb7ca7c21 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpToolCallBeginEvent.ts @@ -0,0 +1,10 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { McpInvocation } from "./McpInvocation"; + +export type McpToolCallBeginEvent = { +/** + * Identifier so this can be paired with the McpToolCallEnd event. + */ +call_id: string, invocation: McpInvocation, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts new file mode 100644 index 0000000000..0ca82b2bc6 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpToolCallEndEvent.ts @@ -0,0 +1,15 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CallToolResult } from "./CallToolResult"; +import type { McpInvocation } from "./McpInvocation"; + +export type McpToolCallEndEvent = { +/** + * Identifier for the corresponding McpToolCallBegin that finished. + */ +call_id: string, invocation: McpInvocation, duration: string, +/** + * Result of the tool call. Note this could be an error. + */ +result: { Ok : CallToolResult } | { Err : string }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts new file mode 100644 index 0000000000..23a4e1efb6 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ModelRerouteEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ModelRerouteReason } from "./ModelRerouteReason"; + +export type ModelRerouteEvent = { from_model: string, to_model: string, reason: ModelRerouteReason, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts b/codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts new file mode 100644 index 0000000000..f5e1abf1e3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ModelRerouteReason.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ModelRerouteReason = "high_risk_cyber_activity"; diff --git a/codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts b/codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts new file mode 100644 index 0000000000..f259e67b99 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/NetworkAccess.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Represents whether outbound network access is available to the agent. + */ +export type NetworkAccess = "restricted" | "enabled"; diff --git a/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts b/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts new file mode 100644 index 0000000000..b4b78e473c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalContext.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; + +export type NetworkApprovalContext = { host: string, protocol: NetworkApprovalProtocol, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts b/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts new file mode 100644 index 0000000000..a33eab566f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/NetworkApprovalProtocol.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type NetworkApprovalProtocol = "http" | "https" | "socks5_tcp" | "socks5_udp"; diff --git a/codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts new file mode 100644 index 0000000000..19ff0d5754 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/PatchApplyBeginEvent.ts @@ -0,0 +1,23 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { FileChange } from "./FileChange"; + +export type PatchApplyBeginEvent = { +/** + * Identifier so this can be paired with the PatchApplyEnd event. + */ +call_id: string, +/** + * Turn ID that this patch belongs to. + * Uses `#[serde(default)]` for backwards compatibility. + */ +turn_id: string, +/** + * If true, there was no ApplyPatchApprovalRequest for this patch. + */ +auto_approved: boolean, +/** + * The changes to be applied. + */ +changes: { [key in string]?: FileChange }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts new file mode 100644 index 0000000000..9dacb00e44 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/PatchApplyEndEvent.ts @@ -0,0 +1,36 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { FileChange } from "./FileChange"; +import type { PatchApplyStatus } from "./PatchApplyStatus"; + +export type PatchApplyEndEvent = { +/** + * Identifier for the PatchApplyBegin that finished. + */ +call_id: string, +/** + * Turn ID that this patch belongs to. + * Uses `#[serde(default)]` for backwards compatibility. + */ +turn_id: string, +/** + * Captured stdout (summary printed by apply_patch). + */ +stdout: string, +/** + * Captured stderr (parser errors, IO failures, etc.). + */ +stderr: string, +/** + * Whether the patch was applied successfully. + */ +success: boolean, +/** + * The changes that were applied (mirrors PatchApplyBeginEvent::changes). + */ +changes: { [key in string]?: FileChange }, +/** + * Completion status for this patch application. + */ +status: PatchApplyStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts b/codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts new file mode 100644 index 0000000000..721fcd9b1f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/PatchApplyStatus.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type PatchApplyStatus = "completed" | "failed" | "declined"; diff --git a/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts b/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts new file mode 100644 index 0000000000..bfc0de27b7 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { FileSystemPermissions } from "./FileSystemPermissions"; +import type { MacOsPermissions } from "./MacOsPermissions"; + +export type PermissionProfile = { network: boolean | null, file_system: FileSystemPermissions | null, macos: MacOsPermissions | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts new file mode 100644 index 0000000000..f2ff588442 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/PlanDeltaEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type PlanDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PlanItem.ts b/codex-rs/app-server-protocol/schema/typescript/PlanItem.ts new file mode 100644 index 0000000000..909ab40e64 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/PlanItem.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type PlanItem = { id: string, text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts b/codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts new file mode 100644 index 0000000000..a9c8acfa75 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/PlanItemArg.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { StepStatus } from "./StepStatus"; + +export type PlanItemArg = { step: string, status: StepStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts b/codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts new file mode 100644 index 0000000000..8604128b4e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RateLimitSnapshot.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CreditsSnapshot } from "./CreditsSnapshot"; +import type { PlanType } from "./PlanType"; +import type { RateLimitWindow } from "./RateLimitWindow"; + +export type RateLimitSnapshot = { limit_id: string | null, limit_name: string | null, primary: RateLimitWindow | null, secondary: RateLimitWindow | null, credits: CreditsSnapshot | null, plan_type: PlanType | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts b/codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts new file mode 100644 index 0000000000..4a85062bf7 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RateLimitWindow.ts @@ -0,0 +1,17 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RateLimitWindow = { +/** + * Percentage (0-100) of the window that has been consumed. + */ +used_percent: number, +/** + * Rolling window duration, in minutes. + */ +window_minutes: number | null, +/** + * Unix timestamp (seconds since epoch) when the window resets. + */ +resets_at: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts new file mode 100644 index 0000000000..62dd4f0018 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RawResponseItemEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ResponseItem } from "./ResponseItem"; + +export type RawResponseItemEvent = { item: ResponseItem, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts b/codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts new file mode 100644 index 0000000000..c01bdd37c6 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReadOnlyAccess.ts @@ -0,0 +1,19 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AbsolutePathBuf } from "./AbsolutePathBuf"; + +/** + * Determines how read-only file access is granted inside a restricted + * sandbox. + */ +export type ReadOnlyAccess = { "type": "restricted", +/** + * Include built-in platform read roots required for basic process + * execution. + */ +include_platform_defaults: boolean, +/** + * Additional absolute roots that should be readable. + */ +readable_roots?: Array, } | { "type": "full-access" }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts new file mode 100644 index 0000000000..99c0c1063c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeAudioFrame.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RealtimeAudioFrame = { data: string, sample_rate: number, num_channels: number, samples_per_channel: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts new file mode 100644 index 0000000000..c73e6833ae --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationClosedEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RealtimeConversationClosedEvent = { reason: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts new file mode 100644 index 0000000000..4ff24a8281 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationRealtimeEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RealtimeEvent } from "./RealtimeEvent"; + +export type RealtimeConversationRealtimeEvent = { payload: RealtimeEvent, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts new file mode 100644 index 0000000000..f2894fcb1e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeConversationStartedEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RealtimeConversationStartedEvent = { session_id: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts new file mode 100644 index 0000000000..8286f34cad --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RealtimeAudioFrame } from "./RealtimeAudioFrame"; +import type { RealtimeHandoffRequested } from "./RealtimeHandoffRequested"; +import type { JsonValue } from "./serde_json/JsonValue"; + +export type RealtimeEvent = { "SessionUpdated": { session_id: string, instructions: string | null, } } | { "AudioOut": RealtimeAudioFrame } | { "ConversationItemAdded": JsonValue } | { "ConversationItemDone": { item_id: string, } } | { "HandoffRequested": RealtimeHandoffRequested } | { "Error": string }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts new file mode 100644 index 0000000000..39b77cfdf1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RealtimeHandoffMessage = { role: string, text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts new file mode 100644 index 0000000000..f3426706aa --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RealtimeHandoffMessage } from "./RealtimeHandoffMessage"; + +export type RealtimeHandoffRequested = { handoff_id: string, item_id: string, input_transcript: string, messages: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts new file mode 100644 index 0000000000..70dfc01d24 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReasoningContentDeltaEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ReasoningContentDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, summary_index: bigint, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts b/codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts new file mode 100644 index 0000000000..80bcb65fd1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReasoningItem.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ReasoningItem = { id: string, summary_text: Array, raw_content: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts new file mode 100644 index 0000000000..ef3a792caf --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReasoningRawContentDeltaEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ReasoningRawContentDeltaEvent = { thread_id: string, turn_id: string, item_id: string, delta: string, content_index: bigint, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts b/codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts new file mode 100644 index 0000000000..320f1096b0 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RejectConfig.ts @@ -0,0 +1,17 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RejectConfig = { +/** + * Reject approval prompts related to sandbox escalation. + */ +sandbox_approval: boolean, +/** + * Reject prompts triggered by execpolicy `prompt` rules. + */ +rules: boolean, +/** + * Reject MCP elicitation prompts. + */ +mcp_elicitations: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts new file mode 100644 index 0000000000..83082f2a57 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RemoteSkillDownloadedEvent.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Response payload for `Op::DownloadRemoteSkill`. + */ +export type RemoteSkillDownloadedEvent = { id: string, name: string, path: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts b/codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts new file mode 100644 index 0000000000..7bf57b3b09 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RemoteSkillSummary.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RemoteSkillSummary = { id: string, name: string, description: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts new file mode 100644 index 0000000000..8ea6453de9 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputEvent.ts @@ -0,0 +1,15 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RequestUserInputQuestion } from "./RequestUserInputQuestion"; + +export type RequestUserInputEvent = { +/** + * Responses API call id for the associated tool call, if available. + */ +call_id: string, +/** + * Turn ID that this request belongs to. + * Uses `#[serde(default)]` for backwards compatibility. + */ +turn_id: string, questions: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts new file mode 100644 index 0000000000..2a68f7b4c8 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestion.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RequestUserInputQuestionOption } from "./RequestUserInputQuestionOption"; + +export type RequestUserInputQuestion = { id: string, header: string, question: string, isOther: boolean, isSecret: boolean, options: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts new file mode 100644 index 0000000000..b2d2a0db48 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RequestUserInputQuestionOption.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type RequestUserInputQuestionOption = { label: string, description: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts new file mode 100644 index 0000000000..752589fe55 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReviewCodeLocation.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ReviewLineRange } from "./ReviewLineRange"; + +/** + * Location of the code related to a review finding. + */ +export type ReviewCodeLocation = { absolute_file_path: string, line_range: ReviewLineRange, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts new file mode 100644 index 0000000000..e7c96bd170 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReviewFinding.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ReviewCodeLocation } from "./ReviewCodeLocation"; + +/** + * A single review finding describing an observed issue or recommendation. + */ +export type ReviewFinding = { title: string, body: string, confidence_score: number, priority: number, code_location: ReviewCodeLocation, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts new file mode 100644 index 0000000000..c57ec6ed60 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReviewLineRange.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Inclusive line range in a file associated with the finding. + */ +export type ReviewLineRange = { start: number, end: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts new file mode 100644 index 0000000000..c45747424b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReviewOutputEvent.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ReviewFinding } from "./ReviewFinding"; + +/** + * Structured review result produced by a child review session. + */ +export type ReviewOutputEvent = { findings: Array, overall_correctness: string, overall_explanation: string, overall_confidence_score: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts new file mode 100644 index 0000000000..1e9b8ad2ee --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReviewRequest.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ReviewTarget } from "./ReviewTarget"; + +/** + * Review request sent to the review session. + */ +export type ReviewRequest = { target: ReviewTarget, user_facing_hint?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts b/codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts new file mode 100644 index 0000000000..a79f1e993c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ReviewTarget.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ReviewTarget = { "type": "uncommittedChanges" } | { "type": "baseBranch", branch: string, } | { "type": "commit", sha: string, +/** + * Optional human-readable label (e.g., commit subject) for UIs. + */ +title: string | null, } | { "type": "custom", instructions: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts b/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts new file mode 100644 index 0000000000..743ad22229 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts @@ -0,0 +1,44 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AbsolutePathBuf } from "./AbsolutePathBuf"; +import type { NetworkAccess } from "./NetworkAccess"; +import type { ReadOnlyAccess } from "./ReadOnlyAccess"; + +/** + * Determines execution restrictions for model shell commands. + */ +export type SandboxPolicy = { "type": "danger-full-access" } | { "type": "read-only", +/** + * Read access granted while running under this policy. + */ +access?: ReadOnlyAccess, } | { "type": "external-sandbox", +/** + * Whether the external sandbox permits outbound network traffic. + */ +network_access: NetworkAccess, } | { "type": "workspace-write", +/** + * Additional folders (beyond cwd and possibly TMPDIR) that should be + * writable from within the sandbox. + */ +writable_roots?: Array, +/** + * Read access granted while running under this policy. + */ +read_only_access?: ReadOnlyAccess, +/** + * When set to `true`, outbound network access is allowed. `false` by + * default. + */ +network_access: boolean, +/** + * When set to `true`, will NOT include the per-user `TMPDIR` + * environment variable among the default writable roots. Defaults to + * `false`. + */ +exclude_tmpdir_env_var: boolean, +/** + * When set to `true`, will NOT include the `/tmp` among the default + * writable roots on UNIX. Defaults to `false`. + */ +exclude_slash_tmp: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts b/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts new file mode 100644 index 0000000000..b4696a0e4c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts @@ -0,0 +1,58 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AskForApproval } from "./AskForApproval"; +import type { EventMsg } from "./EventMsg"; +import type { ReasoningEffort } from "./ReasoningEffort"; +import type { SandboxPolicy } from "./SandboxPolicy"; +import type { ServiceTier } from "./ServiceTier"; +import type { SessionNetworkProxyRuntime } from "./SessionNetworkProxyRuntime"; +import type { ThreadId } from "./ThreadId"; + +export type SessionConfiguredEvent = { session_id: ThreadId, forked_from_id: ThreadId | null, +/** + * Optional user-facing thread name (may be unset). + */ +thread_name?: string, +/** + * Tell the client what model is being queried. + */ +model: string, model_provider_id: string, service_tier: ServiceTier | null, +/** + * When to escalate for approval for execution + */ +approval_policy: AskForApproval, +/** + * How to sandbox commands executed in the system + */ +sandbox_policy: SandboxPolicy, +/** + * Working directory that should be treated as the *root* of the + * session. + */ +cwd: string, +/** + * The effort the model is putting into reasoning about the user's request. + */ +reasoning_effort: ReasoningEffort | null, +/** + * Identifier of the history log file (inode on Unix, 0 otherwise). + */ +history_log_id: bigint, +/** + * Current number of entries in the history log. + */ +history_entry_count: number, +/** + * Optional initial messages (as events) for resumed sessions. + * When present, UIs can use these to seed the history. + */ +initial_messages: Array | null, +/** + * Runtime proxy bind addresses, when the managed proxy was started for this session. + */ +network_proxy?: SessionNetworkProxyRuntime, +/** + * Path in which the rollout is stored. Can be `None` for ephemeral threads + */ +rollout_path: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts b/codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts new file mode 100644 index 0000000000..3f0c6d857e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SessionNetworkProxyRuntime.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type SessionNetworkProxyRuntime = { http_addr: string, socks_addr: string, admin_addr: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts b/codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts new file mode 100644 index 0000000000..e2dd4f4241 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SkillDependencies.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SkillToolDependency } from "./SkillToolDependency"; + +export type SkillDependencies = { tools: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts b/codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts new file mode 100644 index 0000000000..6eaf035d8c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SkillErrorInfo.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type SkillErrorInfo = { path: string, message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts b/codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts new file mode 100644 index 0000000000..30250b9383 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SkillInterface.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type SkillInterface = { display_name?: string, short_description?: string, icon_small?: string, icon_large?: string, brand_color?: string, default_prompt?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts b/codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts new file mode 100644 index 0000000000..088abc406a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SkillMetadata.ts @@ -0,0 +1,12 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SkillDependencies } from "./SkillDependencies"; +import type { SkillInterface } from "./SkillInterface"; +import type { SkillScope } from "./SkillScope"; + +export type SkillMetadata = { name: string, description: string, +/** + * Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description. + */ +short_description?: string, interface?: SkillInterface, dependencies?: SkillDependencies, path: string, scope: SkillScope, enabled: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillScope.ts b/codex-rs/app-server-protocol/schema/typescript/SkillScope.ts new file mode 100644 index 0000000000..997006f5b8 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SkillScope.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type SkillScope = "user" | "repo" | "system" | "admin"; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts b/codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts new file mode 100644 index 0000000000..a5da45e178 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SkillToolDependency.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type SkillToolDependency = { type: string, value: string, description?: string, transport?: string, command?: string, url?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts b/codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts new file mode 100644 index 0000000000..3f46c98a4a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/SkillsListEntry.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SkillErrorInfo } from "./SkillErrorInfo"; +import type { SkillMetadata } from "./SkillMetadata"; + +export type SkillsListEntry = { cwd: string, skills: Array, errors: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/StepStatus.ts b/codex-rs/app-server-protocol/schema/typescript/StepStatus.ts new file mode 100644 index 0000000000..8494a76e0b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/StepStatus.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type StepStatus = "pending" | "in_progress" | "completed"; diff --git a/codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts b/codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts new file mode 100644 index 0000000000..b88993a344 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/StreamErrorEvent.ts @@ -0,0 +1,12 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { CodexErrorInfo } from "./CodexErrorInfo"; + +export type StreamErrorEvent = { message: string, codex_error_info: CodexErrorInfo | null, +/** + * Optional details about the underlying stream failure (often the same + * human-readable message that is surfaced as the terminal error if retries + * are exhausted). + */ +additional_details: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts new file mode 100644 index 0000000000..5f300e6ca5 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TerminalInteractionEvent.ts @@ -0,0 +1,17 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type TerminalInteractionEvent = { +/** + * Identifier for the ExecCommandBegin that produced this chunk. + */ +call_id: string, +/** + * Process id associated with the running command. + */ +process_id: string, +/** + * Stdin sent to the running session. + */ +stdin: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TextElement.ts b/codex-rs/app-server-protocol/schema/typescript/TextElement.ts new file mode 100644 index 0000000000..3dcd369d82 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TextElement.ts @@ -0,0 +1,14 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ByteRange } from "./ByteRange"; + +export type TextElement = { +/** + * Byte range in the parent `text` buffer that this element occupies. + */ +byte_range: ByteRange, +/** + * Optional human-readable placeholder for the element, displayed in the UI. + */ +placeholder: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts new file mode 100644 index 0000000000..639e29f9d7 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ThreadNameUpdatedEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadId } from "./ThreadId"; + +export type ThreadNameUpdatedEvent = { thread_id: ThreadId, thread_name?: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts new file mode 100644 index 0000000000..30bc64c9c1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ThreadRolledBackEvent.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ThreadRolledBackEvent = { +/** + * Number of user turns that were removed from context. + */ +num_turns: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts new file mode 100644 index 0000000000..f58b574641 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TokenCountEvent.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { RateLimitSnapshot } from "./RateLimitSnapshot"; +import type { TokenUsageInfo } from "./TokenUsageInfo"; + +export type TokenCountEvent = { info: TokenUsageInfo | null, rate_limits: RateLimitSnapshot | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts b/codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts new file mode 100644 index 0000000000..41186b25b9 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TokenUsage.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type TokenUsage = { input_tokens: number, cached_input_tokens: number, output_tokens: number, reasoning_output_tokens: number, total_tokens: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts b/codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts new file mode 100644 index 0000000000..cb15de42e7 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TokenUsageInfo.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { TokenUsage } from "./TokenUsage"; + +export type TokenUsageInfo = { total_token_usage: TokenUsage, last_token_usage: TokenUsage, model_context_window: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts b/codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts new file mode 100644 index 0000000000..f07cde6292 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TurnAbortReason.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type TurnAbortReason = "interrupted" | "replaced" | "review_ended"; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts new file mode 100644 index 0000000000..0b4e9075b3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TurnAbortedEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { TurnAbortReason } from "./TurnAbortReason"; + +export type TurnAbortedEvent = { turn_id: string | null, reason: TurnAbortReason, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts new file mode 100644 index 0000000000..6987d59f98 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TurnCompleteEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type TurnCompleteEvent = { turn_id: string, last_agent_message: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts new file mode 100644 index 0000000000..52e3df09b0 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TurnDiffEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type TurnDiffEvent = { unified_diff: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnItem.ts b/codex-rs/app-server-protocol/schema/typescript/TurnItem.ts new file mode 100644 index 0000000000..0f2ea12a21 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TurnItem.ts @@ -0,0 +1,11 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AgentMessageItem } from "./AgentMessageItem"; +import type { ContextCompactionItem } from "./ContextCompactionItem"; +import type { PlanItem } from "./PlanItem"; +import type { ReasoningItem } from "./ReasoningItem"; +import type { UserMessageItem } from "./UserMessageItem"; +import type { WebSearchItem } from "./WebSearchItem"; + +export type TurnItem = { "type": "UserMessage" } & UserMessageItem | { "type": "AgentMessage" } & AgentMessageItem | { "type": "Plan" } & PlanItem | { "type": "Reasoning" } & ReasoningItem | { "type": "WebSearch" } & WebSearchItem | { "type": "ContextCompaction" } & ContextCompactionItem; diff --git a/codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts new file mode 100644 index 0000000000..14c0d76707 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/TurnStartedEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ModeKind } from "./ModeKind"; + +export type TurnStartedEvent = { turn_id: string, model_context_window: bigint | null, collaboration_mode_kind: ModeKind, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts new file mode 100644 index 0000000000..2d94e2e18d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/UndoCompletedEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type UndoCompletedEvent = { success: boolean, message: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts b/codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts new file mode 100644 index 0000000000..712082adff --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/UndoStartedEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type UndoStartedEvent = { message: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts b/codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts new file mode 100644 index 0000000000..61613fcb5f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/UpdatePlanArgs.ts @@ -0,0 +1,10 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { PlanItemArg } from "./PlanItemArg"; + +export type UpdatePlanArgs = { +/** + * Arguments for the `update_plan` todo/checklist tool (not plan mode). + */ +explanation: string | null, plan: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserInput.ts b/codex-rs/app-server-protocol/schema/typescript/UserInput.ts new file mode 100644 index 0000000000..e6a9c3a580 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/UserInput.ts @@ -0,0 +1,16 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { TextElement } from "./TextElement"; + +/** + * User input + */ +export type UserInput = { "type": "text", text: string, +/** + * UI-defined spans within `text` that should be treated as special elements. + * These are byte ranges into the UTF-8 `text` buffer and are used to render + * or persist rich input markers (e.g., image placeholders) across history + * and resume without mutating the literal text. + */ +text_elements: Array, } | { "type": "image", image_url: string, } | { "type": "local_image", path: string, } | { "type": "skill", name: string, path: string, } | { "type": "mention", name: string, path: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts b/codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts new file mode 100644 index 0000000000..2fde364d67 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/UserMessageEvent.ts @@ -0,0 +1,22 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { TextElement } from "./TextElement"; + +export type UserMessageEvent = { message: string, +/** + * Image URLs sourced from `UserInput::Image`. These are safe + * to replay in legacy UI history events and correspond to images sent to + * the model. + */ +images: Array | null, +/** + * Local file paths sourced from `UserInput::LocalImage`. These are kept so + * the UI can reattach images when editing history, and should not be sent + * to the model or treated as API-ready URLs. + */ +local_images: Array, +/** + * UI-defined spans within `message` used to render or persist special elements. + */ +text_elements: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts b/codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts new file mode 100644 index 0000000000..df856287a5 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/UserMessageItem.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { UserInput } from "./UserInput"; + +export type UserMessageItem = { id: string, content: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts new file mode 100644 index 0000000000..76541a773a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ViewImageToolCallEvent.ts @@ -0,0 +1,13 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ViewImageToolCallEvent = { +/** + * Identifier for the originating tool call. + */ +call_id: string, +/** + * Local filesystem path provided to the tool. + */ +path: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts b/codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts new file mode 100644 index 0000000000..35ec40f7cd --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/WarningEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type WarningEvent = { message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts b/codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts new file mode 100644 index 0000000000..4a8d881914 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/WebSearchBeginEvent.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type WebSearchBeginEvent = { call_id: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts b/codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts new file mode 100644 index 0000000000..5b8b67c28b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/WebSearchEndEvent.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { WebSearchAction } from "./WebSearchAction"; + +export type WebSearchEndEvent = { call_id: string, query: string, action: WebSearchAction, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts b/codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts new file mode 100644 index 0000000000..46b1406519 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/WebSearchItem.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { WebSearchAction } from "./WebSearchAction"; + +export type WebSearchItem = { id: string, query: string, action: WebSearchAction, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index fa1284843d..adaeb4c26c 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -1,20 +1,69 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! export type { AbsolutePathBuf } from "./AbsolutePathBuf"; +export type { AgentMessageContent } from "./AgentMessageContent"; +export type { AgentMessageContentDeltaEvent } from "./AgentMessageContentDeltaEvent"; +export type { AgentMessageDeltaEvent } from "./AgentMessageDeltaEvent"; +export type { AgentMessageEvent } from "./AgentMessageEvent"; +export type { AgentMessageItem } from "./AgentMessageItem"; +export type { AgentReasoningDeltaEvent } from "./AgentReasoningDeltaEvent"; +export type { AgentReasoningEvent } from "./AgentReasoningEvent"; +export type { AgentReasoningRawContentDeltaEvent } from "./AgentReasoningRawContentDeltaEvent"; +export type { AgentReasoningRawContentEvent } from "./AgentReasoningRawContentEvent"; +export type { AgentReasoningSectionBreakEvent } from "./AgentReasoningSectionBreakEvent"; +export type { AgentStatus } from "./AgentStatus"; export type { ApplyPatchApprovalParams } from "./ApplyPatchApprovalParams"; +export type { ApplyPatchApprovalRequestEvent } from "./ApplyPatchApprovalRequestEvent"; export type { ApplyPatchApprovalResponse } from "./ApplyPatchApprovalResponse"; +export type { AskForApproval } from "./AskForApproval"; export type { AuthMode } from "./AuthMode"; +export type { BackgroundEventEvent } from "./BackgroundEventEvent"; +export type { ByteRange } from "./ByteRange"; +export type { CallToolResult } from "./CallToolResult"; export type { ClientInfo } from "./ClientInfo"; export type { ClientNotification } from "./ClientNotification"; export type { ClientRequest } from "./ClientRequest"; +export type { CodexErrorInfo } from "./CodexErrorInfo"; +export type { CollabAgentInteractionBeginEvent } from "./CollabAgentInteractionBeginEvent"; +export type { CollabAgentInteractionEndEvent } from "./CollabAgentInteractionEndEvent"; +export type { CollabAgentRef } from "./CollabAgentRef"; +export type { CollabAgentSpawnBeginEvent } from "./CollabAgentSpawnBeginEvent"; +export type { CollabAgentSpawnEndEvent } from "./CollabAgentSpawnEndEvent"; +export type { CollabAgentStatusEntry } from "./CollabAgentStatusEntry"; +export type { CollabCloseBeginEvent } from "./CollabCloseBeginEvent"; +export type { CollabCloseEndEvent } from "./CollabCloseEndEvent"; +export type { CollabResumeBeginEvent } from "./CollabResumeBeginEvent"; +export type { CollabResumeEndEvent } from "./CollabResumeEndEvent"; +export type { CollabWaitingBeginEvent } from "./CollabWaitingBeginEvent"; +export type { CollabWaitingEndEvent } from "./CollabWaitingEndEvent"; export type { CollaborationMode } from "./CollaborationMode"; export type { ContentItem } from "./ContentItem"; +export type { ContextCompactedEvent } from "./ContextCompactedEvent"; +export type { ContextCompactionItem } from "./ContextCompactionItem"; export type { ConversationGitInfo } from "./ConversationGitInfo"; export type { ConversationSummary } from "./ConversationSummary"; +export type { CreditsSnapshot } from "./CreditsSnapshot"; +export type { CustomPrompt } from "./CustomPrompt"; +export type { DeprecationNoticeEvent } from "./DeprecationNoticeEvent"; +export type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; +export type { DynamicToolCallRequest } from "./DynamicToolCallRequest"; +export type { DynamicToolCallResponseEvent } from "./DynamicToolCallResponseEvent"; +export type { ElicitationRequestEvent } from "./ElicitationRequestEvent"; +export type { ErrorEvent } from "./ErrorEvent"; +export type { EventMsg } from "./EventMsg"; +export type { ExecApprovalRequestEvent } from "./ExecApprovalRequestEvent"; export type { ExecCommandApprovalParams } from "./ExecCommandApprovalParams"; export type { ExecCommandApprovalResponse } from "./ExecCommandApprovalResponse"; +export type { ExecCommandBeginEvent } from "./ExecCommandBeginEvent"; +export type { ExecCommandEndEvent } from "./ExecCommandEndEvent"; +export type { ExecCommandOutputDeltaEvent } from "./ExecCommandOutputDeltaEvent"; +export type { ExecCommandSource } from "./ExecCommandSource"; +export type { ExecCommandStatus } from "./ExecCommandStatus"; +export type { ExecOutputStream } from "./ExecOutputStream"; export type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; +export type { ExitedReviewModeEvent } from "./ExitedReviewModeEvent"; export type { FileChange } from "./FileChange"; +export type { FileSystemPermissions } from "./FileSystemPermissions"; export type { ForcedLoginMethod } from "./ForcedLoginMethod"; export type { FunctionCallOutputBody } from "./FunctionCallOutputBody"; export type { FunctionCallOutputContentItem } from "./FunctionCallOutputContentItem"; @@ -28,44 +77,135 @@ export type { GetAuthStatusParams } from "./GetAuthStatusParams"; export type { GetAuthStatusResponse } from "./GetAuthStatusResponse"; export type { GetConversationSummaryParams } from "./GetConversationSummaryParams"; export type { GetConversationSummaryResponse } from "./GetConversationSummaryResponse"; +export type { GetHistoryEntryResponseEvent } from "./GetHistoryEntryResponseEvent"; export type { GhostCommit } from "./GhostCommit"; export type { GitDiffToRemoteParams } from "./GitDiffToRemoteParams"; export type { GitDiffToRemoteResponse } from "./GitDiffToRemoteResponse"; export type { GitSha } from "./GitSha"; +export type { HistoryEntry } from "./HistoryEntry"; export type { InitializeCapabilities } from "./InitializeCapabilities"; export type { InitializeParams } from "./InitializeParams"; export type { InitializeResponse } from "./InitializeResponse"; export type { InputModality } from "./InputModality"; +export type { ItemCompletedEvent } from "./ItemCompletedEvent"; +export type { ItemStartedEvent } from "./ItemStartedEvent"; +export type { ListCustomPromptsResponseEvent } from "./ListCustomPromptsResponseEvent"; +export type { ListRemoteSkillsResponseEvent } from "./ListRemoteSkillsResponseEvent"; +export type { ListSkillsResponseEvent } from "./ListSkillsResponseEvent"; export type { LocalShellAction } from "./LocalShellAction"; export type { LocalShellExecAction } from "./LocalShellExecAction"; export type { LocalShellStatus } from "./LocalShellStatus"; export type { MacOsAutomationValue } from "./MacOsAutomationValue"; +export type { MacOsPermissions } from "./MacOsPermissions"; export type { MacOsPreferencesValue } from "./MacOsPreferencesValue"; +export type { McpAuthStatus } from "./McpAuthStatus"; +export type { McpInvocation } from "./McpInvocation"; +export type { McpListToolsResponseEvent } from "./McpListToolsResponseEvent"; +export type { McpStartupCompleteEvent } from "./McpStartupCompleteEvent"; +export type { McpStartupFailure } from "./McpStartupFailure"; +export type { McpStartupStatus } from "./McpStartupStatus"; +export type { McpStartupUpdateEvent } from "./McpStartupUpdateEvent"; +export type { McpToolCallBeginEvent } from "./McpToolCallBeginEvent"; +export type { McpToolCallEndEvent } from "./McpToolCallEndEvent"; export type { MessagePhase } from "./MessagePhase"; export type { ModeKind } from "./ModeKind"; +export type { ModelRerouteEvent } from "./ModelRerouteEvent"; +export type { ModelRerouteReason } from "./ModelRerouteReason"; +export type { NetworkAccess } from "./NetworkAccess"; +export type { NetworkApprovalContext } from "./NetworkApprovalContext"; +export type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; export type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; export type { NetworkPolicyRuleAction } from "./NetworkPolicyRuleAction"; export type { ParsedCommand } from "./ParsedCommand"; +export type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent"; +export type { PatchApplyEndEvent } from "./PatchApplyEndEvent"; +export type { PatchApplyStatus } from "./PatchApplyStatus"; +export type { PermissionProfile } from "./PermissionProfile"; export type { Personality } from "./Personality"; +export type { PlanDeltaEvent } from "./PlanDeltaEvent"; +export type { PlanItem } from "./PlanItem"; +export type { PlanItemArg } from "./PlanItemArg"; export type { PlanType } from "./PlanType"; +export type { RateLimitSnapshot } from "./RateLimitSnapshot"; +export type { RateLimitWindow } from "./RateLimitWindow"; +export type { RawResponseItemEvent } from "./RawResponseItemEvent"; +export type { ReadOnlyAccess } from "./ReadOnlyAccess"; +export type { RealtimeAudioFrame } from "./RealtimeAudioFrame"; +export type { RealtimeConversationClosedEvent } from "./RealtimeConversationClosedEvent"; +export type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent"; +export type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent"; +export type { RealtimeEvent } from "./RealtimeEvent"; +export type { RealtimeHandoffMessage } from "./RealtimeHandoffMessage"; +export type { RealtimeHandoffRequested } from "./RealtimeHandoffRequested"; +export type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent"; export type { ReasoningEffort } from "./ReasoningEffort"; +export type { ReasoningItem } from "./ReasoningItem"; export type { ReasoningItemContent } from "./ReasoningItemContent"; export type { ReasoningItemReasoningSummary } from "./ReasoningItemReasoningSummary"; +export type { ReasoningRawContentDeltaEvent } from "./ReasoningRawContentDeltaEvent"; export type { ReasoningSummary } from "./ReasoningSummary"; +export type { RejectConfig } from "./RejectConfig"; +export type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent"; +export type { RemoteSkillSummary } from "./RemoteSkillSummary"; export type { RequestId } from "./RequestId"; +export type { RequestUserInputEvent } from "./RequestUserInputEvent"; +export type { RequestUserInputQuestion } from "./RequestUserInputQuestion"; +export type { RequestUserInputQuestionOption } from "./RequestUserInputQuestionOption"; export type { Resource } from "./Resource"; export type { ResourceTemplate } from "./ResourceTemplate"; export type { ResponseItem } from "./ResponseItem"; +export type { ReviewCodeLocation } from "./ReviewCodeLocation"; export type { ReviewDecision } from "./ReviewDecision"; +export type { ReviewFinding } from "./ReviewFinding"; +export type { ReviewLineRange } from "./ReviewLineRange"; +export type { ReviewOutputEvent } from "./ReviewOutputEvent"; +export type { ReviewRequest } from "./ReviewRequest"; +export type { ReviewTarget } from "./ReviewTarget"; +export type { SandboxPolicy } from "./SandboxPolicy"; export type { ServerNotification } from "./ServerNotification"; export type { ServerRequest } from "./ServerRequest"; export type { ServiceTier } from "./ServiceTier"; +export type { SessionConfiguredEvent } from "./SessionConfiguredEvent"; +export type { SessionNetworkProxyRuntime } from "./SessionNetworkProxyRuntime"; export type { SessionSource } from "./SessionSource"; export type { Settings } from "./Settings"; +export type { SkillDependencies } from "./SkillDependencies"; +export type { SkillErrorInfo } from "./SkillErrorInfo"; +export type { SkillInterface } from "./SkillInterface"; +export type { SkillMetadata } from "./SkillMetadata"; +export type { SkillScope } from "./SkillScope"; +export type { SkillToolDependency } from "./SkillToolDependency"; +export type { SkillsListEntry } from "./SkillsListEntry"; +export type { StepStatus } from "./StepStatus"; +export type { StreamErrorEvent } from "./StreamErrorEvent"; export type { SubAgentSource } from "./SubAgentSource"; +export type { TerminalInteractionEvent } from "./TerminalInteractionEvent"; +export type { TextElement } from "./TextElement"; export type { ThreadId } from "./ThreadId"; +export type { ThreadNameUpdatedEvent } from "./ThreadNameUpdatedEvent"; +export type { ThreadRolledBackEvent } from "./ThreadRolledBackEvent"; +export type { TokenCountEvent } from "./TokenCountEvent"; +export type { TokenUsage } from "./TokenUsage"; +export type { TokenUsageInfo } from "./TokenUsageInfo"; export type { Tool } from "./Tool"; +export type { TurnAbortReason } from "./TurnAbortReason"; +export type { TurnAbortedEvent } from "./TurnAbortedEvent"; +export type { TurnCompleteEvent } from "./TurnCompleteEvent"; +export type { TurnDiffEvent } from "./TurnDiffEvent"; +export type { TurnItem } from "./TurnItem"; +export type { TurnStartedEvent } from "./TurnStartedEvent"; +export type { UndoCompletedEvent } from "./UndoCompletedEvent"; +export type { UndoStartedEvent } from "./UndoStartedEvent"; +export type { UpdatePlanArgs } from "./UpdatePlanArgs"; +export type { UserInput } from "./UserInput"; +export type { UserMessageEvent } from "./UserMessageEvent"; +export type { UserMessageItem } from "./UserMessageItem"; export type { Verbosity } from "./Verbosity"; +export type { ViewImageToolCallEvent } from "./ViewImageToolCallEvent"; +export type { WarningEvent } from "./WarningEvent"; export type { WebSearchAction } from "./WebSearchAction"; +export type { WebSearchBeginEvent } from "./WebSearchBeginEvent"; +export type { WebSearchEndEvent } from "./WebSearchEndEvent"; +export type { WebSearchItem } from "./WebSearchItem"; export type { WebSearchMode } from "./WebSearchMode"; export * as v2 from "./v2"; diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 2802a87480..aad5ab7233 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -117,6 +117,7 @@ pub fn generate_ts_with_options( ServerRequest::export_all_to(out_dir)?; export_server_responses(out_dir)?; ServerNotification::export_all_to(out_dir)?; + EventMsg::export_all_to(out_dir)?; if !options.experimental_api { filter_experimental_ts(out_dir)?; @@ -1910,6 +1911,7 @@ mod tests { client_request_ts.contains("MockExperimentalMethodParams"), false ); + assert_eq!(output_dir.join("EventMsg.ts").exists(), true); let thread_start_ts = fs::read_to_string(output_dir.join("v2").join("ThreadStartParams.ts"))?; assert_eq!(thread_start_ts.contains("mockExperimentalField"), false); From 6bee02a346d0aa8dc4d5dcb312545fa37408b6ca Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 3 Mar 2026 14:07:51 -0800 Subject: [PATCH 343/385] Build delegated realtime handoff text from all messages (#13395) ## Summary - Route delegated realtime handoff turns from all handoff message texts, preserving order - Fallback to input_transcript only when no messages are present - Add regression coverage for multi-message handoff requests --- codex-rs/core/src/realtime_conversation.rs | 44 +++++++++-- .../core/tests/suite/realtime_conversation.rs | 74 +++++++++++++++++++ 2 files changed, 110 insertions(+), 8 deletions(-) diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index 8842c41c96..e614be1061 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -373,7 +373,15 @@ pub(crate) async fn handle_audio( } fn realtime_text_from_handoff_request(handoff: &RealtimeHandoffRequested) -> Option { - (!handoff.input_transcript.is_empty()).then(|| handoff.input_transcript.clone()) + let messages = handoff + .messages + .iter() + .map(|message| message.text.as_str()) + .collect::>() + .join("\n"); + (!messages.is_empty()).then_some(messages).or_else(|| { + (!handoff.input_transcript.is_empty()).then(|| handoff.input_transcript.clone()) + }) } fn realtime_api_key( @@ -579,19 +587,39 @@ mod tests { use pretty_assertions::assert_eq; #[test] - fn extracts_text_from_handoff_request_input_transcript() { + fn extracts_text_from_handoff_request_messages() { let handoff = RealtimeHandoffRequested { handoff_id: "handoff_1".to_string(), item_id: "item_1".to_string(), - input_transcript: "hello".to_string(), - messages: vec![RealtimeHandoffMessage { - role: "user".to_string(), - text: "hello".to_string(), - }], + input_transcript: "ignored".to_string(), + messages: vec![ + RealtimeHandoffMessage { + role: "user".to_string(), + text: "hello".to_string(), + }, + RealtimeHandoffMessage { + role: "assistant".to_string(), + text: "hi there".to_string(), + }, + ], }; assert_eq!( realtime_text_from_handoff_request(&handoff), - Some("hello".to_string()) + Some("hello\nhi there".to_string()) + ); + } + + #[test] + fn extracts_text_from_handoff_request_input_transcript_if_messages_missing() { + let handoff = RealtimeHandoffRequested { + handoff_id: "handoff_1".to_string(), + item_id: "item_1".to_string(), + input_transcript: "ignored".to_string(), + messages: vec![], + }; + assert_eq!( + realtime_text_from_handoff_request(&handoff), + Some("ignored".to_string()) ); } diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index 32500299cb..ff4e745dd2 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -918,6 +918,80 @@ async fn inbound_handoff_request_starts_turn() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn inbound_handoff_request_uses_all_messages() -> Result<()> { + skip_if_no_network!(Ok(())); + + let api_server = start_mock_server().await; + let response_mock = responses::mount_sse_once( + &api_server, + responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "ok"), + responses::ev_completed("resp-1"), + ]), + ) + .await; + + let realtime_server = start_websocket_server(vec![vec![vec![ + json!({ + "type": "session.updated", + "session": { "id": "sess_inbound_multi", "instructions": "backend prompt" } + }), + json!({ + "type": "conversation.handoff.requested", + "handoff_id": "handoff_inbound_multi", + "item_id": "item_inbound_multi", + "input_transcript": "ignored", + "messages": [ + { "role": "assistant", "text": "assistant context" }, + { "role": "user", "text": "delegated query" }, + { "role": "assistant", "text": "assist confirm" }, + ] + }), + ]]]) + .await; + + let mut builder = test_codex().with_config({ + let realtime_base_url = realtime_server.uri().to_string(); + move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + } + }); + let test = builder.build(&api_server).await?; + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionUpdated { session_id, .. }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + let request = response_mock.single_request(); + let user_texts = request.message_input_texts("user"); + assert!( + user_texts + .iter() + .any(|text| text == "assistant context\ndelegated query\nassist confirm") + ); + + realtime_server.shutdown().await; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn inbound_conversation_item_does_not_start_turn_and_still_forwards_audio() -> Result<()> { skip_if_no_network!(Ok(())); From bab32afa93292b181e350c2c0416f77fd82adf2b Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Tue, 3 Mar 2026 15:32:47 -0700 Subject: [PATCH 344/385] Require deduplicator success before commenting (#13399) Fixed recent regression in issue dedup action --- .github/workflows/issue-deduplicator.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/issue-deduplicator.yml b/.github/workflows/issue-deduplicator.yml index 62af691fe6..2c7c13e688 100644 --- a/.github/workflows/issue-deduplicator.yml +++ b/.github/workflows/issue-deduplicator.yml @@ -335,7 +335,7 @@ jobs: comment-on-issue: name: Comment with potential duplicates needs: select-final - if: ${{ needs.select-final.result != 'skipped' }} + if: ${{ always() && needs.select-final.result == 'success' }} runs-on: ubuntu-latest permissions: contents: read From 041c896509796c438e34406e43473e60b8282cfc Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 3 Mar 2026 14:41:26 -0800 Subject: [PATCH 345/385] Revert "Revert "realtime prompt changes"" (#13398) Reverts openai/codex#13385 --- ...e__remote_compact_resume_restates_realtime_end_shapes.snap | 2 +- ..._turn_compaction_does_not_restate_realtime_end_shapes.snap | 4 ++-- ...mote_pre_turn_compaction_restates_realtime_end_shapes.snap | 2 +- codex-rs/protocol/src/prompts/realtime/realtime_end.md | 4 +--- codex-rs/protocol/src/prompts/realtime/realtime_start.md | 3 +-- 5 files changed, 6 insertions(+), 9 deletions(-) diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_compact_resume_restates_realtime_end_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_compact_resume_restates_realtime_end_shapes.snap index 1b95615375..fc12d431e2 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_compact_resume_restates_realtime_end_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_compact_resume_restates_realtime_end_shapes.snap @@ -17,7 +17,7 @@ Scenario: After remote manual /compact and resume, the first resumed turn rebuil 00:compaction:encrypted=true 01:message/developer[2]: [01] - [02] \nRealtime conversation ended.\n\nYou are... + [02] \nRealtime conversation ended.\n\nSubsequ... 02:message/user[2]: [01] [02] > diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_does_not_restate_realtime_end_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_does_not_restate_realtime_end_shapes.snap index eb7e583874..b1f83ce4d3 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_does_not_restate_realtime_end_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_does_not_restate_realtime_end_shapes.snap @@ -12,7 +12,7 @@ Scenario: Remote mid-turn continuation compaction after realtime was closed befo 02:message/developer:\nRealtime conversation started.\n\nYou a... 03:message/user:SETUP_USER 04:message/assistant:REMOTE_SETUP_REPLY -05:message/developer:\nRealtime conversation ended.\n\nYou are... +05:message/developer:\nRealtime conversation ended.\n\nSubsequ... 06:message/user:USER_TWO ## Remote Compaction Request @@ -23,7 +23,7 @@ Scenario: Remote mid-turn continuation compaction after realtime was closed befo 02:message/developer:\nRealtime conversation started.\n\nYou a... 03:message/user:SETUP_USER 04:message/assistant:REMOTE_SETUP_REPLY -05:message/developer:\nRealtime conversation ended.\n\nYou are... +05:message/developer:\nRealtime conversation ended.\n\nSubsequ... 06:message/user:USER_TWO 07:function_call/test_tool 08:function_call_output:unsupported call: test_tool diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_end_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_end_shapes.snap index 7f14509dd2..57af327d16 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_end_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_end_shapes.snap @@ -17,7 +17,7 @@ Scenario: Remote pre-turn auto-compaction after realtime was closed between turn 00:compaction:encrypted=true 01:message/developer[2]: [01] - [02] \nRealtime conversation ended.\n\nYou are... + [02] \nRealtime conversation ended.\n\nSubsequ... 02:message/user[2]: [01] [02] > diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_end.md b/codex-rs/protocol/src/prompts/realtime/realtime_end.md index 07ccae5286..abec16da03 100644 --- a/codex-rs/protocol/src/prompts/realtime/realtime_end.md +++ b/codex-rs/protocol/src/prompts/realtime/realtime_end.md @@ -1,5 +1,3 @@ Realtime conversation ended. -You are still operating behind an intermediary rather than speaking to the user directly. Use the conversation transcript and current context to decide whether backend help is actually needed, and avoid verbose responses that only add latency. - -Subsequent user input may return to typed text rather than transcript-style text. Do not assume recognition errors or missing punctuation once realtime has ended. Resume normal chat behavior. +Subsequent user input will return to typed text rather than transcript-style text. Do not assume recognition errors or missing punctuation once realtime has ended. Resume normal chat behavior. diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_start.md b/codex-rs/protocol/src/prompts/realtime/realtime_start.md index c7d363eff7..3159a2b07f 100644 --- a/codex-rs/protocol/src/prompts/realtime/realtime_start.md +++ b/codex-rs/protocol/src/prompts/realtime/realtime_start.md @@ -6,5 +6,4 @@ When invoked, you receive the latest conversation transcript and any relevant mo When user text is routed from realtime, treat it as a transcript. It may be unpunctuated or contain recognition errors. -- Ask brief clarification questions when needed. -- Keep responses concise and action-oriented. +- Keep responses concise and action-oriented. Your updates should help the intermediary respond to the user. From 9b004e2db126995307bc32735ad3ee20e6fe5ced Mon Sep 17 00:00:00 2001 From: xl-openai Date: Tue, 3 Mar 2026 15:00:18 -0800 Subject: [PATCH 346/385] Refactor plugin config and cache path (#13333) Update config.toml plugin entries to use @ as the key. Plugin now stays in [plugins/cache/marketplace-name/plugin-name/$version/] Clean up the plugin code structure. Add plugin install functionality (not used yet). --- codex-rs/core/config.schema.json | 6 - codex-rs/core/src/config/types.rs | 1 - codex-rs/core/src/mcp/mod.rs | 15 +- .../src/{plugins.rs => plugins/manager.rs} | 253 ++++++++---- codex-rs/core/src/plugins/manifest.rs | 37 ++ codex-rs/core/src/plugins/mod.rs | 14 + codex-rs/core/src/plugins/store.rs | 374 ++++++++++++++++++ codex-rs/core/tests/suite/plugins.rs | 14 +- 8 files changed, 622 insertions(+), 92 deletions(-) rename codex-rs/core/src/{plugins.rs => plugins/manager.rs} (72%) create mode 100644 codex-rs/core/src/plugins/manifest.rs create mode 100644 codex-rs/core/src/plugins/mod.rs create mode 100644 codex-rs/core/src/plugins/store.rs diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 3cd7000913..74af6d50c6 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1107,14 +1107,8 @@ "enabled": { "default": true, "type": "boolean" - }, - "path": { - "$ref": "#/definitions/AbsolutePathBuf" } }, - "required": [ - "path" - ], "type": "object" }, "ProjectConfig": { diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index 8fd5b109d0..6f8c349158 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -778,7 +778,6 @@ pub struct SkillConfig { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct PluginConfig { - pub path: AbsolutePathBuf, #[serde(default = "default_enabled")] pub enabled: bool, } diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index 4edb45c462..91a7f74db9 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -417,7 +417,7 @@ mod tests { fs::write(path, contents).unwrap(); } - fn plugin_config_toml(plugin_root: &Path) -> String { + fn plugin_config_toml() -> String { let mut root = toml::map::Map::new(); let mut features = toml::map::Map::new(); @@ -425,14 +425,10 @@ mod tests { root.insert("features".to_string(), Value::Table(features)); let mut plugin = toml::map::Map::new(); - plugin.insert( - "path".to_string(), - Value::String(plugin_root.display().to_string()), - ); plugin.insert("enabled".to_string(), Value::Boolean(true)); let mut plugins = toml::map::Map::new(); - plugins.insert("sample".to_string(), Value::Table(plugin)); + plugins.insert("sample@test".to_string(), Value::Table(plugin)); root.insert("plugins".to_string(), Value::Table(plugins)); toml::to_string(&Value::Table(root)).expect("plugin test config should serialize") @@ -616,7 +612,10 @@ mod tests { #[tokio::test] async fn effective_mcp_servers_include_plugins_without_overriding_user_config() { let codex_home = tempfile::tempdir().expect("tempdir"); - let plugin_root = codex_home.path().join("plugin-sample"); + let plugin_root = codex_home + .path() + .join("plugins/cache") + .join("test/sample/local"); write_file( &plugin_root.join(".codex-plugin/plugin.json"), r#"{"name":"sample"}"#, @@ -638,7 +637,7 @@ mod tests { ); write_file( &codex_home.path().join(CONFIG_TOML_FILE), - &plugin_config_toml(&plugin_root), + &plugin_config_toml(), ); let mut config = ConfigBuilder::default() diff --git a/codex-rs/core/src/plugins.rs b/codex-rs/core/src/plugins/manager.rs similarity index 72% rename from codex-rs/core/src/plugins.rs rename to codex-rs/core/src/plugins/manager.rs index 890d15a323..d98c4379ff 100644 --- a/codex-rs/core/src/plugins.rs +++ b/codex-rs/core/src/plugins/manager.rs @@ -1,4 +1,14 @@ +use super::load_plugin_manifest; +use super::plugin_manifest_name; +use super::store::DEFAULT_PLUGIN_VERSION; +use super::store::PluginId; +use super::store::PluginInstallRequest; +use super::store::PluginInstallResult; +use super::store::PluginStore; +use super::store::PluginStoreError; use crate::config::Config; +use crate::config::ConfigService; +use crate::config::ConfigServiceError; use crate::config::ConfigToml; use crate::config::profile::ConfigProfile; use crate::config::types::McpServerConfig; @@ -7,10 +17,13 @@ use crate::config_loader::ConfigLayerStack; use crate::features::Feature; use crate::features::FeatureOverrides; use crate::features::Features; +use codex_app_server_protocol::ConfigValueWriteParams; +use codex_app_server_protocol::MergeStrategy; use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; use serde_json::Map as JsonMap; use serde_json::Value as JsonValue; +use serde_json::json; use std::collections::HashMap; use std::fs; use std::path::Path; @@ -18,7 +31,6 @@ use std::path::PathBuf; use std::sync::RwLock; use tracing::warn; -const PLUGIN_MANIFEST_PATH: &str = ".codex-plugin/plugin.json"; const DEFAULT_SKILLS_DIR_NAME: &str = "skills"; const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json"; @@ -71,12 +83,16 @@ impl PluginLoadOutcome { } pub struct PluginsManager { + codex_home: PathBuf, + store: PluginStore, cache_by_cwd: RwLock>, } impl PluginsManager { - pub fn new(_codex_home: PathBuf) -> Self { + pub fn new(codex_home: PathBuf) -> Self { Self { + codex_home: codex_home.clone(), + store: PluginStore::new(codex_home), cache_by_cwd: RwLock::new(HashMap::new()), } } @@ -104,7 +120,7 @@ impl PluginsManager { return outcome; } - let outcome = load_plugins_from_layer_stack(config_layer_stack); + let outcome = load_plugins_from_layer_stack(config_layer_stack, &self.store); log_plugin_load_errors(&outcome); let mut cache = match self.cache_by_cwd.write() { Ok(cache) => cache, @@ -128,6 +144,50 @@ impl PluginsManager { Err(err) => err.into_inner().get(cwd).cloned(), } } + + pub async fn install_plugin( + &self, + request: PluginInstallRequest, + ) -> Result { + let store = self.store.clone(); + let result = tokio::task::spawn_blocking(move || store.install(request)) + .await + .map_err(PluginInstallError::join)??; + + ConfigService::new_with_defaults(self.codex_home.clone()) + .write_value(ConfigValueWriteParams { + key_path: format!("plugins.{}", result.plugin_id.as_key()), + value: json!({ + "enabled": true, + }), + merge_strategy: MergeStrategy::Replace, + file_path: None, + expected_version: None, + }) + .await + .map(|_| ()) + .map_err(PluginInstallError::from)?; + + Ok(result) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum PluginInstallError { + #[error("{0}")] + Store(#[from] PluginStoreError), + + #[error("{0}")] + Config(#[from] ConfigServiceError), + + #[error("failed to join plugin install task: {0}")] + Join(#[from] tokio::task::JoinError), +} + +impl PluginInstallError { + fn join(source: tokio::task::JoinError) -> Self { + Self::Join(source) + } } fn plugins_feature_enabled_from_stack(config_layer_stack: &ConfigLayerStack) -> bool { @@ -160,11 +220,6 @@ fn log_plugin_load_errors(outcome: &PluginLoadOutcome) { } } -#[derive(Debug, Default, Deserialize)] -struct PluginManifest { - name: String, -} - #[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase")] struct PluginMcpFile { @@ -172,7 +227,10 @@ struct PluginMcpFile { mcp_servers: HashMap, } -pub fn load_plugins_from_layer_stack(config_layer_stack: &ConfigLayerStack) -> PluginLoadOutcome { +pub(crate) fn load_plugins_from_layer_stack( + config_layer_stack: &ConfigLayerStack, + store: &PluginStore, +) -> PluginLoadOutcome { let mut configured_plugins: Vec<_> = configured_plugins_from_stack(config_layer_stack) .into_iter() .collect(); @@ -181,7 +239,7 @@ pub fn load_plugins_from_layer_stack(config_layer_stack: &ConfigLayerStack) -> P let mut plugins = Vec::with_capacity(configured_plugins.len()); let mut seen_mcp_server_names = HashMap::::new(); for (configured_name, plugin) in configured_plugins { - let loaded_plugin = load_plugin(configured_name.clone(), &plugin); + let loaded_plugin = load_plugin(configured_name.clone(), &plugin, store); for name in loaded_plugin.mcp_servers.keys() { if let Some(previous_plugin) = seen_mcp_server_names.insert(name.clone(), configured_name.clone()) @@ -226,12 +284,18 @@ fn configured_plugins_from_stack( } } -fn load_plugin(config_name: String, plugin: &PluginConfig) -> LoadedPlugin { - let plugin_root = plugin.path.clone(); +fn load_plugin(config_name: String, plugin: &PluginConfig, store: &PluginStore) -> LoadedPlugin { + let plugin_version = DEFAULT_PLUGIN_VERSION.to_string(); + let plugin_root = PluginId::parse(&config_name) + .map(|plugin_id| store.plugin_root(&plugin_id, &plugin_version)); + let root = match &plugin_root { + Ok(plugin_root) => plugin_root.clone(), + Err(_) => store.root().clone(), + }; let mut loaded_plugin = LoadedPlugin { config_name, manifest_name: None, - root: plugin_root.clone(), + root, enabled: plugin.enabled, skill_roots: Vec::new(), mcp_servers: HashMap::new(), @@ -242,6 +306,14 @@ fn load_plugin(config_name: String, plugin: &PluginConfig) -> LoadedPlugin { return loaded_plugin; } + let plugin_root = match plugin_root { + Ok(plugin_root) => plugin_root, + Err(err) => { + loaded_plugin.error = Some(err.to_string()); + return loaded_plugin; + } + }; + if !plugin_root.as_path().is_dir() { loaded_plugin.error = Some("path does not exist or is not a directory".to_string()); return loaded_plugin; @@ -272,33 +344,6 @@ fn load_plugin(config_name: String, plugin: &PluginConfig) -> LoadedPlugin { loaded_plugin } -fn load_plugin_manifest(plugin_root: &Path) -> Option { - let manifest_path = plugin_root.join(PLUGIN_MANIFEST_PATH); - if !manifest_path.is_file() { - return None; - } - let contents = fs::read_to_string(&manifest_path).ok()?; - match serde_json::from_str(&contents) { - Ok(manifest) => Some(manifest), - Err(err) => { - warn!( - path = %manifest_path.display(), - "failed to parse plugin manifest: {err}" - ); - None - } - } -} - -fn plugin_manifest_name(manifest: &PluginManifest, plugin_root: &Path) -> String { - plugin_root - .file_name() - .and_then(|name| name.to_str()) - .filter(|_| manifest.name.trim().is_empty()) - .unwrap_or(&manifest.name) - .to_string() -} - fn default_skill_roots(plugin_root: &Path) -> Vec { let skills_dir = plugin_root.join(DEFAULT_SKILLS_DIR_NAME); if skills_dir.is_dir() { @@ -422,6 +467,7 @@ mod tests { use crate::config::ConfigBuilder; use crate::config::types::McpServerTransportConfig; use pretty_assertions::assert_eq; + use std::fs; use tempfile::TempDir; use toml::Value; @@ -430,11 +476,20 @@ mod tests { fs::write(path, contents).unwrap(); } - fn plugin_config_toml( - plugin_root: &Path, - enabled: bool, - plugins_feature_enabled: bool, - ) -> String { + fn write_plugin(root: &Path, dir_name: &str, manifest_name: &str) { + let plugin_root = root.join(dir_name); + fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); + fs::create_dir_all(plugin_root.join("skills")).unwrap(); + fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + format!(r#"{{"name":"{manifest_name}"}}"#), + ) + .unwrap(); + fs::write(plugin_root.join("skills/SKILL.md"), "skill").unwrap(); + fs::write(plugin_root.join(".mcp.json"), r#"{"mcpServers":{}}"#).unwrap(); + } + + fn plugin_config_toml(enabled: bool, plugins_feature_enabled: bool) -> String { let mut root = toml::map::Map::new(); let mut features = toml::map::Map::new(); @@ -445,14 +500,10 @@ mod tests { root.insert("features".to_string(), Value::Table(features)); let mut plugin = toml::map::Map::new(); - plugin.insert( - "path".to_string(), - Value::String(plugin_root.display().to_string()), - ); plugin.insert("enabled".to_string(), Value::Boolean(enabled)); let mut plugins = toml::map::Map::new(); - plugins.insert("sample".to_string(), Value::Table(plugin)); + plugins.insert("sample@test".to_string(), Value::Table(plugin)); root.insert("plugins".to_string(), Value::Table(plugins)); toml::to_string(&Value::Table(root)).expect("plugin test config should serialize") @@ -471,7 +522,10 @@ mod tests { #[tokio::test] async fn load_plugins_loads_default_skills_and_mcp_servers() { let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home.path().join("plugin-sample"); + let plugin_root = codex_home + .path() + .join("plugins/cache") + .join("test/sample/local"); write_file( &plugin_root.join(".codex-plugin/plugin.json"), @@ -497,16 +551,13 @@ mod tests { }"#, ); - let outcome = load_plugins_from_config( - &plugin_config_toml(&plugin_root, true, true), - codex_home.path(), - ) - .await; + let outcome = + load_plugins_from_config(&plugin_config_toml(true, true), codex_home.path()).await; assert_eq!( outcome.plugins, vec![LoadedPlugin { - config_name: "sample".to_string(), + config_name: "sample@test".to_string(), manifest_name: Some("sample".to_string()), root: AbsolutePathBuf::try_from(plugin_root.clone()).unwrap(), enabled: true, @@ -544,7 +595,10 @@ mod tests { #[tokio::test] async fn load_plugins_preserves_disabled_plugins_without_effective_contributions() { let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home.path().join("plugin-sample"); + let plugin_root = codex_home + .path() + .join("plugins/cache") + .join("test/sample/local"); write_file( &plugin_root.join(".codex-plugin/plugin.json"), @@ -562,16 +616,13 @@ mod tests { }"#, ); - let outcome = load_plugins_from_config( - &plugin_config_toml(&plugin_root, false, true), - codex_home.path(), - ) - .await; + let outcome = + load_plugins_from_config(&plugin_config_toml(false, true), codex_home.path()).await; assert_eq!( outcome.plugins, vec![LoadedPlugin { - config_name: "sample".to_string(), + config_name: "sample@test".to_string(), manifest_name: None, root: AbsolutePathBuf::try_from(plugin_root).unwrap(), enabled: false, @@ -605,7 +656,10 @@ mod tests { #[tokio::test] async fn load_plugins_returns_empty_when_feature_disabled() { let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home.path().join("plugin-sample"); + let plugin_root = codex_home + .path() + .join("plugins/cache") + .join("test/sample/local"); write_file( &plugin_root.join(".codex-plugin/plugin.json"), @@ -616,12 +670,77 @@ mod tests { "---\nname: sample-search\ndescription: search sample data\n---\n", ); + let outcome = + load_plugins_from_config(&plugin_config_toml(true, false), codex_home.path()).await; + + assert_eq!(outcome, PluginLoadOutcome::default()); + } + + #[tokio::test] + async fn load_plugins_rejects_invalid_plugin_keys() { + let codex_home = TempDir::new().unwrap(); + let plugin_root = codex_home + .path() + .join("plugins/cache") + .join("test/sample/local"); + + write_file( + &plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ); + + let mut root = toml::map::Map::new(); + let mut features = toml::map::Map::new(); + features.insert("plugins".to_string(), Value::Boolean(true)); + root.insert("features".to_string(), Value::Table(features)); + + let mut plugin = toml::map::Map::new(); + plugin.insert("enabled".to_string(), Value::Boolean(true)); + + let mut plugins = toml::map::Map::new(); + plugins.insert("sample".to_string(), Value::Table(plugin)); + root.insert("plugins".to_string(), Value::Table(plugins)); + let outcome = load_plugins_from_config( - &plugin_config_toml(&plugin_root, true, false), + &toml::to_string(&Value::Table(root)).expect("plugin test config should serialize"), codex_home.path(), ) .await; - assert_eq!(outcome, PluginLoadOutcome::default()); + assert_eq!(outcome.plugins.len(), 1); + assert_eq!( + outcome.plugins[0].error.as_deref(), + Some("invalid plugin key `sample`; expected @") + ); + assert!(outcome.effective_skill_roots().is_empty()); + assert!(outcome.effective_mcp_servers().is_empty()); + } + + #[tokio::test] + async fn install_plugin_updates_config_with_relative_path_and_plugin_key() { + let tmp = tempfile::tempdir().unwrap(); + write_plugin(tmp.path(), "sample-plugin", "sample-plugin"); + + let result = PluginsManager::new(tmp.path().to_path_buf()) + .install_plugin(PluginInstallRequest { + source_path: tmp.path().join("sample-plugin"), + marketplace_name: None, + }) + .await + .unwrap(); + + let installed_path = tmp.path().join("plugins/cache/debug/sample-plugin/local"); + assert_eq!( + result, + PluginInstallResult { + plugin_id: PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap(), + plugin_version: "local".to_string(), + installed_path, + } + ); + + let config = fs::read_to_string(tmp.path().join("config.toml")).unwrap(); + assert!(config.contains(r#"[plugins."sample-plugin@debug"]"#)); + assert!(config.contains("enabled = true")); } } diff --git a/codex-rs/core/src/plugins/manifest.rs b/codex-rs/core/src/plugins/manifest.rs new file mode 100644 index 0000000000..ad677de814 --- /dev/null +++ b/codex-rs/core/src/plugins/manifest.rs @@ -0,0 +1,37 @@ +use serde::Deserialize; +use std::fs; +use std::path::Path; + +pub(crate) const PLUGIN_MANIFEST_PATH: &str = ".codex-plugin/plugin.json"; + +#[derive(Debug, Default, Deserialize)] +pub(crate) struct PluginManifest { + name: String, +} + +pub(crate) fn load_plugin_manifest(plugin_root: &Path) -> Option { + let manifest_path = plugin_root.join(PLUGIN_MANIFEST_PATH); + if !manifest_path.is_file() { + return None; + } + let contents = fs::read_to_string(&manifest_path).ok()?; + match serde_json::from_str(&contents) { + Ok(manifest) => Some(manifest), + Err(err) => { + tracing::warn!( + path = %manifest_path.display(), + "failed to parse plugin manifest: {err}" + ); + None + } + } +} + +pub(crate) fn plugin_manifest_name(manifest: &PluginManifest, plugin_root: &Path) -> String { + plugin_root + .file_name() + .and_then(|name| name.to_str()) + .filter(|_| manifest.name.trim().is_empty()) + .unwrap_or(&manifest.name) + .to_string() +} diff --git a/codex-rs/core/src/plugins/mod.rs b/codex-rs/core/src/plugins/mod.rs new file mode 100644 index 0000000000..faf0a8dd0c --- /dev/null +++ b/codex-rs/core/src/plugins/mod.rs @@ -0,0 +1,14 @@ +mod manager; +mod manifest; +mod store; + +pub use manager::LoadedPlugin; +pub use manager::PluginInstallError; +pub use manager::PluginLoadOutcome; +pub use manager::PluginsManager; +pub(crate) use manager::plugin_namespace_for_skill_path; +pub(crate) use manifest::load_plugin_manifest; +pub(crate) use manifest::plugin_manifest_name; +pub use store::PluginId; +pub use store::PluginInstallRequest; +pub use store::PluginInstallResult; diff --git a/codex-rs/core/src/plugins/store.rs b/codex-rs/core/src/plugins/store.rs new file mode 100644 index 0000000000..96c355805e --- /dev/null +++ b/codex-rs/core/src/plugins/store.rs @@ -0,0 +1,374 @@ +use super::load_plugin_manifest; +use super::manifest::PLUGIN_MANIFEST_PATH; +use super::plugin_manifest_name; +use codex_utils_absolute_path::AbsolutePathBuf; +use std::fs; +use std::io; +use std::path::Path; +use std::path::PathBuf; + +const DEFAULT_MARKETPLACE_NAME: &str = "debug"; +pub(crate) const DEFAULT_PLUGIN_VERSION: &str = "local"; +pub(crate) const PLUGINS_CACHE_DIR: &str = "plugins/cache"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PluginInstallRequest { + pub source_path: PathBuf, + pub marketplace_name: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PluginId { + pub plugin_name: String, + pub marketplace_name: String, +} + +impl PluginId { + pub fn new(plugin_name: String, marketplace_name: String) -> Result { + validate_plugin_segment(&plugin_name, "plugin name") + .map_err(PluginStoreError::InvalidPluginKey)?; + validate_plugin_segment(&marketplace_name, "marketplace name") + .map_err(PluginStoreError::InvalidPluginKey)?; + Ok(Self { + plugin_name, + marketplace_name, + }) + } + + pub fn parse(plugin_key: &str) -> Result { + let Some((plugin_name, marketplace_name)) = plugin_key.rsplit_once('@') else { + return Err(PluginStoreError::InvalidPluginKey(format!( + "invalid plugin key `{plugin_key}`; expected @" + ))); + }; + if plugin_name.is_empty() || marketplace_name.is_empty() { + return Err(PluginStoreError::InvalidPluginKey(format!( + "invalid plugin key `{plugin_key}`; expected @" + ))); + } + + Self::new(plugin_name.to_string(), marketplace_name.to_string()).map_err(|err| match err { + PluginStoreError::InvalidPluginKey(message) => { + PluginStoreError::InvalidPluginKey(format!("{message} in `{plugin_key}`")) + } + other => other, + }) + } + + pub fn as_key(&self) -> String { + format!("{}@{}", self.plugin_name, self.marketplace_name) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PluginInstallResult { + pub plugin_id: PluginId, + pub plugin_version: String, + pub installed_path: PathBuf, +} + +#[derive(Debug, Clone)] +pub struct PluginStore { + root: AbsolutePathBuf, +} + +impl PluginStore { + pub fn new(codex_home: PathBuf) -> Self { + Self { + root: AbsolutePathBuf::try_from(codex_home.join(PLUGINS_CACHE_DIR)) + .unwrap_or_else(|err| panic!("plugin cache root should be absolute: {err}")), + } + } + + pub fn root(&self) -> &AbsolutePathBuf { + &self.root + } + + pub fn plugin_root(&self, plugin_id: &PluginId, plugin_version: &str) -> AbsolutePathBuf { + AbsolutePathBuf::try_from( + self.root + .as_path() + .join(&plugin_id.marketplace_name) + .join(&plugin_id.plugin_name) + .join(plugin_version), + ) + .unwrap_or_else(|err| panic!("plugin cache path should resolve to an absolute path: {err}")) + } + + pub fn install( + &self, + request: PluginInstallRequest, + ) -> Result { + let source_path = request.source_path; + if !source_path.is_dir() { + return Err(PluginStoreError::InvalidPlugin(format!( + "plugin source path is not a directory: {}", + source_path.display() + ))); + } + + let plugin_name = plugin_name_for_source(&source_path)?; + let marketplace_name = request + .marketplace_name + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| DEFAULT_MARKETPLACE_NAME.to_string()); + let plugin_version = DEFAULT_PLUGIN_VERSION.to_string(); + let plugin_id = match PluginId::new(plugin_name, marketplace_name) { + Ok(plugin_id) => plugin_id, + Err(PluginStoreError::InvalidPluginKey(message)) => { + return Err(PluginStoreError::InvalidPlugin(message)); + } + Err(err) => return Err(err), + }; + let installed_path = self + .plugin_root(&plugin_id, &plugin_version) + .into_path_buf(); + + if let Some(parent) = installed_path.parent() { + fs::create_dir_all(parent).map_err(|err| { + PluginStoreError::io("failed to create plugin cache directory", err) + })?; + } + + remove_existing_target(&installed_path)?; + copy_dir_recursive(&source_path, &installed_path)?; + + Ok(PluginInstallResult { + plugin_id, + plugin_version, + installed_path, + }) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum PluginStoreError { + #[error("{context}: {source}")] + Io { + context: &'static str, + #[source] + source: io::Error, + }, + + #[error("{0}")] + InvalidPlugin(String), + + #[error("{0}")] + InvalidPluginKey(String), +} + +impl PluginStoreError { + fn io(context: &'static str, source: io::Error) -> Self { + Self::Io { context, source } + } +} + +fn plugin_name_for_source(source_path: &Path) -> Result { + let manifest_path = source_path.join(PLUGIN_MANIFEST_PATH); + if !manifest_path.is_file() { + return Err(PluginStoreError::InvalidPlugin(format!( + "missing plugin manifest: {}", + manifest_path.display() + ))); + } + + let manifest = load_plugin_manifest(source_path).ok_or_else(|| { + PluginStoreError::InvalidPlugin(format!( + "missing or invalid plugin manifest: {}", + manifest_path.display() + )) + })?; + + let plugin_name = plugin_manifest_name(&manifest, source_path); + validate_plugin_segment(&plugin_name, "plugin name") + .map_err(PluginStoreError::InvalidPlugin) + .map(|_| plugin_name) +} + +fn validate_plugin_segment(segment: &str, kind: &str) -> Result<(), String> { + if segment.is_empty() { + return Err(format!("invalid {kind}: must not be empty")); + } + if !segment + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') + { + return Err(format!( + "invalid {kind}: only ASCII letters, digits, `_`, and `-` are allowed" + )); + } + Ok(()) +} + +fn remove_existing_target(path: &Path) -> Result<(), PluginStoreError> { + if !path.exists() { + return Ok(()); + } + + if path.is_dir() { + fs::remove_dir_all(path).map_err(|err| { + PluginStoreError::io("failed to remove existing plugin cache entry", err) + }) + } else { + fs::remove_file(path).map_err(|err| { + PluginStoreError::io("failed to remove existing plugin cache entry", err) + }) + } +} + +fn copy_dir_recursive(source: &Path, target: &Path) -> Result<(), PluginStoreError> { + fs::create_dir_all(target) + .map_err(|err| PluginStoreError::io("failed to create plugin target directory", err))?; + + for entry in fs::read_dir(source) + .map_err(|err| PluginStoreError::io("failed to read plugin source directory", err))? + { + let entry = + entry.map_err(|err| PluginStoreError::io("failed to enumerate plugin source", err))?; + let source_path = entry.path(); + let target_path = target.join(entry.file_name()); + let file_type = entry + .file_type() + .map_err(|err| PluginStoreError::io("failed to inspect plugin source entry", err))?; + + if file_type.is_dir() { + copy_dir_recursive(&source_path, &target_path)?; + } else if file_type.is_file() { + fs::copy(&source_path, &target_path) + .map_err(|err| PluginStoreError::io("failed to copy plugin file", err))?; + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use tempfile::tempdir; + + fn write_plugin(root: &Path, dir_name: &str, manifest_name: &str) { + let plugin_root = root.join(dir_name); + fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); + fs::create_dir_all(plugin_root.join("skills")).unwrap(); + fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + format!(r#"{{"name":"{manifest_name}"}}"#), + ) + .unwrap(); + fs::write(plugin_root.join("skills/SKILL.md"), "skill").unwrap(); + fs::write(plugin_root.join(".mcp.json"), r#"{"mcpServers":{}}"#).unwrap(); + } + + #[test] + fn install_copies_plugin_into_default_marketplace() { + let tmp = tempdir().unwrap(); + write_plugin(tmp.path(), "sample-plugin", "sample-plugin"); + + let result = PluginStore::new(tmp.path().to_path_buf()) + .install(PluginInstallRequest { + source_path: tmp.path().join("sample-plugin"), + marketplace_name: None, + }) + .unwrap(); + + let installed_path = tmp.path().join("plugins/cache/debug/sample-plugin/local"); + assert_eq!( + result, + PluginInstallResult { + plugin_id: PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap(), + plugin_version: "local".to_string(), + installed_path: installed_path.clone(), + } + ); + assert!(installed_path.join(".codex-plugin/plugin.json").is_file()); + assert!(installed_path.join("skills/SKILL.md").is_file()); + } + + #[test] + fn install_uses_manifest_name_for_destination_and_key() { + let tmp = tempdir().unwrap(); + write_plugin(tmp.path(), "source-dir", "manifest-name"); + + let result = PluginStore::new(tmp.path().to_path_buf()) + .install(PluginInstallRequest { + source_path: tmp.path().join("source-dir"), + marketplace_name: Some("market".to_string()), + }) + .unwrap(); + + assert_eq!( + result, + PluginInstallResult { + plugin_id: PluginId::new("manifest-name".to_string(), "market".to_string()) + .unwrap(), + plugin_version: "local".to_string(), + installed_path: tmp.path().join("plugins/cache/market/manifest-name/local"), + } + ); + } + + #[test] + fn plugin_root_derives_path_from_key_and_version() { + let tmp = tempdir().unwrap(); + let store = PluginStore::new(tmp.path().to_path_buf()); + let plugin_id = PluginId::new("sample".to_string(), "debug".to_string()).unwrap(); + + assert_eq!( + store.plugin_root(&plugin_id, "local").as_path(), + tmp.path().join("plugins/cache/debug/sample/local") + ); + } + + #[test] + fn plugin_root_rejects_path_separators_in_key_segments() { + let err = PluginId::parse("../../etc@debug").unwrap_err(); + assert_eq!( + err.to_string(), + "invalid plugin name: only ASCII letters, digits, `_`, and `-` are allowed in `../../etc@debug`" + ); + + let err = PluginId::parse("sample@../../etc").unwrap_err(); + assert_eq!( + err.to_string(), + "invalid marketplace name: only ASCII letters, digits, `_`, and `-` are allowed in `sample@../../etc`" + ); + } + + #[test] + fn install_rejects_manifest_names_with_path_separators() { + let tmp = tempdir().unwrap(); + write_plugin(tmp.path(), "source-dir", "../../etc"); + + let err = PluginStore::new(tmp.path().to_path_buf()) + .install(PluginInstallRequest { + source_path: tmp.path().join("source-dir"), + marketplace_name: None, + }) + .unwrap_err(); + + assert_eq!( + err.to_string(), + "invalid plugin name: only ASCII letters, digits, `_`, and `-` are allowed" + ); + } + + #[test] + fn install_rejects_marketplace_names_with_path_separators() { + let tmp = tempdir().unwrap(); + write_plugin(tmp.path(), "source-dir", "sample-plugin"); + + let err = PluginStore::new(tmp.path().to_path_buf()) + .install(PluginInstallRequest { + source_path: tmp.path().join("source-dir"), + marketplace_name: Some("../../etc".to_string()), + }) + .unwrap_err(); + + assert_eq!( + err.to_string(), + "invalid marketplace name: only ASCII letters, digits, `_`, and `-` are allowed" + ); + } +} diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index ed2ba54a3a..3e641d010d 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -24,7 +24,7 @@ use tempfile::TempDir; use wiremock::MockServer; fn write_plugin_skill_plugin(home: &TempDir) -> std::path::PathBuf { - let plugin_root = home.path().join("plugins/sample"); + let plugin_root = home.path().join("plugins/cache/test/sample/local"); let skill_dir = plugin_root.join("skills/sample-search"); std::fs::create_dir_all(skill_dir.as_path()).expect("create plugin skill dir"); std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); @@ -40,17 +40,14 @@ fn write_plugin_skill_plugin(home: &TempDir) -> std::path::PathBuf { .expect("write plugin skill"); std::fs::write( home.path().join("config.toml"), - format!( - "[features]\nplugins = true\n\n[plugins.sample]\nenabled = true\npath = \"{}\"\n", - plugin_root.display() - ), + "[features]\nplugins = true\n\n[plugins.\"sample@test\"]\nenabled = true\n", ) .expect("write config"); skill_dir.join("SKILL.md") } fn write_plugin_mcp_plugin(home: &TempDir, command: &str) { - let plugin_root = home.path().join("plugins/sample"); + let plugin_root = home.path().join("plugins/cache/test/sample/local"); std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); std::fs::write( plugin_root.join(".codex-plugin/plugin.json"), @@ -72,10 +69,7 @@ fn write_plugin_mcp_plugin(home: &TempDir, command: &str) { .expect("write plugin mcp config"); std::fs::write( home.path().join("config.toml"), - format!( - "[features]\nplugins = true\n\n[plugins.sample]\nenabled = true\npath = \"{}\"\n", - plugin_root.display() - ), + "[features]\nplugins = true\n\n[plugins.\"sample@test\"]\nenabled = true\n", ) .expect("write config"); } From 24a2d0c696d8b1b3d0c137f8e67126b33b07d189 Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Tue, 3 Mar 2026 15:12:06 -0800 Subject: [PATCH 347/385] fix(network-proxy): reject mismatched host headers (#13275) ## Summary - reject plain HTTP absolute-form requests whose Host header does not match the request target authority - add host/port-aware Host header validation for non-default ports - add regression coverage for mismatched Host forwarding and validator edge cases --- codex-rs/network-proxy/src/http_proxy.rs | 139 +++++++++++++++-------- 1 file changed, 94 insertions(+), 45 deletions(-) diff --git a/codex-rs/network-proxy/src/http_proxy.rs b/codex-rs/network-proxy/src/http_proxy.rs index cc08cd3b25..4f88d25383 100644 --- a/codex-rs/network-proxy/src/http_proxy.rs +++ b/codex-rs/network-proxy/src/http_proxy.rs @@ -48,6 +48,8 @@ use rama_http::Request; use rama_http::Response; use rama_http::StatusCode; use rama_http::header; +use rama_http::headers::HeaderMapExt; +use rama_http::headers::Host; use rama_http::layer::remove_header::RemoveResponseHeaderLayer; use rama_http::matcher::MethodMatcher; use rama_http_backend::client::proxy::layer::HttpProxyConnector; @@ -55,7 +57,6 @@ use rama_http_backend::server::HttpServer; use rama_http_backend::server::layer::upgrade::UpgradeLayer; use rama_http_backend::server::layer::upgrade::Upgraded; use rama_net::Protocol; -use rama_net::address::HostWithOptPort; use rama_net::address::ProxyAddress; use rama_net::client::ConnectorService; use rama_net::client::EstablishedClientConnection; @@ -562,18 +563,27 @@ async fn http_plain_proxy( }; } - let authority = match RequestContext::try_from(&req).map(|ctx| ctx.host_with_port()) { - Ok(authority) => authority, + let request_ctx = match RequestContext::try_from(&req) { + Ok(request_ctx) => request_ctx, Err(err) => { warn!("missing host: {err}"); return Ok(text_response(StatusCode::BAD_REQUEST, "missing host")); } }; + let authority = request_ctx.host_with_port(); let host = normalize_host(&authority.host.to_string()); let port = authority.port; - if let Err(err) = validate_plain_http_host_header(&req, &authority) { - warn!("HTTP request host mismatch: {err}"); - return Ok(text_response(StatusCode::BAD_REQUEST, "host mismatch")); + if let Err(reason) = validate_absolute_form_host_header(&req, &request_ctx) { + let client = client.as_deref().unwrap_or_default(); + let host_header = req + .headers() + .get(header::HOST) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + warn!( + "request rejected due to mismatched Host header (client={client}, target={host}:{port}, host_header={host_header}, reason={reason})" + ); + return Ok(text_response(StatusCode::BAD_REQUEST, reason)); } let enabled = match app_state .enabled() @@ -757,6 +767,39 @@ fn client_addr(input: &T) -> Option { .map(|info| info.peer_addr().to_string()) } +fn validate_absolute_form_host_header( + req: &Request, + request_ctx: &RequestContext, +) -> Result<(), &'static str> { + if req.uri().scheme_str().is_none() { + return Ok(()); + } + + let Some(host_header) = req + .headers() + .typed_try_get::() + .map_err(|_| "invalid Host header")? + else { + return Ok(()); + }; + + if host_header.0.host != request_ctx.authority.host { + return Err("Host header does not match request target"); + } + + if let Some(host_port) = host_header.0.port { + if Some(host_port) != request_ctx.authority.port { + return Err("Host header does not match request target"); + } + return Ok(()); + } + + if !request_ctx.authority_has_default_port() { + return Err("Host header does not match request target"); + } + + Ok(()) +} fn remove_hop_by_hop_request_headers(headers: &mut HeaderMap) { while let Some(raw_connection) = headers.get(header::CONNECTION).cloned() { headers.remove(header::CONNECTION); @@ -792,45 +835,6 @@ fn remove_hop_by_hop_request_headers(headers: &mut HeaderMap) { } } -fn validate_plain_http_host_header( - req: &Request, - target: &rama_net::address::HostWithPort, -) -> std::result::Result<(), &'static str> { - // Only enforce this in absolute-form requests. Origin-form requests use the Host header as the - // routing authority, so there is no separate target authority to compare against. - if req.uri().authority().is_none() { - return Ok(()); - } - - let Some(raw_host) = req.headers().get(header::HOST) else { - return Ok(()); - }; - let raw_host = raw_host.to_str().map_err(|_| "invalid Host header")?; - let parsed = HostWithOptPort::try_from(raw_host).map_err(|_| "invalid Host header")?; - - let target_host = normalize_host(&target.host.to_string()); - let request_host = normalize_host(&parsed.host.to_string()); - if request_host.is_empty() || request_host != target_host { - return Err("request Host header host does not match target authority"); - } - - let expected_port = target.port; - let request_port = match parsed.port { - Some(port) => port, - None => match req.uri().scheme_str() { - Some("http") => 80, - Some("https") => 443, - Some(_) | None => expected_port, - }, - }; - - if request_port != expected_port { - return Err("request Host header port does not match target authority"); - } - - Ok(()) -} - fn json_blocked(host: &str, reason: &str, details: Option<&PolicyDecisionDetails<'_>>) -> Response { let (message, decision, source, protocol, port) = details .map(|details| { @@ -1136,6 +1140,51 @@ mod tests { assert_eq!(response.unwrap().status(), StatusCode::BAD_REQUEST); } + #[test] + fn validate_absolute_form_host_header_allows_matching_default_port() { + let req = Request::builder() + .method(Method::GET) + .uri("http://example.com/") + .header("host", "example.com") + .body(Body::empty()) + .unwrap(); + + assert_eq!( + validate_absolute_form_host_header(&req, &RequestContext::try_from(&req).unwrap(),), + Ok(()) + ); + } + + #[test] + fn validate_absolute_form_host_header_rejects_mismatched_host() { + let req = Request::builder() + .method(Method::GET) + .uri("http://raw.githubusercontent.com/") + .header("host", "api.github.com") + .body(Body::empty()) + .unwrap(); + + assert_eq!( + validate_absolute_form_host_header(&req, &RequestContext::try_from(&req).unwrap(),), + Err("Host header does not match request target") + ); + } + + #[test] + fn validate_absolute_form_host_header_rejects_missing_non_default_port() { + let req = Request::builder() + .method(Method::GET) + .uri("http://example.com:8080/") + .header("host", "example.com") + .body(Body::empty()) + .unwrap(); + + assert_eq!( + validate_absolute_form_host_header(&req, &RequestContext::try_from(&req).unwrap(),), + Err("Host header does not match request target") + ); + } + #[test] fn remove_hop_by_hop_request_headers_keeps_forwarding_headers() { let mut headers = HeaderMap::new(); From 299b8ac4455a76d510f9967f0392058c62e4a7ce Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Tue, 3 Mar 2026 15:31:52 -0800 Subject: [PATCH 348/385] tui: align pending steers with core acceptance (#12868) ## Summary - submit `Enter` steers immediately while a turn is already running instead of routing them through `queued_user_messages` - keep those submitted steers visible in the footer as `pending_steers` until core records them as a user message or aborts the turn - reconcile pending steers on `ItemCompleted(UserMessage)`, not `RawResponseItem` - emit user-message item lifecycle for leftover pending input at task finish, then remove the TUI `TurnComplete` fallback - keep `queued_user_messages` for actual queued drafts, rendered below pending steers ## Problem While the assistant was generating, pressing `Enter` could send the input into `queued_user_messages`. That queue only drains after the turn ends, so ordinary steers behaved like queued drafts instead of landing at the next core sampling boundary. The first version of this fix also used `RawResponseItem` to decide when a steer had landed. Review feedback was that this is the wrong abstraction for client behavior. There was also a late edge case in core: if pending steer input was accepted after the final sampling decision but before `TurnComplete`, core would record that user message into history at task finish without emitting `ItemStarted(UserMessage)` / `ItemCompleted(UserMessage)`. TUI had a fallback to paper over that gap locally. ## Approach - `Enter` during an active turn now submits a normal `Op::UserTurn` immediately - TUI keeps a local pending-steer preview instead of rendering that user message into history immediately - when core records the steer as `ItemCompleted(UserMessage)`, TUI matches and removes the corresponding pending preview, then renders the committed user message - core now emits the same user-message lifecycle when `on_task_finished(...)` drains leftover pending user input, before `TurnComplete` - with that lifecycle gap closed in core, TUI no longer needs to flush pending steers into history on `TurnComplete` - if the turn is interrupted, pending steers and queued drafts are both restored into the composer, with pending steers first ## Notes - `Tab` still uses the real queued-message path - `queued_user_messages` and `pending_steers` are separate state with separate semantics - the pending-steer matching key is built directly from `UserInput` - this removes the new TUI dependency on `RawResponseItem` ## Validation - `just fmt` - `cargo test -p codex-core task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input -- --nocapture` - `cargo test -p codex-tui` --- codex-rs/core/src/codex.rs | 72 +- codex-rs/core/src/tasks/mod.rs | 23 +- codex-rs/tui/src/bottom_pane/mod.rs | 38 +- ...r_messages.rs => pending_input_preview.rs} | 144 ++- ...iew__tests__render_many_line_message.snap} | 0 ...sts__render_more_than_three_messages.snap} | 0 ...t_preview__tests__render_one_message.snap} | 0 ...view__tests__render_one_pending_steer.snap | 15 + ..._pending_steers_above_queued_messages.snap | 25 + ..._preview__tests__render_two_messages.snap} | 0 ...eview__tests__render_wrapped_message.snap} | 0 codex-rs/tui/src/chatwidget.rs | 245 +++-- codex-rs/tui/src/chatwidget/realtime.rs | 86 +- ...e_final_message_are_rendered_snapshot.snap | 5 - codex-rs/tui/src/chatwidget/tests.rs | 858 +++++++++++++++--- 15 files changed, 1247 insertions(+), 264 deletions(-) rename codex-rs/tui/src/bottom_pane/{queued_user_messages.rs => pending_input_preview.rs} (55%) rename codex-rs/tui/src/bottom_pane/snapshots/{codex_tui__bottom_pane__queued_user_messages__tests__render_many_line_message.snap => codex_tui__bottom_pane__pending_input_preview__tests__render_many_line_message.snap} (100%) rename codex-rs/tui/src/bottom_pane/snapshots/{codex_tui__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap => codex_tui__bottom_pane__pending_input_preview__tests__render_more_than_three_messages.snap} (100%) rename codex-rs/tui/src/bottom_pane/snapshots/{codex_tui__bottom_pane__queued_user_messages__tests__render_one_message.snap => codex_tui__bottom_pane__pending_input_preview__tests__render_one_message.snap} (100%) create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_one_pending_steer.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_pending_steers_above_queued_messages.snap rename codex-rs/tui/src/bottom_pane/snapshots/{codex_tui__bottom_pane__queued_user_messages__tests__render_two_messages.snap => codex_tui__bottom_pane__pending_input_preview__tests__render_two_messages.snap} (100%) rename codex-rs/tui/src/bottom_pane/snapshots/{codex_tui__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap => codex_tui__bottom_pane__pending_input_preview__tests__render_wrapped_message.snap} (100%) delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 3a28a3e83b..7736aa1280 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -6590,6 +6590,7 @@ mod tests { use crate::protocol::TokenCountEvent; use crate::protocol::TokenUsage; use crate::protocol::TokenUsageInfo; + use crate::protocol::TurnCompleteEvent; use crate::protocol::UserMessageEvent; use crate::rollout::policy::EventPersistenceMode; use crate::rollout::recorder::RolloutRecorder; @@ -9307,8 +9308,8 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn task_finish_persists_leftover_pending_input() { - let (sess, tc, _rx) = make_session_and_context_with_rx().await; + async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input() { + let (sess, tc, rx) = make_session_and_context_with_rx().await; let input = vec![UserInput::Text { text: "hello".to_string(), text_elements: Vec::new(), @@ -9323,6 +9324,8 @@ mod tests { ) .await; + while rx.try_recv().is_ok() {} + sess.inject_response_items(vec![ResponseInputItem::Message { role: "user".to_string(), content: vec![ContentItem::InputText { @@ -9348,6 +9351,71 @@ mod tests { history.raw_items().iter().any(|item| item == &expected), "expected pending input to be persisted into history on turn completion" ); + + let first = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("expected raw response item event") + .expect("channel open"); + assert!(matches!(first.msg, EventMsg::RawResponseItem(_))); + + let second = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("expected item started event") + .expect("channel open"); + assert!(matches!( + second.msg, + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::UserMessage(UserMessageItem { content, .. }), + .. + }) if content == vec![UserInput::Text { + text: "late pending input".to_string(), + text_elements: Vec::new(), + }] + )); + + let third = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("expected item completed event") + .expect("channel open"); + assert!(matches!( + third.msg, + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::UserMessage(UserMessageItem { content, .. }), + .. + }) if content == vec![UserInput::Text { + text: "late pending input".to_string(), + text_elements: Vec::new(), + }] + )); + + let fourth = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("expected legacy user message event") + .expect("channel open"); + assert!(matches!( + fourth.msg, + EventMsg::UserMessage(UserMessageEvent { + message, + images, + text_elements, + local_images, + }) if message == "late pending input" + && images == Some(Vec::new()) + && text_elements.is_empty() + && local_images.is_empty() + )); + + let fifth = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("expected turn complete event") + .expect("channel open"); + assert!(matches!( + fifth.msg, + EventMsg::TurnComplete(TurnCompleteEvent { + turn_id, + last_agent_message: None, + }) if turn_id == tc.sub_id + )); } #[tokio::test] diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 97719f1049..5133dc1e27 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -22,6 +22,7 @@ use crate::AuthManager; use crate::codex::Session; use crate::codex::TurnContext; use crate::contextual_user_message::TURN_ABORTED_OPEN_TAG; +use crate::event_mapping::parse_turn_item; use crate::models_manager::manager::ModelsManager; use crate::protocol::EventMsg; use crate::protocol::TurnAbortReason; @@ -30,6 +31,7 @@ use crate::protocol::TurnCompleteEvent; use crate::state::ActiveTurn; use crate::state::RunningTask; use crate::state::TaskKind; +use codex_protocol::items::TurnItem; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; @@ -213,8 +215,25 @@ impl Session { .into_iter() .map(ResponseItem::from) .collect::>(); - self.record_conversation_items(turn_context.as_ref(), &pending_response_items) - .await; + for response_item in pending_response_items { + if let Some(TurnItem::UserMessage(user_message)) = parse_turn_item(&response_item) { + // Keep leftover user input on the same persistence + lifecycle path as the + // normal pre-sampling drain. This helper records the response item once, then + // emits ItemStarted/UserMessage and ItemCompleted/UserMessage for clients. + self.record_user_prompt_and_emit_turn_item( + turn_context.as_ref(), + &user_message.content, + response_item, + ) + .await; + } else { + self.record_conversation_items( + turn_context.as_ref(), + std::slice::from_ref(&response_item), + ) + .await; + } + } } let event = EventMsg::TurnComplete(TurnCompleteEvent { turn_id: turn_context.sub_id.clone(), diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 02c7faeebb..74862df999 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -17,8 +17,8 @@ use std::path::PathBuf; use crate::app_event::ConnectorsSnapshot; use crate::app_event_sender::AppEventSender; +use crate::bottom_pane::pending_input_preview::PendingInputPreview; use crate::bottom_pane::pending_thread_approvals::PendingThreadApprovals; -use crate::bottom_pane::queued_user_messages::QueuedUserMessages; use crate::bottom_pane::unified_exec_footer::UnifiedExecFooter; use crate::key_hint; use crate::key_hint::KeyBinding; @@ -93,9 +93,9 @@ pub(crate) use skills_toggle_view::SkillsToggleView; pub(crate) use status_line_setup::StatusLineItem; pub(crate) use status_line_setup::StatusLineSetupView; mod paste_burst; +mod pending_input_preview; mod pending_thread_approvals; pub mod popup_consts; -mod queued_user_messages; mod scroll_state; mod selection_popup_common; mod textarea; @@ -172,8 +172,8 @@ pub(crate) struct BottomPane { /// When a status row exists, this summary is mirrored inline in that row; /// when no status row exists, it renders as its own footer row. unified_exec_footer: UnifiedExecFooter, - /// Queued user messages to show above the composer while a turn is running. - queued_user_messages: QueuedUserMessages, + /// Preview of pending steers and queued drafts shown above the composer. + pending_input_preview: PendingInputPreview, /// Inactive threads with pending approval requests. pending_thread_approvals: PendingThreadApprovals, context_window_percent: Option, @@ -223,7 +223,7 @@ impl BottomPane { is_task_running: false, status: None, unified_exec_footer: UnifiedExecFooter::new(), - queued_user_messages: QueuedUserMessages::new(), + pending_input_preview: PendingInputPreview::new(), pending_thread_approvals: PendingThreadApprovals::new(), esc_backtrack_hint: false, animations_enabled, @@ -317,7 +317,7 @@ impl BottomPane { /// Update the key hint shown next to queued messages so it matches the /// binding that `ChatWidget` actually listens for. pub(crate) fn set_queued_message_edit_binding(&mut self, binding: KeyBinding) { - self.queued_user_messages.set_edit_binding(binding); + self.pending_input_preview.set_edit_binding(binding); self.request_redraw(); } @@ -774,9 +774,14 @@ impl BottomPane { true } - /// Update the queued messages preview shown above the composer. - pub(crate) fn set_queued_user_messages(&mut self, queued: Vec) { - self.queued_user_messages.messages = queued; + /// Update the pending-input preview shown above the composer. + pub(crate) fn set_pending_input_preview( + &mut self, + queued: Vec, + pending_steers: Vec, + ) { + self.pending_input_preview.pending_steers = pending_steers; + self.pending_input_preview.queued_messages = queued; self.request_redraw(); } @@ -1019,18 +1024,19 @@ impl BottomPane { flex.push(0, RenderableItem::Borrowed(&self.unified_exec_footer)); } let has_pending_thread_approvals = !self.pending_thread_approvals.is_empty(); - let has_queued_messages = !self.queued_user_messages.messages.is_empty(); + let has_pending_input = !self.pending_input_preview.queued_messages.is_empty() + || !self.pending_input_preview.pending_steers.is_empty(); let has_status_or_footer = self.status.is_some() || !self.unified_exec_footer.is_empty(); - let has_inline_previews = has_pending_thread_approvals || has_queued_messages; + let has_inline_previews = has_pending_thread_approvals || has_pending_input; if has_inline_previews && has_status_or_footer { flex.push(0, RenderableItem::Owned("".into())); } flex.push(1, RenderableItem::Borrowed(&self.pending_thread_approvals)); - if has_pending_thread_approvals && has_queued_messages { + if has_pending_thread_approvals && has_pending_input { flex.push(0, RenderableItem::Owned("".into())); } - flex.push(1, RenderableItem::Borrowed(&self.queued_user_messages)); + flex.push(1, RenderableItem::Borrowed(&self.pending_input_preview)); if !has_inline_previews && has_status_or_footer { flex.push(0, RenderableItem::Owned("".into())); } @@ -1406,7 +1412,7 @@ mod tests { StatusDetailsCapitalization::CapitalizeFirst, STATUS_DETAILS_DEFAULT_MAX_LINES, ); - pane.set_queued_user_messages(vec!["Queued follow-up question".to_string()]); + pane.set_pending_input_preview(vec!["Queued follow-up question".to_string()], Vec::new()); let width = 48; let height = pane.desired_height(width); @@ -1433,7 +1439,7 @@ mod tests { }); pane.set_task_running(true); - pane.set_queued_user_messages(vec!["Queued follow-up question".to_string()]); + pane.set_pending_input_preview(vec!["Queued follow-up question".to_string()], Vec::new()); pane.hide_status_indicator(); let width = 48; @@ -1461,7 +1467,7 @@ mod tests { }); pane.set_task_running(true); - pane.set_queued_user_messages(vec!["Queued follow-up question".to_string()]); + pane.set_pending_input_preview(vec!["Queued follow-up question".to_string()], Vec::new()); let width = 48; let height = pane.desired_height(width); diff --git a/codex-rs/tui/src/bottom_pane/queued_user_messages.rs b/codex-rs/tui/src/bottom_pane/pending_input_preview.rs similarity index 55% rename from codex-rs/tui/src/bottom_pane/queued_user_messages.rs rename to codex-rs/tui/src/bottom_pane/pending_input_preview.rs index 30a525f457..da7bc8cb69 100644 --- a/codex-rs/tui/src/bottom_pane/queued_user_messages.rs +++ b/codex-rs/tui/src/bottom_pane/pending_input_preview.rs @@ -10,23 +10,26 @@ use crate::render::renderable::Renderable; use crate::wrapping::RtOptions; use crate::wrapping::adaptive_wrap_lines; -/// Widget that displays a list of user messages queued while a turn is in progress. +/// Widget that displays pending steers plus user messages queued while a turn is in progress. /// -/// The widget shows a key hint at the bottom (e.g. "⌥ + ↑ edit") telling the -/// user how to pop the most recent queued message back into the composer. -/// Because some terminals intercept certain modifier-key combinations, the -/// displayed binding is configurable via [`set_edit_binding`](Self::set_edit_binding). -pub(crate) struct QueuedUserMessages { - pub messages: Vec, +/// The widget shows pending steers first, then queued user messages. It only +/// shows the edit hint at the bottom (e.g. "⌥ + ↑ edit") when there are actual +/// queued user messages to pop back into the composer. Because some terminals +/// intercept certain modifier-key combinations, the displayed binding is +/// configurable via [`set_edit_binding`](Self::set_edit_binding). +pub(crate) struct PendingInputPreview { + pub pending_steers: Vec, + pub queued_messages: Vec, /// Key combination rendered in the hint line. Defaults to Alt+Up but may /// be overridden for terminals where that chord is unavailable. edit_binding: key_hint::KeyBinding, } -impl QueuedUserMessages { +impl PendingInputPreview { pub(crate) fn new() -> Self { Self { - messages: Vec::new(), + pending_steers: Vec::new(), + queued_messages: Vec::new(), edit_binding: key_hint::alt(KeyCode::Up), } } @@ -39,13 +42,31 @@ impl QueuedUserMessages { } fn as_renderable(&self, width: u16) -> Box { - if self.messages.is_empty() || width < 4 { + if (self.pending_steers.is_empty() && self.queued_messages.is_empty()) || width < 4 { return Box::new(()); } let mut lines = vec![]; - for message in &self.messages { + for steer in &self.pending_steers { + let wrapped = adaptive_wrap_lines( + steer + .lines() + .map(|line| format!("pending steer: {line}").dim()), + RtOptions::new(width as usize) + .initial_indent(Line::from(" ! ".dim())) + .subsequent_indent(Line::from(" ")), + ); + let len = wrapped.len(); + for line in wrapped.into_iter().take(3) { + lines.push(line); + } + if len > 3 { + lines.push(Line::from(" …".dim())); + } + } + + for message in &self.queued_messages { let wrapped = adaptive_wrap_lines( message.lines().map(|line| line.dim().italic()), RtOptions::new(width as usize) @@ -61,20 +82,22 @@ impl QueuedUserMessages { } } - lines.push( - Line::from(vec![ - " ".into(), - self.edit_binding.into(), - " edit".into(), - ]) - .dim(), - ); + if !self.queued_messages.is_empty() { + lines.push( + Line::from(vec![ + " ".into(), + self.edit_binding.into(), + " edit".into(), + ]) + .dim(), + ); + } Paragraph::new(lines).into() } } -impl Renderable for QueuedUserMessages { +impl Renderable for PendingInputPreview { fn render(&self, area: Rect, buf: &mut Buffer) { if area.is_empty() { return; @@ -96,21 +119,21 @@ mod tests { #[test] fn desired_height_empty() { - let queue = QueuedUserMessages::new(); + let queue = PendingInputPreview::new(); assert_eq!(queue.desired_height(40), 0); } #[test] fn desired_height_one_message() { - let mut queue = QueuedUserMessages::new(); - queue.messages.push("Hello, world!".to_string()); + let mut queue = PendingInputPreview::new(); + queue.queued_messages.push("Hello, world!".to_string()); assert_eq!(queue.desired_height(40), 2); } #[test] fn render_one_message() { - let mut queue = QueuedUserMessages::new(); - queue.messages.push("Hello, world!".to_string()); + let mut queue = PendingInputPreview::new(); + queue.queued_messages.push("Hello, world!".to_string()); let width = 40; let height = queue.desired_height(width); let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); @@ -120,9 +143,11 @@ mod tests { #[test] fn render_two_messages() { - let mut queue = QueuedUserMessages::new(); - queue.messages.push("Hello, world!".to_string()); - queue.messages.push("This is another message".to_string()); + let mut queue = PendingInputPreview::new(); + queue.queued_messages.push("Hello, world!".to_string()); + queue + .queued_messages + .push("This is another message".to_string()); let width = 40; let height = queue.desired_height(width); let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); @@ -132,11 +157,17 @@ mod tests { #[test] fn render_more_than_three_messages() { - let mut queue = QueuedUserMessages::new(); - queue.messages.push("Hello, world!".to_string()); - queue.messages.push("This is another message".to_string()); - queue.messages.push("This is a third message".to_string()); - queue.messages.push("This is a fourth message".to_string()); + let mut queue = PendingInputPreview::new(); + queue.queued_messages.push("Hello, world!".to_string()); + queue + .queued_messages + .push("This is another message".to_string()); + queue + .queued_messages + .push("This is a third message".to_string()); + queue + .queued_messages + .push("This is a fourth message".to_string()); let width = 40; let height = queue.desired_height(width); let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); @@ -146,11 +177,13 @@ mod tests { #[test] fn render_wrapped_message() { - let mut queue = QueuedUserMessages::new(); + let mut queue = PendingInputPreview::new(); queue - .messages + .queued_messages .push("This is a longer message that should be wrapped".to_string()); - queue.messages.push("This is another message".to_string()); + queue + .queued_messages + .push("This is another message".to_string()); let width = 40; let height = queue.desired_height(width); let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); @@ -160,9 +193,9 @@ mod tests { #[test] fn render_many_line_message() { - let mut queue = QueuedUserMessages::new(); + let mut queue = PendingInputPreview::new(); queue - .messages + .queued_messages .push("This is\na message\nwith many\nlines".to_string()); let width = 40; let height = queue.desired_height(width); @@ -173,8 +206,8 @@ mod tests { #[test] fn long_url_like_message_does_not_expand_into_wrapped_ellipsis_rows() { - let mut queue = QueuedUserMessages::new(); - queue.messages.push( + let mut queue = PendingInputPreview::new(); + queue.queued_messages.push( "example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/session_id=abc123def456ghi789" .to_string(), ); @@ -202,4 +235,35 @@ mod tests { "expected no wrapped-ellipsis row for URL-like token, got rows: {rendered_rows:?}" ); } + + #[test] + fn render_one_pending_steer() { + let mut queue = PendingInputPreview::new(); + queue.pending_steers.push("Please continue.".to_string()); + let width = 48; + let height = queue.desired_height(width); + let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); + queue.render(Rect::new(0, 0, width, height), &mut buf); + assert_snapshot!("render_one_pending_steer", format!("{buf:?}")); + } + + #[test] + fn render_pending_steers_above_queued_messages() { + let mut queue = PendingInputPreview::new(); + queue.pending_steers.push("Please continue.".to_string()); + queue + .pending_steers + .push("Check the last command output.".to_string()); + queue + .queued_messages + .push("Queued follow-up question".to_string()); + let width = 52; + let height = queue.desired_height(width); + let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); + queue.render(Rect::new(0, 0, width, height), &mut buf); + assert_snapshot!( + "render_pending_steers_above_queued_messages", + format!("{buf:?}") + ); + } } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_many_line_message.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_many_line_message.snap similarity index 100% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_many_line_message.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_many_line_message.snap diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_more_than_three_messages.snap similarity index 100% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_more_than_three_messages.snap diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_one_message.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_one_message.snap similarity index 100% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_one_message.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_one_message.snap diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_one_pending_steer.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_one_pending_steer.snap new file mode 100644 index 0000000000..d738b7dc09 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_one_pending_steer.snap @@ -0,0 +1,15 @@ +--- +source: tui/src/bottom_pane/pending_input_preview.rs +assertion_line: 237 +expression: "format!(\"{buf:?}\")" +--- +Buffer { + area: Rect { x: 0, y: 0, width: 48, height: 1 }, + content: [ + " ! pending steer: Please continue. ", + ], + styles: [ + x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 35, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + ] +} diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_pending_steers_above_queued_messages.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_pending_steers_above_queued_messages.snap new file mode 100644 index 0000000000..6979d507df --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_pending_steers_above_queued_messages.snap @@ -0,0 +1,25 @@ +--- +source: tui/src/bottom_pane/pending_input_preview.rs +assertion_line: 252 +expression: "format!(\"{buf:?}\")" +--- +Buffer { + area: Rect { x: 0, y: 0, width: 52, height: 4 }, + content: [ + " ! pending steer: Please continue. ", + " ! pending steer: Check the last command output. ", + " ↳ Queued follow-up question ", + " ⌥ + ↑ edit ", + ], + styles: [ + x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 35, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 49, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC, + x: 29, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM, + x: 14, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + ] +} diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_two_messages.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_two_messages.snap similarity index 100% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_two_messages.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_two_messages.snap diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_wrapped_message.snap similarity index 100% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__pending_input_preview__tests__render_wrapped_message.snap diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 51f39c1f2a..a0d3454183 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -37,6 +37,7 @@ use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; +use self::realtime::PendingSteerCompareKey; use crate::app_event::RealtimeAudioDeviceKind; #[cfg(all(not(target_os = "linux"), feature = "voice-input"))] use crate::audio_device::list_realtime_audio_device_names; @@ -85,6 +86,7 @@ use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::Settings; #[cfg(target_os = "windows")] use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::items::AgentMessageContent; use codex_protocol::items::AgentMessageItem; use codex_protocol::models::MessagePhase; use codex_protocol::models::local_image_label_text; @@ -618,6 +620,11 @@ pub(crate) struct ChatWidget { suppress_session_configured_redraw: bool, // User messages queued while a turn is in progress queued_user_messages: VecDeque, + // Steers already submitted to core but not yet committed into history. + // + // The bottom pane shows these above queued drafts until core records the + // corresponding user message item. + pending_steers: VecDeque, /// Terminal-appropriate keybinding for popping the most-recently queued /// message back into the composer. Determined once at construction time via /// [`queued_message_edit_binding_for_terminal`] and propagated to @@ -650,7 +657,9 @@ pub(crate) struct ChatWidget { had_work_activity: bool, // Whether the current turn emitted a plan update. saw_plan_update_this_turn: bool, - // Whether the current turn emitted a proposed plan item. + // Whether the current turn emitted a proposed plan item that has not been superseded by a + // later steer. This is cleared when the user submits a steer so the plan popup only appears + // if a newer proposed plan arrives afterward. saw_plan_item_this_turn: bool, // Incremental buffer for streamed plan content. plan_delta_buffer: String, @@ -751,6 +760,11 @@ impl From<&str> for UserMessage { } } +struct PendingSteer { + user_message: UserMessage, + compare_key: PendingSteerCompareKey, +} + pub(crate) fn create_initial_user_message( text: Option, local_image_paths: Vec, @@ -778,6 +792,21 @@ pub(crate) fn create_initial_user_message( } } +fn append_text_with_rebased_elements( + target_text: &mut String, + target_text_elements: &mut Vec, + text: &str, + text_elements: impl IntoIterator, +) { + let offset = target_text.len(); + target_text.push_str(text); + target_text_elements.extend(text_elements.into_iter().map(|mut element| { + element.byte_range.start += offset; + element.byte_range.end += offset; + element + })); +} + // When merging multiple queued drafts (e.g., after interrupt), each draft starts numbering // its attachments at [Image #1]. Reassign placeholder labels based on the attachment list so // the combined local_image_paths order matches the labels, even if placeholders were moved @@ -1290,17 +1319,24 @@ impl ChatWidget { self.request_redraw(); } - fn on_agent_message(&mut self, message: String) { - // If we have a stream_controller, then the final agent message is redundant and will be a - // duplicate of what has already been streamed. - if self.stream_controller.is_none() && !message.is_empty() { - self.handle_streaming_delta(message); + fn finalize_completed_assistant_message(&mut self, message: Option<&str>) { + // If we have a stream_controller, the finalized message payload is redundant because the + // visible content has already been accumulated through deltas. + if self.stream_controller.is_none() + && let Some(message) = message + && !message.is_empty() + { + self.handle_streaming_delta(message.to_string()); } self.flush_answer_stream_with_separator(); self.handle_stream_finished(); self.request_redraw(); } + fn on_agent_message(&mut self, message: String) { + self.finalize_completed_assistant_message(Some(&message)); + } + fn on_agent_message_delta(&mut self, delta: String) { self.handle_streaming_delta(delta); } @@ -1483,7 +1519,10 @@ impl ChatWidget { self.unified_exec_wait_streak = None; self.request_redraw(); - if !from_replay && self.queued_user_messages.is_empty() { + let had_pending_steers = !self.pending_steers.is_empty(); + self.refresh_pending_input_preview(); + + if !from_replay && self.queued_user_messages.is_empty() && !had_pending_steers { self.maybe_prompt_plan_implementation(); } // Keep this flag for replayed completion events so a subsequent live TurnComplete can @@ -1865,30 +1904,31 @@ impl ChatWidget { if reason == TurnAbortReason::Interrupted { self.clear_unified_exec_processes(); } - if reason != TurnAbortReason::ReviewEnded { self.add_to_history(history_cell::new_error_event( "Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.".to_owned(), )); } - if let Some(combined) = self.drain_queued_messages_for_restore() { + // Core clears pending_input before emitting TurnAborted, so any unacknowledged steers + // still tracked here must be restored locally instead of waiting for a later commit. + if let Some(combined) = self.drain_pending_messages_for_restore() { self.restore_user_message_to_composer(combined); - self.refresh_queued_user_messages(); } + self.refresh_pending_input_preview(); self.request_redraw(); } - /// Merge queued drafts (plus the current composer state) into a single message for restore. + /// Merge pending steers, queued drafts, and the current composer state into a single message. /// - /// Each queued draft numbers attachments from `[Image #1]`. When we concatenate drafts, we - /// must renumber placeholders in a stable order so the merged attachment list stays aligned - /// with the labels embedded in text. This helper drains the queue, remaps placeholders, and - /// fixes text element byte ranges as content is appended. Returns `None` when there is nothing - /// to restore. - fn drain_queued_messages_for_restore(&mut self) -> Option { - if self.queued_user_messages.is_empty() { + /// Each pending message numbers attachments from `[Image #1]` relative to its own remote + /// images. When we concatenate multiple messages after interrupt, we must renumber local-image + /// placeholders in a stable order and rebase text element byte ranges so the restored composer + /// state stays aligned with the merged attachment list. Returns `None` when there is nothing to + /// restore. + fn drain_pending_messages_for_restore(&mut self) -> Option { + if self.pending_steers.is_empty() && self.queued_user_messages.is_empty() { return None; } @@ -1900,7 +1940,12 @@ impl ChatWidget { mention_bindings: self.bottom_pane.composer_mention_bindings(), }; - let mut to_merge: Vec = self.queued_user_messages.drain(..).collect(); + let mut to_merge: Vec = self + .pending_steers + .drain(..) + .map(|steer| steer.user_message) + .collect(); + to_merge.extend(self.queued_user_messages.drain(..)); if !existing_message.text.is_empty() || !existing_message.local_images.is_empty() || !existing_message.remote_image_urls.is_empty() @@ -1915,7 +1960,6 @@ impl ChatWidget { remote_image_urls: Vec::new(), mention_bindings: Vec::new(), }; - let mut combined_offset = 0usize; let total_remote_images = to_merge .iter() .map(|message| message.remote_image_urls.len()) @@ -1925,22 +1969,23 @@ impl ChatWidget { for (idx, message) in to_merge.into_iter().enumerate() { if idx > 0 { combined.text.push('\n'); - combined_offset += 1; } - let message = remap_placeholders_for_message(message, &mut next_image_label); - let base = combined_offset; - combined.text.push_str(&message.text); - combined_offset += message.text.len(); - combined - .text_elements - .extend(message.text_elements.into_iter().map(|mut elem| { - elem.byte_range.start += base; - elem.byte_range.end += base; - elem - })); - combined.local_images.extend(message.local_images); - combined.remote_image_urls.extend(message.remote_image_urls); - combined.mention_bindings.extend(message.mention_bindings); + let UserMessage { + text, + text_elements, + local_images, + remote_image_urls, + mention_bindings, + } = remap_placeholders_for_message(message, &mut next_image_label); + append_text_with_rebased_elements( + &mut combined.text, + &mut combined.text_elements, + &text, + text_elements, + ); + combined.local_images.extend(local_images); + combined.remote_image_urls.extend(remote_image_urls); + combined.mention_bindings.extend(mention_bindings); } Some(combined) @@ -2350,6 +2395,15 @@ impl ChatWidget { /// returns once stream queues are idle. Final-answer completion (or absent /// phase for legacy models) clears the flag to preserve historical behavior. fn on_agent_message_item_completed(&mut self, item: AgentMessageItem) { + let mut message = String::new(); + for content in &item.content { + match content { + AgentMessageContent::Text { text } => message.push_str(text), + } + } + self.finalize_completed_assistant_message( + (!message.is_empty()).then_some(message.as_str()), + ); self.pending_status_indicator_restore = match item.phase { // Models that don't support preambles only output AgentMessageItems on turn completion. Some(MessagePhase::FinalAnswer) | None => false, @@ -2915,6 +2969,7 @@ impl ChatWidget { thread_name: None, forked_from: None, queued_user_messages: VecDeque::new(), + pending_steers: VecDeque::new(), queued_message_edit_binding, show_welcome_banner: is_first_run, startup_tooltip_override, @@ -3099,6 +3154,7 @@ impl ChatWidget { plan_delta_buffer: String::new(), plan_item_active: false, queued_user_messages: VecDeque::new(), + pending_steers: VecDeque::new(), queued_message_edit_binding, show_welcome_banner: is_first_run, startup_tooltip_override, @@ -3264,6 +3320,7 @@ impl ChatWidget { thread_name: None, forked_from: None, queued_user_messages: VecDeque::new(), + pending_steers: VecDeque::new(), queued_message_edit_binding, show_welcome_banner: false, startup_tooltip_override: None, @@ -3394,7 +3451,7 @@ impl ChatWidget { { if let Some(user_message) = self.queued_user_messages.pop_back() { self.restore_user_message_to_composer(user_message); - self.refresh_queued_user_messages(); + self.refresh_pending_input_preview(); self.request_redraw(); } return; @@ -3429,18 +3486,19 @@ impl ChatWidget { .bottom_pane .take_recent_submission_mention_bindings(), }; + if user_message.text.is_empty() + && user_message.local_images.is_empty() + && user_message.remote_image_urls.is_empty() + { + return; + } let Some(user_message) = self.maybe_defer_user_message_for_realtime(user_message) else { return; }; - // Submissions during active final-answer streaming can race with turn - // completion and strand the UI in a running state. Queue those inputs instead - // of injecting immediately; `on_task_complete()` drains this FIFO via - // `maybe_send_next_queued_input()`, so no typed prompt is dropped. - let should_submit_now = self.is_session_configured() - && !self.is_plan_streaming_in_tui() - && self.stream_controller.is_none(); + let should_submit_now = + self.is_session_configured() && !self.is_plan_streaming_in_tui(); if should_submit_now { // Submitted is emitted when user submits. // Reset any reasoning header only when we are actually submitting a turn. @@ -4086,7 +4144,7 @@ impl ChatWidget { || self.is_review_mode { self.queued_user_messages.push_back(user_message); - self.refresh_queued_user_messages(); + self.refresh_pending_input_preview(); } else { self.submit_user_message(user_message); } @@ -4096,7 +4154,12 @@ impl ChatWidget { if !self.is_session_configured() { tracing::warn!("cannot submit user message before session is configured; queueing"); self.queued_user_messages.push_front(user_message); - self.refresh_queued_user_messages(); + self.refresh_pending_input_preview(); + return; + } + if self.is_review_mode { + self.queued_user_messages.push_back(user_message); + self.refresh_pending_input_preview(); return; } @@ -4123,6 +4186,7 @@ impl ChatWidget { return; } + let render_in_history = !self.agent_turn_running; let mut items: Vec = Vec::new(); // Special-case: "!cmd" executes a local shell command instead of sending to the model. @@ -4251,6 +4315,16 @@ impl ChatWidget { } else { None }; + let pending_steer = (!render_in_history).then(|| PendingSteer { + user_message: UserMessage { + text: text.clone(), + local_images: local_images.clone(), + remote_image_urls: remote_image_urls.clone(), + text_elements: text_elements.clone(), + mention_bindings: mention_bindings.clone(), + }, + compare_key: Self::pending_steer_compare_key_from_items(&items), + }); let personality = self .config .personality @@ -4271,9 +4345,9 @@ impl ChatWidget { personality, }; - self.codex_op_tx.send(op).unwrap_or_else(|e| { - tracing::error!("failed to send message: {e}"); - }); + if !self.submit_op(op) { + return; + } // Persist the text to cross-session message history. if !text.is_empty() { @@ -4292,8 +4366,14 @@ impl ChatWidget { }); } + if let Some(pending_steer) = pending_steer { + self.pending_steers.push_back(pending_steer); + self.saw_plan_item_this_turn = false; + self.refresh_pending_input_preview(); + } + // Show replayable user content in conversation history. - if !text.is_empty() { + if render_in_history && !text.is_empty() { let local_image_paths = local_images .into_iter() .map(|img| img.path) @@ -4311,7 +4391,7 @@ impl ChatWidget { local_image_paths, remote_image_urls, )); - } else if !remote_image_urls.is_empty() { + } else if render_in_history && !remote_image_urls.is_empty() { self.last_rendered_user_message_event = Some(Self::rendered_user_message_event_from_parts( String::new(), @@ -4424,9 +4504,18 @@ impl ChatWidget { match msg { EventMsg::SessionConfigured(e) => self.on_session_configured(e), EventMsg::ThreadNameUpdated(e) => self.on_thread_name_updated(e), - EventMsg::AgentMessage(AgentMessageEvent { message, .. }) => { + EventMsg::AgentMessage(AgentMessageEvent { .. }) + if matches!(replay_kind, Some(ReplayKind::ThreadSnapshot)) + && !self.is_review_mode => {} + EventMsg::AgentMessage(AgentMessageEvent { message, .. }) + if from_replay || self.is_review_mode => + { + // TODO(ccunningham): stop relying on legacy AgentMessage in review mode, + // including thread-snapshot replay, and forward + // ItemCompleted(TurnItem::AgentMessage(_)) instead. self.on_agent_message(message) } + EventMsg::AgentMessage(AgentMessageEvent { .. }) => {} EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta }) => { self.on_agent_message_delta(delta) } @@ -4481,6 +4570,8 @@ impl ChatWidget { self.on_interrupted_turn(ev.reason); } TurnAbortReason::Replaced => { + self.pending_steers.clear(); + self.refresh_pending_input_preview(); self.on_error("Turn aborted: replaced by a new task".to_owned()) } TurnAbortReason::ReviewEnded => { @@ -4599,6 +4690,42 @@ impl ChatWidget { } EventMsg::ItemCompleted(event) => { let item = event.item; + if !from_replay && let codex_protocol::items::TurnItem::UserMessage(item) = &item { + let EventMsg::UserMessage(event) = item.as_legacy_event() else { + unreachable!("user message item should convert to a legacy user message"); + }; + let rendered = Self::rendered_user_message_event_from_event(&event); + let compare_key = Self::pending_steer_compare_key_from_item(item); + if self + .pending_steers + .front() + .is_some_and(|pending| pending.compare_key == compare_key) + { + if let Some(pending) = self.pending_steers.pop_front() { + self.refresh_pending_input_preview(); + let pending_event = UserMessageEvent { + message: pending.user_message.text, + images: Some(pending.user_message.remote_image_urls), + local_images: pending + .user_message + .local_images + .into_iter() + .map(|image| image.path) + .collect(), + text_elements: pending.user_message.text_elements, + }; + self.on_user_message_event(pending_event); + } else if self.last_rendered_user_message_event.as_ref() != Some(&rendered) + { + tracing::warn!( + "pending steer matched compare key but queue was empty when rendering committed user message" + ); + self.on_user_message_event(event); + } + } else if self.last_rendered_user_message_event.as_ref() != Some(&rendered) { + self.on_user_message_event(event); + } + } if let codex_protocol::items::TurnItem::Plan(plan_item) = &item { self.on_plan_item_completed(plan_item.text.clone()); } @@ -4749,17 +4876,23 @@ impl ChatWidget { self.submit_user_message(user_message); } // Update the list to reflect the remaining queued messages (if any). - self.refresh_queued_user_messages(); + self.refresh_pending_input_preview(); } - /// Rebuild and update the queued user messages from the current queue. - fn refresh_queued_user_messages(&mut self) { - let messages: Vec = self + /// Rebuild and update the bottom-pane pending-input preview. + fn refresh_pending_input_preview(&mut self) { + let queued_messages: Vec = self .queued_user_messages .iter() .map(|m| m.text.clone()) .collect(); - self.bottom_pane.set_queued_user_messages(messages); + let pending_steers: Vec = self + .pending_steers + .iter() + .map(|steer| steer.user_message.text.clone()) + .collect(); + self.bottom_pane + .set_pending_input_preview(queued_messages, pending_steers); } pub(crate) fn set_pending_thread_approvals(&mut self, threads: Vec) { diff --git a/codex-rs/tui/src/chatwidget/realtime.rs b/codex-rs/tui/src/chatwidget/realtime.rs index 2970ac4d3a..32f0a15287 100644 --- a/codex-rs/tui/src/chatwidget/realtime.rs +++ b/codex-rs/tui/src/chatwidget/realtime.rs @@ -49,10 +49,16 @@ impl RealtimeConversationUiState { #[derive(Clone, Debug, PartialEq)] pub(super) struct RenderedUserMessageEvent { - message: String, - remote_image_urls: Vec, - local_images: Vec, - text_elements: Vec, + pub(super) message: String, + pub(super) remote_image_urls: Vec, + pub(super) local_images: Vec, + pub(super) text_elements: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct PendingSteerCompareKey { + pub(super) message: String, + pub(super) image_count: usize, } impl ChatWidget { @@ -81,6 +87,78 @@ impl ChatWidget { ) } + /// Build the compare key for a submitted pending steer without invoking the + /// expensive request-serialization path. Pending steers only need to match the + /// committed `ItemCompleted(UserMessage)` emitted after core drains input, which + /// preserves flattened text and total image count but not UI-only text ranges or + /// local image paths. + pub(super) fn pending_steer_compare_key_from_items( + items: &[UserInput], + ) -> PendingSteerCompareKey { + let mut message = String::new(); + let mut image_count = 0; + + for item in items { + match item { + UserInput::Text { text, .. } => message.push_str(text), + UserInput::Image { .. } | UserInput::LocalImage { .. } => image_count += 1, + UserInput::Skill { .. } | UserInput::Mention { .. } => {} + _ => {} + } + } + + PendingSteerCompareKey { + message, + image_count, + } + } + + pub(super) fn pending_steer_compare_key_from_item( + item: &codex_protocol::items::UserMessageItem, + ) -> PendingSteerCompareKey { + Self::pending_steer_compare_key_from_items(&item.content) + } + + #[cfg(test)] + pub(super) fn rendered_user_message_event_from_inputs( + items: &[UserInput], + ) -> RenderedUserMessageEvent { + let mut message = String::new(); + let mut remote_image_urls = Vec::new(); + let mut local_images = Vec::new(); + let mut text_elements = Vec::new(); + + for item in items { + match item { + UserInput::Text { + text, + text_elements: current_text_elements, + } => append_text_with_rebased_elements( + &mut message, + &mut text_elements, + text, + current_text_elements.iter().map(|element| { + TextElement::new( + element.byte_range, + element.placeholder(text).map(str::to_string), + ) + }), + ), + UserInput::Image { image_url } => remote_image_urls.push(image_url.clone()), + UserInput::LocalImage { path } => local_images.push(path.clone()), + UserInput::Skill { .. } | UserInput::Mention { .. } => {} + _ => {} + } + } + + Self::rendered_user_message_event_from_parts( + message, + text_elements, + local_images, + remote_image_urls, + ) + } + pub(super) fn should_render_realtime_user_message_event( &self, event: &UserMessageEvent, diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap deleted file mode 100644 index 6062087181..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: combined ---- -• Here is the result. diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index a720559b5c..6ea109dacb 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -44,6 +44,7 @@ use codex_protocol::items::AgentMessageContent; use codex_protocol::items::AgentMessageItem; use codex_protocol::items::PlanItem; use codex_protocol::items::TurnItem; +use codex_protocol::items::UserMessageItem; use codex_protocol::models::MessagePhase; use codex_protocol::openai_models::ModelPreset; use codex_protocol::openai_models::ReasoningEffortPreset; @@ -211,6 +212,45 @@ async fn resumed_initial_messages_render_history() { ); } +#[tokio::test] +async fn thread_snapshot_replay_does_not_duplicate_agent_message_history() { + let (mut chat, mut rx, _ops) = make_chatwidget_manual(None).await; + + chat.handle_codex_event_replay(Event { + id: "turn-1".into(), + msg: EventMsg::ItemCompleted(ItemCompletedEvent { + thread_id: ThreadId::new(), + turn_id: "turn-1".to_string(), + item: TurnItem::AgentMessage(AgentMessageItem { + id: "msg-1".to_string(), + content: vec![AgentMessageContent::Text { + text: "assistant reply".to_string(), + }], + phase: None, + }), + }), + }); + chat.handle_codex_event_replay(Event { + id: "turn-1".into(), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: "assistant reply".to_string(), + phase: None, + }), + }); + + let cells = drain_insert_history(&mut rx); + assert_eq!( + cells.len(), + 1, + "expected replayed assistant message to render once" + ); + let rendered = lines_to_single_string(&cells[0]); + assert!( + rendered.contains("assistant reply"), + "expected replayed assistant message, got {rendered:?}" + ); +} + #[tokio::test] async fn replayed_user_message_preserves_text_elements_and_local_images() { let (mut chat, mut rx, _ops) = make_chatwidget_manual(None).await; @@ -1181,7 +1221,7 @@ async fn interrupted_turn_restores_queued_messages_with_images_and_elements() { text_elements: second_elements, mention_bindings: Vec::new(), }); - chat.refresh_queued_user_messages(); + chat.refresh_pending_input_preview(); chat.bottom_pane .set_composer_text(existing_text, existing_elements, existing_images.clone()); @@ -1251,7 +1291,7 @@ async fn interrupted_turn_restore_keeps_active_mode_for_resubmission() { text_elements: Vec::new(), mention_bindings: Vec::new(), }); - chat.refresh_queued_user_messages(); + chat.refresh_pending_input_preview(); chat.handle_codex_event(Event { id: "interrupt".into(), @@ -1451,6 +1491,58 @@ async fn entered_review_mode_defaults_to_current_changes_banner() { assert!(chat.is_review_mode); } +#[tokio::test] +async fn live_agent_message_renders_during_review_mode() { + let (mut chat, mut rx, _ops) = make_chatwidget_manual(None).await; + + chat.handle_codex_event(Event { + id: "review-start".into(), + msg: EventMsg::EnteredReviewMode(ReviewRequest { + target: ReviewTarget::UncommittedChanges, + user_facing_hint: None, + }), + }); + let _ = drain_insert_history(&mut rx); + + chat.handle_codex_event(Event { + id: "review-message".into(), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: "Review progress update".to_string(), + phase: None, + }), + }); + + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("Review progress update")); +} + +#[tokio::test] +async fn thread_snapshot_replay_preserves_agent_message_during_review_mode() { + let (mut chat, mut rx, _ops) = make_chatwidget_manual(None).await; + + chat.handle_codex_event_replay(Event { + id: "review-start".into(), + msg: EventMsg::EnteredReviewMode(ReviewRequest { + target: ReviewTarget::UncommittedChanges, + user_facing_hint: None, + }), + }); + let _ = drain_insert_history(&mut rx); + + chat.handle_codex_event_replay(Event { + id: "review-message".into(), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: "Review progress update".to_string(), + phase: None, + }), + }); + + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("Review progress update")); +} + /// Exiting review restores the pre-review context window indicator. #[tokio::test] async fn review_restores_context_window_indicator() { @@ -1720,6 +1812,7 @@ async fn make_chatwidget_manual( show_welcome_banner: true, startup_tooltip_override: None, queued_user_messages: VecDeque::new(), + pending_steers: VecDeque::new(), queued_message_edit_binding: crate::key_hint::alt(KeyCode::Up), suppress_session_configured_redraw: false, pending_notification: None, @@ -2753,6 +2846,94 @@ async fn plan_implementation_popup_shows_after_proposed_plan_output() { ); } +#[tokio::test] +async fn plan_implementation_popup_skips_when_steer_follows_proposed_plan() { + let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await; + chat.set_feature_enabled(Feature::CollaborationModes, true); + let plan_mask = + collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan) + .expect("expected plan collaboration mask"); + chat.set_collaboration_mask(plan_mask); + chat.thread_id = Some(ThreadId::new()); + + chat.on_task_started(); + chat.on_plan_item_completed( + "- Step 1 +- Step 2 +" + .to_string(), + ); + chat.bottom_pane + .set_composer_text("Please continue.".to_string(), Vec::new(), Vec::new()); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + match next_submit_op(&mut op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "Please continue.".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected Op::UserTurn, got {other:?}"), + } + + complete_user_message(&mut chat, "user-1", "Please continue."); + chat.on_task_complete(None, false); + + let popup = render_bottom_popup(&chat, 80); + assert!( + !popup.contains(PLAN_IMPLEMENTATION_TITLE), + "expected no plan popup after a steer follows the plan, got {popup:?}" + ); +} + +#[tokio::test] +async fn plan_implementation_popup_shows_after_new_plan_follows_steer() { + let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await; + chat.set_feature_enabled(Feature::CollaborationModes, true); + let plan_mask = + collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan) + .expect("expected plan collaboration mask"); + chat.set_collaboration_mask(plan_mask); + chat.thread_id = Some(ThreadId::new()); + + chat.on_task_started(); + chat.on_plan_item_completed( + "- Initial plan +" + .to_string(), + ); + chat.bottom_pane + .set_composer_text("Please revise.".to_string(), Vec::new(), Vec::new()); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + match next_submit_op(&mut op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "Please revise.".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected Op::UserTurn, got {other:?}"), + } + + complete_user_message(&mut chat, "user-1", "Please revise."); + chat.on_plan_item_completed( + "- Revised plan +" + .to_string(), + ); + chat.on_task_complete(None, false); + + let popup = render_bottom_popup(&chat, 80); + assert!( + popup.contains(PLAN_IMPLEMENTATION_TITLE), + "expected plan popup after a newer plan follows the steer, got {popup:?}" + ); +} + #[tokio::test] async fn plan_implementation_popup_skips_when_rate_limit_prompt_pending() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await; @@ -3064,6 +3245,41 @@ fn complete_assistant_message( }); } +fn pending_steer(text: &str) -> PendingSteer { + PendingSteer { + user_message: UserMessage::from(text), + compare_key: PendingSteerCompareKey { + message: text.to_string(), + image_count: 0, + }, + } +} + +fn complete_user_message(chat: &mut ChatWidget, item_id: &str, text: &str) { + complete_user_message_for_inputs( + chat, + item_id, + vec![UserInput::Text { + text: text.to_string(), + text_elements: Vec::new(), + }], + ); +} + +fn complete_user_message_for_inputs(chat: &mut ChatWidget, item_id: &str, content: Vec) { + chat.handle_codex_event(Event { + id: format!("raw-{item_id}"), + msg: EventMsg::ItemCompleted(ItemCompletedEvent { + thread_id: ThreadId::new(), + turn_id: "turn-1".to_string(), + item: TurnItem::UserMessage(UserMessageItem { + id: item_id.to_string(), + content, + }), + }), + }); +} + fn begin_exec(chat: &mut ChatWidget, call_id: &str, raw_cmd: &str) -> ExecCommandBeginEvent { begin_exec_with_source(chat, call_id, raw_cmd, ExecCommandSource::Agent) } @@ -3166,7 +3382,7 @@ async fn alt_up_edits_most_recent_queued_message() { .push_back(UserMessage::from("first queued".to_string())); chat.queued_user_messages .push_back(UserMessage::from("second queued".to_string())); - chat.refresh_queued_user_messages(); + chat.refresh_pending_input_preview(); // Press Alt+Up to edit the most recent (last) queued message. chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT)); @@ -3200,7 +3416,7 @@ async fn assert_shift_left_edits_most_recent_queued_message_for_terminal( .push_back(UserMessage::from("first queued".to_string())); chat.queued_user_messages .push_back(UserMessage::from("second queued".to_string())); - chat.refresh_queued_user_messages(); + chat.refresh_pending_input_preview(); // Press Shift+Left to edit the most recent (last) queued message. chat.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); @@ -3459,8 +3675,8 @@ async fn unified_exec_begin_restores_working_status_snapshot() { } #[tokio::test] -async fn enter_queues_while_plan_stream_is_active() { - let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; +async fn steer_enter_queues_while_plan_stream_is_active() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.set_feature_enabled(Feature::CollaborationModes, true); let plan_mask = @@ -3469,6 +3685,7 @@ async fn enter_queues_while_plan_stream_is_active() { chat.set_collaboration_mask(plan_mask); chat.on_task_started(); chat.on_plan_delta("- Step 1".to_string()); + let _ = drain_insert_history(&mut rx); chat.bottom_pane .set_composer_text("queued submission".to_string(), Vec::new(), Vec::new()); @@ -3480,12 +3697,44 @@ async fn enter_queues_while_plan_stream_is_active() { chat.queued_user_messages.front().unwrap().text, "queued submission" ); - assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty)); + assert!(chat.pending_steers.is_empty()); + assert_no_submit_op(&mut op_rx); + assert!(drain_insert_history(&mut rx).is_empty()); } #[tokio::test] -async fn steer_enter_queues_while_final_answer_stream_is_active() { - let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; +async fn steer_enter_uses_pending_steers_while_turn_is_running_without_streaming() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + chat.on_task_started(); + + chat.bottom_pane + .set_composer_text("queued while running".to_string(), Vec::new(), Vec::new()); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert!(chat.queued_user_messages.is_empty()); + assert_eq!(chat.pending_steers.len(), 1); + assert_eq!( + chat.pending_steers.front().unwrap().user_message.text, + "queued while running" + ); + match next_submit_op(&mut op_rx) { + Op::UserTurn { .. } => {} + other => panic!("expected Op::UserTurn, got {other:?}"), + } + assert!(drain_insert_history(&mut rx).is_empty()); + + complete_user_message(&mut chat, "user-1", "queued while running"); + + assert!(chat.pending_steers.is_empty()); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("queued while running")); +} + +#[tokio::test] +async fn steer_enter_uses_pending_steers_while_final_answer_stream_is_active() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.on_task_started(); // Keep the assistant stream open (no commit tick/finalize) to model the repro window: @@ -3499,26 +3748,228 @@ async fn steer_enter_queues_while_final_answer_stream_is_active() { ); chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(chat.queued_user_messages.len(), 1); + assert!(chat.queued_user_messages.is_empty()); + assert_eq!(chat.pending_steers.len(), 1); assert_eq!( - chat.queued_user_messages.front().unwrap().text, + chat.pending_steers.front().unwrap().user_message.text, "queued while streaming" ); - assert_no_submit_op(&mut op_rx); - - // Once final output ends, the queued input must be submitted automatically. - chat.on_task_complete(None, false); - - assert!(chat.queued_user_messages.is_empty()); match next_submit_op(&mut op_rx) { Op::UserTurn { .. } => {} - other => panic!("expected Op::UserTurn after stream completion, got {other:?}"), + other => panic!("expected Op::UserTurn, got {other:?}"), } + assert!(drain_insert_history(&mut rx).is_empty()); + + complete_user_message(&mut chat, "user-1", "queued while streaming"); + + assert!(chat.pending_steers.is_empty()); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("queued while streaming")); +} + +#[tokio::test] +async fn failed_pending_steer_submit_does_not_add_pending_preview() { + let (mut chat, mut rx, op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + chat.on_task_started(); + drop(op_rx); + + chat.bottom_pane.set_composer_text( + "queued while streaming".to_string(), + Vec::new(), + Vec::new(), + ); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert!(chat.pending_steers.is_empty()); + assert!(chat.queued_user_messages.is_empty()); + assert!(drain_insert_history(&mut rx).is_empty()); +} + +#[tokio::test] +async fn live_legacy_agent_message_after_item_completed_does_not_duplicate_assistant_message() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + + complete_assistant_message( + &mut chat, + "msg-live", + "hello", + Some(MessagePhase::FinalAnswer), + ); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("hello")); + + chat.handle_codex_event(Event { + id: "legacy-live".into(), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: "hello".into(), + phase: Some(MessagePhase::FinalAnswer), + }), + }); + + assert!(drain_insert_history(&mut rx).is_empty()); +} + +#[test] +fn rendered_user_message_event_from_inputs_matches_flattened_user_message_shape() { + let local_image = PathBuf::from("/tmp/local.png"); + let rendered = ChatWidget::rendered_user_message_event_from_inputs(&[ + UserInput::Text { + text: "hello ".to_string(), + text_elements: vec![TextElement::new((0..5).into(), None)], + }, + UserInput::Image { + image_url: "https://example.com/remote.png".to_string(), + }, + UserInput::LocalImage { + path: local_image.clone(), + }, + UserInput::Skill { + name: "demo".to_string(), + path: PathBuf::from("/tmp/skill/SKILL.md"), + }, + UserInput::Mention { + name: "repo".to_string(), + path: "app://repo".to_string(), + }, + UserInput::Text { + text: "world".to_string(), + text_elements: vec![TextElement::new((0..5).into(), Some("planet".to_string()))], + }, + ]); + + assert_eq!( + rendered, + ChatWidget::rendered_user_message_event_from_parts( + "hello world".to_string(), + vec![ + TextElement::new((0..5).into(), Some("hello".to_string())), + TextElement::new((6..11).into(), Some("planet".to_string())), + ], + vec![local_image], + vec!["https://example.com/remote.png".to_string()], + ) + ); +} + +#[tokio::test] +async fn item_completed_only_pops_front_pending_steer() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + chat.pending_steers.push_back(pending_steer("first")); + chat.pending_steers.push_back(pending_steer("second")); + chat.refresh_pending_input_preview(); + + complete_user_message(&mut chat, "user-other", "other"); + + assert_eq!(chat.pending_steers.len(), 2); + assert_eq!( + chat.pending_steers.front().unwrap().user_message.text, + "first" + ); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("other")); + + complete_user_message(&mut chat, "user-first", "first"); + + assert_eq!(chat.pending_steers.len(), 1); + assert_eq!( + chat.pending_steers.front().unwrap().user_message.text, + "second" + ); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("first")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn item_completed_pops_pending_steer_with_local_image_and_text_elements() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + chat.on_task_started(); + + let temp = tempdir().expect("tempdir"); + let image_path = temp.path().join("pending-steer.png"); + const TINY_PNG_BYTES: &[u8] = &[ + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, + 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84, 120, 156, 99, 96, 0, 2, 0, 0, 5, 0, + 1, 122, 94, 171, 63, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, + ]; + std::fs::write(&image_path, TINY_PNG_BYTES).expect("write image"); + + let text = "note".to_string(); + let text_elements = vec![TextElement::new((0..4).into(), Some("note".to_string()))]; + chat.submit_user_message(UserMessage { + text: text.clone(), + local_images: vec![LocalImageAttachment { + placeholder: "[Image #1]".to_string(), + path: image_path, + }], + remote_image_urls: Vec::new(), + text_elements, + mention_bindings: Vec::new(), + }); + + match next_submit_op(&mut op_rx) { + Op::UserTurn { .. } => {} + other => panic!("expected Op::UserTurn, got {other:?}"), + } + + assert_eq!(chat.pending_steers.len(), 1); + let pending = chat.pending_steers.front().unwrap(); + assert_eq!(pending.user_message.local_images.len(), 1); + assert_eq!(pending.user_message.text_elements.len(), 1); + assert_eq!(pending.compare_key.message, text); + assert_eq!(pending.compare_key.image_count, 1); + + complete_user_message_for_inputs( + &mut chat, + "user-1", + vec![ + UserInput::Image { + image_url: "data:image/png;base64,placeholder".to_string(), + }, + UserInput::Text { + text, + text_elements: Vec::new(), + }, + ], + ); + + assert!(chat.pending_steers.is_empty()); + + let mut user_cell = None; + while let Ok(ev) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = ev + && let Some(cell) = cell.as_any().downcast_ref::() + { + user_cell = Some(( + cell.message.clone(), + cell.text_elements.clone(), + cell.local_image_paths.clone(), + cell.remote_image_urls.clone(), + )); + break; + } + } + + let (stored_message, stored_elements, stored_images, stored_remote_image_urls) = + user_cell.expect("expected pending steer user history cell"); + assert_eq!(stored_message, "note"); + assert_eq!( + stored_elements, + vec![TextElement::new((0..4).into(), Some("note".to_string()))] + ); + assert_eq!(stored_images.len(), 1); + assert!(stored_images[0].ends_with("pending-steer.png")); + assert!(stored_remote_image_urls.is_empty()); } #[tokio::test] async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() { - let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.on_task_started(); // Simulate "dead mode" repro timing by keeping a final-answer stream active while the @@ -3532,19 +3983,16 @@ async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() .set_composer_text("second follow-up".to_string(), Vec::new(), Vec::new()); chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(chat.queued_user_messages.len(), 2); + assert!(chat.queued_user_messages.is_empty()); + assert_eq!(chat.pending_steers.len(), 2); assert_eq!( - chat.queued_user_messages.front().unwrap().text, + chat.pending_steers.front().unwrap().user_message.text, "first follow-up" ); assert_eq!( - chat.queued_user_messages.back().unwrap().text, + chat.pending_steers.back().unwrap().user_message.text, "second follow-up" ); - assert_no_submit_op(&mut op_rx); - - // Completion must recover by submitting the oldest queued prompt first. - chat.on_task_complete(None, false); let first_items = match next_submit_op(&mut op_rx) { Op::UserTurn { items, .. } => items, @@ -3557,17 +4005,6 @@ async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() text_elements: Vec::new(), }] ); - assert_eq!(chat.queued_user_messages.len(), 1); - assert_eq!( - chat.queued_user_messages.front().unwrap().text, - "second follow-up" - ); - - // A subsequent turn lifecycle should continue draining remaining queued prompts, proving - // the widget did not enter a permanently stuck state. - chat.on_task_started(); - chat.on_task_complete(None, false); - let second_items = match next_submit_op(&mut op_rx) { Op::UserTurn { items, .. } => items, other => panic!("expected Op::UserTurn, got {other:?}"), @@ -3579,7 +4016,208 @@ async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() text_elements: Vec::new(), }] ); + assert!(drain_insert_history(&mut rx).is_empty()); + + complete_user_message(&mut chat, "user-1", "first follow-up"); + + assert_eq!(chat.pending_steers.len(), 1); + assert_eq!( + chat.pending_steers.front().unwrap().user_message.text, + "second follow-up" + ); + let first_insert = drain_insert_history(&mut rx); + assert_eq!(first_insert.len(), 1); + assert!(lines_to_single_string(&first_insert[0]).contains("first follow-up")); + + complete_user_message(&mut chat, "user-2", "second follow-up"); + + assert!(chat.pending_steers.is_empty()); + let second_insert = drain_insert_history(&mut rx); + assert_eq!(second_insert.len(), 1); + assert!(lines_to_single_string(&second_insert[0]).contains("second follow-up")); +} + +#[tokio::test] +async fn manual_interrupt_restores_pending_steers_to_composer() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + chat.on_task_started(); + chat.on_agent_message_delta( + "Final answer line +" + .to_string(), + ); + + chat.bottom_pane.set_composer_text( + "queued while streaming".to_string(), + Vec::new(), + Vec::new(), + ); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_eq!(chat.pending_steers.len(), 1); + match next_submit_op(&mut op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "queued while streaming".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected Op::UserTurn, got {other:?}"), + } + assert!(drain_insert_history(&mut rx).is_empty()); + + chat.on_interrupted_turn(TurnAbortReason::Interrupted); + + assert!(chat.pending_steers.is_empty()); + assert_eq!(chat.bottom_pane.composer_text(), "queued while streaming"); + assert_no_submit_op(&mut op_rx); + + let inserted = drain_insert_history(&mut rx); + assert!( + inserted + .iter() + .all(|cell| !lines_to_single_string(cell).contains("queued while streaming")) + ); +} + +#[tokio::test] +async fn manual_interrupt_restores_pending_steer_mention_bindings_to_composer() { + let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + chat.on_task_started(); + chat.on_agent_message_delta("Final answer line\n".to_string()); + + let mention_bindings = vec![MentionBinding { + mention: "figma".to_string(), + path: "/tmp/skills/figma/SKILL.md".to_string(), + }]; + chat.bottom_pane.set_composer_text_with_mention_bindings( + "please use $figma".to_string(), + vec![TextElement::new( + (11..17).into(), + Some("$figma".to_string()), + )], + Vec::new(), + mention_bindings.clone(), + ); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + match next_submit_op(&mut op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "please use $figma".to_string(), + text_elements: vec![TextElement::new( + (11..17).into(), + Some("$figma".to_string()), + )], + }] + ), + other => panic!("expected Op::UserTurn, got {other:?}"), + } + + chat.on_interrupted_turn(TurnAbortReason::Interrupted); + + assert_eq!(chat.bottom_pane.composer_text(), "please use $figma"); + assert_eq!(chat.bottom_pane.take_mention_bindings(), mention_bindings); + assert_no_submit_op(&mut op_rx); +} + +#[tokio::test] +async fn manual_interrupt_restores_pending_steers_before_queued_messages() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + chat.on_task_started(); + chat.on_agent_message_delta( + "Final answer line +" + .to_string(), + ); + + chat.bottom_pane + .set_composer_text("pending steer".to_string(), Vec::new(), Vec::new()); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + chat.queued_user_messages + .push_back(UserMessage::from("queued draft".to_string())); + chat.refresh_pending_input_preview(); + + match next_submit_op(&mut op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "pending steer".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected Op::UserTurn, got {other:?}"), + } + assert!(drain_insert_history(&mut rx).is_empty()); + + chat.on_interrupted_turn(TurnAbortReason::Interrupted); + + assert!(chat.pending_steers.is_empty()); assert!(chat.queued_user_messages.is_empty()); + assert_eq!( + chat.bottom_pane.composer_text(), + "pending steer +queued draft" + ); + assert_no_submit_op(&mut op_rx); +} + +#[tokio::test] +async fn replaced_turn_clears_pending_steers_but_keeps_queued_drafts() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + chat.on_task_started(); + chat.on_agent_message_delta( + "Final answer line +" + .to_string(), + ); + + chat.bottom_pane + .set_composer_text("pending steer".to_string(), Vec::new(), Vec::new()); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + chat.queued_user_messages + .push_back(UserMessage::from("queued draft".to_string())); + chat.refresh_pending_input_preview(); + + match next_submit_op(&mut op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "pending steer".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected Op::UserTurn, got {other:?}"), + } + assert!(drain_insert_history(&mut rx).is_empty()); + + chat.handle_codex_event(Event { + id: "replaced".into(), + msg: EventMsg::TurnAborted(codex_protocol::protocol::TurnAbortedEvent { + turn_id: Some("turn-1".to_string()), + reason: TurnAbortReason::Replaced, + }), + }); + + assert!(chat.pending_steers.is_empty()); + assert!(chat.queued_user_messages.is_empty()); + assert_eq!(chat.bottom_pane.composer_text(), ""); + match next_submit_op(&mut op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "queued draft".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected queued draft Op::UserTurn, got {other:?}"), + } } #[tokio::test] @@ -3998,13 +4636,7 @@ async fn unified_exec_wait_after_final_agent_message_snapshot() { begin_unified_exec_startup(&mut chat, "call-wait", "proc-1", "cargo test -p codex-core"); terminal_interaction(&mut chat, "call-wait-stdin", "proc-1", ""); - chat.handle_codex_event(Event { - id: "turn-1".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: "Final response.".into(), - phase: None, - }), - }); + complete_assistant_message(&mut chat, "msg-1", "Final response.", None); chat.handle_codex_event(Event { id: "turn-1".into(), msg: EventMsg::TurnComplete(TurnCompleteEvent { @@ -4805,7 +5437,7 @@ async fn slash_copy_state_clears_on_thread_rollback() { async fn slash_copy_is_unavailable_when_legacy_agent_message_is_not_repeated_on_turn_complete() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; - chat.handle_codex_event(Event { + chat.handle_codex_event_replay(Event { id: "turn-1".into(), msg: EventMsg::AgentMessage(AgentMessageEvent { message: "Legacy final message".into(), @@ -7110,7 +7742,7 @@ async fn interrupt_restores_queued_messages_into_composer() { .push_back(UserMessage::from("first queued".to_string())); chat.queued_user_messages .push_back(UserMessage::from("second queued".to_string())); - chat.refresh_queued_user_messages(); + chat.refresh_pending_input_preview(); // Deliver a TurnAborted event with Interrupted reason (as if Esc was pressed). chat.handle_codex_event(Event { @@ -7150,7 +7782,7 @@ async fn interrupt_prepends_queued_messages_before_existing_composer_text() { .push_back(UserMessage::from("first queued".to_string())); chat.queued_user_messages .push_back(UserMessage::from("second queued".to_string())); - chat.refresh_queued_user_messages(); + chat.refresh_pending_input_preview(); chat.handle_codex_event(Event { id: "turn-1".into(), @@ -8395,22 +9027,10 @@ async fn multiple_agent_messages_in_single_turn_emit_multiple_headers() { }); // First finalized assistant message - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: "First message".into(), - phase: None, - }), - }); + complete_assistant_message(&mut chat, "msg-first", "First message", None); // Second finalized assistant message in the same turn - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: "Second message".into(), - phase: None, - }), - }); + complete_assistant_message(&mut chat, "msg-second", "Second message", None); // End turn chat.handle_codex_event(Event { @@ -8450,13 +9070,7 @@ async fn final_reasoning_then_message_without_deltas_are_rendered() { text: "I will first analyze the request.".into(), }), }); - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: "Here is the result.".into(), - phase: None, - }), - }); + complete_assistant_message(&mut chat, "msg-result", "Here is the result.", None); // Drain history and snapshot the combined visible content. let cells = drain_insert_history(&mut rx); @@ -8467,83 +9081,18 @@ async fn final_reasoning_then_message_without_deltas_are_rendered() { assert_snapshot!(combined); } -#[tokio::test] -async fn deltas_then_same_final_message_are_rendered_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; - - // Stream some reasoning deltas first. - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { - delta: "I will ".into(), - }), - }); - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { - delta: "first analyze the ".into(), - }), - }); - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { - delta: "request.".into(), - }), - }); - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentReasoning(AgentReasoningEvent { - text: "request.".into(), - }), - }); - - // Then stream answer deltas, followed by the exact same final message. - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { - delta: "Here is the ".into(), - }), - }); - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { - delta: "result.".into(), - }), - }); - - chat.handle_codex_event(Event { - id: "s1".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: "Here is the result.".into(), - phase: None, - }), - }); - - // Snapshot the combined visible content to ensure we render as expected - // when deltas are followed by the identical final message. - let cells = drain_insert_history(&mut rx); - let combined = cells - .iter() - .map(|lines| lines_to_single_string(lines)) - .collect::(); - assert_snapshot!(combined); -} - // Combined visual snapshot using vt100 for history + direct buffer overlay for UI. // This renders the final visual as seen in a terminal: history above, then a blank line, // then the exec block, another blank line, the status line, a blank line, and the composer. #[tokio::test] async fn chatwidget_exec_and_status_layout_vt100_snapshot() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; - chat.handle_codex_event(Event { - id: "t1".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: - "I’m going to search the repo for where “Change Approved” is rendered to update that view." - .into(), - phase: None, - }), - }); + complete_assistant_message( + &mut chat, + "msg-search", + "I’m going to search the repo for where “Change Approved” is rendered to update that view.", + None, + ); let command = vec!["bash".into(), "-lc".into(), "rg \"Change Approved\"".into()]; let parsed_cmd = vec![ @@ -8757,6 +9306,37 @@ async fn chatwidget_tall() { assert_snapshot!(term.backend().vt100().screen().contents()); } +#[tokio::test] +async fn enter_queues_user_messages_while_review_is_running() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; + chat.thread_id = Some(ThreadId::new()); + + chat.handle_codex_event(Event { + id: "review-1".into(), + msg: EventMsg::EnteredReviewMode(ReviewRequest { + target: ReviewTarget::UncommittedChanges, + user_facing_hint: Some("current changes".to_string()), + }), + }); + let _ = drain_insert_history(&mut rx); + + chat.bottom_pane.set_composer_text( + "Queued while /review is running.".to_string(), + Vec::new(), + Vec::new(), + ); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_eq!(chat.queued_user_messages.len(), 1); + assert_eq!( + chat.queued_user_messages.front().unwrap().text, + "Queued while /review is running." + ); + assert!(chat.pending_steers.is_empty()); + assert_no_submit_op(&mut op_rx); + assert!(drain_insert_history(&mut rx).is_empty()); +} + #[tokio::test] async fn review_queues_user_messages_snapshot() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; From 935754baa353f13f76149f55c11a3b362a6089db Mon Sep 17 00:00:00 2001 From: joeytrasatti-openai Date: Tue, 3 Mar 2026 15:56:11 -0800 Subject: [PATCH 349/385] Add thread metadata update endpoint to app server (#13280) ## Summary - add the v2 `thread/metadata/update` API, including protocol/schema/TypeScript exports and app-server docs - patch stored thread `gitInfo` in sqlite without resuming the thread, with validation plus support for explicit `null` clears - repair missing sqlite thread rows from rollout data before patching, and make those repairs safe by inserting only when absent and updating only git columns so newer metadata is not clobbered - keep sqlite authoritative for mutable thread git metadata by preserving existing sqlite git fields during reconcile/backfill and only using rollout `SessionMeta` git fields to fill gaps - add regression coverage for the endpoint, repair paths, concurrent sqlite writes, clearing git fields, and rollout/backfill reconciliation - fix the login server shutdown race so cancelling before the waiter starts still terminates `block_until_done()` correctly ## Testing - `cargo test -p codex-state apply_rollout_items_preserves_existing_git_branch_and_fills_missing_git_fields` - `cargo test -p codex-state update_thread_git_info_preserves_newer_non_git_metadata` - `cargo test -p codex-core backfill_sessions_preserves_existing_git_branch_and_fills_missing_git_fields` - `cargo test -p codex-app-server thread_metadata_update` - `cargo test` - currently fails in existing `codex-core` grep-files tests with `unsupported call: grep_files`: - `suite::grep_files::grep_files_tool_collects_matches` - `suite::grep_files::grep_files_tool_reports_empty_results` --- .../schema/json/ClientRequest.json | 72 + .../codex_app_server_protocol.schemas.json | 87 + .../codex_app_server_protocol.v2.schemas.json | 87 + .../json/v2/ThreadMetadataUpdateParams.json | 52 + .../json/v2/ThreadMetadataUpdateResponse.json | 1666 +++++++++++++++++ .../schema/typescript/ClientRequest.ts | 3 +- .../v2/ThreadMetadataGitInfoUpdateParams.ts | 20 + .../v2/ThreadMetadataUpdateParams.ts | 12 + .../v2/ThreadMetadataUpdateResponse.ts | 6 + .../schema/typescript/v2/index.ts | 3 + .../src/protocol/common.rs | 4 + .../app-server-protocol/src/protocol/v2.rs | 55 + codex-rs/app-server/Cargo.toml | 1 - codex-rs/app-server/README.md | 29 + .../app-server/src/codex_message_processor.rs | 308 +++ .../app-server/tests/common/mcp_process.rs | 12 +- .../tests/suite/fuzzy_file_search.rs | 2 +- codex-rs/app-server/tests/suite/v2/mod.rs | 1 + .../tests/suite/v2/thread_metadata_update.rs | 462 +++++ .../app-server/tests/suite/v2/turn_start.rs | 2 +- codex-rs/core/src/rollout/metadata.rs | 64 +- codex-rs/core/src/state_db.rs | 3 + codex-rs/state/src/model/thread_metadata.rs | 13 + codex-rs/state/src/runtime/threads.rs | 293 +++ 24 files changed, 3251 insertions(+), 6 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateParams.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataGitInfoUpdateParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateResponse.ts create mode 100644 codex-rs/app-server/tests/suite/v2/thread_metadata_update.rs diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 01790fb98f..40745ce666 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -2059,6 +2059,54 @@ }, "type": "object" }, + "ThreadMetadataGitInfoUpdateParams": { + "properties": { + "branch": { + "description": "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "originUrl": { + "description": "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "sha": { + "description": "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "ThreadMetadataUpdateParams": { + "properties": { + "gitInfo": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadMetadataGitInfoUpdateParams" + }, + { + "type": "null" + } + ], + "description": "Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value." + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "type": "object" + }, "ThreadReadParams": { "properties": { "includeTurns": { @@ -2939,6 +2987,30 @@ "title": "Thread/name/setRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/metadata/update" + ], + "title": "Thread/metadata/updateRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadMetadataUpdateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/metadata/updateRequest", + "type": "object" + }, { "properties": { "id": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index ddeee0ce73..4695d2a810 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -523,6 +523,30 @@ "title": "Thread/name/setRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "thread/metadata/update" + ], + "title": "Thread/metadata/updateRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadMetadataUpdateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/metadata/updateRequest", + "type": "object" + }, { "properties": { "id": { @@ -13611,6 +13635,69 @@ "title": "ThreadLoadedListResponse", "type": "object" }, + "ThreadMetadataGitInfoUpdateParams": { + "properties": { + "branch": { + "description": "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "originUrl": { + "description": "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "sha": { + "description": "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "ThreadMetadataUpdateParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "gitInfo": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ThreadMetadataGitInfoUpdateParams" + }, + { + "type": "null" + } + ], + "description": "Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value." + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadMetadataUpdateParams", + "type": "object" + }, + "ThreadMetadataUpdateResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/v2/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadMetadataUpdateResponse", + "type": "object" + }, "ThreadNameUpdatedNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 1bd5733364..e1f4c85d13 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -1012,6 +1012,30 @@ "title": "Thread/name/setRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/metadata/update" + ], + "title": "Thread/metadata/updateRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadMetadataUpdateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/metadata/updateRequest", + "type": "object" + }, { "properties": { "id": { @@ -12289,6 +12313,69 @@ "title": "ThreadLoadedListResponse", "type": "object" }, + "ThreadMetadataGitInfoUpdateParams": { + "properties": { + "branch": { + "description": "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "originUrl": { + "description": "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "sha": { + "description": "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "ThreadMetadataUpdateParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "gitInfo": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadMetadataGitInfoUpdateParams" + }, + { + "type": "null" + } + ], + "description": "Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value." + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadMetadataUpdateParams", + "type": "object" + }, + "ThreadMetadataUpdateResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadMetadataUpdateResponse", + "type": "object" + }, "ThreadNameUpdatedNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateParams.json new file mode 100644 index 0000000000..c6679568ea --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateParams.json @@ -0,0 +1,52 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ThreadMetadataGitInfoUpdateParams": { + "properties": { + "branch": { + "description": "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "originUrl": { + "description": "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + }, + "sha": { + "description": "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + } + }, + "properties": { + "gitInfo": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadMetadataGitInfoUpdateParams" + }, + { + "type": "null" + } + ], + "description": "Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value." + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadMetadataUpdateParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json new file mode 100644 index 0000000000..800010ee2a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json @@ -0,0 +1,1666 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ByteRange": { + "properties": { + "end": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "start": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "end", + "start" + ], + "type": "object" + }, + "CodexErrorInfo": { + "description": "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", + "oneOf": [ + { + "enum": [ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "httpConnectionFailed": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "httpConnectionFailed" + ], + "title": "HttpConnectionFailedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Failed to connect to the response SSE stream.", + "properties": { + "responseStreamConnectionFailed": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseStreamConnectionFailed" + ], + "title": "ResponseStreamConnectionFailedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "The response SSE stream disconnected in the middle of a turn before completion.", + "properties": { + "responseStreamDisconnected": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseStreamDisconnected" + ], + "title": "ResponseStreamDisconnectedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Reached the retry limit for responses.", + "properties": { + "responseTooManyFailedAttempts": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseTooManyFailedAttempts" + ], + "title": "ResponseTooManyFailedAttemptsCodexErrorInfo", + "type": "object" + } + ] + }, + "CollabAgentState": { + "properties": { + "message": { + "type": [ + "string", + "null" + ] + }, + "status": { + "$ref": "#/definitions/CollabAgentStatus" + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "CollabAgentStatus": { + "enum": [ + "pendingInit", + "running", + "completed", + "errored", + "shutdown", + "notFound" + ], + "type": "string" + }, + "CollabAgentTool": { + "enum": [ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent" + ], + "type": "string" + }, + "CollabAgentToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "CommandAction": { + "oneOf": [ + { + "properties": { + "command": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "read" + ], + "title": "ReadCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "name", + "path", + "type" + ], + "title": "ReadCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "listFiles" + ], + "title": "ListFilesCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "ListFilesCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "SearchCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "type": { + "enum": [ + "unknown" + ], + "title": "UnknownCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "UnknownCommandAction", + "type": "object" + } + ] + }, + "CommandExecutionStatus": { + "enum": [ + "inProgress", + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "FileUpdateChange": { + "properties": { + "diff": { + "type": "string" + }, + "kind": { + "$ref": "#/definitions/PatchChangeKind" + }, + "path": { + "type": "string" + } + }, + "required": [ + "diff", + "kind", + "path" + ], + "type": "object" + }, + "GitInfo": { + "properties": { + "branch": { + "type": [ + "string", + "null" + ] + }, + "originUrl": { + "type": [ + "string", + "null" + ] + }, + "sha": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "McpToolCallError": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "McpToolCallResult": { + "properties": { + "content": { + "items": true, + "type": "array" + }, + "structuredContent": true + }, + "required": [ + "content" + ], + "type": "object" + }, + "McpToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "MessagePhase": { + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] + }, + "PatchApplyStatus": { + "enum": [ + "inProgress", + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "PatchChangeKind": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "add" + ], + "title": "AddPatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AddPatchChangeKind", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "delete" + ], + "title": "DeletePatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DeletePatchChangeKind", + "type": "object" + }, + { + "properties": { + "move_path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "update" + ], + "title": "UpdatePatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UpdatePatchChangeKind", + "type": "object" + } + ] + }, + "SessionSource": { + "oneOf": [ + { + "enum": [ + "cli", + "vscode", + "exec", + "appServer", + "unknown" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "subAgent": { + "$ref": "#/definitions/SubAgentSource" + } + }, + "required": [ + "subAgent" + ], + "title": "SubAgentSessionSource", + "type": "object" + } + ] + }, + "SubAgentSource": { + "oneOf": [ + { + "enum": [ + "review", + "compact", + "memory_consolidation" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "thread_spawn": { + "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "depth": { + "format": "int32", + "type": "integer" + }, + "parent_thread_id": { + "$ref": "#/definitions/ThreadId" + } + }, + "required": [ + "depth", + "parent_thread_id" + ], + "type": "object" + } + }, + "required": [ + "thread_spawn" + ], + "title": "ThreadSpawnSubAgentSource", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "other": { + "type": "string" + } + }, + "required": [ + "other" + ], + "title": "OtherSubAgentSource", + "type": "object" + } + ] + }, + "TextElement": { + "properties": { + "byteRange": { + "allOf": [ + { + "$ref": "#/definitions/ByteRange" + } + ], + "description": "Byte range in the parent `text` buffer that this element occupies." + }, + "placeholder": { + "description": "Optional human-readable placeholder for the element, displayed in the UI.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "byteRange" + ], + "type": "object" + }, + "Thread": { + "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "cliVersion": { + "description": "Version of the CLI that created the thread.", + "type": "string" + }, + "createdAt": { + "description": "Unix timestamp (in seconds) when the thread was created.", + "format": "int64", + "type": "integer" + }, + "cwd": { + "description": "Working directory captured for the thread.", + "type": "string" + }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, + "gitInfo": { + "anyOf": [ + { + "$ref": "#/definitions/GitInfo" + }, + { + "type": "null" + } + ], + "description": "Optional Git metadata captured when the thread was created." + }, + "id": { + "type": "string" + }, + "modelProvider": { + "description": "Model provider used for this thread (for example, 'openai').", + "type": "string" + }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, + "path": { + "description": "[UNSTABLE] Path to the thread on disk.", + "type": [ + "string", + "null" + ] + }, + "preview": { + "description": "Usually the first user message in the thread, if available.", + "type": "string" + }, + "source": { + "allOf": [ + { + "$ref": "#/definitions/SessionSource" + } + ], + "description": "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.)." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/ThreadStatus" + } + ], + "description": "Current runtime status for the thread." + }, + "turns": { + "description": "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + "items": { + "$ref": "#/definitions/Turn" + }, + "type": "array" + }, + "updatedAt": { + "description": "Unix timestamp (in seconds) when the thread was last updated.", + "format": "int64", + "type": "integer" + } + }, + "required": [ + "cliVersion", + "createdAt", + "cwd", + "ephemeral", + "id", + "modelProvider", + "preview", + "source", + "status", + "turns", + "updatedAt" + ], + "type": "object" + }, + "ThreadActiveFlag": { + "enum": [ + "waitingOnApproval", + "waitingOnUserInput" + ], + "type": "string" + }, + "ThreadId": { + "type": "string" + }, + "ThreadItem": { + "oneOf": [ + { + "properties": { + "content": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "type": { + "enum": [ + "userMessage" + ], + "title": "UserMessageThreadItemType", + "type": "string" + } + }, + "required": [ + "content", + "id", + "type" + ], + "title": "UserMessageThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "agentMessage" + ], + "title": "AgentMessageThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "AgentMessageThreadItem", + "type": "object" + }, + { + "description": "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + "properties": { + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "plan" + ], + "title": "PlanThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "PlanThreadItem", + "type": "object" + }, + { + "properties": { + "content": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "summary": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "enum": [ + "reasoning" + ], + "title": "ReasoningThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ReasoningThreadItem", + "type": "object" + }, + { + "properties": { + "aggregatedOutput": { + "description": "The command's output, aggregated from stdout and stderr.", + "type": [ + "string", + "null" + ] + }, + "command": { + "description": "The command to be executed.", + "type": "string" + }, + "commandActions": { + "description": "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + "items": { + "$ref": "#/definitions/CommandAction" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory.", + "type": "string" + }, + "durationMs": { + "description": "The duration of the command execution in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "exitCode": { + "description": "The command's exit code.", + "format": "int32", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "processId": { + "description": "Identifier for the underlying PTY process (when available).", + "type": [ + "string", + "null" + ] + }, + "status": { + "$ref": "#/definitions/CommandExecutionStatus" + }, + "type": { + "enum": [ + "commandExecution" + ], + "title": "CommandExecutionThreadItemType", + "type": "string" + } + }, + "required": [ + "command", + "commandActions", + "cwd", + "id", + "status", + "type" + ], + "title": "CommandExecutionThreadItem", + "type": "object" + }, + { + "properties": { + "changes": { + "items": { + "$ref": "#/definitions/FileUpdateChange" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/PatchApplyStatus" + }, + "type": { + "enum": [ + "fileChange" + ], + "title": "FileChangeThreadItemType", + "type": "string" + } + }, + "required": [ + "changes", + "id", + "status", + "type" + ], + "title": "FileChangeThreadItem", + "type": "object" + }, + { + "properties": { + "arguments": true, + "durationMs": { + "description": "The duration of the MCP tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "error": { + "anyOf": [ + { + "$ref": "#/definitions/McpToolCallError" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "result": { + "anyOf": [ + { + "$ref": "#/definitions/McpToolCallResult" + }, + { + "type": "null" + } + ] + }, + "server": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/McpToolCallStatus" + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "mcpToolCall" + ], + "title": "McpToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "server", + "status", + "tool", + "type" + ], + "title": "McpToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "agentsStates": { + "additionalProperties": { + "$ref": "#/definitions/CollabAgentState" + }, + "description": "Last known status of the target agents, when available.", + "type": "object" + }, + "id": { + "description": "Unique identifier for this collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Prompt text sent as part of the collab tool call, when available.", + "type": [ + "string", + "null" + ] + }, + "receiverThreadIds": { + "description": "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + "items": { + "type": "string" + }, + "type": "array" + }, + "senderThreadId": { + "description": "Thread ID of the agent issuing the collab request.", + "type": "string" + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/CollabAgentToolCallStatus" + } + ], + "description": "Current status of the collab tool call." + }, + "tool": { + "allOf": [ + { + "$ref": "#/definitions/CollabAgentTool" + } + ], + "description": "Name of the collab tool that was invoked." + }, + "type": { + "enum": [ + "collabAgentToolCall" + ], + "title": "CollabAgentToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "agentsStates", + "id", + "receiverThreadIds", + "senderThreadId", + "status", + "tool", + "type" + ], + "title": "CollabAgentToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "action": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchAction" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "query": { + "type": "string" + }, + "type": { + "enum": [ + "webSearch" + ], + "title": "WebSearchThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "query", + "type" + ], + "title": "WebSearchThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "imageView" + ], + "title": "ImageViewThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "path", + "type" + ], + "title": "ImageViewThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "review": { + "type": "string" + }, + "type": { + "enum": [ + "enteredReviewMode" + ], + "title": "EnteredReviewModeThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "review", + "type" + ], + "title": "EnteredReviewModeThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "review": { + "type": "string" + }, + "type": { + "enum": [ + "exitedReviewMode" + ], + "title": "ExitedReviewModeThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "review", + "type" + ], + "title": "ExitedReviewModeThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "type": { + "enum": [ + "contextCompaction" + ], + "title": "ContextCompactionThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ContextCompactionThreadItem", + "type": "object" + } + ] + }, + "ThreadStatus": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "notLoaded" + ], + "title": "NotLoadedThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "NotLoadedThreadStatus", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "idle" + ], + "title": "IdleThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "IdleThreadStatus", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "systemError" + ], + "title": "SystemErrorThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SystemErrorThreadStatus", + "type": "object" + }, + { + "properties": { + "activeFlags": { + "items": { + "$ref": "#/definitions/ThreadActiveFlag" + }, + "type": "array" + }, + "type": { + "enum": [ + "active" + ], + "title": "ActiveThreadStatusType", + "type": "string" + } + }, + "required": [ + "activeFlags", + "type" + ], + "title": "ActiveThreadStatus", + "type": "object" + } + ] + }, + "Turn": { + "properties": { + "error": { + "anyOf": [ + { + "$ref": "#/definitions/TurnError" + }, + { + "type": "null" + } + ], + "description": "Only populated when the Turn's status is failed." + }, + "id": { + "type": "string" + }, + "items": { + "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "items": { + "$ref": "#/definitions/ThreadItem" + }, + "type": "array" + }, + "status": { + "$ref": "#/definitions/TurnStatus" + } + }, + "required": [ + "id", + "items", + "status" + ], + "type": "object" + }, + "TurnError": { + "properties": { + "additionalDetails": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "codexErrorInfo": { + "anyOf": [ + { + "$ref": "#/definitions/CodexErrorInfo" + }, + { + "type": "null" + } + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "TurnStatus": { + "enum": [ + "completed", + "interrupted", + "failed", + "inProgress" + ], + "type": "string" + }, + "UserInput": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "text_elements": { + "default": [], + "description": "UI-defined spans within `text` used to render or persist special elements.", + "items": { + "$ref": "#/definitions/TextElement" + }, + "type": "array" + }, + "type": { + "enum": [ + "text" + ], + "title": "TextUserInputType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "TextUserInput", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "image" + ], + "title": "ImageUserInputType", + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "type", + "url" + ], + "title": "ImageUserInput", + "type": "object" + }, + { + "properties": { + "path": { + "type": "string" + }, + "type": { + "enum": [ + "localImage" + ], + "title": "LocalImageUserInputType", + "type": "string" + } + }, + "required": [ + "path", + "type" + ], + "title": "LocalImageUserInput", + "type": "object" + }, + { + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "skill" + ], + "title": "SkillUserInputType", + "type": "string" + } + }, + "required": [ + "name", + "path", + "type" + ], + "title": "SkillUserInput", + "type": "object" + }, + { + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "mention" + ], + "title": "MentionUserInputType", + "type": "string" + } + }, + "required": [ + "name", + "path", + "type" + ], + "title": "MentionUserInput", + "type": "object" + } + ] + }, + "WebSearchAction": { + "oneOf": [ + { + "properties": { + "queries": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchWebSearchActionType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SearchWebSearchAction", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "openPage" + ], + "title": "OpenPageWebSearchActionType", + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "type" + ], + "title": "OpenPageWebSearchAction", + "type": "object" + }, + { + "properties": { + "pattern": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "findInPage" + ], + "title": "FindInPageWebSearchActionType", + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "type" + ], + "title": "FindInPageWebSearchAction", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "other" + ], + "title": "OtherWebSearchActionType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "OtherWebSearchAction", + "type": "object" + } + ] + } + }, + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadMetadataUpdateResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index f6df83b6e4..379ab414c2 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -32,6 +32,7 @@ import type { ThreadCompactStartParams } from "./v2/ThreadCompactStartParams"; import type { ThreadForkParams } from "./v2/ThreadForkParams"; import type { ThreadListParams } from "./v2/ThreadListParams"; import type { ThreadLoadedListParams } from "./v2/ThreadLoadedListParams"; +import type { ThreadMetadataUpdateParams } from "./v2/ThreadMetadataUpdateParams"; import type { ThreadReadParams } from "./v2/ThreadReadParams"; import type { ThreadResumeParams } from "./v2/ThreadResumeParams"; import type { ThreadRollbackParams } from "./v2/ThreadRollbackParams"; @@ -47,4 +48,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta /** * Request from the client to the server. */ -export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/remote/list", id: RequestId, params: SkillsRemoteReadParams, } | { "method": "skills/remote/export", id: RequestId, params: SkillsRemoteWriteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; +export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/remote/list", id: RequestId, params: SkillsRemoteReadParams, } | { "method": "skills/remote/export", id: RequestId, params: SkillsRemoteWriteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataGitInfoUpdateParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataGitInfoUpdateParams.ts new file mode 100644 index 0000000000..7424ae3606 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataGitInfoUpdateParams.ts @@ -0,0 +1,20 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ThreadMetadataGitInfoUpdateParams = { +/** + * Omit to leave the stored commit unchanged, set to `null` to clear it, + * or provide a non-empty string to replace it. + */ +sha?: string | null, +/** + * Omit to leave the stored branch unchanged, set to `null` to clear it, + * or provide a non-empty string to replace it. + */ +branch?: string | null, +/** + * Omit to leave the stored origin URL unchanged, set to `null` to clear it, + * or provide a non-empty string to replace it. + */ +originUrl?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateParams.ts new file mode 100644 index 0000000000..5b6eb8a05f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateParams.ts @@ -0,0 +1,12 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadMetadataGitInfoUpdateParams } from "./ThreadMetadataGitInfoUpdateParams"; + +export type ThreadMetadataUpdateParams = { threadId: string, +/** + * Patch the stored Git metadata for this thread. + * Omit a field to leave it unchanged, set it to `null` to clear it, or + * provide a string to replace the stored value. + */ +gitInfo?: ThreadMetadataGitInfoUpdateParams | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateResponse.ts new file mode 100644 index 0000000000..d9c09ef2d3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadMetadataUpdateResponse.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { Thread } from "./Thread"; + +export type ThreadMetadataUpdateResponse = { thread: Thread, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 757eb72893..9c677641fa 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -179,6 +179,9 @@ export type { ThreadListParams } from "./ThreadListParams"; export type { ThreadListResponse } from "./ThreadListResponse"; export type { ThreadLoadedListParams } from "./ThreadLoadedListParams"; export type { ThreadLoadedListResponse } from "./ThreadLoadedListResponse"; +export type { ThreadMetadataGitInfoUpdateParams } from "./ThreadMetadataGitInfoUpdateParams"; +export type { ThreadMetadataUpdateParams } from "./ThreadMetadataUpdateParams"; +export type { ThreadMetadataUpdateResponse } from "./ThreadMetadataUpdateResponse"; export type { ThreadNameUpdatedNotification } from "./ThreadNameUpdatedNotification"; export type { ThreadReadParams } from "./ThreadReadParams"; export type { ThreadReadResponse } from "./ThreadReadResponse"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 98efcdd290..67968507c7 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -211,6 +211,10 @@ client_request_definitions! { params: v2::ThreadSetNameParams, response: v2::ThreadSetNameResponse, }, + ThreadMetadataUpdate => "thread/metadata/update" { + params: v2::ThreadMetadataUpdateParams, + response: v2::ThreadMetadataUpdateResponse, + }, ThreadUnarchive => "thread/unarchive" { params: v2::ThreadUnarchiveParams, response: v2::ThreadUnarchiveResponse, diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 8f0b37beef..6b26433ae0 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2068,6 +2068,61 @@ pub struct ThreadUnarchiveParams { #[ts(export_to = "v2/")] pub struct ThreadSetNameResponse {} +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadMetadataUpdateParams { + pub thread_id: String, + /// Patch the stored Git metadata for this thread. + /// Omit a field to leave it unchanged, set it to `null` to clear it, or + /// provide a string to replace the stored value. + #[ts(optional = nullable)] + pub git_info: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadMetadataGitInfoUpdateParams { + /// Omit to leave the stored commit unchanged, set to `null` to clear it, + /// or provide a non-empty string to replace it. + #[serde( + default, + skip_serializing_if = "Option::is_none", + serialize_with = "super::serde_helpers::serialize_double_option", + deserialize_with = "super::serde_helpers::deserialize_double_option" + )] + #[ts(optional = nullable, type = "string | null")] + pub sha: Option>, + /// Omit to leave the stored branch unchanged, set to `null` to clear it, + /// or provide a non-empty string to replace it. + #[serde( + default, + skip_serializing_if = "Option::is_none", + serialize_with = "super::serde_helpers::serialize_double_option", + deserialize_with = "super::serde_helpers::deserialize_double_option" + )] + #[ts(optional = nullable, type = "string | null")] + pub branch: Option>, + /// Omit to leave the stored origin URL unchanged, set to `null` to clear it, + /// or provide a non-empty string to replace it. + #[serde( + default, + skip_serializing_if = "Option::is_none", + serialize_with = "super::serde_helpers::serialize_double_option", + deserialize_with = "super::serde_helpers::deserialize_double_option" + )] + #[ts(optional = nullable, type = "string | null")] + pub origin_url: Option>, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadMetadataUpdateResponse { + pub thread: Thread, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index ba2355f675..ca7f7bffb7 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -66,7 +66,6 @@ axum = { workspace = true, default-features = false, features = [ ] } base64 = { workspace = true } core_test_support = { workspace = true } -codex-state = { workspace = true } codex-utils-cargo-bin = { workspace = true } pretty_assertions = { workspace = true } rmcp = { workspace = true, default-features = false, features = [ diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 9ec4821e8d..d2d8aa5445 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -126,6 +126,7 @@ Example with notification opt-out: - `thread/list` — page through stored rollouts; supports cursor-based pagination and optional `modelProviders`, `sourceKinds`, `archived`, `cwd`, and `searchTerm` filters. Each returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded. - `thread/loaded/list` — list the thread ids currently loaded in memory. - `thread/read` — read a stored thread by id without resuming it; optionally include turns via `includeTurns`. The returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded. +- `thread/metadata/update` — patch stored thread metadata in sqlite; currently supports updating persisted `gitInfo` fields and returns the refreshed `thread`. - `thread/status/changed` — notification emitted when a loaded thread’s status changes (`threadId` + new `status`). - `thread/archive` — move a thread’s rollout file into the archived directory; returns `{}` on success and emits `thread/archived`. - `thread/unsubscribe` — unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server shuts down and unloads the thread, then emits `thread/closed`. @@ -324,6 +325,34 @@ Use `thread/read` to fetch a stored thread by id without resuming it. Pass `incl } } ``` +### Example: Update stored thread metadata + +Use `thread/metadata/update` to patch sqlite-backed metadata for a thread without resuming it. Today this supports persisted `gitInfo`; omitted fields are left unchanged, while explicit `null` clears a stored value. + +```json +{ "method": "thread/metadata/update", "id": 24, "params": { + "threadId": "thr_123", + "gitInfo": { "branch": "feature/sidebar-pr" } +} } +{ "id": 24, "result": { + "thread": { + "id": "thr_123", + "gitInfo": { "sha": null, "branch": "feature/sidebar-pr", "originUrl": null } + } +} } + +{ "method": "thread/metadata/update", "id": 25, "params": { + "threadId": "thr_123", + "gitInfo": { "branch": null } +} } +{ "id": 25, "result": { + "thread": { + "id": "thr_123", + "gitInfo": null + } +} } +``` + ### Example: Archive a thread Use `thread/archive` to move the persisted rollout (stored as a JSONL file on disk) into the archived sessions directory. diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 1c18345559..f154bff311 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -110,6 +110,9 @@ use codex_app_server_protocol::ThreadListParams; use codex_app_server_protocol::ThreadListResponse; use codex_app_server_protocol::ThreadLoadedListParams; use codex_app_server_protocol::ThreadLoadedListResponse; +use codex_app_server_protocol::ThreadMetadataGitInfoUpdateParams; +use codex_app_server_protocol::ThreadMetadataUpdateParams; +use codex_app_server_protocol::ThreadMetadataUpdateResponse; use codex_app_server_protocol::ThreadNameUpdatedNotification; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadReadResponse; @@ -201,6 +204,7 @@ use codex_core::skills::remote::export_remote_skill; use codex_core::skills::remote::list_remote_skills; use codex_core::state_db::StateDbHandle; use codex_core::state_db::get_state_db; +use codex_core::state_db::reconcile_rollout; use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_core::windows_sandbox::WindowsSandboxSetupMode as CoreWindowsSandboxSetupMode; use codex_core::windows_sandbox::WindowsSandboxSetupRequest; @@ -239,6 +243,8 @@ use codex_protocol::protocol::USER_MESSAGE_BEGIN; use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use codex_protocol::user_input::UserInput as CoreInputItem; use codex_rmcp_client::perform_oauth_login_return_url; +use codex_state::StateRuntime; +use codex_state::ThreadMetadataBuilder; use codex_state::log_db::LogDbLayer; use codex_utils_json_to_toml::json_to_toml; use std::collections::HashMap; @@ -597,6 +603,10 @@ impl CodexMessageProcessor { self.thread_set_name(to_connection_request_id(request_id), params) .await; } + ClientRequest::ThreadMetadataUpdate { request_id, params } => { + self.thread_metadata_update(to_connection_request_id(request_id), params) + .await; + } ClientRequest::ThreadUnarchive { request_id, params } => { self.thread_unarchive(to_connection_request_id(request_id), params) .await; @@ -1924,6 +1934,304 @@ impl CodexMessageProcessor { .await; } + async fn thread_metadata_update( + &self, + request_id: ConnectionRequestId, + params: ThreadMetadataUpdateParams, + ) { + let ThreadMetadataUpdateParams { + thread_id, + git_info, + } = params; + + let thread_uuid = match ThreadId::from_string(&thread_id) { + Ok(id) => id, + Err(err) => { + self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) + .await; + return; + } + }; + + let Some(ThreadMetadataGitInfoUpdateParams { + sha, + branch, + origin_url, + }) = git_info + else { + self.send_invalid_request_error( + request_id, + "gitInfo must include at least one field".to_string(), + ) + .await; + return; + }; + + if sha.is_none() && branch.is_none() && origin_url.is_none() { + self.send_invalid_request_error( + request_id, + "gitInfo must include at least one field".to_string(), + ) + .await; + return; + } + + let loaded_thread = self.thread_manager.get_thread(thread_uuid).await.ok(); + let mut state_db_ctx = loaded_thread.as_ref().and_then(|thread| thread.state_db()); + if state_db_ctx.is_none() { + state_db_ctx = get_state_db(&self.config, None).await; + } + let Some(state_db_ctx) = state_db_ctx else { + self.send_internal_error( + request_id, + format!("sqlite state db unavailable for thread {thread_uuid}"), + ) + .await; + return; + }; + + if let Err(error) = self + .ensure_thread_metadata_row_exists(thread_uuid, &state_db_ctx, loaded_thread.as_ref()) + .await + { + self.outgoing.send_error(request_id, error).await; + return; + } + + let git_sha = match sha { + Some(Some(sha)) => { + let sha = sha.trim().to_string(); + if sha.is_empty() { + self.send_invalid_request_error( + request_id, + "gitInfo.sha must not be empty".to_string(), + ) + .await; + return; + } + Some(Some(sha)) + } + Some(None) => Some(None), + None => None, + }; + let git_branch = match branch { + Some(Some(branch)) => { + let branch = branch.trim().to_string(); + if branch.is_empty() { + self.send_invalid_request_error( + request_id, + "gitInfo.branch must not be empty".to_string(), + ) + .await; + return; + } + Some(Some(branch)) + } + Some(None) => Some(None), + None => None, + }; + let git_origin_url = match origin_url { + Some(Some(origin_url)) => { + let origin_url = origin_url.trim().to_string(); + if origin_url.is_empty() { + self.send_invalid_request_error( + request_id, + "gitInfo.originUrl must not be empty".to_string(), + ) + .await; + return; + } + Some(Some(origin_url)) + } + Some(None) => Some(None), + None => None, + }; + + let updated = match state_db_ctx + .update_thread_git_info( + thread_uuid, + git_sha.as_ref().map(|value| value.as_deref()), + git_branch.as_ref().map(|value| value.as_deref()), + git_origin_url.as_ref().map(|value| value.as_deref()), + ) + .await + { + Ok(updated) => updated, + Err(err) => { + self.send_internal_error( + request_id, + format!("failed to update thread metadata for {thread_uuid}: {err}"), + ) + .await; + return; + } + }; + if !updated { + self.send_internal_error( + request_id, + format!("thread metadata disappeared before update completed: {thread_uuid}"), + ) + .await; + return; + } + + let Some(summary) = + read_summary_from_state_db_context_by_thread_id(Some(&state_db_ctx), thread_uuid).await + else { + self.send_internal_error( + request_id, + format!("failed to reload updated thread metadata for {thread_uuid}"), + ) + .await; + return; + }; + + let mut thread = summary_to_thread(summary); + self.attach_thread_name(thread_uuid, &mut thread).await; + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + false, + ); + + self.outgoing + .send_response(request_id, ThreadMetadataUpdateResponse { thread }) + .await; + } + + async fn ensure_thread_metadata_row_exists( + &self, + thread_uuid: ThreadId, + state_db_ctx: &Arc, + loaded_thread: Option<&Arc>, + ) -> Result<(), JSONRPCErrorError> { + fn invalid_request(message: String) -> JSONRPCErrorError { + JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message, + data: None, + } + } + + fn internal_error(message: String) -> JSONRPCErrorError { + JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message, + data: None, + } + } + + match state_db_ctx.get_thread(thread_uuid).await { + Ok(Some(_)) => return Ok(()), + Ok(None) => {} + Err(err) => { + return Err(internal_error(format!( + "failed to load thread metadata for {thread_uuid}: {err}" + ))); + } + } + + if let Some(thread) = loaded_thread { + let Some(rollout_path) = thread.rollout_path() else { + return Err(invalid_request(format!( + "ephemeral thread does not support metadata updates: {thread_uuid}" + ))); + }; + + reconcile_rollout( + Some(state_db_ctx), + rollout_path.as_path(), + self.config.model_provider_id.as_str(), + None, + &[], + None, + None, + ) + .await; + + match state_db_ctx.get_thread(thread_uuid).await { + Ok(Some(_)) => return Ok(()), + Ok(None) => {} + Err(err) => { + return Err(internal_error(format!( + "failed to load reconciled thread metadata for {thread_uuid}: {err}" + ))); + } + } + + let config_snapshot = thread.config_snapshot().await; + let model_provider = config_snapshot.model_provider_id.clone(); + let mut builder = ThreadMetadataBuilder::new( + thread_uuid, + rollout_path, + Utc::now(), + config_snapshot.session_source.clone(), + ); + builder.model_provider = Some(model_provider.clone()); + builder.cwd = config_snapshot.cwd.clone(); + builder.cli_version = Some(env!("CARGO_PKG_VERSION").to_string()); + builder.sandbox_policy = config_snapshot.sandbox_policy.clone(); + builder.approval_mode = config_snapshot.approval_policy; + let metadata = builder.build(model_provider.as_str()); + if let Err(err) = state_db_ctx.insert_thread_if_absent(&metadata).await { + return Err(internal_error(format!( + "failed to create thread metadata for {thread_uuid}: {err}" + ))); + } + return Ok(()); + } + + let rollout_path = + match find_thread_path_by_id_str(&self.config.codex_home, &thread_uuid.to_string()) + .await + { + Ok(Some(path)) => path, + Ok(None) => match find_archived_thread_path_by_id_str( + &self.config.codex_home, + &thread_uuid.to_string(), + ) + .await + { + Ok(Some(path)) => path, + Ok(None) => { + return Err(invalid_request(format!("thread not found: {thread_uuid}"))); + } + Err(err) => { + return Err(internal_error(format!( + "failed to locate archived thread id {thread_uuid}: {err}" + ))); + } + }, + Err(err) => { + return Err(internal_error(format!( + "failed to locate thread id {thread_uuid}: {err}" + ))); + } + }; + + reconcile_rollout( + Some(state_db_ctx), + rollout_path.as_path(), + self.config.model_provider_id.as_str(), + None, + &[], + None, + None, + ) + .await; + + match state_db_ctx.get_thread(thread_uuid).await { + Ok(Some(_)) => Ok(()), + Ok(None) => Err(internal_error(format!( + "failed to create thread metadata from rollout for {thread_uuid}" + ))), + Err(err) => Err(internal_error(format!( + "failed to load reconciled thread metadata for {thread_uuid}: {err}" + ))), + } + } + async fn thread_unarchive( &mut self, request_id: ConnectionRequestId, diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index 4b525878b8..753816b8d2 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -44,6 +44,7 @@ use codex_app_server_protocol::ThreadCompactStartParams; use codex_app_server_protocol::ThreadForkParams; use codex_app_server_protocol::ThreadListParams; use codex_app_server_protocol::ThreadLoadedListParams; +use codex_app_server_protocol::ThreadMetadataUpdateParams; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadRealtimeAppendAudioParams; use codex_app_server_protocol::ThreadRealtimeAppendTextParams; @@ -100,7 +101,7 @@ impl McpProcess { cmd.stderr(Stdio::piped()); cmd.current_dir(codex_home); cmd.env("CODEX_HOME", codex_home); - cmd.env("RUST_LOG", "debug"); + cmd.env("RUST_LOG", "info"); cmd.env_remove(CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR); for (k, v) in env_overrides { @@ -333,6 +334,15 @@ impl McpProcess { self.send_request("thread/name/set", params).await } + /// Send a `thread/metadata/update` JSON-RPC request. + pub async fn send_thread_metadata_update_request( + &mut self, + params: ThreadMetadataUpdateParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("thread/metadata/update", params).await + } + /// Send a `thread/unsubscribe` JSON-RPC request. pub async fn send_thread_unsubscribe_request( &mut self, diff --git a/codex-rs/app-server/tests/suite/fuzzy_file_search.rs b/codex-rs/app-server/tests/suite/fuzzy_file_search.rs index b6932560f0..81b965319c 100644 --- a/codex-rs/app-server/tests/suite/fuzzy_file_search.rs +++ b/codex-rs/app-server/tests/suite/fuzzy_file_search.rs @@ -434,7 +434,7 @@ async fn test_fuzzy_file_search_session_update_after_stop_fails() -> Result<()> async fn test_fuzzy_file_search_session_stops_sending_updates_after_stop() -> Result<()> { let codex_home = TempDir::new()?; let root = TempDir::new()?; - for i in 0..10_000 { + for i in 0..2_000 { let file_path = root.path().join(format!("file-{i:04}.txt")); std::fs::write(file_path, "contents")?; } diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index cb3acb633d..7b7010086a 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -24,6 +24,7 @@ mod thread_archive; mod thread_fork; mod thread_list; mod thread_loaded_list; +mod thread_metadata_update; mod thread_read; mod thread_resume; mod thread_rollback; diff --git a/codex-rs/app-server/tests/suite/v2/thread_metadata_update.rs b/codex-rs/app-server/tests/suite/v2/thread_metadata_update.rs new file mode 100644 index 0000000000..50917ee8a7 --- /dev/null +++ b/codex-rs/app-server/tests/suite/v2/thread_metadata_update.rs @@ -0,0 +1,462 @@ +use anyhow::Result; +use app_test_support::McpProcess; +use app_test_support::create_fake_rollout; +use app_test_support::create_mock_responses_server_repeating_assistant; +use app_test_support::rollout_path; +use app_test_support::to_response; +use codex_app_server_protocol::GitInfo; +use codex_app_server_protocol::JSONRPCError; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadMetadataGitInfoUpdateParams; +use codex_app_server_protocol::ThreadMetadataUpdateParams; +use codex_app_server_protocol::ThreadMetadataUpdateResponse; +use codex_app_server_protocol::ThreadReadParams; +use codex_app_server_protocol::ThreadReadResponse; +use codex_app_server_protocol::ThreadResumeParams; +use codex_app_server_protocol::ThreadResumeResponse; +use codex_app_server_protocol::ThreadStartParams; +use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::ThreadStatus; +use codex_core::ARCHIVED_SESSIONS_SUBDIR; +use codex_core::state_db::reconcile_rollout; +use codex_protocol::ThreadId; +use codex_protocol::protocol::GitInfo as RolloutGitInfo; +use codex_state::StateRuntime; +use pretty_assertions::assert_eq; +use serde_json::Value; +use std::fs; +use std::path::Path; +use std::sync::Arc; +use tempfile::TempDir; +use tokio::time::timeout; + +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +#[tokio::test] +async fn thread_metadata_update_patches_git_branch_and_returns_updated_thread() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let start_id = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let start_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(start_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(start_resp)?; + + let update_id = mcp + .send_thread_metadata_update_request(ThreadMetadataUpdateParams { + thread_id: thread.id.clone(), + git_info: Some(ThreadMetadataGitInfoUpdateParams { + sha: None, + branch: Some(Some("feature/sidebar-pr".to_string())), + origin_url: None, + }), + }) + .await?; + let update_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(update_id)), + ) + .await??; + let update_result = update_resp.result.clone(); + let ThreadMetadataUpdateResponse { thread: updated } = + to_response::(update_resp)?; + + assert_eq!(updated.id, thread.id); + assert_eq!( + updated.git_info, + Some(GitInfo { + sha: None, + branch: Some("feature/sidebar-pr".to_string()), + origin_url: None, + }) + ); + assert_eq!(updated.status, ThreadStatus::Idle); + let updated_thread_json = update_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/metadata/update result.thread must be an object"); + let updated_git_info_json = updated_thread_json + .get("gitInfo") + .and_then(Value::as_object) + .expect("thread/metadata/update must serialize `thread.gitInfo` on the wire"); + assert_eq!( + updated_git_info_json.get("branch").and_then(Value::as_str), + Some("feature/sidebar-pr") + ); + + let read_id = mcp + .send_thread_read_request(ThreadReadParams { + thread_id: thread.id, + 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: read } = to_response::(read_resp)?; + + assert_eq!( + read.git_info, + Some(GitInfo { + sha: None, + branch: Some("feature/sidebar-pr".to_string()), + origin_url: None, + }) + ); + assert_eq!(read.status, ThreadStatus::Idle); + + Ok(()) +} + +#[tokio::test] +async fn thread_metadata_update_rejects_empty_git_info_patch() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let start_id = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let start_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(start_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(start_resp)?; + + let update_id = mcp + .send_thread_metadata_update_request(ThreadMetadataUpdateParams { + thread_id: thread.id, + git_info: Some(ThreadMetadataGitInfoUpdateParams { + sha: None, + branch: None, + origin_url: None, + }), + }) + .await?; + let update_err: JSONRPCError = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(update_id)), + ) + .await??; + + assert_eq!( + update_err.error.message, + "gitInfo must include at least one field" + ); + + Ok(()) +} + +#[tokio::test] +async fn thread_metadata_update_repairs_missing_sqlite_row_for_stored_thread() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + let _state_db = init_state_db(codex_home.path()).await?; + + let preview = "Stored thread preview"; + let thread_id = create_fake_rollout( + codex_home.path(), + "2025-01-05T12-00-00", + "2025-01-05T12:00:00Z", + preview, + Some("mock_provider"), + None, + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let update_id = mcp + .send_thread_metadata_update_request(ThreadMetadataUpdateParams { + thread_id: thread_id.clone(), + git_info: Some(ThreadMetadataGitInfoUpdateParams { + sha: None, + branch: Some(Some("feature/stored-thread".to_string())), + origin_url: None, + }), + }) + .await?; + let update_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(update_id)), + ) + .await??; + let ThreadMetadataUpdateResponse { thread: updated } = + to_response::(update_resp)?; + + assert_eq!(updated.id, thread_id); + assert_eq!(updated.preview, preview); + assert_eq!(updated.created_at, 1736078400); + assert_eq!( + updated.git_info, + Some(GitInfo { + sha: None, + branch: Some("feature/stored-thread".to_string()), + origin_url: None, + }) + ); + + Ok(()) +} + +#[tokio::test] +async fn thread_metadata_update_repairs_loaded_thread_without_resetting_summary() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + let state_db = init_state_db(codex_home.path()).await?; + + let preview = "Loaded thread preview"; + let thread_id = create_fake_rollout( + codex_home.path(), + "2025-01-06T08-30-00", + "2025-01-06T08:30:00Z", + preview, + Some("mock_provider"), + None, + )?; + let thread_uuid = ThreadId::from_string(&thread_id)?; + let rollout_path = rollout_path(codex_home.path(), "2025-01-06T08-30-00", &thread_id); + reconcile_rollout( + Some(&state_db), + rollout_path.as_path(), + "mock_provider", + None, + &[], + None, + None, + ) + .await; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let resume_id = mcp + .send_thread_resume_request(ThreadResumeParams { + thread_id: thread_id.clone(), + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let _: ThreadResumeResponse = to_response::(resume_resp)?; + + assert_eq!(state_db.delete_thread(thread_uuid).await?, 1); + + let update_id = mcp + .send_thread_metadata_update_request(ThreadMetadataUpdateParams { + thread_id: thread_id.clone(), + git_info: Some(ThreadMetadataGitInfoUpdateParams { + sha: None, + branch: Some(Some("feature/loaded-thread".to_string())), + origin_url: None, + }), + }) + .await?; + let update_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(update_id)), + ) + .await??; + let ThreadMetadataUpdateResponse { thread: updated } = + to_response::(update_resp)?; + + assert_eq!(updated.id, thread_id); + assert_eq!(updated.preview, preview); + assert_eq!(updated.created_at, 1736152200); + assert_eq!( + updated.git_info, + Some(GitInfo { + sha: None, + branch: Some("feature/loaded-thread".to_string()), + origin_url: None, + }) + ); + + Ok(()) +} + +#[tokio::test] +async fn thread_metadata_update_repairs_missing_sqlite_row_for_archived_thread() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + let _state_db = init_state_db(codex_home.path()).await?; + + let preview = "Archived thread preview"; + let thread_id = create_fake_rollout( + codex_home.path(), + "2025-01-06T08-30-00", + "2025-01-06T08:30:00Z", + preview, + Some("mock_provider"), + None, + )?; + + let archived_dir = codex_home.path().join(ARCHIVED_SESSIONS_SUBDIR); + fs::create_dir_all(&archived_dir)?; + let archived_source = rollout_path(codex_home.path(), "2025-01-06T08-30-00", &thread_id); + let archived_dest = archived_dir.join( + archived_source + .file_name() + .expect("archived rollout should have a file name"), + ); + fs::rename(&archived_source, &archived_dest)?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let update_id = mcp + .send_thread_metadata_update_request(ThreadMetadataUpdateParams { + thread_id: thread_id.clone(), + git_info: Some(ThreadMetadataGitInfoUpdateParams { + sha: None, + branch: Some(Some("feature/archived-thread".to_string())), + origin_url: None, + }), + }) + .await?; + let update_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(update_id)), + ) + .await??; + let ThreadMetadataUpdateResponse { thread: updated } = + to_response::(update_resp)?; + + assert_eq!(updated.id, thread_id); + assert_eq!(updated.preview, preview); + assert_eq!(updated.created_at, 1736152200); + assert_eq!( + updated.git_info, + Some(GitInfo { + sha: None, + branch: Some("feature/archived-thread".to_string()), + origin_url: None, + }) + ); + + Ok(()) +} + +#[tokio::test] +async fn thread_metadata_update_can_clear_stored_git_fields() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let thread_id = create_fake_rollout( + codex_home.path(), + "2025-01-07T09-15-00", + "2025-01-07T09:15:00Z", + "Thread preview", + Some("mock_provider"), + Some(RolloutGitInfo { + commit_hash: Some("abc123".to_string()), + branch: Some("feature/sidebar-pr".to_string()), + repository_url: Some("git@example.com:openai/codex.git".to_string()), + }), + )?; + let _state_db = init_state_db(codex_home.path()).await?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let update_id = mcp + .send_thread_metadata_update_request(ThreadMetadataUpdateParams { + thread_id: thread_id.clone(), + git_info: Some(ThreadMetadataGitInfoUpdateParams { + sha: Some(None), + branch: Some(None), + origin_url: Some(None), + }), + }) + .await?; + let update_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(update_id)), + ) + .await??; + let ThreadMetadataUpdateResponse { thread: updated } = + to_response::(update_resp)?; + + assert_eq!(updated.id, thread_id.clone()); + assert_eq!(updated.git_info, None); + + let read_id = mcp + .send_thread_read_request(ThreadReadParams { + thread_id, + 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: read } = to_response::(read_resp)?; + + assert_eq!(read.git_info, None); + + Ok(()) +} + +async fn init_state_db(codex_home: &Path) -> Result> { + let state_db = + StateRuntime::init(codex_home.to_path_buf(), "mock_provider".into(), None).await?; + state_db.mark_backfill_complete(None).await?; + Ok(state_db) +} + +fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { + let config_toml = codex_home.join("config.toml"); + std::fs::write( + config_toml, + format!( + r#" +model = "mock-model" +approval_policy = "never" +sandbox_mode = "read-only" + +model_provider = "mock_provider" +suppress_unstable_features_warning = true + +[features] +sqlite = true + +[model_providers.mock_provider] +name = "Mock provider for test" +base_url = "{server_uri}/v1" +wire_api = "responses" +request_max_retries = 0 +stream_max_retries = 0 +"# + ), + ) +} diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 0888d0f23e..15b309ddf4 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -62,7 +62,7 @@ use tempfile::TempDir; use tokio::time::timeout; #[cfg(windows)] -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); #[cfg(not(windows))] const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const TEST_ORIGINATOR: &str = "codex_vscode"; diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs index 0bee69b6aa..66ca9248eb 100644 --- a/codex-rs/core/src/rollout/metadata.rs +++ b/codex-rs/core/src/rollout/metadata.rs @@ -282,6 +282,9 @@ pub(crate) async fn backfill_sessions( let mut metadata = outcome.metadata; metadata.cwd = normalize_cwd_for_state_db(&metadata.cwd); let memory_mode = outcome.memory_mode.unwrap_or_else(|| "enabled".to_string()); + if let Ok(Some(existing_metadata)) = runtime.get_thread(metadata.id).await { + metadata.prefer_existing_git_info(&existing_metadata); + } if rollout.archived && metadata.archived_at.is_none() { let fallback_archived_at = metadata.updated_at; metadata.archived_at = file_modified_time_utc(&rollout.path) @@ -503,6 +506,7 @@ mod tests { use chrono::Utc; use codex_protocol::ThreadId; use codex_protocol::protocol::CompactedItem; + use codex_protocol::protocol::GitInfo; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionMeta; @@ -669,12 +673,14 @@ mod tests { "2026-01-27T12-34-56", "2026-01-27T12:34:56Z", first_uuid, + None, ); let second_path = write_rollout_in_sessions( codex_home.as_path(), "2026-01-27T12-35-56", "2026-01-27T12:35:56Z", second_uuid, + None, ); let runtime = @@ -730,6 +736,58 @@ mod tests { assert!(state.last_success_at.is_some()); } + #[tokio::test] + async fn backfill_sessions_preserves_existing_git_branch_and_fills_missing_git_fields() { + let dir = tempdir().expect("tempdir"); + let codex_home = dir.path().to_path_buf(); + let thread_uuid = Uuid::new_v4(); + let rollout_path = write_rollout_in_sessions( + codex_home.as_path(), + "2026-01-27T12-34-56", + "2026-01-27T12:34:56Z", + thread_uuid, + Some(GitInfo { + commit_hash: Some("rollout-sha".to_string()), + branch: Some("rollout-branch".to_string()), + repository_url: Some("git@example.com:openai/codex.git".to_string()), + }), + ); + + let runtime = + codex_state::StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let thread_id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id"); + let mut existing = extract_metadata_from_rollout(&rollout_path, "test-provider", None) + .await + .expect("extract") + .metadata; + existing.git_sha = None; + existing.git_branch = Some("sqlite-branch".to_string()); + existing.git_origin_url = None; + runtime + .upsert_thread(&existing) + .await + .expect("existing metadata upsert"); + + let mut config = crate::config::test_config(); + config.codex_home = codex_home.clone(); + config.model_provider_id = "test-provider".to_string(); + backfill_sessions(runtime.as_ref(), &config, None).await; + + let persisted = runtime + .get_thread(thread_id) + .await + .expect("get thread") + .expect("thread exists"); + assert_eq!(persisted.git_sha.as_deref(), Some("rollout-sha")); + assert_eq!(persisted.git_branch.as_deref(), Some("sqlite-branch")); + assert_eq!( + persisted.git_origin_url.as_deref(), + Some("git@example.com:openai/codex.git") + ); + } + #[tokio::test] async fn backfill_sessions_normalizes_cwd_before_upsert() { let dir = tempdir().expect("tempdir"); @@ -742,6 +800,7 @@ mod tests { "2026-01-27T12:34:56Z", thread_uuid, session_cwd.clone(), + None, ); let runtime = @@ -770,6 +829,7 @@ mod tests { filename_ts: &str, event_ts: &str, thread_uuid: Uuid, + git: Option, ) -> PathBuf { write_rollout_in_sessions_with_cwd( codex_home, @@ -777,6 +837,7 @@ mod tests { event_ts, thread_uuid, codex_home.to_path_buf(), + git, ) } @@ -786,6 +847,7 @@ mod tests { event_ts: &str, thread_uuid: Uuid, cwd: PathBuf, + git: Option, ) -> PathBuf { let id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id"); let sessions_dir = codex_home.join("sessions"); @@ -808,7 +870,7 @@ mod tests { }; let session_meta_line = SessionMetaLine { meta: session_meta, - git: None, + git, }; let rollout_line = RolloutLine { timestamp: event_ts.to_string(), diff --git a/codex-rs/core/src/state_db.rs b/codex-rs/core/src/state_db.rs index 43641402fe..953c7a8e12 100644 --- a/codex-rs/core/src/state_db.rs +++ b/codex-rs/core/src/state_db.rs @@ -390,6 +390,9 @@ pub async fn reconcile_rollout( let mut metadata = outcome.metadata; let memory_mode = outcome.memory_mode.unwrap_or_else(|| "enabled".to_string()); metadata.cwd = normalize_cwd_for_state_db(&metadata.cwd); + if let Ok(Some(existing_metadata)) = ctx.get_thread(metadata.id).await { + metadata.prefer_existing_git_info(&existing_metadata); + } match archived_only { Some(true) if metadata.archived_at.is_none() => { metadata.archived_at = Some(metadata.updated_at); diff --git a/codex-rs/state/src/model/thread_metadata.rs b/codex-rs/state/src/model/thread_metadata.rs index 9616268012..c4362a8df2 100644 --- a/codex-rs/state/src/model/thread_metadata.rs +++ b/codex-rs/state/src/model/thread_metadata.rs @@ -197,6 +197,19 @@ impl ThreadMetadataBuilder { } impl ThreadMetadata { + /// Preserve existing non-null Git fields when rollout-derived metadata is reconciled. + pub fn prefer_existing_git_info(&mut self, existing: &Self) { + if existing.git_sha.is_some() { + self.git_sha = existing.git_sha.clone(); + } + if existing.git_branch.is_some() { + self.git_branch = existing.git_branch.clone(); + } + if existing.git_origin_url.is_some() { + self.git_origin_url = existing.git_origin_url.clone(); + } + } + /// Return the list of field names that differ between `self` and `other`. pub fn diff_fields(&self, other: &Self) -> Vec<&'static str> { let mut diffs = Vec::new(); diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rs index f9e939a4a1..2a1f44e1e9 100644 --- a/codex-rs/state/src/runtime/threads.rs +++ b/codex-rs/state/src/runtime/threads.rs @@ -207,6 +207,64 @@ FROM threads .await } + pub async fn insert_thread_if_absent( + &self, + metadata: &crate::ThreadMetadata, + ) -> anyhow::Result { + let result = sqlx::query( + r#" +INSERT INTO threads ( + id, + rollout_path, + created_at, + updated_at, + source, + agent_nickname, + agent_role, + model_provider, + cwd, + cli_version, + title, + sandbox_policy, + approval_mode, + tokens_used, + first_user_message, + archived, + archived_at, + git_sha, + git_branch, + git_origin_url, + memory_mode +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +ON CONFLICT(id) DO NOTHING + "#, + ) + .bind(metadata.id.to_string()) + .bind(metadata.rollout_path.display().to_string()) + .bind(datetime_to_epoch_seconds(metadata.created_at)) + .bind(datetime_to_epoch_seconds(metadata.updated_at)) + .bind(metadata.source.as_str()) + .bind(metadata.agent_nickname.as_deref()) + .bind(metadata.agent_role.as_deref()) + .bind(metadata.model_provider.as_str()) + .bind(metadata.cwd.display().to_string()) + .bind(metadata.cli_version.as_str()) + .bind(metadata.title.as_str()) + .bind(metadata.sandbox_policy.as_str()) + .bind(metadata.approval_mode.as_str()) + .bind(metadata.tokens_used) + .bind(metadata.first_user_message.as_deref().unwrap_or_default()) + .bind(metadata.archived_at.is_some()) + .bind(metadata.archived_at.map(datetime_to_epoch_seconds)) + .bind(metadata.git_sha.as_deref()) + .bind(metadata.git_branch.as_deref()) + .bind(metadata.git_origin_url.as_deref()) + .bind("enabled") + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + pub async fn set_thread_memory_mode( &self, thread_id: ThreadId, @@ -220,6 +278,35 @@ FROM threads Ok(result.rows_affected() > 0) } + pub async fn update_thread_git_info( + &self, + thread_id: ThreadId, + git_sha: Option>, + git_branch: Option>, + git_origin_url: Option>, + ) -> anyhow::Result { + let result = sqlx::query( + r#" +UPDATE threads +SET + git_sha = CASE WHEN ? THEN ? ELSE git_sha END, + git_branch = CASE WHEN ? THEN ? ELSE git_branch END, + git_origin_url = CASE WHEN ? THEN ? ELSE git_origin_url END +WHERE id = ? + "#, + ) + .bind(git_sha.is_some()) + .bind(git_sha.flatten()) + .bind(git_branch.is_some()) + .bind(git_branch.flatten()) + .bind(git_origin_url.is_some()) + .bind(git_origin_url.flatten()) + .bind(thread_id.to_string()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + async fn upsert_thread_with_creation_memory_mode( &self, metadata: &crate::ThreadMetadata, @@ -361,6 +448,9 @@ ON CONFLICT(thread_id, position) DO NOTHING for item in items { apply_rollout_item(&mut metadata, item, &self.default_provider); } + if let Some(existing_metadata) = existing_metadata.as_ref() { + metadata.prefer_existing_git_info(existing_metadata); + } if let Some(updated_at) = file_modified_time_utc(builder.rollout_path.as_path()).await { metadata.updated_at = updated_at; } @@ -559,6 +649,7 @@ mod tests { use super::*; use crate::runtime::test_support::test_thread_metadata; use crate::runtime::test_support::unique_temp_dir; + use codex_protocol::protocol::GitInfo; use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; @@ -654,4 +745,206 @@ mod tests { .expect("memory mode should load"); assert_eq!(memory_mode.as_deref(), Some("polluted")); } + + #[tokio::test] + async fn apply_rollout_items_preserves_existing_git_branch_and_fills_missing_git_fields() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("state db should initialize"); + let thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000457").expect("valid thread id"); + let mut metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone()); + metadata.git_branch = Some("sqlite-branch".to_string()); + + runtime + .upsert_thread(&metadata) + .await + .expect("initial upsert should succeed"); + + let created_at = metadata.created_at.to_rfc3339(); + let builder = ThreadMetadataBuilder::new( + thread_id, + metadata.rollout_path.clone(), + metadata.created_at, + SessionSource::Cli, + ); + let items = vec![RolloutItem::SessionMeta(SessionMetaLine { + meta: SessionMeta { + id: thread_id, + forked_from_id: None, + timestamp: created_at, + cwd: PathBuf::new(), + originator: String::new(), + cli_version: String::new(), + source: SessionSource::Cli, + agent_nickname: None, + agent_role: None, + model_provider: None, + base_instructions: None, + dynamic_tools: None, + memory_mode: None, + }, + git: Some(GitInfo { + commit_hash: Some("rollout-sha".to_string()), + branch: Some("rollout-branch".to_string()), + repository_url: Some("git@example.com:openai/codex.git".to_string()), + }), + })]; + + runtime + .apply_rollout_items(&builder, &items, None, None) + .await + .expect("apply_rollout_items should succeed"); + + let persisted = runtime + .get_thread(thread_id) + .await + .expect("thread should load") + .expect("thread should exist"); + assert_eq!(persisted.git_sha.as_deref(), Some("rollout-sha")); + assert_eq!(persisted.git_branch.as_deref(), Some("sqlite-branch")); + assert_eq!( + persisted.git_origin_url.as_deref(), + Some("git@example.com:openai/codex.git") + ); + } + + #[tokio::test] + async fn update_thread_git_info_preserves_newer_non_git_metadata() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("state db should initialize"); + let thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000789").expect("valid thread id"); + let metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone()); + + runtime + .upsert_thread(&metadata) + .await + .expect("initial upsert should succeed"); + + let updated_at = datetime_to_epoch_seconds( + DateTime::::from_timestamp(1_700_000_100, 0).expect("timestamp"), + ); + sqlx::query( + "UPDATE threads SET updated_at = ?, tokens_used = ?, first_user_message = ? WHERE id = ?", + ) + .bind(updated_at) + .bind(123_i64) + .bind("newer preview") + .bind(thread_id.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("concurrent metadata write should succeed"); + + let updated = runtime + .update_thread_git_info( + thread_id, + Some(Some("abc123")), + Some(Some("feature/branch")), + Some(Some("git@example.com:openai/codex.git")), + ) + .await + .expect("git info update should succeed"); + assert!(updated, "git info update should touch the thread row"); + + let persisted = runtime + .get_thread(thread_id) + .await + .expect("thread should load") + .expect("thread should exist"); + assert_eq!(persisted.tokens_used, 123); + assert_eq!( + persisted.first_user_message.as_deref(), + Some("newer preview") + ); + assert_eq!(datetime_to_epoch_seconds(persisted.updated_at), updated_at); + assert_eq!(persisted.git_sha.as_deref(), Some("abc123")); + assert_eq!(persisted.git_branch.as_deref(), Some("feature/branch")); + assert_eq!( + persisted.git_origin_url.as_deref(), + Some("git@example.com:openai/codex.git") + ); + } + + #[tokio::test] + async fn insert_thread_if_absent_preserves_existing_metadata() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("state db should initialize"); + let thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000791").expect("valid thread id"); + + let mut existing = test_thread_metadata(&codex_home, thread_id, codex_home.clone()); + existing.tokens_used = 123; + existing.first_user_message = Some("newer preview".to_string()); + existing.updated_at = DateTime::::from_timestamp(1_700_000_100, 0).expect("timestamp"); + runtime + .upsert_thread(&existing) + .await + .expect("initial upsert should succeed"); + + let mut fallback = test_thread_metadata(&codex_home, thread_id, codex_home.clone()); + fallback.tokens_used = 0; + fallback.first_user_message = None; + fallback.updated_at = DateTime::::from_timestamp(1_700_000_000, 0).expect("timestamp"); + + let inserted = runtime + .insert_thread_if_absent(&fallback) + .await + .expect("insert should succeed"); + assert!(!inserted, "existing rows should not be overwritten"); + + let persisted = runtime + .get_thread(thread_id) + .await + .expect("thread should load") + .expect("thread should exist"); + assert_eq!(persisted.tokens_used, 123); + assert_eq!( + persisted.first_user_message.as_deref(), + Some("newer preview") + ); + assert_eq!( + datetime_to_epoch_seconds(persisted.updated_at), + datetime_to_epoch_seconds(existing.updated_at) + ); + } + + #[tokio::test] + async fn update_thread_git_info_can_clear_fields() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("state db should initialize"); + let thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000790").expect("valid thread id"); + let mut metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone()); + metadata.git_sha = Some("abc123".to_string()); + metadata.git_branch = Some("feature/branch".to_string()); + metadata.git_origin_url = Some("git@example.com:openai/codex.git".to_string()); + + runtime + .upsert_thread(&metadata) + .await + .expect("initial upsert should succeed"); + + let updated = runtime + .update_thread_git_info(thread_id, Some(None), Some(None), Some(None)) + .await + .expect("git info clear should succeed"); + assert!(updated, "git info clear should touch the thread row"); + + let persisted = runtime + .get_thread(thread_id) + .await + .expect("thread should load") + .expect("thread should exist"); + assert_eq!(persisted.git_sha, None); + assert_eq!(persisted.git_branch, None); + assert_eq!(persisted.git_origin_url, None); + } } From b92146d48b66798fc70f58952a68efc0f26b01e5 Mon Sep 17 00:00:00 2001 From: Curtis 'Fjord' Hawthorne Date: Tue, 3 Mar 2026 15:56:54 -0800 Subject: [PATCH 350/385] Add under-development original-resolution view_image support (#13050) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Add original-resolution support for `view_image` behind the under-development `view_image_original_resolution` feature flag. When the flag is enabled and the target model is `gpt-5.3-codex` or newer, `view_image` now preserves original PNG/JPEG/WebP bytes and sends `detail: "original"` to the Responses API instead of using the legacy resize/compress path. ## What changed - Added `view_image_original_resolution` as an under-development feature flag. - Added `ImageDetail` to the protocol models and support for serializing `detail: "original"` on tool-returned images. - Added `PromptImageMode::Original` to `codex-utils-image`. - Preserves original PNG/JPEG/WebP bytes. - Keeps legacy behavior for the resize path. - Updated `view_image` to: - use the shared `local_image_content_items_with_label_number(...)` helper in both code paths - select original-resolution mode only when: - the feature flag is enabled, and - the model slug parses as `gpt-5.3-codex` or newer - Kept local user image attachments on the existing resize path; this change is specific to `view_image`. - Updated history/image accounting so only `detail: "original"` images use the docs-based GPT-5 image cost calculation; legacy images still use the old fixed estimate. - Added JS REPL guidance, gated on the same feature flag, to prefer JPEG at 85% quality unless lossless is required, while still allowing other formats when explicitly requested. - Updated tests and helper code that construct `FunctionCallOutputContentItem::InputImage` to carry the new `detail` field. ## Behavior ### Feature off - `view_image` keeps the existing resize/re-encode behavior. - History estimation keeps the existing fixed-cost heuristic. ### Feature on + `gpt-5.3-codex+` - `view_image` sends original-resolution images with `detail: "original"`. - PNG/JPEG/WebP source bytes are preserved when possible. - History estimation uses the GPT-5 docs-based image-cost calculation for those `detail: "original"` images. #### [git stack](https://github.com/magus/git-stack-cli) - 👉 `1` https://github.com/openai/codex/pull/13050 - ⏳ `2` https://github.com/openai/codex/pull/13331 - ⏳ `3` https://github.com/openai/codex/pull/13049 --- codex-rs/Cargo.lock | 2 + .../schema/json/ClientRequest.json | 19 ++ .../schema/json/EventMsg.json | 19 ++ .../codex_app_server_protocol.schemas.json | 19 ++ .../codex_app_server_protocol.v2.schemas.json | 19 ++ .../RawResponseItemCompletedNotification.json | 19 ++ .../schema/json/v2/ThreadResumeParams.json | 19 ++ .../FunctionCallOutputContentItem.ts | 3 +- .../schema/typescript/ImageDetail.ts | 5 + .../schema/typescript/index.ts | 1 + .../app-server/tests/common/models_cache.rs | 1 + .../tests/suite/v2/dynamic_tools.rs | 5 +- codex-rs/codex-api/src/endpoint/models.rs | 1 + .../codex-api/tests/models_integration.rs | 1 + codex-rs/core/Cargo.toml | 6 +- codex-rs/core/config.schema.json | 6 + codex-rs/core/models.json | 12 ++ codex-rs/core/src/client.rs | 1 + codex-rs/core/src/context_manager/history.rs | 98 +++++++-- .../core/src/context_manager/history_tests.rs | 98 ++++++++- codex-rs/core/src/features.rs | 8 + codex-rs/core/src/models_manager/manager.rs | 22 +- .../core/src/models_manager/model_info.rs | 1 + codex-rs/core/src/project_doc.rs | 18 ++ codex-rs/core/src/tools/context.rs | 2 + .../core/src/tools/handlers/view_image.rs | 24 ++- codex-rs/core/src/tools/js_repl/mod.rs | 7 +- codex-rs/core/src/truncate.rs | 7 +- codex-rs/core/tests/suite/model_switching.rs | 2 + codex-rs/core/tests/suite/models_cache_ttl.rs | 1 + codex-rs/core/tests/suite/personality.rs | 2 + codex-rs/core/tests/suite/remote_models.rs | 3 + codex-rs/core/tests/suite/rmcp_client.rs | 1 + codex-rs/core/tests/suite/view_image.rs | 203 ++++++++++++++++++ codex-rs/protocol/src/models.rs | 51 ++++- codex-rs/protocol/src/openai_models.rs | 4 + codex-rs/utils/image/src/lib.rs | 191 +++++++++++----- 37 files changed, 794 insertions(+), 107 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/ImageDetail.ts diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index d9ee0f608b..b0c1e38429 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1820,8 +1820,10 @@ dependencies = [ "codex-state", "codex-test-macros", "codex-utils-absolute-path", + "codex-utils-cache", "codex-utils-cargo-bin", "codex-utils-home-dir", + "codex-utils-image", "codex-utils-pty", "codex-utils-readiness", "codex-utils-stream-parser", diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 40745ce666..84ee3d5c1f 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -514,6 +514,16 @@ }, { "properties": { + "detail": { + "anyOf": [ + { + "$ref": "#/definitions/ImageDetail" + }, + { + "type": "null" + } + ] + }, "image_url": { "type": "string" }, @@ -627,6 +637,15 @@ ], "type": "string" }, + "ImageDetail": { + "enum": [ + "auto", + "low", + "high", + "original" + ], + "type": "string" + }, "InitializeCapabilities": { "description": "Client-declared capabilities negotiated during initialize.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index 4258bf7c2c..85de9c0dab 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -3478,6 +3478,16 @@ }, { "properties": { + "detail": { + "anyOf": [ + { + "$ref": "#/definitions/ImageDetail" + }, + { + "type": "null" + } + ] + }, "image_url": { "type": "string" }, @@ -3569,6 +3579,15 @@ ], "type": "object" }, + "ImageDetail": { + "enum": [ + "auto", + "low", + "high", + "original" + ], + "type": "string" + }, "LocalShellAction": { "oneOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 4695d2a810..a60e6c4a44 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -9700,6 +9700,16 @@ }, { "properties": { + "detail": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ImageDetail" + }, + { + "type": "null" + } + ] + }, "image_url": { "type": "string" }, @@ -9865,6 +9875,15 @@ ], "type": "string" }, + "ImageDetail": { + "enum": [ + "auto", + "low", + "high", + "original" + ], + "type": "string" + }, "InputModality": { "description": "Canonical user-input modality tags advertised by a model.", "oneOf": [ diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index e1f4c85d13..b4a5f9f6cb 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -6542,6 +6542,16 @@ }, { "properties": { + "detail": { + "anyOf": [ + { + "$ref": "#/definitions/ImageDetail" + }, + { + "type": "null" + } + ] + }, "image_url": { "type": "string" }, @@ -6828,6 +6838,15 @@ ], "type": "object" }, + "ImageDetail": { + "enum": [ + "auto", + "low", + "high", + "original" + ], + "type": "string" + }, "InitializeCapabilities": { "description": "Client-declared capabilities negotiated during initialize.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json index 4717ff266b..cedfdb19c4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json @@ -103,6 +103,16 @@ }, { "properties": { + "detail": { + "anyOf": [ + { + "$ref": "#/definitions/ImageDetail" + }, + { + "type": "null" + } + ] + }, "image_url": { "type": "string" }, @@ -173,6 +183,15 @@ ], "type": "object" }, + "ImageDetail": { + "enum": [ + "auto", + "low", + "high", + "original" + ], + "type": "string" + }, "LocalShellAction": { "oneOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json index 353bda693d..91850f60e5 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -145,6 +145,16 @@ }, { "properties": { + "detail": { + "anyOf": [ + { + "$ref": "#/definitions/ImageDetail" + }, + { + "type": "null" + } + ] + }, "image_url": { "type": "string" }, @@ -215,6 +225,15 @@ ], "type": "object" }, + "ImageDetail": { + "enum": [ + "auto", + "low", + "high", + "original" + ], + "type": "string" + }, "LocalShellAction": { "oneOf": [ { diff --git a/codex-rs/app-server-protocol/schema/typescript/FunctionCallOutputContentItem.ts b/codex-rs/app-server-protocol/schema/typescript/FunctionCallOutputContentItem.ts index 8bfb6993d0..fb2996f1e5 100644 --- a/codex-rs/app-server-protocol/schema/typescript/FunctionCallOutputContentItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/FunctionCallOutputContentItem.ts @@ -1,9 +1,10 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ImageDetail } from "./ImageDetail"; /** * Responses API compatible content items that can be returned by a tool call. * This is a subset of ContentItem with the types we support as function call outputs. */ -export type FunctionCallOutputContentItem = { "type": "input_text", text: string, } | { "type": "input_image", image_url: string, }; +export type FunctionCallOutputContentItem = { "type": "input_text", text: string, } | { "type": "input_image", image_url: string, detail?: ImageDetail, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ImageDetail.ts b/codex-rs/app-server-protocol/schema/typescript/ImageDetail.ts new file mode 100644 index 0000000000..a48f07c088 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/ImageDetail.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ImageDetail = "auto" | "low" | "high" | "original"; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index adaeb4c26c..228998cddb 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -83,6 +83,7 @@ export type { GitDiffToRemoteParams } from "./GitDiffToRemoteParams"; export type { GitDiffToRemoteResponse } from "./GitDiffToRemoteResponse"; export type { GitSha } from "./GitSha"; export type { HistoryEntry } from "./HistoryEntry"; +export type { ImageDetail } from "./ImageDetail"; export type { InitializeCapabilities } from "./InitializeCapabilities"; export type { InitializeParams } from "./InitializeParams"; export type { InitializeResponse } from "./InitializeResponse"; diff --git a/codex-rs/app-server/tests/common/models_cache.rs b/codex-rs/app-server/tests/common/models_cache.rs index 0de8fda5f2..0c2a2e5857 100644 --- a/codex-rs/app-server/tests/common/models_cache.rs +++ b/codex-rs/app-server/tests/common/models_cache.rs @@ -38,6 +38,7 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo { apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs b/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs index 52a597f66b..f3945c2b4d 100644 --- a/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs +++ b/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs @@ -399,7 +399,10 @@ async fn dynamic_tool_call_round_trip_sends_content_items_to_model() -> Result<( FunctionCallOutputContentItem::InputText { text } } DynamicToolCallOutputContentItem::InputImage { image_url } => { - FunctionCallOutputContentItem::InputImage { image_url } + FunctionCallOutputContentItem::InputImage { + image_url, + detail: None, + } } }) .collect::>(); diff --git a/codex-rs/codex-api/src/endpoint/models.rs b/codex-rs/codex-api/src/endpoint/models.rs index 5d1c5fb12e..ab90fc438f 100644 --- a/codex-rs/codex-api/src/endpoint/models.rs +++ b/codex-rs/codex-api/src/endpoint/models.rs @@ -208,6 +208,7 @@ mod tests { "apply_patch_tool_type": null, "truncation_policy": {"mode": "bytes", "limit": 10_000}, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272_000, "experimental_supported_tools": [], })) diff --git a/codex-rs/codex-api/tests/models_integration.rs b/codex-rs/codex-api/tests/models_integration.rs index 2b61f0de60..3d9133700c 100644 --- a/codex-rs/codex-api/tests/models_integration.rs +++ b/codex-rs/codex-api/tests/models_integration.rs @@ -86,6 +86,7 @@ async fn models_client_hits_models_endpoint() { apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index c3a37bb989..eafedc9d73 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -48,6 +48,8 @@ codex-protocol = { workspace = true } codex-rmcp-client = { workspace = true } codex-state = { workspace = true } codex-utils-absolute-path = { workspace = true } +codex-utils-cache = { workspace = true } +codex-utils-image = { workspace = true } codex-utils-home-dir = { workspace = true } codex-utils-pty = { workspace = true } codex-utils-readiness = { workspace = true } @@ -64,6 +66,7 @@ eventsource-stream = { workspace = true } futures = { workspace = true } http = { workspace = true } iana-time-zone = { workspace = true } +image = { workspace = true, features = ["jpeg", "png", "webp"] } indexmap = { workspace = true } keyring = { workspace = true, features = ["crypto-rust"] } libc = { workspace = true } @@ -88,7 +91,6 @@ sha2 = { workspace = true } shlex = { workspace = true } similar = { workspace = true } tempfile = { workspace = true } -test-case = "3.3.1" test-log = { workspace = true } thiserror = { workspace = true } time = { workspace = true, features = [ @@ -157,11 +159,11 @@ codex-test-macros = { workspace = true } codex-utils-cargo-bin = { workspace = true } core_test_support = { workspace = true } ctor = { workspace = true } -image = { workspace = true, features = ["jpeg", "png"] } insta = { workspace = true } maplit = { workspace = true } predicates = { workspace = true } pretty_assertions = { workspace = true } +test-case = "3.3.1" opentelemetry_sdk = { workspace = true, features = [ "experimental_metrics_custom_reader", "metrics", diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 74af6d50c6..749f6de23b 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -355,6 +355,9 @@ "fast_mode": { "type": "boolean" }, + "image_detail_original": { + "type": "boolean" + }, "include_apply_patch_tool": { "type": "boolean" }, @@ -1739,6 +1742,9 @@ "fast_mode": { "type": "boolean" }, + "image_detail_original": { + "type": "boolean" + }, "include_apply_patch_tool": { "type": "boolean" }, diff --git a/codex-rs/core/models.json b/codex-rs/core/models.json index 2fd55b9869..04660bf46a 100644 --- a/codex-rs/core/models.json +++ b/codex-rs/core/models.json @@ -15,6 +15,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": true, + "supports_image_detail_original": true, "context_window": 272000, "reasoning_summary_format": "experimental", "slug": "gpt-5.3-codex", @@ -83,6 +84,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": true, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "experimental", "slug": "gpt-5.2-codex", @@ -155,6 +157,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "experimental", "slug": "gpt-5.1-codex-max", @@ -220,6 +223,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "experimental", "slug": "gpt-5.1-codex", @@ -281,6 +285,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": true, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "none", "slug": "gpt-5.2", @@ -346,6 +351,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": true, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "none", "slug": "gpt-5.1", @@ -407,6 +413,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "experimental", "slug": "gpt-5-codex", @@ -468,6 +475,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "none", "slug": "gpt-5", @@ -532,6 +540,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 128000, "reasoning_summary_format": "none", "slug": "gpt-oss-120b", @@ -589,6 +598,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 128000, "reasoning_summary_format": "none", "slug": "gpt-oss-20b", @@ -647,6 +657,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "experimental", "slug": "gpt-5.1-codex-mini", @@ -704,6 +715,7 @@ "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272000, "reasoning_summary_format": "experimental", "slug": "gpt-5-codex-mini", diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 9e5974b487..d81c10f396 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -1305,6 +1305,7 @@ mod tests { "apply_patch_tool_type": null, "truncation_policy": {"mode": "bytes", "limit": 10000}, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272000, "auto_compact_token_limit": null, "experimental_supported_tools": [] diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index e4b7755abf..40e0f31e41 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -2,21 +2,29 @@ use crate::codex::TurnContext; use crate::context_manager::normalize; use crate::event_mapping::is_contextual_user_message_content; use crate::truncate::TruncationPolicy; +use crate::truncate::approx_bytes_for_tokens; use crate::truncate::approx_token_count; use crate::truncate::approx_tokens_from_byte_count_i64; use crate::truncate::truncate_function_output_items_with_policy; use crate::truncate::truncate_text; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ImageDetail; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::InputModality; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; use codex_protocol::protocol::TurnContextItem; +use codex_utils_cache::BlockingLruCache; +use codex_utils_cache::sha1_digest; +use std::num::NonZeroUsize; use std::ops::Deref; +use std::sync::LazyLock; /// Transcript of thread history #[derive(Debug, Clone, Default)] @@ -428,7 +436,19 @@ fn estimate_item_token_count(item: &ResponseItem) -> i64 { /// /// The estimator later converts bytes to tokens using a 4-bytes/token heuristic /// with ceiling division, so 7,373 bytes maps to approximately 1,844 tokens. -const IMAGE_BYTES_ESTIMATE: i64 = 7373; +const RESIZED_IMAGE_BYTES_ESTIMATE: i64 = 7373; +// See https://platform.openai.com/docs/guides/images-vision#calculating-costs. +// Use a direct 32px patch count only for `detail: "original"`; +// all other image inputs continue to use `RESIZED_IMAGE_BYTES_ESTIMATE`. +const ORIGINAL_IMAGE_PATCH_SIZE: u32 = 32; +const ORIGINAL_IMAGE_ESTIMATE_CACHE_SIZE: usize = 32; + +static ORIGINAL_IMAGE_ESTIMATE_CACHE: LazyLock>> = + LazyLock::new(|| { + BlockingLruCache::new( + NonZeroUsize::new(ORIGINAL_IMAGE_ESTIMATE_CACHE_SIZE).unwrap_or(NonZeroUsize::MIN), + ) + }); pub(crate) fn estimate_response_item_model_visible_bytes(item: &ResponseItem) -> i64 { match item { @@ -444,15 +464,15 @@ pub(crate) fn estimate_response_item_model_visible_bytes(item: &ResponseItem) -> let raw = serde_json::to_string(item) .map(|serialized| i64::try_from(serialized.len()).unwrap_or(i64::MAX)) .unwrap_or_default(); - let (payload_bytes, image_count) = image_data_url_estimate_adjustment(item); - if payload_bytes == 0 || image_count == 0 { + let (payload_bytes, replacement_bytes) = image_data_url_estimate_adjustment(item); + if payload_bytes == 0 || replacement_bytes == 0 { raw } else { - // Replace raw base64 payload bytes with a fixed per-image cost. - // We intentionally preserve the data URL prefix and JSON wrapper - // bytes already included in `raw`. + // Replace raw base64 payload bytes with a per-image estimate. + // We intentionally preserve the data URL prefix and JSON + // wrapper bytes already included in `raw`. raw.saturating_sub(payload_bytes) - .saturating_add(image_count.saturating_mul(IMAGE_BYTES_ESTIMATE)) + .saturating_add(replacement_bytes) } } } @@ -463,7 +483,7 @@ pub(crate) fn estimate_response_item_model_visible_bytes(item: &ResponseItem) -> /// /// We only discount payloads for `data:image/...;base64,...` URLs (case /// insensitive markers) and leave everything else at raw serialized size. -fn base64_data_url_payload_len(url: &str) -> Option { +fn parse_base64_image_data_url(url: &str) -> Option<&str> { if !url .get(.."data:".len()) .is_some_and(|prefix| prefix.eq_ignore_ascii_case("data:")) @@ -489,22 +509,62 @@ fn base64_data_url_payload_len(url: &str) -> Option { if !has_base64_marker { return None; } - Some(payload.len()) + Some(payload) +} + +fn estimate_original_image_bytes(image_url: &str) -> Option { + let key = sha1_digest(image_url.as_bytes()); + ORIGINAL_IMAGE_ESTIMATE_CACHE.get_or_insert_with(key, || { + let payload = match parse_base64_image_data_url(image_url) { + Some(payload) => payload, + None => { + tracing::trace!("skipping original-detail estimate for non-base64 image data URL"); + return None; + } + }; + let bytes = match BASE64_STANDARD.decode(payload) { + Ok(bytes) => bytes, + Err(error) => { + tracing::trace!("failed to decode original-detail image payload: {error}"); + return None; + } + }; + let dynamic = match image::load_from_memory(&bytes) { + Ok(dynamic) => dynamic, + Err(error) => { + tracing::trace!("failed to decode original-detail image bytes: {error}"); + return None; + } + }; + let width = i64::from(dynamic.width()); + let height = i64::from(dynamic.height()); + let patch_size = i64::from(ORIGINAL_IMAGE_PATCH_SIZE); + let patches_wide = width.saturating_add(patch_size.saturating_sub(1)) / patch_size; + let patches_high = height.saturating_add(patch_size.saturating_sub(1)) / patch_size; + let patch_count = patches_wide.saturating_mul(patches_high); + let patch_count = usize::try_from(patch_count).unwrap_or(usize::MAX); + Some(i64::try_from(approx_bytes_for_tokens(patch_count)).unwrap_or(i64::MAX)) + }) } /// Scans one response item for discount-eligible inline image data URLs and /// returns: /// - total base64 payload bytes to subtract from raw serialized size -/// - count of qualifying images to replace with `IMAGE_BYTES_ESTIMATE` +/// - total replacement byte estimate for those images fn image_data_url_estimate_adjustment(item: &ResponseItem) -> (i64, i64) { let mut payload_bytes = 0i64; - let mut image_count = 0i64; + let mut replacement_bytes = 0i64; - let mut accumulate = |image_url: &str| { - if let Some(payload_len) = base64_data_url_payload_len(image_url) { + let mut accumulate = |image_url: &str, detail: Option| { + if let Some(payload_len) = parse_base64_image_data_url(image_url).map(str::len) { payload_bytes = payload_bytes.saturating_add(i64::try_from(payload_len).unwrap_or(i64::MAX)); - image_count = image_count.saturating_add(1); + replacement_bytes = replacement_bytes.saturating_add(match detail { + Some(ImageDetail::Original) => { + estimate_original_image_bytes(image_url).unwrap_or(RESIZED_IMAGE_BYTES_ESTIMATE) + } + _ => RESIZED_IMAGE_BYTES_ESTIMATE, + }); } }; @@ -512,7 +572,7 @@ fn image_data_url_estimate_adjustment(item: &ResponseItem) -> (i64, i64) { ResponseItem::Message { content, .. } => { for content_item in content { if let ContentItem::InputImage { image_url } = content_item { - accumulate(image_url); + accumulate(image_url, None); } } } @@ -520,8 +580,10 @@ fn image_data_url_estimate_adjustment(item: &ResponseItem) -> (i64, i64) { | ResponseItem::CustomToolCallOutput { output, .. } => { if let FunctionCallOutputBody::ContentItems(items) = &output.body { for content_item in items { - if let FunctionCallOutputContentItem::InputImage { image_url } = content_item { - accumulate(image_url); + if let FunctionCallOutputContentItem::InputImage { image_url, detail } = + content_item + { + accumulate(image_url, *detail); } } } @@ -529,7 +591,7 @@ fn image_data_url_estimate_adjustment(item: &ResponseItem) -> (i64, i64) { _ => {} } - (payload_bytes, image_count) + (payload_bytes, replacement_bytes) } fn is_model_generated_item(item: &ResponseItem) -> bool { diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index 798abc7675..46aa462322 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -1,12 +1,15 @@ use super::*; use crate::truncate; use crate::truncate::TruncationPolicy; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_git::GhostCommit; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ImageDetail; use codex_protocol::models::LocalShellAction; use codex_protocol::models::LocalShellExecAction; use codex_protocol::models::LocalShellStatus; @@ -14,6 +17,9 @@ use codex_protocol::models::ReasoningItemContent; use codex_protocol::models::ReasoningItemReasoningSummary; use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::default_input_modalities; +use image::ImageBuffer; +use image::ImageFormat; +use image::Rgba; use pretty_assertions::assert_eq; use regex_lite::Regex; @@ -276,6 +282,7 @@ fn for_prompt_strips_images_when_model_does_not_support_images() { }, FunctionCallOutputContentItem::InputImage { image_url: "https://example.com/result.png".to_string(), + detail: None, }, ]), }, @@ -294,6 +301,7 @@ fn for_prompt_strips_images_when_model_does_not_support_images() { }, FunctionCallOutputContentItem::InputImage { image_url: "https://example.com/js-repl-result.png".to_string(), + detail: None, }, ]), }, @@ -489,6 +497,7 @@ fn replace_last_turn_images_replaces_tool_output_images() { body: FunctionCallOutputBody::ContentItems(vec![ FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,AAA".to_string(), + detail: None, }, ]), success: Some(true), @@ -1302,7 +1311,7 @@ fn image_data_url_payload_does_not_dominate_message_estimate() { let raw_len = serde_json::to_string(&image_item).unwrap().len() as i64; let estimated = estimate_response_item_model_visible_bytes(&image_item); - let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + let expected = raw_len - payload.len() as i64 + RESIZED_IMAGE_BYTES_ESTIMATE; let text_only_estimated = estimate_response_item_model_visible_bytes(&text_only_item); assert_eq!(estimated, expected); @@ -1320,13 +1329,16 @@ fn image_data_url_payload_does_not_dominate_function_call_output_estimate() { FunctionCallOutputContentItem::InputText { text: "Screenshot captured".to_string(), }, - FunctionCallOutputContentItem::InputImage { image_url }, + FunctionCallOutputContentItem::InputImage { + image_url, + detail: None, + }, ]), }; let raw_len = serde_json::to_string(&item).unwrap().len() as i64; let estimated = estimate_response_item_model_visible_bytes(&item); - let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + let expected = raw_len - payload.len() as i64 + RESIZED_IMAGE_BYTES_ESTIMATE; assert_eq!(estimated, expected); assert!(estimated < raw_len); @@ -1342,13 +1354,16 @@ fn image_data_url_payload_does_not_dominate_custom_tool_call_output_estimate() { FunctionCallOutputContentItem::InputText { text: "Screenshot captured".to_string(), }, - FunctionCallOutputContentItem::InputImage { image_url }, + FunctionCallOutputContentItem::InputImage { + image_url, + detail: None, + }, ]), }; let raw_len = serde_json::to_string(&item).unwrap().len() as i64; let estimated = estimate_response_item_model_visible_bytes(&item); - let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + let expected = raw_len - payload.len() as i64 + RESIZED_IMAGE_BYTES_ESTIMATE; assert_eq!(estimated, expected); assert!(estimated < raw_len); @@ -1370,6 +1385,7 @@ fn non_base64_image_urls_are_unchanged() { output: FunctionCallOutputPayload::from_content_items(vec![ FunctionCallOutputContentItem::InputImage { image_url: "file:///tmp/foo.png".to_string(), + detail: None, }, ]), }; @@ -1409,7 +1425,10 @@ fn non_image_base64_data_url_is_unchanged() { let item = ResponseItem::FunctionCallOutput { call_id: "call-octet".to_string(), output: FunctionCallOutputPayload::from_content_items(vec![ - FunctionCallOutputContentItem::InputImage { image_url }, + FunctionCallOutputContentItem::InputImage { + image_url, + detail: None, + }, ]), }; @@ -1433,7 +1452,7 @@ fn mixed_case_data_url_markers_are_adjusted() { let raw_len = serde_json::to_string(&item).unwrap().len() as i64; let estimated = estimate_response_item_model_visible_bytes(&item); - let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + let expected = raw_len - payload.len() as i64 + RESIZED_IMAGE_BYTES_ESTIMATE; assert_eq!(estimated, expected); } @@ -1465,7 +1484,70 @@ fn multiple_inline_images_apply_multiple_fixed_costs() { let raw_len = serde_json::to_string(&item).unwrap().len() as i64; let payload_sum = (payload_one.len() + payload_two.len()) as i64; let estimated = estimate_response_item_model_visible_bytes(&item); - let expected = raw_len - payload_sum + (2 * IMAGE_BYTES_ESTIMATE); + let expected = raw_len - payload_sum + (2 * RESIZED_IMAGE_BYTES_ESTIMATE); + + assert_eq!(estimated, expected); +} + +#[test] +fn original_detail_images_scale_with_dimensions() { + // 2304x864 at 32px patches yields 72 * 27 = 1,944 patches. + // The byte heuristic uses 4 bytes per token, so the replacement cost is 7,776 bytes. + const EXPECTED_ORIGINAL_DETAIL_IMAGE_BYTES: i64 = 7_776; + + let width = 2304; + let height = 864; + let image = ImageBuffer::from_pixel(width, height, Rgba([12u8, 34, 56, 255])); + let mut bytes = std::io::Cursor::new(Vec::new()); + image + .write_to(&mut bytes, ImageFormat::Png) + .expect("encode png"); + let payload = BASE64_STANDARD.encode(bytes.get_ref()); + let image_url = format!("data:image/png;base64,{payload}"); + let item = ResponseItem::FunctionCallOutput { + call_id: "call-original".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url, + detail: Some(ImageDetail::Original), + }, + ]), + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + let expected = raw_len - payload.len() as i64 + EXPECTED_ORIGINAL_DETAIL_IMAGE_BYTES; + + assert_eq!(estimated, expected); +} + +#[test] +fn original_detail_webp_images_scale_with_dimensions() { + // Same dimensions as the PNG case above, so the patch-based replacement cost is the same. + const EXPECTED_ORIGINAL_DETAIL_IMAGE_BYTES: i64 = 7_776; + + let width = 2304; + let height = 864; + let image = ImageBuffer::from_pixel(width, height, Rgba([12u8, 34, 56, 255])); + let mut bytes = std::io::Cursor::new(Vec::new()); + image + .write_to(&mut bytes, ImageFormat::WebP) + .expect("encode webp"); + let payload = BASE64_STANDARD.encode(bytes.get_ref()); + let image_url = format!("data:image/webp;base64,{payload}"); + let item = ResponseItem::FunctionCallOutput { + call_id: "call-original-webp".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url, + detail: Some(ImageDetail::Original), + }, + ]), + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + let expected = raw_len - payload.len() as i64 + EXPECTED_ORIGINAL_DETAIL_IMAGE_BYTES; assert_eq!(estimated, expected); } diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index d76c2dfc42..30c38e835f 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -119,6 +119,8 @@ pub enum Feature { MemoryTool, /// Append additional AGENTS.md guidance to user instructions. ChildAgentsMd, + /// Allow `detail: "original"` image outputs on supported models. + ImageDetailOriginal, /// Enforce UTF8 output in Powershell. PowershellUtf8, /// Compress request bodies (zstd) when sending streaming requests to codex-backend. @@ -529,6 +531,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::ImageDetailOriginal, + key: "image_detail_original", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::ApplyPatchFreeform, key: "apply_patch_freeform", diff --git a/codex-rs/core/src/models_manager/manager.rs b/codex-rs/core/src/models_manager/manager.rs index 1d7309020e..35e723d253 100644 --- a/codex-rs/core/src/models_manager/manager.rs +++ b/codex-rs/core/src/models_manager/manager.rs @@ -471,6 +471,7 @@ mod tests { "apply_patch_tool_type": null, "truncation_policy": {"mode": "bytes", "limit": 10_000}, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": 272_000, "experimental_supported_tools": [], })) @@ -549,6 +550,8 @@ mod tests { .build() .await .expect("load default test config"); + let mut overlay = remote_model("gpt-overlay", "Overlay", 0); + overlay.supports_image_detail_original = true; let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); @@ -556,7 +559,7 @@ mod tests { codex_home.path().to_path_buf(), auth_manager, Some(ModelsResponse { - models: vec![remote_model("gpt-overlay", "Overlay", 0)], + models: vec![overlay], }), CollaborationModesConfig::default(), ); @@ -568,6 +571,7 @@ mod tests { assert_eq!(model_info.slug, "gpt-overlay-experiment"); assert_eq!(model_info.display_name, "Overlay"); assert_eq!(model_info.context_window, Some(272_000)); + assert!(model_info.supports_image_detail_original); assert!(!model_info.supports_parallel_tool_calls); assert!(!model_info.used_fallback_model_metadata); } @@ -580,26 +584,24 @@ mod tests { .build() .await .expect("load default test config"); + let mut remote = remote_model("gpt-image", "Image", 0); + remote.supports_image_detail_original = true; let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); let manager = ModelsManager::new( codex_home.path().to_path_buf(), auth_manager, - None, + Some(ModelsResponse { + models: vec![remote], + }), CollaborationModesConfig::default(), ); - let known_slug = manager - .get_remote_models() - .await - .first() - .expect("bundled models should include at least one model") - .slug - .clone(); - let namespaced_model = format!("custom/{known_slug}"); + let namespaced_model = "custom/gpt-image".to_string(); let model_info = manager.get_model_info(&namespaced_model, &config).await; assert_eq!(model_info.slug, namespaced_model); + assert!(model_info.supports_image_detail_original); assert!(!model_info.used_fallback_model_metadata); } diff --git a/codex-rs/core/src/models_manager/model_info.rs b/codex-rs/core/src/models_manager/model_info.rs index 4824e4cd11..643d42571d 100644 --- a/codex-rs/core/src/models_manager/model_info.rs +++ b/codex-rs/core/src/models_manager/model_info.rs @@ -80,6 +80,7 @@ pub(crate) fn model_info_from_slug(slug: &str) -> ModelInfo { apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 8323b86a1b..6370b15447 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -55,6 +55,9 @@ fn render_js_repl_instructions(config: &Config) -> Option { section.push_str("- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n"); section.push_str("- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n"); section.push_str("- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n"); + if config.features.enabled(Feature::ImageDetailOriginal) { + section.push_str("- When generating or converting images for `view_image` in `js_repl`, prefer JPEG at 85% quality unless lossless quality is strictly required; other formats can be used if the user requests them. This keeps uploads smaller and reduces the chance of hitting image size caps.\n"); + } section.push_str("- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n"); section.push_str("- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n"); @@ -492,6 +495,21 @@ mod tests { assert_eq!(res, expected); } + #[tokio::test] + async fn js_repl_original_resolution_guidance_is_feature_gated() { + let tmp = tempfile::tempdir().expect("tempdir"); + let mut cfg = make_config(&tmp, 4096, None).await; + cfg.features + .enable(Feature::JsRepl) + .enable(Feature::ImageDetailOriginal); + + let res = get_user_instructions(&cfg, None) + .await + .expect("js_repl instructions expected"); + let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- When generating or converting images for `view_image` in `js_repl`, prefer JPEG at 85% quality unless lossless quality is strictly required; other formats can be used if the user requests them. This keeps uploads smaller and reduces the chance of hitting image size caps.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; + assert_eq!(res, expected); + } + /// When both system instructions *and* a project doc are present the two /// should be concatenated with the separator. #[tokio::test] diff --git a/codex-rs/core/src/tools/context.rs b/codex-rs/core/src/tools/context.rs index 0700b4d013..9f85e6acf8 100644 --- a/codex-rs/core/src/tools/context.rs +++ b/codex-rs/core/src/tools/context.rs @@ -222,6 +222,7 @@ mod tests { }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,AAA".to_string(), + detail: None, }, FunctionCallOutputContentItem::InputText { text: "line 2".to_string(), @@ -239,6 +240,7 @@ mod tests { }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,AAA".to_string(), + detail: None, }, FunctionCallOutputContentItem::InputText { text: "line 2".to_string(), diff --git a/codex-rs/core/src/tools/handlers/view_image.rs b/codex-rs/core/src/tools/handlers/view_image.rs index 9bf03acb00..6401751125 100644 --- a/codex-rs/core/src/tools/handlers/view_image.rs +++ b/codex-rs/core/src/tools/handlers/view_image.rs @@ -1,10 +1,15 @@ use async_trait::async_trait; +use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputContentItem; +use codex_protocol::models::ImageDetail; +use codex_protocol::models::local_image_content_items_with_label_number; use codex_protocol::openai_models::InputModality; +use codex_utils_image::PromptImageMode; use serde::Deserialize; use tokio::fs; +use crate::features::Feature; use crate::function_tool::FunctionCallError; use crate::protocol::EventMsg; use crate::protocol::ViewImageToolCallEvent; @@ -14,8 +19,6 @@ use crate::tools::context::ToolPayload; use crate::tools::handlers::parse_arguments; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; -use codex_protocol::models::ContentItem; -use codex_protocol::models::local_image_content_items_with_label_number; pub struct ViewImageHandler; @@ -81,15 +84,26 @@ impl ToolHandler for ViewImageHandler { } let event_path = abs_path.clone(); - let content = local_image_content_items_with_label_number(&abs_path, None); - let content = content + let use_original_detail = turn.config.features.enabled(Feature::ImageDetailOriginal) + && turn.model_info.supports_image_detail_original; + let image_mode = if use_original_detail { + PromptImageMode::Original + } else { + PromptImageMode::ResizeToFit + }; + let image_detail = use_original_detail.then_some(ImageDetail::Original); + + let content = local_image_content_items_with_label_number(&abs_path, None, image_mode) .into_iter() .map(|item| match item { ContentItem::InputText { text } => { FunctionCallOutputContentItem::InputText { text } } ContentItem::InputImage { image_url } => { - FunctionCallOutputContentItem::InputImage { image_url } + FunctionCallOutputContentItem::InputImage { + image_url, + detail: image_detail, + } } ContentItem::OutputText { text } => { FunctionCallOutputContentItem::InputText { text } diff --git a/codex-rs/core/src/tools/js_repl/mod.rs b/codex-rs/core/src/tools/js_repl/mod.rs index a234fd0eb8..ea9f42ce63 100644 --- a/codex-rs/core/src/tools/js_repl/mod.rs +++ b/codex-rs/core/src/tools/js_repl/mod.rs @@ -1900,6 +1900,7 @@ mod tests { output: FunctionCallOutputPayload::from_content_items(vec![ FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,abcd".to_string(), + detail: None, }, ]), }; @@ -1929,6 +1930,7 @@ mod tests { output: FunctionCallOutputPayload::from_content_items(vec![ FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,abcd".to_string(), + detail: None, }, ]), }; @@ -2417,15 +2419,17 @@ console.log(out.output?.body?.text ?? ""); image_url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" .to_string(), + detail: None, }] .as_slice() ); - let [FunctionCallOutputContentItem::InputImage { image_url }] = + let [FunctionCallOutputContentItem::InputImage { image_url, detail }] = result.content_items.as_slice() else { panic!("view_image should return exactly one input_image content item"); }; assert!(image_url.starts_with("data:image/png;base64,")); + assert_eq!(*detail, None); assert!(session.get_pending_input().await.is_empty()); Ok(()) @@ -2515,6 +2519,7 @@ console.log(out.type); }, FunctionCallOutputContentItem::InputImage { image_url: image_url.to_string(), + detail: None, }, ] ); diff --git a/codex-rs/core/src/truncate.rs b/codex-rs/core/src/truncate.rs index 309ed91b6f..fb275e6d46 100644 --- a/codex-rs/core/src/truncate.rs +++ b/codex-rs/core/src/truncate.rs @@ -138,9 +138,10 @@ pub(crate) fn truncate_function_output_items_with_policy( remaining_budget = 0; } } - FunctionCallOutputContentItem::InputImage { image_url } => { + FunctionCallOutputContentItem::InputImage { image_url, detail } => { out.push(FunctionCallOutputContentItem::InputImage { image_url: image_url.clone(), + detail: *detail, }); } } @@ -491,6 +492,7 @@ mod tests { FunctionCallOutputContentItem::InputText { text: t2.clone() }, FunctionCallOutputContentItem::InputImage { image_url: "img:mid".to_string(), + detail: None, }, FunctionCallOutputContentItem::InputText { text: t3 }, FunctionCallOutputContentItem::InputText { text: t4 }, @@ -518,7 +520,8 @@ mod tests { assert_eq!( output[2], FunctionCallOutputContentItem::InputImage { - image_url: "img:mid".to_string() + image_url: "img:mid".to_string(), + detail: None, } ); diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index 385072f912..e8fbcc851c 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -278,6 +278,7 @@ async fn model_change_from_image_to_text_strips_prior_image_content() -> Result< apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, @@ -439,6 +440,7 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result< apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(large_context_window), auto_compact_token_limit: None, effective_context_window_percent, diff --git a/codex-rs/core/tests/suite/models_cache_ttl.rs b/codex-rs/core/tests/suite/models_cache_ttl.rs index d2202b58cf..54b0629243 100644 --- a/codex-rs/core/tests/suite/models_cache_ttl.rs +++ b/codex-rs/core/tests/suite/models_cache_ttl.rs @@ -344,6 +344,7 @@ fn test_remote_model(slug: &str, priority: i32) -> ModelInfo { apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index 73f57ba0b0..f3a1f2e4db 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -619,6 +619,7 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(128_000), auto_compact_token_limit: None, effective_context_window_percent: 95, @@ -729,6 +730,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(128_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index 63f15f9c0d..ac2bc71565 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -303,6 +303,7 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, @@ -543,6 +544,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, @@ -1007,6 +1009,7 @@ fn test_remote_model_with_policy( apply_patch_tool_type: None, truncation_policy, supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 06c0042985..a8d414e998 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -409,6 +409,7 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index 5b8b9e0888..9b73afbc1b 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -291,6 +291,208 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn view_image_tool_can_preserve_original_resolution_on_gpt5_3_codex() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex() + .with_model("gpt-5.3-codex") + .with_config(|config| { + config.features.enable(Feature::ImageDetailOriginal); + }); + let TestCodex { + codex, + cwd, + session_configured, + .. + } = builder.build(&server).await?; + + let rel_path = "assets/original-example.png"; + let abs_path = cwd.path().join(rel_path); + if let Some(parent) = abs_path.parent() { + std::fs::create_dir_all(parent)?; + } + let original_width = 2304; + let original_height = 864; + let image = ImageBuffer::from_pixel(original_width, original_height, Rgba([0u8, 80, 255, 255])); + image.save(&abs_path)?; + + let call_id = "view-image-original"; + let arguments = serde_json::json!({ "path": rel_path }).to_string(); + + let first_response = sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, "view_image", &arguments), + ev_completed("resp-1"), + ]); + responses::mount_sse_once(&server, first_response).await; + + let second_response = sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]); + let mock = responses::mount_sse_once(&server, second_response).await; + + let session_model = session_configured.model.clone(); + + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "please add the original screenshot".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: session_model, + effort: None, + service_tier: None, + summary: None, + collaboration_mode: None, + personality: None, + }) + .await?; + + wait_for_event_with_timeout( + &codex, + |event| matches!(event, EventMsg::TurnComplete(_)), + Duration::from_secs(10), + ) + .await; + + let req = mock.single_request(); + let function_output = req.function_call_output(call_id); + let output_items = function_output + .get("output") + .and_then(Value::as_array) + .expect("function_call_output should be a content item array"); + assert_eq!(output_items.len(), 1); + assert_eq!( + output_items[0].get("detail").and_then(Value::as_str), + Some("original") + ); + let image_url = output_items[0] + .get("image_url") + .and_then(Value::as_str) + .expect("image_url present"); + + let (_, encoded) = image_url + .split_once(',') + .expect("image url contains data prefix"); + let decoded = BASE64_STANDARD + .decode(encoded) + .expect("image data decodes from base64 for request"); + let preserved = load_from_memory(&decoded).expect("load preserved image"); + let (width, height) = preserved.dimensions(); + assert_eq!(width, original_width); + assert_eq!(height, original_height); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn view_image_tool_keeps_legacy_behavior_below_gpt5_3_codex() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_model("gpt-5.2").with_config(|config| { + config.features.enable(Feature::ImageDetailOriginal); + }); + let TestCodex { + codex, + cwd, + session_configured, + .. + } = builder.build(&server).await?; + + let rel_path = "assets/original-example-lower-model.png"; + let abs_path = cwd.path().join(rel_path); + if let Some(parent) = abs_path.parent() { + std::fs::create_dir_all(parent)?; + } + let original_width = 2304; + let original_height = 864; + let image = ImageBuffer::from_pixel(original_width, original_height, Rgba([0u8, 80, 255, 255])); + image.save(&abs_path)?; + + let call_id = "view-image-original-lower-model"; + let arguments = serde_json::json!({ "path": rel_path }).to_string(); + + let first_response = sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, "view_image", &arguments), + ev_completed("resp-1"), + ]); + responses::mount_sse_once(&server, first_response).await; + + let second_response = sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]); + let mock = responses::mount_sse_once(&server, second_response).await; + + let session_model = session_configured.model.clone(); + + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "please add the screenshot".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: session_model, + effort: None, + service_tier: None, + summary: None, + collaboration_mode: None, + personality: None, + }) + .await?; + + wait_for_event_with_timeout( + &codex, + |event| matches!(event, EventMsg::TurnComplete(_)), + Duration::from_secs(10), + ) + .await; + + let req = mock.single_request(); + let function_output = req.function_call_output(call_id); + let output_items = function_output + .get("output") + .and_then(Value::as_array) + .expect("function_call_output should be a content item array"); + assert_eq!(output_items.len(), 1); + assert_eq!(output_items[0].get("detail"), None); + + let image_url = output_items[0] + .get("image_url") + .and_then(Value::as_str) + .expect("image_url present"); + + let (prefix, encoded) = image_url + .split_once(',') + .expect("image url contains data prefix"); + assert_eq!(prefix, "data:image/png;base64"); + + let decoded = BASE64_STANDARD + .decode(encoded) + .expect("image data decodes from base64 for request"); + let resized = load_from_memory(&decoded).expect("load resized image"); + let (resized_width, resized_height) = resized.dimensions(); + assert!(resized_width <= 2048); + assert!(resized_height <= 768); + assert!(resized_width < original_width); + assert!(resized_height < original_height); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn js_repl_view_image_tool_attaches_local_image() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); @@ -674,6 +876,7 @@ async fn view_image_tool_returns_unsupported_message_for_text_only_model() -> an apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: Some(272_000), auto_compact_token_limit: None, effective_context_window_percent: 95, diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 8461209823..8be7c9abf3 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; use std::path::Path; -use codex_utils_image::load_and_resize_to_fit; +use codex_utils_image::PromptImageMode; +use codex_utils_image::load_for_prompt; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; @@ -175,6 +176,15 @@ pub enum ContentItem { OutputText { text: String }, } +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "lowercase")] +pub enum ImageDetail { + Auto, + Low, + High, + Original, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "snake_case")] /// Classifies an assistant message as interim commentary or final answer text. @@ -710,8 +720,9 @@ fn unsupported_image_error_placeholder(path: &std::path::Path, mime: &str) -> Co pub fn local_image_content_items_with_label_number( path: &std::path::Path, label_number: Option, + mode: PromptImageMode, ) -> Vec { - match load_and_resize_to_fit(path) { + match load_for_prompt(path, mode) { Ok(image) => { let mut items = Vec::with_capacity(3); if let Some(label_number) = label_number { @@ -872,7 +883,11 @@ impl From> for ResponseInputItem { } UserInput::LocalImage { path } => { image_index += 1; - local_image_content_items_with_label_number(&path, Some(image_index)) + local_image_content_items_with_label_number( + &path, + Some(image_index), + PromptImageMode::ResizeToFit, + ) } UserInput::Skill { .. } | UserInput::Mention { .. } => Vec::new(), // Tool bodies are injected later in core }) @@ -937,9 +952,16 @@ pub struct ShellCommandToolCallParams { #[serde(tag = "type", rename_all = "snake_case")] pub enum FunctionCallOutputContentItem { // Do not rename, these are serialized and used directly in the responses API. - InputText { text: String }, + InputText { + text: String, + }, // Do not rename, these are serialized and used directly in the responses API. - InputImage { image_url: String }, + InputImage { + image_url: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + detail: Option, + }, } /// Converts structured function-call output content into plain text for @@ -983,7 +1005,10 @@ impl From Self::InputText { text } } crate::dynamic_tools::DynamicToolCallOutputContentItem::InputImage { image_url } => { - Self::InputImage { image_url } + Self::InputImage { + image_url, + detail: None, + } } } } @@ -1185,7 +1210,10 @@ fn convert_mcp_content_to_items( let mime_type = mime_type.unwrap_or_else(|| "application/octet-stream".into()); format!("data:{mime_type};base64,{data}") }; - FunctionCallOutputContentItem::InputImage { image_url } + FunctionCallOutputContentItem::InputImage { + image_url, + detail: None, + } } Ok(McpContent::Unknown) | Err(_) => FunctionCallOutputContentItem::InputText { text: serde_json::to_string(content).unwrap_or_else(|_| "".to_string()), @@ -1239,6 +1267,7 @@ mod tests { items, vec![FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,Zm9v".to_string(), + detail: None, }] ); } @@ -1256,6 +1285,7 @@ mod tests { items, vec![FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,Zm9v".to_string(), + detail: None, }] ); } @@ -1278,6 +1308,7 @@ mod tests { }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,AAA".to_string(), + detail: None, }, FunctionCallOutputContentItem::InputText { text: "line 2".to_string(), @@ -1296,6 +1327,7 @@ mod tests { }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,AAA".to_string(), + detail: None, }, ]; @@ -1318,6 +1350,7 @@ mod tests { }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,AAA".to_string(), + detail: None, }, ]); @@ -1542,6 +1575,7 @@ mod tests { }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,BASE64".into(), + detail: None, }, ] ); @@ -1567,6 +1601,7 @@ mod tests { output: FunctionCallOutputPayload::from_content_items(vec![ FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,BASE64".into(), + detail: None, }, ]), }; @@ -1602,6 +1637,7 @@ mod tests { items, vec![FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,BASE64".into(), + detail: None, }] ); @@ -1624,6 +1660,7 @@ mod tests { }, FunctionCallOutputContentItem::InputImage { image_url: "data:image/png;base64,XYZ".into(), + detail: None, }, ]; assert_eq!( diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs index b63f137442..089b002680 100644 --- a/codex-rs/protocol/src/openai_models.rs +++ b/codex-rs/protocol/src/openai_models.rs @@ -245,6 +245,8 @@ pub struct ModelInfo { pub apply_patch_tool_type: Option, pub truncation_policy: TruncationPolicyConfig, pub supports_parallel_tool_calls: bool, + #[serde(default)] + pub supports_image_detail_original: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub context_window: Option, /// Token threshold for automatic compaction. When omitted, core derives it @@ -515,6 +517,7 @@ mod tests { apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, + supports_image_detail_original: false, context_window: None, auto_compact_token_limit: None, effective_context_window_percent: 95, @@ -713,6 +716,7 @@ mod tests { .expect("deserialize model info"); assert_eq!(model.availability_nux, None); + assert!(!model.supports_image_detail_original); } #[test] diff --git a/codex-rs/utils/image/src/lib.rs b/codex-rs/utils/image/src/lib.rs index 0950bf176e..d0aba2f608 100644 --- a/codex-rs/utils/image/src/lib.rs +++ b/codex-rs/utils/image/src/lib.rs @@ -14,6 +14,7 @@ use image::ImageEncoder; use image::ImageFormat; use image::codecs::jpeg::JpegEncoder; use image::codecs::png::PngEncoder; +use image::codecs::webp::WebPEncoder; use image::imageops::FilterType; /// Maximum width used when resizing images before uploading. pub const MAX_WIDTH: u32 = 2048; @@ -33,24 +34,48 @@ pub struct EncodedImage { impl EncodedImage { pub fn into_data_url(self) -> String { let encoded = BASE64_STANDARD.encode(&self.bytes); - format!("data:{};base64,{}", self.mime, encoded) + format!("data:{};base64,{encoded}", self.mime) } } -static IMAGE_CACHE: LazyLock> = +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PromptImageMode { + ResizeToFit, + Original, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct ImageCacheKey { + digest: [u8; 20], + mode: PromptImageMode, +} + +static IMAGE_CACHE: LazyLock> = LazyLock::new(|| BlockingLruCache::new(NonZeroUsize::new(32).unwrap_or(NonZeroUsize::MIN))); pub fn load_and_resize_to_fit(path: &Path) -> Result { + load_for_prompt(path, PromptImageMode::ResizeToFit) +} + +pub fn load_for_prompt( + path: &Path, + mode: PromptImageMode, +) -> Result { let path_buf = path.to_path_buf(); let file_bytes = read_file_bytes(path, &path_buf)?; - let key = sha1_digest(&file_bytes); + let key = ImageCacheKey { + digest: sha1_digest(&file_bytes), + mode, + }; IMAGE_CACHE.get_or_try_insert_with(key, move || { let format = match image::guess_format(&file_bytes) { Ok(ImageFormat::Png) => Some(ImageFormat::Png), Ok(ImageFormat::Jpeg) => Some(ImageFormat::Jpeg), + Ok(ImageFormat::Gif) => Some(ImageFormat::Gif), + Ok(ImageFormat::WebP) => Some(ImageFormat::WebP), _ => None, }; @@ -63,42 +88,54 @@ pub fn load_and_resize_to_fit(path: &Path) -> Result bool { + // Public API docs explicitly call out non-animated GIF support only. + // Preserve byte-for-byte only for formats we can safely pass through. + matches!( + format, + ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP + ) +} + fn read_file_bytes(path: &Path, path_for_error: &Path) -> Result, ImageProcessingError> { match tokio::runtime::Handle::try_current() { // If we're inside a Tokio runtime, avoid block_on (it panics on worker threads). @@ -123,6 +160,7 @@ fn encode_image( ) -> Result<(Vec, ImageFormat), ImageProcessingError> { let target_format = match preferred_format { ImageFormat::Jpeg => ImageFormat::Jpeg, + ImageFormat::WebP => ImageFormat::WebP, _ => ImageFormat::Png, }; @@ -153,6 +191,21 @@ fn encode_image( source, })?; } + ImageFormat::WebP => { + let rgba = image.to_rgba8(); + let encoder = WebPEncoder::new_lossless(&mut buffer); + encoder + .write_image( + rgba.as_raw(), + image.width(), + image.height(), + ColorType::Rgba8.into(), + ) + .map_err(|source| ImageProcessingError::Encode { + format: target_format, + source, + })?; + } _ => unreachable!("unsupported target_format should have been handled earlier"), } @@ -162,6 +215,8 @@ fn encode_image( fn format_to_mime(format: ImageFormat) -> String { match format { ImageFormat::Jpeg => "image/jpeg".to_string(), + ImageFormat::Gif => "image/gif".to_string(), + ImageFormat::WebP => "image/webp".to_string(), _ => "image/png".to_string(), } } @@ -176,38 +231,70 @@ mod tests { #[tokio::test(flavor = "multi_thread")] async fn returns_original_image_when_within_bounds() { + for (format, mime) in [ + (ImageFormat::Png, "image/png"), + (ImageFormat::WebP, "image/webp"), + ] { + let temp_file = NamedTempFile::new().expect("temp file"); + let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255])); + image + .save_with_format(temp_file.path(), format) + .expect("write image to temp file"); + + let original_bytes = std::fs::read(temp_file.path()).expect("read written image"); + let encoded = load_and_resize_to_fit(temp_file.path()).expect("process image"); + + assert_eq!(encoded.width, 64); + assert_eq!(encoded.height, 32); + assert_eq!(encoded.mime, mime); + assert_eq!(encoded.bytes, original_bytes); + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn downscales_large_image() { + for (format, mime) in [ + (ImageFormat::Png, "image/png"), + (ImageFormat::WebP, "image/webp"), + ] { + let temp_file = NamedTempFile::new().expect("temp file"); + let image = ImageBuffer::from_pixel(4096, 2048, Rgba([200u8, 10, 10, 255])); + image + .save_with_format(temp_file.path(), format) + .expect("write image to temp file"); + + let processed = load_and_resize_to_fit(temp_file.path()).expect("process image"); + + assert!(processed.width <= MAX_WIDTH); + assert!(processed.height <= MAX_HEIGHT); + assert_eq!(processed.mime, mime); + + let detected_format = + image::guess_format(&processed.bytes).expect("detect resized output format"); + assert_eq!(detected_format, format); + + let loaded = image::load_from_memory(&processed.bytes) + .expect("read resized bytes back into image"); + assert_eq!(loaded.dimensions(), (processed.width, processed.height)); + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn preserves_large_image_in_original_mode() { let temp_file = NamedTempFile::new().expect("temp file"); - let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255])); + let image = ImageBuffer::from_pixel(4096, 2048, Rgba([180u8, 30, 30, 255])); image .save_with_format(temp_file.path(), ImageFormat::Png) .expect("write png to temp file"); let original_bytes = std::fs::read(temp_file.path()).expect("read written image"); + let processed = + load_for_prompt(temp_file.path(), PromptImageMode::Original).expect("process image"); - let encoded = load_and_resize_to_fit(temp_file.path()).expect("process image"); - - assert_eq!(encoded.width, 64); - assert_eq!(encoded.height, 32); - assert_eq!(encoded.mime, "image/png"); - assert_eq!(encoded.bytes, original_bytes); - } - - #[tokio::test(flavor = "multi_thread")] - async fn downscales_large_image() { - let temp_file = NamedTempFile::new().expect("temp file"); - let image = ImageBuffer::from_pixel(4096, 2048, Rgba([200u8, 10, 10, 255])); - image - .save_with_format(temp_file.path(), ImageFormat::Png) - .expect("write png to temp file"); - - let processed = load_and_resize_to_fit(temp_file.path()).expect("process image"); - - assert!(processed.width <= MAX_WIDTH); - assert!(processed.height <= MAX_HEIGHT); - - let loaded = - image::load_from_memory(&processed.bytes).expect("read resized bytes back into image"); - assert_eq!(loaded.dimensions(), (processed.width, processed.height)); + assert_eq!(processed.width, 4096); + assert_eq!(processed.height, 2048); + assert_eq!(processed.mime, "image/png"); + assert_eq!(processed.bytes, original_bytes); } #[tokio::test(flavor = "multi_thread")] From 1afbbc11c3e2452cd61a4b102eb96b60e45f2de0 Mon Sep 17 00:00:00 2001 From: alexsong-oai Date: Tue, 3 Mar 2026 16:12:23 -0800 Subject: [PATCH 351/385] Ensure the env values of imported shell_environment_policy.set is string (#13402) --- codex-rs/core/src/external_agent_config.rs | 183 ++++++++++++++------- 1 file changed, 125 insertions(+), 58 deletions(-) diff --git a/codex-rs/core/src/external_agent_config.rs b/codex-rs/core/src/external_agent_config.rs index 1d466e6f4b..d0fde766f5 100644 --- a/codex-rs/core/src/external_agent_config.rs +++ b/codex-rs/core/src/external_agent_config.rs @@ -126,7 +126,7 @@ impl ExternalAgentConfigService { items.push(ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::Config, description: format!( - "Migrate {} into {}.", + "Migrate {} into {}", source_settings.display(), target_config.display() ), @@ -153,7 +153,7 @@ impl ExternalAgentConfigService { items.push(ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::Skills, description: format!( - "Copy skill folders from {} to {}.", + "Copy skill folders from {} to {}", source_skills.display(), target_skills.display() ), @@ -161,19 +161,23 @@ impl ExternalAgentConfigService { }); } - let source_agents_md = repo_root.map_or_else( - || self.claude_home.join("CLAUDE.md"), - |repo_root| repo_root.join("CLAUDE.md"), - ); + let source_agents_md = if let Some(repo_root) = repo_root { + find_repo_agents_md_source(repo_root)? + } else { + let path = self.claude_home.join("CLAUDE.md"); + is_non_empty_text_file(&path)?.then_some(path) + }; let target_agents_md = repo_root.map_or_else( || self.codex_home.join("AGENTS.md"), |repo_root| repo_root.join("AGENTS.md"), ); - if source_agents_md.is_file() && is_missing_or_empty_text_file(&target_agents_md)? { + if let Some(source_agents_md) = source_agents_md + && is_missing_or_empty_text_file(&target_agents_md)? + { items.push(ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::AgentsMd, description: format!( - "Import {} to {}.", + "Import {} to {}", source_agents_md.display(), target_agents_md.display() ), @@ -283,7 +287,10 @@ impl ExternalAgentConfigService { fn import_agents_md(&self, cwd: Option<&Path>) -> io::Result<()> { let (source_agents_md, target_agents_md) = if let Some(repo_root) = find_repo_root(cwd)? { - (repo_root.join("CLAUDE.md"), repo_root.join("AGENTS.md")) + let Some(source_agents_md) = find_repo_agents_md_source(&repo_root)? else { + return Ok(()); + }; + (source_agents_md, repo_root.join("AGENTS.md")) } else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) { return Ok(()); } else { @@ -292,7 +299,9 @@ impl ExternalAgentConfigService { self.codex_home.join("AGENTS.md"), ) }; - if !source_agents_md.is_file() || !is_missing_or_empty_text_file(&target_agents_md)? { + if !is_non_empty_text_file(&source_agents_md)? + || !is_missing_or_empty_text_file(&target_agents_md)? + { return Ok(()); } @@ -376,6 +385,27 @@ fn is_missing_or_empty_text_file(path: &Path) -> io::Result { Ok(fs::read_to_string(path)?.trim().is_empty()) } +fn is_non_empty_text_file(path: &Path) -> io::Result { + if !path.is_file() { + return Ok(false); + } + + Ok(!fs::read_to_string(path)?.trim().is_empty()) +} + +fn find_repo_agents_md_source(repo_root: &Path) -> io::Result> { + for candidate in [ + repo_root.join("CLAUDE.md"), + repo_root.join(".claude").join("CLAUDE.md"), + ] { + if is_non_empty_text_file(&candidate)? { + return Ok(Some(candidate)); + } + } + + Ok(None) +} + fn copy_dir_recursive(source: &Path, target: &Path) -> io::Result<()> { fs::create_dir_all(target)?; @@ -487,7 +517,7 @@ fn build_config_from_external(settings: &JsonValue) -> io::Result { shell_policy.insert("inherit".to_string(), TomlValue::String("core".to_string())); shell_policy.insert( "set".to_string(), - TomlValue::Table(json_object_to_toml_table(env)?), + TomlValue::Table(json_object_to_env_toml_table(env)), ); root.insert( "shell_environment_policy".to_string(), @@ -511,36 +541,25 @@ fn build_config_from_external(settings: &JsonValue) -> io::Result { Ok(TomlValue::Table(root)) } -fn json_object_to_toml_table( +fn json_object_to_env_toml_table( object: &serde_json::Map, -) -> io::Result> { +) -> toml::map::Map { let mut table = toml::map::Map::new(); for (key, value) in object { - table.insert(key.clone(), json_to_toml_value(value)?); + if let Some(value) = json_env_value_to_string(value) { + table.insert(key.clone(), TomlValue::String(value)); + } } - Ok(table) + table } -fn json_to_toml_value(value: &JsonValue) -> io::Result { +fn json_env_value_to_string(value: &JsonValue) -> Option { match value { - JsonValue::Null => Ok(TomlValue::String("null".to_string())), - JsonValue::Bool(v) => Ok(TomlValue::Boolean(*v)), - JsonValue::Number(n) => { - if let Some(i) = n.as_i64() { - return Ok(TomlValue::Integer(i)); - } - if let Some(f) = n.as_f64() { - return Ok(TomlValue::Float(f)); - } - Err(invalid_data_error("unsupported JSON number")) - } - JsonValue::String(v) => Ok(TomlValue::String(v.clone())), - JsonValue::Array(values) => values - .iter() - .map(json_to_toml_value) - .collect::>>() - .map(TomlValue::Array), - JsonValue::Object(map) => json_object_to_toml_table(map).map(TomlValue::Table), + JsonValue::String(value) => Some(value.clone()), + JsonValue::Null => None, + JsonValue::Bool(value) => Some(value.to_string()), + JsonValue::Number(value) => Some(value.to_string()), + JsonValue::Array(_) | JsonValue::Object(_) => None, } } @@ -576,7 +595,7 @@ fn merge_missing_toml_values(existing: &mut TomlValue, incoming: &TomlValue) -> fn write_toml_file(path: &Path, value: &TomlValue) -> io::Result<()> { let serialized = toml::to_string_pretty(value) .map_err(|err| invalid_data_error(format!("failed to serialize config.toml: {err}")))?; - fs::write(path, format!("{serialized}\n")) + fs::write(path, format!("{}\n", serialized.trim_end())) } fn is_empty_toml_table(value: &TomlValue) -> bool { @@ -638,7 +657,7 @@ mod tests { ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::Config, description: format!( - "Migrate {} into {}.", + "Migrate {} into {}", claude_home.join("settings.json").display(), codex_home.join("config.toml").display() ), @@ -647,7 +666,7 @@ mod tests { ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::Skills, description: format!( - "Copy skill folders from {} to {}.", + "Copy skill folders from {} to {}", claude_home.join("skills").display(), agents_skills.display() ), @@ -656,7 +675,7 @@ mod tests { ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::AgentsMd, description: format!( - "Import {} to {}.", + "Import {} to {}", claude_home.join("CLAUDE.md").display(), codex_home.join("AGENTS.md").display() ), @@ -687,7 +706,7 @@ mod tests { ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::AgentsMd, description: format!( - "Import {} to {}.", + "Import {} to {}", repo_root.join("CLAUDE.md").display(), repo_root.join("AGENTS.md").display(), ), @@ -696,7 +715,7 @@ mod tests { ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::AgentsMd, description: format!( - "Import {} to {}.", + "Import {} to {}", repo_root.join("CLAUDE.md").display(), repo_root.join("AGENTS.md").display(), ), @@ -717,7 +736,7 @@ mod tests { fs::create_dir_all(claude_home.join("skills").join("skill-a")).expect("create skills"); fs::write( claude_home.join("settings.json"), - r#"{"model":"claude","permissions":{"ask":["git push"]},"env":{"FOO":"bar"},"sandbox":{"enabled":true,"network":{"allowLocalBinding":true}}}"#, + r#"{"model":"claude","permissions":{"ask":["git push"]},"env":{"FOO":"bar","CI":false,"MAX_RETRIES":3,"MY_TEAM":"codex","IGNORED":null,"LIST":["a","b"],"MAP":{"x":1}},"sandbox":{"enabled":true,"network":{"allowLocalBinding":true}}}"#, ) .expect("write settings"); fs::write( @@ -752,23 +771,10 @@ mod tests { "Codex guidance" ); - let parsed_config: TomlValue = toml::from_str( - &fs::read_to_string(codex_home.join("config.toml")).expect("read config"), - ) - .expect("parse config"); - let expected_config: TomlValue = toml::from_str( - r#" - sandbox_mode = "workspace-write" - - [shell_environment_policy] - inherit = "core" - - [shell_environment_policy.set] - FOO = "bar" - "#, - ) - .expect("parse expected"); - assert_eq!(parsed_config, expected_config); + assert_eq!( + fs::read_to_string(codex_home.join("config.toml")).expect("read config"), + "sandbox_mode = \"workspace-write\"\n\n[shell_environment_policy]\ninherit = \"core\"\n\n[shell_environment_policy.set]\nCI = \"false\"\nFOO = \"bar\"\nMAX_RETRIES = \"3\"\nMY_TEAM = \"codex\"\n" + ); assert_eq!( fs::read_to_string(agents_skills.join("skill-a").join("SKILL.md")) .expect("read copied skill"), @@ -917,4 +923,65 @@ mod tests { "Codex guidance" ); } + + #[test] + fn detect_repo_prefers_non_empty_dot_claude_agents_source() { + let root = TempDir::new().expect("create tempdir"); + let repo_root = root.path().join("repo"); + fs::create_dir_all(repo_root.join(".git")).expect("create git"); + fs::create_dir_all(repo_root.join(".claude")).expect("create dot claude"); + fs::write(repo_root.join("CLAUDE.md"), " \n\t").expect("write empty root source"); + fs::write( + repo_root.join(".claude").join("CLAUDE.md"), + "Claude code guidance", + ) + .expect("write dot claude source"); + + let items = service_for_paths(root.path().join(".claude"), root.path().join(".codex")) + .detect(ExternalAgentConfigDetectOptions { + include_home: false, + cwds: Some(vec![repo_root.clone()]), + }) + .expect("detect"); + + assert_eq!( + items, + vec![ExternalAgentConfigMigrationItem { + item_type: ExternalAgentConfigMigrationItemType::AgentsMd, + description: format!( + "Import {} to {}", + repo_root.join(".claude").join("CLAUDE.md").display(), + repo_root.join("AGENTS.md").display(), + ), + cwd: Some(repo_root), + }] + ); + } + + #[test] + fn import_repo_uses_non_empty_dot_claude_agents_source() { + let root = TempDir::new().expect("create tempdir"); + let repo_root = root.path().join("repo"); + fs::create_dir_all(repo_root.join(".git")).expect("create git"); + fs::create_dir_all(repo_root.join(".claude")).expect("create dot claude"); + fs::write(repo_root.join("CLAUDE.md"), "").expect("write empty root source"); + fs::write( + repo_root.join(".claude").join("CLAUDE.md"), + "Claude code guidance", + ) + .expect("write dot claude source"); + + service_for_paths(root.path().join(".claude"), root.path().join(".codex")) + .import(vec![ExternalAgentConfigMigrationItem { + item_type: ExternalAgentConfigMigrationItemType::AgentsMd, + description: String::new(), + cwd: Some(repo_root.clone()), + }]) + .expect("import"); + + assert_eq!( + fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"), + "Codex guidance" + ); + } } From c4cb594e73fda4b9247d606fb00eb2c58da26647 Mon Sep 17 00:00:00 2001 From: Curtis 'Fjord' Hawthorne Date: Tue, 3 Mar 2026 16:25:59 -0800 Subject: [PATCH 352/385] Make js_repl image output controllable (#13331) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Instead of always adding inner function call outputs to the model context, let js code decide which ones to return. - Stop auto-hoisting nested tool outputs from `codex.tool(...)` into the outer `js_repl` function output. - Keep `codex.tool(...)` return values unchanged as structured JS objects. - Add `codex.emitImage(...)` as the explicit path for attaching an image to the outer `js_repl` function output. - Support emitting from a direct image URL, a single `input_image` item, an explicit `{ bytes, mimeType }` object, or a raw tool response object containing exactly one image. - Preserve existing `view_image` original-resolution behavior when JS emits the raw `view_image` tool result. - Suppress the special `ViewImageToolCall` event for `js_repl`-sourced `view_image` calls so nested inspection stays side-effect free until JS explicitly emits. - Update the `js_repl` docs and generated project instructions with both recommended patterns: - `await codex.emitImage(codex.tool("view_image", { path }))` - `await codex.emitImage({ bytes: await page.screenshot({ type: "jpeg", quality: 85 }), mimeType: "image/jpeg" })` #### [git stack](https://github.com/magus/git-stack-cli) - ✅ `1` https://github.com/openai/codex/pull/13050 - 👉 `2` https://github.com/openai/codex/pull/13331 - ⏳ `3` https://github.com/openai/codex/pull/13049 --- codex-rs/core/src/project_doc.rs | 18 +- codex-rs/core/src/tools/js_repl/kernel.js | 317 ++++++++++- codex-rs/core/src/tools/js_repl/mod.rs | 614 +++++++++++++++++++--- codex-rs/core/tests/suite/client.rs | 123 +++++ codex-rs/core/tests/suite/view_image.rs | 122 ++++- docs/js_repl.md | 7 +- 6 files changed, 1124 insertions(+), 77 deletions(-) diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 6370b15447..debe39c2ad 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -52,9 +52,13 @@ fn render_js_repl_instructions(config: &Config) -> Option { "- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n", ); section.push_str("- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n"); - section.push_str("- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n"); - section.push_str("- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n"); - section.push_str("- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n"); + section.push_str( + "- Helpers: `codex.tmpDir`, `codex.tool(name, args?)`, and `codex.emitImage(imageLike)`.\n", + ); + section.push_str("- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike. Nested tool outputs stay inside JavaScript unless you emit them explicitly.\n"); + section.push_str("- `codex.emitImage(...)` adds exactly one image to the outer `js_repl` function output. It accepts a direct image URL, a single `input_image` item, an object like `{ bytes, mimeType }`, or a raw tool response object with exactly one image and no text. It rejects mixed text-and-image content.\n"); + section.push_str("- Example of sharing an in-memory Playwright screenshot: `await codex.emitImage({ bytes: await page.screenshot({ type: \"jpeg\", quality: 85 }), mimeType: \"image/jpeg\" })`.\n"); + section.push_str("- Example of sharing a local image tool result: `await codex.emitImage(codex.tool(\"view_image\", { path: \"/absolute/path\" }))`.\n"); if config.features.enabled(Feature::ImageDetailOriginal) { section.push_str("- When generating or converting images for `view_image` in `js_repl`, prefer JPEG at 85% quality unless lossless quality is strictly required; other formats can be used if the user requests them. This keeps uploads smaller and reduces the chance of hitting image size caps.\n"); } @@ -67,7 +71,7 @@ fn render_js_repl_instructions(config: &Config) -> Option { .push_str("- MCP tools (if any) can also be called by name via `codex.tool(...)`.\n"); } - section.push_str("- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."); + section.push_str("- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log`, `codex.tool(...)`, and `codex.emitImage(...)`."); Some(section) } @@ -476,7 +480,7 @@ mod tests { let res = get_user_instructions(&cfg, None) .await .expect("js_repl instructions expected"); - let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; + let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir`, `codex.tool(name, args?)`, and `codex.emitImage(imageLike)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike. Nested tool outputs stay inside JavaScript unless you emit them explicitly.\n- `codex.emitImage(...)` adds exactly one image to the outer `js_repl` function output. It accepts a direct image URL, a single `input_image` item, an object like `{ bytes, mimeType }`, or a raw tool response object with exactly one image and no text. It rejects mixed text-and-image content.\n- Example of sharing an in-memory Playwright screenshot: `await codex.emitImage({ bytes: await page.screenshot({ type: \"jpeg\", quality: 85 }), mimeType: \"image/jpeg\" })`.\n- Example of sharing a local image tool result: `await codex.emitImage(codex.tool(\"view_image\", { path: \"/absolute/path\" }))`.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log`, `codex.tool(...)`, and `codex.emitImage(...)`."; assert_eq!(res, expected); } @@ -491,7 +495,7 @@ mod tests { let res = get_user_instructions(&cfg, None) .await .expect("js_repl instructions expected"); - let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Do not call tools directly; use `js_repl` + `codex.tool(...)` for all tool calls, including shell commands.\n- MCP tools (if any) can also be called by name via `codex.tool(...)`.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; + let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir`, `codex.tool(name, args?)`, and `codex.emitImage(imageLike)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike. Nested tool outputs stay inside JavaScript unless you emit them explicitly.\n- `codex.emitImage(...)` adds exactly one image to the outer `js_repl` function output. It accepts a direct image URL, a single `input_image` item, an object like `{ bytes, mimeType }`, or a raw tool response object with exactly one image and no text. It rejects mixed text-and-image content.\n- Example of sharing an in-memory Playwright screenshot: `await codex.emitImage({ bytes: await page.screenshot({ type: \"jpeg\", quality: 85 }), mimeType: \"image/jpeg\" })`.\n- Example of sharing a local image tool result: `await codex.emitImage(codex.tool(\"view_image\", { path: \"/absolute/path\" }))`.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Do not call tools directly; use `js_repl` + `codex.tool(...)` for all tool calls, including shell commands.\n- MCP tools (if any) can also be called by name via `codex.tool(...)`.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log`, `codex.tool(...)`, and `codex.emitImage(...)`."; assert_eq!(res, expected); } @@ -506,7 +510,7 @@ mod tests { let res = get_user_instructions(&cfg, None) .await .expect("js_repl instructions expected"); - let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir` and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- When generating or converting images for `view_image` in `js_repl`, prefer JPEG at 85% quality unless lossless quality is strictly required; other formats can be used if the user requests them. This keeps uploads smaller and reduces the chance of hitting image size caps.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; + let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.tmpDir`, `codex.tool(name, args?)`, and `codex.emitImage(imageLike)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike. Nested tool outputs stay inside JavaScript unless you emit them explicitly.\n- `codex.emitImage(...)` adds exactly one image to the outer `js_repl` function output. It accepts a direct image URL, a single `input_image` item, an object like `{ bytes, mimeType }`, or a raw tool response object with exactly one image and no text. It rejects mixed text-and-image content.\n- Example of sharing an in-memory Playwright screenshot: `await codex.emitImage({ bytes: await page.screenshot({ type: \"jpeg\", quality: 85 }), mimeType: \"image/jpeg\" })`.\n- Example of sharing a local image tool result: `await codex.emitImage(codex.tool(\"view_image\", { path: \"/absolute/path\" }))`.\n- When generating or converting images for `view_image` in `js_repl`, prefer JPEG at 85% quality unless lossless quality is strictly required; other formats can be used if the user requests them. This keeps uploads smaller and reduces the chance of hitting image size caps.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log`, `codex.tool(...)`, and `codex.emitImage(...)`."; assert_eq!(res, expected); } diff --git a/codex-rs/core/src/tools/js_repl/kernel.js b/codex-rs/core/src/tools/js_repl/kernel.js index f5459fde79..038783fb2b 100644 --- a/codex-rs/core/src/tools/js_repl/kernel.js +++ b/codex-rs/core/src/tools/js_repl/kernel.js @@ -115,7 +115,10 @@ function isDeniedBuiltin(specifier) { /** @type {Map void>} */ const pendingTool = new Map(); +/** @type {Map void>} */ +const pendingEmitImage = new Map(); let toolCounter = 0; +let emitImageCounter = 0; const tmpDir = process.env.CODEX_JS_TMP_DIR || process.cwd(); const nodeModuleDirEnv = process.env.CODEX_JS_REPL_NODE_MODULE_DIRS ?? ""; const moduleSearchBases = (() => { @@ -480,8 +483,255 @@ function withCapturedConsole(ctx, fn) { }); } +function isPlainObject(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function toByteArray(value) { + if (value instanceof Uint8Array) { + return value; + } + if (value instanceof ArrayBuffer) { + return new Uint8Array(value); + } + if (ArrayBuffer.isView(value)) { + return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + } + return null; +} + +function encodeByteImage(bytes, mimeType, detail) { + if (bytes.byteLength === 0) { + throw new Error("codex.emitImage expected non-empty bytes"); + } + if (typeof mimeType !== "string" || !mimeType) { + throw new Error("codex.emitImage expected a non-empty mimeType"); + } + const image_url = `data:${mimeType};base64,${Buffer.from(bytes).toString("base64")}`; + return { image_url, detail }; +} + +function parseImageDetail(detail) { + if (typeof detail === "undefined") { + return undefined; + } + if (typeof detail !== "string" || !detail) { + throw new Error("codex.emitImage expected detail to be a non-empty string"); + } + if ( + detail !== "auto" && + detail !== "low" && + detail !== "high" && + detail !== "original" + ) { + throw new Error( + 'codex.emitImage expected detail to be one of "auto", "low", "high", or "original"', + ); + } + return detail; +} + +function parseInputImageItem(value) { + if (!isPlainObject(value) || value.type !== "input_image") { + return null; + } + if (typeof value.image_url !== "string" || !value.image_url) { + throw new Error("codex.emitImage expected a non-empty image_url"); + } + return { + images: [{ image_url: value.image_url, detail: parseImageDetail(value.detail) }], + textCount: 0, + }; +} + +function parseContentItems(items) { + if (!Array.isArray(items)) { + return null; + } + + const images = []; + let textCount = 0; + for (const item of items) { + if (!isPlainObject(item) || typeof item.type !== "string") { + throw new Error("codex.emitImage received malformed content items"); + } + if (item.type === "input_image") { + if (typeof item.image_url !== "string" || !item.image_url) { + throw new Error("codex.emitImage expected a non-empty image_url"); + } + images.push({ + image_url: item.image_url, + detail: parseImageDetail(item.detail), + }); + continue; + } + if (item.type === "input_text" || item.type === "output_text") { + textCount += 1; + continue; + } + throw new Error( + `codex.emitImage does not support content item type "${item.type}"`, + ); + } + + return { images, textCount }; +} + +function parseByteImageValue(value) { + if (!isPlainObject(value) || !("bytes" in value)) { + return null; + } + const bytes = toByteArray(value.bytes); + if (!bytes) { + throw new Error( + "codex.emitImage expected bytes to be Buffer, Uint8Array, ArrayBuffer, or ArrayBufferView", + ); + } + const detail = parseImageDetail(value.detail); + return encodeByteImage(bytes, value.mimeType, detail); +} + +function parseToolOutput(output) { + if (typeof output === "string") { + return { + images: [], + textCount: output.length > 0 ? 1 : 0, + }; + } + + const parsedItems = parseContentItems(output); + if (parsedItems) { + return parsedItems; + } + + throw new Error("codex.emitImage received an unsupported tool output shape"); +} + +function normalizeMcpImageData(data, mimeType) { + if (typeof data !== "string" || !data) { + throw new Error("codex.emitImage expected MCP image data"); + } + if (data.startsWith("data:")) { + return data; + } + const normalizedMimeType = + typeof mimeType === "string" && mimeType ? mimeType : "application/octet-stream"; + return `data:${normalizedMimeType};base64,${data}`; +} + +function parseMcpToolResult(result) { + if (typeof result === "string") { + return { images: [], textCount: result.length > 0 ? 1 : 0 }; + } + + if (!isPlainObject(result)) { + throw new Error("codex.emitImage received an unsupported MCP result"); + } + + if ("Err" in result) { + const error = result.Err; + return { images: [], textCount: typeof error === "string" && error ? 1 : 0 }; + } + + if (!("Ok" in result)) { + throw new Error("codex.emitImage received an unsupported MCP result"); + } + + const ok = result.Ok; + if (!isPlainObject(ok) || !Array.isArray(ok.content)) { + throw new Error("codex.emitImage received malformed MCP content"); + } + + const images = []; + let textCount = 0; + for (const item of ok.content) { + if (!isPlainObject(item) || typeof item.type !== "string") { + throw new Error("codex.emitImage received malformed MCP content"); + } + if (item.type === "image") { + images.push({ + image_url: normalizeMcpImageData(item.data, item.mimeType ?? item.mime_type), + }); + continue; + } + if (item.type === "text") { + textCount += 1; + continue; + } + throw new Error( + `codex.emitImage does not support MCP content type "${item.type}"`, + ); + } + + return { images, textCount }; +} + +function requireSingleImage(parsed) { + if (parsed.textCount > 0) { + throw new Error("codex.emitImage does not accept mixed text and image content"); + } + if (parsed.images.length !== 1) { + throw new Error("codex.emitImage expected exactly one image"); + } + return parsed.images[0]; +} + +function normalizeEmitImageValue(value) { + if (typeof value === "string") { + if (!value) { + throw new Error("codex.emitImage expected a non-empty image URL"); + } + return { image_url: value }; + } + + const directItem = parseInputImageItem(value); + if (directItem) { + return requireSingleImage(directItem); + } + + const byteImage = parseByteImageValue(value); + if (byteImage) { + return byteImage; + } + + const directItems = parseContentItems(value); + if (directItems) { + return requireSingleImage(directItems); + } + + if (!isPlainObject(value)) { + throw new Error("codex.emitImage received an unsupported value"); + } + + if (value.type === "message") { + return requireSingleImage(parseContentItems(value.content)); + } + + if ( + value.type === "function_call_output" || + value.type === "custom_tool_call_output" + ) { + return requireSingleImage(parseToolOutput(value.output)); + } + + if (value.type === "mcp_tool_call_output") { + return requireSingleImage(parseMcpToolResult(value.result)); + } + + if ("output" in value) { + return requireSingleImage(parseToolOutput(value.output)); + } + + if ("content" in value) { + return requireSingleImage(parseContentItems(value.content)); + } + + throw new Error("codex.emitImage received an unsupported value"); +} + async function handleExec(message) { activeExecId = message.id; + const pendingBackgroundTasks = new Set(); const tool = (toolName, args) => { if (typeof toolName !== "string" || !toolName) { return Promise.reject(new Error("codex.tool expects a tool name string")); @@ -512,13 +762,57 @@ async function handleExec(message) { }); }); }; + const emitImage = (imageLike) => { + const operation = (async () => { + const normalized = normalizeEmitImageValue(await imageLike); + const id = `${message.id}-emit-image-${emitImageCounter++}`; + const payload = { + type: "emit_image", + id, + exec_id: message.id, + image_url: normalized.image_url, + detail: normalized.detail ?? null, + }; + send(payload); + return new Promise((resolve, reject) => { + pendingEmitImage.set(id, (res) => { + if (!res.ok) { + reject(new Error(res.error || "emitImage failed")); + return; + } + resolve(); + }); + }); + })(); + + const observation = { observed: false }; + const trackedOperation = operation.then( + () => ({ ok: true, error: null, observation }), + (error) => ({ ok: false, error, observation }), + ); + pendingBackgroundTasks.add(trackedOperation); + return { + then(onFulfilled, onRejected) { + observation.observed = true; + return operation.then(onFulfilled, onRejected); + }, + catch(onRejected) { + observation.observed = true; + return operation.catch(onRejected); + }, + finally(onFinally) { + observation.observed = true; + return operation.finally(onFinally); + }, + }; + }; try { const code = typeof message.code === "string" ? message.code : ""; const { source, nextBindings } = await buildModuleSource(code); let output = ""; - context.codex = { tmpDir, tool }; + context.codex = { tmpDir, tool, emitImage }; context.tmpDir = tmpDir; await withCapturedConsole(context, async (logs) => { @@ -558,6 +852,15 @@ async function handleExec(message) { }); await module.evaluate(); + if (pendingBackgroundTasks.size > 0) { + const backgroundResults = await Promise.all([...pendingBackgroundTasks]); + const firstUnhandledBackgroundError = backgroundResults.find( + (result) => !result.ok && !result.observation.observed, + ); + if (firstUnhandledBackgroundError) { + throw firstUnhandledBackgroundError.error; + } + } previousModule = module; previousBindings = nextBindings; output = logs.join("\n"); @@ -593,6 +896,14 @@ function handleToolResult(message) { } } +function handleEmitImageResult(message) { + const resolver = pendingEmitImage.get(message.id); + if (resolver) { + pendingEmitImage.delete(message.id); + resolver(message); + } +} + let queue = Promise.resolve(); process.on("uncaughtException", (error) => { @@ -622,5 +933,9 @@ input.on("line", (line) => { } if (message.type === "run_tool_result") { handleToolResult(message); + return; + } + if (message.type === "emit_image_result") { + handleEmitImageResult(message); } }); diff --git a/codex-rs/core/src/tools/js_repl/mod.rs b/codex-rs/core/src/tools/js_repl/mod.rs index ea9f42ce63..a8a9123073 100644 --- a/codex-rs/core/src/tools/js_repl/mod.rs +++ b/codex-rs/core/src/tools/js_repl/mod.rs @@ -12,6 +12,7 @@ use codex_protocol::ThreadId; use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ImageDetail; use codex_protocol::models::ResponseInputItem; use serde::Deserialize; use serde::Serialize; @@ -35,6 +36,7 @@ use crate::codex::Session; use crate::codex::TurnContext; use crate::exec::ExecExpiration; use crate::exec_env::create_env; +use crate::features::Feature; use crate::function_tool::FunctionCallError; use crate::sandboxing::CommandSpec; use crate::sandboxing::SandboxManager; @@ -372,18 +374,14 @@ impl JsReplManager { Some(state.cancel.clone()) } - async fn record_exec_tool_call_content_items( + async fn record_exec_content_item( exec_tool_calls: &Arc>>, exec_id: &str, - content_items: Vec, + content_item: FunctionCallOutputContentItem, ) { - if content_items.is_empty() { - return; - } - let mut calls = exec_tool_calls.lock().await; if let Some(state) = calls.get_mut(exec_id) { - state.content_items.extend(content_items); + state.content_items.push(content_item); } } @@ -1131,6 +1129,49 @@ impl JsReplManager { exec_contexts.lock().await.remove(&id); JsReplManager::clear_exec_tool_calls_map(&exec_tool_calls, &id).await; } + KernelToHost::EmitImage(req) => { + let exec_id = req.exec_id.clone(); + let emit_id = req.id.clone(); + let response = + if let Some(ctx) = exec_contexts.lock().await.get(&exec_id).cloned() { + let content_item = emitted_image_content_item( + ctx.turn.as_ref(), + req.image_url, + req.detail, + ); + JsReplManager::record_exec_content_item( + &exec_tool_calls, + &exec_id, + content_item, + ) + .await; + HostToKernel::EmitImageResult(EmitImageResult { + id: emit_id, + ok: true, + error: None, + }) + } else { + HostToKernel::EmitImageResult(EmitImageResult { + id: emit_id, + ok: false, + error: Some("js_repl exec context not found".to_string()), + }) + }; + + if let Err(err) = JsReplManager::write_message(&stdin, &response).await { + let snapshot = + JsReplManager::kernel_debug_snapshot(&child, &recent_stderr).await; + warn!( + exec_id = %exec_id, + emit_id = %req.id, + error = %err, + kernel_pid = ?snapshot.pid, + kernel_status = %snapshot.status, + kernel_stderr_tail = %snapshot.stderr_tail, + "failed to reply to kernel emit_image request" + ); + } + } KernelToHost::RunTool(req) => { let Some(reset_cancel) = JsReplManager::begin_exec_tool_call(&exec_tool_calls, &req.exec_id).await @@ -1176,11 +1217,7 @@ impl JsReplManager { response: None, error: Some("js_repl execution reset".to_string()), }, - result = JsReplManager::run_tool_request( - ctx, - req, - Arc::clone(&exec_tool_calls_for_task), - ) => result, + result = JsReplManager::run_tool_request(ctx, req) => result, } } None => RunToolResult { @@ -1274,11 +1311,7 @@ impl JsReplManager { } } - async fn run_tool_request( - exec: ExecContext, - req: RunToolRequest, - exec_tool_calls: Arc>>, - ) -> RunToolResult { + async fn run_tool_request(exec: ExecContext, req: RunToolRequest) -> RunToolResult { if is_js_repl_internal_tool(&req.tool_name) { let error = "js_repl cannot invoke itself".to_string(); let summary = Self::summarize_tool_call_error(&error); @@ -1351,15 +1384,6 @@ impl JsReplManager { .await { Ok(response) => { - if let Some(items) = response_content_items(&response) { - Self::record_exec_tool_call_content_items( - &exec_tool_calls, - &req.exec_id, - items, - ) - .await; - } - let summary = Self::summarize_tool_call_response(&response); match serde_json::to_value(response) { Ok(value) => { @@ -1432,24 +1456,23 @@ impl JsReplManager { } } -fn response_content_items( - response: &ResponseInputItem, -) -> Option> { - match response { - ResponseInputItem::FunctionCallOutput { output, .. } - | ResponseInputItem::CustomToolCallOutput { output, .. } => output - .content_items() - .map(<[FunctionCallOutputContentItem]>::to_vec), - ResponseInputItem::McpToolCallOutput { result, .. } => match result { - Ok(result) => FunctionCallOutputPayload::from(result) - .content_items() - .map(<[FunctionCallOutputContentItem]>::to_vec), - Err(_) => None, - }, - ResponseInputItem::Message { .. } => None, +fn emitted_image_content_item( + turn: &TurnContext, + image_url: String, + detail: Option, +) -> FunctionCallOutputContentItem { + FunctionCallOutputContentItem::InputImage { + image_url, + detail: detail.or_else(|| default_output_image_detail_for_turn(turn)), } } +fn default_output_image_detail_for_turn(turn: &TurnContext) -> Option { + (turn.config.features.enabled(Feature::ImageDetailOriginal) + && turn.model_info.supports_image_detail_original) + .then_some(ImageDetail::Original) +} + fn build_exec_result_content_items( output: String, content_items: Vec, @@ -1497,6 +1520,7 @@ enum KernelToHost { error: Option, }, RunTool(RunToolRequest), + EmitImage(EmitImageRequest), } #[derive(Clone, Debug, Serialize)] @@ -1509,6 +1533,7 @@ enum HostToKernel { timeout_ms: Option, }, RunToolResult(RunToolResult), + EmitImageResult(EmitImageResult), } #[derive(Clone, Debug, Deserialize)] @@ -1529,6 +1554,23 @@ struct RunToolResult { error: Option, } +#[derive(Clone, Debug, Deserialize)] +struct EmitImageRequest { + id: String, + exec_id: String, + image_url: String, + #[serde(default)] + detail: Option, +} + +#[derive(Clone, Debug, Serialize)] +struct EmitImageResult { + id: String, + ok: bool, + #[serde(default)] + error: Option, +} + #[derive(Debug)] enum ExecResultMessage { Ok { @@ -1667,6 +1709,7 @@ mod tests { use super::*; use crate::codex::make_session_and_context; use crate::codex::make_session_and_context_with_dynamic_tools_and_rx; + use crate::features::Feature; use crate::protocol::AskForApproval; use crate::protocol::EventMsg; use crate::protocol::SandboxPolicy; @@ -1676,6 +1719,7 @@ mod tests { use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; + use codex_protocol::models::ImageDetail; use codex_protocol::models::ResponseInputItem; use codex_protocol::openai_models::InputModality; use pretty_assertions::assert_eq; @@ -1923,6 +1967,43 @@ mod tests { ); } + #[tokio::test] + async fn emitted_image_content_item_preserves_explicit_detail() { + let (_session, turn) = make_session_and_context().await; + let content_item = emitted_image_content_item( + &turn, + "data:image/png;base64,AAA".to_string(), + Some(ImageDetail::Low), + ); + assert_eq!( + content_item, + FunctionCallOutputContentItem::InputImage { + image_url: "data:image/png;base64,AAA".to_string(), + detail: Some(ImageDetail::Low), + } + ); + } + + #[tokio::test] + async fn emitted_image_content_item_uses_turn_original_detail_when_enabled() { + let (_session, mut turn) = make_session_and_context().await; + Arc::make_mut(&mut turn.config) + .features + .enable(Feature::ImageDetailOriginal); + turn.model_info.supports_image_detail_original = true; + + let content_item = + emitted_image_content_item(&turn, "data:image/png;base64,AAA".to_string(), None); + + assert_eq!( + content_item, + FunctionCallOutputContentItem::InputImage { + image_url: "data:image/png;base64,AAA".to_string(), + detail: Some(ImageDetail::Original), + } + ); + } + #[test] fn summarize_tool_call_response_for_multimodal_custom_output() { let response = ResponseInputItem::CustomToolCallOutput { @@ -2361,7 +2442,7 @@ console.log("cell-complete"); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn js_repl_can_attach_image_via_view_image_tool() -> anyhow::Result<()> { + async fn js_repl_does_not_auto_attach_image_via_view_image_tool() -> anyhow::Result<()> { if !can_run_js_repl_runtime_tests().await { return Ok(()); } @@ -2398,7 +2479,65 @@ const png = Buffer.from( await fs.writeFile(imagePath, png); const out = await codex.tool("view_image", { path: imagePath }); console.log(out.type); -console.log(out.output?.body?.text ?? ""); +"#; + + let result = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await?; + assert!(result.output.contains("function_call_output")); + assert!(result.content_items.is_empty()); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_can_emit_image_via_view_image_tool() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, mut turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + turn.approval_policy + .set(AskForApproval::Never) + .expect("test setup should allow updating approval policy"); + turn.sandbox_policy + .set(SandboxPolicy::DangerFullAccess) + .expect("test setup should allow updating sandbox policy"); + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +const fs = await import("node:fs/promises"); +const path = await import("node:path"); +const imagePath = path.join(codex.tmpDir, "js-repl-view-image-explicit.png"); +const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", + "base64" +); +await fs.writeFile(imagePath, png); +const out = await codex.tool("view_image", { path: imagePath }); +await codex.emitImage(out); +console.log(out.type); "#; let result = manager @@ -2423,20 +2562,374 @@ console.log(out.output?.body?.text ?? ""); }] .as_slice() ); - let [FunctionCallOutputContentItem::InputImage { image_url, detail }] = - result.content_items.as_slice() - else { - panic!("view_image should return exactly one input_image content item"); - }; - assert!(image_url.starts_with("data:image/png;base64,")); - assert_eq!(*detail, None); assert!(session.get_pending_input().await.is_empty()); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn js_repl_can_attach_image_via_dynamic_tool_with_mixed_content() -> anyhow::Result<()> { + async fn js_repl_can_emit_image_from_bytes_and_mime_type() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", + "base64" +); +await codex.emitImage({ bytes: png, mimeType: "image/png" }); +"#; + + let result = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await?; + assert_eq!( + result.content_items.as_slice(), + [FunctionCallOutputContentItem::InputImage { + image_url: + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" + .to_string(), + detail: None, + }] + .as_slice() + ); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_can_emit_multiple_images_in_one_cell() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +await codex.emitImage( + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" +); +await codex.emitImage( + "data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=" +); +"#; + + let result = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await?; + assert_eq!( + result.content_items.as_slice(), + [ + FunctionCallOutputContentItem::InputImage { + image_url: + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" + .to_string(), + detail: None, + }, + FunctionCallOutputContentItem::InputImage { + image_url: + "data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=" + .to_string(), + detail: None, + }, + ] + .as_slice() + ); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_waits_for_unawaited_emit_image_before_completion() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +void codex.emitImage( + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" +); +console.log("cell-complete"); +"#; + + let result = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await?; + assert!(result.output.contains("cell-complete")); + assert_eq!( + result.content_items.as_slice(), + [FunctionCallOutputContentItem::InputImage { + image_url: + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" + .to_string(), + detail: None, + }] + .as_slice() + ); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_unawaited_emit_image_errors_fail_cell() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +void codex.emitImage({ bytes: new Uint8Array(), mimeType: "image/png" }); +console.log("cell-complete"); +"#; + + let err = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await + .expect_err("unawaited invalid emitImage should fail"); + assert!(err.to_string().contains("expected non-empty bytes")); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_caught_emit_image_error_does_not_fail_cell() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +try { + await codex.emitImage({ bytes: new Uint8Array(), mimeType: "image/png" }); +} catch (error) { + console.log(error.message); +} +console.log("cell-complete"); +"#; + + let result = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await?; + assert!(result.output.contains("expected non-empty bytes")); + assert!(result.output.contains("cell-complete")); + assert!(result.content_items.is_empty()); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_emit_image_requires_explicit_mime_type_for_bytes() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", + "base64" +); +await codex.emitImage({ bytes: png }); +"#; + + let err = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await + .expect_err("missing mimeType should fail"); + assert!(err.to_string().contains("expected a non-empty mimeType")); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_emit_image_rejects_invalid_detail() -> anyhow::Result<()> { + if !can_run_js_repl_runtime_tests().await { + return Ok(()); + } + + let (session, turn) = make_session_and_context().await; + if !turn + .model_info + .input_modalities + .contains(&InputModality::Image) + { + return Ok(()); + } + + let session = Arc::new(session); + let turn = Arc::new(turn); + *session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::default())); + let manager = turn.js_repl.manager().await?; + let code = r#" +const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", + "base64" +); +await codex.emitImage({ bytes: png, mimeType: "image/png", detail: "ultra" }); +"#; + + let err = manager + .execute( + Arc::clone(&session), + turn, + tracker, + JsReplArgs { + code: code.to_string(), + timeout_ms: Some(15_000), + }, + ) + .await + .expect_err("invalid detail should fail"); + assert!(err.to_string().contains("expected detail to be one of")); + assert!(session.get_pending_input().await.is_empty()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn js_repl_emit_image_rejects_mixed_content() -> anyhow::Result<()> { if !can_run_js_repl_runtime_tests().await { return Ok(()); } @@ -2466,7 +2959,7 @@ console.log(out.output?.body?.text ?? ""); let manager = turn.js_repl.manager().await?; let code = r#" const out = await codex.tool("inline_image", {}); -console.log(out.type); +await codex.emitImage(out); "#; let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; @@ -2509,19 +3002,10 @@ console.log(out.type); response_watcher, ); response_watcher_result?; - let result = result?; - assert!(result.output.contains("function_call_output")); - assert_eq!( - result.content_items, - vec![ - FunctionCallOutputContentItem::InputText { - text: "inline image note".to_string(), - }, - FunctionCallOutputContentItem::InputImage { - image_url: image_url.to_string(), - detail: None, - }, - ] + let err = result.expect_err("mixed content should fail"); + assert!( + err.to_string() + .contains("does not accept mixed text and image content") ); assert!(session.get_pending_input().await.is_empty()); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index d4a8ce9f3e..d6fde7e691 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -21,7 +21,9 @@ use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; use codex_protocol::config_types::Verbosity; use codex_protocol::models::ContentItem; +use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ImageDetail; use codex_protocol::models::LocalShellAction; use codex_protocol::models::LocalShellExecAction; use codex_protocol::models::LocalShellStatus; @@ -485,6 +487,127 @@ async fn resume_replays_legacy_js_repl_image_rollout_shapes() { assert!(legacy_image_index < new_user_index); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn resume_replays_image_tool_outputs_with_detail() { + skip_if_no_network!(); + + let image_url = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEAAUAmJaACdLoB+AADsAD+8ut//NgVzXPv9//S4P0uD9Lg/9KQAAA="; + let function_call_id = "view-image-call"; + let custom_call_id = "js-repl-call"; + let rollout = vec![ + RolloutLine { + timestamp: "2024-01-01T00:00:00.000Z".to_string(), + item: RolloutItem::SessionMeta(SessionMetaLine { + meta: SessionMeta { + id: ThreadId::default(), + timestamp: "2024-01-01T00:00:00Z".to_string(), + cwd: ".".into(), + originator: "test_originator".to_string(), + cli_version: "test_version".to_string(), + model_provider: Some("test-provider".to_string()), + ..Default::default() + }, + git: None, + }), + }, + RolloutLine { + timestamp: "2024-01-01T00:00:01.000Z".to_string(), + item: RolloutItem::ResponseItem(ResponseItem::FunctionCall { + id: None, + name: "view_image".to_string(), + arguments: "{\"path\":\"/tmp/example.webp\"}".to_string(), + call_id: function_call_id.to_string(), + }), + }, + RolloutLine { + timestamp: "2024-01-01T00:00:01.500Z".to_string(), + item: RolloutItem::ResponseItem(ResponseItem::FunctionCallOutput { + call_id: function_call_id.to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url: image_url.to_string(), + detail: Some(ImageDetail::Original), + }, + ]), + }), + }, + RolloutLine { + timestamp: "2024-01-01T00:00:02.000Z".to_string(), + item: RolloutItem::ResponseItem(ResponseItem::CustomToolCall { + id: None, + status: Some("completed".to_string()), + call_id: custom_call_id.to_string(), + name: "js_repl".to_string(), + input: "console.log('image flow')".to_string(), + }), + }, + RolloutLine { + timestamp: "2024-01-01T00:00:02.500Z".to_string(), + item: RolloutItem::ResponseItem(ResponseItem::CustomToolCallOutput { + call_id: custom_call_id.to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url: image_url.to_string(), + detail: Some(ImageDetail::Original), + }, + ]), + }), + }, + ]; + + let tmpdir = TempDir::new().unwrap(); + let session_path = tmpdir + .path() + .join("resume-image-tool-outputs-with-detail.jsonl"); + let mut file = std::fs::File::create(&session_path).unwrap(); + for line in rollout { + writeln!(file, "{}", serde_json::to_string(&line).unwrap()).unwrap(); + } + + let server = MockServer::start().await; + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + + let codex_home = Arc::new(TempDir::new().unwrap()); + let mut builder = test_codex().with_model("gpt-5.1"); + let test = builder + .resume(&server, codex_home, session_path.clone()) + .await + .expect("resume conversation"); + test.submit_turn("after resume").await.unwrap(); + + let function_output = resp_mock + .single_request() + .function_call_output(function_call_id); + assert_eq!( + function_output.get("output"), + Some(&serde_json::json!([ + { + "type": "input_image", + "image_url": image_url, + "detail": "original" + } + ])) + ); + + let custom_output = resp_mock + .single_request() + .custom_tool_call_output(custom_call_id); + assert_eq!( + custom_output.get("output"), + Some(&serde_json::json!([ + { + "type": "input_image", + "image_url": image_url, + "detail": "original" + } + ])) + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_conversation_id_and_model_headers_in_request() { skip_if_no_network!(); diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index 9b73afbc1b..b56e28d020 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -494,7 +494,7 @@ async fn view_image_tool_keeps_legacy_behavior_below_gpt5_3_codex() -> anyhow::R } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn js_repl_view_image_tool_attaches_local_image() -> anyhow::Result<()> { +async fn js_repl_emit_image_attaches_local_image() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; @@ -519,7 +519,7 @@ const png = Buffer.from( ); await fs.writeFile(imagePath, png); const out = await codex.tool("view_image", { path: imagePath }); -console.log(out.output?.body?.text ?? ""); +await codex.emitImage(out); "#; let first_response = sse(vec![ @@ -555,12 +555,29 @@ console.log(out.output?.body?.text ?? ""); }) .await?; + let mut tool_event = None; wait_for_event_with_timeout( &codex, - |event| matches!(event, EventMsg::TurnComplete(_)), + |event| match event { + EventMsg::ViewImageToolCall(_) => { + tool_event = Some(event.clone()); + false + } + EventMsg::TurnComplete(_) => true, + _ => false, + }, Duration::from_secs(10), ) .await; + let tool_event = match tool_event { + Some(EventMsg::ViewImageToolCall(event)) => event, + other => panic!("expected ViewImageToolCall event, got {other:?}"), + }; + assert!( + tool_event.path.ends_with("js-repl-view-image.png"), + "unexpected image path: {}", + tool_event.path.display() + ); let req = mock.single_request(); let body = req.body_json(); @@ -591,6 +608,105 @@ console.log(out.output?.body?.text ?? ""); Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn js_repl_view_image_requires_explicit_emit() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::JsRepl); + }); + let TestCodex { + codex, + cwd, + session_configured, + .. + } = builder.build(&server).await?; + + let call_id = "js-repl-view-image-no-emit"; + let js_input = r#" +const fs = await import("node:fs/promises"); +const path = await import("node:path"); +const imagePath = path.join(codex.tmpDir, "js-repl-view-image-no-emit.png"); +const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", + "base64" +); +await fs.writeFile(imagePath, png); +const out = await codex.tool("view_image", { path: imagePath }); +console.log(out.type); +"#; + + let first_response = sse(vec![ + ev_response_created("resp-1"), + ev_custom_tool_call(call_id, "js_repl", js_input), + ev_completed("resp-1"), + ]); + responses::mount_sse_once(&server, first_response).await; + + let second_response = sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]); + let mock = responses::mount_sse_once(&server, second_response).await; + + let session_model = session_configured.model.clone(); + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "use js_repl to write an image but do not emit it".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: session_model, + effort: None, + service_tier: None, + summary: None, + collaboration_mode: None, + personality: None, + }) + .await?; + + let mut tool_event = None; + wait_for_event_with_timeout( + &codex, + |event| match event { + EventMsg::ViewImageToolCall(_) => { + tool_event = Some(event.clone()); + false + } + EventMsg::TurnComplete(_) => true, + _ => false, + }, + Duration::from_secs(10), + ) + .await; + let tool_event = match tool_event { + Some(EventMsg::ViewImageToolCall(event)) => event, + other => panic!("expected ViewImageToolCall event, got {other:?}"), + }; + assert!( + tool_event.path.ends_with("js-repl-view-image-no-emit.png"), + "unexpected image path: {}", + tool_event.path.display() + ); + + let req = mock.single_request(); + let custom_output = req.custom_tool_call_output(call_id); + let output_items = custom_output.get("output").and_then(Value::as_array); + assert!( + output_items.is_none_or(|items| items + .iter() + .all(|item| item.get("type").and_then(Value::as_str) != Some("input_image"))), + "nested view_image should not auto-populate js_repl output" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn view_image_tool_errors_when_path_is_directory() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); diff --git a/docs/js_repl.md b/docs/js_repl.md index b36da5dc08..dd33902900 100644 --- a/docs/js_repl.md +++ b/docs/js_repl.md @@ -65,8 +65,13 @@ For `CODEX_JS_REPL_NODE_MODULE_DIRS` and `js_repl_node_module_dirs`, module reso - `codex.tmpDir`: per-session scratch directory path. - `codex.tool(name, args?)`: executes a normal Codex tool call from inside `js_repl` (including shell tools like `shell` / `shell_command` when available). +- `codex.emitImage(imageLike)`: explicitly adds exactly one image to the outer `js_repl` function output. - Each `codex.tool(...)` call emits a bounded summary at `info` level from the `codex_core::tools::js_repl` logger. At `trace` level, the same path also logs the exact raw response object or error string seen by JavaScript. -- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool("view_image", { path: "/absolute/path" })`, then delete the file. +- Nested `codex.tool(...)` outputs stay inside JavaScript unless you emit them explicitly. +- `codex.emitImage(...)` accepts a direct image URL, a single `input_image` item, an object like `{ bytes, mimeType }`, or a raw tool response object that contains exactly one image and no text. +- `codex.emitImage(...)` rejects mixed text-and-image content. +- Example of sharing an in-memory Playwright screenshot: `await codex.emitImage({ bytes: await page.screenshot({ type: "jpeg", quality: 85 }), mimeType: "image/jpeg" })`. +- Example of sharing a local image tool result: `await codex.emitImage(codex.tool("view_image", { path: "/absolute/path" }))`. Avoid writing directly to `process.stdout` / `process.stderr` / `process.stdin`; the kernel uses a JSON-line transport over stdio. From 082682a62871bb14864cfabd54b88368a9830b90 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Tue, 3 Mar 2026 16:29:15 -0800 Subject: [PATCH 353/385] feat: load plugin apps (#13401) load plugin-apps from `.app.json`. make apps runtime-mentionable iff `codex_apps` MCP actually exposes tools for that `connector_id`. if the app isn't available, it's filtered out of runtime connector set, so no tools are added and no app-mentions resolve. right now we don't have a clean cli-side error for an app not being installed. can look at this after. ### Tests Added tests, tested locally that using a plugin that bundles an app picks up the app. --- codex-rs/chatgpt/src/connectors.rs | 19 ++- codex-rs/core/src/codex.rs | 21 ++- codex-rs/core/src/connectors.rs | 106 ++++++++++++ codex-rs/core/src/plugins/manager.rs | 160 ++++++++++++++++++ codex-rs/core/src/plugins/mod.rs | 1 + .../core/tests/common/apps_test_server.rs | 21 ++- codex-rs/core/tests/suite/plugins.rs | 129 ++++++++++++++ 7 files changed, 444 insertions(+), 13 deletions(-) diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index 620a93872e..81c382f5d6 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -26,7 +26,9 @@ pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_o pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status; pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools; use codex_core::connectors::merge_connectors; +use codex_core::connectors::merge_plugin_apps; pub use codex_core::connectors::with_app_enabled_state; +use codex_core::plugins::PluginsManager; #[derive(Debug, Deserialize)] struct DirectoryListResponse { @@ -106,7 +108,10 @@ pub async fn list_cached_all_connectors(config: &Config) -> Option> } let token_data = get_chatgpt_token_data()?; let cache_key = all_connectors_cache_key(config, &token_data); - read_cached_all_connectors(&cache_key).map(filter_disallowed_connectors) + read_cached_all_connectors(&cache_key).map(|connectors| { + let connectors = merge_plugin_apps(connectors, plugin_apps_for_config(config)); + filter_disallowed_connectors(connectors) + }) } pub async fn list_all_connectors_with_options( @@ -123,7 +128,8 @@ pub async fn list_all_connectors_with_options( get_chatgpt_token_data().ok_or_else(|| anyhow::anyhow!("ChatGPT token not available"))?; let cache_key = all_connectors_cache_key(config, &token_data); if !force_refetch && let Some(cached_connectors) = read_cached_all_connectors(&cache_key) { - return Ok(filter_disallowed_connectors(cached_connectors)); + let connectors = merge_plugin_apps(cached_connectors, plugin_apps_for_config(config)); + return Ok(filter_disallowed_connectors(connectors)); } let mut apps = list_directory_connectors(config).await?; @@ -151,7 +157,8 @@ pub async fn list_all_connectors_with_options( }); let connectors = filter_disallowed_connectors(connectors); write_cached_all_connectors(cache_key, &connectors); - Ok(connectors) + let connectors = merge_plugin_apps(connectors, plugin_apps_for_config(config)); + Ok(filter_disallowed_connectors(connectors)) } fn all_connectors_cache_key(config: &Config, token_data: &TokenData) -> AllConnectorsCacheKey { @@ -192,6 +199,12 @@ fn write_cached_all_connectors(cache_key: AllConnectorsCacheKey, connectors: &[A }); } +fn plugin_apps_for_config(config: &Config) -> Vec { + PluginsManager::new(config.codex_home.clone()) + .plugins_for_config(config) + .effective_apps() +} + pub fn merge_connectors_with_accessible( connectors: Vec, accessible_connectors: Vec, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 7736aa1280..1ead1871f5 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -4891,10 +4891,15 @@ pub(crate) async fn run_turn( Ok(mcp_tools) => mcp_tools, Err(_) => return None, }; - connectors::with_app_enabled_state( + let plugin_apps = sess + .services + .plugins_manager + .plugins_for_config(&turn_context.config); + let connectors = connectors::merge_plugin_apps_with_accessible( + plugin_apps.effective_apps(), connectors::accessible_connectors_from_mcp_tools(&mcp_tools), - &turn_context.config, - ) + ); + connectors::with_app_enabled_state(connectors, &turn_context.config) } else { Vec::new() }; @@ -5614,8 +5619,16 @@ async fn built_tools( effective_explicitly_enabled_connectors.extend(sess.get_connector_selection().await); let connectors = if turn_context.features.enabled(Feature::Apps) { - Some(connectors::with_app_enabled_state( + let plugin_apps = sess + .services + .plugins_manager + .plugins_for_config(&turn_context.config); + let connectors = connectors::merge_plugin_apps_with_accessible( + plugin_apps.effective_apps(), connectors::accessible_connectors_from_mcp_tools(&mcp_tools), + ); + Some(connectors::with_app_enabled_state( + connectors, &turn_context.config, )) } else { diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index 33b003770e..3ad48fa008 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::collections::HashSet; use std::env; use std::path::PathBuf; use std::sync::LazyLock; @@ -29,6 +30,7 @@ use crate::mcp::auth::compute_auth_statuses; use crate::mcp::with_codex_apps_mcp; use crate::mcp_connection_manager::McpConnectionManager; use crate::mcp_connection_manager::codex_apps_tools_cache_key; +use crate::plugins::AppConnectorId; use crate::token_data::TokenData; pub const CONNECTORS_CACHE_TTL: Duration = Duration::from_secs(3600); @@ -353,6 +355,48 @@ pub fn merge_connectors( merged } +pub fn merge_plugin_apps( + connectors: Vec, + plugin_apps: Vec, +) -> Vec { + let mut merged = connectors; + let mut connector_ids = merged + .iter() + .map(|connector| connector.id.clone()) + .collect::>(); + + for connector_id in plugin_apps { + if connector_ids.insert(connector_id.0.clone()) { + merged.push(plugin_app_to_app_info(connector_id)); + } + } + + merged.sort_by(|left, right| { + right + .is_accessible + .cmp(&left.is_accessible) + .then_with(|| left.name.cmp(&right.name)) + .then_with(|| left.id.cmp(&right.id)) + }); + merged +} + +pub fn merge_plugin_apps_with_accessible( + plugin_apps: Vec, + accessible_connectors: Vec, +) -> Vec { + let accessible_connector_ids: HashSet<&str> = accessible_connectors + .iter() + .map(|connector| connector.id.as_str()) + .collect(); + let plugin_connectors = plugin_apps + .into_iter() + .filter(|connector_id| accessible_connector_ids.contains(connector_id.0.as_str())) + .map(plugin_app_to_app_info) + .collect::>(); + merge_connectors(plugin_connectors, accessible_connectors) +} + pub fn with_app_enabled_state(mut connectors: Vec, config: &Config) -> Vec { let apps_config = read_apps_config(config); if let Some(apps_config) = apps_config.as_ref() { @@ -575,6 +619,28 @@ where accessible } +fn plugin_app_to_app_info(connector_id: AppConnectorId) -> AppInfo { + // Leave the placeholder name as the connector id so merge_connectors() can + // replace it with canonical app metadata from directory fetches or + // connector_name values from codex_apps tool discovery. + let connector_id = connector_id.0; + let name = connector_id.clone(); + AppInfo { + id: connector_id.clone(), + name: name.clone(), + description: None, + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: Some(connector_install_url(&name, &connector_id)), + is_accessible: false, + is_enabled: true, + } +} + fn normalize_connector_value(value: Option<&str>) -> Option { value .map(str::trim) @@ -647,6 +713,46 @@ mod tests { } } + #[test] + fn merge_connectors_replaces_plugin_placeholder_name_with_accessible_name() { + let plugin = plugin_app_to_app_info(AppConnectorId("calendar".to_string())); + let accessible = AppInfo { + id: "calendar".to_string(), + name: "Google Calendar".to_string(), + description: Some("Plan events".to_string()), + logo_url: Some("https://example.com/logo.png".to_string()), + logo_url_dark: Some("https://example.com/logo-dark.png".to_string()), + distribution_channel: Some("workspace".to_string()), + branding: None, + app_metadata: None, + labels: None, + install_url: None, + is_accessible: true, + is_enabled: true, + }; + + let merged = merge_connectors(vec![plugin], vec![accessible]); + + assert_eq!( + merged, + vec![AppInfo { + id: "calendar".to_string(), + name: "Google Calendar".to_string(), + description: Some("Plan events".to_string()), + logo_url: Some("https://example.com/logo.png".to_string()), + logo_url_dark: Some("https://example.com/logo-dark.png".to_string()), + distribution_channel: Some("workspace".to_string()), + branding: None, + app_metadata: None, + labels: None, + install_url: Some(connector_install_url("calendar", "calendar")), + is_accessible: true, + is_enabled: true, + }] + ); + assert_eq!(connector_mention_slug(&merged[0]), "google-calendar"); + } + #[test] fn app_tool_policy_uses_global_defaults_for_destructive_hints() { let apps_config = AppsConfigToml { diff --git a/codex-rs/core/src/plugins/manager.rs b/codex-rs/core/src/plugins/manager.rs index d98c4379ff..c5a7b894af 100644 --- a/codex-rs/core/src/plugins/manager.rs +++ b/codex-rs/core/src/plugins/manager.rs @@ -33,6 +33,10 @@ use tracing::warn; const DEFAULT_SKILLS_DIR_NAME: &str = "skills"; const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json"; +const DEFAULT_APP_CONFIG_FILE: &str = ".app.json"; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct AppConnectorId(pub String); #[derive(Debug, Clone, PartialEq)] pub struct LoadedPlugin { @@ -42,6 +46,7 @@ pub struct LoadedPlugin { pub enabled: bool, pub skill_roots: Vec, pub mcp_servers: HashMap, + pub apps: Vec, pub error: Option, } @@ -80,6 +85,21 @@ impl PluginLoadOutcome { } mcp_servers } + + pub fn effective_apps(&self) -> Vec { + let mut apps = Vec::new(); + let mut seen_connector_ids = std::collections::HashSet::new(); + + for plugin in self.plugins.iter().filter(|plugin| plugin.is_active()) { + for connector_id in &plugin.apps { + if seen_connector_ids.insert(connector_id.clone()) { + apps.push(connector_id.clone()); + } + } + } + + apps + } } pub struct PluginsManager { @@ -227,6 +247,18 @@ struct PluginMcpFile { mcp_servers: HashMap, } +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct PluginAppFile { + #[serde(default)] + apps: HashMap, +} + +#[derive(Debug, Default, Deserialize)] +struct PluginAppConfig { + id: String, +} + pub(crate) fn load_plugins_from_layer_stack( config_layer_stack: &ConfigLayerStack, store: &PluginStore, @@ -299,6 +331,7 @@ fn load_plugin(config_name: String, plugin: &PluginConfig, store: &PluginStore) enabled: plugin.enabled, skill_roots: Vec::new(), mcp_servers: HashMap::new(), + apps: Vec::new(), error: None, }; @@ -341,6 +374,10 @@ fn load_plugin(config_name: String, plugin: &PluginConfig, store: &PluginStore) } } loaded_plugin.mcp_servers = mcp_servers; + loaded_plugin.apps = load_apps_from_file( + plugin_root.as_path(), + &plugin_root.as_path().join(DEFAULT_APP_CONFIG_FILE), + ); loaded_plugin } @@ -364,6 +401,39 @@ fn default_mcp_config_paths(plugin_root: &Path) -> Vec { paths } +fn load_apps_from_file(plugin_root: &Path, app_config_path: &Path) -> Vec { + let Ok(contents) = fs::read_to_string(app_config_path) else { + return Vec::new(); + }; + let parsed = match serde_json::from_str::(&contents) { + Ok(parsed) => parsed, + Err(err) => { + warn!( + path = %app_config_path.display(), + "failed to parse plugin app config: {err}" + ); + return Vec::new(); + } + }; + + let mut apps: Vec = parsed.apps.into_values().collect(); + apps.sort_unstable_by(|left, right| left.id.cmp(&right.id)); + + apps.into_iter() + .filter_map(|app| { + if app.id.trim().is_empty() { + warn!( + plugin = %plugin_root.display(), + "plugin app config is missing an app id" + ); + None + } else { + Some(AppConnectorId(app.id)) + } + }) + .collect() +} + fn load_mcp_servers_from_file(plugin_root: &Path, mcp_config_path: &Path) -> PluginMcpDiscovery { let Ok(contents) = fs::read_to_string(mcp_config_path) else { return PluginMcpDiscovery::default(); @@ -550,6 +620,16 @@ mod tests { } }"#, ); + write_file( + &plugin_root.join(".app.json"), + r#"{ + "apps": { + "example": { + "id": "connector_example" + } + } +}"#, + ); let outcome = load_plugins_from_config(&plugin_config_toml(true, true), codex_home.path()).await; @@ -582,6 +662,7 @@ mod tests { oauth_resource: None, }, )]), + apps: vec![AppConnectorId("connector_example".to_string())], error: None, }] ); @@ -590,6 +671,10 @@ mod tests { vec![plugin_root.join("skills")] ); assert_eq!(outcome.effective_mcp_servers().len(), 1); + assert_eq!( + outcome.effective_apps(), + vec![AppConnectorId("connector_example".to_string())] + ); } #[tokio::test] @@ -628,6 +713,7 @@ mod tests { enabled: false, skill_roots: Vec::new(), mcp_servers: HashMap::new(), + apps: Vec::new(), error: None, }] ); @@ -635,6 +721,80 @@ mod tests { assert!(outcome.effective_mcp_servers().is_empty()); } + #[tokio::test] + async fn effective_apps_dedupes_connector_ids_across_plugins() { + let codex_home = TempDir::new().unwrap(); + let plugin_a_root = codex_home + .path() + .join("plugins/cache") + .join("test/plugin-a/local"); + let plugin_b_root = codex_home + .path() + .join("plugins/cache") + .join("test/plugin-b/local"); + + write_file( + &plugin_a_root.join(".codex-plugin/plugin.json"), + r#"{"name":"plugin-a"}"#, + ); + write_file( + &plugin_a_root.join(".app.json"), + r#"{ + "apps": { + "example": { + "id": "connector_example" + } + } +}"#, + ); + write_file( + &plugin_b_root.join(".codex-plugin/plugin.json"), + r#"{"name":"plugin-b"}"#, + ); + write_file( + &plugin_b_root.join(".app.json"), + r#"{ + "apps": { + "chat": { + "id": "connector_example" + }, + "gmail": { + "id": "connector_gmail" + } + } +}"#, + ); + + let mut root = toml::map::Map::new(); + let mut features = toml::map::Map::new(); + features.insert("plugins".to_string(), Value::Boolean(true)); + root.insert("features".to_string(), Value::Table(features)); + + let mut plugins = toml::map::Map::new(); + + let mut plugin_a = toml::map::Map::new(); + plugin_a.insert("enabled".to_string(), Value::Boolean(true)); + plugins.insert("plugin-a@test".to_string(), Value::Table(plugin_a)); + + let mut plugin_b = toml::map::Map::new(); + plugin_b.insert("enabled".to_string(), Value::Boolean(true)); + plugins.insert("plugin-b@test".to_string(), Value::Table(plugin_b)); + + root.insert("plugins".to_string(), Value::Table(plugins)); + let config_toml = + toml::to_string(&Value::Table(root)).expect("plugin test config should serialize"); + + let outcome = load_plugins_from_config(&config_toml, codex_home.path()).await; + + assert_eq!( + outcome.effective_apps(), + vec![ + AppConnectorId("connector_example".to_string()), + AppConnectorId("connector_gmail".to_string()), + ] + ); + } + #[test] fn plugin_namespace_for_skill_path_uses_manifest_name() { let codex_home = TempDir::new().unwrap(); diff --git a/codex-rs/core/src/plugins/mod.rs b/codex-rs/core/src/plugins/mod.rs index faf0a8dd0c..37b4009bc0 100644 --- a/codex-rs/core/src/plugins/mod.rs +++ b/codex-rs/core/src/plugins/mod.rs @@ -2,6 +2,7 @@ mod manager; mod manifest; mod store; +pub use manager::AppConnectorId; pub use manager::LoadedPlugin; pub use manager::PluginInstallError; pub use manager::PluginLoadOutcome; diff --git a/codex-rs/core/tests/common/apps_test_server.rs b/codex-rs/core/tests/common/apps_test_server.rs index c562e390e1..1160a125a1 100644 --- a/codex-rs/core/tests/common/apps_test_server.rs +++ b/codex-rs/core/tests/common/apps_test_server.rs @@ -23,8 +23,15 @@ pub struct AppsTestServer { impl AppsTestServer { pub async fn mount(server: &MockServer) -> Result { + Self::mount_with_connector_name(server, CONNECTOR_NAME).await + } + + pub async fn mount_with_connector_name( + server: &MockServer, + connector_name: &str, + ) -> Result { mount_oauth_metadata(server).await; - mount_streamable_http_json_rpc(server).await; + mount_streamable_http_json_rpc(server, connector_name.to_string()).await; Ok(Self { chatgpt_base_url: server.uri(), }) @@ -43,15 +50,17 @@ async fn mount_oauth_metadata(server: &MockServer) { .await; } -async fn mount_streamable_http_json_rpc(server: &MockServer) { +async fn mount_streamable_http_json_rpc(server: &MockServer, connector_name: String) { Mock::given(method("POST")) .and(path_regex("^/api/codex/apps/?$")) - .respond_with(CodexAppsJsonRpcResponder) + .respond_with(CodexAppsJsonRpcResponder { connector_name }) .mount(server) .await; } -struct CodexAppsJsonRpcResponder; +struct CodexAppsJsonRpcResponder { + connector_name: String, +} impl Respond for CodexAppsJsonRpcResponder { fn respond(&self, request: &Request) -> ResponseTemplate { @@ -117,7 +126,7 @@ impl Respond for CodexAppsJsonRpcResponder { }, "_meta": { "connector_id": CONNECTOR_ID, - "connector_name": CONNECTOR_NAME + "connector_name": self.connector_name.clone() } }, { @@ -133,7 +142,7 @@ impl Respond for CodexAppsJsonRpcResponder { }, "_meta": { "connector_id": CONNECTOR_ID, - "connector_name": CONNECTOR_NAME + "connector_name": self.connector_name.clone() } } ], diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index 3e641d010d..12d81402c8 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -7,11 +7,14 @@ use std::time::Instant; use anyhow::Result; use codex_core::CodexAuth; +use codex_core::features::Feature; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; +use core_test_support::apps_test_server::AppsTestServer; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_once; +use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; @@ -74,6 +77,35 @@ fn write_plugin_mcp_plugin(home: &TempDir, command: &str) { .expect("write config"); } +fn write_plugin_app_plugin(home: &TempDir) { + let plugin_root = home.path().join("plugins/sample"); + std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); + std::fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ) + .expect("write plugin manifest"); + std::fs::write( + plugin_root.join(".app.json"), + r#"{ + "apps": { + "calendar": { + "id": "calendar" + } + } +}"#, + ) + .expect("write plugin app config"); + std::fs::write( + home.path().join("config.toml"), + format!( + "[features]\nplugins = true\n\n[plugins.sample]\nenabled = true\npath = \"{}\"\n", + plugin_root.display() + ), + ) + .expect("write config"); +} + async fn build_plugin_test_codex( server: &MockServer, codex_home: Arc, @@ -88,6 +120,23 @@ async fn build_plugin_test_codex( .codex) } +fn tool_names(body: &serde_json::Value) -> Vec { + body.get("tools") + .and_then(serde_json::Value::as_array) + .map(|tools| { + tools + .iter() + .filter_map(|tool| { + tool.get("name") + .or_else(|| tool.get("type")) + .and_then(serde_json::Value::as_str) + .map(str::to_string) + }) + .collect() + }) + .unwrap_or_default() +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn plugin_skills_append_to_instructions() -> Result<()> { skip_if_no_network!(Ok(())); @@ -138,6 +187,86 @@ async fn plugin_skills_append_to_instructions() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plugin_apps_expose_tools_after_canonical_name_mention() -> Result<()> { + skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let apps_server = AppsTestServer::mount_with_connector_name(&server, "Google Calendar").await?; + let mock = mount_sse_sequence( + &server, + vec![ + sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), + sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]), + ], + ) + .await; + + let codex_home = Arc::new(TempDir::new()?); + write_plugin_app_plugin(codex_home.as_ref()); + let mut builder = test_codex() + .with_home(codex_home) + .with_auth(CodexAuth::from_api_key("Test API Key")) + .with_config(move |config| { + config.features.enable(Feature::Apps); + config.features.disable(Feature::AppsMcpGateway); + config.chatgpt_base_url = apps_server.chatgpt_base_url; + }); + let codex = builder + .build(&server) + .await + .expect("create new conversation") + .codex; + + codex + .submit(Op::UserInput { + items: vec![codex_protocol::user_input::UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + codex + .submit(Op::UserInput { + items: vec![codex_protocol::user_input::UserInput::Text { + text: "Use $google-calendar and then call tools.".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let requests = mock.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let first_tools = tool_names(&requests[0].body_json()); + assert!( + !first_tools + .iter() + .any(|name| name == "mcp__codex_apps__calendar_create_event"), + "app tools should stay hidden before plugin app mention: {first_tools:?}" + ); + + let second_tools = tool_names(&requests[1].body_json()); + assert!( + second_tools + .iter() + .any(|name| name == "mcp__codex_apps__calendar_create_event"), + "calendar create tool should be available after plugin app mention: {second_tools:?}" + ); + assert!( + second_tools + .iter() + .any(|name| name == "mcp__codex_apps__calendar_list_events"), + "calendar list tool should be available after plugin app mention: {second_tools:?}" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn plugin_mcp_tools_are_listed() -> Result<()> { skip_if_no_network!(Ok(())); From e951ef43741628a4835dceaf61df297c504b7281 Mon Sep 17 00:00:00 2001 From: rhan-oai Date: Tue, 3 Mar 2026 16:34:11 -0800 Subject: [PATCH 354/385] [feedback] diagnostics (#13292) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - added header logic to display diagnostics on cli - added logic for collecting env vars Screenshot 2026-03-03 at 3 49 31 PM Screenshot 2026-03-02 at 6 47 54 PM --- codex-rs/Cargo.lock | 1 + codex-rs/feedback/Cargo.toml | 1 + codex-rs/feedback/src/feedback_diagnostics.rs | 247 ++++++++++++++++++ codex-rs/feedback/src/lib.rs | 146 +++++++++-- codex-rs/tui/src/bottom_pane/feedback_view.rs | 162 ++++++++++-- ...ck_view_with_connectivity_diagnostics.snap | 17 ++ codex-rs/tui/src/chatwidget.rs | 14 +- ...s__feedback_good_result_consent_popup.snap | 15 ++ ..._tests__feedback_upload_consent_popup.snap | 1 + codex-rs/tui/src/chatwidget/tests.rs | 23 +- 10 files changed, 586 insertions(+), 41 deletions(-) create mode 100644 codex-rs/feedback/src/feedback_diagnostics.rs create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_with_connectivity_diagnostics.snap create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index b0c1e38429..48e8c598db 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1999,6 +1999,7 @@ dependencies = [ "sentry", "tracing", "tracing-subscriber", + "url", ] [[package]] diff --git a/codex-rs/feedback/Cargo.toml b/codex-rs/feedback/Cargo.toml index 73803af86a..43d572f895 100644 --- a/codex-rs/feedback/Cargo.toml +++ b/codex-rs/feedback/Cargo.toml @@ -10,6 +10,7 @@ codex-protocol = { workspace = true } sentry = { version = "0.46" } tracing = { workspace = true } tracing-subscriber = { workspace = true } +url = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } diff --git a/codex-rs/feedback/src/feedback_diagnostics.rs b/codex-rs/feedback/src/feedback_diagnostics.rs new file mode 100644 index 0000000000..5497fe0579 --- /dev/null +++ b/codex-rs/feedback/src/feedback_diagnostics.rs @@ -0,0 +1,247 @@ +use std::collections::HashMap; + +use url::Url; + +const DEFAULT_OPENAI_BASE_URL: &str = "https://api.openai.com/v1"; +const OPENAI_BASE_URL_ENV_VAR: &str = "OPENAI_BASE_URL"; +pub const FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME: &str = "codex-connectivity-diagnostics.txt"; +const PROXY_ENV_VARS: &[&str] = &[ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", +]; + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FeedbackDiagnostics { + diagnostics: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FeedbackDiagnostic { + pub headline: String, + pub details: Vec, +} + +impl FeedbackDiagnostics { + pub fn new(diagnostics: Vec) -> Self { + Self { diagnostics } + } + + pub fn collect_from_env() -> Self { + Self::collect_from_pairs(std::env::vars()) + } + + fn collect_from_pairs(pairs: I) -> Self + where + I: IntoIterator, + K: Into, + V: Into, + { + let env = pairs + .into_iter() + .map(|(key, value)| (key.into(), value.into())) + .collect::>(); + let mut diagnostics = Vec::new(); + + let proxy_details = PROXY_ENV_VARS + .iter() + .filter_map(|key| { + let value = env.get(*key)?.trim(); + if value.is_empty() { + return None; + } + + let detail = match sanitize_proxy_value(value) { + Some(sanitized) => format!("{key} = {sanitized}"), + None => format!("{key} = invalid value"), + }; + Some(detail) + }) + .collect::>(); + if !proxy_details.is_empty() { + diagnostics.push(FeedbackDiagnostic { + headline: "Proxy environment variables are set and may affect connectivity." + .to_string(), + details: proxy_details, + }); + } + + if let Some(value) = env.get(OPENAI_BASE_URL_ENV_VAR).map(String::as_str) { + let trimmed = value.trim(); + if !trimmed.is_empty() && trimmed.trim_end_matches('/') != DEFAULT_OPENAI_BASE_URL { + let detail = match sanitize_url_for_display(trimmed) { + Some(sanitized) => format!("{OPENAI_BASE_URL_ENV_VAR} = {sanitized}"), + None => format!("{OPENAI_BASE_URL_ENV_VAR} = invalid value"), + }; + diagnostics.push(FeedbackDiagnostic { + headline: "OPENAI_BASE_URL is set and may affect connectivity.".to_string(), + details: vec![detail], + }); + } + } + + Self { diagnostics } + } + + pub fn is_empty(&self) -> bool { + self.diagnostics.is_empty() + } + + pub fn diagnostics(&self) -> &[FeedbackDiagnostic] { + &self.diagnostics + } + + pub fn attachment_text(&self) -> Option { + if self.diagnostics.is_empty() { + return None; + } + + let mut lines = vec!["Connectivity diagnostics".to_string(), String::new()]; + for diagnostic in &self.diagnostics { + lines.push(format!("- {}", diagnostic.headline)); + lines.extend( + diagnostic + .details + .iter() + .map(|detail| format!(" - {detail}")), + ); + } + + Some(lines.join("\n")) + } +} + +pub fn sanitize_url_for_display(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return None; + } + + let Ok(mut url) = Url::parse(trimmed) else { + return None; + }; + let _ = url.set_username(""); + let _ = url.set_password(None); + url.set_query(None); + url.set_fragment(None); + Some(url.to_string().trim_end_matches('/').to_string()).filter(|value| !value.is_empty()) +} + +fn sanitize_proxy_value(raw: &str) -> Option { + if raw.contains("://") { + return sanitize_url_for_display(raw); + } + + sanitize_url_for_display(&format!("http://{raw}")) +} + +#[cfg(test)] +mod tests { + use pretty_assertions::assert_eq; + + use super::FeedbackDiagnostic; + use super::FeedbackDiagnostics; + use super::sanitize_url_for_display; + + #[test] + fn collect_from_pairs_reports_sanitized_diagnostics_and_attachment() { + let diagnostics = FeedbackDiagnostics::collect_from_pairs([ + ( + "HTTPS_PROXY", + "https://user:password@secure-proxy.example.com:443?secret=1", + ), + ("http_proxy", "proxy.example.com:8080"), + ("all_proxy", "socks5h://all-proxy.example.com:1080"), + ("OPENAI_BASE_URL", "https://example.com/v1?token=secret"), + ]); + + assert_eq!( + diagnostics, + FeedbackDiagnostics { + diagnostics: vec![ + FeedbackDiagnostic { + headline: + "Proxy environment variables are set and may affect connectivity." + .to_string(), + details: vec![ + "http_proxy = http://proxy.example.com:8080".to_string(), + "HTTPS_PROXY = https://secure-proxy.example.com".to_string(), + "all_proxy = socks5h://all-proxy.example.com:1080".to_string(), + ], + }, + FeedbackDiagnostic { + headline: "OPENAI_BASE_URL is set and may affect connectivity.".to_string(), + details: vec!["OPENAI_BASE_URL = https://example.com/v1".to_string()], + }, + ], + } + ); + + assert_eq!( + diagnostics.attachment_text(), + Some( + "Connectivity diagnostics\n\n- Proxy environment variables are set and may affect connectivity.\n - http_proxy = http://proxy.example.com:8080\n - HTTPS_PROXY = https://secure-proxy.example.com\n - all_proxy = socks5h://all-proxy.example.com:1080\n- OPENAI_BASE_URL is set and may affect connectivity.\n - OPENAI_BASE_URL = https://example.com/v1" + .to_string() + ) + ); + } + + #[test] + fn collect_from_pairs_ignores_absent_and_default_values() { + for diagnostics in [ + FeedbackDiagnostics::collect_from_pairs(Vec::<(String, String)>::new()), + FeedbackDiagnostics::collect_from_pairs([( + "OPENAI_BASE_URL", + "https://api.openai.com/v1/", + )]), + ] { + assert_eq!(diagnostics, FeedbackDiagnostics::default()); + assert_eq!(diagnostics.attachment_text(), None); + } + } + + #[test] + fn collect_from_pairs_reports_invalid_values_without_echoing_them() { + let invalid_proxy = "not a valid\nproxy"; + let invalid_base_url = "not a valid\nurl"; + let diagnostics = FeedbackDiagnostics::collect_from_pairs([ + ("HTTP_PROXY", invalid_proxy), + ("OPENAI_BASE_URL", invalid_base_url), + ]); + + assert_eq!( + diagnostics, + FeedbackDiagnostics { + diagnostics: vec![ + FeedbackDiagnostic { + headline: + "Proxy environment variables are set and may affect connectivity." + .to_string(), + details: vec!["HTTP_PROXY = invalid value".to_string()], + }, + FeedbackDiagnostic { + headline: "OPENAI_BASE_URL is set and may affect connectivity.".to_string(), + details: vec!["OPENAI_BASE_URL = invalid value".to_string()], + }, + ], + } + ); + let attachment_text = diagnostics + .attachment_text() + .expect("invalid diagnostics should still render attachment text"); + assert!(!attachment_text.contains(invalid_proxy)); + assert!(!attachment_text.contains(invalid_base_url)); + } + + #[test] + fn sanitize_url_for_display_strips_credentials_query_and_fragment() { + let sanitized = sanitize_url_for_display( + "https://user:password@example.com:8443/v1?token=secret#fragment", + ); + + assert_eq!(sanitized, Some("https://example.com:8443/v1".to_string())); + } +} diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index ee8e98c39e..0bd76936aa 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -13,6 +13,8 @@ use anyhow::Result; use anyhow::anyhow; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; +use feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME; +use feedback_diagnostics::FeedbackDiagnostics; use tracing::Event; use tracing::Level; use tracing::field::Visit; @@ -21,6 +23,8 @@ use tracing_subscriber::filter::Targets; use tracing_subscriber::fmt::writer::MakeWriter; use tracing_subscriber::registry::LookupSpan; +pub mod feedback_diagnostics; + const DEFAULT_MAX_BYTES: usize = 4 * 1024 * 1024; // 4 MiB const SENTRY_DSN: &str = "https://ae32ed50620d7a7792c1ce5df38b3e3e@o33249.ingest.us.sentry.io/4510195390611458"; @@ -88,7 +92,7 @@ impl CodexFeedback { .with_filter(Targets::new().with_target(FEEDBACK_TAGS_TARGET, Level::TRACE)) } - pub fn snapshot(&self, session_id: Option) -> CodexLogSnapshot { + pub fn snapshot(&self, session_id: Option) -> FeedbackSnapshot { let bytes = { let guard = self.inner.ring.lock().expect("mutex poisoned"); guard.snapshot_bytes() @@ -97,9 +101,10 @@ impl CodexFeedback { let guard = self.inner.tags.lock().expect("mutex poisoned"); guard.clone() }; - CodexLogSnapshot { + FeedbackSnapshot { bytes, tags, + feedback_diagnostics: FeedbackDiagnostics::collect_from_env(), thread_id: session_id .map(|id| id.to_string()) .unwrap_or("no-active-thread-".to_string() + &ThreadId::new().to_string()), @@ -199,17 +204,35 @@ impl RingBuffer { } } -pub struct CodexLogSnapshot { +pub struct FeedbackSnapshot { bytes: Vec, tags: BTreeMap, + feedback_diagnostics: FeedbackDiagnostics, pub thread_id: String, } -impl CodexLogSnapshot { +impl FeedbackSnapshot { pub(crate) fn as_bytes(&self) -> &[u8] { &self.bytes } + pub fn feedback_diagnostics(&self) -> &FeedbackDiagnostics { + &self.feedback_diagnostics + } + + pub fn with_feedback_diagnostics(mut self, feedback_diagnostics: FeedbackDiagnostics) -> Self { + self.feedback_diagnostics = feedback_diagnostics; + self + } + + pub fn feedback_diagnostics_attachment_text(&self, include_logs: bool) -> Option { + if !include_logs { + return None; + } + + self.feedback_diagnostics.attachment_text() + } + pub fn save_to_temp_file(&self) -> io::Result { let dir = std::env::temp_dir(); let filename = format!("codex-feedback-{}.log", self.thread_id); @@ -224,18 +247,16 @@ impl CodexLogSnapshot { classification: &str, reason: Option<&str>, include_logs: bool, - extra_log_files: &[PathBuf], + extra_attachment_paths: &[PathBuf], session_source: Option, logs_override: Option>, ) -> Result<()> { use std::collections::BTreeMap; - use std::fs; use std::str::FromStr; use std::sync::Arc; use sentry::Client; use sentry::ClientOptions; - use sentry::protocol::Attachment; use sentry::protocol::Envelope; use sentry::protocol::EnvelopeItem; use sentry::protocol::Event; @@ -309,16 +330,46 @@ impl CodexLogSnapshot { } envelope.add_item(EnvelopeItem::Event(event)); + for attachment in + self.feedback_attachments(include_logs, extra_attachment_paths, logs_override) + { + envelope.add_item(EnvelopeItem::Attachment(attachment)); + } + + client.send_envelope(envelope); + client.flush(Some(Duration::from_secs(UPLOAD_TIMEOUT_SECS))); + Ok(()) + } + + fn feedback_attachments( + &self, + include_logs: bool, + extra_attachment_paths: &[PathBuf], + logs_override: Option>, + ) -> Vec { + use sentry::protocol::Attachment; + + let mut attachments = Vec::new(); + if include_logs { - envelope.add_item(EnvelopeItem::Attachment(Attachment { + attachments.push(Attachment { buffer: logs_override.unwrap_or_else(|| self.bytes.clone()), filename: String::from("codex-logs.log"), content_type: Some("text/plain".to_string()), ty: None, - })); + }); } - for path in extra_log_files { + if let Some(text) = self.feedback_diagnostics_attachment_text(include_logs) { + attachments.push(Attachment { + buffer: text.into_bytes(), + filename: FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME.to_string(), + content_type: Some("text/plain".to_string()), + ty: None, + }); + } + + for path in extra_attachment_paths { let data = match fs::read(path) { Ok(data) => data, Err(err) => { @@ -330,22 +381,19 @@ impl CodexLogSnapshot { continue; } }; - let fname = path + let filename = path .file_name() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "extra-log.log".to_string()); - let content_type = "text/plain".to_string(); - envelope.add_item(EnvelopeItem::Attachment(Attachment { + attachments.push(Attachment { buffer: data, - filename: fname, - content_type: Some(content_type), + filename, + content_type: Some("text/plain".to_string()), ty: None, - })); + }); } - client.send_envelope(envelope); - client.flush(Some(Duration::from_secs(UPLOAD_TIMEOUT_SECS))); - Ok(()) + attachments } } @@ -430,7 +478,12 @@ impl Visit for FeedbackTagsVisitor { #[cfg(test)] mod tests { + use std::ffi::OsStr; + use std::fs; + use super::*; + use feedback_diagnostics::FeedbackDiagnostic; + use pretty_assertions::assert_eq; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; @@ -460,4 +513,59 @@ mod tests { pretty_assertions::assert_eq!(snap.tags.get("model").map(String::as_str), Some("gpt-5")); pretty_assertions::assert_eq!(snap.tags.get("cached").map(String::as_str), Some("true")); } + + #[test] + fn feedback_attachments_gate_connectivity_diagnostics() { + let extra_filename = format!("codex-feedback-extra-{}.jsonl", ThreadId::new()); + let extra_path = std::env::temp_dir().join(&extra_filename); + fs::write(&extra_path, "rollout").expect("extra attachment should be written"); + + let snapshot_with_diagnostics = CodexFeedback::new() + .snapshot(None) + .with_feedback_diagnostics(FeedbackDiagnostics::new(vec![FeedbackDiagnostic { + headline: "OPENAI_BASE_URL is set and may affect connectivity.".to_string(), + details: vec!["OPENAI_BASE_URL = https://example.com/v1".to_string()], + }])); + + let attachments_with_diagnostics = snapshot_with_diagnostics.feedback_attachments( + true, + std::slice::from_ref(&extra_path), + Some(vec![1]), + ); + + assert_eq!( + attachments_with_diagnostics + .iter() + .map(|attachment| attachment.filename.as_str()) + .collect::>(), + vec![ + "codex-logs.log", + FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME, + extra_filename.as_str() + ] + ); + assert_eq!(attachments_with_diagnostics[0].buffer, vec![1]); + assert_eq!( + attachments_with_diagnostics[1].buffer, + b"Connectivity diagnostics\n\n- OPENAI_BASE_URL is set and may affect connectivity.\n - OPENAI_BASE_URL = https://example.com/v1".to_vec() + ); + assert_eq!(attachments_with_diagnostics[2].buffer, b"rollout".to_vec()); + assert_eq!( + OsStr::new(attachments_with_diagnostics[2].filename.as_str()), + OsStr::new(extra_filename.as_str()) + ); + let attachments_without_diagnostics = CodexFeedback::new() + .snapshot(None) + .feedback_attachments(true, &[], Some(vec![1])); + + assert_eq!( + attachments_without_diagnostics + .iter() + .map(|attachment| attachment.filename.as_str()) + .collect::>(), + vec!["codex-logs.log"] + ); + assert_eq!(attachments_without_diagnostics[0].buffer, vec![1]); + fs::remove_file(extra_path).expect("extra attachment should be removed"); + } } diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index 33368faa45..f9bbfe2436 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -1,6 +1,8 @@ use std::cell::RefCell; use std::path::PathBuf; +use codex_feedback::feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME; +use codex_feedback::feedback_diagnostics::FeedbackDiagnostics; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; @@ -19,6 +21,8 @@ use crate::app_event::FeedbackCategory; use crate::app_event_sender::AppEventSender; use crate::history_cell; use crate::render::renderable::Renderable; +use crate::wrapping::RtOptions; +use crate::wrapping::word_wrap_lines; use codex_protocol::protocol::SessionSource; use super::CancellationEvent; @@ -46,7 +50,7 @@ pub(crate) enum FeedbackAudience { /// both logs and rollout with classification + metadata. pub(crate) struct FeedbackNoteView { category: FeedbackCategory, - snapshot: codex_feedback::CodexLogSnapshot, + snapshot: codex_feedback::FeedbackSnapshot, rollout_path: Option, app_event_tx: AppEventSender, include_logs: bool, @@ -61,7 +65,7 @@ pub(crate) struct FeedbackNoteView { impl FeedbackNoteView { pub(crate) fn new( category: FeedbackCategory, - snapshot: codex_feedback::CodexLogSnapshot, + snapshot: codex_feedback::FeedbackSnapshot, rollout_path: Option, app_event_tx: AppEventSender, include_logs: bool, @@ -87,7 +91,7 @@ impl FeedbackNoteView { } else { Some(note.as_str()) }; - let log_file_paths = if self.include_logs { + let attachment_paths = if self.include_logs { self.rollout_path.iter().cloned().collect::>() } else { Vec::new() @@ -100,7 +104,7 @@ impl FeedbackNoteView { classification, reason_opt, self.include_logs, - &log_file_paths, + &attachment_paths, Some(SessionSource::Cli), None, ); @@ -217,21 +221,21 @@ impl BottomPaneView for FeedbackNoteView { impl Renderable for FeedbackNoteView { fn desired_height(&self, width: u16) -> u16 { - 1u16 + self.input_height(width) + 3u16 + self.intro_lines(width).len() as u16 + self.input_height(width) + 2u16 } fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> { if area.height < 2 || area.width <= 2 { return None; } + let intro_height = self.intro_lines(area.width).len() as u16; let text_area_height = self.input_height(area.width).saturating_sub(1); if text_area_height == 0 { return None; } - let top_line_count = 1u16; // title only let textarea_rect = Rect { x: area.x.saturating_add(2), - y: area.y.saturating_add(top_line_count).saturating_add(1), + y: area.y.saturating_add(intro_height).saturating_add(1), width: area.width.saturating_sub(2), height: text_area_height, }; @@ -244,23 +248,26 @@ impl Renderable for FeedbackNoteView { return; } - let (title, placeholder) = feedback_title_and_placeholder(self.category); + let intro_lines = self.intro_lines(area.width); + let (_, placeholder) = feedback_title_and_placeholder(self.category); let input_height = self.input_height(area.width); - // Title line - let title_area = Rect { - x: area.x, - y: area.y, - width: area.width, - height: 1, - }; - let title_spans: Vec> = vec![gutter(), title.bold()]; - Paragraph::new(Line::from(title_spans)).render(title_area, buf); + for (offset, line) in intro_lines.iter().enumerate() { + Paragraph::new(line.clone()).render( + Rect { + x: area.x, + y: area.y.saturating_add(offset as u16), + width: area.width, + height: 1, + }, + buf, + ); + } // Input line let input_area = Rect { x: area.x, - y: area.y.saturating_add(1), + y: area.y.saturating_add(intro_lines.len() as u16), width: area.width, height: input_height, }; @@ -334,6 +341,56 @@ impl FeedbackNoteView { let text_height = self.textarea.desired_height(usable_width).clamp(1, 8); text_height.saturating_add(1).min(9) } + + fn intro_lines(&self, width: u16) -> Vec> { + let (title, _) = feedback_title_and_placeholder(self.category); + let mut lines = vec![Line::from(vec![gutter(), title.bold()])]; + if should_show_feedback_connectivity_details( + self.category, + self.snapshot.feedback_diagnostics(), + ) { + lines.push(Line::from(vec![gutter()])); + lines.push(Line::from(vec![ + gutter(), + "Connectivity diagnostics".bold(), + ])); + lines.extend(self.diagnostics_lines(width)); + } + lines + } + + fn diagnostics_lines(&self, width: u16) -> Vec> { + let width = usize::from(width.max(1)); + let headline_options = RtOptions::new(width) + .initial_indent(Line::from(vec![gutter(), " - ".into()])) + .subsequent_indent(Line::from(vec![gutter(), " ".into()])); + let detail_options = RtOptions::new(width) + .initial_indent(Line::from(vec![gutter(), " - ".dim()])) + .subsequent_indent(Line::from(vec![gutter(), " ".into()])); + let mut lines = Vec::new(); + + for diagnostic in self.snapshot.feedback_diagnostics().diagnostics() { + lines.extend(word_wrap_lines( + [Line::from(diagnostic.headline.clone())], + headline_options.clone(), + )); + for detail in &diagnostic.details { + lines.extend(word_wrap_lines( + [Line::from(detail.clone())], + detail_options.clone(), + )); + } + } + + lines + } +} + +pub(crate) fn should_show_feedback_connectivity_details( + category: FeedbackCategory, + diagnostics: &FeedbackDiagnostics, +) -> bool { + category != FeedbackCategory::GoodResult && !diagnostics.is_empty() } fn gutter() -> Span<'static> { @@ -485,6 +542,7 @@ pub(crate) fn feedback_upload_consent_params( app_event_tx: AppEventSender, category: FeedbackCategory, rollout_path: Option, + include_connectivity_diagnostics_attachment: bool, ) -> super::SelectionViewParams { use super::popup_consts::standard_popup_hint_line; let yes_action: super::SelectionAction = Box::new({ @@ -521,6 +579,15 @@ pub(crate) fn feedback_upload_consent_params( { header_lines.push(Line::from(vec![" • ".into(), name.into()]).into()); } + if include_connectivity_diagnostics_attachment { + header_lines.push( + Line::from(vec![ + " • ".into(), + FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME.into(), + ]) + .into(), + ); + } super::SelectionViewParams { footer_hint: Some(standard_popup_hint_line()), @@ -537,7 +604,6 @@ pub(crate) fn feedback_upload_consent_params( }, super::SelectionItem { name: "No".to_string(), - description: Some("".to_string()), actions: vec![no_action], dismiss_on_select: true, ..Default::default() @@ -555,6 +621,8 @@ mod tests { use super::*; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; + use codex_feedback::feedback_diagnostics::FeedbackDiagnostic; + use pretty_assertions::assert_eq; fn render(view: &FeedbackNoteView, width: u16) -> String { let height = view.desired_height(width); @@ -635,6 +703,62 @@ mod tests { insta::assert_snapshot!("feedback_view_safety_check", rendered); } + #[test] + fn feedback_view_with_connectivity_diagnostics() { + let (tx_raw, _rx) = tokio::sync::mpsc::unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let diagnostics = FeedbackDiagnostics::new(vec![ + FeedbackDiagnostic { + headline: "Proxy environment variables are set and may affect connectivity." + .to_string(), + details: vec!["HTTP_PROXY = http://proxy.example.com:8080".to_string()], + }, + FeedbackDiagnostic { + headline: "OPENAI_BASE_URL is set and may affect connectivity.".to_string(), + details: vec!["OPENAI_BASE_URL = https://example.com/v1".to_string()], + }, + ]); + let snapshot = codex_feedback::CodexFeedback::new() + .snapshot(None) + .with_feedback_diagnostics(diagnostics); + let view = FeedbackNoteView::new( + FeedbackCategory::Bug, + snapshot, + None, + tx, + false, + FeedbackAudience::External, + ); + let rendered = render(&view, 60); + + insta::assert_snapshot!("feedback_view_with_connectivity_diagnostics", rendered); + } + + #[test] + fn should_show_feedback_connectivity_details_only_for_non_good_result_with_diagnostics() { + let diagnostics = FeedbackDiagnostics::new(vec![FeedbackDiagnostic { + headline: "Proxy environment variables are set and may affect connectivity." + .to_string(), + details: vec!["HTTP_PROXY = http://proxy.example.com:8080".to_string()], + }]); + + assert_eq!( + should_show_feedback_connectivity_details(FeedbackCategory::Bug, &diagnostics), + true + ); + assert_eq!( + should_show_feedback_connectivity_details(FeedbackCategory::GoodResult, &diagnostics), + false + ); + assert_eq!( + should_show_feedback_connectivity_details( + FeedbackCategory::BadResult, + &FeedbackDiagnostics::default() + ), + false + ); + } + #[test] fn issue_url_available_for_bug_bad_result_safety_check_and_other() { let bug_url = issue_url_for_category( diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_with_connectivity_diagnostics.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_with_connectivity_diagnostics.snap new file mode 100644 index 0000000000..ec1322ce84 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_with_connectivity_diagnostics.snap @@ -0,0 +1,17 @@ +--- +source: tui/src/bottom_pane/feedback_view.rs +assertion_line: 749 +expression: rendered +--- +▌ Tell us more (bug) +▌ +▌ Connectivity diagnostics +▌ - Proxy environment variables are set and may affect +▌ connectivity. +▌ - HTTP_PROXY = http://proxy.example.com:8080 +▌ - OPENAI_BASE_URL is set and may affect connectivity. +▌ - OPENAI_BASE_URL = https://example.com/v1 +▌ +▌ (optional) Write a short description to help us further + +Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index a0d3454183..0296bd08d2 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1284,8 +1284,16 @@ impl ChatWidget { category: crate::app_event::FeedbackCategory, include_logs: bool, ) { - // Build a fresh snapshot at the time of opening the note overlay. let snapshot = self.feedback.snapshot(self.thread_id); + self.show_feedback_note(category, include_logs, snapshot); + } + + fn show_feedback_note( + &mut self, + category: crate::app_event::FeedbackCategory, + include_logs: bool, + snapshot: codex_feedback::FeedbackSnapshot, + ) { let rollout = if include_logs { self.current_rollout_path.clone() } else { @@ -1310,10 +1318,14 @@ impl ChatWidget { } pub(crate) fn open_feedback_consent(&mut self, category: crate::app_event::FeedbackCategory) { + let snapshot = self.feedback.snapshot(self.thread_id); let params = crate::bottom_pane::feedback_upload_consent_params( self.app_event_tx.clone(), category, self.current_rollout_path.clone(), + snapshot + .feedback_diagnostics_attachment_text(true) + .is_some(), ); self.bottom_pane.show_selection_view(params); self.request_redraw(); diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap new file mode 100644 index 0000000000..4529d6d478 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_good_result_consent_popup.snap @@ -0,0 +1,15 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + Upload logs? + + The following files will be sent: + • codex-logs.log + • codex-connectivity-diagnostics.txt + +› 1. Yes Share the current Codex session logs with the team for + troubleshooting. + 2. No + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap index cc3d8e3755..4529d6d478 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap @@ -6,6 +6,7 @@ expression: popup The following files will be sent: • codex-logs.log + • codex-connectivity-diagnostics.txt › 1. Yes Share the current Codex session logs with the team for troubleshooting. diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 6ea109dacb..0ee7974d26 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -7068,13 +7068,32 @@ async fn feedback_selection_popup_snapshot() { async fn feedback_upload_consent_popup_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - // Open the consent popup directly for a chosen category. - chat.open_feedback_consent(crate::app_event::FeedbackCategory::Bug); + chat.show_selection_view(crate::bottom_pane::feedback_upload_consent_params( + chat.app_event_tx.clone(), + crate::app_event::FeedbackCategory::Bug, + chat.current_rollout_path.clone(), + true, + )); let popup = render_bottom_popup(&chat, 80); assert_snapshot!("feedback_upload_consent_popup", popup); } +#[tokio::test] +async fn feedback_good_result_consent_popup_includes_connectivity_diagnostics_filename() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + + chat.show_selection_view(crate::bottom_pane::feedback_upload_consent_params( + chat.app_event_tx.clone(), + crate::app_event::FeedbackCategory::GoodResult, + chat.current_rollout_path.clone(), + true, + )); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("feedback_good_result_consent_popup", popup); +} + #[tokio::test] async fn reasoning_popup_escape_returns_to_model_popup() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; From 0fbd84081bf11065dfd0cd8d9f31faa6b599877a Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 3 Mar 2026 17:01:00 -0800 Subject: [PATCH 355/385] feat(app-server): add a skills/changed v2 notification (#13414) This adds a first-class app-server v2 `skills/changed` notification for the existing skills live-reload signal. Before this change, clients only had the legacy raw `codex/event/skills_update_available` event. With this PR, v2 clients can listen for a typed JSON-RPC notification instead of depending on the legacy `codex/event/*` stream, which we want to remove soon. --- .../schema/json/ServerNotification.json | 24 ++++++++ .../codex_app_server_protocol.schemas.json | 26 ++++++++ .../codex_app_server_protocol.v2.schemas.json | 26 ++++++++ .../json/v2/SkillsChangedNotification.json | 6 ++ .../schema/typescript/ServerNotification.ts | 3 +- .../v2/SkillsChangedNotification.ts | 11 ++++ .../schema/typescript/v2/index.ts | 1 + .../src/protocol/common.rs | 1 + .../app-server-protocol/src/protocol/v2.rs | 9 +++ codex-rs/app-server/README.md | 9 +++ .../app-server/src/bespoke_event_handling.rs | 10 +++ .../app-server/tests/suite/v2/skills_list.rs | 61 +++++++++++++++++++ 12 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 codex-rs/app-server-protocol/schema/json/v2/SkillsChangedNotification.json create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/SkillsChangedNotification.ts diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 28df2574b2..61d15286a1 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1485,6 +1485,10 @@ } ] }, + "SkillsChangedNotification": { + "description": "Notification emitted when watched local skill files change.\n\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.", + "type": "object" + }, "SubAgentSource": { "oneOf": [ { @@ -3202,6 +3206,26 @@ "title": "Thread/closedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "skills/changed" + ], + "title": "Skills/changedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsChangedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Skills/changedNotification", + "type": "object" + }, { "properties": { "method": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index a60e6c4a44..61e32239f7 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -6039,6 +6039,26 @@ "title": "Thread/closedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "skills/changed" + ], + "title": "Skills/changedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/SkillsChangedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Skills/changedNotification", + "type": "object" + }, { "properties": { "method": { @@ -12302,6 +12322,12 @@ ], "type": "object" }, + "SkillsChangedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Notification emitted when watched local skill files change.\n\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.", + "title": "SkillsChangedNotification", + "type": "object" + }, "SkillsConfigWriteParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index b4a5f9f6cb..1d4482c6ff 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -9977,6 +9977,26 @@ "title": "Thread/closedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "skills/changed" + ], + "title": "Skills/changedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsChangedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Skills/changedNotification", + "type": "object" + }, { "properties": { "method": { @@ -10972,6 +10992,12 @@ ], "type": "object" }, + "SkillsChangedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Notification emitted when watched local skill files change.\n\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.", + "title": "SkillsChangedNotification", + "type": "object" + }, "SkillsConfigWriteParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/SkillsChangedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/SkillsChangedNotification.json new file mode 100644 index 0000000000..cb67d81602 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/SkillsChangedNotification.json @@ -0,0 +1,6 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Notification emitted when watched local skill files change.\n\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.", + "title": "SkillsChangedNotification", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts index d7f70d3558..8157ba2f48 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts @@ -25,6 +25,7 @@ import type { ReasoningSummaryPartAddedNotification } from "./v2/ReasoningSummar import type { ReasoningSummaryTextDeltaNotification } from "./v2/ReasoningSummaryTextDeltaNotification"; import type { ReasoningTextDeltaNotification } from "./v2/ReasoningTextDeltaNotification"; import type { ServerRequestResolvedNotification } from "./v2/ServerRequestResolvedNotification"; +import type { SkillsChangedNotification } from "./v2/SkillsChangedNotification"; import type { TerminalInteractionNotification } from "./v2/TerminalInteractionNotification"; import type { ThreadArchivedNotification } from "./v2/ThreadArchivedNotification"; import type { ThreadClosedNotification } from "./v2/ThreadClosedNotification"; @@ -48,4 +49,4 @@ import type { WindowsWorldWritableWarningNotification } from "./v2/WindowsWorldW /** * Notification sent from the server to the client. */ -export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; +export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillsChangedNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsChangedNotification.ts new file mode 100644 index 0000000000..23ed93a5ec --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsChangedNotification.ts @@ -0,0 +1,11 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Notification emitted when watched local skill files change. + * + * Treat this as an invalidation signal and re-run `skills/list` with the + * client's current parameters when refreshed skill metadata is needed. + */ +export type SkillsChangedNotification = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 9c677641fa..02bf51727d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -150,6 +150,7 @@ export type { SkillInterface } from "./SkillInterface"; export type { SkillMetadata } from "./SkillMetadata"; export type { SkillScope } from "./SkillScope"; export type { SkillToolDependency } from "./SkillToolDependency"; +export type { SkillsChangedNotification } from "./SkillsChangedNotification"; export type { SkillsConfigWriteParams } from "./SkillsConfigWriteParams"; export type { SkillsConfigWriteResponse } from "./SkillsConfigWriteResponse"; export type { SkillsListEntry } from "./SkillsListEntry"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 67968507c7..19e1fb1770 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -753,6 +753,7 @@ server_notification_definitions! { ThreadArchived => "thread/archived" (v2::ThreadArchivedNotification), ThreadUnarchived => "thread/unarchived" (v2::ThreadUnarchivedNotification), ThreadClosed => "thread/closed" (v2::ThreadClosedNotification), + SkillsChanged => "skills/changed" (v2::SkillsChangedNotification), ThreadNameUpdated => "thread/name/updated" (v2::ThreadNameUpdatedNotification), ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification), TurnStarted => "turn/started" (v2::TurnStartedNotification), diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 6b26433ae0..0a63b42c46 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -3635,6 +3635,15 @@ pub struct ThreadClosedNotification { pub thread_id: String, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +/// Notification emitted when watched local skill files change. +/// +/// Treat this as an invalidation signal and re-run `skills/list` with the +/// client's current parameters when refreshed skill metadata is needed. +pub struct SkillsChangedNotification {} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index d2d8aa5445..786a935b6d 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -148,6 +148,7 @@ Example with notification opt-out: - `experimentalFeature/list` — list feature flags with stage metadata (`beta`, `underDevelopment`, `stable`, etc.), enabled/default-enabled state, and cursor pagination. For non-beta flags, `displayName`/`description`/`announcement` are `null`. - `collaborationMode/list` — list available collaboration mode presets (experimental, no pagination). This response omits built-in developer instructions; clients should either pass `settings.developer_instructions: null` when setting a mode to use Codex's built-in instructions, or provide their own instructions explicitly. - `skills/list` — list skills for one or more `cwd` values (optional `forceReload`). +- `skills/changed` — notification emitted when watched local skill files change. - `skills/remote/list` — list public remote skills (**under development; do not call from production clients yet**). - `skills/remote/export` — download a remote skill by `hazelnutId` into `skills` under `codex_home` (**under development; do not call from production clients yet**). - `app/list` — list available apps. @@ -841,6 +842,7 @@ Use `skills/list` to fetch the available skills (optionally scoped by `cwds`, wi You can also add `perCwdExtraUserRoots` to scan additional absolute paths as `user` scope for specific `cwd` entries. Entries whose `cwd` is not present in `cwds` are ignored. `skills/list` might reuse a cached skills result per `cwd`; setting `forceReload` to `true` refreshes the result from disk. +The server also emits `skills/changed` notifications when watched local skill files change. Treat this as an invalidation signal and re-run `skills/list` with your current params when needed. ```json { "method": "skills/list", "id": 25, "params": { @@ -876,6 +878,13 @@ Entries whose `cwd` is not present in `cwds` are ignored. } } ``` +```json +{ + "method": "skills/changed", + "params": {} +} +``` + To enable or disable a skill by path: ```json diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 2f293c9347..4d005706db 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -61,6 +61,7 @@ use codex_app_server_protocol::ReasoningTextDeltaNotification; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; +use codex_app_server_protocol::SkillsChangedNotification; use codex_app_server_protocol::TerminalInteractionNotification; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadNameUpdatedNotification; @@ -220,6 +221,15 @@ pub(crate) async fn apply_bespoke_event_handling( .await; handle_turn_complete(conversation_id, event_turn_id, &outgoing, &thread_state).await; } + EventMsg::SkillsUpdateAvailable => { + if let ApiVersion::V2 = api_version { + outgoing + .send_server_notification(ServerNotification::SkillsChanged( + SkillsChangedNotification {}, + )) + .await; + } + } EventMsg::Warning(_warning_event) => {} EventMsg::ModelReroute(event) => { if let ApiVersion::V2 = api_version { diff --git a/codex-rs/app-server/tests/suite/v2/skills_list.rs b/codex-rs/app-server/tests/suite/v2/skills_list.rs index e099bdb646..03443a47eb 100644 --- a/codex-rs/app-server/tests/suite/v2/skills_list.rs +++ b/codex-rs/app-server/tests/suite/v2/skills_list.rs @@ -1,18 +1,22 @@ use std::time::Duration; +use anyhow::Context; use anyhow::Result; use app_test_support::McpProcess; use app_test_support::to_response; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::SkillsChangedNotification; use codex_app_server_protocol::SkillsListExtraRootsForCwd; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::SkillsListResponse; +use codex_app_server_protocol::ThreadStartParams; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::time::timeout; const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); +const WATCHER_TIMEOUT: Duration = Duration::from_secs(20); fn write_skill(root: &TempDir, name: &str) -> Result<()> { let skill_dir = root.path().join("skills").join(name); @@ -214,3 +218,60 @@ async fn skills_list_uses_cached_result_until_force_reload() -> Result<()> { ); Ok(()) } + +#[tokio::test] +async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<()> { + let codex_home = TempDir::new()?; + write_skill(&codex_home, "demo")?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + let thread_start_request_id = mcp + .send_thread_start_request(ThreadStartParams { + model: None, + model_provider: None, + service_tier: None, + cwd: None, + approval_policy: None, + sandbox: None, + config: None, + service_name: None, + base_instructions: None, + developer_instructions: None, + personality: None, + ephemeral: None, + dynamic_tools: None, + mock_experimental_field: None, + experimental_raw_events: false, + persist_extended_history: false, + }) + .await?; + let _: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_start_request_id)), + ) + .await??; + + let skill_path = codex_home + .path() + .join("skills") + .join("demo") + .join("SKILL.md"); + std::fs::write( + &skill_path, + "---\nname: demo\ndescription: updated\n---\n\n# Updated\n", + )?; + + let notification = timeout( + WATCHER_TIMEOUT, + mcp.read_stream_until_notification_message("skills/changed"), + ) + .await??; + let params = notification + .params + .context("skills/changed params must be present")?; + let notification: SkillsChangedNotification = serde_json::from_value(params)?; + + assert_eq!(notification, SkillsChangedNotification {}); + Ok(()) +} From 52521a5e408c86b22dfe37edab7cec2376854961 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 3 Mar 2026 17:03:45 -0800 Subject: [PATCH 356/385] feat(app-server): propagate app-server trace context into core (#13368) ### Summary Propagate trace context originating at app-server RPC method handlers -> codex core submission loop (so this includes spans such as `run_turn`!). This implements PR 2 of the app-server tracing rollout. This also removes the old lower-level env-based reparenting in core so explicit request/submission ancestry wins instead of being overridden by ambient `TRACEPARENT` state. ### What changed - Added `trace: Option` to codex_protocol::Submission - Taught `Codex::submit()` / `submit_with_id()` to automatically capture the current span context when constructing or forwarding a submission - Wrapped the core submission loop in a submission_dispatch span parented from Submission.trace - Warn on invalid submission trace carriers and ignore them cleanly - Removed the old env-based downstream reparenting path in core task execution - Stopped OTEL provider init from implicitly attaching env trace context process-wide - Updated mcp-server Submission call sites for the new field Added focused unit tests for: - capturing trace context into Submission - preferring `Submission.trace` when building the core dispatch span ### Why PR 1 gave us consistent inbound request spans in app-server, but that only covered the transport boundary. For long-running work like turns and reviews, the important missing piece was preserving ancestry after the request handler returns and core continues work on a different async path. This change makes that handoff explicit and keeps the parentage rules simple: - app-server request span sets the current context - `Submission.trace` snapshots that context - core restores it once, at the submission boundary - deeper core spans inherit naturally That also lets us stop relying on env-based reparenting for this path, which was too ambient and could override explicit ancestry. --- codex-rs/Cargo.lock | 6 + codex-rs/core/Cargo.toml | 2 + codex-rs/core/src/codex.rs | 475 ++++++++++++------- codex-rs/core/src/codex_delegate.rs | 50 +- codex-rs/core/src/tasks/regular.rs | 3 - codex-rs/exec/Cargo.toml | 4 + codex-rs/exec/src/lib.rs | 110 ++++- codex-rs/mcp-server/src/codex_tool_runner.rs | 1 + codex-rs/mcp-server/src/message_processor.rs | 1 + codex-rs/otel/src/otel_provider.rs | 22 - codex-rs/otel/src/traces/otel_manager.rs | 8 - codex-rs/protocol/src/protocol.rs | 3 + 12 files changed, 489 insertions(+), 196 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 48e8c598db..1974883dd4 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1851,6 +1851,7 @@ dependencies = [ "notify", "once_cell", "openssl-sys", + "opentelemetry", "opentelemetry_sdk", "os_info", "predicates", @@ -1880,6 +1881,7 @@ dependencies = [ "toml 0.9.11+spec-1.1.0", "toml_edit 0.24.0+spec-1.1.0", "tracing", + "tracing-opentelemetry", "tracing-subscriber", "tracing-test", "url", @@ -1916,6 +1918,7 @@ dependencies = [ "codex-arg0", "codex-cloud-requirements", "codex-core", + "codex-otel", "codex-protocol", "codex-utils-absolute-path", "codex-utils-cargo-bin", @@ -1925,6 +1928,8 @@ dependencies = [ "codex-utils-sandbox-summary", "core_test_support", "libc", + "opentelemetry", + "opentelemetry_sdk", "owo-colors", "predicates", "pretty_assertions", @@ -1936,6 +1941,7 @@ dependencies = [ "tempfile", "tokio", "tracing", + "tracing-opentelemetry", "tracing-subscriber", "ts-rs", "uuid", diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index eafedc9d73..ebb01edc4e 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -161,6 +161,7 @@ core_test_support = { workspace = true } ctor = { workspace = true } insta = { workspace = true } maplit = { workspace = true } +opentelemetry = { workspace = true } predicates = { workspace = true } pretty_assertions = { workspace = true } test-case = "3.3.1" @@ -170,6 +171,7 @@ opentelemetry_sdk = { workspace = true, features = [ ] } serial_test = { workspace = true } tempfile = { workspace = true } +tracing-opentelemetry = { workspace = true } tracing-subscriber = { workspace = true } tracing-test = { workspace = true, features = ["no-env-filter"] } walkdir = { workspace = true } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 1ead1871f5..87aac73185 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -70,6 +70,8 @@ use codex_hooks::HooksConfig; use codex_network_proxy::NetworkProxy; use codex_network_proxy::NetworkProxyAuditMetadata; use codex_network_proxy::normalize_host; +use codex_otel::current_span_w3c_trace_context; +use codex_otel::set_parent_from_w3c_trace_context; use codex_protocol::ThreadId; use codex_protocol::approvals::ExecPolicyAmendment; use codex_protocol::approvals::NetworkPolicyAmendment; @@ -539,14 +541,21 @@ impl Codex { /// Submit the `op` wrapped in a `Submission` with a unique ID. pub async fn submit(&self, op: Op) -> CodexResult { let id = Uuid::now_v7().to_string(); - let sub = Submission { id: id.clone(), op }; + let sub = Submission { + id: id.clone(), + op, + trace: None, + }; self.submit_with_id(sub).await?; Ok(id) } /// Use sparingly: prefer `submit()` so Codex is responsible for generating /// unique IDs for each submission. - pub async fn submit_with_id(&self, sub: Submission) -> CodexResult<()> { + pub async fn submit_with_id(&self, mut sub: Submission) -> CodexResult<()> { + if sub.trace.is_none() { + sub.trace = current_span_w3c_trace_context(); + } self.tx_sub .send(sub) .await @@ -3686,176 +3695,230 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv // To break out of this loop, send Op::Shutdown. while let Ok(sub) = rx_sub.recv().await { debug!(?sub, "Submission"); - match sub.op.clone() { - Op::Interrupt => { - handlers::interrupt(&sess).await; - } - Op::CleanBackgroundTerminals => { - handlers::clean_background_terminals(&sess).await; - } - Op::RealtimeConversationStart(params) => { - if let Err(err) = - handle_realtime_conversation_start(&sess, sub.id.clone(), params).await - { - sess.send_event_raw(Event { - id: sub.id.clone(), - msg: EventMsg::Error(ErrorEvent { - message: err.to_string(), - codex_error_info: Some(CodexErrorInfo::Other), - }), - }) - .await; + let dispatch_span = submission_dispatch_span(&sub); + let should_exit = async { + match sub.op.clone() { + Op::Interrupt => { + handlers::interrupt(&sess).await; + false } - } - Op::RealtimeConversationAudio(params) => { - handle_realtime_conversation_audio(&sess, sub.id.clone(), params).await; - } - Op::RealtimeConversationText(params) => { - handle_realtime_conversation_text(&sess, sub.id.clone(), params).await; - } - Op::RealtimeConversationClose => { - handle_realtime_conversation_close(&sess, sub.id.clone()).await; - } - Op::OverrideTurnContext { - cwd, - approval_policy, - sandbox_policy, - windows_sandbox_level, - model, - effort, - summary, - service_tier, - collaboration_mode, - personality, - } => { - let collaboration_mode = if let Some(collab_mode) = collaboration_mode { - collab_mode - } else { - let state = sess.state.lock().await; - state.session_configuration.collaboration_mode.with_updates( - model.clone(), - effort, - None, + Op::CleanBackgroundTerminals => { + handlers::clean_background_terminals(&sess).await; + false + } + Op::RealtimeConversationStart(params) => { + if let Err(err) = + handle_realtime_conversation_start(&sess, sub.id.clone(), params).await + { + sess.send_event_raw(Event { + id: sub.id.clone(), + msg: EventMsg::Error(ErrorEvent { + message: err.to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + }), + }) + .await; + } + false + } + Op::RealtimeConversationAudio(params) => { + handle_realtime_conversation_audio(&sess, sub.id.clone(), params).await; + false + } + Op::RealtimeConversationText(params) => { + handle_realtime_conversation_text(&sess, sub.id.clone(), params).await; + false + } + Op::RealtimeConversationClose => { + handle_realtime_conversation_close(&sess, sub.id.clone()).await; + false + } + Op::OverrideTurnContext { + cwd, + approval_policy, + sandbox_policy, + windows_sandbox_level, + model, + effort, + summary, + service_tier, + collaboration_mode, + personality, + } => { + let collaboration_mode = if let Some(collab_mode) = collaboration_mode { + collab_mode + } else { + let state = sess.state.lock().await; + state.session_configuration.collaboration_mode.with_updates( + model.clone(), + effort, + None, + ) + }; + handlers::override_turn_context( + &sess, + sub.id.clone(), + SessionSettingsUpdate { + cwd, + approval_policy, + sandbox_policy, + windows_sandbox_level, + collaboration_mode: Some(collaboration_mode), + reasoning_summary: summary, + service_tier, + personality, + ..Default::default() + }, ) - }; - handlers::override_turn_context( - &sess, - sub.id.clone(), - SessionSettingsUpdate { - cwd, - approval_policy, - sandbox_policy, - windows_sandbox_level, - collaboration_mode: Some(collaboration_mode), - reasoning_summary: summary, - service_tier, - personality, - ..Default::default() - }, - ) - .await; - } - Op::UserInput { .. } | Op::UserTurn { .. } => { - handlers::user_input_or_turn(&sess, sub.id.clone(), sub.op).await; - } - Op::ExecApproval { - id: approval_id, - turn_id, - decision, - } => { - handlers::exec_approval(&sess, approval_id, turn_id, decision).await; - } - Op::PatchApproval { id, decision } => { - handlers::patch_approval(&sess, id, decision).await; - } - Op::UserInputAnswer { id, response } => { - handlers::request_user_input_response(&sess, id, response).await; - } - Op::DynamicToolResponse { id, response } => { - handlers::dynamic_tool_response(&sess, id, response).await; - } - Op::AddToHistory { text } => { - handlers::add_to_history(&sess, &config, text).await; - } - Op::GetHistoryEntryRequest { offset, log_id } => { - handlers::get_history_entry_request(&sess, &config, sub.id.clone(), offset, log_id) .await; - } - Op::ListMcpTools => { - handlers::list_mcp_tools(&sess, &config, sub.id.clone()).await; - } - Op::RefreshMcpServers { config } => { - handlers::refresh_mcp_servers(&sess, config).await; - } - Op::ReloadUserConfig => { - handlers::reload_user_config(&sess).await; - } - Op::ListCustomPrompts => { - handlers::list_custom_prompts(&sess, sub.id.clone()).await; - } - Op::ListSkills { cwds, force_reload } => { - handlers::list_skills(&sess, sub.id.clone(), cwds, force_reload).await; - } - Op::ListRemoteSkills { - hazelnut_scope, - product_surface, - enabled, - } => { - handlers::list_remote_skills( - &sess, - &config, - sub.id.clone(), + false + } + Op::UserInput { .. } | Op::UserTurn { .. } => { + handlers::user_input_or_turn(&sess, sub.id.clone(), sub.op).await; + false + } + Op::ExecApproval { + id: approval_id, + turn_id, + decision, + } => { + handlers::exec_approval(&sess, approval_id, turn_id, decision).await; + false + } + Op::PatchApproval { id, decision } => { + handlers::patch_approval(&sess, id, decision).await; + false + } + Op::UserInputAnswer { id, response } => { + handlers::request_user_input_response(&sess, id, response).await; + false + } + Op::DynamicToolResponse { id, response } => { + handlers::dynamic_tool_response(&sess, id, response).await; + false + } + Op::AddToHistory { text } => { + handlers::add_to_history(&sess, &config, text).await; + false + } + Op::GetHistoryEntryRequest { offset, log_id } => { + handlers::get_history_entry_request( + &sess, + &config, + sub.id.clone(), + offset, + log_id, + ) + .await; + false + } + Op::ListMcpTools => { + handlers::list_mcp_tools(&sess, &config, sub.id.clone()).await; + false + } + Op::RefreshMcpServers { config } => { + handlers::refresh_mcp_servers(&sess, config).await; + false + } + Op::ReloadUserConfig => { + handlers::reload_user_config(&sess).await; + false + } + Op::ListCustomPrompts => { + handlers::list_custom_prompts(&sess, sub.id.clone()).await; + false + } + Op::ListSkills { cwds, force_reload } => { + handlers::list_skills(&sess, sub.id.clone(), cwds, force_reload).await; + false + } + Op::ListRemoteSkills { hazelnut_scope, product_surface, enabled, - ) - .await; - } - Op::DownloadRemoteSkill { hazelnut_id } => { - handlers::export_remote_skill(&sess, &config, sub.id.clone(), hazelnut_id).await; - } - Op::Undo => { - handlers::undo(&sess, sub.id.clone()).await; - } - Op::Compact => { - handlers::compact(&sess, sub.id.clone()).await; - } - Op::DropMemories => { - handlers::drop_memories(&sess, &config, sub.id.clone()).await; - } - Op::UpdateMemories => { - handlers::update_memories(&sess, &config, sub.id.clone()).await; - } - Op::ThreadRollback { num_turns } => { - handlers::thread_rollback(&sess, sub.id.clone(), num_turns).await; - } - Op::SetThreadName { name } => { - handlers::set_thread_name(&sess, sub.id.clone(), name).await; - } - Op::RunUserShellCommand { command } => { - handlers::run_user_shell_command(&sess, sub.id.clone(), command).await; - } - Op::ResolveElicitation { - server_name, - request_id, - decision, - } => { - handlers::resolve_elicitation(&sess, server_name, request_id, decision).await; - } - Op::Shutdown => { - if handlers::shutdown(&sess, sub.id.clone()).await { - break; + } => { + handlers::list_remote_skills( + &sess, + &config, + sub.id.clone(), + hazelnut_scope, + product_surface, + enabled, + ) + .await; + false } + Op::DownloadRemoteSkill { hazelnut_id } => { + handlers::export_remote_skill(&sess, &config, sub.id.clone(), hazelnut_id) + .await; + false + } + Op::Undo => { + handlers::undo(&sess, sub.id.clone()).await; + false + } + Op::Compact => { + handlers::compact(&sess, sub.id.clone()).await; + false + } + Op::DropMemories => { + handlers::drop_memories(&sess, &config, sub.id.clone()).await; + false + } + Op::UpdateMemories => { + handlers::update_memories(&sess, &config, sub.id.clone()).await; + false + } + Op::ThreadRollback { num_turns } => { + handlers::thread_rollback(&sess, sub.id.clone(), num_turns).await; + false + } + Op::SetThreadName { name } => { + handlers::set_thread_name(&sess, sub.id.clone(), name).await; + false + } + Op::RunUserShellCommand { command } => { + handlers::run_user_shell_command(&sess, sub.id.clone(), command).await; + false + } + Op::ResolveElicitation { + server_name, + request_id, + decision, + } => { + handlers::resolve_elicitation(&sess, server_name, request_id, decision).await; + false + } + Op::Shutdown => handlers::shutdown(&sess, sub.id.clone()).await, + Op::Review { review_request } => { + handlers::review(&sess, &config, sub.id.clone(), review_request).await; + false + } + _ => false, // Ignore unknown ops; enum is non_exhaustive to allow extensions. } - Op::Review { review_request } => { - handlers::review(&sess, &config, sub.id.clone(), review_request).await; - } - _ => {} // Ignore unknown ops; enum is non_exhaustive to allow extensions. + } + .instrument(dispatch_span) + .await; + if should_exit { + break; } } debug!("Agent loop exited"); } +fn submission_dispatch_span(sub: &Submission) -> tracing::Span { + let dispatch_span = info_span!("submission_dispatch", submission.id = sub.id.as_str()); + if let Some(trace) = sub.trace.as_ref() + && !set_parent_from_w3c_trace_context(&dispatch_span, trace) + { + warn!( + submission.id = sub.id.as_str(), + "ignoring invalid submission trace carrier" + ); + } + dispatch_span +} + /// Operation handlers mod handlers { use crate::codex::Session; @@ -6627,9 +6690,17 @@ mod tests { use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelsResponse; + use codex_protocol::protocol::Submission; + use codex_protocol::protocol::W3cTraceContext; + use opentelemetry::trace::TraceContextExt; + use opentelemetry::trace::TraceId; + use opentelemetry::trace::TracerProvider as _; + use opentelemetry_sdk::trace::SdkTracerProvider; use std::path::Path; use std::time::Duration; use tokio::time::sleep; + use tracing_opentelemetry::OpenTelemetrySpanExt; + use tracing_subscriber::prelude::*; use codex_protocol::mcp::CallToolResult as McpCallToolResult; use pretty_assertions::assert_eq; @@ -8105,6 +8176,12 @@ mod tests { }) } + fn test_tracing_subscriber() -> impl tracing::Subscriber + Send + Sync { + let provider = SdkTracerProvider::builder().build(); + let tracer = provider.tracer("codex-core-tests"); + tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer)) + } + async fn build_test_config(codex_home: &Path) -> Config { ConfigBuilder::default() .codex_home(codex_home.to_path_buf()) @@ -8432,6 +8509,86 @@ mod tests { (session, turn_context) } + #[tokio::test] + async fn submit_with_id_captures_current_span_trace_context() { + let (session, _turn_context) = make_session_and_context().await; + let (tx_sub, rx_sub) = async_channel::bounded(1); + let (_tx_event, rx_event) = async_channel::unbounded(); + let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit); + let codex = Codex { + tx_sub, + rx_event, + agent_status, + session: Arc::new(session), + }; + + let subscriber = test_tracing_subscriber(); + let _guard = tracing::subscriber::set_default(subscriber); + + let request_parent = W3cTraceContext { + traceparent: Some("00-00000000000000000000000000000011-0000000000000022-01".into()), + tracestate: Some("vendor=value".into()), + }; + let request_span = info_span!("app_server.request"); + assert!(set_parent_from_w3c_trace_context( + &request_span, + &request_parent + )); + + let expected_trace = async { + let expected_trace = + current_span_w3c_trace_context().expect("current span should have trace context"); + codex + .submit_with_id(Submission { + id: "sub-1".into(), + op: Op::Interrupt, + trace: None, + }) + .await + .expect("submit should succeed"); + expected_trace + } + .instrument(request_span) + .await; + + let submitted = rx_sub.recv().await.expect("submission"); + assert_eq!(submitted.trace, Some(expected_trace)); + } + + #[test] + fn submission_dispatch_span_prefers_submission_trace_context() { + let subscriber = test_tracing_subscriber(); + let _guard = tracing::subscriber::set_default(subscriber); + + let ambient_parent = W3cTraceContext { + traceparent: Some("00-00000000000000000000000000000033-0000000000000044-01".into()), + tracestate: None, + }; + let ambient_span = info_span!("ambient"); + assert!(set_parent_from_w3c_trace_context( + &ambient_span, + &ambient_parent + )); + + let submission_trace = W3cTraceContext { + traceparent: Some("00-00000000000000000000000000000055-0000000000000066-01".into()), + tracestate: Some("vendor=value".into()), + }; + let dispatch_span = ambient_span.in_scope(|| { + submission_dispatch_span(&Submission { + id: "sub-1".into(), + op: Op::Interrupt, + trace: Some(submission_trace), + }) + }); + + let trace_id = dispatch_span.context().span().span_context().trace_id(); + assert_eq!( + trace_id, + TraceId::from_hex("00000000000000000000000000000055").expect("trace id") + ); + } + pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( dynamic_tools: Vec, ) -> ( diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 1e8dd71419..f6ef7f36e0 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -154,6 +154,7 @@ pub(crate) async fn run_codex_thread_one_shot( .send(Submission { id: "shutdown".to_string(), op: Op::Shutdown {}, + trace: None, }) .await; child_cancel.cancel(); @@ -298,11 +299,11 @@ async fn forward_ops( cancel_token_ops: CancellationToken, ) { loop { - let op: Op = match rx_ops.recv().or_cancel(&cancel_token_ops).await { - Ok(Ok(Submission { id: _, op })) => op, + let submission = match rx_ops.recv().or_cancel(&cancel_token_ops).await { + Ok(Ok(submission)) => submission, Ok(Err(_)) | Err(_) => break, }; - let _ = codex.submit(op).await; + let _ = codex.submit_with_id(submission).await; } } @@ -550,4 +551,47 @@ mod tests { "expected Shutdown op after cancellation" ); } + + #[tokio::test] + async fn forward_ops_preserves_submission_trace_context() { + let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let (_tx_events, rx_events) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit); + let (session, _ctx, _rx_evt) = crate::codex::make_session_and_context_with_rx().await; + let codex = Arc::new(Codex { + tx_sub, + rx_event: rx_events, + agent_status, + session, + }); + let (tx_ops, rx_ops) = bounded(1); + let cancel = CancellationToken::new(); + let forward = tokio::spawn(forward_ops(Arc::clone(&codex), rx_ops, cancel)); + + let submission = Submission { + id: "sub-1".to_string(), + op: Op::Interrupt, + trace: Some(codex_protocol::protocol::W3cTraceContext { + traceparent: Some( + "00-1234567890abcdef1234567890abcdef-1234567890abcdef-01".to_string(), + ), + tracestate: Some("vendor=state".to_string()), + }), + }; + tx_ops.send(submission.clone()).await.unwrap(); + drop(tx_ops); + + let forwarded = timeout(Duration::from_secs(1), rx_sub.recv()) + .await + .expect("forward_ops hung") + .expect("forwarded submission missing"); + assert_eq!(submission.id, forwarded.id); + assert_eq!(submission.op, forwarded.op); + assert_eq!(submission.trace, forwarded.trace); + + timeout(Duration::from_secs(1), forward) + .await + .expect("forward_ops did not exit") + .expect("forward_ops join error"); + } } diff --git a/codex-rs/core/src/tasks/regular.rs b/codex-rs/core/src/tasks/regular.rs index 62493a46cd..b4af4e11f3 100644 --- a/codex-rs/core/src/tasks/regular.rs +++ b/codex-rs/core/src/tasks/regular.rs @@ -78,9 +78,6 @@ impl SessionTask for RegularTask { let sess = session.clone_session(); let run_turn_span = trace_span!("run_turn"); sess.set_server_reasoning_included(false).await; - sess.services - .otel_manager - .apply_traceparent_parent(&run_turn_span); let prewarmed_client_session = self.take_prewarmed_session().await; run_turn( sess, diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index f3fa573ab5..1eb4f7e277 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -21,6 +21,7 @@ clap = { workspace = true, features = ["derive"] } codex-arg0 = { workspace = true } codex-cloud-requirements = { workspace = true } codex-core = { workspace = true } +codex-otel = { workspace = true } codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-cli = { workspace = true } @@ -55,10 +56,13 @@ codex-apply-patch = { workspace = true } codex-utils-cargo-bin = { workspace = true } core_test_support = { workspace = true } libc = { workspace = true } +opentelemetry = { workspace = true } +opentelemetry_sdk = { workspace = true } predicates = { workspace = true } pretty_assertions = { workspace = true } rmcp = { workspace = true } tempfile = { workspace = true } +tracing-opentelemetry = { workspace = true } uuid = { workspace = true } walkdir = { workspace = true } wiremock = { workspace = true } diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 5f0ac4865e..0c7271c56f 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -34,6 +34,8 @@ use codex_core::format_exec_policy_error_with_source; use codex_core::git_info::get_git_repo_root; use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_core::models_manager::manager::RefreshStrategy; +use codex_otel::set_parent_from_context; +use codex_otel::traceparent_context_from_env; use codex_protocol::approvals::ElicitationAction; use codex_protocol::config_types::SandboxMode; use codex_protocol::protocol::AskForApproval; @@ -58,9 +60,12 @@ use std::path::PathBuf; use std::sync::Arc; use supports_color::Stream; use tokio::sync::Mutex; +use tracing::Instrument; use tracing::debug; use tracing::error; +use tracing::field; use tracing::info; +use tracing::info_span; use tracing::warn; use tracing_subscriber::EnvFilter; use tracing_subscriber::prelude::*; @@ -94,6 +99,32 @@ struct ThreadEventEnvelope { suppress_output: bool, } +struct ExecRunArgs { + command: Option, + config: Config, + cursor_ansi: bool, + dangerously_bypass_approvals_and_sandbox: bool, + exec_span: tracing::Span, + images: Vec, + json_mode: bool, + last_message_file: Option, + model_provider: Option, + oss: bool, + output_schema_path: Option, + prompt: Option, + skip_git_repo_check: bool, + stderr_with_ansi: bool, +} + +fn exec_root_span() -> tracing::Span { + info_span!( + "codex.exec", + otel.kind = "internal", + thread.id = field::Empty, + turn.id = field::Empty, + ) +} + pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { if let Err(err) = set_default_originator("codex_exec".to_string()) { tracing::warn!(?err, "Failed to set codex exec originator override {err:?}"); @@ -347,6 +378,48 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result .with(otel_logger_layer) .try_init(); + let exec_span = exec_root_span(); + if let Some(context) = traceparent_context_from_env() { + set_parent_from_context(&exec_span, context); + } + run_exec_session(ExecRunArgs { + command, + config, + cursor_ansi, + dangerously_bypass_approvals_and_sandbox, + exec_span: exec_span.clone(), + images, + json_mode, + last_message_file, + model_provider, + oss, + output_schema_path, + prompt, + skip_git_repo_check, + stderr_with_ansi, + }) + .instrument(exec_span) + .await +} + +async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> { + let ExecRunArgs { + command, + config, + cursor_ansi, + dangerously_bypass_approvals_and_sandbox, + exec_span, + images, + json_mode, + last_message_file, + model_provider, + oss, + output_schema_path, + prompt, + skip_git_repo_check, + stderr_with_ansi, + } = args; + let mut event_processor: Box = match json_mode { true => Box::new(EventProcessorWithJsonOutput::new(last_message_file.clone())), _ => Box::new(EventProcessorWithHumanOutput::create_with_ansi( @@ -435,6 +508,9 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result } else { thread_manager.start_thread(config.clone()).await? }; + let primary_thread_id_for_span = primary_thread_id.to_string(); + exec_span.record("thread.id", primary_thread_id_for_span.as_str()); + let (initial_operation, prompt_summary) = match (command, prompt, images) { (Some(ExecCommand::Review(review_cli)), _, _) => { let review_request = build_review_request(review_cli)?; @@ -554,7 +630,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result }); } - match initial_operation { + let task_id = match initial_operation { InitialOperation::UserTurn { items, output_schema, @@ -583,6 +659,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result task_id } }; + exec_span.record("turn.id", task_id.as_str()); // Run the loop until the task is complete. // Track whether a fatal error was reported by the server so we can @@ -934,13 +1011,44 @@ fn build_review_request(args: ReviewArgs) -> anyhow::Result { #[cfg(test)] mod tests { use super::*; + use codex_otel::set_parent_from_w3c_trace_context; + use opentelemetry::trace::TraceContextExt; + use opentelemetry::trace::TraceId; + use opentelemetry::trace::TracerProvider as _; + use opentelemetry_sdk::trace::SdkTracerProvider; use pretty_assertions::assert_eq; + use tracing_opentelemetry::OpenTelemetrySpanExt; + + fn test_tracing_subscriber() -> impl tracing::Subscriber + Send + Sync { + let provider = SdkTracerProvider::builder().build(); + let tracer = provider.tracer("codex-exec-tests"); + tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer)) + } #[test] fn exec_defaults_analytics_to_enabled() { assert_eq!(DEFAULT_ANALYTICS_ENABLED, true); } + #[test] + fn exec_root_span_can_be_parented_from_trace_context() { + let subscriber = test_tracing_subscriber(); + let _guard = tracing::subscriber::set_default(subscriber); + + let parent = codex_protocol::protocol::W3cTraceContext { + traceparent: Some("00-00000000000000000000000000000077-0000000000000088-01".into()), + tracestate: Some("vendor=value".into()), + }; + let exec_span = exec_root_span(); + assert!(set_parent_from_w3c_trace_context(&exec_span, &parent)); + + let trace_id = exec_span.context().span().span_context().trace_id(); + assert_eq!( + trace_id, + TraceId::from_hex("00000000000000000000000000000077").expect("trace id") + ); + } + #[test] fn builds_uncommitted_review_request() { let request = build_review_request(ReviewArgs { diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index e624fe2b1b..24896b042a 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -115,6 +115,7 @@ pub async fn run_codex_tool_session( }], final_output_json_schema: None, }, + trace: None, }; if let Err(e) = thread.submit_with_id(submission).await { diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 6b634e1947..e51c3d619d 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -576,6 +576,7 @@ impl MessageProcessor { .submit_with_id(Submission { id: request_id_string, op: codex_protocol::protocol::Op::Interrupt, + trace: None, }) .await { diff --git a/codex-rs/otel/src/otel_provider.rs b/codex-rs/otel/src/otel_provider.rs index c9233f5d6a..dcfb313b67 100644 --- a/codex-rs/otel/src/otel_provider.rs +++ b/codex-rs/otel/src/otel_provider.rs @@ -7,7 +7,6 @@ use crate::trace_context::context_from_trace_headers; use gethostname::gethostname; use opentelemetry::Context; use opentelemetry::KeyValue; -use opentelemetry::context::ContextGuard; use opentelemetry::global; use opentelemetry::trace::TracerProvider as _; use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; @@ -28,7 +27,6 @@ use opentelemetry_sdk::trace::BatchSpanProcessor; use opentelemetry_sdk::trace::SdkTracerProvider; use opentelemetry_sdk::trace::Tracer; use opentelemetry_semantic_conventions as semconv; -use std::cell::RefCell; use std::env; use std::error::Error; use std::sync::OnceLock; @@ -43,10 +41,6 @@ const HOST_NAME_ATTRIBUTE: &str = "host.name"; const TRACEPARENT_ENV_VAR: &str = "TRACEPARENT"; const TRACESTATE_ENV_VAR: &str = "TRACESTATE"; static TRACEPARENT_CONTEXT: OnceLock> = OnceLock::new(); - -thread_local! { - static TRACEPARENT_GUARD: RefCell> = const { RefCell::new(None) }; -} pub struct OtelProvider { pub logger: Option, pub tracer_provider: Option, @@ -113,10 +107,6 @@ impl OtelProvider { global::set_tracer_provider(provider); global::set_text_map_propagator(TraceContextPropagator::new()); } - if tracer.is_some() { - attach_traceparent_context(); - } - Ok(Some(Self { logger, tracer_provider, @@ -176,18 +166,6 @@ pub fn traceparent_context_from_env() -> Option { .clone() } -fn attach_traceparent_context() { - TRACEPARENT_GUARD.with(|guard| { - let mut guard = guard.borrow_mut(); - if guard.is_some() { - return; - } - if let Some(context) = traceparent_context_from_env() { - *guard = Some(context.attach()); - } - }); -} - fn load_traceparent_context() -> Option { let traceparent = env::var(TRACEPARENT_ENV_VAR).ok()?; let tracestate = env::var(TRACESTATE_ENV_VAR).ok(); diff --git a/codex-rs/otel/src/traces/otel_manager.rs b/codex-rs/otel/src/traces/otel_manager.rs index 32b9fba860..1074b6edd1 100644 --- a/codex-rs/otel/src/traces/otel_manager.rs +++ b/codex-rs/otel/src/traces/otel_manager.rs @@ -15,7 +15,6 @@ use crate::metrics::names::WEBSOCKET_EVENT_COUNT_METRIC; use crate::metrics::names::WEBSOCKET_EVENT_DURATION_METRIC; use crate::metrics::names::WEBSOCKET_REQUEST_COUNT_METRIC; use crate::metrics::names::WEBSOCKET_REQUEST_DURATION_METRIC; -use crate::otel_provider::traceparent_context_from_env; use crate::sanitize_metric_tag_value; use chrono::SecondsFormat; use chrono::Utc; @@ -41,7 +40,6 @@ use std::time::Duration; use std::time::Instant; use tokio::time::error::Elapsed; use tracing::Span; -use tracing_opentelemetry::OpenTelemetrySpanExt; pub use crate::OtelEventMetadata; pub use crate::OtelManager; @@ -92,12 +90,6 @@ impl OtelManager { } } - pub fn apply_traceparent_parent(&self, span: &Span) { - if let Some(context) = traceparent_context_from_env() { - let _ = span.set_parent(context); - } - } - pub fn record_responses(&self, handle_responses_span: &Span, event: &ResponseEvent) { handle_responses_span.record("otel.name", OtelManager::responses_type(event)); diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 3f1c392719..2591a8fb1d 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -82,6 +82,9 @@ pub struct Submission { pub id: String, /// Payload pub op: Op, + /// Optional W3C trace carrier propagated across async submission handoffs. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trace: Option, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] From 639a5f6c48a22fa0b828064518fadcafe8ad31e4 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Tue, 3 Mar 2026 17:31:37 -0800 Subject: [PATCH 357/385] copy command-runner to CODEX_HOME so sandbox users can always execute it (#13413) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit • Keep Windows sandbox runner launches working from packaged installs by running the helper from a user-owned runtime location. On some Windows installs, the packaged helper location is difficult to use reliably for sandboxed runner launches even though the binaries are present. This change works around that by copying codex- command-runner.exe into CODEX_HOME/.sandbox-bin/, reusing that copy across launches, and falling back to the existing packaged-path lookup if anything goes wrong. The runtime copy lives in a dedicated directory with tighter ACLs than .sandbox: sandbox users can read and execute the runner there, but they cannot modify it. This keeps the workaround focused on the command runner, leaves the setup helper on its trusted packaged path, and adds logging so it is clear which runner path was selected at launch. --- codex-rs/windows-sandbox-rs/Cargo.toml | 2 +- .../windows-sandbox-rs/src/elevated_impl.rs | 36 +- .../src/helper_materialization.rs | 351 ++++++++++++++++++ codex-rs/windows-sandbox-rs/src/identity.rs | 2 +- codex-rs/windows-sandbox-rs/src/lib.rs | 3 + .../windows-sandbox-rs/src/setup_main_win.rs | 34 +- .../src/setup_orchestrator.rs | 45 ++- 7 files changed, 448 insertions(+), 25 deletions(-) create mode 100644 codex-rs/windows-sandbox-rs/src/helper_materialization.rs diff --git a/codex-rs/windows-sandbox-rs/Cargo.toml b/codex-rs/windows-sandbox-rs/Cargo.toml index f92c389e4b..cb7cebe9d7 100644 --- a/codex-rs/windows-sandbox-rs/Cargo.toml +++ b/codex-rs/windows-sandbox-rs/Cargo.toml @@ -29,6 +29,7 @@ codex-utils-string = { workspace = true } dunce = "1.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +tempfile = "3" windows = { version = "0.58", features = [ "Win32_Foundation", "Win32_NetworkManagement_WindowsFirewall", @@ -79,7 +80,6 @@ version = "0.52" [dev-dependencies] pretty_assertions = { workspace = true } -tempfile = "3" [build-dependencies] winres = "0.1" diff --git a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs index 8f8de37e0e..b3a5e9a1aa 100644 --- a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs +++ b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs @@ -6,6 +6,8 @@ mod windows_impl { use crate::env::ensure_non_interactive_pager; use crate::env::inherit_path_env; use crate::env::normalize_null_device_env; + use crate::helper_materialization::resolve_helper_for_launch; + use crate::helper_materialization::HelperExecutable; use crate::identity::require_logon_sandbox_creds; use crate::logging::log_failure; use crate::logging::log_note; @@ -110,17 +112,9 @@ mod windows_impl { } } - /// Locates `codex-command-runner.exe` next to the current binary. - fn find_runner_exe() -> PathBuf { - if let Ok(exe) = std::env::current_exe() { - if let Some(dir) = exe.parent() { - let candidate = dir.join("codex-command-runner.exe"); - if candidate.exists() { - return candidate; - } - } - } - PathBuf::from("codex-command-runner.exe") + /// Resolves the command runner path, preferring CODEX_HOME/.sandbox/bin. + fn find_runner_exe(codex_home: &Path, log_dir: Option<&Path>) -> PathBuf { + resolve_helper_for_launch(HelperExecutable::CommandRunner, codex_home, log_dir) } /// Generates a unique named-pipe path used to communicate with the runner process. @@ -286,7 +280,7 @@ mod windows_impl { )?; // Launch runner as sandbox user via CreateProcessWithLogonW. - let runner_exe = find_runner_exe(); + let runner_exe = find_runner_exe(codex_home, logs_base_dir); let runner_cmdline = runner_exe .to_str() .map(|s| s.to_string()) @@ -340,6 +334,16 @@ mod windows_impl { // Suppress WER/UI popups from the runner process so we can collect exit codes. let _ = unsafe { SetErrorMode(0x0001 | 0x0002) }; // SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX + log_note( + &format!( + "runner launch: exe={} cmdline={} cwd={}", + runner_exe.display(), + runner_full_cmd, + cwd.display() + ), + logs_base_dir, + ); + // Ensure command line buffer is mutable and includes the exe as argv[0]. let spawn_res = unsafe { CreateProcessWithLogonW( @@ -362,6 +366,14 @@ mod windows_impl { }; if spawn_res == 0 { let err = unsafe { GetLastError() } as i32; + log_note( + &format!( + "runner launch failed before process start: exe={} cmdline={} error={err}", + runner_exe.display(), + runner_full_cmd + ), + logs_base_dir, + ); return Err(anyhow::anyhow!("CreateProcessWithLogonW failed: {}", err)); } diff --git a/codex-rs/windows-sandbox-rs/src/helper_materialization.rs b/codex-rs/windows-sandbox-rs/src/helper_materialization.rs new file mode 100644 index 0000000000..cda0800628 --- /dev/null +++ b/codex-rs/windows-sandbox-rs/src/helper_materialization.rs @@ -0,0 +1,351 @@ +use anyhow::anyhow; +use anyhow::Context; +use anyhow::Result; +use std::collections::HashMap; +use std::fs; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Mutex; +use std::sync::OnceLock; +use tempfile::NamedTempFile; + +use crate::logging::log_note; +use crate::sandbox_bin_dir; + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub(crate) enum HelperExecutable { + CommandRunner, +} + +impl HelperExecutable { + fn file_name(self) -> &'static str { + match self { + Self::CommandRunner => "codex-command-runner.exe", + } + } + + fn label(self) -> &'static str { + match self { + Self::CommandRunner => "command-runner", + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum CopyOutcome { + Reused, + ReCopied, +} + +static HELPER_PATH_CACHE: OnceLock>> = OnceLock::new(); + +pub(crate) fn helper_bin_dir(codex_home: &Path) -> PathBuf { + sandbox_bin_dir(codex_home) +} + +pub(crate) fn legacy_lookup(kind: HelperExecutable) -> PathBuf { + if let Ok(exe) = std::env::current_exe() { + if let Some(dir) = exe.parent() { + let candidate = dir.join(kind.file_name()); + if candidate.exists() { + return candidate; + } + } + } + PathBuf::from(kind.file_name()) +} + +pub(crate) fn resolve_helper_for_launch( + kind: HelperExecutable, + codex_home: &Path, + log_dir: Option<&Path>, +) -> PathBuf { + match copy_helper_if_needed(kind, codex_home, log_dir) { + Ok(path) => { + log_note( + &format!( + "helper launch resolution: using copied {} path {}", + kind.label(), + path.display() + ), + log_dir, + ); + path + } + Err(err) => { + let fallback = legacy_lookup(kind); + log_note( + &format!( + "helper copy failed for {}: {err:#}; falling back to legacy path {}", + kind.label(), + fallback.display() + ), + log_dir, + ); + fallback + } + } +} + +pub(crate) fn copy_helper_if_needed( + kind: HelperExecutable, + codex_home: &Path, + log_dir: Option<&Path>, +) -> Result { + let cache_key = format!("{}|{}", kind.file_name(), codex_home.display()); + if let Some(path) = cached_helper_path(&cache_key) { + log_note( + &format!( + "helper copy: using in-memory cache for {} -> {}", + kind.label(), + path.display() + ), + log_dir, + ); + return Ok(path); + } + + let source = sibling_source_path(kind)?; + let destination = helper_bin_dir(codex_home).join(kind.file_name()); + log_note( + &format!( + "helper copy: validating {} source={} destination={}", + kind.label(), + source.display(), + destination.display() + ), + log_dir, + ); + let outcome = copy_from_source_if_needed(&source, &destination)?; + let action = match outcome { + CopyOutcome::Reused => "reused", + CopyOutcome::ReCopied => "recopied", + }; + log_note( + &format!( + "helper copy: {} {} source={} destination={}", + action, + kind.label(), + source.display(), + destination.display() + ), + log_dir, + ); + store_helper_path(cache_key, destination.clone()); + Ok(destination) +} + +fn cached_helper_path(cache_key: &str) -> Option { + let cache = HELPER_PATH_CACHE.get_or_init(|| Mutex::new(HashMap::new())); + let guard = cache.lock().ok()?; + guard.get(cache_key).cloned() +} + +fn store_helper_path(cache_key: String, path: PathBuf) { + let cache = HELPER_PATH_CACHE.get_or_init(|| Mutex::new(HashMap::new())); + if let Ok(mut guard) = cache.lock() { + guard.insert(cache_key, path); + } +} + +fn sibling_source_path(kind: HelperExecutable) -> Result { + let exe = std::env::current_exe().context("resolve current executable for helper lookup")?; + let dir = exe + .parent() + .ok_or_else(|| anyhow!("current executable has no parent directory"))?; + let candidate = dir.join(kind.file_name()); + if candidate.exists() { + Ok(candidate) + } else { + Err(anyhow!( + "helper not found next to current executable: {}", + candidate.display() + )) + } +} + +fn copy_from_source_if_needed(source: &Path, destination: &Path) -> Result { + if destination_is_fresh(source, destination)? { + return Ok(CopyOutcome::Reused); + } + + let destination_dir = destination + .parent() + .ok_or_else(|| anyhow!("helper destination has no parent: {}", destination.display()))?; + fs::create_dir_all(destination_dir).with_context(|| { + format!( + "create helper destination directory {}", + destination_dir.display() + ) + })?; + + let temp_path = NamedTempFile::new_in(destination_dir) + .with_context(|| { + format!( + "create temporary helper file in {}", + destination_dir.display() + ) + })? + .into_temp_path(); + let temp_path_buf = temp_path.to_path_buf(); + + let mut source_file = fs::File::open(source) + .with_context(|| format!("open helper source for read {}", source.display()))?; + let mut temp_file = fs::OpenOptions::new() + .write(true) + .truncate(true) + .open(&temp_path_buf) + .with_context(|| format!("open temporary helper file {}", temp_path_buf.display()))?; + + // Write into a temp file created inside `.sandbox-bin` so the copied helper keeps the + // destination directory's inherited ACLs instead of reusing the source file's descriptor. + std::io::copy(&mut source_file, &mut temp_file).with_context(|| { + format!( + "copy helper from {} to {}", + source.display(), + temp_path_buf.display() + ) + })?; + temp_file + .flush() + .with_context(|| format!("flush temporary helper file {}", temp_path_buf.display()))?; + drop(temp_file); + + if destination.exists() { + fs::remove_file(destination).with_context(|| { + format!("remove stale helper destination {}", destination.display()) + })?; + } + + match fs::rename(&temp_path_buf, destination) { + Ok(()) => Ok(CopyOutcome::ReCopied), + Err(rename_err) => { + if destination_is_fresh(source, destination)? { + Ok(CopyOutcome::Reused) + } else { + Err(rename_err).with_context(|| { + format!( + "rename helper temp file {} to {}", + temp_path_buf.display(), + destination.display() + ) + }) + } + } + } +} + +fn destination_is_fresh(source: &Path, destination: &Path) -> Result { + let source_meta = fs::metadata(source) + .with_context(|| format!("read helper source metadata {}", source.display()))?; + let destination_meta = match fs::metadata(destination) { + Ok(meta) => meta, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(err) => { + return Err(err) + .with_context(|| format!("read helper destination metadata {}", destination.display())); + } + }; + + if source_meta.len() != destination_meta.len() { + return Ok(false); + } + + let source_modified = source_meta + .modified() + .with_context(|| format!("read helper source mtime {}", source.display()))?; + let destination_modified = destination_meta + .modified() + .with_context(|| format!("read helper destination mtime {}", destination.display()))?; + + Ok(destination_modified >= source_modified) +} + +#[cfg(test)] +mod tests { + use super::destination_is_fresh; + use super::helper_bin_dir; + use super::copy_from_source_if_needed; + use super::CopyOutcome; + use pretty_assertions::assert_eq; + use std::fs; + use std::path::Path; + use std::path::PathBuf; + use tempfile::TempDir; + + #[test] + fn copy_from_source_if_needed_copies_missing_destination() { + let tmp = TempDir::new().expect("tempdir"); + let source = tmp.path().join("source.exe"); + let destination = tmp.path().join("bin").join("helper.exe"); + + fs::write(&source, b"runner-v1").expect("write source"); + + let outcome = copy_from_source_if_needed(&source, &destination).expect("copy helper"); + + assert_eq!(CopyOutcome::ReCopied, outcome); + assert_eq!(b"runner-v1".as_slice(), fs::read(&destination).expect("read destination")); + } + + #[test] + fn destination_is_fresh_uses_size_and_mtime() { + let tmp = TempDir::new().expect("tempdir"); + let source = tmp.path().join("source.exe"); + let destination = tmp.path().join("destination.exe"); + + fs::write(&destination, b"same-size").expect("write destination"); + std::thread::sleep(std::time::Duration::from_secs(1)); + fs::write(&source, b"same-size").expect("write source"); + assert!(!destination_is_fresh(&source, &destination).expect("stale metadata")); + + fs::write(&destination, b"same-size").expect("rewrite destination"); + assert!(destination_is_fresh(&source, &destination).expect("fresh metadata")); + } + + #[test] + fn copy_from_source_if_needed_reuses_fresh_destination() { + let tmp = TempDir::new().expect("tempdir"); + let source = tmp.path().join("source.exe"); + let destination = tmp.path().join("bin").join("helper.exe"); + + fs::write(&source, b"runner-v1").expect("write source"); + copy_from_source_if_needed(&source, &destination).expect("initial copy"); + + let outcome = + copy_from_source_if_needed(&source, &destination).expect("revalidate helper"); + + assert_eq!(CopyOutcome::Reused, outcome); + assert_eq!(b"runner-v1".as_slice(), fs::read(&destination).expect("read destination")); + } + + #[test] + fn helper_bin_dir_is_under_sandbox_bin() { + let codex_home = Path::new(r"C:\Users\example\.codex"); + + assert_eq!( + PathBuf::from(r"C:\Users\example\.codex\.sandbox-bin"), + helper_bin_dir(codex_home) + ); + } + + #[test] + fn copy_runner_into_shared_bin_dir() { + let tmp = TempDir::new().expect("tempdir"); + let codex_home = tmp.path().join("codex-home"); + let source_dir = tmp.path().join("sibling-source"); + fs::create_dir_all(&source_dir).expect("create source dir"); + let runner_source = source_dir.join("codex-command-runner.exe"); + let runner_destination = helper_bin_dir(&codex_home).join("codex-command-runner.exe"); + fs::write(&runner_source, b"runner").expect("runner"); + + let runner_outcome = + copy_from_source_if_needed(&runner_source, &runner_destination).expect("runner copy"); + + assert_eq!(CopyOutcome::ReCopied, runner_outcome); + assert_eq!( + b"runner".as_slice(), + fs::read(&runner_destination).expect("read runner") + ); + } +} diff --git a/codex-rs/windows-sandbox-rs/src/identity.rs b/codex-rs/windows-sandbox-rs/src/identity.rs index b195e36b91..b9d5e29ed7 100644 --- a/codex-rs/windows-sandbox-rs/src/identity.rs +++ b/codex-rs/windows-sandbox-rs/src/identity.rs @@ -130,7 +130,7 @@ pub fn require_logon_sandbox_creds( codex_home: &Path, ) -> Result { let sandbox_dir = crate::setup::sandbox_dir(codex_home); - let needed_read = gather_read_roots(command_cwd, policy); + let needed_read = gather_read_roots(command_cwd, policy, codex_home); let needed_write = gather_write_roots(policy, policy_cwd, command_cwd, env_map); // NOTE: Do not add CODEX_HOME/.sandbox to `needed_write`; it must remain non-writable by the // restricted capability token. The setup helper's `lock_sandbox_dir` is responsible for diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index fc96e5186b..565d589724 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -11,6 +11,7 @@ windows_modules!( cap, dpapi, env, + helper_materialization, hide_users, identity, logging, @@ -85,6 +86,8 @@ pub use setup::run_setup_refresh; #[cfg(target_os = "windows")] pub use setup::run_setup_refresh_with_extra_read_roots; #[cfg(target_os = "windows")] +pub use setup::sandbox_bin_dir; +#[cfg(target_os = "windows")] pub use setup::sandbox_dir; #[cfg(target_os = "windows")] pub use setup::sandbox_secrets_dir; diff --git a/codex-rs/windows-sandbox-rs/src/setup_main_win.rs b/codex-rs/windows-sandbox-rs/src/setup_main_win.rs index f3de7c8564..476620cc2e 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_main_win.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_main_win.rs @@ -18,6 +18,7 @@ use codex_windows_sandbox::log_note; use codex_windows_sandbox::path_mask_allows; use codex_windows_sandbox::protect_workspace_agents_dir; use codex_windows_sandbox::protect_workspace_codex_dir; +use codex_windows_sandbox::sandbox_bin_dir; use codex_windows_sandbox::sandbox_dir; use codex_windows_sandbox::sandbox_secrets_dir; use codex_windows_sandbox::string_from_sid_bytes; @@ -245,6 +246,8 @@ fn lock_sandbox_dir( real_user: &str, sandbox_group_sid: &[u8], sandbox_group_access_mode: i32, + sandbox_group_mask: u32, + real_user_mask: u32, _log: &mut File, ) -> Result<()> { std::fs::create_dir_all(dir)?; @@ -254,7 +257,7 @@ fn lock_sandbox_dir( let entries = [ ( sandbox_group_sid.to_vec(), - FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, + sandbox_group_mask, sandbox_group_access_mode, ), ( @@ -267,11 +270,7 @@ fn lock_sandbox_dir( FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, GRANT_ACCESS, ), - ( - real_sid, - FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE, - GRANT_ACCESS, - ), + (real_sid, real_user_mask, GRANT_ACCESS), ]; unsafe { let mut eas: Vec = Vec::new(); @@ -740,6 +739,25 @@ fn run_setup_full(payload: &Payload, log: &mut File, sbx_dir: &Path) -> Result<( } }); + lock_sandbox_dir( + &sandbox_bin_dir(&payload.codex_home), + &payload.real_user, + &sandbox_group_sid, + GRANT_ACCESS, + FILE_GENERIC_READ | FILE_GENERIC_EXECUTE, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, + log, + ) + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSandboxLockFailed, + format!( + "lock sandbox bin dir {} failed: {err}", + sandbox_bin_dir(&payload.codex_home).display() + ), + )) + })?; + if refresh_only { log_line( log, @@ -756,6 +774,8 @@ fn run_setup_full(payload: &Payload, log: &mut File, sbx_dir: &Path) -> Result<( &payload.real_user, &sandbox_group_sid, GRANT_ACCESS, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE, log, ) .map_err(|err| { @@ -772,6 +792,8 @@ fn run_setup_full(payload: &Payload, log: &mut File, sbx_dir: &Path) -> Result<( &payload.real_user, &sandbox_group_sid, DENY_ACCESS, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE, log, ) .map_err(|err| { diff --git a/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs b/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs index d612ea6583..d43d8b85fc 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs @@ -11,6 +11,7 @@ use std::process::Stdio; use crate::allow::compute_allow_paths; use crate::allow::AllowDenyPaths; +use crate::helper_materialization::helper_bin_dir; use crate::logging::log_note; use crate::path_normalization::canonical_path_key; use crate::policy::SandboxPolicy; @@ -55,6 +56,10 @@ pub fn sandbox_dir(codex_home: &Path) -> PathBuf { codex_home.join(".sandbox") } +pub fn sandbox_bin_dir(codex_home: &Path) -> PathBuf { + codex_home.join(".sandbox-bin") +} + pub fn sandbox_secrets_dir(codex_home: &Path) -> PathBuf { codex_home.join(".sandbox-secrets") } @@ -93,7 +98,7 @@ pub fn run_setup_refresh_with_extra_read_roots( codex_home: &Path, extra_read_roots: Vec, ) -> Result<()> { - let mut read_roots = gather_read_roots(command_cwd, policy); + let mut read_roots = gather_read_roots(command_cwd, policy, codex_home); read_roots.extend(extra_read_roots); run_setup_refresh_inner( policy, @@ -276,13 +281,20 @@ fn profile_read_roots(user_profile: &Path) -> Vec { .collect() } -pub(crate) fn gather_read_roots(command_cwd: &Path, policy: &SandboxPolicy) -> Vec { +pub(crate) fn gather_read_roots( + command_cwd: &Path, + policy: &SandboxPolicy, + codex_home: &Path, +) -> Vec { let mut roots: Vec = Vec::new(); if let Ok(exe) = std::env::current_exe() { if let Some(dir) = exe.parent() { roots.push(dir.to_path_buf()); } } + let helper_dir = helper_bin_dir(codex_home); + let _ = std::fs::create_dir_all(&helper_dir); + roots.push(helper_dir); for p in [ PathBuf::from(r"C:\Windows"), PathBuf::from(r"C:\Program Files"), @@ -583,7 +595,7 @@ fn build_payload_roots( let mut read_roots = if let Some(roots) = read_roots_override { canonical_existing(&roots) } else { - gather_read_roots(command_cwd, policy) + gather_read_roots(command_cwd, policy, codex_home) }; let write_root_set: HashSet = write_roots.iter().cloned().collect(); read_roots.retain(|root| !write_root_set.contains(root)); @@ -591,11 +603,14 @@ fn build_payload_roots( } fn filter_sensitive_write_roots(mut roots: Vec, codex_home: &Path) -> Vec { - // Never grant capability write access to CODEX_HOME or anything under CODEX_HOME/.sandbox. - // These locations contain sandbox control/state and must remain tamper-resistant. + // Never grant capability write access to CODEX_HOME or anything under CODEX_HOME/.sandbox, + // CODEX_HOME/.sandbox-bin, or CODEX_HOME/.sandbox-secrets. These locations contain sandbox + // control/state and helper binaries and must remain tamper-resistant. let codex_home_key = canonical_path_key(codex_home); let sbx_dir_key = canonical_path_key(&sandbox_dir(codex_home)); let sbx_dir_prefix = format!("{}/", sbx_dir_key.trim_end_matches('/')); + let sbx_bin_dir_key = canonical_path_key(&sandbox_bin_dir(codex_home)); + let sbx_bin_dir_prefix = format!("{}/", sbx_bin_dir_key.trim_end_matches('/')); let secrets_dir_key = canonical_path_key(&sandbox_secrets_dir(codex_home)); let secrets_dir_prefix = format!("{}/", secrets_dir_key.trim_end_matches('/')); @@ -604,6 +619,8 @@ fn filter_sensitive_write_roots(mut roots: Vec, codex_home: &Path) -> V key != codex_home_key && key != sbx_dir_key && !key.starts_with(&sbx_dir_prefix) + && key != sbx_bin_dir_key + && !key.starts_with(&sbx_bin_dir_prefix) && key != secrets_dir_key && !key.starts_with(&secrets_dir_prefix) }); @@ -612,7 +629,10 @@ fn filter_sensitive_write_roots(mut roots: Vec, codex_home: &Path) -> V #[cfg(test)] mod tests { + use super::gather_read_roots; use super::profile_read_roots; + use crate::helper_materialization::helper_bin_dir; + use crate::policy::SandboxPolicy; use pretty_assertions::assert_eq; use std::collections::HashSet; use std::fs; @@ -649,4 +669,19 @@ mod tests { assert_eq!(vec![missing_profile], roots); } + + #[test] + fn gather_read_roots_includes_helper_bin_dir() { + let tmp = TempDir::new().expect("tempdir"); + let codex_home = tmp.path().join("codex-home"); + let command_cwd = tmp.path().join("workspace"); + fs::create_dir_all(&command_cwd).expect("create workspace"); + let policy = SandboxPolicy::new_read_only_policy(); + + let roots = gather_read_roots(&command_cwd, &policy, &codex_home); + let expected = + dunce::canonicalize(helper_bin_dir(&codex_home)).expect("canonical helper dir"); + + assert!(roots.contains(&expected)); + } } From 2d8c1575b8ba94179923348065062dc70f09deab Mon Sep 17 00:00:00 2001 From: zbarsky-openai Date: Tue, 3 Mar 2026 20:59:32 -0500 Subject: [PATCH 358/385] [bazel] Bump rules_rs and llvm (#13366) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. --- .bazelrc | 2 +- BUILD.bazel | 9 +-- MODULE.bazel | 72 +++++-------------- MODULE.bazel.lock | 27 ++++--- codex-rs/app-server/BUILD.bazel | 1 - codex-rs/core/BUILD.bazel | 1 - codex-rs/mcp-server/BUILD.bazel | 1 - defs.bzl | 31 +++----- ...hains_llvm_bootstrapped_resource_dir.patch | 37 +++------- rbe.bzl | 2 +- 10 files changed, 57 insertions(+), 126 deletions(-) diff --git a/.bazelrc b/.bazelrc index 7f561aa9ee..820a94a735 100644 --- a/.bazelrc +++ b/.bazelrc @@ -18,7 +18,7 @@ common --enable_platform_specific_config common:linux --host_platform=//:local_linux common:windows --host_platform=//:local_windows common --@rules_cc//cc/toolchains/args/archiver_flags:use_libtool_on_macos=False -common --@toolchains_llvm_bootstrapped//config:experimental_stub_libgcc_s +common --@llvm//config:experimental_stub_libgcc_s # We need to use the sh toolchain on windows so we don't send host bash paths to the linux executor. common:windows --@rules_rust//rust/settings:experimental_use_sh_toolchain_for_bootstrap_process_wrapper diff --git a/BUILD.bazel b/BUILD.bazel index 66548cd03c..ed38c18b57 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -1,11 +1,4 @@ load("@apple_support//xcode:xcode_config.bzl", "xcode_config") -load("@rules_cc//cc:defs.bzl", "cc_shared_library") - -cc_shared_library( - name = "clang", - deps = ["@llvm-project//clang:libclang"], - visibility = ["//visibility:public"], -) xcode_config(name = "disable_xcode") @@ -16,7 +9,7 @@ platform( name = "local_linux", constraint_values = [ # We mark the local platform as glibc-compatible because musl-built rust cannot dlopen proc macros. - "@toolchains_llvm_bootstrapped//constraints/libc:gnu.2.28", + "@llvm//constraints/libc:gnu.2.28", ], parents = ["@platforms//host"], ) diff --git a/MODULE.bazel b/MODULE.bazel index b2115f4664..f55bd1f26d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,18 +1,18 @@ module(name = "codex") bazel_dep(name = "platforms", version = "1.0.0") -bazel_dep(name = "toolchains_llvm_bootstrapped", version = "0.5.6") +bazel_dep(name = "llvm", version = "0.6.1") single_version_override( - module_name = "toolchains_llvm_bootstrapped", + module_name = "llvm", patch_strip = 1, patches = [ "//patches:toolchains_llvm_bootstrapped_resource_dir.patch", ], ) -register_toolchains("@toolchains_llvm_bootstrapped//toolchain:all") +register_toolchains("@llvm//toolchain:all") -osx = use_extension("@toolchains_llvm_bootstrapped//extensions:osx.bzl", "osx") +osx = use_extension("@llvm//extensions:osx.bzl", "osx") osx.framework(name = "ApplicationServices") osx.framework(name = "AppKit") osx.framework(name = "ColorSync") @@ -33,21 +33,13 @@ osx.framework(name = "Kernel") osx.framework(name = "OSLog") osx.framework(name = "Security") osx.framework(name = "SystemConfiguration") -use_repo(osx, "macosx15.4.sdk") +use_repo(osx, "macos_sdk") # Needed to disable xcode... bazel_dep(name = "apple_support", version = "2.1.0") bazel_dep(name = "rules_cc", version = "0.2.16") bazel_dep(name = "rules_platform", version = "0.1.0") -bazel_dep(name = "rules_rs", version = "0.0.23") - -# Special toolchains branch -archive_override( - module_name = "rules_rs", - integrity = "sha256-O34UF4H7b1Qacu3vlu2Od4ILGVApzg5j1zl952SFL3w=", - strip_prefix = "rules_rs-097123c2aa72672e371e69e7035869f5a45c7b2b", - url = "https://github.com/dzbarsky/rules_rs/archive/097123c2aa72672e371e69e7035869f5a45c7b2b.tar.gz", -) +bazel_dep(name = "rules_rs", version = "0.0.40") rules_rust = use_extension("@rules_rs//rs/experimental:rules_rust.bzl", "rules_rust") use_repo(rules_rust, "rules_rust") @@ -57,13 +49,9 @@ toolchains.toolchain( edition = "2024", version = "1.93.0", ) -use_repo( - toolchains, - "experimental_rust_toolchains_1_93_0", - "rust_toolchain_artifacts_macos_aarch64_1_93_0", -) +use_repo(toolchains, "default_rust_toolchains") -register_toolchains("@experimental_rust_toolchains_1_93_0//:all") +register_toolchains("@default_rust_toolchains//:all") crate = use_extension("@rules_rs//rs:extensions.bzl", "crate") crate.from_cargo( @@ -79,6 +67,7 @@ crate.from_cargo( "x86_64-apple-darwin", "x86_64-pc-windows-gnullvm", ], + use_experimental_platforms = True, ) bazel_dep(name = "zstd", version = "1.5.7") @@ -139,11 +128,9 @@ crate.annotation( "OPENSSL_NO_VENDOR": "1", "OPENSSL_STATIC": "1", }, - crate_features = [ - "dep:openssl-src", - ], crate = "openssl-sys", data = ["@openssl//:gen_dir"], + gen_build_script = "on", ) inject_repo(crate, "openssl") @@ -153,27 +140,28 @@ crate.annotation( workspace_cargo_toml = "rust/runfiles/Cargo.toml", ) -llvm = use_extension("@toolchains_llvm_bootstrapped//extensions:llvm.bzl", "llvm") +llvm = use_extension("@llvm//extensions:llvm.bzl", "llvm") use_repo(llvm, "llvm-project") crate.annotation( # Provide the hermetic SDK path so the build script doesn't try to invoke an unhermetic `xcrun --show-sdk-path`. build_script_data = [ - "@macosx15.4.sdk//sysroot", + "@macos_sdk//sysroot", ], build_script_env = { - "BINDGEN_EXTRA_CLANG_ARGS": "-isystem $(location @toolchains_llvm_bootstrapped//:builtin_headers)", - "COREAUDIO_SDK_PATH": "$(location @macosx15.4.sdk//sysroot)", - "LIBCLANG_PATH": "$(location @codex//:clang)", + "BINDGEN_EXTRA_CLANG_ARGS": "-isystem $(location @llvm//:builtin_headers)", + "COREAUDIO_SDK_PATH": "$(location @macos_sdk//sysroot)", + "LIBCLANG_PATH": "$(location @llvm-project//clang:libclang_interface_output)", }, build_script_tools = [ - "@codex//:clang", - "@toolchains_llvm_bootstrapped//:builtin_headers", + "@llvm-project//clang:libclang_interface_output", + "@llvm//:builtin_headers", ], crate = "coreaudio-sys", + gen_build_script = "on", ) -inject_repo(crate, "codex", "toolchains_llvm_bootstrapped", "macosx15.4.sdk") +inject_repo(crate, "llvm", "llvm-project", "macos_sdk") # Fix readme inclusions crate.annotation( @@ -184,28 +172,6 @@ crate.annotation( ], ) -WINDOWS_IMPORT_LIB = """ -load("@rules_cc//cc:defs.bzl", "cc_import") - -cc_import( - name = "windows_import_lib", - static_library = glob(["lib/*.a"])[0], -) -""" - -crate.annotation( - additive_build_file_content = WINDOWS_IMPORT_LIB, - crate = "windows_x86_64_gnullvm", - gen_build_script = "off", - deps = [":windows_import_lib"], -) -crate.annotation( - additive_build_file_content = WINDOWS_IMPORT_LIB, - crate = "windows_aarch64_gnullvm", - gen_build_script = "off", - deps = [":windows_import_lib"], -) - bazel_dep(name = "alsa_lib", version = "1.2.9.bcr.4") crate.annotation( diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 9b459b9941..46220ab3cb 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -44,10 +44,12 @@ "https://bcr.bazel.build/modules/bazel_features/1.28.0/MODULE.bazel": "4b4200e6cbf8fa335b2c3f43e1d6ef3e240319c33d43d60cc0fbd4b87ece299d", "https://bcr.bazel.build/modules/bazel_features/1.3.0/MODULE.bazel": "cdcafe83ec318cda34e02948e81d790aab8df7a929cec6f6969f13a489ccecd9", "https://bcr.bazel.build/modules/bazel_features/1.30.0/MODULE.bazel": "a14b62d05969a293b80257e72e597c2da7f717e1e69fa8b339703ed6731bec87", + "https://bcr.bazel.build/modules/bazel_features/1.32.0/MODULE.bazel": "095d67022a58cb20f7e20e1aefecfa65257a222c18a938e2914fd257b5f1ccdc", "https://bcr.bazel.build/modules/bazel_features/1.33.0/MODULE.bazel": "8b8dc9d2a4c88609409c3191165bccec0e4cb044cd7a72ccbe826583303459f6", "https://bcr.bazel.build/modules/bazel_features/1.34.0/MODULE.bazel": "e8475ad7c8965542e0c7aac8af68eb48c4af904be3d614b6aa6274c092c2ea1e", - "https://bcr.bazel.build/modules/bazel_features/1.34.0/source.json": "dfa5c4b01110313153b484a735764d247fee5624bbab63d25289e43b151a657a", "https://bcr.bazel.build/modules/bazel_features/1.4.1/MODULE.bazel": "e45b6bb2350aff3e442ae1111c555e27eac1d915e77775f6fdc4b351b758b5d7", + "https://bcr.bazel.build/modules/bazel_features/1.42.0/MODULE.bazel": "e8ca15cb2639c5f12183db6dcb678735555d0cdd739b32a0418b6532b5e565f8", + "https://bcr.bazel.build/modules/bazel_features/1.42.0/source.json": "f2ea90e5dd0322481147114c7d5e4608c4b3fae2eeccae655e4d76a382389f6f", "https://bcr.bazel.build/modules/bazel_features/1.9.0/MODULE.bazel": "885151d58d90d8d9c811eb75e3288c11f850e1d6b481a8c9f766adee4712358b", "https://bcr.bazel.build/modules/bazel_features/1.9.1/MODULE.bazel": "8f679097876a9b609ad1f60249c49d68bfab783dd9be012faf9d82547b14815a", "https://bcr.bazel.build/modules/bazel_lib/3.0.0/MODULE.bazel": "22b70b80ac89ad3f3772526cd9feee2fa412c2b01933fea7ed13238a448d370d", @@ -88,6 +90,9 @@ "https://bcr.bazel.build/modules/libcap/2.27.bcr.1/MODULE.bazel": "7c034d7a4d92b2293294934377f5d1cbc88119710a11079fa8142120f6f08768", "https://bcr.bazel.build/modules/libcap/2.27.bcr.1/source.json": "3b116cbdbd25a68ffb587b672205f6d353a4c19a35452e480d58fc89531e0a10", "https://bcr.bazel.build/modules/libpfm/4.11.0/MODULE.bazel": "45061ff025b301940f1e30d2c16bea596c25b176c8b6b3087e92615adbd52902", + "https://bcr.bazel.build/modules/llvm/0.6.0/MODULE.bazel": "42c2182c49f13d2df83a4a4a95ab55d31efda47b2d67acf419bf6b31522b2a30", + "https://bcr.bazel.build/modules/llvm/0.6.1/MODULE.bazel": "29170ab19f4e2dc9b6bbf9b3d101738e84142f63ba29a13cc33e0d40f74c79b0", + "https://bcr.bazel.build/modules/llvm/0.6.1/source.json": "2d8cdd3a5f8e1d16132dbbe97250133101e4863c0376d23273d9afd7363cc331", "https://bcr.bazel.build/modules/nlohmann_json/3.6.1/MODULE.bazel": "6f7b417dcc794d9add9e556673ad25cb3ba835224290f4f848f8e2db1e1fca74", "https://bcr.bazel.build/modules/nlohmann_json/3.6.1/source.json": "f448c6e8963fdfa7eb831457df83ad63d3d6355018f6574fb017e8169deb43a9", "https://bcr.bazel.build/modules/openssl/3.5.4.bcr.0/MODULE.bazel": "0f6b8f20b192b9ff0781406256150bcd46f19e66d807dcb0c540548439d6fc35", @@ -199,6 +204,8 @@ "https://bcr.bazel.build/modules/rules_python/1.6.0/MODULE.bazel": "7e04ad8f8d5bea40451cf80b1bd8262552aa73f841415d20db96b7241bd027d8", "https://bcr.bazel.build/modules/rules_python/1.7.0/MODULE.bazel": "d01f995ecd137abf30238ad9ce97f8fc3ac57289c8b24bd0bf53324d937a14f8", "https://bcr.bazel.build/modules/rules_python/1.7.0/source.json": "028a084b65dcf8f4dc4f82f8778dbe65df133f234b316828a82e060d81bdce32", + "https://bcr.bazel.build/modules/rules_rs/0.0.40/MODULE.bazel": "63238bcb69010753dbd37b5ed08cb79d3af2d88a40b0fda0b110f60f307e86d4", + "https://bcr.bazel.build/modules/rules_rs/0.0.40/source.json": "ae3b17d2f9e4fbcd3de543318e71f83d8522c8527f385bf2b2a7665ec504827e", "https://bcr.bazel.build/modules/rules_shell/0.2.0/MODULE.bazel": "fda8a652ab3c7d8fee214de05e7a9916d8b28082234e8d2c0094505c5268ed3c", "https://bcr.bazel.build/modules/rules_shell/0.3.0/MODULE.bazel": "de4402cd12f4cc8fda2354fce179fdb068c0b9ca1ec2d2b17b3e21b24c1a937b", "https://bcr.bazel.build/modules/rules_shell/0.4.1/MODULE.bazel": "00e501db01bbf4e3e1dd1595959092c2fadf2087b2852d3f553b5370f5633592", @@ -223,9 +230,6 @@ "https://bcr.bazel.build/modules/tar.bzl/0.2.1/MODULE.bazel": "52d1c00a80a8cc67acbd01649e83d8dd6a9dc426a6c0b754a04fe8c219c76468", "https://bcr.bazel.build/modules/tar.bzl/0.6.0/MODULE.bazel": "a3584b4edcfafcabd9b0ef9819808f05b372957bbdff41601429d5fd0aac2e7c", "https://bcr.bazel.build/modules/tar.bzl/0.6.0/source.json": "4a620381df075a16cb3a7ed57bd1d05f7480222394c64a20fa51bdb636fda658", - "https://bcr.bazel.build/modules/toolchains_llvm_bootstrapped/0.5.2/MODULE.bazel": "f7c822cea99caef928d7cbe695498096e53c4b2c0ea45997e9a64bf6b77b43b0", - "https://bcr.bazel.build/modules/toolchains_llvm_bootstrapped/0.5.6/MODULE.bazel": "7298112608aefec21ea8bfbe325b14472222a0243c3dabcd0287eba418791f35", - "https://bcr.bazel.build/modules/toolchains_llvm_bootstrapped/0.5.6/source.json": "c2a30627cfe15e4deeba63a75d1894324444ae0276eb17ac0161ba5c220c1cb2", "https://bcr.bazel.build/modules/upb/0.0.0-20220923-a547704/MODULE.bazel": "7298990c00040a0e2f121f6c32544bab27d4452f80d9ce51349b1a28f3005c43", "https://bcr.bazel.build/modules/with_cfg.bzl/0.12.0/MODULE.bazel": "b573395fe63aef4299ba095173e2f62ccfee5ad9bbf7acaa95dba73af9fc2b38", "https://bcr.bazel.build/modules/with_cfg.bzl/0.12.0/source.json": "3f3fbaeafecaf629877ad152a2c9def21f8d330d91aa94c5dc75bbb98c10b8b8", @@ -244,7 +248,7 @@ "@@aspect_tools_telemetry+//:extension.bzl%telemetry": { "general": { "bzlTransitiveDigest": "dnnhvKMf9MIXMulhbhHBblZdDAfAkiSVjApIXpUz9Y8=", - "usagesDigest": "RFeOiu3n5PGxbV4G+nHCOyM04AaEegaq6ajL+2iZ3Bo=", + "usagesDigest": "2ScE07TNSr/xo2GnYHCRI4JX4hiql6iZaNKUIUshUv4=", "recordedInputs": [ "REPO_MAPPING:aspect_tools_telemetry+,bazel_lib bazel_lib+", "REPO_MAPPING:aspect_tools_telemetry+,bazel_skylib bazel_skylib+" @@ -255,17 +259,20 @@ "attributes": { "deps": { "abseil-cpp": "20250814.1", - "apple_support": "1.24.2", + "alsa_lib": "1.2.9.bcr.4", + "apple_support": "2.1.0", "aspect_bazel_lib": "2.19.3", "aspect_tools_telemetry": "0.3.2", "bazel_features": "1.34.0", - "bazel_lib": "3.0.0", + "bazel_lib": "3.2.0", "bazel_skylib": "1.8.2", "buildozer": "8.2.1", + "bzip2": "1.0.8.bcr.3", "gawk": "5.3.2.bcr.1", "googletest": "1.17.0", "jq.bzl": "0.1.0", "jsoncpp": "1.9.6", + "libcap": "2.27.bcr.1", "nlohmann_json": "3.6.1", "openssl": "3.5.4.bcr.0", "package_metadata": "0.0.5", @@ -285,15 +292,17 @@ "rules_platform": "0.1.0", "rules_proto": "7.1.0", "rules_python": "1.7.0", - "rules_rs": "0.0.23", "rules_shell": "0.6.1", "rules_swift": "3.1.2", + "sed": "4.9.bcr.3", "stardoc": "0.7.2", "swift_argument_parser": "1.3.1.2", "tar.bzl": "0.6.0", + "toolchains_llvm_bootstrapped": "0.5.6", "with_cfg.bzl": "0.12.0", "yq.bzl": "0.1.1", - "zlib": "1.3.1.bcr.5" + "zlib": "1.3.1.bcr.8", + "zstd": "1.5.7" } } } diff --git a/codex-rs/app-server/BUILD.bazel b/codex-rs/app-server/BUILD.bazel index b6766f2237..5f1ba790d5 100644 --- a/codex-rs/app-server/BUILD.bazel +++ b/codex-rs/app-server/BUILD.bazel @@ -3,6 +3,5 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "app-server", crate_name = "codex_app_server", - integration_deps_extra = ["//codex-rs/app-server/tests/common:common"], test_tags = ["no-sandbox"], ) diff --git a/codex-rs/core/BUILD.bazel b/codex-rs/core/BUILD.bazel index cbfd6cacf1..d0f5b9d8a4 100644 --- a/codex-rs/core/BUILD.bazel +++ b/codex-rs/core/BUILD.bazel @@ -46,7 +46,6 @@ codex_rust_crate( # succeeds without this workaround. "//:AGENTS.md", ], - integration_deps_extra = ["//codex-rs/core/tests/common:common"], test_tags = ["no-sandbox"], extra_binaries = [ "//codex-rs/linux-sandbox:codex-linux-sandbox", diff --git a/codex-rs/mcp-server/BUILD.bazel b/codex-rs/mcp-server/BUILD.bazel index abdb61dd49..5bf39611b9 100644 --- a/codex-rs/mcp-server/BUILD.bazel +++ b/codex-rs/mcp-server/BUILD.bazel @@ -3,5 +3,4 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "mcp-server", crate_name = "codex_mcp_server", - integration_deps_extra = ["//codex-rs/mcp-server/tests/common:common"], ) diff --git a/defs.bzl b/defs.bzl index 6be15d80f9..d618725eb8 100644 --- a/defs.bzl +++ b/defs.bzl @@ -17,7 +17,7 @@ def multiplatform_binaries(name, platforms = PLATFORMS): for platform in platforms: platform_data( name = name + "_" + platform, - platform = "@toolchains_llvm_bootstrapped//platforms:" + platform, + platform = "@llvm//platforms:" + platform, target = name, tags = ["manual"], ) @@ -42,7 +42,6 @@ def codex_rust_crate( rustc_flags_extra = [], rustc_env = {}, deps_extra = [], - integration_deps_extra = [], integration_compile_data_extra = [], test_data_extra = [], test_tags = [], @@ -73,7 +72,6 @@ def codex_rust_crate( rustc_env: Extra rustc_env entries to merge with defaults. deps_extra: Extra normal deps beyond @crates resolution. Typically only needed when features add additional deps. - integration_deps_extra: Extra deps for integration tests only. integration_compile_data_extra: Extra compile_data for integration tests. test_data_extra: Extra runtime data for tests. test_tags: Tags applied to unit + integration test targets. @@ -81,11 +79,6 @@ def codex_rust_crate( extra_binaries: Additional binary labels to surface as test data and `CARGO_BIN_EXE_*` environment variables. These are only needed for binaries from a different crate. """ - deps = all_crate_deps(normal = True) + deps_extra - dev_deps = all_crate_deps(normal_dev = True) - proc_macro_deps = all_crate_deps(proc_macro = True) - proc_macro_dev_deps = all_crate_deps(proc_macro_dev = True) - test_env = { "INSTA_WORKSPACE_ROOT": ".", "INSTA_SNAPSHOT_PATH": "src", @@ -99,18 +92,19 @@ def codex_rust_crate( lib_srcs = crate_srcs or native.glob(["src/**/*.rs"], exclude = binaries.values(), allow_empty = True) + maybe_deps = [] + if build_script_enabled and native.glob(["build.rs"], allow_empty = True): cargo_build_script( name = name + "-build-script", srcs = ["build.rs"], deps = all_crate_deps(build = True), - proc_macro_deps = all_crate_deps(build_proc_macro = True), data = build_script_data, # Some build script deps sniff version-related env vars... version = "0.0.0", ) - deps = deps + [name + "-build-script"] + maybe_deps += [name + "-build-script"] if lib_srcs: lib_rule = rust_proc_macro if proc_macro else rust_library @@ -118,8 +112,7 @@ def codex_rust_crate( name = name, crate_name = crate_name, crate_features = crate_features, - deps = deps, - proc_macro_deps = proc_macro_deps, + deps = all_crate_deps() + maybe_deps + deps_extra, compile_data = compile_data, data = lib_data_extra, srcs = lib_srcs, @@ -133,18 +126,14 @@ def codex_rust_crate( name = name + "-unit-tests", crate = name, env = test_env, - deps = deps + dev_deps, - proc_macro_deps = proc_macro_deps + proc_macro_dev_deps, + deps = all_crate_deps(normal = True, normal_dev = True) + maybe_deps + deps_extra, rustc_flags = rustc_flags_extra, rustc_env = rustc_env, data = test_data_extra, tags = test_tags, ) - if proc_macro: - proc_macro_deps += [name] - else: - deps += [name] + maybe_deps += [name] sanitized_binaries = [] cargo_env = {} @@ -157,8 +146,7 @@ def codex_rust_crate( name = binary, crate_name = binary.replace("-", "_"), crate_root = main, - deps = deps, - proc_macro_deps = proc_macro_deps, + deps = all_crate_deps() + maybe_deps + deps_extra, edition = crate_edition, rustc_flags = rustc_flags_extra, srcs = native.glob(["src/**/*.rs"]), @@ -184,8 +172,7 @@ def codex_rust_crate( srcs = [test], data = native.glob(["tests/**"], allow_empty = True) + sanitized_binaries + test_data_extra, compile_data = native.glob(["tests/**"], allow_empty = True) + integration_compile_data_extra, - deps = deps + dev_deps + integration_deps_extra, - proc_macro_deps = proc_macro_deps + proc_macro_dev_deps, + deps = all_crate_deps(normal = True, normal_dev = True) + maybe_deps + deps_extra, # Keep `file!()` paths Cargo-like (`core/tests/...`) instead of # Bazel workspace-prefixed (`codex-rs/core/tests/...`) for snapshot parity. rustc_flags = rustc_flags_extra + ["--remap-path-prefix=codex-rs="], diff --git a/patches/toolchains_llvm_bootstrapped_resource_dir.patch b/patches/toolchains_llvm_bootstrapped_resource_dir.patch index ab03782802..e475c7a060 100644 --- a/patches/toolchains_llvm_bootstrapped_resource_dir.patch +++ b/patches/toolchains_llvm_bootstrapped_resource_dir.patch @@ -1,5 +1,5 @@ diff --git a/toolchain/args/BUILD.bazel b/toolchain/args/BUILD.bazel -index e6dc56c..b323589 100644 +index 7da0ddb..78326d9 100644 --- a/toolchain/args/BUILD.bazel +++ b/toolchain/args/BUILD.bazel @@ -17,8 +17,8 @@ package(default_visibility = ["//visibility:public"]) @@ -12,29 +12,10 @@ index e6dc56c..b323589 100644 ], args = [ "-resource-dir", -@@ -32,6 +32,46 @@ cc_args( - ], +@@ -32,6 +32,25 @@ cc_args( + }, ) -+alias( -+ name = "clang_builtin_headers_include_search_directory", -+ actual = select({ -+ "@toolchains_llvm_bootstrapped//platforms/config:linux_x86_64": "@llvm-toolchain-minimal-21.1.8-linux-amd64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:linux_aarch64": "@llvm-toolchain-minimal-21.1.8-linux-arm64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:linux_x86_64_gnu": "@llvm-toolchain-minimal-21.1.8-linux-amd64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:linux_aarch64_gnu": "@llvm-toolchain-minimal-21.1.8-linux-arm64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:linux_x86_64_musl": "@llvm-toolchain-minimal-21.1.8-linux-amd64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:linux_aarch64_musl": "@llvm-toolchain-minimal-21.1.8-linux-arm64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:macos_x86_64": "@llvm-toolchain-minimal-21.1.8-darwin-arm64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:macos_aarch64": "@llvm-toolchain-minimal-21.1.8-darwin-arm64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:windows_x86_64": "@llvm-toolchain-minimal-21.1.8-windows-amd64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:windows_aarch64": "@llvm-toolchain-minimal-21.1.8-windows-arm64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:none_wasm32": "@llvm-toolchain-minimal-21.1.8-linux-amd64//:builtin_headers", -+ "@toolchains_llvm_bootstrapped//platforms/config:none_wasm64": "@llvm-toolchain-minimal-21.1.8-linux-amd64//:builtin_headers", -+ }), -+ visibility = ["//toolchain:__subpackages__"], -+) -+ +cc_args( + name = "clang_builtin_headers_include_search_paths", + actions = [ @@ -46,24 +27,22 @@ index e6dc56c..b323589 100644 + "{clang_builtin_headers_include_search_path}", + ], + format = { -+ "clang_builtin_headers_include_search_path": ":clang_builtin_headers_include_search_directory", ++ "clang_builtin_headers_include_search_path": "//:builtin_headers", + }, + data = [ -+ ":clang_builtin_headers_include_search_directory", -+ ], -+ allowlist_include_directories = [ -+ ":clang_builtin_headers_include_search_directory", ++ "//:builtin_headers", + ], ++ allowlist_include_directories = ["//:builtin_headers"], +) + cc_args( name = "llvm_target_for_platform", actions = [ diff --git a/toolchain/BUILD.bazel b/toolchain/BUILD.bazel -index 6ffc9f7..e02089a 100644 +index 1f89467..8f20f10 100644 --- a/toolchain/BUILD.bazel +++ b/toolchain/BUILD.bazel -@@ -100,6 +100,7 @@ cc_args_list( +@@ -107,6 +107,7 @@ cc_args_list( "@platforms//os:macos": [], "//conditions:default": [ "//toolchain/args:resource_dir", diff --git a/rbe.bzl b/rbe.bzl index 5d13812771..a634731cad 100644 --- a/rbe.bzl +++ b/rbe.bzl @@ -18,7 +18,7 @@ platform( "@platforms//cpu:{cpu}", "@platforms//os:linux", "@bazel_tools//tools/cpp:clang", - "@toolchains_llvm_bootstrapped//constraints/libc:gnu.2.28", + "@llvm//constraints/libc:gnu.2.28", ], exec_properties = {{ # Ubuntu-based image that includes git, python3, dotslash, and other From e6773f856c97ce766b7f507a99e5447a1e2a306c Mon Sep 17 00:00:00 2001 From: Celia Chen Date: Tue, 3 Mar 2026 18:41:57 -0800 Subject: [PATCH 359/385] Feat: Preserve network access on read-only sandbox policies (#13409) ## Summary `PermissionProfile.network` could not be preserved when additional or compiled permissions resolved to `SandboxPolicy::ReadOnly`, because `ReadOnly` had no network_access field. This change makes read-only + network enabled representable directly and threads that through the protocol, app-server v2 mirror, and permission- merging logic. ## What changed - Added `network_access: bool` to `SandboxPolicy::ReadOnly` in the core protocol and app-server v2 protocol. - Kept backward compatibility by defaulting the new field to false, so legacy read-only payloads still deserialize unchanged. - Updated `has_full_network_access()` and sandbox summaries to respect read-only network access. - Preserved PermissionProfile.network when: - compiling skill permission profiles into sandbox policies - normalizing additional permissions - merging additional permissions into existing sandbox policies - Updated the approval overlay to show network in the rendered permission rule when requested. - Regenerated app-server schema fixtures for the new v2 wire shape. --- .../schema/json/ClientRequest.json | 4 + .../schema/json/EventMsg.json | 4 + .../codex_app_server_protocol.schemas.json | 4 + .../codex_app_server_protocol.v2.schemas.json | 4 + .../schema/json/v2/CommandExecParams.json | 4 + .../schema/json/v2/ThreadForkResponse.json | 4 + .../schema/json/v2/ThreadResumeResponse.json | 4 + .../schema/json/v2/ThreadStartResponse.json | 4 + .../schema/json/v2/TurnStartParams.json | 4 + .../schema/typescript/SandboxPolicy.ts | 7 +- .../schema/typescript/v2/SandboxPolicy.ts | 2 +- .../app-server-protocol/src/protocol/v2.rs | 29 ++++-- codex-rs/app-server-test-client/src/lib.rs | 3 + codex-rs/core/src/sandboxing/mod.rs | 96 +++++++++++++++++-- codex-rs/core/src/skills/permissions.rs | 15 ++- codex-rs/linux-sandbox/src/bwrap.rs | 2 + codex-rs/protocol/src/protocol.rs | 26 ++++- .../tui/src/bottom_pane/approval_overlay.rs | 9 ++ ...overlay_additional_permissions_prompt.snap | 2 +- .../sandbox-summary/src/sandbox_summary.rs | 17 +++- 20 files changed, 218 insertions(+), 26 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 84ee3d5c1f..509d442678 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -1637,6 +1637,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index 85de9c0dab..a22962cd40 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -5350,6 +5350,10 @@ ], "description": "Read access granted while running under this policy." }, + "network_access": { + "description": "When set to `true`, outbound network access is allowed. `false` by default.", + "type": "boolean" + }, "type": { "enum": [ "read-only" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 61e32239f7..d7ba5671ee 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -11963,6 +11963,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 1d4482c6ff..5cb5a7594c 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -9743,6 +9743,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json b/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json index 4528b34159..08f1a9a15a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json @@ -89,6 +89,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 3e4dca5b1c..41f4c9b7bb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -653,6 +653,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index d9fbc0d02c..416bceb6e0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -653,6 +653,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index ee8b384998..25db79cf24 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -653,6 +653,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json index 0a769c3525..9e749d5b81 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -214,6 +214,10 @@ "type": "fullAccess" } }, + "networkAccess": { + "default": false, + "type": "boolean" + }, "type": { "enum": [ "readOnly" diff --git a/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts b/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts index 743ad22229..8440fd8043 100644 --- a/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts +++ b/codex-rs/app-server-protocol/schema/typescript/SandboxPolicy.ts @@ -12,7 +12,12 @@ export type SandboxPolicy = { "type": "danger-full-access" } | { "type": "read-o /** * Read access granted while running under this policy. */ -access?: ReadOnlyAccess, } | { "type": "external-sandbox", +access?: ReadOnlyAccess, +/** + * When set to `true`, outbound network access is allowed. `false` by + * default. + */ +network_access?: boolean, } | { "type": "external-sandbox", /** * Whether the external sandbox permits outbound network traffic. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts index c81c2642d2..c6780648cf 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts @@ -5,4 +5,4 @@ import type { AbsolutePathBuf } from "../AbsolutePathBuf"; import type { NetworkAccess } from "./NetworkAccess"; import type { ReadOnlyAccess } from "./ReadOnlyAccess"; -export type SandboxPolicy = { "type": "dangerFullAccess" } | { "type": "readOnly", access: ReadOnlyAccess, } | { "type": "externalSandbox", networkAccess: NetworkAccess, } | { "type": "workspaceWrite", writableRoots: Array, readOnlyAccess: ReadOnlyAccess, networkAccess: boolean, excludeTmpdirEnvVar: boolean, excludeSlashTmp: boolean, }; +export type SandboxPolicy = { "type": "dangerFullAccess" } | { "type": "readOnly", access: ReadOnlyAccess, networkAccess: boolean, } | { "type": "externalSandbox", networkAccess: NetworkAccess, } | { "type": "workspaceWrite", writableRoots: Array, readOnlyAccess: ReadOnlyAccess, networkAccess: boolean, excludeTmpdirEnvVar: boolean, excludeSlashTmp: boolean, }; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 0a63b42c46..8c5dfedb16 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -950,6 +950,8 @@ pub enum SandboxPolicy { ReadOnly { #[serde(default)] access: ReadOnlyAccess, + #[serde(default)] + network_access: bool, }, #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] @@ -979,11 +981,13 @@ impl SandboxPolicy { SandboxPolicy::DangerFullAccess => { codex_protocol::protocol::SandboxPolicy::DangerFullAccess } - SandboxPolicy::ReadOnly { access } => { - codex_protocol::protocol::SandboxPolicy::ReadOnly { - access: access.to_core(), - } - } + SandboxPolicy::ReadOnly { + access, + network_access, + } => codex_protocol::protocol::SandboxPolicy::ReadOnly { + access: access.to_core(), + network_access: *network_access, + }, SandboxPolicy::ExternalSandbox { network_access } => { codex_protocol::protocol::SandboxPolicy::ExternalSandbox { network_access: match network_access { @@ -1015,11 +1019,13 @@ impl From for SandboxPolicy { codex_protocol::protocol::SandboxPolicy::DangerFullAccess => { SandboxPolicy::DangerFullAccess } - codex_protocol::protocol::SandboxPolicy::ReadOnly { access } => { - SandboxPolicy::ReadOnly { - access: ReadOnlyAccess::from(access), - } - } + codex_protocol::protocol::SandboxPolicy::ReadOnly { + access, + network_access, + } => SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::from(access), + network_access, + }, codex_protocol::protocol::SandboxPolicy::ExternalSandbox { network_access } => { SandboxPolicy::ExternalSandbox { network_access: match network_access { @@ -4342,6 +4348,7 @@ mod tests { include_platform_defaults: false, readable_roots: vec![readable_root.clone()], }, + network_access: true, }; let core_policy = v2_policy.to_core(); @@ -4352,6 +4359,7 @@ mod tests { include_platform_defaults: false, readable_roots: vec![readable_root], }, + network_access: true, } ); @@ -4402,6 +4410,7 @@ mod tests { policy, SandboxPolicy::ReadOnly { access: ReadOnlyAccess::FullAccess, + network_access: false, } ); } diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index 7baad9be66..06f677ceb7 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -589,6 +589,7 @@ fn trigger_zsh_fork_multi_cmd_approval( turn_params.approval_policy = Some(AskForApproval::OnRequest); turn_params.sandbox_policy = Some(SandboxPolicy::ReadOnly { access: ReadOnlyAccess::FullAccess, + network_access: false, }); let turn_response = client.turn_start(turn_params)?; @@ -722,6 +723,7 @@ fn trigger_cmd_approval( Some(AskForApproval::OnRequest), Some(SandboxPolicy::ReadOnly { access: ReadOnlyAccess::FullAccess, + network_access: false, }), dynamic_tools, ) @@ -744,6 +746,7 @@ fn trigger_patch_approval( Some(AskForApproval::OnRequest), Some(SandboxPolicy::ReadOnly { access: ReadOnlyAccess::FullAccess, + network_access: false, }), dynamic_tools, ) diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index bbd73749e4..fe7d077bb8 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -31,6 +31,7 @@ use codex_protocol::models::PermissionProfile; pub use codex_protocol::models::SandboxPermissions; use codex_protocol::protocol::ReadOnlyAccess; use codex_utils_absolute_path::AbsolutePathBuf; +use dunce::canonicalize; use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; @@ -110,6 +111,7 @@ pub(crate) fn normalize_additional_permissions( .write .map(|paths| normalize_permission_paths(paths, "file_system.write")); Ok(PermissionProfile { + network: additional_permissions.network, file_system: Some(FileSystemPermissions { read, write }), ..Default::default() }) @@ -123,9 +125,7 @@ fn normalize_permission_paths( let mut seen = HashSet::new(); for path in paths { - let canonicalized = path - .as_path() - .canonicalize() + let canonicalized = canonicalize(path.as_path()) .ok() .and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok()) .unwrap_or(path); @@ -189,6 +189,13 @@ fn merge_read_only_access_with_additional_reads( } } +fn merge_network_access( + base_network_access: bool, + additional_permissions: &PermissionProfile, +) -> bool { + base_network_access || matches!(additional_permissions.network, Some(true)) +} + fn sandbox_policy_with_additional_permissions( sandbox_policy: &SandboxPolicy, additional_permissions: &PermissionProfile, @@ -218,15 +225,19 @@ fn sandbox_policy_with_additional_permissions( read_only_access, extra_reads, ), - network_access: *network_access, + network_access: merge_network_access(*network_access, additional_permissions), exclude_tmpdir_env_var: *exclude_tmpdir_env_var, exclude_slash_tmp: *exclude_slash_tmp, } } - SandboxPolicy::ReadOnly { access } => { + SandboxPolicy::ReadOnly { + access, + network_access, + } => { if extra_writes.is_empty() { SandboxPolicy::ReadOnly { access: merge_read_only_access_with_additional_reads(access, extra_reads), + network_access: merge_network_access(*network_access, additional_permissions), } } else { // todo(dylan) - for now, this grants more access than the request. We should restrict this, @@ -238,7 +249,7 @@ fn sandbox_policy_with_additional_permissions( access, extra_reads, ), - network_access: false, + network_access: merge_network_access(*network_access, additional_permissions), exclude_tmpdir_env_var: false, exclude_slash_tmp: false, } @@ -412,11 +423,19 @@ pub async fn execute_env( #[cfg(test)] mod tests { use super::SandboxManager; + use super::normalize_additional_permissions; + use super::sandbox_policy_with_additional_permissions; use crate::exec::SandboxType; + use crate::protocol::ReadOnlyAccess; use crate::protocol::SandboxPolicy; use crate::tools::sandboxing::SandboxablePreference; use codex_protocol::config_types::WindowsSandboxLevel; + use codex_protocol::models::FileSystemPermissions; + use codex_protocol::models::PermissionProfile; + use codex_utils_absolute_path::AbsolutePathBuf; + use dunce::canonicalize; use pretty_assertions::assert_eq; + use tempfile::TempDir; #[test] fn danger_full_access_defaults_to_no_sandbox_without_network_requirements() { @@ -442,4 +461,69 @@ mod tests { ); assert_eq!(sandbox, expected); } + + #[test] + fn normalize_additional_permissions_preserves_network() { + let temp_dir = TempDir::new().expect("create temp dir"); + let path = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let permissions = normalize_additional_permissions(PermissionProfile { + network: Some(true), + file_system: Some(FileSystemPermissions { + read: Some(vec![path.clone()]), + write: Some(vec![path.clone()]), + }), + ..Default::default() + }) + .expect("permissions"); + + assert_eq!(permissions.network, Some(true)); + assert_eq!( + permissions.file_system, + Some(FileSystemPermissions { + read: Some(vec![path.clone()]), + write: Some(vec![path]), + }) + ); + } + + #[test] + fn read_only_additional_permissions_can_enable_network_without_writes() { + let temp_dir = TempDir::new().expect("create temp dir"); + let path = AbsolutePathBuf::from_absolute_path( + canonicalize(temp_dir.path()).expect("canonicalize temp dir"), + ) + .expect("absolute temp dir"); + let policy = sandbox_policy_with_additional_permissions( + &SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![path.clone()], + }, + network_access: false, + }, + &PermissionProfile { + network: Some(true), + file_system: Some(FileSystemPermissions { + read: Some(vec![path.clone()]), + write: Some(Vec::new()), + }), + ..Default::default() + }, + ) + .expect("policy"); + + assert_eq!( + policy, + SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: vec![path], + }, + network_access: true, + } + ); + } } diff --git a/codex-rs/core/src/skills/permissions.rs b/codex-rs/core/src/skills/permissions.rs index 1d0e6c82ad..825128307d 100644 --- a/codex-rs/core/src/skills/permissions.rs +++ b/codex-rs/core/src/skills/permissions.rs @@ -44,6 +44,7 @@ pub(crate) fn compile_permission_profile( file_system, macos, } = permissions?; + let network_access = network.unwrap_or_default(); let file_system = file_system.unwrap_or_default(); let fs_read = normalize_permission_paths( file_system.read.as_deref().unwrap_or_default(), @@ -64,7 +65,7 @@ pub(crate) fn compile_permission_profile( readable_roots: fs_read, } }, - network_access: network.unwrap_or_default(), + network_access, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, } @@ -74,6 +75,12 @@ pub(crate) fn compile_permission_profile( include_platform_defaults: true, readable_roots: fs_read, }, + network_access, + } + } else if network_access { + SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + network_access: true, } } else { // Default sandbox policy @@ -320,7 +327,10 @@ mod tests { profile, Permissions { approval_policy: Constrained::allow_any(AskForApproval::Never), - sandbox_policy: Constrained::allow_any(SandboxPolicy::new_read_only_policy()), + sandbox_policy: Constrained::allow_any(SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + network_access: true, + }), network: None, allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), @@ -366,6 +376,7 @@ mod tests { .expect("absolute read path") ], }, + network_access: true, }), network: None, allow_login_shell: true, diff --git a/codex-rs/linux-sandbox/src/bwrap.rs b/codex-rs/linux-sandbox/src/bwrap.rs index 67a8b8e604..56c4ce70d1 100644 --- a/codex-rs/linux-sandbox/src/bwrap.rs +++ b/codex-rs/linux-sandbox/src/bwrap.rs @@ -478,6 +478,7 @@ mod tests { .expect("absolute readable root"), ], }, + network_access: false, }; let args = create_filesystem_args(&policy, temp_dir.path()).expect("filesystem args"); @@ -503,6 +504,7 @@ mod tests { include_platform_defaults: true, readable_roots: Vec::new(), }, + network_access: false, }; // `ReadOnlyAccess::Restricted` always includes `cwd` as a readable diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 2591a8fb1d..55f19255b0 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -626,6 +626,11 @@ pub enum SandboxPolicy { skip_serializing_if = "ReadOnlyAccess::has_full_disk_read_access" )] access: ReadOnlyAccess, + + /// When set to `true`, outbound network access is allowed. `false` by + /// default. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + network_access: bool, }, /// Indicates the process is already in an external sandbox. Allows full @@ -715,6 +720,7 @@ impl SandboxPolicy { pub fn new_read_only_policy() -> Self { SandboxPolicy::ReadOnly { access: ReadOnlyAccess::FullAccess, + network_access: false, } } @@ -735,7 +741,7 @@ impl SandboxPolicy { match self { SandboxPolicy::DangerFullAccess => true, SandboxPolicy::ExternalSandbox { .. } => true, - SandboxPolicy::ReadOnly { access } => access.has_full_disk_read_access(), + SandboxPolicy::ReadOnly { access, .. } => access.has_full_disk_read_access(), SandboxPolicy::WorkspaceWrite { read_only_access, .. } => read_only_access.has_full_disk_read_access(), @@ -755,7 +761,7 @@ impl SandboxPolicy { match self { SandboxPolicy::DangerFullAccess => true, SandboxPolicy::ExternalSandbox { network_access } => network_access.is_enabled(), - SandboxPolicy::ReadOnly { .. } => false, + SandboxPolicy::ReadOnly { network_access, .. } => *network_access, SandboxPolicy::WorkspaceWrite { network_access, .. } => *network_access, } } @@ -766,7 +772,7 @@ impl SandboxPolicy { return false; } match self { - SandboxPolicy::ReadOnly { access } => access.include_platform_defaults(), + SandboxPolicy::ReadOnly { access, .. } => access.include_platform_defaults(), SandboxPolicy::WorkspaceWrite { read_only_access, .. } => read_only_access.include_platform_defaults(), @@ -782,7 +788,7 @@ impl SandboxPolicy { pub fn get_readable_roots_with_cwd(&self, cwd: &Path) -> Vec { let mut roots = match self { SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } => Vec::new(), - SandboxPolicy::ReadOnly { access } => access.get_readable_roots_with_cwd(cwd), + SandboxPolicy::ReadOnly { access, .. } => access.get_readable_roots_with_cwd(cwd), SandboxPolicy::WorkspaceWrite { read_only_access, .. } => { @@ -3131,6 +3137,18 @@ mod tests { assert!(enabled.has_full_network_access()); } + #[test] + fn read_only_reports_network_access_flags() { + let restricted = SandboxPolicy::new_read_only_policy(); + assert!(!restricted.has_full_network_access()); + + let enabled = SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + network_access: true, + }; + assert!(enabled.has_full_network_access()); + } + #[test] fn reject_config_mcp_elicitation_flag_is_field_driven() { assert!( diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index a9ef2cd38a..548be75769 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -641,6 +641,9 @@ fn format_additional_permissions_rule( additional_permissions: &PermissionProfile, ) -> Option { let mut parts = Vec::new(); + if matches!(additional_permissions.network, Some(true)) { + parts.push("network".to_string()); + } if let Some(file_system) = additional_permissions.file_system.as_ref() { if let Some(read) = file_system.read.as_ref() { let reads = read @@ -1074,6 +1077,7 @@ mod tests { available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, additional_permissions: Some(PermissionProfile { + network: Some(true), file_system: Some(FileSystemPermissions { read: Some(vec![absolute_path("/tmp/readme.txt")]), write: Some(vec![absolute_path("/tmp/out.txt")]), @@ -1100,6 +1104,10 @@ mod tests { .any(|line| line.contains("Permission rule:")), "expected permission-rule line, got {rendered:?}" ); + assert!( + rendered.iter().any(|line| line.contains("network;")), + "expected network permission text, got {rendered:?}" + ); } #[test] @@ -1115,6 +1123,7 @@ mod tests { available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, additional_permissions: Some(PermissionProfile { + network: Some(true), file_system: Some(FileSystemPermissions { read: Some(vec![absolute_path("/tmp/readme.txt")]), write: Some(vec![absolute_path("/tmp/out.txt")]), diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__approval_overlay__tests__approval_overlay_additional_permissions_prompt.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__approval_overlay__tests__approval_overlay_additional_permissions_prompt.snap index 5b04b78b12..989f80f572 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__approval_overlay__tests__approval_overlay_additional_permissions_prompt.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__approval_overlay__tests__approval_overlay_additional_permissions_prompt.snap @@ -7,7 +7,7 @@ expression: "render_overlay_lines(&view, 120)" Reason: need filesystem access - Permission rule: read `/tmp/readme.txt`; write `/tmp/out.txt` + Permission rule: network; read `/tmp/readme.txt`; write `/tmp/out.txt` $ cat /tmp/readme.txt diff --git a/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs b/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs index a5c9b31fdd..a65d6b2ce9 100644 --- a/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs +++ b/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs @@ -4,7 +4,13 @@ use codex_protocol::protocol::SandboxPolicy; pub fn summarize_sandbox_policy(sandbox_policy: &SandboxPolicy) -> String { match sandbox_policy { SandboxPolicy::DangerFullAccess => "danger-full-access".to_string(), - SandboxPolicy::ReadOnly { .. } => "read-only".to_string(), + SandboxPolicy::ReadOnly { network_access, .. } => { + let mut summary = "read-only".to_string(); + if *network_access { + summary.push_str(" (network access enabled)"); + } + summary + } SandboxPolicy::ExternalSandbox { network_access } => { let mut summary = "external-sandbox".to_string(); if matches!(network_access, NetworkAccess::Enabled) { @@ -66,6 +72,15 @@ mod tests { assert_eq!(summary, "external-sandbox (network access enabled)"); } + #[test] + fn summarizes_read_only_with_enabled_network() { + let summary = summarize_sandbox_policy(&SandboxPolicy::ReadOnly { + access: Default::default(), + network_access: true, + }); + assert_eq!(summary, "read-only (network access enabled)"); + } + #[test] fn workspace_write_summary_still_includes_network_access() { let root = if cfg!(windows) { "C:\\repo" } else { "/repo" }; From bfff0c729f51b84eba5bb423b1ca4eb8317e91fd Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Tue, 3 Mar 2026 20:40:22 -0800 Subject: [PATCH 360/385] config: enforce enterprise feature requirements (#13388) ## Why Enterprises can already constrain approvals, sandboxing, and web search through `requirements.toml` and MDM, but feature flags were still only configurable as managed defaults. That meant an enterprise could suggest feature values, but it could not actually pin them. This change closes that gap and makes enterprise feature requirements behave like the other constrained settings. The effective feature set now stays consistent with enterprise requirements during config load, when config writes are validated, and when runtime code mutates feature flags later in the session. It also tightens the runtime API for managed features. `ManagedFeatures` now follows the same constraint-oriented shape as `Constrained` instead of exposing panic-prone mutation helpers, and production code can no longer construct it through an unconstrained `From` path. The PR also hardens the `compact_resume_fork` integration coverage on Windows. After the feature-management changes, `compact_resume_after_second_compaction_preserves_history` was overflowing the libtest/Tokio thread stacks on Windows, so the test now uses an explicit larger-stack harness as a pragmatic mitigation. That may not be the ideal root-cause fix, and it merits a parallel investigation into whether part of the async future chain should be boxed to reduce stack pressure instead. ## What Changed Enterprises can now pin feature values in `requirements.toml` with the requirements-side `features` table: ```toml [features] personality = true unified_exec = false ``` Only canonical feature keys are allowed in the requirements `features` table; omitted keys remain unconstrained. - Added a requirements-side pinned feature map to `ConfigRequirementsToml`, threaded it through source-preserving requirements merge and normalization in `codex-config`, and made the TOML surface use `[features]` (while still accepting legacy `[feature_requirements]` for compatibility). - Exposed `featureRequirements` from `configRequirements/read`, regenerated the JSON/TypeScript schema artifacts, and updated the app-server README. - Wrapped the effective feature set in `ManagedFeatures`, backed by `ConstrainedWithSource`, and changed its API to mirror `Constrained`: `can_set(...)`, `set(...) -> ConstraintResult<()>`, and result-returning `enable` / `disable` / `set_enabled` helpers. - Removed the legacy-usage and bulk-map passthroughs from `ManagedFeatures`; callers that need those behaviors now mutate a plain `Features` value and reapply it through `set(...)`, so the constrained wrapper remains the enforcement boundary. - Removed the production loophole for constructing unconstrained `ManagedFeatures`. Non-test code now creates it through the configured feature-loading path, and `impl From for ManagedFeatures` is restricted to `#[cfg(test)]`. - Rejected legacy feature aliases in enterprise feature requirements, and return a load error when a pinned combination cannot survive dependency normalization. - Validated config writes against enterprise feature requirements before persisting changes, including explicit conflicting writes and profile-specific feature states that normalize into invalid combinations. - Updated runtime and TUI feature-toggle paths to use the constrained setter API and to persist or apply the effective post-constraint value rather than the requested value. - Updated the `core_test_support` Bazel target to include the bundled core model-catalog fixtures in its runtime data, so helper code that resolves `core/models.json` through runfiles works in remote Bazel test environments. - Renamed the core config test coverage to emphasize that effective feature values are normalized at runtime, while conflicting persisted config writes are rejected. - Ran `compact_resume_after_second_compaction_preserves_history` inside an explicit 8 MiB test thread and Tokio runtime worker stack, following the existing larger-stack integration-test pattern, to keep the Windows `compact_resume_fork` test slice from aborting while a parallel investigation continues into whether some of the underlying async futures should be boxed. ## Verification - `cargo test -p codex-config` - `cargo test -p codex-core feature_requirements_ -- --nocapture` - `cargo test -p codex-core load_requirements_toml_produces_expected_constraints -- --nocapture` - `cargo test -p codex-core compact_resume_after_second_compaction_preserves_history -- --nocapture` - `cargo test -p codex-core compact_resume_fork -- --nocapture` - Re-ran the built `codex-core` `tests/all` binary with `RUST_MIN_STACK=262144` for `compact_resume_after_second_compaction_preserves_history` to confirm the explicit-stack harness fixes the deterministic low-stack repro. - `cargo test -p codex-core` - This still fails locally in unrelated integration areas that expect the `codex` / `test_stdio_server` binaries or hit existing `search_tool` wiremock mismatches. ## Docs `developers.openai.com/codex` should document the requirements-side `[features]` table for enterprise and MDM-managed configuration, including that it only accepts canonical feature keys and that conflicting config writes are rejected. --- .../codex_app_server_protocol.schemas.json | 9 + .../codex_app_server_protocol.v2.schemas.json | 9 + .../v2/ConfigRequirementsReadResponse.json | 9 + .../typescript/v2/ConfigRequirements.ts | 2 +- .../app-server-protocol/src/protocol/v2.rs | 2 + codex-rs/app-server/README.md | 2 +- .../app-server/src/codex_message_processor.rs | 8 +- codex-rs/app-server/src/config_api.rs | 17 + codex-rs/cloud-requirements/src/lib.rs | 12 + codex-rs/config/src/config_requirements.rs | 76 ++++ codex-rs/config/src/lib.rs | 1 + codex-rs/core/src/agent/control.rs | 5 +- codex-rs/core/src/codex.rs | 38 +- codex-rs/core/src/config/managed_features.rs | 344 ++++++++++++++++++ codex-rs/core/src/config/mod.rs | 189 ++++++++-- codex-rs/core/src/config/service.rs | 135 +++++++ codex-rs/core/src/config_loader/mod.rs | 1 + codex-rs/core/src/config_loader/tests.rs | 25 ++ codex-rs/core/src/features.rs | 29 +- codex-rs/core/src/mcp/mod.rs | 15 +- codex-rs/core/src/memories/phase2.rs | 2 +- codex-rs/core/src/project_doc.rs | 24 +- codex-rs/core/src/rollout/recorder.rs | 15 +- codex-rs/core/src/tasks/review.rs | 2 +- .../core/src/tools/handlers/multi_agents.rs | 2 +- codex-rs/core/src/tools/js_repl/mod.rs | 3 +- codex-rs/core/tests/common/BUILD.bazel | 3 + codex-rs/core/tests/common/test_codex.rs | 84 ++++- codex-rs/core/tests/common/zsh_fork.rs | 10 +- codex-rs/core/tests/suite/agent_jobs.rs | 40 +- codex-rs/core/tests/suite/agent_websocket.rs | 20 +- codex-rs/core/tests/suite/apply_patch_cli.rs | 5 +- codex-rs/core/tests/suite/approvals.rs | 5 +- codex-rs/core/tests/suite/client.rs | 10 +- .../core/tests/suite/client_websockets.rs | 20 +- codex-rs/core/tests/suite/compact.rs | 2 +- .../core/tests/suite/compact_resume_fork.rs | 31 +- .../core/tests/suite/deprecation_notice.rs | 15 +- codex-rs/core/tests/suite/exec_policy.rs | 30 +- .../core/tests/suite/hierarchical_agents.rs | 10 +- codex-rs/core/tests/suite/js_repl.rs | 15 +- codex-rs/core/tests/suite/memories.rs | 31 +- codex-rs/core/tests/suite/model_switching.rs | 5 +- .../core/tests/suite/model_visible_layout.rs | 10 +- codex-rs/core/tests/suite/otel.rs | 60 ++- codex-rs/core/tests/suite/personality.rs | 60 ++- codex-rs/core/tests/suite/plugins.rs | 11 +- codex-rs/core/tests/suite/prompt_caching.rs | 40 +- .../core/tests/suite/request_compression.rs | 10 +- .../core/tests/suite/request_permissions.rs | 30 +- .../core/tests/suite/request_user_input.rs | 6 +- codex-rs/core/tests/suite/search_tool.rs | 17 +- codex-rs/core/tests/suite/shell_command.rs | 12 +- codex-rs/core/tests/suite/shell_snapshot.rs | 40 +- codex-rs/core/tests/suite/sqlite_state.rs | 30 +- .../tests/suite/subagent_notifications.rs | 11 +- codex-rs/core/tests/suite/tool_harness.rs | 10 +- codex-rs/core/tests/suite/tools.rs | 10 +- codex-rs/core/tests/suite/undo.rs | 5 +- codex-rs/core/tests/suite/unified_exec.rs | 130 +++++-- .../tests/suite/unstable_features_warning.rs | 10 +- codex-rs/core/tests/suite/user_shell_cmd.rs | 5 +- codex-rs/core/tests/suite/view_image.rs | 21 +- codex-rs/core/tests/suite/web_search.rs | 25 +- .../core/tests/suite/websocket_fallback.rs | 20 +- codex-rs/tui/src/app.rs | 40 +- codex-rs/tui/src/chatwidget.rs | 14 +- codex-rs/tui/src/chatwidget/tests.rs | 40 +- codex-rs/tui/src/debug_config.rs | 2 + codex-rs/tui/src/lib.rs | 5 +- 70 files changed, 1718 insertions(+), 268 deletions(-) create mode 100644 codex-rs/core/src/config/managed_features.rs diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index d7ba5671ee..374bdc1971 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -9007,6 +9007,15 @@ "type": "null" } ] + }, + "featureRequirements": { + "additionalProperties": { + "type": "boolean" + }, + "type": [ + "object", + "null" + ] } }, "type": "object" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 5cb5a7594c..2ca096cff1 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -2881,6 +2881,15 @@ "type": "null" } ] + }, + "featureRequirements": { + "additionalProperties": { + "type": "boolean" + }, + "type": [ + "object", + "null" + ] } }, "type": "object" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 651e035e9c..c4a06943aa 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -81,6 +81,15 @@ "type": "null" } ] + }, + "featureRequirements": { + "additionalProperties": { + "type": "boolean" + }, + "type": [ + "object", + "null" + ] } }, "type": "object" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ConfigRequirements.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ConfigRequirements.ts index f99c880697..47a99453fe 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ConfigRequirements.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ConfigRequirements.ts @@ -6,4 +6,4 @@ import type { AskForApproval } from "./AskForApproval"; import type { ResidencyRequirement } from "./ResidencyRequirement"; import type { SandboxMode } from "./SandboxMode"; -export type ConfigRequirements = {allowedApprovalPolicies: Array | null, allowedSandboxModes: Array | null, allowedWebSearchModes: Array | null, enforceResidency: ResidencyRequirement | null}; +export type ConfigRequirements = {allowedApprovalPolicies: Array | null, allowedSandboxModes: Array | null, allowedWebSearchModes: Array | null, featureRequirements: { [key in string]?: boolean } | null, enforceResidency: ResidencyRequirement | null}; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 8c5dfedb16..7c69d9fa11 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeMap; use std::collections::HashMap; use std::path::PathBuf; @@ -611,6 +612,7 @@ pub struct ConfigRequirements { pub allowed_approval_policies: Option>, pub allowed_sandbox_modes: Option>, pub allowed_web_search_modes: Option>, + pub feature_requirements: Option>, pub enforce_residency: Option, #[experimental("configRequirements/read.network")] pub network: Option, diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 786a935b6d..b105d411b1 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -165,7 +165,7 @@ Example with notification opt-out: - `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home). - `config/value/write` — write a single config key/value to the user's config.toml on disk. - `config/batchWrite` — apply multiple config edits atomically to the user's config.toml on disk. -- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`), `enforceResidency`, and `network` constraints. +- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`), pinned feature values (`featureRequirements`), `enforceResidency`, and `network` constraints. ### Example: Start or resume a thread diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index f154bff311..80558642cb 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -4550,11 +4550,9 @@ impl CodexMessageProcessor { } }; - if thread.enabled(Feature::Apps) { - config.features.enable(Feature::Apps); - } else { - config.features.disable(Feature::Apps); - } + let _ = config + .features + .set_enabled(Feature::Apps, thread.enabled(Feature::Apps)); } if !config.features.enabled(Feature::Apps) { diff --git a/codex-rs/app-server/src/config_api.rs b/codex-rs/app-server/src/config_api.rs index c9317ac9f5..4b0b66ccab 100644 --- a/codex-rs/app-server/src/config_api.rs +++ b/codex-rs/app-server/src/config_api.rs @@ -127,6 +127,9 @@ fn map_requirements_toml_to_api(requirements: ConfigRequirementsToml) -> ConfigR } normalized }), + feature_requirements: requirements + .feature_requirements + .map(|requirements| requirements.entries), enforce_residency: requirements .enforce_residency .map(map_residency_requirement_to_api), @@ -212,6 +215,12 @@ mod tests { allowed_web_search_modes: Some(vec![ codex_core::config_loader::WebSearchModeRequirement::Cached, ]), + feature_requirements: Some(codex_core::config_loader::FeatureRequirementsToml { + entries: std::collections::BTreeMap::from([ + ("apps".to_string(), false), + ("personality".to_string(), true), + ]), + }), mcp_servers: None, rules: None, enforce_residency: Some(CoreResidencyRequirement::Us), @@ -247,6 +256,13 @@ mod tests { mapped.allowed_web_search_modes, Some(vec![WebSearchMode::Cached, WebSearchMode::Disabled]), ); + assert_eq!( + mapped.feature_requirements, + Some(std::collections::BTreeMap::from([ + ("apps".to_string(), false), + ("personality".to_string(), true), + ])), + ); assert_eq!( mapped.enforce_residency, Some(codex_app_server_protocol::ResidencyRequirement::Us), @@ -275,6 +291,7 @@ mod tests { allowed_approval_policies: None, allowed_sandbox_modes: None, allowed_web_search_modes: Some(Vec::new()), + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index 2b51a9e9eb..9e4a8b002d 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -761,6 +761,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -803,6 +804,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -856,6 +858,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -912,6 +915,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -939,6 +943,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -986,6 +991,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -1032,6 +1038,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -1082,6 +1089,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -1133,6 +1141,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -1184,6 +1193,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -1272,6 +1282,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -1295,6 +1306,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index d895ef0736..40af63f7af 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -79,6 +79,7 @@ pub struct ConfigRequirements { pub approval_policy: ConstrainedWithSource, pub sandbox_policy: ConstrainedWithSource, pub web_search_mode: ConstrainedWithSource, + pub feature_requirements: Option>, pub mcp_servers: Option>>, pub exec_policy: Option>, pub enforce_residency: ConstrainedWithSource>, @@ -101,6 +102,7 @@ impl Default for ConfigRequirements { Constrained::allow_any(WebSearchMode::Cached), None, ), + feature_requirements: None, mcp_servers: None, exec_policy: None, enforce_residency: ConstrainedWithSource::new(Constrained::allow_any(None), None), @@ -227,12 +229,26 @@ impl fmt::Display for WebSearchModeRequirement { } } +#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct FeatureRequirementsToml { + #[serde(flatten)] + pub entries: BTreeMap, +} + +impl FeatureRequirementsToml { + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + /// Base config deserialized from system `requirements.toml` or MDM. #[derive(Deserialize, Debug, Clone, Default, PartialEq)] pub struct ConfigRequirementsToml { pub allowed_approval_policies: Option>, pub allowed_sandbox_modes: Option>, pub allowed_web_search_modes: Option>, + #[serde(rename = "features", alias = "feature_requirements")] + pub feature_requirements: Option, pub mcp_servers: Option>, pub rules: Option, pub enforce_residency: Option, @@ -267,6 +283,7 @@ pub struct ConfigRequirementsWithSources { pub allowed_approval_policies: Option>>, pub allowed_sandbox_modes: Option>>, pub allowed_web_search_modes: Option>>, + pub feature_requirements: Option>, pub mcp_servers: Option>>, pub rules: Option>, pub enforce_residency: Option>, @@ -302,6 +319,7 @@ impl ConfigRequirementsWithSources { allowed_approval_policies, allowed_sandbox_modes, allowed_web_search_modes, + feature_requirements, mcp_servers, rules, enforce_residency, @@ -315,6 +333,7 @@ impl ConfigRequirementsWithSources { allowed_approval_policies, allowed_sandbox_modes, allowed_web_search_modes, + feature_requirements, mcp_servers, rules, enforce_residency, @@ -324,6 +343,7 @@ impl ConfigRequirementsWithSources { allowed_approval_policies: allowed_approval_policies.map(|sourced| sourced.value), allowed_sandbox_modes: allowed_sandbox_modes.map(|sourced| sourced.value), allowed_web_search_modes: allowed_web_search_modes.map(|sourced| sourced.value), + feature_requirements: feature_requirements.map(|sourced| sourced.value), mcp_servers: mcp_servers.map(|sourced| sourced.value), rules: rules.map(|sourced| sourced.value), enforce_residency: enforce_residency.map(|sourced| sourced.value), @@ -370,6 +390,10 @@ impl ConfigRequirementsToml { self.allowed_approval_policies.is_none() && self.allowed_sandbox_modes.is_none() && self.allowed_web_search_modes.is_none() + && self + .feature_requirements + .as_ref() + .is_none_or(FeatureRequirementsToml::is_empty) && self.mcp_servers.is_none() && self.rules.is_none() && self.enforce_residency.is_none() @@ -385,6 +409,7 @@ impl TryFrom for ConfigRequirements { allowed_approval_policies, allowed_sandbox_modes, allowed_web_search_modes, + feature_requirements, mcp_servers, rules, enforce_residency, @@ -521,6 +546,8 @@ impl TryFrom for ConfigRequirements { } None => ConstrainedWithSource::new(Constrained::allow_any(WebSearchMode::Cached), None), }; + let feature_requirements = + feature_requirements.filter(|requirements| !requirements.value.is_empty()); let enforce_residency = match enforce_residency { Some(Sourced { @@ -553,6 +580,7 @@ impl TryFrom for ConfigRequirements { approval_policy, sandbox_policy, web_search_mode, + feature_requirements, mcp_servers, exec_policy, enforce_residency, @@ -588,6 +616,7 @@ mod tests { allowed_approval_policies, allowed_sandbox_modes, allowed_web_search_modes, + feature_requirements, mcp_servers, rules, enforce_residency, @@ -600,6 +629,8 @@ mod tests { .map(|value| Sourced::new(value, RequirementSource::Unknown)), allowed_web_search_modes: allowed_web_search_modes .map(|value| Sourced::new(value, RequirementSource::Unknown)), + feature_requirements: feature_requirements + .map(|value| Sourced::new(value, RequirementSource::Unknown)), mcp_servers: mcp_servers.map(|value| Sourced::new(value, RequirementSource::Unknown)), rules: rules.map(|value| Sourced::new(value, RequirementSource::Unknown)), enforce_residency: enforce_residency @@ -622,6 +653,9 @@ mod tests { WebSearchModeRequirement::Cached, WebSearchModeRequirement::Live, ]; + let feature_requirements = FeatureRequirementsToml { + entries: BTreeMap::from([("personality".to_string(), true)]), + }; let enforce_residency = ResidencyRequirement::Us; let enforce_source = source.clone(); @@ -631,6 +665,7 @@ mod tests { allowed_approval_policies: Some(allowed_approval_policies.clone()), allowed_sandbox_modes: Some(allowed_sandbox_modes.clone()), allowed_web_search_modes: Some(allowed_web_search_modes.clone()), + feature_requirements: Some(feature_requirements.clone()), mcp_servers: None, rules: None, enforce_residency: Some(enforce_residency), @@ -651,6 +686,10 @@ mod tests { allowed_web_search_modes, enforce_source.clone(), )), + feature_requirements: Some(Sourced::new( + feature_requirements, + enforce_source.clone(), + )), mcp_servers: None, rules: None, enforce_residency: Some(Sourced::new(enforce_residency, enforce_source)), @@ -683,6 +722,7 @@ mod tests { )), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -723,6 +763,7 @@ mod tests { )), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -809,6 +850,8 @@ mod tests { allowed_sandbox_modes = ["read-only"] allowed_web_search_modes = ["cached"] enforce_residency = "us" + [features] + personality = true "#, )?; @@ -829,6 +872,13 @@ mod tests { requirements.web_search_mode.source, Some(source_location.clone()) ); + assert_eq!( + requirements + .feature_requirements + .as_ref() + .map(|requirements| requirements.source.clone()), + Some(source_location.clone()) + ); assert_eq!(requirements.enforce_residency.source, Some(source_location)); Ok(()) @@ -1038,6 +1088,32 @@ mod tests { Ok(()) } + #[test] + fn deserialize_feature_requirements() -> Result<()> { + let toml_str = r#" + [features] + apps = false + personality = true + "#; + let config: ConfigRequirementsToml = from_str(toml_str)?; + let requirements: ConfigRequirements = with_unknown_source(config).try_into()?; + + assert_eq!( + requirements.feature_requirements, + Some(Sourced::new( + FeatureRequirementsToml { + entries: BTreeMap::from([ + ("apps".to_string(), false), + ("personality".to_string(), true), + ]), + }, + RequirementSource::Unknown, + )) + ); + + Ok(()) + } + #[test] fn network_requirements_are_preserved_as_constraints_with_source() -> Result<()> { let toml_str = r#" diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs index b85e99133d..c8e25e6e60 100644 --- a/codex-rs/config/src/lib.rs +++ b/codex-rs/config/src/lib.rs @@ -16,6 +16,7 @@ pub use config_requirements::ConfigRequirements; pub use config_requirements::ConfigRequirementsToml; pub use config_requirements::ConfigRequirementsWithSources; pub use config_requirements::ConstrainedWithSource; +pub use config_requirements::FeatureRequirementsToml; pub use config_requirements::McpServerIdentity; pub use config_requirements::McpServerRequirement; pub use config_requirements::NetworkConstraints; diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 85f28b4f6b..fa643ff3ce 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -1381,7 +1381,10 @@ mod tests { #[tokio::test] async fn resume_thread_subagent_restores_stored_nickname_and_role() { let (home, mut config) = test_config().await; - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow sqlite"); let manager = ThreadManager::with_models_provider_and_home_for_tests( CodexAuth::from_api_key("dummy"), config.model_provider.clone(), diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 87aac73185..9b9e0214a8 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -23,11 +23,11 @@ use crate::compact::InitialContextInjection; use crate::compact::run_inline_auto_compact_task; use crate::compact::should_use_remote_compact_task; use crate::compact_remote::run_inline_remote_auto_compact_task; +use crate::config::ManagedFeatures; use crate::connectors; use crate::exec_policy::ExecPolicyManager; use crate::features::FEATURES; use crate::features::Feature; -use crate::features::Features; use crate::features::maybe_push_unstable_features_warning; #[cfg(test)] use crate::models_manager::collaboration_mode_presets::CollaborationModesConfig; @@ -373,18 +373,24 @@ impl Codex { if let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { depth, .. }) = session_source && depth >= config.agent_max_depth { - config.features.disable(Feature::Collab); + let _ = config.features.disable(Feature::Collab); } if config.features.enabled(Feature::JsRepl) && let Err(err) = resolve_compatible_node(config.js_repl_node_path.as_deref()).await { - let message = format!( - "Disabled `js_repl` for this session because the configured Node runtime is unavailable or incompatible. {err}" - ); + let _ = config.features.disable(Feature::JsRepl); + let _ = config.features.disable(Feature::JsReplToolsOnly); + let message = if config.features.enabled(Feature::JsRepl) { + format!( + "`js_repl` remains enabled because enterprise requirements pin it on, but the configured Node runtime is unavailable or incompatible. {err}" + ) + } else { + format!( + "Disabled `js_repl` for this session because the configured Node runtime is unavailable or incompatible. {err}" + ) + }; warn!("{message}"); - config.features.disable(Feature::JsRepl); - config.features.disable(Feature::JsReplToolsOnly); config.startup_warnings.push(message); } @@ -620,7 +626,7 @@ pub(crate) struct Session { state: Mutex, /// The set of enabled features should be invariant for the lifetime of the /// session. - features: Features, + features: ManagedFeatures, pending_mcp_server_refresh_config: Mutex>, pub(crate) conversation: Arc, pub(crate) active_turn: Mutex>, @@ -674,7 +680,7 @@ pub(crate) struct TurnContext { pub(crate) windows_sandbox_level: WindowsSandboxLevel, pub(crate) shell_environment_policy: ShellEnvironmentPolicy, pub(crate) tools_config: ToolsConfig, - pub(crate) features: Features, + pub(crate) features: ManagedFeatures, pub(crate) ghost_snapshot: GhostSnapshotConfig, pub(crate) final_output_json_schema: Option, pub(crate) codex_linux_sandbox_exe: Option, @@ -3020,7 +3026,7 @@ impl Session { self.features.enabled(feature) } - pub(crate) fn features(&self) -> Features { + pub(crate) fn features(&self) -> ManagedFeatures { self.features.clone() } @@ -4719,9 +4725,8 @@ async fn spawn_review_thread( .await; // For reviews, disable web_search and view_image regardless of global settings. let mut review_features = sess.features.clone(); - review_features - .disable(crate::features::Feature::WebSearchRequest) - .disable(crate::features::Feature::WebSearchCached); + let _ = review_features.disable(crate::features::Feature::WebSearchRequest); + let _ = review_features.disable(crate::features::Feature::WebSearchCached); let review_web_search_mode = WebSearchMode::Disabled; let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &review_model_info, @@ -8260,7 +8265,10 @@ mod tests { async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { let codex_home = tempfile::tempdir().expect("create temp dir"); let mut config = build_test_config(codex_home.path()).await; - config.features.enable(Feature::ShellZshFork); + config + .features + .enable(Feature::ShellZshFork) + .expect("test config should allow shell_zsh_fork"); config.zsh_path = None; let config = Arc::new(config); @@ -8813,7 +8821,7 @@ mod tests { #[tokio::test] async fn record_model_warning_appends_user_message() { let (mut session, turn_context) = make_session_and_context().await; - let features = Features::with_defaults(); + let features = crate::features::Features::with_defaults().into(); session.features = features; session diff --git a/codex-rs/core/src/config/managed_features.rs b/codex-rs/core/src/config/managed_features.rs new file mode 100644 index 0000000000..13510b0d85 --- /dev/null +++ b/codex-rs/core/src/config/managed_features.rs @@ -0,0 +1,344 @@ +use std::collections::BTreeMap; + +use codex_config::Constrained; +use codex_config::ConstrainedWithSource; +use codex_config::ConstraintError; +use codex_config::ConstraintResult; +use codex_config::FeatureRequirementsToml; +use codex_config::RequirementSource; +use codex_config::Sourced; + +use crate::config::ConfigToml; +use crate::config::profile::ConfigProfile; +use crate::features::Feature; +use crate::features::FeatureOverrides; +use crate::features::Features; +use crate::features::canonical_feature_for_key; +use crate::features::feature_for_key; + +/// Wrapper around [`Features`] which enforces constraints defined in +/// `FeatureRequirementsToml` and provides normalization to ensure constraints +/// are satisfied. Constraints are enforced on construction and mutation of +/// `ManagedFeatures`. +#[derive(Debug, Clone, PartialEq)] +pub struct ManagedFeatures { + value: ConstrainedWithSource, + pinned_features: BTreeMap, +} + +impl ManagedFeatures { + pub(crate) fn from_configured( + configured_features: Features, + feature_requirements: Option>, + ) -> std::io::Result { + let (pinned_features, source) = match feature_requirements { + Some(Sourced { + value: feature_requirements, + source, + }) => ( + parse_feature_requirements(feature_requirements, &source)?, + Some(source), + ), + None => (BTreeMap::new(), None), + }; + + let normalized_features = normalize_candidate(configured_features, &pinned_features); + validate_pinned_features(&normalized_features, &pinned_features, source.as_ref())?; + Ok(Self { + value: ConstrainedWithSource::new(Constrained::allow_any(normalized_features), source), + pinned_features, + }) + } + + pub fn get(&self) -> &Features { + self.value.get() + } + + fn normalize_and_validate(&self, candidate: Features) -> ConstraintResult { + let normalized = normalize_candidate(candidate, &self.pinned_features); + self.value.can_set(&normalized)?; + validate_pinned_features_constraint( + &normalized, + &self.pinned_features, + self.value.source.as_ref(), + )?; + Ok(normalized) + } + + pub fn can_set(&self, candidate: &Features) -> ConstraintResult<()> { + self.normalize_and_validate(candidate.clone()).map(|_| ()) + } + + pub fn set(&mut self, candidate: Features) -> ConstraintResult<()> { + let normalized = self.normalize_and_validate(candidate)?; + self.value.value.set(normalized) + } + + pub fn set_enabled(&mut self, feature: Feature, enabled: bool) -> ConstraintResult<()> { + let mut next = self.get().clone(); + next.set_enabled(feature, enabled); + self.set(next) + } + + pub fn enable(&mut self, feature: Feature) -> ConstraintResult<()> { + self.set_enabled(feature, true) + } + + pub fn disable(&mut self, feature: Feature) -> ConstraintResult<()> { + self.set_enabled(feature, false) + } +} + +/// Only available for tests to ensure `ManagedFeatures` is constructed with +/// any required constraints taken into account. +#[cfg(test)] +impl From for ManagedFeatures { + fn from(features: Features) -> Self { + Self { + value: ConstrainedWithSource::new(Constrained::allow_any(features), None), + pinned_features: BTreeMap::new(), + } + } +} + +impl std::ops::Deref for ManagedFeatures { + type Target = Features; + + fn deref(&self) -> &Self::Target { + self.get() + } +} + +fn normalize_candidate( + mut candidate: Features, + pinned_features: &BTreeMap, +) -> Features { + for (feature, enabled) in pinned_features { + candidate.set_enabled(*feature, *enabled); + } + candidate.normalize_dependencies(); + candidate +} + +fn validate_pinned_features_constraint( + normalized_features: &Features, + pinned_features: &BTreeMap, + source: Option<&RequirementSource>, +) -> ConstraintResult<()> { + let Some(source) = source else { + return Ok(()); + }; + let allowed = feature_requirements_display(pinned_features); + for (feature, enabled) in pinned_features { + if normalized_features.enabled(*feature) != *enabled { + return Err(ConstraintError::InvalidValue { + field_name: "features", + candidate: format!( + "{}={}", + feature.key(), + normalized_features.enabled(*feature) + ), + allowed, + requirement_source: source.clone(), + }); + } + } + + Ok(()) +} + +fn validate_pinned_features( + normalized_features: &Features, + pinned_features: &BTreeMap, + source: Option<&RequirementSource>, +) -> std::io::Result<()> { + validate_pinned_features_constraint(normalized_features, pinned_features, source) + .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err)) +} + +fn feature_requirements_display(feature_requirements: &BTreeMap) -> String { + let values = feature_requirements + .iter() + .map(|(feature, enabled)| format!("{}={enabled}", feature.key())) + .collect::>(); + format!("[{}]", values.join(", ")) +} + +fn parse_feature_requirements( + feature_requirements: FeatureRequirementsToml, + source: &RequirementSource, +) -> std::io::Result> { + let mut pinned_features = BTreeMap::new(); + for (key, enabled) in feature_requirements.entries { + if let Some(feature) = canonical_feature_for_key(&key) { + pinned_features.insert(feature, enabled); + continue; + } + + if let Some(feature) = feature_for_key(&key) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "invalid `features` requirement `{key}` from {source}: use canonical feature key `{}`", + feature.key() + ), + )); + } + + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("invalid `features` requirement `{key}` from {source}"), + )); + } + + Ok(pinned_features) +} + +fn explicit_feature_settings_in_config(cfg: &ConfigToml) -> Vec<(String, Feature, bool)> { + let mut explicit_settings = Vec::new(); + + if let Some(features) = cfg.features.as_ref() { + for (key, enabled) in &features.entries { + if let Some(feature) = feature_for_key(key) { + explicit_settings.push((format!("features.{key}"), feature, *enabled)); + } + } + } + if let Some(enabled) = cfg.experimental_use_unified_exec_tool { + explicit_settings.push(( + "experimental_use_unified_exec_tool".to_string(), + Feature::UnifiedExec, + enabled, + )); + } + if let Some(enabled) = cfg.experimental_use_freeform_apply_patch { + explicit_settings.push(( + "experimental_use_freeform_apply_patch".to_string(), + Feature::ApplyPatchFreeform, + enabled, + )); + } + if let Some(enabled) = cfg.tools.as_ref().and_then(|tools| tools.web_search) { + explicit_settings.push(( + "tools.web_search".to_string(), + Feature::WebSearchRequest, + enabled, + )); + } + + for (profile_name, profile) in &cfg.profiles { + if let Some(features) = profile.features.as_ref() { + for (key, enabled) in &features.entries { + if let Some(feature) = feature_for_key(key) { + explicit_settings.push(( + format!("profiles.{profile_name}.features.{key}"), + feature, + *enabled, + )); + } + } + } + if let Some(enabled) = profile.include_apply_patch_tool { + explicit_settings.push(( + format!("profiles.{profile_name}.include_apply_patch_tool"), + Feature::ApplyPatchFreeform, + enabled, + )); + } + if let Some(enabled) = profile.experimental_use_unified_exec_tool { + explicit_settings.push(( + format!("profiles.{profile_name}.experimental_use_unified_exec_tool"), + Feature::UnifiedExec, + enabled, + )); + } + if let Some(enabled) = profile.experimental_use_freeform_apply_patch { + explicit_settings.push(( + format!("profiles.{profile_name}.experimental_use_freeform_apply_patch"), + Feature::ApplyPatchFreeform, + enabled, + )); + } + if let Some(enabled) = profile.tools_web_search { + explicit_settings.push(( + format!("profiles.{profile_name}.tools_web_search"), + Feature::WebSearchRequest, + enabled, + )); + } + } + + explicit_settings +} + +pub(crate) fn validate_explicit_feature_settings_in_config_toml( + cfg: &ConfigToml, + feature_requirements: Option<&Sourced>, +) -> std::io::Result<()> { + let Some(Sourced { + value: feature_requirements, + source, + }) = feature_requirements + else { + return Ok(()); + }; + + let pinned_features = parse_feature_requirements(feature_requirements.clone(), source)?; + if pinned_features.is_empty() { + return Ok(()); + } + + let allowed = feature_requirements_display(&pinned_features); + for (path, feature, enabled) in explicit_feature_settings_in_config(cfg) { + if pinned_features + .get(&feature) + .is_some_and(|required| *required != enabled) + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + ConstraintError::InvalidValue { + field_name: "features", + candidate: format!("{path}={enabled}"), + allowed, + requirement_source: source.clone(), + }, + )); + } + } + + Ok(()) +} + +pub(crate) fn validate_feature_requirements_in_config_toml( + cfg: &ConfigToml, + feature_requirements: Option<&Sourced>, +) -> std::io::Result<()> { + fn validate_profile( + cfg: &ConfigToml, + profile_name: Option<&str>, + profile: &ConfigProfile, + feature_requirements: Option<&Sourced>, + ) -> std::io::Result<()> { + let configured_features = Features::from_config(cfg, profile, FeatureOverrides::default()); + ManagedFeatures::from_configured(configured_features, feature_requirements.cloned()) + .map(|_| ()) + .map_err(|err| { + if let Some(profile_name) = profile_name { + std::io::Error::new( + err.kind(), + format!( + "invalid feature configuration for profile `{profile_name}`: {err}" + ), + ) + } else { + err + } + }) + } + + validate_profile(cfg, None, &ConfigProfile::default(), feature_requirements)?; + for (profile_name, profile) in &cfg.profiles { + validate_profile(cfg, Some(profile_name), profile, feature_requirements)?; + } + Ok(()) +} diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index bb313f25f3..3b71f8fac4 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -91,6 +91,7 @@ use toml::Value as TomlValue; use toml_edit::DocumentMut; pub mod edit; +mod managed_features; mod network_proxy_spec; mod permissions; pub mod profile; @@ -102,6 +103,7 @@ pub use codex_config::ConstraintError; pub use codex_config::ConstraintResult; pub use codex_network_proxy::NetworkProxyAuditMetadata; +pub use managed_features::ManagedFeatures; pub use network_proxy_spec::NetworkProxySpec; pub use network_proxy_spec::StartedNetworkProxy; pub use permissions::NetworkToml; @@ -475,7 +477,7 @@ pub struct Config { pub ghost_snapshot: GhostSnapshotConfig, /// Centralized feature flags; source of truth for feature gating. - pub features: Features, + pub features: ManagedFeatures, /// When `true`, suppress warnings about unstable (under development) features. pub suppress_unstable_features_warning: bool, @@ -1684,7 +1686,19 @@ impl Config { codex_home: PathBuf, config_layer_stack: ConfigLayerStack, ) -> std::io::Result { - let requirements = config_layer_stack.requirements().clone(); + // Ensure that every field of ConfigRequirements is applied to the final + // Config. + let ConfigRequirements { + approval_policy: mut constrained_approval_policy, + sandbox_policy: mut constrained_sandbox_policy, + web_search_mode: mut constrained_web_search_mode, + feature_requirements, + mcp_servers, + exec_policy: _, + enforce_residency, + network: network_requirements, + } = config_layer_stack.requirements().clone(); + let user_instructions = Self::load_instructions(Some(&codex_home)); let mut startup_warnings = Vec::new(); @@ -1739,7 +1753,8 @@ impl Config { web_search_request: override_tools_web_search_request, }; - let features = Features::from_config(&cfg, &config_profile, feature_overrides); + let configured_features = Features::from_config(&cfg, &config_profile, feature_overrides); + let features = ManagedFeatures::from_configured(configured_features, feature_requirements)?; let windows_sandbox_mode = resolve_windows_sandbox_mode(&cfg, &config_profile); let resolved_cwd = { use std::env; @@ -1780,7 +1795,7 @@ impl Config { config_profile.sandbox_mode, windows_sandbox_level, &resolved_cwd, - Some(&requirements.sandbox_policy), + Some(&constrained_sandbox_policy), ); if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = &mut sandbox_policy { for path in additional_writable_roots { @@ -1805,13 +1820,13 @@ impl Config { } }); if !approval_policy_was_explicit - && let Err(err) = requirements.approval_policy.can_set(&approval_policy) + && let Err(err) = constrained_approval_policy.can_set(&approval_policy) { tracing::warn!( error = %err, "default approval policy is disallowed by requirements; falling back to required default" ); - approval_policy = requirements.approval_policy.value(); + approval_policy = constrained_approval_policy.value(); } let web_search_mode = resolve_web_search_mode(&cfg, &config_profile, &features) .unwrap_or(WebSearchMode::Cached); @@ -2052,18 +2067,6 @@ impl Config { .or_else(|| resolve_sqlite_home_env(&resolved_cwd)) .unwrap_or_else(|| codex_home.to_path_buf()); - // Ensure that every field of ConfigRequirements is applied to the final - // Config. - let ConfigRequirements { - approval_policy: mut constrained_approval_policy, - sandbox_policy: mut constrained_sandbox_policy, - web_search_mode: mut constrained_web_search_mode, - mcp_servers, - exec_policy: _, - enforce_residency, - network: network_requirements, - } = requirements; - apply_requirement_constrained_value( "approval_policy", approval_policy, @@ -4967,7 +4970,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: !cfg!(windows), background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), - features: Features::with_defaults(), + features: Features::with_defaults().into(), suppress_unstable_features_warning: false, active_profile: Some("o3".to_string()), active_project: ProjectConfig { trust_level: None }, @@ -5097,7 +5100,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: !cfg!(windows), background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), - features: Features::with_defaults(), + features: Features::with_defaults().into(), suppress_unstable_features_warning: false, active_profile: Some("gpt3".to_string()), active_project: ProjectConfig { trust_level: None }, @@ -5225,7 +5228,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: !cfg!(windows), background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), - features: Features::with_defaults(), + features: Features::with_defaults().into(), suppress_unstable_features_warning: false, active_profile: Some("zdr".to_string()), active_project: ProjectConfig { trust_level: None }, @@ -5339,7 +5342,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: !cfg!(windows), background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), - features: Features::with_defaults(), + features: Features::with_defaults().into(), suppress_unstable_features_warning: false, active_profile: Some("gpt5".to_string()), active_project: ProjectConfig { trust_level: None }, @@ -5394,6 +5397,7 @@ model_verbosity = "high" allowed_web_search_modes: Some(vec![ crate::config_loader::WebSearchModeRequirement::Cached, ]), + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -5998,6 +6002,7 @@ mcp_oauth_callback_url = "https://example.com/callback" crate::config_loader::SandboxModeRequirement::ReadOnly, ]), allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -6116,6 +6121,146 @@ trust_level = "untrusted" ); Ok(()) } + + #[tokio::test] + async fn feature_requirements_normalize_effective_feature_values() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + + let config = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .cloud_requirements(CloudRequirementsLoader::new(async { + Ok(Some(crate::config_loader::ConfigRequirementsToml { + feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([ + ("personality".to_string(), true), + ("shell_tool".to_string(), false), + ]), + }), + ..Default::default() + })) + })) + .build() + .await?; + + assert!(config.features.enabled(Feature::Personality)); + assert!(!config.features.enabled(Feature::ShellTool)); + assert!( + !config + .startup_warnings + .iter() + .any(|warning| warning.contains("Configured value for `features`")), + "{:?}", + config.startup_warnings + ); + + Ok(()) + } + + #[tokio::test] + async fn explicit_feature_config_is_normalized_by_requirements() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#" +[features] +personality = false +shell_tool = true +"#, + )?; + + let config = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .cloud_requirements(CloudRequirementsLoader::new(async { + Ok(Some(crate::config_loader::ConfigRequirementsToml { + feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([ + ("personality".to_string(), true), + ("shell_tool".to_string(), false), + ]), + }), + ..Default::default() + })) + })) + .build() + .await?; + + assert!(config.features.enabled(Feature::Personality)); + assert!(!config.features.enabled(Feature::ShellTool)); + assert!( + !config + .startup_warnings + .iter() + .any(|warning| warning.contains("Configured value for `features`")), + "{:?}", + config.startup_warnings + ); + + Ok(()) + } + + #[tokio::test] + async fn feature_requirements_normalize_runtime_feature_mutations() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + + let mut config = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .cloud_requirements(CloudRequirementsLoader::new(async { + Ok(Some(crate::config_loader::ConfigRequirementsToml { + feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([ + ("personality".to_string(), true), + ("shell_tool".to_string(), false), + ]), + }), + ..Default::default() + })) + })) + .build() + .await?; + + let mut requested = config.features.get().clone(); + requested + .disable(Feature::Personality) + .enable(Feature::ShellTool); + assert!(config.features.can_set(&requested).is_ok()); + config + .features + .set(requested) + .expect("managed feature mutations should normalize successfully"); + + assert!(config.features.enabled(Feature::Personality)); + assert!(!config.features.enabled(Feature::ShellTool)); + + Ok(()) + } + + #[tokio::test] + async fn feature_requirements_reject_legacy_aliases() { + let codex_home = TempDir::new().expect("tempdir"); + + let err = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .cloud_requirements(CloudRequirementsLoader::new(async { + Ok(Some(crate::config_loader::ConfigRequirementsToml { + feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([("collab".to_string(), true)]), + }), + ..Default::default() + })) + })) + .build() + .await + .expect_err("legacy aliases should be rejected"); + + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + assert!( + err.to_string() + .contains("use canonical feature key `multi_agent`"), + "{err}" + ); + } + #[test] fn experimental_realtime_ws_base_url_loads_from_config_toml() -> std::io::Result<()> { let cfg: ConfigToml = toml::from_str( diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/core/src/config/service.rs index da675d2389..10e0679e57 100644 --- a/codex-rs/core/src/config/service.rs +++ b/codex-rs/core/src/config/service.rs @@ -1,6 +1,9 @@ use super::ConfigToml; +use super::deserialize_config_toml_with_base; use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; +use crate::config::managed_features::validate_explicit_feature_settings_in_config_toml; +use crate::config::managed_features::validate_feature_requirements_in_config_toml; use crate::config_loader::CloudRequirementsLoader; use crate::config_loader::ConfigLayerEntry; use crate::config_loader::ConfigLayerStack; @@ -331,6 +334,35 @@ impl ConfigService { format!("Invalid configuration: {err}"), ) })?; + let user_config_toml = + deserialize_config_toml_with_base(user_config.clone(), &self.codex_home).map_err( + |err| { + ConfigServiceError::write( + ConfigWriteErrorCode::ConfigValidationError, + format!("Invalid configuration: {err}"), + ) + }, + )?; + validate_explicit_feature_settings_in_config_toml( + &user_config_toml, + layers.requirements().feature_requirements.as_ref(), + ) + .map_err(|err| { + ConfigServiceError::write( + ConfigWriteErrorCode::ConfigValidationError, + format!("Invalid configuration: {err}"), + ) + })?; + validate_feature_requirements_in_config_toml( + &user_config_toml, + layers.requirements().feature_requirements.as_ref(), + ) + .map_err(|err| { + ConfigServiceError::write( + ConfigWriteErrorCode::ConfigValidationError, + format!("Invalid configuration: {err}"), + ) + })?; let updated_layers = layers.with_user_config(&provided_path, user_config.clone()); let effective = updated_layers.effective_config(); @@ -706,6 +738,7 @@ mod tests { use codex_app_server_protocol::AskForApproval; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; + use std::collections::BTreeMap; use tempfile::tempdir; #[test] @@ -1088,6 +1121,108 @@ personality = true assert_eq!(contents.trim(), "model = \"user\""); } + #[tokio::test] + async fn write_value_rejects_feature_requirement_conflict() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); + + let service = ConfigService::new( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides { + managed_config_path: None, + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + macos_managed_config_requirements_base64: None, + }, + CloudRequirementsLoader::new(async { + Ok(Some(ConfigRequirementsToml { + feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([("personality".to_string(), true)]), + }), + ..Default::default() + })) + }), + ); + + let error = service + .write_value(ConfigValueWriteParams { + file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), + key_path: "features.personality".to_string(), + value: serde_json::json!(false), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect_err("conflicting feature write should fail"); + + assert_eq!( + error.write_error_code(), + Some(ConfigWriteErrorCode::ConfigValidationError) + ); + assert!( + error + .to_string() + .contains("invalid value for `features`: `features.personality=false`"), + "{error}" + ); + assert_eq!( + std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).unwrap(), + "" + ); + } + + #[tokio::test] + async fn write_value_rejects_profile_feature_requirement_conflict() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); + + let service = ConfigService::new( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides { + managed_config_path: None, + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + macos_managed_config_requirements_base64: None, + }, + CloudRequirementsLoader::new(async { + Ok(Some(ConfigRequirementsToml { + feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([("personality".to_string(), true)]), + }), + ..Default::default() + })) + }), + ); + + let error = service + .write_value(ConfigValueWriteParams { + file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), + key_path: "profiles.enterprise.features.personality".to_string(), + value: serde_json::json!(false), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect_err("conflicting profile feature write should fail"); + + assert_eq!( + error.write_error_code(), + Some(ConfigWriteErrorCode::ConfigValidationError) + ); + assert!( + error.to_string().contains( + "invalid value for `features`: `profiles.enterprise.features.personality=false`" + ), + "{error}" + ); + assert_eq!( + std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).unwrap(), + "" + ); + } + #[tokio::test] async fn read_reports_managed_overrides_user_and_session_flags() { let tmp = tempdir().expect("tempdir"); diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index 63b3be48e9..b94bf81d08 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -34,6 +34,7 @@ pub use codex_config::ConfigLoadError; pub use codex_config::ConfigRequirements; pub use codex_config::ConfigRequirementsToml; pub use codex_config::ConstrainedWithSource; +pub use codex_config::FeatureRequirementsToml; pub use codex_config::LoaderOverrides; pub use codex_config::McpServerIdentity; pub use codex_config::McpServerRequirement; diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index 983acbe8d1..fb8de08615 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -23,6 +23,7 @@ use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::SandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; +use std::collections::BTreeMap; use std::collections::HashMap; use std::path::Path; use tempfile::tempdir; @@ -494,6 +495,9 @@ async fn load_requirements_toml_produces_expected_constraints() -> anyhow::Resul allowed_approval_policies = ["never", "on-request"] allowed_web_search_modes = ["cached"] enforce_residency = "us" + +[features] +personality = true "#, ) .await?; @@ -515,6 +519,15 @@ enforce_residency = "us" .cloned(), Some(vec![crate::config_loader::WebSearchModeRequirement::Cached]) ); + assert_eq!( + config_requirements_toml + .feature_requirements + .as_ref() + .map(|requirements| requirements.value.clone()), + Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([("personality".to_string(), true)]), + }) + ); let config_requirements: ConfigRequirements = config_requirements_toml.try_into()?; assert_eq!( config_requirements.approval_policy.value(), @@ -552,6 +565,15 @@ enforce_residency = "us" config_requirements.enforce_residency.value(), Some(crate::config_loader::ResidencyRequirement::Us) ); + assert_eq!( + config_requirements + .feature_requirements + .as_ref() + .map(|requirements| requirements.value.clone()), + Some(crate::config_loader::FeatureRequirementsToml { + entries: BTreeMap::from([("personality".to_string(), true)]), + }) + ); Ok(()) } @@ -581,6 +603,7 @@ allowed_approval_policies = ["on-request"] allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -629,6 +652,7 @@ allowed_approval_policies = ["on-request"] allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, @@ -666,6 +690,7 @@ async fn load_config_layers_includes_cloud_requirements() -> anyhow::Result<()> allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 30c38e835f..ef6712fd00 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -245,6 +245,14 @@ impl Features { self } + pub fn set_enabled(&mut self, f: Feature, enabled: bool) -> &mut Self { + if enabled { + self.enable(f) + } else { + self.disable(f) + } + } + pub fn record_legacy_usage_force(&mut self, alias: &str, feature: Feature) { let (summary, details) = legacy_usage_notice(alias, feature); self.legacy_usages.insert(LegacyFeatureUsage { @@ -353,10 +361,7 @@ impl Features { } overrides.apply(&mut features); - if features.enabled(Feature::JsReplToolsOnly) && !features.enabled(Feature::JsRepl) { - tracing::warn!("js_repl_tools_only requires js_repl; disabling js_repl_tools_only"); - features.disable(Feature::JsReplToolsOnly); - } + features.normalize_dependencies(); features } @@ -364,6 +369,13 @@ impl Features { pub fn enabled_features(&self) -> Vec { self.enabled.iter().copied().collect() } + + pub(crate) fn normalize_dependencies(&mut self) { + if self.enabled(Feature::JsReplToolsOnly) && !self.enabled(Feature::JsRepl) { + tracing::warn!("js_repl_tools_only requires js_repl; disabling js_repl_tools_only"); + self.disable(Feature::JsReplToolsOnly); + } + } } fn legacy_usage_notice(alias: &str, feature: Feature) -> (String, Option) { @@ -404,7 +416,7 @@ fn web_search_details() -> &'static str { } /// Keys accepted in `[features]` tables. -fn feature_for_key(key: &str) -> Option { +pub(crate) fn feature_for_key(key: &str) -> Option { for spec in FEATURES { if spec.key == key { return Some(spec.id); @@ -413,6 +425,13 @@ fn feature_for_key(key: &str) -> Option { legacy::feature_for_key(key) } +pub(crate) fn canonical_feature_for_key(key: &str) -> Option { + FEATURES + .iter() + .find(|spec| spec.key == key) + .map(|spec| spec.id) +} + /// Returns `true` if the provided string matches a known feature toggle key. pub fn is_known_feature_key(key: &str) -> bool { feature_for_key(key).is_some() diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index 91a7f74db9..ac7dd2acaf 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -566,7 +566,10 @@ mod tests { fn codex_apps_mcp_url_uses_openai_connectors_gateway_when_feature_is_enabled() { let mut config = crate::config::test_config(); config.chatgpt_base_url = "https://chatgpt.com".to_string(); - config.features.enable(Feature::AppsMcpGateway); + config + .features + .enable(Feature::AppsMcpGateway) + .expect("test config should allow apps gateway"); assert_eq!( codex_apps_mcp_url(&config), @@ -582,7 +585,10 @@ mod tests { let mut servers = with_codex_apps_mcp(HashMap::new(), false, None, &config); assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME)); - config.features.enable(Feature::Apps); + config + .features + .enable(Feature::Apps) + .expect("test config should allow apps"); servers = with_codex_apps_mcp(servers, true, None, &config); let server = servers @@ -595,7 +601,10 @@ mod tests { assert_eq!(url, "https://chatgpt.com/backend-api/wham/apps"); - config.features.enable(Feature::AppsMcpGateway); + config + .features + .enable(Feature::AppsMcpGateway) + .expect("test config should allow apps gateway"); servers = with_codex_apps_mcp(servers, true, None, &config); let server = servers .get(CODEX_APPS_MCP_SERVER_NAME) diff --git a/codex-rs/core/src/memories/phase2.rs b/codex-rs/core/src/memories/phase2.rs index ff13e4f64c..c8575035e5 100644 --- a/codex-rs/core/src/memories/phase2.rs +++ b/codex-rs/core/src/memories/phase2.rs @@ -266,7 +266,7 @@ mod agent { // Approval policy agent_config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never); // Consolidation runs as an internal sub-agent and must not recursively delegate. - agent_config.features.disable(Feature::Collab); + let _ = agent_config.features.disable(Feature::Collab); // Sandbox policy let mut writable_roots = Vec::new(); diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index debe39c2ad..2cf884c593 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -475,7 +475,9 @@ mod tests { async fn js_repl_instructions_are_appended_when_enabled() { let tmp = tempfile::tempdir().expect("tempdir"); let mut cfg = make_config(&tmp, 4096, None).await; - cfg.features.enable(Feature::JsRepl); + cfg.features + .enable(Feature::JsRepl) + .expect("test config should allow js_repl"); let res = get_user_instructions(&cfg, None) .await @@ -488,9 +490,13 @@ mod tests { async fn js_repl_tools_only_instructions_are_feature_gated() { let tmp = tempfile::tempdir().expect("tempdir"); let mut cfg = make_config(&tmp, 4096, None).await; - cfg.features + let mut features = cfg.features.get().clone(); + features .enable(Feature::JsRepl) .enable(Feature::JsReplToolsOnly); + cfg.features + .set(features) + .expect("test config should allow js_repl tool restrictions"); let res = get_user_instructions(&cfg, None) .await @@ -503,9 +509,13 @@ mod tests { async fn js_repl_original_resolution_guidance_is_feature_gated() { let tmp = tempfile::tempdir().expect("tempdir"); let mut cfg = make_config(&tmp, 4096, None).await; - cfg.features + let mut features = cfg.features.get().clone(); + features .enable(Feature::JsRepl) .enable(Feature::ImageDetailOriginal); + cfg.features + .set(features) + .expect("test config should allow js_repl image detail settings"); let res = get_user_instructions(&cfg, None) .await @@ -730,7 +740,9 @@ mod tests { async fn apps_feature_does_not_emit_user_instructions_by_itself() { let tmp = tempfile::tempdir().expect("tempdir"); let mut cfg = make_config(&tmp, 4096, None).await; - cfg.features.enable(Feature::Apps); + cfg.features + .enable(Feature::Apps) + .expect("test config should allow apps"); let res = get_user_instructions(&cfg, None).await; assert_eq!(res, None); @@ -742,7 +754,9 @@ mod tests { fs::write(tmp.path().join("AGENTS.md"), "base doc").unwrap(); let mut cfg = make_config(&tmp, 4096, None).await; - cfg.features.enable(Feature::Apps); + cfg.features + .enable(Feature::Apps) + .expect("test config should allow apps"); let res = get_user_instructions(&cfg, None) .await diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index 7602b75c6a..23edc57ae0 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -1207,7 +1207,10 @@ mod tests { .codex_home(home.path().to_path_buf()) .build() .await?; - config.features.disable(Feature::Sqlite); + config + .features + .disable(Feature::Sqlite) + .expect("test config should allow sqlite to be disabled"); let newest = write_session_file(home.path(), "2025-01-03T12-00-00", Uuid::from_u128(9001))?; let middle = write_session_file(home.path(), "2025-01-02T12-00-00", Uuid::from_u128(9002))?; @@ -1253,7 +1256,10 @@ mod tests { .codex_home(home.path().to_path_buf()) .build() .await?; - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow sqlite"); let uuid = Uuid::from_u128(9010); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); @@ -1319,7 +1325,10 @@ mod tests { .codex_home(home.path().to_path_buf()) .build() .await?; - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow sqlite"); let uuid = Uuid::from_u128(9011); let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id"); diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index dcb3b4cdc8..4192236b48 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -95,7 +95,7 @@ async fn start_review_conversation( { panic!("by construction Constrained must always support Disabled: {err}"); } - sub_agent_config.features.disable(Feature::Collab); + let _ = sub_agent_config.features.disable(Feature::Collab); // Set explicit review rubric for the sub-agent sub_agent_config.base_instructions = Some(crate::REVIEW_PROMPT.to_string()); diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index c179fcef7a..20b001315b 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -973,7 +973,7 @@ fn apply_spawn_agent_runtime_overrides( fn apply_spawn_agent_overrides(config: &mut Config, child_depth: i32) { if child_depth >= config.agent_max_depth { - config.features.disable(Feature::Collab); + let _ = config.features.disable(Feature::Collab); } } diff --git a/codex-rs/core/src/tools/js_repl/mod.rs b/codex-rs/core/src/tools/js_repl/mod.rs index a8a9123073..86463e1b95 100644 --- a/codex-rs/core/src/tools/js_repl/mod.rs +++ b/codex-rs/core/src/tools/js_repl/mod.rs @@ -1989,7 +1989,8 @@ mod tests { let (_session, mut turn) = make_session_and_context().await; Arc::make_mut(&mut turn.config) .features - .enable(Feature::ImageDetailOriginal); + .enable(Feature::ImageDetailOriginal) + .expect("test config should allow feature update"); turn.model_info.supports_image_detail_original = true; let content_item = diff --git a/codex-rs/core/tests/common/BUILD.bazel b/codex-rs/core/tests/common/BUILD.bazel index abfb79624d..aec0c17817 100644 --- a/codex-rs/core/tests/common/BUILD.bazel +++ b/codex-rs/core/tests/common/BUILD.bazel @@ -4,4 +4,7 @@ codex_rust_crate( name = "common", crate_name = "core_test_support", crate_srcs = glob(["*.rs"]), + lib_data_extra = [ + "//codex-rs/core:model_availability_nux_fixtures", + ], ) diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 392d4d354f..a79838df00 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -3,6 +3,7 @@ use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use anyhow::Context; use anyhow::Result; use codex_core::CodexAuth; use codex_core::CodexThread; @@ -11,12 +12,15 @@ use codex_core::ThreadManager; use codex_core::built_in_model_providers; use codex_core::config::Config; use codex_core::features::Feature; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_protocol::config_types::ServiceTier; +use codex_protocol::openai_models::ModelsResponse; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionConfiguredEvent; +use codex_protocol::protocol::SessionSource; use codex_protocol::user_input::UserInput; use serde_json::Value; use tempfile::TempDir; @@ -28,11 +32,13 @@ use crate::responses::output_value_to_text; use crate::responses::start_mock_server; use crate::streaming_sse::StreamingSseServer; use crate::wait_for_event; +use crate::wait_for_event_match; use wiremock::Match; use wiremock::matchers::path_regex; type ConfigMutator = dyn FnOnce(&mut Config) + Send; type PreBuildHook = dyn FnOnce(&Path) + Send + 'static; +const TEST_MODEL_WITH_EXPERIMENTAL_TOOLS: &str = "test-gpt-5.1-codex"; /// A collection of different ways the model can output an apply_patch call #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -128,7 +134,10 @@ impl TestCodexBuilder { self.config_mutators.push(Box::new(move |config| { config.model_provider.base_url = Some(base_url_clone); config.experimental_realtime_ws_model = Some("realtime-test-model".to_string()); - config.features.enable(Feature::ResponsesWebsockets); + config + .features + .enable(Feature::ResponsesWebsockets) + .expect("test config should allow feature update"); })); self.build_with_home_and_base_url(base_url, home, None) .await @@ -172,11 +181,21 @@ impl TestCodexBuilder { resume_from: Option, ) -> anyhow::Result { let auth = self.auth.clone(); - let thread_manager = codex_core::test_support::thread_manager_with_models_provider_and_home( - auth.clone(), - config.model_provider.clone(), - config.codex_home.clone(), - ); + let thread_manager = if let Some(model_catalog) = config.model_catalog.clone() { + ThreadManager::new( + config.codex_home.clone(), + codex_core::test_support::auth_manager_from_auth(auth.clone()), + SessionSource::Exec, + Some(model_catalog), + CollaborationModesConfig::default(), + ) + } else { + codex_core::test_support::thread_manager_with_models_provider_and_home( + auth.clone(), + config.model_provider.clone(), + config.codex_home.clone(), + ) + }; let thread_manager = Arc::new(thread_manager); let new_conversation = match resume_from { @@ -232,17 +251,56 @@ impl TestCodexBuilder { for mutator in mutators { mutator(&mut config); } + ensure_test_model_catalog(&mut config)?; if config.include_apply_patch_tool { - config.features.enable(Feature::ApplyPatchFreeform); + config.features.enable(Feature::ApplyPatchFreeform)?; } else { - config.features.disable(Feature::ApplyPatchFreeform); + config.features.disable(Feature::ApplyPatchFreeform)?; } Ok((config, cwd)) } } +fn ensure_test_model_catalog(config: &mut Config) -> Result<()> { + if config.model.as_deref() != Some(TEST_MODEL_WITH_EXPERIMENTAL_TOOLS) + || config.model_catalog.is_some() + { + return Ok(()); + } + + let bundled_models_path = codex_utils_cargo_bin::find_resource!("../../models.json") + .context("bundled models.json")?; + let bundled_models_contents = + std::fs::read_to_string(&bundled_models_path).with_context(|| { + format!( + "read bundled models.json from {}", + bundled_models_path.display() + ) + })?; + let bundled_models: ModelsResponse = + serde_json::from_str(&bundled_models_contents).context("parse bundled models.json")?; + let mut model = bundled_models + .models + .iter() + .find(|candidate| candidate.slug == "gpt-5.1-codex") + .cloned() + .unwrap_or_else(|| panic!("missing bundled model gpt-5.1-codex")); + model.slug = TEST_MODEL_WITH_EXPERIMENTAL_TOOLS.to_string(); + model.display_name = TEST_MODEL_WITH_EXPERIMENTAL_TOOLS.to_string(); + model.experimental_supported_tools = vec![ + "test_sync_tool".to_string(), + "read_file".to_string(), + "grep_files".to_string(), + "list_dir".to_string(), + ]; + config.model_catalog = Some(ModelsResponse { + models: vec![model], + }); + Ok(()) +} + pub struct TestCodex { pub home: Arc, pub cwd: Arc, @@ -334,8 +392,14 @@ impl TestCodex { }) .await?; - wait_for_event(&self.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) + let turn_id = wait_for_event_match(&self.codex, |event| match event { + EventMsg::TurnStarted(event) => Some(event.turn_id.clone()), + _ => None, + }) + .await; + wait_for_event(&self.codex, |event| match event { + EventMsg::TurnComplete(event) => event.turn_id == turn_id, + _ => false, }) .await; Ok(()) diff --git a/codex-rs/core/tests/common/zsh_fork.rs b/codex-rs/core/tests/common/zsh_fork.rs index 22ae69303e..fbc46421d9 100644 --- a/codex-rs/core/tests/common/zsh_fork.rs +++ b/codex-rs/core/tests/common/zsh_fork.rs @@ -24,8 +24,14 @@ impl ZshForkRuntime { approval_policy: AskForApproval, sandbox_policy: SandboxPolicy, ) { - config.features.enable(Feature::ShellTool); - config.features.enable(Feature::ShellZshFork); + config + .features + .enable(Feature::ShellTool) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::ShellZshFork) + .expect("test config should allow feature update"); config.zsh_path = Some(self.zsh_path.clone()); config.main_execve_wrapper_exe = Some(self.main_execve_wrapper_exe.clone()); config.permissions.allow_login_shell = false; diff --git a/codex-rs/core/tests/suite/agent_jobs.rs b/codex-rs/core/tests/suite/agent_jobs.rs index 5708f400ad..190302a3e1 100644 --- a/codex-rs/core/tests/suite/agent_jobs.rs +++ b/codex-rs/core/tests/suite/agent_jobs.rs @@ -222,8 +222,14 @@ fn parse_simple_csv_line(line: &str) -> Vec { async fn report_agent_job_result_rejects_wrong_thread() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Collab); - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Collab) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -282,8 +288,14 @@ async fn report_agent_job_result_rejects_wrong_thread() -> Result<()> { async fn spawn_agents_on_csv_runs_and_exports() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Collab); - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Collab) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -319,8 +331,14 @@ async fn spawn_agents_on_csv_dedupes_item_ids() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Collab); - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Collab) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -371,8 +389,14 @@ async fn spawn_agents_on_csv_dedupes_item_ids() -> Result<()> { async fn spawn_agents_on_csv_stop_halts_future_items() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Collab); - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Collab) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/agent_websocket.rs b/codex-rs/core/tests/suite/agent_websocket.rs index 0db3cf61ad..5e81452a49 100644 --- a/codex-rs/core/tests/suite/agent_websocket.rs +++ b/codex-rs/core/tests/suite/agent_websocket.rs @@ -183,7 +183,10 @@ async fn websocket_v2_test_codex_shell_chain() -> Result<()> { .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ResponsesWebsocketsV2); + config + .features + .enable(Feature::ResponsesWebsocketsV2) + .expect("test config should allow feature update"); }); let test = builder.build_with_websocket_server(&server).await?; @@ -262,7 +265,10 @@ async fn websocket_v2_first_turn_uses_updated_fast_tier_after_startup_prewarm() .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ResponsesWebsocketsV2); + config + .features + .enable(Feature::ResponsesWebsocketsV2) + .expect("test config should allow feature update"); }); let test = builder.build_with_websocket_server(&server).await?; @@ -311,7 +317,10 @@ async fn websocket_v2_first_turn_drops_fast_tier_after_startup_prewarm() -> Resu .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ResponsesWebsocketsV2); + config + .features + .enable(Feature::ResponsesWebsocketsV2) + .expect("test config should allow feature update"); config.service_tier = Some(ServiceTier::Fast); }); let test = builder.build_with_websocket_server(&server).await?; @@ -365,7 +374,10 @@ async fn websocket_v2_next_turn_uses_updated_service_tier() -> Result<()> { .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ResponsesWebsocketsV2); + config + .features + .enable(Feature::ResponsesWebsocketsV2) + .expect("test config should allow feature update"); }); let test = builder.build_with_websocket_server(&server).await?; diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index 112b1c1bed..28fdd0b83e 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -674,7 +674,10 @@ async fn apply_patch_cli_verification_failure_has_no_side_effects( let harness = apply_patch_harness_with(|builder| { builder.with_config(|config| { - config.features.enable(Feature::ApplyPatchFreeform); + config + .features + .enable(Feature::ApplyPatchFreeform) + .expect("test config should allow feature update"); }) }) .await?; diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 3f82139fe3..9ca159965f 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -1598,7 +1598,10 @@ async fn run_scenario(scenario: &ScenarioSpec) -> Result<()> { config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy.clone()); for feature in features { - config.features.enable(feature); + config + .features + .enable(feature) + .expect("test config should allow feature update"); } }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index d6fde7e691..3ac9a72c3c 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -939,8 +939,14 @@ async fn includes_apps_guidance_as_developer_message_when_enabled() { let mut builder = test_codex() .with_auth(CodexAuth::from_api_key("Test API Key")) .with_config(move |config| { - config.features.enable(Feature::Apps); - config.features.disable(Feature::AppsMcpGateway); + config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); + config + .features + .disable(Feature::AppsMcpGateway) + .expect("test config should allow feature update"); config.chatgpt_base_url = apps_base_url; }); let codex = builder diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index b2098c039c..4896a0fa1c 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -1481,15 +1481,27 @@ async fn websocket_harness_with_options( let mut config = load_default_config_for_test(&codex_home).await; config.model = Some(MODEL.to_string()); if websocket_enabled { - config.features.enable(Feature::ResponsesWebsockets); + config + .features + .enable(Feature::ResponsesWebsockets) + .expect("test config should allow feature update"); } else { - config.features.disable(Feature::ResponsesWebsockets); + config + .features + .disable(Feature::ResponsesWebsockets) + .expect("test config should allow feature update"); } if runtime_metrics_enabled { - config.features.enable(Feature::RuntimeMetrics); + config + .features + .enable(Feature::RuntimeMetrics) + .expect("test config should allow feature update"); } if websocket_v2_enabled { - config.features.enable(Feature::ResponsesWebsocketsV2); + config + .features + .enable(Feature::ResponsesWebsocketsV2) + .expect("test config should allow feature update"); } let config = Arc::new(config); let mut model_info = codex_core::test_support::construct_model_info_offline(MODEL, &config); diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index ac6ffc915d..bb34789499 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -3112,7 +3112,7 @@ async fn snapshot_request_shape_pre_turn_compaction_strips_incoming_model_switch .with_config(move |config| { config.model_provider = model_provider; set_test_compact_prompt(config); - config + let _ = config .features .enable(codex_core::features::Feature::RemoteModels); config.model_auto_compact_token_limit = Some(200); diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index 5b3f409125..fe536077a3 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -10,6 +10,7 @@ use super::compact::COMPACT_WARNING_MESSAGE; use super::compact::FIRST_REPLY; use super::compact::SUMMARY_TEXT; +use anyhow::Result; use codex_core::CodexThread; use codex_core::ThreadManager; use codex_core::compact::SUMMARIZATION_PROMPT; @@ -291,13 +292,36 @@ async fn compact_resume_and_fork_preserve_model_history_view() { assert_eq!(requests.len(), 5); } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[test] /// Scenario: after the forked branch is compacted, resuming again should reuse /// the compacted history and only append the new user message. -async fn compact_resume_after_second_compaction_preserves_history() { +fn compact_resume_after_second_compaction_preserves_history() -> Result<()> { + const TEST_STACK_SIZE_BYTES: usize = 8 * 1024 * 1024; + + let handle = std::thread::Builder::new() + .name("compact_resume_after_second_compaction_preserves_history".to_string()) + .stack_size(TEST_STACK_SIZE_BYTES) + .spawn(|| -> Result<()> { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_stack_size(TEST_STACK_SIZE_BYTES) + .enable_all() + .build()?; + runtime.block_on(compact_resume_after_second_compaction_preserves_history_impl()) + })?; + + match handle.join() { + Ok(result) => result, + Err(_) => Err(anyhow::anyhow!( + "compact_resume_after_second_compaction_preserves_history thread panicked" + )), + } +} + +async fn compact_resume_after_second_compaction_preserves_history_impl() -> Result<()> { if network_disabled() { println!("Skipping test because network is disabled in this sandbox"); - return; + return Ok(()); } // 1. Arrange mocked SSE responses for the initial flow plus the second compact. @@ -402,6 +426,7 @@ async fn compact_resume_after_second_compaction_preserves_history() { assert_eq!(chunk, seeded_user_prefix); } } + Ok(()) } fn normalize_line_endings(value: &mut Value) { diff --git a/codex-rs/core/tests/suite/deprecation_notice.rs b/codex-rs/core/tests/suite/deprecation_notice.rs index 2a7563bea1..e3cc890ea2 100644 --- a/codex-rs/core/tests/suite/deprecation_notice.rs +++ b/codex-rs/core/tests/suite/deprecation_notice.rs @@ -26,10 +26,14 @@ async fn emits_deprecation_notice_for_legacy_feature_flag() -> anyhow::Result<() let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + let mut features = config.features.get().clone(); + features.enable(Feature::UnifiedExec); + features + .record_legacy_usage_force("use_experimental_unified_exec_tool", Feature::UnifiedExec); config .features - .record_legacy_usage_force("use_experimental_unified_exec_tool", Feature::UnifiedExec); + .set(features) + .expect("test config should allow managed feature metadata updates"); config.use_experimental_unified_exec_tool = true; }); @@ -122,7 +126,12 @@ async fn emits_deprecation_notice_for_web_search_feature_flag_values() -> anyhow let mut builder = test_codex().with_config(move |config| { let mut entries = BTreeMap::new(); entries.insert("web_search_request".to_string(), enabled); - config.features.apply_map(&entries); + let mut features = config.features.get().clone(); + features.apply_map(&entries); + config + .features + .set(features) + .expect("test config should allow managed feature map updates"); }); let TestCodex { codex, .. } = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/exec_policy.rs b/codex-rs/core/tests/suite/exec_policy.rs index bf8416e97d..5b34b20c71 100644 --- a/codex-rs/core/tests/suite/exec_policy.rs +++ b/codex-rs/core/tests/suite/exec_policy.rs @@ -167,7 +167,10 @@ async fn execpolicy_blocks_shell_invocation() -> Result<()> { async fn shell_command_empty_script_with_collaboration_mode_does_not_panic() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_model("gpt-5").with_config(|config| { - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; let call_id = "shell-empty-script-collab"; @@ -219,8 +222,14 @@ async fn shell_command_empty_script_with_collaboration_mode_does_not_panic() -> async fn unified_exec_empty_script_with_collaboration_mode_does_not_panic() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_model("gpt-5").with_config(|config| { - config.features.enable(Feature::UnifiedExec); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; let call_id = "unified-exec-empty-script-collab"; @@ -272,7 +281,10 @@ async fn unified_exec_empty_script_with_collaboration_mode_does_not_panic() -> R async fn shell_command_whitespace_script_with_collaboration_mode_does_not_panic() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_model("gpt-5").with_config(|config| { - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; let call_id = "shell-whitespace-script-collab"; @@ -324,8 +336,14 @@ async fn shell_command_whitespace_script_with_collaboration_mode_does_not_panic( async fn unified_exec_whitespace_script_with_collaboration_mode_does_not_panic() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_model("gpt-5").with_config(|config| { - config.features.enable(Feature::UnifiedExec); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; let call_id = "unified-exec-whitespace-script-collab"; diff --git a/codex-rs/core/tests/suite/hierarchical_agents.rs b/codex-rs/core/tests/suite/hierarchical_agents.rs index 5f1f84340d..9eb9015950 100644 --- a/codex-rs/core/tests/suite/hierarchical_agents.rs +++ b/codex-rs/core/tests/suite/hierarchical_agents.rs @@ -19,7 +19,10 @@ async fn hierarchical_agents_appends_to_project_doc_in_user_instructions() { .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ChildAgentsMd); + config + .features + .enable(Feature::ChildAgentsMd) + .expect("test config should allow feature update"); std::fs::write(config.cwd.join("AGENTS.md"), "be nice").expect("write AGENTS.md"); }); let test = builder.build(&server).await.expect("build test codex"); @@ -58,7 +61,10 @@ async fn hierarchical_agents_emits_when_no_project_doc() { .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ChildAgentsMd); + config + .features + .enable(Feature::ChildAgentsMd) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await.expect("build test codex"); diff --git a/codex-rs/core/tests/suite/js_repl.rs b/codex-rs/core/tests/suite/js_repl.rs index 31dbe6e60a..c6175b4444 100644 --- a/codex-rs/core/tests/suite/js_repl.rs +++ b/codex-rs/core/tests/suite/js_repl.rs @@ -76,7 +76,10 @@ async fn run_js_repl_turn( calls: &[(&str, &str)], ) -> Result { let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::JsRepl); + config + .features + .enable(Feature::JsRepl) + .expect("test config should allow feature update"); }); let test = builder.build(server).await?; @@ -112,7 +115,10 @@ async fn js_repl_is_not_advertised_when_startup_node_is_incompatible() -> Result let old_node = write_too_old_node_script(temp.path())?; let mut builder = test_codex().with_config(move |config| { - config.features.enable(Feature::JsRepl); + config + .features + .enable(Feature::JsRepl) + .expect("test config should allow feature update"); config.js_repl_node_path = Some(old_node); }); let test = builder.build(&server).await?; @@ -164,7 +170,10 @@ async fn js_repl_persists_top_level_bindings_and_supports_tla() -> Result<()> { let server = responses::start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::JsRepl); + config + .features + .enable(Feature::JsRepl) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/memories.rs b/codex-rs/core/tests/suite/memories.rs index 80e2d6ff6d..7fb4fe0bb2 100644 --- a/codex-rs/core/tests/suite/memories.rs +++ b/codex-rs/core/tests/suite/memories.rs @@ -166,8 +166,14 @@ async fn web_search_pollution_moves_selected_thread_into_removed_phase2_inputs() let db = init_state_db(&home).await?; let mut initial_builder = test_codex().with_home(home.clone()).with_config(|config| { - config.features.enable(Feature::Sqlite); - config.features.enable(Feature::MemoryTool); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::MemoryTool) + .expect("test config should allow feature update"); config.memories.max_raw_memories_for_consolidation = 1; config.memories.no_memories_if_mcp_or_web_search = true; }); @@ -232,8 +238,14 @@ async fn web_search_pollution_moves_selected_thread_into_removed_phase2_inputs() .await; let mut resumed_builder = test_codex().with_home(home.clone()).with_config(|config| { - config.features.enable(Feature::Sqlite); - config.features.enable(Feature::MemoryTool); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::MemoryTool) + .expect("test config should allow feature update"); config.memories.max_raw_memories_for_consolidation = 1; config.memories.no_memories_if_mcp_or_web_search = true; }); @@ -310,9 +322,16 @@ async fn web_search_pollution_moves_selected_thread_into_removed_phase2_inputs() } async fn build_test_codex(server: &wiremock::MockServer, home: Arc) -> Result { + #[allow(clippy::expect_used)] let mut builder = test_codex().with_home(home).with_config(|config| { - config.features.enable(Feature::Sqlite); - config.features.enable(Feature::MemoryTool); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::MemoryTool) + .expect("test config should allow feature update"); config.memories.max_raw_memories_for_consolidation = 1; }); builder.build(server).await diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index e8fbcc851c..df02d5e258 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -133,7 +133,10 @@ async fn model_and_personality_change_only_appends_model_instructions() -> Resul let mut builder = test_codex() .with_model("gpt-5.2-codex") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; let next_model = "exp-codex-personality"; diff --git a/codex-rs/core/tests/suite/model_visible_layout.rs b/codex-rs/core/tests/suite/model_visible_layout.rs index a6a044f3f6..b02e3ae156 100644 --- a/codex-rs/core/tests/suite/model_visible_layout.rs +++ b/codex-rs/core/tests/suite/model_visible_layout.rs @@ -102,7 +102,10 @@ async fn snapshot_model_visible_layout_turn_overrides() -> Result<()> { let mut builder = test_codex() .with_model("gpt-5.2-codex") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::Pragmatic); }); let test = builder.build(&server).await?; @@ -332,7 +335,10 @@ async fn snapshot_model_visible_layout_resume_with_personality_change() -> Resul let mut resume_builder = test_codex().with_config(|config| { config.model = Some("gpt-5.2-codex".to_string()); - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::Pragmatic); }); let resumed = resume_builder.resume(&server, home, rollout_path).await?; diff --git a/codex-rs/core/tests/suite/otel.rs b/codex-rs/core/tests/suite/otel.rs index 03f87aec14..2463b98de7 100644 --- a/codex-rs/core/tests/suite/otel.rs +++ b/codex-rs/core/tests/suite/otel.rs @@ -176,7 +176,10 @@ async fn process_sse_emits_failed_event_on_parse_error() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -217,7 +220,10 @@ async fn process_sse_records_failed_event_when_stream_closes_without_completed() let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -278,7 +284,10 @@ async fn process_sse_failed_event_records_response_error_message() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -337,7 +346,10 @@ async fn process_sse_failed_event_logs_parse_error() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -383,7 +395,10 @@ async fn process_sse_failed_event_logs_missing_error() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -438,7 +453,10 @@ async fn process_sse_failed_event_logs_response_completed_parse_error() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -559,7 +577,10 @@ async fn handle_responses_span_records_response_kind_and_tool_name() { let TestCodex { codex, .. } = test_codex() .with_config(|config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -625,7 +646,10 @@ async fn record_responses_sets_span_fields_for_response_events() { let TestCodex { codex, .. } = test_codex() .with_config(|config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -706,7 +730,10 @@ async fn handle_response_item_records_tool_result_for_custom_tool_call() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -776,7 +803,10 @@ async fn handle_response_item_records_tool_result_for_function_call() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -856,7 +886,10 @@ async fn handle_response_item_records_tool_result_for_local_shell_missing_ids() let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await @@ -920,7 +953,10 @@ async fn handle_response_item_records_tool_result_for_local_shell_call() { let TestCodex { codex, .. } = test_codex() .with_config(move |config| { - config.features.disable(Feature::GhostCommit); + config + .features + .disable(Feature::GhostCommit) + .expect("test config should allow feature update"); }) .build(&server) .await diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index f3a1f2e4db..548c09ba45 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -44,7 +44,10 @@ const LOCAL_PRAGMATIC_TEMPLATE: &str = "You are a deeply pragmatic, effective so async fn personality_does_not_mutate_base_instructions_without_template() { let codex_home = TempDir::new().expect("create temp dir"); let mut config = load_default_config_for_test(&codex_home).await; - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::Friendly); let model_info = codex_core::test_support::construct_model_info_offline("gpt-5.1", &config); @@ -58,7 +61,10 @@ async fn personality_does_not_mutate_base_instructions_without_template() { async fn base_instructions_override_disables_personality_template() { let codex_home = TempDir::new().expect("create temp dir"); let mut config = load_default_config_for_test(&codex_home).await; - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::Friendly); config.base_instructions = Some("override instructions".to_string()); @@ -81,7 +87,10 @@ async fn user_turn_personality_none_does_not_add_update_message() -> anyhow::Res let mut builder = test_codex() .with_model("gpt-5.2-codex") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -127,7 +136,10 @@ async fn config_personality_some_sets_instructions_template() -> anyhow::Result< let mut builder = test_codex() .with_model("gpt-5.2-codex") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::Friendly); }); let test = builder.build(&server).await?; @@ -181,7 +193,10 @@ async fn config_personality_none_sends_no_personality() -> anyhow::Result<()> { let mut builder = test_codex() .with_model("gpt-5.2-codex") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::None); }); let test = builder.build(&server).await?; @@ -242,7 +257,10 @@ async fn default_personality_is_pragmatic_without_config_toml() -> anyhow::Resul let mut builder = test_codex() .with_model("gpt-5.2-codex") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -290,7 +308,10 @@ async fn user_turn_personality_some_adds_update_message() -> anyhow::Result<()> let mut builder = test_codex() .with_model("exp-codex-personality") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -388,7 +409,10 @@ async fn user_turn_personality_same_value_does_not_add_update_message() -> anyho let mut builder = test_codex() .with_model("exp-codex-personality") .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::Pragmatic); }); let test = builder.build(&server).await?; @@ -472,7 +496,10 @@ async fn user_turn_personality_same_value_does_not_add_update_message() -> anyho async fn instructions_uses_base_if_feature_disabled() -> anyhow::Result<()> { let codex_home = TempDir::new().expect("create temp dir"); let mut config = load_default_config_for_test(&codex_home).await; - config.features.disable(Feature::Personality); + config + .features + .disable(Feature::Personality) + .expect("test config should allow feature update"); config.personality = Some(Personality::Friendly); let model_info = @@ -498,7 +525,10 @@ async fn user_turn_personality_skips_if_feature_disabled() -> anyhow::Result<()> let mut builder = test_codex() .with_model("exp-codex-personality") .with_config(|config| { - config.features.disable(Feature::Personality); + config + .features + .disable(Feature::Personality) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -642,7 +672,10 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow let mut builder = test_codex() .with_auth(codex_core::CodexAuth::create_dummy_chatgpt_auth_for_testing()) .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.model = Some(remote_slug.to_string()); config.personality = Some(Personality::Friendly); }); @@ -757,7 +790,10 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - let mut builder = test_codex() .with_auth(codex_core::CodexAuth::create_dummy_chatgpt_auth_for_testing()) .with_config(|config| { - config.features.enable(Feature::Personality); + config + .features + .enable(Feature::Personality) + .expect("test config should allow feature update"); config.model = Some("gpt-5.2-codex".to_string()); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index 12d81402c8..6850cb11ef 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -203,12 +203,19 @@ async fn plugin_apps_expose_tools_after_canonical_name_mention() -> Result<()> { let codex_home = Arc::new(TempDir::new()?); write_plugin_app_plugin(codex_home.as_ref()); + #[allow(clippy::expect_used)] let mut builder = test_codex() .with_home(codex_home) .with_auth(CodexAuth::from_api_key("Test API Key")) .with_config(move |config| { - config.features.enable(Feature::Apps); - config.features.disable(Feature::AppsMcpGateway); + config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); + config + .features + .disable(Feature::AppsMcpGateway) + .expect("test config should allow feature update"); config.chatgpt_base_url = apps_server.chatgpt_base_url; }); let codex = builder diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 0275f3b4b2..d8fd96ddfa 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -125,7 +125,10 @@ async fn prompt_tools_are_consistent_across_requests() -> anyhow::Result<()> { .web_search_mode .set(WebSearchMode::Cached) .expect("test web_search_mode should satisfy constraints"); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }) .build(&server) .await?; @@ -219,8 +222,14 @@ async fn gpt_5_tools_without_apply_patch_append_apply_patch_instructions() -> an let TestCodex { codex, .. } = test_codex() .with_config(|config| { config.user_instructions = Some("be consistent and helpful".to_string()); - config.features.disable(Feature::ApplyPatchFreeform); - config.features.enable(Feature::CollaborationModes); + config + .features + .disable(Feature::ApplyPatchFreeform) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); config.model = Some("gpt-5".to_string()); }) .build(&server) @@ -291,7 +300,10 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests let TestCodex { codex, config, .. } = test_codex() .with_config(|config| { config.user_instructions = Some("be consistent and helpful".to_string()); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }) .build(&server) .await?; @@ -379,7 +391,10 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> an let TestCodex { codex, .. } = test_codex() .with_config(|config| { config.user_instructions = Some("be consistent and helpful".to_string()); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }) .build(&server) .await?; @@ -643,7 +658,10 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res let TestCodex { codex, .. } = test_codex() .with_config(|config| { config.user_instructions = Some("be consistent and helpful".to_string()); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }) .build(&server) .await?; @@ -767,7 +785,10 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a } = test_codex() .with_config(|config| { config.user_instructions = Some("be consistent and helpful".to_string()); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }) .build(&server) .await?; @@ -888,7 +909,10 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu } = test_codex() .with_config(|config| { config.user_instructions = Some("be consistent and helpful".to_string()); - config.features.enable(Feature::CollaborationModes); + config + .features + .enable(Feature::CollaborationModes) + .expect("test config should allow feature update"); }) .build(&server) .await?; diff --git a/codex-rs/core/tests/suite/request_compression.rs b/codex-rs/core/tests/suite/request_compression.rs index 9942435048..7f8b996c08 100644 --- a/codex-rs/core/tests/suite/request_compression.rs +++ b/codex-rs/core/tests/suite/request_compression.rs @@ -30,7 +30,10 @@ async fn request_body_is_zstd_compressed_for_codex_backend_when_enabled() -> any let mut builder = test_codex() .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) .with_config(move |config| { - config.features.enable(Feature::EnableRequestCompression); + config + .features + .enable(Feature::EnableRequestCompression) + .expect("test config should allow feature update"); config.model_provider.base_url = Some(base_url); }); let codex = builder.build(&server).await?.codex; @@ -74,7 +77,10 @@ async fn request_body_is_not_compressed_for_api_key_auth_even_when_enabled() -> let base_url = format!("{}/backend-api/codex/v1", server.uri()); let mut builder = test_codex().with_config(move |config| { - config.features.enable(Feature::EnableRequestCompression); + config + .features + .enable(Feature::EnableRequestCompression) + .expect("test config should allow feature update"); config.model_provider.base_url = Some(base_url); }); let codex = builder.build(&server).await?.codex; diff --git a/codex-rs/core/tests/suite/request_permissions.rs b/codex-rs/core/tests/suite/request_permissions.rs index 6f898e8c03..6c495f3464 100644 --- a/codex-rs/core/tests/suite/request_permissions.rs +++ b/codex-rs/core/tests/suite/request_permissions.rs @@ -201,7 +201,10 @@ async fn with_additional_permissions_requires_approval_under_on_request() -> Res let mut builder = test_codex().with_config(move |config| { config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); - config.features.enable(Feature::RequestPermissions); + config + .features + .enable(Feature::RequestPermissions) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -280,7 +283,10 @@ async fn relative_additional_permissions_resolve_against_tool_workdir() -> Resul let mut builder = test_codex().with_config(move |config| { config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); - config.features.enable(Feature::RequestPermissions); + config + .features + .enable(Feature::RequestPermissions) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -372,7 +378,10 @@ async fn read_only_with_additional_permissions_widens_to_unrequested_cwd_write() let mut builder = test_codex().with_config(move |config| { config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); - config.features.enable(Feature::RequestPermissions); + config + .features + .enable(Feature::RequestPermissions) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -462,7 +471,10 @@ async fn read_only_with_additional_permissions_widens_to_unrequested_tmp_write() let mut builder = test_codex().with_config(move |config| { config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); - config.features.enable(Feature::RequestPermissions); + config + .features + .enable(Feature::RequestPermissions) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -553,7 +565,10 @@ async fn workspace_write_with_additional_permissions_can_write_outside_cwd() -> let mut builder = test_codex().with_config(move |config| { config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); - config.features.enable(Feature::RequestPermissions); + config + .features + .enable(Feature::RequestPermissions) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -651,7 +666,10 @@ async fn with_additional_permissions_denied_approval_blocks_execution() -> Resul let mut builder = test_codex().with_config(move |config| { config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); - config.features.enable(Feature::RequestPermissions); + config + .features + .enable(Feature::RequestPermissions) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/request_user_input.rs b/codex-rs/core/tests/suite/request_user_input.rs index f767234c89..f66c2f209d 100644 --- a/codex-rs/core/tests/suite/request_user_input.rs +++ b/codex-rs/core/tests/suite/request_user_input.rs @@ -79,6 +79,7 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul let server = start_mock_server().await; let builder = test_codex(); + #[allow(clippy::expect_used)] let TestCodex { codex, cwd, @@ -87,7 +88,10 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul } = builder .with_config(move |config| { if mode == ModeKind::Default { - config.features.enable(Feature::DefaultModeRequestUserInput); + config + .features + .enable(Feature::DefaultModeRequestUserInput) + .expect("test config should allow feature update"); } }) .build(&server) diff --git a/codex-rs/core/tests/suite/search_tool.rs b/codex-rs/core/tests/suite/search_tool.rs index d852c9cfb3..c55295f01c 100644 --- a/codex-rs/core/tests/suite/search_tool.rs +++ b/codex-rs/core/tests/suite/search_tool.rs @@ -22,6 +22,7 @@ use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; @@ -142,8 +143,14 @@ fn configure_apps_with_optional_rmcp( apps_base_url: &str, rmcp_server_bin: Option, ) { - config.features.enable(Feature::Apps); - config.features.disable(Feature::AppsMcpGateway); + config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); + config + .features + .disable(Feature::AppsMcpGateway) + .expect("test config should allow feature update"); config.chatgpt_base_url = apps_base_url.to_string(); if let Some(command) = rmcp_server_bin { let mut servers = config.mcp_servers.get().clone(); @@ -181,13 +188,13 @@ async fn search_tool_flag_adds_tool() -> Result<()> { let server = start_mock_server().await; let apps_server = AppsTestServer::mount(&server).await?; - let mock = mount_sse_sequence( + let mock = mount_sse_once( &server, - vec![sse(vec![ + sse(vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "done"), ev_completed("resp-1"), - ])], + ]), ) .await; diff --git a/codex-rs/core/tests/suite/shell_command.rs b/codex-rs/core/tests/suite/shell_command.rs index 38b1594b32..fe34630598 100644 --- a/codex-rs/core/tests/suite/shell_command.rs +++ b/codex-rs/core/tests/suite/shell_command.rs @@ -251,9 +251,13 @@ async fn shell_command_times_out_with_timeout_ms() -> anyhow::Result<()> { async fn unicode_output(login: bool) -> anyhow::Result<()> { skip_if_no_network!(Ok(())); + #[allow(clippy::expect_used)] let harness = shell_command_harness_with(|builder| { builder.with_model("gpt-5.2").with_config(|config| { - config.features.enable(Feature::PowershellUtf8); + config + .features + .enable(Feature::PowershellUtf8) + .expect("test config should allow feature update"); }) }) .await?; @@ -281,9 +285,13 @@ async fn unicode_output(login: bool) -> anyhow::Result<()> { async fn unicode_output_with_newlines(login: bool) -> anyhow::Result<()> { skip_if_no_network!(Ok(())); + #[allow(clippy::expect_used)] let harness = shell_command_harness_with(|builder| { builder.with_model("gpt-5.2").with_config(|config| { - config.features.enable(Feature::PowershellUtf8); + config + .features + .enable(Feature::PowershellUtf8) + .expect("test config should allow feature update"); }) }) .await?; diff --git a/codex-rs/core/tests/suite/shell_snapshot.rs b/codex-rs/core/tests/suite/shell_snapshot.rs index 59c13fa50d..491853f279 100644 --- a/codex-rs/core/tests/suite/shell_snapshot.rs +++ b/codex-rs/core/tests/suite/shell_snapshot.rs @@ -119,8 +119,14 @@ async fn run_snapshot_command_with_options( } = options; let builder = test_codex().with_config(move |config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); - config.features.enable(Feature::ShellSnapshot); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::ShellSnapshot) + .expect("test config should allow feature update"); config.permissions.shell_environment_policy.r#set = shell_environment_set; }); let harness = TestCodexHarness::with_builder(builder).await?; @@ -207,7 +213,10 @@ async fn run_shell_command_snapshot_with_options( shell_environment_set, } = options; let builder = test_codex().with_config(move |config| { - config.features.enable(Feature::ShellSnapshot); + config + .features + .enable(Feature::ShellSnapshot) + .expect("test config should allow feature update"); config.permissions.shell_environment_policy.r#set = shell_environment_set; }); let harness = TestCodexHarness::with_builder(builder).await?; @@ -399,7 +408,10 @@ async fn linux_shell_command_uses_shell_snapshot() -> Result<()> { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_command_snapshot_preserves_shell_environment_policy_set() -> Result<()> { let builder = test_codex().with_config(|config| { - config.features.enable(Feature::ShellSnapshot); + config + .features + .enable(Feature::ShellSnapshot) + .expect("test config should allow feature update"); config.permissions.shell_environment_policy.r#set = policy_set_path_for_test(); }); let harness = TestCodexHarness::with_builder(builder).await?; @@ -446,8 +458,14 @@ async fn shell_command_snapshot_preserves_shell_environment_policy_set() -> Resu async fn linux_unified_exec_snapshot_preserves_shell_environment_policy_set() -> Result<()> { let builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); - config.features.enable(Feature::ShellSnapshot); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::ShellSnapshot) + .expect("test config should allow feature update"); config.permissions.shell_environment_policy.r#set = policy_set_path_for_test(); }); let harness = TestCodexHarness::with_builder(builder).await?; @@ -493,7 +511,10 @@ async fn linux_unified_exec_snapshot_preserves_shell_environment_policy_set() -> #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_command_snapshot_still_intercepts_apply_patch() -> Result<()> { let builder = test_codex().with_config(|config| { - config.features.enable(Feature::ShellSnapshot); + config + .features + .enable(Feature::ShellSnapshot) + .expect("test config should allow feature update"); config.include_apply_patch_tool = true; }); let harness = TestCodexHarness::with_builder(builder).await?; @@ -562,7 +583,10 @@ async fn shell_command_snapshot_still_intercepts_apply_patch() -> Result<()> { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_snapshot_deleted_after_shutdown_with_skills() -> Result<()> { let builder = test_codex().with_config(|config| { - config.features.enable(Feature::ShellSnapshot); + config + .features + .enable(Feature::ShellSnapshot) + .expect("test config should allow feature update"); }); let harness = TestCodexHarness::with_builder(builder).await?; let home = harness.test().home.clone(); diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index 177453d6dd..b17219e5f1 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -40,7 +40,10 @@ use uuid::Uuid; async fn new_thread_is_recorded_in_state_db() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -170,7 +173,10 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { fs::write(&rollout_path, format!("{jsonl}\n")).expect("should write rollout file"); }) .with_config(|config| { - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -230,7 +236,10 @@ async fn user_messages_persist_in_state_db() -> Result<()> { .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; @@ -281,7 +290,10 @@ async fn web_search_marks_thread_memory_mode_polluted_when_configured() -> Resul .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); config.memories.no_memories_if_mcp_or_web_search = true; }); let test = builder.build(&server).await?; @@ -331,7 +343,10 @@ async fn mcp_call_marks_thread_memory_mode_polluted_when_configured() -> Result< let rmcp_test_server_bin = stdio_server_bin()?; let mut builder = test_codex().with_config(move |config| { - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); config.memories.no_memories_if_mcp_or_web_search = true; let mut servers = config.mcp_servers.get().clone(); @@ -434,7 +449,10 @@ async fn tool_call_logs_include_thread_id() -> Result<()> { .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; let db = test.codex.state_db().expect("state db enabled"); diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index 3dc463c4ab..5c154177a3 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -140,8 +140,12 @@ async fn setup_turn_one_with_spawned_child( ) .await; + #[allow(clippy::expect_used)] let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Collab); + config + .features + .enable(Feature::Collab) + .expect("test config should allow feature update"); }); let test = builder.build(server).await?; test.submit_turn(TURN_1_PROMPT).await?; @@ -252,7 +256,10 @@ async fn spawned_child_receives_forked_parent_context() -> Result<()> { .await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::Collab); + config + .features + .enable(Feature::Collab) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/tool_harness.rs b/codex-rs/core/tests/suite/tool_harness.rs index ca666bce38..7e0ee338a4 100644 --- a/codex-rs/core/tests/suite/tool_harness.rs +++ b/codex-rs/core/tests/suite/tool_harness.rs @@ -284,7 +284,10 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ApplyPatchFreeform); + config + .features + .enable(Feature::ApplyPatchFreeform) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -389,7 +392,10 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::ApplyPatchFreeform); + config + .features + .enable(Feature::ApplyPatchFreeform) + .expect("test config should allow feature update"); }); let TestCodex { codex, diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index 9f1803c75e..6dd844595d 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -293,9 +293,15 @@ async fn collect_tools(use_unified_exec: bool) -> Result> { let mut builder = test_codex().with_config(move |config| { if use_unified_exec { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); } else { - config.features.disable(Feature::UnifiedExec); + config + .features + .disable(Feature::UnifiedExec) + .expect("test config should allow feature update"); } }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/undo.rs b/codex-rs/core/tests/suite/undo.rs index e129a815bf..f059ece746 100644 --- a/codex-rs/core/tests/suite/undo.rs +++ b/codex-rs/core/tests/suite/undo.rs @@ -29,7 +29,10 @@ use pretty_assertions::assert_eq; async fn undo_harness() -> Result { let builder = test_codex().with_model("gpt-5.1").with_config(|config| { config.include_apply_patch_tool = true; - config.features.enable(Feature::GhostCommit); + config + .features + .enable(Feature::GhostCommit) + .expect("test config should allow feature update"); }); TestCodexHarness::with_builder(builder).await } diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index a3ef5711f8..d345153562 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -164,7 +164,10 @@ async fn unified_exec_intercepts_apply_patch_exec_command() -> Result<()> { let builder = test_codex().with_config(|config| { config.include_apply_patch_tool = true; config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let harness = TestCodexHarness::with_builder(builder).await?; @@ -294,7 +297,10 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { let mut builder = test_codex().with_model("gpt-5").with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -370,7 +376,10 @@ async fn unified_exec_resolves_relative_workdir() -> Result<()> { let mut builder = test_codex().with_model("gpt-5").with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -452,7 +461,10 @@ async fn unified_exec_respects_workdir_override() -> Result<()> { let mut builder = test_codex().with_model("gpt-5").with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -535,7 +547,10 @@ async fn unified_exec_emits_exec_command_end_event() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -626,7 +641,10 @@ async fn unified_exec_emits_output_delta_for_exec_command() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -702,7 +720,10 @@ async fn unified_exec_full_lifecycle_with_background_end_event() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -813,7 +834,10 @@ async fn unified_exec_emits_terminal_interaction_for_write_stdin() -> Result<()> let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -917,7 +941,10 @@ async fn unified_exec_terminal_interaction_captures_delayed_output() -> Result<( let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1112,7 +1139,10 @@ async fn unified_exec_emits_one_begin_and_one_end_event() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1232,7 +1262,10 @@ async fn exec_command_reports_chunk_and_exit_metadata() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1351,7 +1384,10 @@ async fn unified_exec_defaults_to_pipe() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1441,7 +1477,10 @@ async fn unified_exec_can_enable_tty() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1525,7 +1564,10 @@ async fn unified_exec_respects_early_exit_notifications() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1621,7 +1663,10 @@ async fn write_stdin_returns_exit_metadata_and_clears_session() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1788,7 +1833,10 @@ async fn unified_exec_emits_end_event_when_session_dies_via_stdin() -> Result<() let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1898,7 +1946,10 @@ async fn unified_exec_keeps_long_running_session_after_turn_end() -> Result<()> let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -1994,7 +2045,10 @@ async fn unified_exec_interrupt_terminates_long_running_session() -> Result<()> let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2070,7 +2124,10 @@ async fn unified_exec_reuses_session_via_stdin() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2187,7 +2244,10 @@ async fn unified_exec_streams_after_lagged_output() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2322,7 +2382,10 @@ async fn unified_exec_timeout_and_followup_poll() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2432,7 +2495,10 @@ async fn unified_exec_formats_large_output_summary() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2521,7 +2587,10 @@ async fn unified_exec_runs_under_sandbox() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2605,7 +2674,10 @@ async fn unified_exec_python_prompt_under_seatbelt() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2724,7 +2796,10 @@ async fn unified_exec_runs_on_all_platforms() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -2801,7 +2876,10 @@ async fn unified_exec_prunes_exited_sessions_first() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; - config.features.enable(Feature::UnifiedExec); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); }); let TestCodex { codex, diff --git a/codex-rs/core/tests/suite/unstable_features_warning.rs b/codex-rs/core/tests/suite/unstable_features_warning.rs index a215ecbc06..9269ed262a 100644 --- a/codex-rs/core/tests/suite/unstable_features_warning.rs +++ b/codex-rs/core/tests/suite/unstable_features_warning.rs @@ -19,7 +19,10 @@ use toml::toml; async fn emits_warning_when_unstable_features_enabled_via_config() { let home = TempDir::new().expect("tempdir"); let mut config = load_default_config_for_test(&home).await; - config.features.enable(Feature::ChildAgentsMd); + config + .features + .enable(Feature::ChildAgentsMd) + .expect("test config should allow feature update"); let user_config_path = AbsolutePathBuf::from_absolute_path(config.codex_home.join(CONFIG_TOML_FILE)) .expect("absolute user config path"); @@ -56,7 +59,10 @@ async fn emits_warning_when_unstable_features_enabled_via_config() { async fn suppresses_warning_when_configured() { let home = TempDir::new().expect("tempdir"); let mut config = load_default_config_for_test(&home).await; - config.features.enable(Feature::ChildAgentsMd); + config + .features + .enable(Feature::ChildAgentsMd) + .expect("test config should allow feature update"); config.suppress_unstable_features_warning = true; let user_config_path = AbsolutePathBuf::from_absolute_path(config.codex_home.join(CONFIG_TOML_FILE)) diff --git a/codex-rs/core/tests/suite/user_shell_cmd.rs b/codex-rs/core/tests/suite/user_shell_cmd.rs index 6ce43a2d13..8bd94ab9f1 100644 --- a/codex-rs/core/tests/suite/user_shell_cmd.rs +++ b/codex-rs/core/tests/suite/user_shell_cmd.rs @@ -250,7 +250,10 @@ async fn user_shell_command_history_is_persisted_and_shared_with_model() -> anyh let server = responses::start_mock_server().await; // Disable it to ease command matching. let mut builder = core_test_support::test_codex::test_codex().with_config(move |config| { - config.features.disable(Feature::ShellSnapshot); + config + .features + .disable(Feature::ShellSnapshot) + .expect("test config should allow feature update"); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index b56e28d020..3e652577bb 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -299,7 +299,10 @@ async fn view_image_tool_can_preserve_original_resolution_on_gpt5_3_codex() -> a let mut builder = test_codex() .with_model("gpt-5.3-codex") .with_config(|config| { - config.features.enable(Feature::ImageDetailOriginal); + config + .features + .enable(Feature::ImageDetailOriginal) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -398,7 +401,10 @@ async fn view_image_tool_keeps_legacy_behavior_below_gpt5_3_codex() -> anyhow::R let server = start_mock_server().await; let mut builder = test_codex().with_model("gpt-5.2").with_config(|config| { - config.features.enable(Feature::ImageDetailOriginal); + config + .features + .enable(Feature::ImageDetailOriginal) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -499,7 +505,10 @@ async fn js_repl_emit_image_attaches_local_image() -> anyhow::Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::JsRepl); + config + .features + .enable(Feature::JsRepl) + .expect("test config should allow feature update"); }); let TestCodex { codex, @@ -613,8 +622,12 @@ async fn js_repl_view_image_requires_explicit_emit() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; + #[allow(clippy::expect_used)] let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::JsRepl); + config + .features + .enable(Feature::JsRepl) + .expect("test config should allow feature update"); }); let TestCodex { codex, diff --git a/codex-rs/core/tests/suite/web_search.rs b/codex-rs/core/tests/suite/web_search.rs index e7082a832c..6df0338e92 100644 --- a/codex-rs/core/tests/suite/web_search.rs +++ b/codex-rs/core/tests/suite/web_search.rs @@ -74,7 +74,10 @@ async fn web_search_mode_takes_precedence_over_legacy_flags() { let mut builder = test_codex() .with_model("gpt-5-codex") .with_config(|config| { - config.features.enable(Feature::WebSearchRequest); + config + .features + .enable(Feature::WebSearchRequest) + .expect("test config should allow feature update"); config .web_search_mode .set(WebSearchMode::Cached) @@ -119,8 +122,14 @@ async fn web_search_mode_defaults_to_cached_when_features_disabled() { .web_search_mode .set(WebSearchMode::Cached) .expect("test web_search_mode should satisfy constraints"); - config.features.disable(Feature::WebSearchCached); - config.features.disable(Feature::WebSearchRequest); + config + .features + .disable(Feature::WebSearchCached) + .expect("test config should allow feature update"); + config + .features + .disable(Feature::WebSearchRequest) + .expect("test config should allow feature update"); }); let test = builder .build(&server) @@ -170,8 +179,14 @@ async fn web_search_mode_updates_between_turns_with_sandbox_policy() { .web_search_mode .set(WebSearchMode::Cached) .expect("test web_search_mode should satisfy constraints"); - config.features.disable(Feature::WebSearchCached); - config.features.disable(Feature::WebSearchRequest); + config + .features + .disable(Feature::WebSearchCached) + .expect("test config should allow feature update"); + config + .features + .disable(Feature::WebSearchRequest) + .expect("test config should allow feature update"); }); let test = builder .build(&server) diff --git a/codex-rs/core/tests/suite/websocket_fallback.rs b/codex-rs/core/tests/suite/websocket_fallback.rs index fadd427c16..302ae3965b 100644 --- a/codex-rs/core/tests/suite/websocket_fallback.rs +++ b/codex-rs/core/tests/suite/websocket_fallback.rs @@ -45,7 +45,10 @@ async fn websocket_fallback_switches_to_http_on_upgrade_required_connect() -> Re move |config| { config.model_provider.base_url = Some(base_url); config.model_provider.wire_api = codex_core::WireApi::Responses; - config.features.enable(Feature::ResponsesWebsockets); + config + .features + .enable(Feature::ResponsesWebsockets) + .expect("test config should allow feature update"); // If we don't treat 426 specially, the sampling loop would retry the WebSocket // handshake before switching to the HTTP transport. config.model_provider.stream_max_retries = Some(2); @@ -91,7 +94,10 @@ async fn websocket_fallback_switches_to_http_after_retries_exhausted() -> Result move |config| { config.model_provider.base_url = Some(base_url); config.model_provider.wire_api = codex_core::WireApi::Responses; - config.features.enable(Feature::ResponsesWebsockets); + config + .features + .enable(Feature::ResponsesWebsockets) + .expect("test config should allow feature update"); config.model_provider.stream_max_retries = Some(2); config.model_provider.request_max_retries = Some(0); } @@ -136,7 +142,10 @@ async fn websocket_fallback_hides_first_websocket_retry_stream_error() -> Result move |config| { config.model_provider.base_url = Some(base_url); config.model_provider.wire_api = codex_core::WireApi::Responses; - config.features.enable(Feature::ResponsesWebsockets); + config + .features + .enable(Feature::ResponsesWebsockets) + .expect("test config should allow feature update"); config.model_provider.stream_max_retries = Some(2); config.model_provider.request_max_retries = Some(0); } @@ -211,7 +220,10 @@ async fn websocket_fallback_is_sticky_across_turns() -> Result<()> { move |config| { config.model_provider.base_url = Some(base_url); config.model_provider.wire_api = codex_core::WireApi::Responses; - config.features.enable(Feature::ResponsesWebsockets); + config + .features + .enable(Feature::ResponsesWebsockets) + .expect("test config should allow feature update"); config.model_provider.stream_max_retries = Some(2); config.model_provider.request_max_retries = Some(0); } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 1fe9d0d499..dd20187508 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -2835,25 +2835,31 @@ impl App { .with_profile(self.active_profile.as_deref()); for (feature, enabled) in &updates { let feature_key = feature.key(); - if *enabled { - // Update the in-memory configs. - self.config.features.enable(*feature); - self.chat_widget.set_feature_enabled(*feature, true); + if let Err(err) = self.config.features.set_enabled(*feature, *enabled) { + tracing::error!( + error = %err, + feature = feature_key, + "failed to update constrained feature flags" + ); + self.chat_widget.add_error_message(format!( + "Failed to update experimental feature `{feature_key}`: {err}" + )); + continue; + } + let effective_enabled = self.config.features.enabled(*feature); + self.chat_widget + .set_feature_enabled(*feature, effective_enabled); + if effective_enabled { builder = builder.set_feature_enabled(feature_key, true); + } else if feature.default_enabled() { + builder = builder.set_feature_enabled(feature_key, false); } else { - // Update the in-memory configs. - self.config.features.disable(*feature); - self.chat_widget.set_feature_enabled(*feature, false); - if feature.default_enabled() { - builder = builder.set_feature_enabled(feature_key, false); - } else { - // If the feature already default to `false`, we drop the key - // in the config file so that the user does not miss the feature - // once it gets globally released. - builder = builder.with_edits(vec![ConfigEdit::ClearPath { - segments: vec!["features".to_string(), feature_key.to_string()], - }]); - } + // If the feature already default to `false`, we drop the key + // in the config file so that the user does not miss the feature + // once it gets globally released. + builder = builder.with_edits(vec![ConfigEdit::ClearPath { + segments: vec!["features".to_string(), feature_key.to_string()], + }]); } } if windows_sandbox_changed { diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 0296bd08d2..e4e33e795a 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -6939,12 +6939,15 @@ impl ChatWidget { } #[cfg_attr(not(target_os = "windows"), allow(dead_code))] - pub(crate) fn set_feature_enabled(&mut self, feature: Feature, enabled: bool) { - if enabled { - self.config.features.enable(feature); - } else { - self.config.features.disable(feature); + pub(crate) fn set_feature_enabled(&mut self, feature: Feature, enabled: bool) -> bool { + if let Err(err) = self.config.features.set_enabled(feature, enabled) { + tracing::warn!( + error = %err, + feature = feature.key(), + "failed to update constrained chat widget feature state" + ); } + let enabled = self.config.features.enabled(feature); if feature == Feature::VoiceTranscription { self.bottom_pane.set_voice_transcription_enabled(enabled); } @@ -6985,6 +6988,7 @@ impl ChatWidget { ), ); } + enabled } pub(crate) fn set_full_access_warning_acknowledged(&mut self, acknowledged: bool) { diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 0ee7974d26..2861be570d 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -6059,7 +6059,10 @@ fn render_bottom_popup(chat: &ChatWidget, width: u16) -> String { #[tokio::test] async fn apps_popup_refreshes_when_connectors_snapshot_updates() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); let notion_id = "unit_test_apps_popup_refresh_connector_1"; let linear_id = "unit_test_apps_popup_refresh_connector_2"; @@ -6149,7 +6152,10 @@ async fn apps_popup_refreshes_when_connectors_snapshot_updates() { #[tokio::test] async fn apps_refresh_failure_keeps_existing_full_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); let notion_id = "unit_test_apps_refresh_failure_connector_1"; let linear_id = "unit_test_apps_refresh_failure_connector_2"; @@ -6228,7 +6234,10 @@ async fn apps_refresh_failure_keeps_existing_full_snapshot() { #[tokio::test] async fn apps_refresh_failure_with_cached_snapshot_triggers_pending_force_refetch() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); chat.connectors_prefetch_in_flight = true; chat.connectors_force_refetch_pending = true; @@ -6264,7 +6273,10 @@ async fn apps_refresh_failure_with_cached_snapshot_triggers_pending_force_refetc #[tokio::test] async fn apps_partial_refresh_uses_same_filtering_as_full_refresh() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); let full_connectors = vec![ @@ -6360,7 +6372,10 @@ async fn apps_partial_refresh_uses_same_filtering_as_full_refresh() { #[tokio::test] async fn apps_popup_shows_disabled_status_for_installed_but_disabled_apps() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); chat.on_connectors_loaded( @@ -6398,7 +6413,10 @@ async fn apps_popup_shows_disabled_status_for_installed_but_disabled_apps() { #[tokio::test] async fn apps_initial_load_applies_enabled_state_from_config() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); let temp = tempdir().expect("tempdir"); @@ -6447,7 +6465,10 @@ async fn apps_initial_load_applies_enabled_state_from_config() { #[tokio::test] async fn apps_refresh_preserves_toggled_enabled_state() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); chat.on_connectors_loaded( @@ -6512,7 +6533,10 @@ async fn apps_refresh_preserves_toggled_enabled_state() { #[tokio::test] async fn apps_popup_for_not_installed_app_uses_install_only_selected_description() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - chat.config.features.enable(Feature::Apps); + chat.config + .features + .enable(Feature::Apps) + .expect("test config should allow feature update"); chat.bottom_pane.set_connectors_enabled(true); chat.on_connectors_loaded( diff --git a/codex-rs/tui/src/debug_config.rs b/codex-rs/tui/src/debug_config.rs index a3e98d85c7..91588fd3d7 100644 --- a/codex-rs/tui/src/debug_config.rs +++ b/codex-rs/tui/src/debug_config.rs @@ -527,6 +527,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), allowed_sandbox_modes: Some(vec![SandboxModeRequirement::ReadOnly]), allowed_web_search_modes: Some(vec![WebSearchModeRequirement::Cached]), + feature_requirements: None, mcp_servers: Some(BTreeMap::from([( "docs".to_string(), McpServerRequirement { @@ -652,6 +653,7 @@ approval_policy = "never" allowed_approval_policies: None, allowed_sandbox_modes: None, allowed_web_search_modes: Some(Vec::new()), + feature_requirements: None, mcp_servers: None, rules: None, enforce_residency: None, diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 5d36ec441d..b9a1a5c47c 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -1501,7 +1501,10 @@ trust_level = "untrusted" async fn read_session_cwd_prefers_sqlite_when_thread_id_present() -> std::io::Result<()> { let temp_dir = TempDir::new()?; let mut config = build_config(&temp_dir).await?; - config.features.enable(Feature::Sqlite); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow sqlite"); let thread_id = ThreadId::new(); let rollout_cwd = temp_dir.path().join("rollout-cwd"); From 2e154a35bc6df9239dff23b6552076fc2a8a49b1 Mon Sep 17 00:00:00 2001 From: gabec-openai Date: Wed, 4 Mar 2026 13:43:52 +0900 Subject: [PATCH 361/385] Add role-specific subagent nickname overrides (#13218) ## Summary - add `nickname_candidates` to agent role config - use role-specific nickname pools for spawned and resumed subagents - validate and schema-generate the new config surface ## Testing - `just fmt` - `just write-config-schema` - `just fix -p codex-core` - `cargo test -p codex-core` - `cargo test` --------- Co-authored-by: Codex --- codex-rs/core/config.schema.json | 7 + codex-rs/core/src/agent/control.rs | 76 +++++++++- codex-rs/core/src/agent/role.rs | 37 +++-- codex-rs/core/src/config/mod.rs | 222 +++++++++++++++++++++++++++++ 4 files changed, 330 insertions(+), 12 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 749f6de23b..71d624d2c0 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -20,6 +20,13 @@ "description": { "description": "Human-facing role documentation used in spawn tool guidance.", "type": "string" + }, + "nickname_candidates": { + "description": "Candidate nicknames for agents spawned with this role.", + "items": { + "type": "string" + }, + "type": "array" } }, "type": "object" diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index fa643ff3ce..e7547f9c9d 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -1,5 +1,7 @@ use crate::agent::AgentStatus; use crate::agent::guards::Guards; +use crate::agent::role::DEFAULT_ROLE_NAME; +use crate::agent::role::resolve_role_config; use crate::agent::status::is_final; use crate::error::CodexErr; use crate::error::Result as CodexResult; @@ -32,7 +34,7 @@ pub(crate) struct SpawnAgentOptions { pub(crate) fork_parent_spawn_call_id: Option, } -fn agent_nickname_list() -> Vec<&'static str> { +fn default_agent_nickname_list() -> Vec<&'static str> { AGENT_NAMES .lines() .map(str::trim) @@ -40,6 +42,23 @@ fn agent_nickname_list() -> Vec<&'static str> { .collect() } +fn agent_nickname_candidates( + config: &crate::config::Config, + role_name: Option<&str>, +) -> Vec { + let role_name = role_name.unwrap_or(DEFAULT_ROLE_NAME); + if let Some(candidates) = + resolve_role_config(config, role_name).and_then(|role| role.nickname_candidates.clone()) + { + return candidates; + } + + default_agent_nickname_list() + .into_iter() + .map(ToOwned::to_owned) + .collect() +} + /// Control-plane handle for multi-agent operations. /// `AgentControl` is held by each session (via `SessionServices`). It provides capability to /// spawn new agents and the inter-agent communication layer. @@ -94,7 +113,10 @@ impl AgentControl { agent_role, .. })) => { - let agent_nickname = reservation.reserve_agent_nickname(&agent_nickname_list())?; + let candidate_names = agent_nickname_candidates(&config, agent_role.as_deref()); + let candidate_name_refs: Vec<&str> = + candidate_names.iter().map(String::as_str).collect(); + let agent_nickname = reservation.reserve_agent_nickname(&candidate_name_refs)?; Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, depth, @@ -225,8 +247,12 @@ impl AgentControl { let reserved_agent_nickname = resumed_agent_nickname .as_deref() .map(|agent_nickname| { + let candidate_names = + agent_nickname_candidates(&config, resumed_agent_role.as_deref()); + let candidate_name_refs: Vec<&str> = + candidate_names.iter().map(String::as_str).collect(); reservation.reserve_agent_nickname_with_preference( - &agent_nickname_list(), + &candidate_name_refs, Some(agent_nickname), ) }) @@ -467,6 +493,7 @@ mod tests { use crate::CodexThread; use crate::ThreadManager; use crate::agent::agent_status_from_event; + use crate::config::AgentRoleConfig; use crate::config::Config; use crate::config::ConfigBuilder; use crate::config_loader::LoaderOverrides; @@ -1378,6 +1405,49 @@ mod tests { assert_eq!(agent_role, Some("explorer".to_string())); } + #[tokio::test] + async fn spawn_thread_subagent_uses_role_specific_nickname_candidates() { + let mut harness = AgentControlHarness::new().await; + harness.config.agent_roles.insert( + "researcher".to_string(), + AgentRoleConfig { + description: Some("Research role".to_string()), + config_file: None, + nickname_candidates: Some(vec!["Atlas".to_string()]), + }, + ); + let (parent_thread_id, _parent_thread) = harness.start_thread().await; + + let child_thread_id = harness + .control + .spawn_agent( + harness.config.clone(), + text_input("hello child"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: Some("researcher".to_string()), + })), + ) + .await + .expect("child spawn should succeed"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + let snapshot = child_thread.config_snapshot().await; + + let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { agent_nickname, .. }) = + snapshot.session_source + else { + panic!("expected thread-spawn sub-agent source"); + }; + assert_eq!(agent_nickname, Some("Atlas".to_string())); + } + #[tokio::test] async fn resume_thread_subagent_restores_stored_nickname_and_role() { let (home, mut config) = test_config().await; diff --git a/codex-rs/core/src/agent/role.rs b/codex-rs/core/src/agent/role.rs index 3ca496d6e1..0793febe54 100644 --- a/codex-rs/core/src/agent/role.rs +++ b/codex-rs/core/src/agent/role.rs @@ -38,15 +38,9 @@ pub(crate) async fn apply_role_to_config( role_name: Option<&str>, ) -> Result<(), String> { let role_name = role_name.unwrap_or(DEFAULT_ROLE_NAME); - let (config_file, is_built_in) = config - .agent_roles - .get(role_name) - .map(|role| (&role.config_file, false)) - .or_else(|| { - built_in::configs() - .get(role_name) - .map(|role| (&role.config_file, true)) - }) + let is_built_in = !config.agent_roles.contains_key(role_name); + let (config_file, is_built_in) = resolve_role_config(config, role_name) + .map(|role| (&role.config_file, is_built_in)) .ok_or_else(|| format!("unknown agent_type '{role_name}'"))?; let Some(config_file) = config_file.as_ref() else { return Ok(()); @@ -139,6 +133,16 @@ pub(crate) async fn apply_role_to_config( Ok(()) } +pub(crate) fn resolve_role_config<'a>( + config: &'a Config, + role_name: &str, +) -> Option<&'a AgentRoleConfig> { + config + .agent_roles + .get(role_name) + .or_else(|| built_in::configs().get(role_name)) +} + pub(crate) mod spawn_tool_spec { use super::*; @@ -196,6 +200,7 @@ mod built_in { AgentRoleConfig { description: Some("Default agent.".to_string()), config_file: None, + nickname_candidates: None, } ), ( @@ -210,6 +215,7 @@ Rules: - Run explorers in parallel when useful. - Reuse existing explorers for related questions."#.to_string()), config_file: Some("explorer.toml".to_string().parse().unwrap_or_default()), + nickname_candidates: None, } ), ( @@ -224,6 +230,7 @@ Rules: - Explicitly assign **ownership** of the task (files / responsibility). - Always tell workers they are **not alone in the codebase**, and they should ignore edits made by others without touching them."#.to_string()), config_file: None, + nickname_candidates: None, } ), // Awaiter is temp removed @@ -354,6 +361,7 @@ mod tests { AgentRoleConfig { description: None, config_file: Some(PathBuf::from("/path/does/not/exist.toml")), + nickname_candidates: None, }, ); @@ -373,6 +381,7 @@ mod tests { AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -403,6 +412,7 @@ mod tests { AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -456,6 +466,7 @@ model_provider = "test-provider" AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -512,6 +523,7 @@ model_provider = "role-provider" AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -569,6 +581,7 @@ model_provider = "base-provider" AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -630,6 +643,7 @@ model_reasoning_effort = "high" AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -671,6 +685,7 @@ writable_roots = ["./sandbox-root"] AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -724,6 +739,7 @@ writable_roots = ["./sandbox-root"] AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -764,6 +780,7 @@ enabled = false AgentRoleConfig { description: None, config_file: Some(role_path), + nickname_candidates: None, }, ); @@ -791,6 +808,7 @@ enabled = false AgentRoleConfig { description: Some("user override".to_string()), config_file: None, + nickname_candidates: None, }, ), ("researcher".to_string(), AgentRoleConfig::default()), @@ -811,6 +829,7 @@ enabled = false AgentRoleConfig { description: Some("first".to_string()), config_file: None, + nickname_candidates: None, }, )]); diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 3b71f8fac4..2d833d8b51 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -78,6 +78,7 @@ use serde::Deserialize; use serde::Serialize; use similar::DiffableStr; use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::collections::HashMap; use std::io::ErrorKind; use std::path::Path; @@ -1385,6 +1386,7 @@ pub struct AgentsToml { /// [agents.researcher] /// description = "Research-focused role." /// config_file = "./agents/researcher.toml" + /// nickname_candidates = ["Herodotus", "Ibn Battuta"] /// ``` #[serde(default, flatten)] pub roles: BTreeMap, @@ -1396,6 +1398,8 @@ pub struct AgentRoleConfig { pub description: Option, /// Path to a role-specific config layer. pub config_file: Option, + /// Candidate nicknames for agents spawned with this role. + pub nickname_candidates: Option>, } #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] @@ -1407,6 +1411,9 @@ pub struct AgentRoleToml { /// Path to a role-specific config layer. /// Relative paths are resolved relative to the `config.toml` that defines them. pub config_file: Option, + + /// Candidate nicknames for agents spawned with this role. + pub nickname_candidates: Option>, } impl From for Tools { @@ -1895,11 +1902,16 @@ impl Config { let config_file = role.config_file.as_ref().map(AbsolutePathBuf::to_path_buf); Self::validate_agent_role_config_file(name, config_file.as_deref())?; + let nickname_candidates = Self::normalize_agent_role_nickname_candidates( + name, + role.nickname_candidates.as_deref(), + )?; Ok(( name.clone(), AgentRoleConfig { description: role.description.clone(), config_file, + nickname_candidates, }, )) }) @@ -2361,6 +2373,58 @@ impl Config { } } + fn normalize_agent_role_nickname_candidates( + role_name: &str, + nickname_candidates: Option<&[String]>, + ) -> std::io::Result>> { + let Some(nickname_candidates) = nickname_candidates else { + return Ok(None); + }; + + if nickname_candidates.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("agents.{role_name}.nickname_candidates must contain at least one name"), + )); + } + + let mut normalized_candidates = Vec::with_capacity(nickname_candidates.len()); + let mut seen_candidates = BTreeSet::new(); + + for nickname in nickname_candidates { + let normalized_nickname = nickname.trim(); + if normalized_nickname.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("agents.{role_name}.nickname_candidates cannot contain blank names"), + )); + } + + if !seen_candidates.insert(normalized_nickname.to_owned()) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("agents.{role_name}.nickname_candidates cannot contain duplicates"), + )); + } + + if !normalized_nickname + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "agents.{role_name}.nickname_candidates may only contain ASCII letters, digits, spaces, hyphens, and underscores" + ), + )); + } + + normalized_candidates.push(normalized_nickname.to_owned()); + } + + Ok(Some(normalized_candidates)) + } + pub fn set_windows_sandbox_enabled(&mut self, value: bool) { self.permissions.windows_sandbox_mode = if value { Some(WindowsSandboxModeToml::Unelevated) @@ -4662,6 +4726,7 @@ model = "gpt-5.1-codex" AgentRoleToml { description: Some("Research role".to_string()), config_file: Some(AbsolutePathBuf::from_absolute_path(missing_path)?), + nickname_candidates: None, }, )]), }), @@ -4698,6 +4763,7 @@ model = "gpt-5.1-codex" r#"[agents.researcher] description = "Research role" config_file = "./agents/researcher.toml" +nickname_candidates = ["Hypatia", "Noether"] "#, ) .await?; @@ -4714,6 +4780,162 @@ config_file = "./agents/researcher.toml" .and_then(|role| role.config_file.as_ref()), Some(&role_config_path) ); + assert_eq!( + config + .agent_roles + .get("researcher") + .and_then(|role| role.nickname_candidates.as_ref()) + .map(|candidates| candidates.iter().map(String::as_str).collect::>()), + Some(vec!["Hypatia", "Noether"]) + ); + + Ok(()) + } + + #[test] + fn load_config_normalizes_agent_role_nickname_candidates() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg = ConfigToml { + agents: Some(AgentsToml { + max_threads: None, + max_depth: None, + job_max_runtime_seconds: None, + roles: BTreeMap::from([( + "researcher".to_string(), + AgentRoleToml { + description: Some("Research role".to_string()), + config_file: None, + nickname_candidates: Some(vec![ + " Hypatia ".to_string(), + "Noether".to_string(), + ]), + }, + )]), + }), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!( + config + .agent_roles + .get("researcher") + .and_then(|role| role.nickname_candidates.as_ref()) + .map(|candidates| candidates.iter().map(String::as_str).collect::>()), + Some(vec!["Hypatia", "Noether"]) + ); + + Ok(()) + } + + #[test] + fn load_config_rejects_empty_agent_role_nickname_candidates() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg = ConfigToml { + agents: Some(AgentsToml { + max_threads: None, + max_depth: None, + job_max_runtime_seconds: None, + roles: BTreeMap::from([( + "researcher".to_string(), + AgentRoleToml { + description: Some("Research role".to_string()), + config_file: None, + nickname_candidates: Some(Vec::new()), + }, + )]), + }), + ..Default::default() + }; + + let result = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + ); + let err = result.expect_err("empty nickname candidates should be rejected"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert!( + err.to_string() + .contains("agents.researcher.nickname_candidates") + ); + + Ok(()) + } + + #[test] + fn load_config_rejects_duplicate_agent_role_nickname_candidates() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg = ConfigToml { + agents: Some(AgentsToml { + max_threads: None, + max_depth: None, + job_max_runtime_seconds: None, + roles: BTreeMap::from([( + "researcher".to_string(), + AgentRoleToml { + description: Some("Research role".to_string()), + config_file: None, + nickname_candidates: Some(vec![ + "Hypatia".to_string(), + " Hypatia ".to_string(), + ]), + }, + )]), + }), + ..Default::default() + }; + + let result = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + ); + let err = result.expect_err("duplicate nickname candidates should be rejected"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert!( + err.to_string() + .contains("agents.researcher.nickname_candidates cannot contain duplicates") + ); + + Ok(()) + } + + #[test] + fn load_config_rejects_unsafe_agent_role_nickname_candidates() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg = ConfigToml { + agents: Some(AgentsToml { + max_threads: None, + max_depth: None, + job_max_runtime_seconds: None, + roles: BTreeMap::from([( + "researcher".to_string(), + AgentRoleToml { + description: Some("Research role".to_string()), + config_file: None, + nickname_candidates: Some(vec!["Agent ".to_string()]), + }, + )]), + }), + ..Default::default() + }; + + let result = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + ); + let err = result.expect_err("unsafe nickname candidates should be rejected"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert!(err.to_string().contains( + "agents.researcher.nickname_candidates may only contain ASCII letters, digits, spaces, hyphens, and underscores" + )); Ok(()) } From d622bff384b8781133ba3a30ff9b5c8b15f36fb5 Mon Sep 17 00:00:00 2001 From: Celia Chen Date: Tue, 3 Mar 2026 20:57:29 -0800 Subject: [PATCH 362/385] chore: Nest skill and protocol network permissions under `network.enabled` (#13427) ## Summary Changes the permission profile shape from a bare network boolean to a nested object. Before: ```yaml permissions: network: true ``` After: ```yaml permissions: network: enabled: true ``` This also updates the shared Rust and app-server protocol types so `PermissionProfile.network` is no longer `Option`, but `Option` with `enabled: Option`. ## What Changed - Updated `PermissionProfile` in `codex-rs/protocol/src/models.rs`: - `pub network: Option` -> `pub network: Option` - Added `NetworkPermissions` with: - `pub enabled: Option` - Changed emptiness semantics so `network` is only considered empty when `enabled` is `None` - Updated skill metadata parsing to accept `permissions.network.enabled` - Updated core permission consumers to read `network.enabled.unwrap_or(false)` where a concrete boolean is needed - Updated app-server v2 protocol types and regenerated schema/TypeScript outputs - Updated docs to mention `additionalPermissions.network.enabled` --- ...CommandExecutionRequestApprovalParams.json | 21 ++++++++-- .../schema/json/EventMsg.json | 21 ++++++++-- .../schema/json/ServerRequest.json | 21 ++++++++-- .../codex_app_server_protocol.schemas.json | 42 ++++++++++++++++--- .../codex_app_server_protocol.v2.schemas.json | 21 ++++++++-- .../schema/typescript/NetworkPermissions.ts | 5 +++ .../schema/typescript/PermissionProfile.ts | 3 +- .../schema/typescript/index.ts | 1 + .../v2/AdditionalNetworkPermissions.ts | 5 +++ .../v2/AdditionalPermissionProfile.ts | 3 +- .../schema/typescript/v2/index.ts | 1 + .../app-server-protocol/src/protocol/v2.rs | 20 ++++++++- codex-rs/app-server/README.md | 2 +- codex-rs/core/src/sandboxing/mod.rs | 23 ++++++++-- codex-rs/core/src/skills/loader.rs | 9 +++- codex-rs/core/src/skills/permissions.rs | 15 +++++-- codex-rs/protocol/src/models.rs | 18 +++++++- .../src/unix/escalate_server.rs | 9 +++- .../tui/src/bottom_pane/approval_overlay.rs | 16 +++++-- 19 files changed, 216 insertions(+), 40 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/NetworkPermissions.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/AdditionalNetworkPermissions.ts diff --git a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json index 5a19a39281..891946fd94 100644 --- a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json @@ -65,6 +65,17 @@ }, "type": "object" }, + "AdditionalNetworkPermissions": { + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, "AdditionalPermissionProfile": { "properties": { "fileSystem": { @@ -88,9 +99,13 @@ ] }, "network": { - "type": [ - "boolean", - "null" + "anyOf": [ + { + "$ref": "#/definitions/AdditionalNetworkPermissions" + }, + { + "type": "null" + } ] } }, diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index a22962cd40..cafd8bc5d0 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -3888,6 +3888,17 @@ ], "type": "string" }, + "NetworkPermissions": { + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, "NetworkPolicyAmendment": { "properties": { "action": { @@ -4052,9 +4063,13 @@ ] }, "network": { - "type": [ - "boolean", - "null" + "anyOf": [ + { + "$ref": "#/definitions/NetworkPermissions" + }, + { + "type": "null" + } ] } }, diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index 9138440548..fce6ec6190 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -65,6 +65,17 @@ }, "type": "object" }, + "AdditionalNetworkPermissions": { + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, "AdditionalPermissionProfile": { "properties": { "fileSystem": { @@ -88,9 +99,13 @@ ] }, "network": { - "type": [ - "boolean", - "null" + "anyOf": [ + { + "$ref": "#/definitions/AdditionalNetworkPermissions" + }, + { + "type": "null" + } ] } }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 374bdc1971..94e9f3a50c 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -61,6 +61,17 @@ }, "type": "object" }, + "AdditionalNetworkPermissions": { + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, "AdditionalPermissionProfile": { "properties": { "fileSystem": { @@ -84,9 +95,13 @@ ] }, "network": { - "type": [ - "boolean", - "null" + "anyOf": [ + { + "$ref": "#/definitions/AdditionalNetworkPermissions" + }, + { + "type": "null" + } ] } }, @@ -5272,6 +5287,17 @@ ], "type": "string" }, + "NetworkPermissions": { + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, "NetworkPolicyAmendment": { "properties": { "action": { @@ -5428,9 +5454,13 @@ ] }, "network": { - "type": [ - "boolean", - "null" + "anyOf": [ + { + "$ref": "#/definitions/NetworkPermissions" + }, + { + "type": "null" + } ] } }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 2ca096cff1..0d1de74481 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -7824,6 +7824,17 @@ ], "type": "string" }, + "NetworkPermissions": { + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, "NetworkPolicyAmendment": { "properties": { "action": { @@ -8148,9 +8159,13 @@ ] }, "network": { - "type": [ - "boolean", - "null" + "anyOf": [ + { + "$ref": "#/definitions/NetworkPermissions" + }, + { + "type": "null" + } ] } }, diff --git a/codex-rs/app-server-protocol/schema/typescript/NetworkPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/NetworkPermissions.ts new file mode 100644 index 0000000000..7fb197b0e7 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/NetworkPermissions.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type NetworkPermissions = { enabled: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts b/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts index bfc0de27b7..c9a60f067c 100644 --- a/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts +++ b/codex-rs/app-server-protocol/schema/typescript/PermissionProfile.ts @@ -3,5 +3,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { FileSystemPermissions } from "./FileSystemPermissions"; import type { MacOsPermissions } from "./MacOsPermissions"; +import type { NetworkPermissions } from "./NetworkPermissions"; -export type PermissionProfile = { network: boolean | null, file_system: FileSystemPermissions | null, macos: MacOsPermissions | null, }; +export type PermissionProfile = { network: NetworkPermissions | null, file_system: FileSystemPermissions | null, macos: MacOsPermissions | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index 228998cddb..faad506dfc 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -115,6 +115,7 @@ export type { ModelRerouteReason } from "./ModelRerouteReason"; export type { NetworkAccess } from "./NetworkAccess"; export type { NetworkApprovalContext } from "./NetworkApprovalContext"; export type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; +export type { NetworkPermissions } from "./NetworkPermissions"; export type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; export type { NetworkPolicyRuleAction } from "./NetworkPolicyRuleAction"; export type { ParsedCommand } from "./ParsedCommand"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalNetworkPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalNetworkPermissions.ts new file mode 100644 index 0000000000..823de26ca3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalNetworkPermissions.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type AdditionalNetworkPermissions = { enabled: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalPermissionProfile.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalPermissionProfile.ts index 4ca4dca120..701ba54316 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalPermissionProfile.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalPermissionProfile.ts @@ -3,5 +3,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions"; import type { AdditionalMacOsPermissions } from "./AdditionalMacOsPermissions"; +import type { AdditionalNetworkPermissions } from "./AdditionalNetworkPermissions"; -export type AdditionalPermissionProfile = { network: boolean | null, fileSystem: AdditionalFileSystemPermissions | null, macos: AdditionalMacOsPermissions | null, }; +export type AdditionalPermissionProfile = { network: AdditionalNetworkPermissions | null, fileSystem: AdditionalFileSystemPermissions | null, macos: AdditionalMacOsPermissions | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 02bf51727d..0c9b2dc587 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -6,6 +6,7 @@ export type { AccountRateLimitsUpdatedNotification } from "./AccountRateLimitsUp export type { AccountUpdatedNotification } from "./AccountUpdatedNotification"; export type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions"; export type { AdditionalMacOsPermissions } from "./AdditionalMacOsPermissions"; +export type { AdditionalNetworkPermissions } from "./AdditionalNetworkPermissions"; export type { AdditionalPermissionProfile } from "./AdditionalPermissionProfile"; export type { AgentMessageDeltaNotification } from "./AgentMessageDeltaNotification"; export type { AnalyticsConfig } from "./AnalyticsConfig"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 7c69d9fa11..2147295c9a 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -31,6 +31,7 @@ use codex_protocol::models::MacOsAutomationValue as CoreMacOsAutomationValue; use codex_protocol::models::MacOsPermissions as CoreMacOsPermissions; use codex_protocol::models::MacOsPreferencesValue as CoreMacOsPreferencesValue; use codex_protocol::models::MessagePhase; +use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions; use codex_protocol::models::PermissionProfile as CorePermissionProfile; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::InputModality; @@ -852,11 +853,26 @@ impl From for AdditionalMacOsPermissions { } } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct AdditionalNetworkPermissions { + pub enabled: Option, +} + +impl From for AdditionalNetworkPermissions { + fn from(value: CoreNetworkPermissions) -> Self { + Self { + enabled: value.enabled, + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct AdditionalPermissionProfile { - pub network: Option, + pub network: Option, pub file_system: Option, pub macos: Option, } @@ -864,7 +880,7 @@ pub struct AdditionalPermissionProfile { impl From for AdditionalPermissionProfile { fn from(value: CorePermissionProfile) -> Self { Self { - network: value.network, + network: value.network.map(AdditionalNetworkPermissions::from), file_system: value.file_system.map(AdditionalFileSystemPermissions::from), macos: value.macos.map(AdditionalMacOsPermissions::from), } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index b105d411b1..658b2e08d8 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -742,7 +742,7 @@ Certain actions (shell commands or modifying files) may require explicit user ap Order of messages: 1. `item/started` — shows the pending `commandExecution` item with `command`, `cwd`, and other fields so you can render the proposed action. -2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access; any filesystem paths in that payload are absolute on the wire. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. Clients can prefer `availableDecisions` when present to render the exact set of choices the server wants to expose, while still falling back to the older heuristics if it is omitted. +2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access; any filesystem paths in that payload are absolute on the wire, and network access is represented as `additionalPermissions.network.enabled`. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. Clients can prefer `availableDecisions` when present to render the exact set of choices the server wants to expose, while still falling back to the older heuristics if it is omitted. 3. Client response — for example `{ "decision": "accept" }`, `{ "decision": "acceptForSession" }`, `{ "decision": { "acceptWithExecpolicyAmendment": { "execpolicy_amendment": [...] } } }`, `{ "decision": { "applyNetworkPolicyAmendment": { "network_policy_amendment": { "host": "example.com", "action": "allow" } } } }`, `{ "decision": "decline" }`, or `{ "decision": "cancel" }`. 4. `serverRequest/resolved` — `{ threadId, requestId }` confirms the pending request has been resolved or cleared, including lifecycle cleanup on turn start/complete/interrupt. 5. `item/completed` — final `commandExecution` item with `status: "completed" | "failed" | "declined"` and execution output. Render this as the authoritative result. diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index fe7d077bb8..10c5d71da2 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -193,7 +193,12 @@ fn merge_network_access( base_network_access: bool, additional_permissions: &PermissionProfile, ) -> bool { - base_network_access || matches!(additional_permissions.network, Some(true)) + base_network_access + || additional_permissions + .network + .as_ref() + .and_then(|network| network.enabled) + .unwrap_or(false) } fn sandbox_policy_with_additional_permissions( @@ -431,6 +436,7 @@ mod tests { use crate::tools::sandboxing::SandboxablePreference; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::FileSystemPermissions; + use codex_protocol::models::NetworkPermissions; use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; use dunce::canonicalize; @@ -470,7 +476,9 @@ mod tests { ) .expect("absolute temp dir"); let permissions = normalize_additional_permissions(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), file_system: Some(FileSystemPermissions { read: Some(vec![path.clone()]), write: Some(vec![path.clone()]), @@ -479,7 +487,12 @@ mod tests { }) .expect("permissions"); - assert_eq!(permissions.network, Some(true)); + assert_eq!( + permissions.network, + Some(NetworkPermissions { + enabled: Some(true), + }) + ); assert_eq!( permissions.file_system, Some(FileSystemPermissions { @@ -505,7 +518,9 @@ mod tests { network_access: false, }, &PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), file_system: Some(FileSystemPermissions { read: Some(vec![path.clone()]), write: Some(Vec::new()), diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index bfa22cf01b..751fa07200 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -32,6 +32,8 @@ use tracing::error; #[cfg(test)] use crate::config::Config; +#[cfg(test)] +use codex_protocol::models::NetworkPermissions; #[derive(Debug, Deserialize)] struct SkillFrontmatter { @@ -1387,7 +1389,8 @@ policy: {} skill_dir, r#" permissions: - network: true + network: + enabled: true file_system: read: - "./data" @@ -1408,7 +1411,9 @@ permissions: assert_eq!( outcome.skills[0].permission_profile, Some(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), file_system: Some(FileSystemPermissions { read: Some(vec![ AbsolutePathBuf::try_from(normalized(skill_dir.join("data").as_path())) diff --git a/codex-rs/core/src/skills/permissions.rs b/codex-rs/core/src/skills/permissions.rs index 825128307d..53b1f7bd93 100644 --- a/codex-rs/core/src/skills/permissions.rs +++ b/codex-rs/core/src/skills/permissions.rs @@ -44,7 +44,7 @@ pub(crate) fn compile_permission_profile( file_system, macos, } = permissions?; - let network_access = network.unwrap_or_default(); + let network_access = network.and_then(|value| value.enabled).unwrap_or_default(); let file_system = file_system.unwrap_or_default(); let fs_read = normalize_permission_paths( file_system.read.as_deref().unwrap_or_default(), @@ -232,6 +232,7 @@ mod tests { use codex_protocol::models::MacOsPermissions; #[cfg(target_os = "macos")] use codex_protocol::models::MacOsPreferencesValue; + use codex_protocol::models::NetworkPermissions; use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; @@ -251,7 +252,9 @@ mod tests { fs::create_dir_all(&read_dir).expect("read dir"); let profile = compile_permission_profile(Some(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), file_system: Some(FileSystemPermissions { read: Some(vec![ absolute_path(&skill_dir.join("data")), @@ -318,7 +321,9 @@ mod tests { fs::create_dir_all(&skill_dir).expect("skill dir"); let profile = compile_permission_profile(Some(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), ..Default::default() })) .expect("profile"); @@ -353,7 +358,9 @@ mod tests { fs::create_dir_all(&read_dir).expect("read dir"); let profile = compile_permission_profile(Some(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), file_system: Some(FileSystemPermissions { read: Some(vec![absolute_path(&skill_dir.join("data"))]), write: Some(Vec::new()), diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 8be7c9abf3..d12eef3b30 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -84,6 +84,17 @@ impl MacOsPermissions { } } +#[derive(Debug, Clone, Default, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TS)] +pub struct NetworkPermissions { + pub enabled: Option, +} + +impl NetworkPermissions { + pub fn is_empty(&self) -> bool { + self.enabled.is_none() + } +} + #[derive(Debug, Clone, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TS)] #[serde(untagged)] pub enum MacOsPreferencesValue { @@ -126,14 +137,17 @@ pub struct MacOsSeatbeltProfileExtensions { #[derive(Debug, Clone, Default, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TS)] pub struct PermissionProfile { - pub network: Option, + pub network: Option, pub file_system: Option, pub macos: Option, } impl PermissionProfile { pub fn is_empty(&self) -> bool { - self.network.is_none() + self.network + .as_ref() + .map(NetworkPermissions::is_empty) + .unwrap_or(true) && self .file_system .as_ref() diff --git a/codex-rs/shell-escalation/src/unix/escalate_server.rs b/codex-rs/shell-escalation/src/unix/escalate_server.rs index bb45c3ed71..92d9adb9d3 100644 --- a/codex-rs/shell-escalation/src/unix/escalate_server.rs +++ b/codex-rs/shell-escalation/src/unix/escalate_server.rs @@ -277,6 +277,7 @@ async fn handle_escalate_session_with_policy( mod tests { use super::*; use codex_protocol::approvals::EscalationPermissions; + use codex_protocol::models::NetworkPermissions; use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; @@ -513,14 +514,18 @@ mod tests { Arc::new(DeterministicEscalationPolicy { decision: EscalationDecision::escalate(EscalationExecution::Permissions( EscalationPermissions::PermissionProfile(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), ..Default::default() }), )), }), Arc::new(PermissionAssertingShellCommandExecutor { expected_permissions: EscalationPermissions::PermissionProfile(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), ..Default::default() }), }), diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 548be75769..21f0261cf1 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -641,7 +641,12 @@ fn format_additional_permissions_rule( additional_permissions: &PermissionProfile, ) -> Option { let mut parts = Vec::new(); - if matches!(additional_permissions.network, Some(true)) { + if additional_permissions + .network + .as_ref() + .and_then(|network| network.enabled) + .unwrap_or(false) + { parts.push("network".to_string()); } if let Some(file_system) = additional_permissions.file_system.as_ref() { @@ -721,6 +726,7 @@ mod tests { use super::*; use crate::app_event::AppEvent; use codex_protocol::models::FileSystemPermissions; + use codex_protocol::models::NetworkPermissions; use codex_protocol::protocol::ExecPolicyAmendment; use codex_protocol::protocol::NetworkApprovalProtocol; use codex_protocol::protocol::NetworkPolicyAmendment; @@ -1077,7 +1083,9 @@ mod tests { available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, additional_permissions: Some(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), file_system: Some(FileSystemPermissions { read: Some(vec![absolute_path("/tmp/readme.txt")]), write: Some(vec![absolute_path("/tmp/out.txt")]), @@ -1123,7 +1131,9 @@ mod tests { available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, additional_permissions: Some(PermissionProfile { - network: Some(true), + network: Some(NetworkPermissions { + enabled: Some(true), + }), file_system: Some(FileSystemPermissions { read: Some(vec![absolute_path("/tmp/readme.txt")]), write: Some(vec![absolute_path("/tmp/out.txt")]), From 7134220f3c1a5119cc0ea775b1807fe186b8a614 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Tue, 3 Mar 2026 21:44:52 -0800 Subject: [PATCH 363/385] core: box wrapper futures to reduce stack pressure (#13429) Follow-up to [#13388](https://github.com/openai/codex/pull/13388). This uses the same general fix pattern as [#12421](https://github.com/openai/codex/pull/12421), but in the `codex-core` compact/resume/fork path. ## Why `compact_resume_after_second_compaction_preserves_history` started overflowing the stack on Windows CI after `#13388`. The important part is that this was not a compaction-recursion bug. The test exercises a path with several thin `async fn` wrappers around much larger thread-spawn, resume, and fork futures. When one `async fn` awaits another inline, the outer future stores the callee future as part of its own state machine. In a long wrapper chain, that means a caller can accidentally inline a lot more state than the source code suggests. That is exactly what was happening here: - `ThreadManager` convenience methods such as `start_thread`, `resume_thread_from_rollout`, and `fork_thread` were inlining the larger spawn/resume futures beneath them. - `core_test_support::test_codex` added another wrapper layer on top of those same paths. - `compact_resume_fork` adds a few more helpers, and this particular test drives the resume/fork path multiple times. On Windows, that was enough to push both the libtest thread and Tokio worker threads over the edge. The previous 8 MiB test-thread workaround proved the failure was stack-related, but it did not address the underlying future size. ## How This Was Debugged The useful debugging pattern here was to turn the CI-only failure into a local low-stack repro. 1. First, remove the explicit large-stack harness so the test runs on the normal `#[tokio::test]` path. 2. Build the test binary normally. 3. Re-run the already-built `tests/all` binary directly with progressively smaller `RUST_MIN_STACK` values. Running the built binary directly matters: it keeps the reduced stack size focused on the test process instead of also applying it to `cargo` and `rustc`. That made it possible to answer two questions quickly: - Does the failure still reproduce without the workaround? Yes. - Does boxing the wrapper futures actually buy back stack headroom? Also yes. After this change, the built test binary passes with `RUST_MIN_STACK=917504` and still overflows at `786432`, which is enough evidence to justify removing the explicit 8 MiB override while keeping a deterministic low-stack repro for future debugging. If we hit a similar issue again, the first places to inspect are thin `async fn` wrappers that mostly forward into a much larger async implementation. ## `Box::pin()` Primer `async fn` compiles into a state machine. If a wrapper does this: ```rust async fn wrapper() { inner().await; } ``` then `wrapper()` stores the full `inner()` future inline as part of its own state. If the wrapper instead does this: ```rust async fn wrapper() { Box::pin(inner()).await; } ``` then the child future lives on the heap, and the outer future only stores a pinned pointer to it. That usually trades one allocation for a substantially smaller outer future, which is exactly the tradeoff we want when the problem is stack pressure rather than raw CPU time. Useful references: - [`Box::pin`](https://doc.rust-lang.org/std/boxed/struct.Box.html#method.pin) - [Async book: Pinning](https://rust-lang.github.io/async-book/04_pinning/01_chapter.html) ## What Changed - Boxed the wrapper futures in `core/src/thread_manager.rs` around `start_thread`, `resume_thread_from_rollout`, `fork_thread`, and the corresponding `ThreadManagerState` spawn helpers so callers no longer inline the full spawn/resume state machine through multiple layers. - Boxed the matching test-only wrapper futures in `core/tests/common/test_codex.rs` and `core/tests/suite/compact_resume_fork.rs`, which sit directly on top of the same path. - Restored `compact_resume_after_second_compaction_preserves_history` in `core/tests/suite/compact_resume_fork.rs` to a normal `#[tokio::test]` and removed the explicit `TEST_STACK_SIZE_BYTES` thread/runtime sizing. - Simplified a tiny helper in `compact_resume_fork` by making `fetch_conversation_path()` synchronous, which removes one more unnecessary future layer from the test path. ## Verification - `cargo test -p codex-core --test all suite::compact_resume_fork::compact_resume_after_second_compaction_preserves_history -- --exact --nocapture` - `cargo test -p codex-core --test all suite::compact_resume_fork -- --nocapture` - Re-ran the built `codex-core` `tests/all` binary directly with reduced stack sizes: - `RUST_MIN_STACK=917504` passes - `RUST_MIN_STACK=786432` still overflows - `cargo test -p codex-core` - Still fails locally in unrelated existing integration areas that expect the `codex` / `test_stdio_server` binaries or hit the existing `search_tool` wiremock mismatches. --- codex-rs/core/src/thread_manager.rs | 94 +++++++++---------- codex-rs/core/tests/common/test_codex.rs | 25 ++--- .../core/tests/suite/compact_resume_fork.rs | 49 +++------- 3 files changed, 72 insertions(+), 96 deletions(-) diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 2723ad955c..68ccae1776 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -312,8 +312,9 @@ impl ThreadManager { } pub async fn start_thread(&self, config: Config) -> CodexResult { - self.start_thread_with_tools(config, Vec::new(), false) - .await + // Box delegated thread-spawn futures so these convenience wrappers do + // not inline the full spawn path into every caller's async state. + Box::pin(self.start_thread_with_tools(config, Vec::new(), false)).await } pub async fn start_thread_with_tools( @@ -322,12 +323,12 @@ impl ThreadManager { dynamic_tools: Vec, persist_extended_history: bool, ) -> CodexResult { - self.start_thread_with_tools_and_service_name( + Box::pin(self.start_thread_with_tools_and_service_name( config, dynamic_tools, persist_extended_history, None, - ) + )) .await } @@ -338,17 +339,16 @@ impl ThreadManager { persist_extended_history: bool, metrics_service_name: Option, ) -> CodexResult { - self.state - .spawn_thread( - config, - InitialHistory::New, - Arc::clone(&self.state.auth_manager), - self.agent_control(), - dynamic_tools, - persist_extended_history, - metrics_service_name, - ) - .await + Box::pin(self.state.spawn_thread( + config, + InitialHistory::New, + Arc::clone(&self.state.auth_manager), + self.agent_control(), + dynamic_tools, + persist_extended_history, + metrics_service_name, + )) + .await } pub async fn resume_thread_from_rollout( @@ -358,7 +358,7 @@ impl ThreadManager { auth_manager: Arc, ) -> CodexResult { let initial_history = RolloutRecorder::get_rollout_history(&rollout_path).await?; - self.resume_thread_with_history(config, initial_history, auth_manager, false) + Box::pin(self.resume_thread_with_history(config, initial_history, auth_manager, false)) .await } @@ -369,17 +369,16 @@ impl ThreadManager { auth_manager: Arc, persist_extended_history: bool, ) -> CodexResult { - self.state - .spawn_thread( - config, - initial_history, - auth_manager, - self.agent_control(), - Vec::new(), - persist_extended_history, - None, - ) - .await + Box::pin(self.state.spawn_thread( + config, + initial_history, + auth_manager, + self.agent_control(), + Vec::new(), + persist_extended_history, + None, + )) + .await } /// Removes the thread from the manager's internal map, though the thread is stored @@ -411,17 +410,16 @@ impl ThreadManager { ) -> CodexResult { let history = RolloutRecorder::get_rollout_history(&path).await?; let history = truncate_before_nth_user_message(history, nth_user_message); - self.state - .spawn_thread( - config, - history, - Arc::clone(&self.state.auth_manager), - self.agent_control(), - Vec::new(), - persist_extended_history, - None, - ) - .await + Box::pin(self.state.spawn_thread( + config, + history, + Arc::clone(&self.state.auth_manager), + self.agent_control(), + Vec::new(), + persist_extended_history, + None, + )) + .await } pub(crate) fn agent_control(&self) -> AgentControl { @@ -474,14 +472,14 @@ impl ThreadManagerState { config: Config, agent_control: AgentControl, ) -> CodexResult { - self.spawn_new_thread_with_source( + Box::pin(self.spawn_new_thread_with_source( config, agent_control, self.session_source.clone(), false, None, None, - ) + )) .await } @@ -494,7 +492,7 @@ impl ThreadManagerState { metrics_service_name: Option, inherited_shell_snapshot: Option>, ) -> CodexResult { - self.spawn_thread_with_source( + Box::pin(self.spawn_thread_with_source( config, InitialHistory::New, Arc::clone(&self.auth_manager), @@ -504,7 +502,7 @@ impl ThreadManagerState { persist_extended_history, metrics_service_name, inherited_shell_snapshot, - ) + )) .await } @@ -517,7 +515,7 @@ impl ThreadManagerState { inherited_shell_snapshot: Option>, ) -> CodexResult { let initial_history = RolloutRecorder::get_rollout_history(&rollout_path).await?; - self.spawn_thread_with_source( + Box::pin(self.spawn_thread_with_source( config, initial_history, Arc::clone(&self.auth_manager), @@ -527,7 +525,7 @@ impl ThreadManagerState { false, None, inherited_shell_snapshot, - ) + )) .await } @@ -540,7 +538,7 @@ impl ThreadManagerState { persist_extended_history: bool, inherited_shell_snapshot: Option>, ) -> CodexResult { - self.spawn_thread_with_source( + Box::pin(self.spawn_thread_with_source( config, initial_history, Arc::clone(&self.auth_manager), @@ -550,7 +548,7 @@ impl ThreadManagerState { persist_extended_history, None, inherited_shell_snapshot, - ) + )) .await } @@ -566,7 +564,7 @@ impl ThreadManagerState { persist_extended_history: bool, metrics_service_name: Option, ) -> CodexResult { - self.spawn_thread_with_source( + Box::pin(self.spawn_thread_with_source( config, initial_history, auth_manager, @@ -576,7 +574,7 @@ impl ThreadManagerState { persist_extended_history, metrics_service_name, None, - ) + )) .await } diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index a79838df00..7bd5763d19 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -105,7 +105,7 @@ impl TestCodexBuilder { Some(home) => home, None => Arc::new(TempDir::new()?), }; - self.build_with_home(server, home, None).await + Box::pin(self.build_with_home(server, home, None)).await } pub async fn build_with_streaming_server( @@ -117,8 +117,7 @@ impl TestCodexBuilder { Some(home) => home, None => Arc::new(TempDir::new()?), }; - self.build_with_home_and_base_url(format!("{base_url}/v1"), home, None) - .await + Box::pin(self.build_with_home_and_base_url(format!("{base_url}/v1"), home, None)).await } pub async fn build_with_websocket_server( @@ -139,8 +138,7 @@ impl TestCodexBuilder { .enable(Feature::ResponsesWebsockets) .expect("test config should allow feature update"); })); - self.build_with_home_and_base_url(base_url, home, None) - .await + Box::pin(self.build_with_home_and_base_url(base_url, home, None)).await } pub async fn resume( @@ -149,7 +147,7 @@ impl TestCodexBuilder { home: Arc, rollout_path: PathBuf, ) -> anyhow::Result { - self.build_with_home(server, home, Some(rollout_path)).await + Box::pin(self.build_with_home(server, home, Some(rollout_path))).await } async fn build_with_home( @@ -160,7 +158,7 @@ impl TestCodexBuilder { ) -> anyhow::Result { let base_url = format!("{}/v1", server.uri()); let (config, cwd) = self.prepare_config(base_url, &home).await?; - self.build_from_config(config, cwd, home, resume_from).await + Box::pin(self.build_from_config(config, cwd, home, resume_from)).await } async fn build_with_home_and_base_url( @@ -170,7 +168,7 @@ impl TestCodexBuilder { resume_from: Option, ) -> anyhow::Result { let (config, cwd) = self.prepare_config(base_url, &home).await?; - self.build_from_config(config, cwd, home, resume_from).await + Box::pin(self.build_from_config(config, cwd, home, resume_from)).await } async fn build_from_config( @@ -201,11 +199,14 @@ impl TestCodexBuilder { let new_conversation = match resume_from { Some(path) => { let auth_manager = codex_core::test_support::auth_manager_from_auth(auth); - thread_manager - .resume_thread_from_rollout(config.clone(), path, auth_manager) - .await? + Box::pin(thread_manager.resume_thread_from_rollout( + config.clone(), + path, + auth_manager, + )) + .await? } - None => thread_manager.start_thread(config.clone()).await?, + None => Box::pin(thread_manager.start_thread(config.clone())).await?, }; Ok(TestCodex { diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index fe536077a3..be79c11708 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -157,7 +157,7 @@ async fn compact_resume_and_fork_preserve_model_history_view() { user_turn(&base, "hello world").await; compact_conversation(&base).await; user_turn(&base, "AFTER_COMPACT").await; - let base_path = fetch_conversation_path(&base).await; + let base_path = fetch_conversation_path(&base); assert!( base_path.exists(), "compact+resume test expects base path {base_path:?} to exist", @@ -165,7 +165,7 @@ async fn compact_resume_and_fork_preserve_model_history_view() { let resumed = resume_conversation(&manager, &config, base_path).await; user_turn(&resumed, "AFTER_RESUME").await; - let resumed_path = fetch_conversation_path(&resumed).await; + let resumed_path = fetch_conversation_path(&resumed); assert!( resumed_path.exists(), "compact+resume test expects resumed path {resumed_path:?} to exist", @@ -292,33 +292,10 @@ async fn compact_resume_and_fork_preserve_model_history_view() { assert_eq!(requests.len(), 5); } -#[test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] /// Scenario: after the forked branch is compacted, resuming again should reuse /// the compacted history and only append the new user message. -fn compact_resume_after_second_compaction_preserves_history() -> Result<()> { - const TEST_STACK_SIZE_BYTES: usize = 8 * 1024 * 1024; - - let handle = std::thread::Builder::new() - .name("compact_resume_after_second_compaction_preserves_history".to_string()) - .stack_size(TEST_STACK_SIZE_BYTES) - .spawn(|| -> Result<()> { - let runtime = tokio::runtime::Builder::new_multi_thread() - .worker_threads(2) - .thread_stack_size(TEST_STACK_SIZE_BYTES) - .enable_all() - .build()?; - runtime.block_on(compact_resume_after_second_compaction_preserves_history_impl()) - })?; - - match handle.join() { - Ok(result) => result, - Err(_) => Err(anyhow::anyhow!( - "compact_resume_after_second_compaction_preserves_history thread panicked" - )), - } -} - -async fn compact_resume_after_second_compaction_preserves_history_impl() -> Result<()> { +async fn compact_resume_after_second_compaction_preserves_history() -> Result<()> { if network_disabled() { println!("Skipping test because network is disabled in this sandbox"); return Ok(()); @@ -335,7 +312,7 @@ async fn compact_resume_after_second_compaction_preserves_history_impl() -> Resu user_turn(&base, "hello world").await; compact_conversation(&base).await; user_turn(&base, "AFTER_COMPACT").await; - let base_path = fetch_conversation_path(&base).await; + let base_path = fetch_conversation_path(&base); assert!( base_path.exists(), "second compact test expects base path {base_path:?} to exist", @@ -343,7 +320,7 @@ async fn compact_resume_after_second_compaction_preserves_history_impl() -> Resu let resumed = resume_conversation(&manager, &config, base_path).await; user_turn(&resumed, "AFTER_RESUME").await; - let resumed_path = fetch_conversation_path(&resumed).await; + let resumed_path = fetch_conversation_path(&resumed); assert!( resumed_path.exists(), "second compact test expects resumed path {resumed_path:?} to exist", @@ -354,7 +331,7 @@ async fn compact_resume_after_second_compaction_preserves_history_impl() -> Resu compact_conversation(&forked).await; user_turn(&forked, "AFTER_COMPACT_2").await; - let forked_path = fetch_conversation_path(&forked).await; + let forked_path = fetch_conversation_path(&forked); assert!( forked_path.exists(), "second compact test expects forked path {forked_path:?} to exist", @@ -558,7 +535,9 @@ async fn start_test_conversation( config.model = Some(model); } }); - let test = builder.build(server).await.expect("create conversation"); + let test = Box::pin(builder.build(server)) + .await + .expect("create conversation"); (test.home, test.config, test.thread_manager, test.codex) } @@ -595,7 +574,7 @@ async fn compact_conversation(conversation: &Arc) { wait_for_event(conversation, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; } -async fn fetch_conversation_path(conversation: &Arc) -> std::path::PathBuf { +fn fetch_conversation_path(conversation: &Arc) -> std::path::PathBuf { conversation.rollout_path().expect("rollout path") } @@ -607,8 +586,7 @@ async fn resume_conversation( let auth_manager = codex_core::test_support::auth_manager_from_auth( codex_core::CodexAuth::from_api_key("dummy"), ); - manager - .resume_thread_from_rollout(config.clone(), path, auth_manager) + Box::pin(manager.resume_thread_from_rollout(config.clone(), path, auth_manager)) .await .expect("resume conversation") .thread @@ -621,8 +599,7 @@ async fn fork_thread( path: std::path::PathBuf, nth_user_message: usize, ) -> Arc { - manager - .fork_thread(nth_user_message, config.clone(), path, false) + Box::pin(manager.fork_thread(nth_user_message, config.clone(), path, false)) .await .expect("fork conversation") .thread From 4f6c4bb143a9c53ea762194248c95e85bf0ac9d3 Mon Sep 17 00:00:00 2001 From: Val Kharitonov Date: Tue, 3 Mar 2026 22:46:05 -0800 Subject: [PATCH 364/385] support 'flex' tier in app-server in addition to 'fast' (#13391) --- .../schema/json/ClientRequest.json | 3 +- .../schema/json/EventMsg.json | 3 +- .../codex_app_server_protocol.schemas.json | 3 +- .../codex_app_server_protocol.v2.schemas.json | 3 +- .../schema/json/v2/ConfigReadResponse.json | 3 +- .../schema/json/v2/ThreadForkParams.json | 3 +- .../schema/json/v2/ThreadForkResponse.json | 3 +- .../schema/json/v2/ThreadResumeParams.json | 3 +- .../schema/json/v2/ThreadResumeResponse.json | 3 +- .../schema/json/v2/ThreadStartParams.json | 3 +- .../schema/json/v2/ThreadStartResponse.json | 3 +- .../schema/json/v2/TurnStartParams.json | 3 +- .../schema/typescript/ServiceTier.ts | 2 +- codex-rs/app-server/README.md | 3 ++ .../app-server/tests/suite/v2/thread_start.rs | 29 +++++++++++++++++++ codex-rs/core/config.schema.json | 5 ++-- codex-rs/core/src/client.rs | 3 +- codex-rs/core/src/client_common.rs | 26 +++++++++++++++++ codex-rs/core/src/config/mod.rs | 21 +++++++------- codex-rs/core/tests/suite/model_switching.rs | 20 +++++++++++++ codex-rs/protocol/src/config_types.rs | 1 + codex-rs/tui/src/chatwidget.rs | 7 +++-- 22 files changed, 123 insertions(+), 30 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 509d442678..1ae43c01b2 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -1728,7 +1728,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index cafd8bc5d0..fa1df138e6 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -5460,7 +5460,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 94e9f3a50c..a217af3106 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -12134,7 +12134,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 0d1de74481..b2e21a80f4 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -10770,7 +10770,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json index 626db8daeb..dd0a86fe91 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -707,7 +707,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json index ff0bf3f044..d4ef3effdb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json @@ -53,7 +53,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" } diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 41f4c9b7bb..896546347e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -744,7 +744,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json index 91850f60e5..a401c2141a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -759,7 +759,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 416bceb6e0..e712036051 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -744,7 +744,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json index 311b7b40cd..0cdc8d4598 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json @@ -78,7 +78,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" } diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 25db79cf24..57098610c8 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -744,7 +744,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json index 9e749d5b81..b1d5febacc 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -305,7 +305,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/typescript/ServiceTier.ts b/codex-rs/app-server-protocol/schema/typescript/ServiceTier.ts index bb2b5103e6..ce11286dbd 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServiceTier.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServiceTier.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type ServiceTier = "fast"; +export type ServiceTier = "fast" | "flex"; diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 658b2e08d8..068d4ee18e 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -180,6 +180,7 @@ Start a fresh thread when you need a new Codex conversation. "approvalPolicy": "never", "sandbox": "workspaceWrite", "personality": "friendly", + "serviceTier": "flex", "serviceName": "my_app_server_client", // optional metrics tag (`service_name`) // Experimental: requires opt-in "dynamicTools": [ @@ -208,6 +209,7 @@ Start a fresh thread when you need a new Codex conversation. ``` Valid `personality` values are `"friendly"`, `"pragmatic"`, and `"none"`. When `"none"` is selected, the personality placeholder is replaced with an empty string. +Valid `serviceTier` values are `"fast"` and `"flex"`. To continue a stored session, call `thread/resume` with the `thread.id` you previously recorded. The response shape matches `thread/start`, and no additional notifications are emitted. You can also pass the same configuration overrides supported by `thread/start`, such as `personality`: @@ -415,6 +417,7 @@ You can optionally specify config overrides on the new turn. If specified, these "networkAccess": true }, "model": "gpt-5.1-codex", + "serviceTier": "flex", "effort": "medium", "summary": "concise", "personality": "friendly", diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index 57eddd195a..bc383a19d1 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -12,6 +12,7 @@ use codex_app_server_protocol::ThreadStartedNotification; use codex_app_server_protocol::ThreadStatus; use codex_app_server_protocol::ThreadStatusChangedNotification; use codex_core::config::set_project_trust_level; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::TrustLevel; use codex_protocol::openai_models::ReasoningEffort; use pretty_assertions::assert_eq; @@ -180,6 +181,34 @@ model_reasoning_effort = "high" Ok(()) } +#[tokio::test] +async fn thread_start_accepts_flex_service_tier() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let req_id = mcp + .send_thread_start_request(ThreadStartParams { + service_tier: Some(Some(ServiceTier::Flex)), + ..Default::default() + }) + .await?; + + let resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(req_id)), + ) + .await??; + let ThreadStartResponse { service_tier, .. } = to_response::(resp)?; + + assert_eq!(service_tier, Some(ServiceTier::Flex)); + Ok(()) +} + #[tokio::test] async fn thread_start_accepts_metrics_service_name() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 71d624d2c0..3a108b854b 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1336,7 +1336,8 @@ }, "ServiceTier": { "enum": [ - "fast" + "fast", + "flex" ], "type": "string" }, @@ -2146,7 +2147,7 @@ "$ref": "#/definitions/ServiceTier" } ], - "description": "Optional explicit service tier preference for new turns." + "description": "Optional explicit service tier preference for new turns (`fast` or `flex`)." }, "shell_environment_policy": { "allOf": [ diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index d81c10f396..7479623cbd 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -546,7 +546,8 @@ impl ModelClientSession { include, service_tier: match service_tier { Some(ServiceTier::Fast) => Some("priority".to_string()), - _ => None, + Some(service_tier) => Some(service_tier.to_string()), + None => None, }, prompt_cache_key, text, diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index cddf99d6f5..21c4c56660 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -234,6 +234,7 @@ mod tests { use codex_api::common::OpenAiVerbosity; use codex_api::common::TextControls; use codex_api::create_text_param_for_request; + use codex_protocol::config_types::ServiceTier; use codex_protocol::models::FunctionCallOutputPayload; use pretty_assertions::assert_eq; @@ -342,6 +343,31 @@ mod tests { assert!(v.get("text").is_none()); } + #[test] + fn serializes_flex_service_tier_when_set() { + let req = ResponsesApiRequest { + model: "gpt-5.1".to_string(), + instructions: "i".to_string(), + input: vec![], + tools: vec![], + tool_choice: "auto".to_string(), + parallel_tool_calls: true, + reasoning: None, + store: false, + stream: true, + include: vec![], + prompt_cache_key: None, + service_tier: Some(ServiceTier::Flex.to_string()), + text: None, + }; + + let v = serde_json::to_value(&req).expect("json"); + assert_eq!( + v.get("service_tier").and_then(|tier| tier.as_str()), + Some("flex") + ); + } + #[test] fn reserializes_shell_outputs_for_function_and_custom_tool_calls() { let raw_output = r#"{"output":"hello","metadata":{"exit_code":0,"duration_seconds":0.5}}"#; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 2d833d8b51..ca99cce54b 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -189,7 +189,7 @@ pub struct Config { /// Optional override of model selection. pub model: Option, - /// Effective service tier preference for new turns. + /// Effective service tier preference for new turns (`fast` or `flex`). pub service_tier: Option, /// Model used specifically for review sessions. @@ -1191,7 +1191,7 @@ pub struct ConfigToml { /// Optionally specify a personality for the model pub personality: Option, - /// Optional explicit service tier preference for new turns. + /// Optional explicit service tier preference for new turns (`fast` or `flex`). pub service_tier: Option, /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). @@ -1984,15 +1984,14 @@ impl Config { let forced_login_method = cfg.forced_login_method; let model = model.or(config_profile.model).or(cfg.model); - let service_tier = if features.enabled(Feature::FastMode) { - service_tier_override.unwrap_or_else(|| { - config_profile - .service_tier - .or(cfg.service_tier) - .filter(|tier| matches!(tier, ServiceTier::Fast)) - }) - } else { - None + let service_tier = service_tier_override + .unwrap_or_else(|| config_profile.service_tier.or(cfg.service_tier)); + let service_tier = match service_tier { + Some(ServiceTier::Fast) if features.enabled(Feature::FastMode) => { + Some(ServiceTier::Fast) + } + Some(ServiceTier::Flex) => Some(ServiceTier::Flex), + _ => None, }; let compact_prompt = compact_prompt.or(cfg.compact_prompt).and_then(|value| { diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index df02d5e258..c58fb0fea8 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -22,6 +22,7 @@ use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed_with_tokens; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_models_once; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::sse_completed; @@ -247,6 +248,25 @@ async fn service_tier_change_is_applied_on_next_http_turn() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn flex_service_tier_is_applied_to_http_turn() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await; + + let test = test_codex().build(&server).await?; + + test.submit_turn_with_service_tier("flex turn", Some(ServiceTier::Flex)) + .await?; + + let request = resp_mock.single_request(); + let body = request.body_json(); + assert_eq!(body["service_tier"].as_str(), Some("flex")); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn model_change_from_image_to_text_strips_prior_image_content() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs index 984dcf39f1..b467d34857 100644 --- a/codex-rs/protocol/src/config_types.rs +++ b/codex-rs/protocol/src/config_types.rs @@ -118,6 +118,7 @@ pub enum WebSearchMode { #[strum(serialize_all = "lowercase")] pub enum ServiceTier { Fast, + Flex, } #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)] diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index e4e33e795a..840505f36b 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -3681,7 +3681,7 @@ impl ChatWidget { self.open_model_popup(); } SlashCommand::Fast => { - let next_tier = if self.config.service_tier.is_some() { + let next_tier = if matches!(self.config.service_tier, Some(ServiceTier::Fast)) { None } else { Some(ServiceTier::Fast) @@ -3976,7 +3976,8 @@ impl ChatWidget { "on" => self.set_service_tier_selection(Some(ServiceTier::Fast)), "off" => self.set_service_tier_selection(None), "status" => { - let status = if self.config.service_tier.is_some() { + let status = if matches!(self.config.service_tier, Some(ServiceTier::Fast)) + { "on" } else { "off" @@ -4342,7 +4343,7 @@ impl ChatWidget { .personality .filter(|_| self.config.features.enabled(Feature::Personality)) .filter(|_| self.current_model_supports_personality()); - let service_tier = self.fast_mode_enabled().then_some(self.config.service_tier); + let service_tier = self.config.service_tier.map(Some); let op = Op::UserTurn { items, cwd: self.config.cwd.clone(), From fa2306b303a8c7b1ef2ebb41117051bede08cb09 Mon Sep 17 00:00:00 2001 From: Won Park Date: Tue, 3 Mar 2026 23:11:28 -0800 Subject: [PATCH 365/385] image-gen-core (#13290) Core tool-calling for image-gen, handles requesting and receiving logic for images using response API --- .../schema/json/ClientRequest.json | 34 ++ .../schema/json/EventMsg.json | 34 ++ .../codex_app_server_protocol.schemas.json | 34 ++ .../codex_app_server_protocol.v2.schemas.json | 34 ++ .../RawResponseItemCompletedNotification.json | 34 ++ .../schema/json/v2/ThreadResumeParams.json | 34 ++ .../schema/typescript/ResponseItem.ts | 2 +- codex-rs/core/config.schema.json | 6 + codex-rs/core/src/client.rs | 1 - codex-rs/core/src/client_common.rs | 3 + codex-rs/core/src/compact_remote.rs | 1 + codex-rs/core/src/context_manager/history.rs | 9 +- .../core/src/context_manager/history_tests.rs | 91 ++++++ .../core/src/context_manager/normalize.rs | 28 +- codex-rs/core/src/features.rs | 14 + codex-rs/core/src/rollout/policy.rs | 2 + codex-rs/core/src/tools/spec.rs | 71 ++++- codex-rs/core/tests/common/responses.rs | 18 ++ codex-rs/core/tests/suite/model_switching.rs | 299 +++++++++++++++--- codex-rs/otel/src/traces/otel_manager.rs | 1 + codex-rs/protocol/src/models.rs | 60 ++++ codex-rs/protocol/src/openai_models.rs | 1 + 22 files changed, 766 insertions(+), 45 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 1ae43c01b2..e57ffa12c9 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -1416,6 +1416,40 @@ "title": "WebSearchCallResponseItem", "type": "object" }, + { + "properties": { + "id": { + "type": "string" + }, + "result": { + "type": "string" + }, + "revised_prompt": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "type": { + "enum": [ + "image_generation_call" + ], + "title": "ImageGenerationCallResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "result", + "status", + "type" + ], + "title": "ImageGenerationCallResponseItem", + "type": "object" + }, { "properties": { "ghost_commit": { diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index fa1df138e6..526d852a2e 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -4983,6 +4983,40 @@ "title": "WebSearchCallResponseItem", "type": "object" }, + { + "properties": { + "id": { + "type": "string" + }, + "result": { + "type": "string" + }, + "revised_prompt": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "type": { + "enum": [ + "image_generation_call" + ], + "title": "ImageGenerationCallResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "result", + "status", + "type" + ], + "title": "ImageGenerationCallResponseItem", + "type": "object" + }, { "properties": { "ghost_commit": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index a217af3106..2ccd20466c 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -11761,6 +11761,40 @@ "title": "WebSearchCallResponseItem", "type": "object" }, + { + "properties": { + "id": { + "type": "string" + }, + "result": { + "type": "string" + }, + "revised_prompt": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "type": { + "enum": [ + "image_generation_call" + ], + "title": "ImageGenerationCallResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "result", + "status", + "type" + ], + "title": "ImageGenerationCallResponseItem", + "type": "object" + }, { "properties": { "ghost_commit": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index b2e21a80f4..1bbea24c8a 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -9324,6 +9324,40 @@ "title": "WebSearchCallResponseItem", "type": "object" }, + { + "properties": { + "id": { + "type": "string" + }, + "result": { + "type": "string" + }, + "revised_prompt": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "type": { + "enum": [ + "image_generation_call" + ], + "title": "ImageGenerationCallResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "result", + "status", + "type" + ], + "title": "ImageGenerationCallResponseItem", + "type": "object" + }, { "properties": { "ghost_commit": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json index cedfdb19c4..cb14542607 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json @@ -641,6 +641,40 @@ "title": "WebSearchCallResponseItem", "type": "object" }, + { + "properties": { + "id": { + "type": "string" + }, + "result": { + "type": "string" + }, + "revised_prompt": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "type": { + "enum": [ + "image_generation_call" + ], + "title": "ImageGenerationCallResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "result", + "status", + "type" + ], + "title": "ImageGenerationCallResponseItem", + "type": "object" + }, { "properties": { "ghost_commit": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json index a401c2141a..3dce8b5df1 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -691,6 +691,40 @@ "title": "WebSearchCallResponseItem", "type": "object" }, + { + "properties": { + "id": { + "type": "string" + }, + "result": { + "type": "string" + }, + "revised_prompt": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "type": { + "enum": [ + "image_generation_call" + ], + "title": "ImageGenerationCallResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "result", + "status", + "type" + ], + "title": "ImageGenerationCallResponseItem", + "type": "object" + }, { "properties": { "ghost_commit": { diff --git a/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts b/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts index dd7621f01d..dc42485935 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts @@ -15,4 +15,4 @@ export type ResponseItem = { "type": "message", role: string, content: Array ApiResponsesOptions { let turn_metadata_header = parse_turn_metadata_header(turn_metadata_header); let conversation_id = self.client.state.conversation_id.to_string(); - ApiResponsesOptions { conversation_id: Some(conversation_id), session_source: Some(self.client.state.session_source.clone()), diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index 21c4c56660..50facf53e4 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -166,6 +166,8 @@ pub(crate) mod tools { Function(ResponsesApiTool), #[serde(rename = "local_shell")] LocalShell {}, + #[serde(rename = "image_generation")] + ImageGeneration {}, // TODO: Understand why we get an error on web_search although the API docs say it's supported. // https://platform.openai.com/docs/guides/tools-web-search?api-mode=responses#:~:text=%7B%20type%3A%20%22web_search%22%20%7D%2C // The `external_web_access` field determines whether the web search is over cached or live content. @@ -184,6 +186,7 @@ pub(crate) mod tools { match self { ToolSpec::Function(tool) => tool.name.as_str(), ToolSpec::LocalShell {} => "local_shell", + ToolSpec::ImageGeneration {} => "image_generation", ToolSpec::WebSearch { .. } => "web_search", ToolSpec::Freeform(tool) => tool.name.as_str(), } diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index 6d8368bce4..40c520f659 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -206,6 +206,7 @@ fn should_keep_compacted_history_item(item: &ResponseItem) -> bool { | ResponseItem::CustomToolCall { .. } | ResponseItem::CustomToolCallOutput { .. } | ResponseItem::WebSearchCall { .. } + | ResponseItem::ImageGenerationCall { .. } | ResponseItem::GhostSnapshot { .. } | ResponseItem::Other => false, } diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 40e0f31e41..1bafca4082 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -344,6 +344,9 @@ impl ContextManager { // all outputs must have a corresponding function/tool call normalize::remove_orphan_outputs(&mut self.items); + //rewrite image_gen_calls to messages to support stateless input + normalize::rewrite_image_generation_calls_for_stateless_input(&mut self.items); + // strip images when model does not support them normalize::strip_images_when_unsupported(input_modalities, &mut self.items); } @@ -374,6 +377,7 @@ impl ContextManager { | ResponseItem::LocalShellCall { .. } | ResponseItem::FunctionCall { .. } | ResponseItem::WebSearchCall { .. } + | ResponseItem::ImageGenerationCall { .. } | ResponseItem::CustomToolCall { .. } | ResponseItem::Compaction { .. } | ResponseItem::GhostSnapshot { .. } @@ -402,7 +406,8 @@ fn truncate_function_output_payload( } /// API messages include every non-system item (user/assistant messages, reasoning, -/// tool calls, tool outputs, shell calls, and web-search calls). +/// tool calls, tool outputs, shell calls, web-search calls, and image-generation +/// calls). fn is_api_message(message: &ResponseItem) -> bool { match message { ResponseItem::Message { role, .. } => role.as_str() != "system", @@ -413,6 +418,7 @@ fn is_api_message(message: &ResponseItem) -> bool { | ResponseItem::LocalShellCall { .. } | ResponseItem::Reasoning { .. } | ResponseItem::WebSearchCall { .. } + | ResponseItem::ImageGenerationCall { .. } | ResponseItem::Compaction { .. } => true, ResponseItem::GhostSnapshot { .. } => false, ResponseItem::Other => false, @@ -600,6 +606,7 @@ fn is_model_generated_item(item: &ResponseItem) -> bool { ResponseItem::Reasoning { .. } | ResponseItem::FunctionCall { .. } | ResponseItem::WebSearchCall { .. } + | ResponseItem::ImageGenerationCall { .. } | ResponseItem::CustomToolCall { .. } | ResponseItem::LocalShellCall { .. } | ResponseItem::Compaction { .. } => true, diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index 46aa462322..b678c2e6cb 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -395,6 +395,97 @@ fn for_prompt_strips_images_when_model_does_not_support_images() { } } +#[test] +fn for_prompt_rewrites_image_generation_calls_when_images_are_supported() { + let history = create_history_with_items(vec![ + ResponseItem::ImageGenerationCall { + id: "ig_123".to_string(), + status: "generating".to_string(), + revised_prompt: Some("lobster".to_string()), + result: "Zm9v".to_string(), + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "hi".to_string(), + }], + end_turn: None, + phase: None, + }, + ]); + + assert_eq!( + history.for_prompt(&default_input_modalities()), + vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputImage { + image_url: "data:image/png;base64,Zm9v".to_string(), + }], + end_turn: None, + phase: None, + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "hi".to_string(), + }], + end_turn: None, + phase: None, + } + ] + ); +} + +#[test] +fn for_prompt_rewrites_image_generation_calls_when_images_are_unsupported() { + let history = create_history_with_items(vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "generate a lobster".to_string(), + }], + end_turn: None, + phase: None, + }, + ResponseItem::ImageGenerationCall { + id: "ig_123".to_string(), + status: "completed".to_string(), + revised_prompt: Some("lobster".to_string()), + result: "Zm9v".to_string(), + }, + ]); + + assert_eq!( + history.for_prompt(&[InputModality::Text]), + vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "generate a lobster".to_string(), + }], + end_turn: None, + phase: None, + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "image content omitted because you do not support image input" + .to_string(), + }], + end_turn: None, + phase: None, + }, + ] + ); +} + #[test] fn get_history_for_prompt_drops_ghost_commits() { let items = vec![ResponseItem::GhostSnapshot { diff --git a/codex-rs/core/src/context_manager/normalize.rs b/codex-rs/core/src/context_manager/normalize.rs index 572ac51fc8..465edae41b 100644 --- a/codex-rs/core/src/context_manager/normalize.rs +++ b/codex-rs/core/src/context_manager/normalize.rs @@ -1,10 +1,9 @@ -use std::collections::HashSet; - use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::InputModality; +use std::collections::HashSet; use crate::util::error_or_panic; use tracing::info; @@ -211,6 +210,31 @@ where } } +pub(crate) fn rewrite_image_generation_calls_for_stateless_input(items: &mut Vec) { + let original_items = std::mem::take(items); + *items = original_items + .into_iter() + .map(|item| match item { + ResponseItem::ImageGenerationCall { result, .. } => { + let image_url = if result.starts_with("data:") { + result + } else { + format!("data:image/png;base64,{result}") + }; + + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputImage { image_url }], + end_turn: None, + phase: None, + } + } + _ => item, + }) + .collect(); +} + /// Strip image content from messages and tool outputs when the model does not support images. /// When `input_modalities` contains `InputModality::Image`, no stripping is performed. pub(crate) fn strip_images_when_unsupported( diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index ef6712fd00..dbc4e70685 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -131,6 +131,8 @@ pub enum Feature { Apps, /// Enable plugins. Plugins, + /// Allow the model to invoke the built-in image generation tool. + ImageGeneration, /// Route apps MCP calls through the configured gateway. AppsMcpGateway, /// Allow prompting and installing missing MCP dependencies. @@ -649,6 +651,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::ImageGeneration, + key: "image_generation", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::AppsMcpGateway, key: "apps_mcp_gateway", @@ -868,6 +876,12 @@ mod tests { assert_eq!(Feature::JsRepl.default_enabled(), false); } + #[test] + fn image_generation_is_under_development() { + assert_eq!(Feature::ImageGeneration.stage(), Stage::UnderDevelopment); + assert_eq!(Feature::ImageGeneration.default_enabled(), false); + } + #[test] fn collab_is_legacy_alias_for_multi_agent() { assert_eq!(feature_for_key("multi_agent"), Some(Feature::Collab)); diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 4c76bc54f6..9af54610e2 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -35,6 +35,7 @@ pub(crate) fn should_persist_response_item(item: &ResponseItem) -> bool { | ResponseItem::CustomToolCall { .. } | ResponseItem::CustomToolCallOutput { .. } | ResponseItem::WebSearchCall { .. } + | ResponseItem::ImageGenerationCall { .. } | ResponseItem::GhostSnapshot { .. } | ResponseItem::Compaction { .. } => true, ResponseItem::Other => false, @@ -53,6 +54,7 @@ pub(crate) fn should_persist_response_item_for_memories(item: &ResponseItem) -> | ResponseItem::CustomToolCallOutput { .. } | ResponseItem::WebSearchCall { .. } => true, ResponseItem::Reasoning { .. } + | ResponseItem::ImageGenerationCall { .. } | ResponseItem::GhostSnapshot { .. } | ResponseItem::Compaction { .. } | ResponseItem::Other => false, diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 0e53670750..3ff8bc50e1 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -23,6 +23,7 @@ use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::models::VIEW_IMAGE_TOOL_NAME; use codex_protocol::openai_models::ApplyPatchToolType; use codex_protocol::openai_models::ConfigShellToolType; +use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ModelInfo; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; @@ -35,7 +36,6 @@ use std::collections::HashMap; const SEARCH_TOOL_BM25_DESCRIPTION_TEMPLATE: &str = include_str!("../../templates/search_tool/tool_description.md"); - #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum ShellCommandBackendConfig { Classic, @@ -49,6 +49,7 @@ pub(crate) struct ToolsConfig { pub allow_login_shell: bool, pub apply_patch_tool_type: Option, pub web_search_mode: Option, + pub image_gen_tool: bool, pub agent_roles: BTreeMap, pub search_tool: bool, pub request_permission_enabled: bool, @@ -86,6 +87,8 @@ impl ToolsConfig { features.enabled(Feature::DefaultModeRequestUserInput); let include_search_tool = features.enabled(Feature::Apps); let include_artifact_tools = features.enabled(Feature::Artifact); + let include_image_gen_tool = + features.enabled(Feature::ImageGeneration) && supports_image_generation(model_info); let include_agent_jobs = include_collab_tools && features.enabled(Feature::Sqlite); let request_permission_enabled = features.enabled(Feature::RequestPermissions); let shell_command_backend = @@ -135,6 +138,7 @@ impl ToolsConfig { allow_login_shell: true, apply_patch_tool_type, web_search_mode: *web_search_mode, + image_gen_tool: include_image_gen_tool, agent_roles: BTreeMap::new(), search_tool: include_search_tool, request_permission_enabled, @@ -160,6 +164,10 @@ impl ToolsConfig { } } +fn supports_image_generation(model_info: &ModelInfo) -> bool { + model_info.input_modalities.contains(&InputModality::Image) +} + /// Generic JSON‑Schema subset needed for our tool definitions #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type", rename_all = "lowercase")] @@ -1917,6 +1925,10 @@ pub(crate) fn build_specs( Some(WebSearchMode::Disabled) | None => {} } + if config.image_gen_tool { + builder.push_spec(ToolSpec::ImageGeneration {}); + } + builder.push_spec_with_parallel_support(create_view_image_tool(), true); builder.register_handler("view_image", view_image_handler); @@ -1995,6 +2007,7 @@ mod tests { use crate::models_manager::manager::ModelsManager; use crate::models_manager::model_info::with_config_overrides; use crate::tools::registry::ConfiguredToolSpec; + use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelsResponse; use pretty_assertions::assert_eq; @@ -2047,6 +2060,7 @@ mod tests { match tool { ToolSpec::Function(ResponsesApiTool { name, .. }) => name, ToolSpec::LocalShell {} => "local_shell", + ToolSpec::ImageGeneration {} => "image_generation", ToolSpec::WebSearch { .. } => "web_search", ToolSpec::Freeform(FreeformTool { name, .. }) => name, } @@ -2125,7 +2139,10 @@ mod tests { ToolSpec::Function(ResponsesApiTool { parameters, .. }) => { strip_descriptions_schema(parameters); } - ToolSpec::Freeform(_) | ToolSpec::LocalShell {} | ToolSpec::WebSearch { .. } => {} + ToolSpec::Freeform(_) + | ToolSpec::LocalShell {} + | ToolSpec::ImageGeneration {} + | ToolSpec::WebSearch { .. } => {} } } @@ -2374,6 +2391,56 @@ mod tests { assert_contains_tool_names(&tools, &["js_repl", "js_repl_reset"]); } + #[test] + fn image_generation_tools_require_feature_and_supported_model() { + let config = test_config(); + let mut supported_model_info = + ModelsManager::construct_model_info_offline_for_tests("gpt-5.2", &config); + supported_model_info.slug = "custom/gpt-5.2-variant".to_string(); + let mut unsupported_model_info = supported_model_info.clone(); + unsupported_model_info.input_modalities = vec![InputModality::Text]; + let default_features = Features::with_defaults(); + let mut image_generation_features = default_features.clone(); + image_generation_features.enable(Feature::ImageGeneration); + + let default_tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &supported_model_info, + features: &default_features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + }); + let (default_tools, _) = build_specs(&default_tools_config, None, None, &[]).build(); + assert!( + !default_tools + .iter() + .any(|tool| tool.spec.name() == "image_generation"), + "image_generation should be disabled by default" + ); + + let supported_tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &supported_model_info, + features: &image_generation_features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + }); + let (supported_tools, _) = build_specs(&supported_tools_config, None, None, &[]).build(); + assert_contains_tool_names(&supported_tools, &["image_generation"]); + + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &unsupported_model_info, + features: &image_generation_features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + }); + let (tools, _) = build_specs(&tools_config, None, None, &[]).build(); + assert!( + !tools + .iter() + .any(|tool| tool.spec.name() == "image_generation"), + "image_generation should be disabled for unsupported models" + ); + } + #[test] fn js_repl_freeform_grammar_blocks_common_non_js_prefixes() { let ToolSpec::Freeform(FreeformTool { format, .. }) = create_js_repl_tool() else { diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 4f2e89636e..d07b155f61 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -739,6 +739,24 @@ pub fn ev_web_search_call_done(id: &str, status: &str, query: &str) -> Value { }) } +pub fn ev_image_generation_call( + id: &str, + status: &str, + revised_prompt: &str, + result: &str, +) -> Value { + serde_json::json!({ + "type": "response.output_item.done", + "item": { + "type": "image_generation_call", + "id": id, + "status": status, + "revised_prompt": revised_prompt, + "result": result, + } + }) +} + pub fn ev_function_call(call_id: &str, name: &str, arguments: &str) -> Value { serde_json::json!({ "type": "response.output_item.done", diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index c58fb0fea8..a93d0f751b 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -20,6 +20,7 @@ use codex_protocol::protocol::Op; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; use core_test_support::responses::ev_completed_with_tokens; +use core_test_support::responses::ev_image_generation_call; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_models_once; use core_test_support::responses::mount_sse_once; @@ -33,6 +34,47 @@ use core_test_support::wait_for_event; use pretty_assertions::assert_eq; use wiremock::MockServer; +fn test_model_info( + slug: &str, + display_name: &str, + description: &str, + input_modalities: Vec, +) -> ModelInfo { + ModelInfo { + slug: slug.to_string(), + display_name: display_name.to_string(), + description: Some(description.to_string()), + default_reasoning_level: Some(ReasoningEffort::Medium), + supported_reasoning_levels: vec![ReasoningEffortPreset { + effort: ReasoningEffort::Medium, + description: ReasoningEffort::Medium.to_string(), + }], + shell_type: ConfigShellToolType::ShellCommand, + visibility: ModelVisibility::List, + supported_in_api: true, + input_modalities, + prefer_websockets: false, + used_fallback_model_metadata: false, + priority: 1, + upgrade: None, + base_instructions: "base instructions".to_string(), + model_messages: None, + supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, + support_verbosity: false, + default_verbosity: None, + availability_nux: None, + apply_patch_tool_type: None, + truncation_policy: TruncationPolicyConfig::bytes(10_000), + supports_parallel_tool_calls: false, + supports_image_detail_original: false, + context_window: Some(272_000), + auto_compact_token_limit: None, + effective_context_window_percent: 95, + experimental_supported_tools: Vec::new(), + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn model_change_appends_model_instructions_developer_message() -> Result<()> { skip_if_no_network!(Ok(())); @@ -274,44 +316,18 @@ async fn model_change_from_image_to_text_strips_prior_image_content() -> Result< let server = MockServer::start().await; let image_model_slug = "test-image-model"; let text_model_slug = "test-text-only-model"; - let image_model = ModelInfo { - slug: image_model_slug.to_string(), - display_name: "Test Image Model".to_string(), - description: Some("supports image input".to_string()), - default_reasoning_level: Some(ReasoningEffort::Medium), - supported_reasoning_levels: vec![ReasoningEffortPreset { - effort: ReasoningEffort::Medium, - description: ReasoningEffort::Medium.to_string(), - }], - shell_type: ConfigShellToolType::ShellCommand, - visibility: ModelVisibility::List, - supported_in_api: true, - input_modalities: default_input_modalities(), - prefer_websockets: false, - used_fallback_model_metadata: false, - priority: 1, - upgrade: None, - base_instructions: "base instructions".to_string(), - model_messages: None, - supports_reasoning_summaries: false, - default_reasoning_summary: ReasoningSummary::Auto, - support_verbosity: false, - default_verbosity: None, - availability_nux: None, - apply_patch_tool_type: None, - truncation_policy: TruncationPolicyConfig::bytes(10_000), - supports_parallel_tool_calls: false, - supports_image_detail_original: false, - context_window: Some(272_000), - auto_compact_token_limit: None, - effective_context_window_percent: 95, - experimental_supported_tools: Vec::new(), - }; - let mut text_model = image_model.clone(); - text_model.slug = text_model_slug.to_string(); - text_model.display_name = "Test Text Model".to_string(); - text_model.description = Some("text only".to_string()); - text_model.input_modalities = vec![InputModality::Text]; + let image_model = test_model_info( + image_model_slug, + "Test Image Model", + "supports image input", + default_input_modalities(), + ); + let text_model = test_model_info( + text_model_slug, + "Test Text Model", + "text only", + vec![InputModality::Text], + ); mount_models_once( &server, ModelsResponse { @@ -421,6 +437,213 @@ async fn model_change_from_image_to_text_strips_prior_image_content() -> Result< Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn generated_image_is_replayed_for_image_capable_models() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::start().await; + let image_model_slug = "test-image-model"; + let image_model = test_model_info( + image_model_slug, + "Test Image Model", + "supports image input", + default_input_modalities(), + ); + mount_models_once( + &server, + ModelsResponse { + models: vec![image_model], + }, + ) + .await; + + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_image_generation_call("ig_123", "completed", "lobster", "Zm9v"), + ev_completed_with_tokens("resp-1", 10), + ]), + sse_completed("resp-2"), + ], + ) + .await; + + let mut builder = test_codex() + .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(move |config| { + config.model = Some(image_model_slug.to_string()); + }); + let test = builder.build(&server).await?; + let models_manager = test.thread_manager.get_models_manager(); + let _ = models_manager + .list_models(RefreshStrategy::OnlineIfUncached) + .await; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "generate a lobster".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + model: image_model_slug.to_string(), + effort: test.config.model_reasoning_effort, + service_tier: None, + summary: None, + collaboration_mode: None, + personality: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "describe the generated image".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + model: image_model_slug.to_string(), + effort: test.config.model_reasoning_effort, + service_tier: None, + summary: None, + collaboration_mode: None, + personality: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let second_request = requests.last().expect("expected second request"); + assert_eq!( + second_request.message_input_image_urls("user"), + vec!["data:image/png;base64,Zm9v".to_string()] + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn model_change_from_generated_image_to_text_strips_prior_generated_image_content() +-> Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::start().await; + let image_model_slug = "test-image-model"; + let text_model_slug = "test-text-only-model"; + let image_model = test_model_info( + image_model_slug, + "Test Image Model", + "supports image input", + default_input_modalities(), + ); + let text_model = test_model_info( + text_model_slug, + "Test Text Model", + "text only", + vec![InputModality::Text], + ); + mount_models_once( + &server, + ModelsResponse { + models: vec![image_model, text_model], + }, + ) + .await; + + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_image_generation_call("ig_123", "completed", "lobster", "Zm9v"), + ev_completed_with_tokens("resp-1", 10), + ]), + sse_completed("resp-2"), + ], + ) + .await; + + let mut builder = test_codex() + .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(move |config| { + config.model = Some(image_model_slug.to_string()); + }); + let test = builder.build(&server).await?; + let models_manager = test.thread_manager.get_models_manager(); + let _ = models_manager + .list_models(RefreshStrategy::OnlineIfUncached) + .await; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "generate a lobster".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + model: image_model_slug.to_string(), + effort: test.config.model_reasoning_effort, + service_tier: None, + summary: None, + collaboration_mode: None, + personality: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "describe the generated image".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + model: text_model_slug.to_string(), + effort: test.config.model_reasoning_effort, + service_tier: None, + summary: None, + collaboration_mode: None, + personality: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let second_request = requests.last().expect("expected second request"); + assert!( + second_request.message_input_image_urls("user").is_empty(), + "second request should strip generated image content for text-only models" + ); + assert!( + second_request + .message_input_texts("user") + .iter() + .any(|text| text == "image content omitted because you do not support image input"), + "second request should include the image-omitted placeholder text" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn model_switch_to_smaller_model_updates_token_context_window() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/otel/src/traces/otel_manager.rs b/codex-rs/otel/src/traces/otel_manager.rs index 1074b6edd1..aa11fce3b0 100644 --- a/codex-rs/otel/src/traces/otel_manager.rs +++ b/codex-rs/otel/src/traces/otel_manager.rs @@ -771,6 +771,7 @@ impl OtelManager { ResponseItem::CustomToolCall { .. } => "custom_tool_call".into(), ResponseItem::CustomToolCallOutput { .. } => "custom_tool_call_output".into(), ResponseItem::WebSearchCall { .. } => "web_search_call".into(), + ResponseItem::ImageGenerationCall { .. } => "image_generation_call".into(), ResponseItem::GhostSnapshot { .. } => "ghost_snapshot".into(), ResponseItem::Compaction { .. } => "compaction".into(), ResponseItem::Other => "other".into(), diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index d12eef3b30..90d9945b06 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -313,6 +313,23 @@ pub enum ResponseItem { #[ts(optional)] action: Option, }, + // Emitted by the Responses API when the agent triggers image generation. + // Example payload: + // { + // "id":"ig_123", + // "type":"image_generation_call", + // "status":"completed", + // "revised_prompt":"A gray tabby cat hugging an otter...", + // "result":"..." + // } + ImageGenerationCall { + id: String, + status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + revised_prompt: Option, + result: String, + }, // Generated by the harness but considered exactly as a model response. GhostSnapshot { ghost_commit: GhostCommit, @@ -1286,6 +1303,49 @@ mod tests { ); } + #[test] + fn response_item_parses_image_generation_call() { + let item = serde_json::from_value::(serde_json::json!({ + "id": "ig_123", + "type": "image_generation_call", + "status": "completed", + "revised_prompt": "A small blue square", + "result": "Zm9v", + })) + .expect("image generation item should deserialize"); + + assert_eq!( + item, + ResponseItem::ImageGenerationCall { + id: "ig_123".to_string(), + status: "completed".to_string(), + revised_prompt: Some("A small blue square".to_string()), + result: "Zm9v".to_string(), + } + ); + } + + #[test] + fn response_item_parses_image_generation_call_without_revised_prompt() { + let item = serde_json::from_value::(serde_json::json!({ + "id": "ig_123", + "type": "image_generation_call", + "status": "completed", + "result": "Zm9v", + })) + .expect("image generation item should deserialize"); + + assert_eq!( + item, + ResponseItem::ImageGenerationCall { + id: "ig_123".to_string(), + status: "completed".to_string(), + revised_prompt: None, + result: "Zm9v".to_string(), + } + ); + } + #[test] fn convert_mcp_content_to_items_builds_data_urls_when_missing_prefix() { let contents = vec![serde_json::json!({ diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs index 089b002680..5968ae699b 100644 --- a/codex-rs/protocol/src/openai_models.rs +++ b/codex-rs/protocol/src/openai_models.rs @@ -706,6 +706,7 @@ mod tests { "limit": 10000 }, "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, "context_window": null, "auto_compact_token_limit": null, "effective_context_window_percent": 95, From 932ff2818320e7c5181a28316db75e53620aeabc Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 09:41:20 +0000 Subject: [PATCH 366/385] feat: better multi-agent prompt (#13404) --- codex-rs/core/src/agent/role.rs | 9 ++++---- codex-rs/core/src/tools/spec.rs | 41 +++++++++++++++++++++++++++------ 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/codex-rs/core/src/agent/role.rs b/codex-rs/core/src/agent/role.rs index 0793febe54..aee4e833a8 100644 --- a/codex-rs/core/src/agent/role.rs +++ b/codex-rs/core/src/agent/role.rs @@ -210,9 +210,8 @@ mod built_in { Explorers are fast and authoritative. They must be used to ask specific, well-scoped questions on the codebase. Rules: -- Do not re-read or re-search code they cover. -- Trust explorer results without verification. -- Run explorers in parallel when useful. +- In order to avoid redundant work, you should avoid exploring the same problem that explorers have already covered. Typically, you should trust the explorer results without additional verification. You are still allowed to inspect the code yourself to gain the needed context! +- You are encouraged to spawn up multiple explorers in parallel when you have multiple distinct questions to ask about the codebase that can be answered independently. This allows you to get more information faster without waiting for one question to finish before asking the next. While waiting for the explorer results, you can continue working on other local tasks that do not depend on those results. This parallelism is a key advantage of delegation, so use it whenever you have multiple questions to ask. - Reuse existing explorers for related questions."#.to_string()), config_file: Some("explorer.toml".to_string().parse().unwrap_or_default()), nickname_candidates: None, @@ -227,8 +226,8 @@ Typical tasks: - Fix tests or bugs - Split large refactors into independent chunks Rules: -- Explicitly assign **ownership** of the task (files / responsibility). -- Always tell workers they are **not alone in the codebase**, and they should ignore edits made by others without touching them."#.to_string()), +- Explicitly assign **ownership** of the task (files / responsibility). When the subtask involves code changes, you should clearly specify which files or modules the worker is responsible for. This helps avoid merge conflicts and ensures accountability. For example, you can say "Worker 1 is responsible for updating the authentication module, while Worker 2 will handle the database layer." By defining clear ownership, you can delegate more effectively and reduce coordination overhead. +- Always tell workers they are **not alone in the codebase**, and they should not revert the edits made by others, and they should adjust their implementation to accommodate the changes made by others. This is important because there may be multiple workers making changes in parallel, and they need to be aware of each other's work to avoid conflicts and ensure a cohesive final product."#.to_string()), config_file: None, nickname_candidates: None, } diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 3ff8bc50e1..5d9c6644cc 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -748,9 +748,37 @@ fn create_spawn_agent_tool(config: &ToolsConfig) -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "spawn_agent".to_string(), - description: - "Spawn a sub-agent for a well-scoped task. Returns the agent id (and user-facing nickname when available) to use to communicate with this agent." - .to_string(), + description: r#"Spawn a sub-agent for a well-scoped task. Returns the agent id (and user-facing nickname when available) to use to communicate with this agent. This spawn_agent tool provides you access to smaller but more efficient sub-agents. A mini model can solve many tasks faster than the main model. You should follow the rules and guidelines below to use this tool. + +### When to delegate vs. do the subtask yourself +- First, quickly analyze the overall user task and form a succinct high-level plan. Identify which tasks are immediate blockers on the critical path, and which tasks are sidecar tasks that are needed but can run in parallel without blocking the next local step. As part of that plan, explicitly decide what immediate task you should do locally right now. Do this planning step before delegating to agents so you do not hand off the immediate blocking task to a submodel and then waste time waiting on it. +- Use the smaller subagent when a subtask is easy enough for it to handle and can run in parallel with your local work. Prefer delegating concrete, bounded sidecar tasks that materially advance the main task without blocking your immediate next local step. +- Do not delegate urgent blocking work when your immediate next step depends on that result. If the very next action is blocked on that task, the main rollout should usually do it locally to keep the critical path moving. +- Keep work local when the subtask is too difficult to delegate well and when it is tightly coupled, urgent, or likely to block your immediate next step. + +### Designing delegated subtasks +- Subtasks must be concrete, well-defined, and self-contained. +- Delegated subtasks must materially advance the main task. +- Do not duplicate work between the main rollout and delegated subtasks. +- Avoid issuing multiple delegate calls on the same unresolved thread unless the new delegated task is genuinely different and necessary. +- Narrow the delegated ask to the concrete output you need next. +- For coding tasks, prefer delegating concrete code-change worker subtasks over read-only explorer analysis when the subagent can make a bounded patch in a clear write scope. +- When delegating coding work, instruct the submodel to edit files directly in its forked workspace and list the file paths it changed in the final answer. +- For code-edit subtasks, decompose work so each delegated task has a disjoint write set. + +### After you delegate +- Call wait very sparingly. Only call wait when you need the result immediately for the next critical-path step and you are blocked until it returns. +- Do not redo delegated subagent tasks yourself; focus on integrating results or tackling non-overlapping work. +- While the subagent is running in the background, do meaningful non-overlapping work immediately. +- Do not repeatedly wait by reflex. +- When a delegated coding task returns, quickly review the uploaded changes, then integrate or refine them. + +### Parallel delegation patterns +- Run multiple independent information-seeking subtasks in parallel when you have distinct questions that can be answered independently. +- Split implementation into disjoint codebase slices and spawn multiple agents for them in parallel when the write scopes do not overlap. +- Delegate verification only when it can run in parallel with ongoing implementation and is likely to catch a concrete risk before final integration. +- The key is to find opportunities to spawn multiple independent subtasks in parallel within the same round, while ensuring each subtask is well-defined, self-contained, and materially advances the main task."# + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -916,9 +944,8 @@ fn create_send_input_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "send_input".to_string(), - description: - "Send a message to an existing agent. Use interrupt=true to redirect work immediately." - .to_string(), + description: "Send a message to an existing agent. Use interrupt=true to redirect work immediately. You should reuse the agent by send_input if you believe your assigned task is highly dependent on the context of a previous task." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -974,7 +1001,7 @@ fn create_wait_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "wait".to_string(), - description: "Wait for agents to reach a final status. Completed statuses may include the agent's final message. Returns empty status when timed out. Once the agent reaches his final status, a notification message will be received containing the same completed status." + description: "Wait for agents to reach a final status. Completed statuses may include the agent's final message. Returns empty status when timed out. Once the agent reaches a final status, a notification message will be received containing the same completed status." .to_string(), strict: false, parameters: JsonSchema::Object { From a4ad101125cc2166d6675aea8309193f07c6f04c Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 09:41:29 +0000 Subject: [PATCH 367/385] feat: ordinal nick name (#13412) --- codex-rs/core/src/agent/guards.rs | 85 ++++++++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/agent/guards.rs b/codex-rs/core/src/agent/guards.rs index 4213cd0ed0..056d2b7f6a 100644 --- a/codex-rs/core/src/agent/guards.rs +++ b/codex-rs/core/src/agent/guards.rs @@ -30,6 +30,26 @@ struct ActiveAgents { used_agent_nicknames: HashSet, nickname_reset_count: usize, } + +fn format_agent_nickname(name: &str, nickname_reset_count: usize) -> String { + match nickname_reset_count { + 0 => name.to_string(), + reset_count => { + let value = reset_count + 1; + let suffix = match value % 100 { + 11..=13 => "th", + _ => match value % 10 { + 1 => "st", // codespell:ignore + 2 => "nd", // codespell:ignore + 3 => "rd", // codespell:ignore + _ => "th", // codespell:ignore + }, + }; + format!("{name} the {value}{suffix}") + } + } +} + fn session_depth(session_source: &SessionSource) -> i32 { match session_source { SessionSource::SubAgent(SubAgentSource::ThreadSpawn { depth, .. }) => *depth, @@ -107,20 +127,23 @@ impl Guards { if names.is_empty() { return None; } - let available_names: Vec<&str> = names + let available_names: Vec = names .iter() - .copied() - .filter(|name| !active_agents.used_agent_nicknames.contains(*name)) + .map(|name| format_agent_nickname(name, active_agents.nickname_reset_count)) + .filter(|name| !active_agents.used_agent_nicknames.contains(name)) .collect(); if let Some(name) = available_names.choose(&mut rand::rng()) { - (*name).to_string() + name.clone() } else { active_agents.used_agent_nicknames.clear(); active_agents.nickname_reset_count += 1; if let Some(metrics) = codex_otel::metrics::global() { let _ = metrics.counter("codex.multi_agent.nickname_pool_reset", 1, &[]); } - names.choose(&mut rand::rng())?.to_string() + format_agent_nickname( + names.choose(&mut rand::rng())?, + active_agents.nickname_reset_count, + ) } }; active_agents @@ -202,6 +225,16 @@ impl Drop for SpawnReservation { mod tests { use super::*; use pretty_assertions::assert_eq; + use std::collections::HashSet; + + #[test] + fn format_agent_nickname_adds_ordinals_after_reset() { + assert_eq!(format_agent_nickname("Plato", 0), "Plato"); + assert_eq!(format_agent_nickname("Plato", 1), "Plato the 2nd"); + assert_eq!(format_agent_nickname("Plato", 2), "Plato the 3rd"); + assert_eq!(format_agent_nickname("Plato", 10), "Plato the 11th"); + assert_eq!(format_agent_nickname("Plato", 20), "Plato the 21st"); + } #[test] fn session_depth_defaults_to_zero_for_root_sources() { @@ -352,7 +385,7 @@ mod tests { let second_name = second .reserve_agent_nickname(&["alpha"]) .expect("name should be reused after pool reset"); - assert_eq!(second_name, "alpha"); + assert_eq!(second_name, "alpha the 2nd"); let active_agents = guards .active_agents .lock() @@ -389,11 +422,49 @@ mod tests { let third_name = third .reserve_agent_nickname(&["alpha", "beta"]) .expect("pool reset should permit a duplicate"); - assert!(third_name == "alpha" || third_name == "beta"); + let expected_names = + HashSet::from(["alpha the 2nd".to_string(), "beta the 2nd".to_string()]); + assert!(expected_names.contains(&third_name)); let active_agents = guards .active_agents .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); assert_eq!(active_agents.nickname_reset_count, 1); } + + #[test] + fn repeated_resets_advance_the_ordinal_suffix() { + let guards = Arc::new(Guards::default()); + + let mut first = guards.reserve_spawn_slot(None).expect("reserve first slot"); + let first_name = first + .reserve_agent_nickname(&["Plato"]) + .expect("reserve first agent name"); + let first_id = ThreadId::new(); + first.commit(first_id); + assert_eq!(first_name, "Plato"); + guards.release_spawned_thread(first_id); + + let mut second = guards + .reserve_spawn_slot(None) + .expect("reserve second slot"); + let second_name = second + .reserve_agent_nickname(&["Plato"]) + .expect("reserve second agent name"); + let second_id = ThreadId::new(); + second.commit(second_id); + assert_eq!(second_name, "Plato the 2nd"); + guards.release_spawned_thread(second_id); + + let mut third = guards.reserve_spawn_slot(None).expect("reserve third slot"); + let third_name = third + .reserve_agent_nickname(&["Plato"]) + .expect("reserve third agent name"); + assert_eq!(third_name, "Plato the 3rd"); + let active_agents = guards + .active_agents + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(active_agents.nickname_reset_count, 2); + } } From 49634b7f9c0702598bbd5a233ddcb8bad5302e79 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 10:17:25 +0000 Subject: [PATCH 368/385] add metric for per-turn token usage (#13454) --- codex-rs/core/src/codex.rs | 7 ++--- codex-rs/core/src/state/turn.rs | 2 ++ codex-rs/core/src/tasks/mod.rs | 50 +++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 9b9e0214a8..0ac2b14f4b 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -3238,12 +3238,9 @@ impl Session { turn_context: &TurnContext, token_usage: Option<&TokenUsage>, ) { - { + if let Some(token_usage) = token_usage { let mut state = self.state.lock().await; - if let Some(token_usage) = token_usage { - state - .update_token_info_from_usage(token_usage, turn_context.model_context_window()); - } + state.update_token_info_from_usage(token_usage, turn_context.model_context_window()); } self.send_token_count_event(turn_context).await; } diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index ccc50d066b..9366880aca 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -15,6 +15,7 @@ use tokio::sync::oneshot; use crate::codex::TurnContext; use crate::protocol::ReviewDecision; +use crate::protocol::TokenUsage; use crate::tasks::SessionTask; /// Metadata about the currently running turn. @@ -73,6 +74,7 @@ pub(crate) struct TurnState { pending_user_input: HashMap>, pending_dynamic_tools: HashMap>, pending_input: Vec, + pub(crate) token_usage_at_turn_start: TokenUsage, } impl TurnState { diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 5133dc1e27..a814d36dcc 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -199,11 +199,13 @@ impl Session { let mut active = self.active_turn.lock().await; let mut pending_input = Vec::::new(); let mut should_clear_active_turn = false; + let mut token_usage_at_turn_start = None; if let Some(at) = active.as_mut() && at.remove_task(&turn_context.sub_id) { let mut ts = at.turn_state.lock().await; pending_input = ts.take_pending_input(); + token_usage_at_turn_start = Some(ts.token_usage_at_turn_start.clone()); should_clear_active_turn = true; } if should_clear_active_turn { @@ -235,6 +237,52 @@ impl Session { } } } + // Emit token usage metrics. + if let Some(token_usage_at_turn_start) = token_usage_at_turn_start { + let total_token_usage = self.total_token_usage().await.unwrap_or_default(); + let turn_token_usage = crate::protocol::TokenUsage { + input_tokens: (total_token_usage.input_tokens + - token_usage_at_turn_start.input_tokens) + .max(0), + cached_input_tokens: (total_token_usage.cached_input_tokens + - token_usage_at_turn_start.cached_input_tokens) + .max(0), + output_tokens: (total_token_usage.output_tokens + - token_usage_at_turn_start.output_tokens) + .max(0), + reasoning_output_tokens: (total_token_usage.reasoning_output_tokens + - token_usage_at_turn_start.reasoning_output_tokens) + .max(0), + total_tokens: (total_token_usage.total_tokens + - token_usage_at_turn_start.total_tokens) + .max(0), + }; + self.services.otel_manager.histogram( + "codex.turn.token_usage", + turn_token_usage.total_tokens, + &[("token_type", "total")], + ); + self.services.otel_manager.histogram( + "codex.turn.token_usage", + turn_token_usage.input_tokens, + &[("token_type", "input")], + ); + self.services.otel_manager.histogram( + "codex.turn.token_usage", + turn_token_usage.cached_input(), + &[("token_type", "cached_input")], + ); + self.services.otel_manager.histogram( + "codex.turn.token_usage", + turn_token_usage.output_tokens, + &[("token_type", "output")], + ); + self.services.otel_manager.histogram( + "codex.turn.token_usage", + turn_token_usage.reasoning_output_tokens, + &[("token_type", "reasoning_output")], + ); + } let event = EventMsg::TurnComplete(TurnCompleteEvent { turn_id: turn_context.sub_id.clone(), last_agent_message, @@ -243,8 +291,10 @@ impl Session { } async fn register_new_active_task(&self, task: RunningTask) { + let token_usage_at_turn_start = self.total_token_usage().await.unwrap_or_default(); let mut active = self.active_turn.lock().await; let mut turn = ActiveTurn::default(); + turn.turn_state.lock().await.token_usage_at_turn_start = token_usage_at_turn_start; turn.add_task(task); *active = Some(turn); } From e4a202ea52439fd14f2eddd465c0e9824f8d1fb6 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 10:17:29 +0000 Subject: [PATCH 369/385] fix: pending messages in `/agent` (#13240) --- codex-rs/tui/src/app.rs | 799 +++++++++++++++++++++- codex-rs/tui/src/bottom_pane/mod.rs | 9 + codex-rs/tui/src/chatwidget.rs | 122 +++- codex-rs/tui/src/chatwidget/tests.rs | 25 + codex-rs/utils/sleep-inhibitor/src/lib.rs | 12 + 5 files changed, 960 insertions(+), 7 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index dd20187508..da196ef2c5 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -12,6 +12,7 @@ use crate::bottom_pane::SelectionViewParams; use crate::bottom_pane::popup_consts::standard_popup_hint_line; use crate::chatwidget::ChatWidget; use crate::chatwidget::ExternalEditorState; +use crate::chatwidget::ThreadInputState; use crate::cwd_prompt::CwdPromptAction; use crate::diff_render::DiffSummary; use crate::exec_command::strip_bash_lc_and_escape; @@ -254,6 +255,7 @@ struct SessionSummary { struct ThreadEventSnapshot { session_configured: Option, events: Vec, + input_state: Option, } #[derive(Debug)] @@ -262,6 +264,7 @@ struct ThreadEventStore { buffer: VecDeque, user_message_ids: HashSet, pending_interactive_replay: PendingInteractiveReplayState, + input_state: Option, capacity: usize, active: bool, } @@ -273,6 +276,7 @@ impl ThreadEventStore { buffer: VecDeque::new(), user_message_ids: HashSet::new(), pending_interactive_replay: PendingInteractiveReplayState::default(), + input_state: None, capacity, active: false, } @@ -342,6 +346,7 @@ impl ThreadEventStore { }) .cloned() .collect(), + input_state: self.input_state.clone(), } } @@ -917,13 +922,15 @@ impl App { let Some(active_id) = self.active_thread_id else { return; }; - let Some(receiver) = self.active_thread_rx.take() else { - return; - }; + let input_state = self.chat_widget.capture_thread_input_state(); if let Some(channel) = self.thread_event_channels.get_mut(&active_id) { + let receiver = self.active_thread_rx.take(); let mut store = channel.store.lock().await; store.active = false; - channel.receiver = Some(receiver); + store.input_state = input_state; + if let Some(receiver) = receiver { + channel.receiver = Some(receiver); + } } } @@ -1335,7 +1342,7 @@ impl App { self.chat_widget = ChatWidget::new_with_op_sender(init, codex_op_tx); self.reset_for_thread_switch(tui)?; - self.replay_thread_snapshot(snapshot); + self.replay_thread_snapshot(snapshot, !is_replay_only); if is_replay_only { self.chat_widget.add_info_message( format!("Agent thread {thread_id} is closed. Replaying saved transcript."), @@ -1473,13 +1480,24 @@ impl App { (active_thread_id != primary_thread_id).then_some((active_thread_id, primary_thread_id)) } - fn replay_thread_snapshot(&mut self, snapshot: ThreadEventSnapshot) { + fn replay_thread_snapshot( + &mut self, + snapshot: ThreadEventSnapshot, + resume_restored_queue: bool, + ) { if let Some(event) = snapshot.session_configured { self.handle_codex_event_replay(event); } + self.chat_widget.set_queue_autosend_suppressed(true); + self.chat_widget + .restore_thread_input_state(snapshot.input_state); for event in snapshot.events { self.handle_codex_event_replay(event); } + self.chat_widget.set_queue_autosend_suppressed(false); + if resume_restored_queue { + self.chat_widget.maybe_send_next_queued_input(); + } self.refresh_status_line(); } @@ -3667,7 +3685,12 @@ mod tests { use codex_core::config::types::ModelAvailabilityNuxConfig; use codex_otel::OtelManager; use codex_protocol::ThreadId; + use codex_protocol::config_types::CollaborationMode; + use codex_protocol::config_types::CollaborationModeMask; + use codex_protocol::config_types::ModeKind; + use codex_protocol::config_types::Settings; use codex_protocol::openai_models::ModelAvailabilityNux; + use codex_protocol::protocol::AgentMessageDeltaEvent; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -3675,6 +3698,10 @@ mod tests { use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::ThreadRolledBackEvent; + use codex_protocol::protocol::TurnAbortReason; + use codex_protocol::protocol::TurnAbortedEvent; + use codex_protocol::protocol::TurnCompleteEvent; + use codex_protocol::protocol::TurnStartedEvent; use codex_protocol::protocol::UserMessageEvent; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; @@ -3977,6 +4004,755 @@ mod tests { Ok(()) } + #[tokio::test] + async fn replay_thread_snapshot_restores_draft_and_queued_input() { + let mut app = make_test_app().await; + let thread_id = ThreadId::new(); + app.thread_event_channels.insert( + thread_id, + ThreadEventChannel::new_with_session_configured( + THREAD_EVENT_CHANNEL_CAPACITY, + Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }, + ), + ); + app.activate_thread_channel(thread_id).await; + + app.chat_widget + .apply_external_edit("draft prompt".to_string()); + app.chat_widget.submit_user_message_with_mode( + "queued follow-up".to_string(), + CollaborationModeMask { + name: "Default".to_string(), + mode: None, + model: None, + reasoning_effort: None, + developer_instructions: None, + }, + ); + let expected_input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected thread input state"); + + app.store_active_thread_receiver().await; + + let snapshot = { + let channel = app + .thread_event_channels + .get(&thread_id) + .expect("thread channel should exist"); + let store = channel.store.lock().await; + assert_eq!(store.input_state, Some(expected_input_state)); + store.snapshot() + }; + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + + app.replay_thread_snapshot(snapshot, true); + + assert_eq!(app.chat_widget.composer_text_with_pending(), "draft prompt"); + assert!(app.chat_widget.queued_user_message_texts().is_empty()); + match next_user_turn_op(&mut new_op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "queued follow-up".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected queued follow-up submission, got {other:?}"), + } + } + + #[tokio::test] + async fn replayed_turn_complete_submits_restored_queued_follow_up() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let session_configured = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + app.chat_widget + .handle_codex_event(session_configured.clone()); + app.chat_widget.handle_codex_event(Event { + id: "turn-started".to_string(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + }); + app.chat_widget.handle_codex_event(Event { + id: "agent-delta".to_string(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "streaming".to_string(), + }), + }); + app.chat_widget + .apply_external_edit("queued follow-up".to_string()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected queued follow-up state"); + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.chat_widget.handle_codex_event(session_configured); + while new_op_rx.try_recv().is_ok() {} + app.replay_thread_snapshot( + ThreadEventSnapshot { + session_configured: None, + events: vec![Event { + id: "turn-complete".to_string(), + msg: EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-1".to_string(), + last_agent_message: None, + }), + }], + input_state: Some(input_state), + }, + true, + ); + + match next_user_turn_op(&mut new_op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "queued follow-up".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected queued follow-up submission, got {other:?}"), + } + } + + #[tokio::test] + async fn replay_only_thread_keeps_restored_queue_visible() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let session_configured = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + app.chat_widget + .handle_codex_event(session_configured.clone()); + app.chat_widget.handle_codex_event(Event { + id: "turn-started".to_string(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + }); + app.chat_widget.handle_codex_event(Event { + id: "agent-delta".to_string(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "streaming".to_string(), + }), + }); + app.chat_widget + .apply_external_edit("queued follow-up".to_string()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected queued follow-up state"); + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.chat_widget.handle_codex_event(session_configured); + while new_op_rx.try_recv().is_ok() {} + + app.replay_thread_snapshot( + ThreadEventSnapshot { + session_configured: None, + events: vec![Event { + id: "turn-complete".to_string(), + msg: EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-1".to_string(), + last_agent_message: None, + }), + }], + input_state: Some(input_state), + }, + false, + ); + + assert_eq!( + app.chat_widget.queued_user_message_texts(), + vec!["queued follow-up".to_string()] + ); + assert!( + new_op_rx.try_recv().is_err(), + "replay-only threads should not auto-submit restored queue" + ); + } + + #[tokio::test] + async fn replay_thread_snapshot_keeps_queue_when_running_state_only_comes_from_snapshot() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let session_configured = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + app.chat_widget + .handle_codex_event(session_configured.clone()); + app.chat_widget.handle_codex_event(Event { + id: "turn-started".to_string(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + }); + app.chat_widget.handle_codex_event(Event { + id: "agent-delta".to_string(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "streaming".to_string(), + }), + }); + app.chat_widget + .apply_external_edit("queued follow-up".to_string()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected queued follow-up state"); + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.chat_widget.handle_codex_event(session_configured); + while new_op_rx.try_recv().is_ok() {} + + app.replay_thread_snapshot( + ThreadEventSnapshot { + session_configured: None, + events: vec![], + input_state: Some(input_state), + }, + true, + ); + + assert_eq!( + app.chat_widget.queued_user_message_texts(), + vec!["queued follow-up".to_string()] + ); + assert!( + new_op_rx.try_recv().is_err(), + "restored queue should stay queued when replay did not prove the turn finished" + ); + } + + #[tokio::test] + async fn replay_thread_snapshot_does_not_submit_queue_before_replay_catches_up() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let session_configured = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + app.chat_widget + .handle_codex_event(session_configured.clone()); + app.chat_widget.handle_codex_event(Event { + id: "turn-started".to_string(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + }); + app.chat_widget.handle_codex_event(Event { + id: "agent-delta".to_string(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "streaming".to_string(), + }), + }); + app.chat_widget + .apply_external_edit("queued follow-up".to_string()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected queued follow-up state"); + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.chat_widget.handle_codex_event(session_configured); + while new_op_rx.try_recv().is_ok() {} + + app.replay_thread_snapshot( + ThreadEventSnapshot { + session_configured: None, + events: vec![ + Event { + id: "older-turn-complete".to_string(), + msg: EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-0".to_string(), + last_agent_message: None, + }), + }, + Event { + id: "latest-turn-started".to_string(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + }, + ], + input_state: Some(input_state), + }, + true, + ); + + assert!( + new_op_rx.try_recv().is_err(), + "queued follow-up should stay queued until the latest turn completes" + ); + assert_eq!( + app.chat_widget.queued_user_message_texts(), + vec!["queued follow-up".to_string()] + ); + + app.chat_widget.handle_codex_event(Event { + id: "latest-turn-complete".to_string(), + msg: EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-1".to_string(), + last_agent_message: None, + }), + }); + + match next_user_turn_op(&mut new_op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: "queued follow-up".to_string(), + text_elements: Vec::new(), + }] + ), + other => panic!("expected queued follow-up submission, got {other:?}"), + } + } + + #[tokio::test] + async fn replay_thread_snapshot_restores_pending_pastes_for_submit() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + app.thread_event_channels.insert( + thread_id, + ThreadEventChannel::new_with_session_configured( + THREAD_EVENT_CHANNEL_CAPACITY, + Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }, + ), + ); + app.activate_thread_channel(thread_id).await; + + let large = "x".repeat(1005); + app.chat_widget.handle_paste(large.clone()); + let expected_input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected thread input state"); + + app.store_active_thread_receiver().await; + + let snapshot = { + let channel = app + .thread_event_channels + .get(&thread_id) + .expect("thread channel should exist"); + let store = channel.store.lock().await; + assert_eq!(store.input_state, Some(expected_input_state)); + store.snapshot() + }; + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.replay_thread_snapshot(snapshot, true); + + assert_eq!(app.chat_widget.composer_text_with_pending(), large); + + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + match next_user_turn_op(&mut new_op_rx) { + Op::UserTurn { items, .. } => assert_eq!( + items, + vec![UserInput::Text { + text: large, + text_elements: Vec::new(), + }] + ), + other => panic!("expected restored paste submission, got {other:?}"), + } + } + + #[tokio::test] + async fn replay_thread_snapshot_restores_collaboration_mode_for_draft_submit() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let session_configured = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + app.chat_widget + .handle_codex_event(session_configured.clone()); + app.chat_widget + .set_reasoning_effort(Some(ReasoningEffortConfig::High)); + app.chat_widget + .set_collaboration_mask(CollaborationModeMask { + name: "Plan".to_string(), + mode: Some(ModeKind::Plan), + model: Some("gpt-restored".to_string()), + reasoning_effort: Some(Some(ReasoningEffortConfig::High)), + developer_instructions: None, + }); + app.chat_widget + .apply_external_edit("draft prompt".to_string()); + let input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected draft input state"); + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.chat_widget.handle_codex_event(session_configured); + app.chat_widget + .set_reasoning_effort(Some(ReasoningEffortConfig::Low)); + app.chat_widget + .set_collaboration_mask(CollaborationModeMask { + name: "Default".to_string(), + mode: Some(ModeKind::Default), + model: Some("gpt-replacement".to_string()), + reasoning_effort: Some(Some(ReasoningEffortConfig::Low)), + developer_instructions: None, + }); + while new_op_rx.try_recv().is_ok() {} + + app.replay_thread_snapshot( + ThreadEventSnapshot { + session_configured: None, + events: vec![], + input_state: Some(input_state), + }, + true, + ); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + match next_user_turn_op(&mut new_op_rx) { + Op::UserTurn { + items, + model, + effort, + collaboration_mode, + .. + } => { + assert_eq!( + items, + vec![UserInput::Text { + text: "draft prompt".to_string(), + text_elements: Vec::new(), + }] + ); + assert_eq!(model, "gpt-restored".to_string()); + assert_eq!(effort, Some(ReasoningEffortConfig::High)); + assert_eq!( + collaboration_mode, + Some(CollaborationMode { + mode: ModeKind::Plan, + settings: Settings { + model: "gpt-restored".to_string(), + reasoning_effort: Some(ReasoningEffortConfig::High), + developer_instructions: None, + }, + }) + ); + } + other => panic!("expected restored draft submission, got {other:?}"), + } + } + + #[tokio::test] + async fn replay_thread_snapshot_restores_collaboration_mode_without_input() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let session_configured = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + app.chat_widget + .handle_codex_event(session_configured.clone()); + app.chat_widget + .set_reasoning_effort(Some(ReasoningEffortConfig::High)); + app.chat_widget + .set_collaboration_mask(CollaborationModeMask { + name: "Plan".to_string(), + mode: Some(ModeKind::Plan), + model: Some("gpt-restored".to_string()), + reasoning_effort: Some(Some(ReasoningEffortConfig::High)), + developer_instructions: None, + }); + let input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected collaboration-only input state"); + + let (chat_widget, _app_event_tx, _rx, _new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.chat_widget.handle_codex_event(session_configured); + app.chat_widget + .set_reasoning_effort(Some(ReasoningEffortConfig::Low)); + app.chat_widget + .set_collaboration_mask(CollaborationModeMask { + name: "Default".to_string(), + mode: Some(ModeKind::Default), + model: Some("gpt-replacement".to_string()), + reasoning_effort: Some(Some(ReasoningEffortConfig::Low)), + developer_instructions: None, + }); + + app.replay_thread_snapshot( + ThreadEventSnapshot { + session_configured: None, + events: vec![], + input_state: Some(input_state), + }, + true, + ); + + assert_eq!( + app.chat_widget.active_collaboration_mode_kind(), + ModeKind::Plan + ); + assert_eq!(app.chat_widget.current_model(), "gpt-restored"); + assert_eq!( + app.chat_widget.current_reasoning_effort(), + Some(ReasoningEffortConfig::High) + ); + } + + #[tokio::test] + async fn replayed_interrupted_turn_restores_queued_input_to_composer() { + let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let session_configured = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + app.chat_widget + .handle_codex_event(session_configured.clone()); + app.chat_widget.handle_codex_event(Event { + id: "turn-started".to_string(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + }); + app.chat_widget.handle_codex_event(Event { + id: "agent-delta".to_string(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "streaming".to_string(), + }), + }); + app.chat_widget + .apply_external_edit("queued follow-up".to_string()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let input_state = app + .chat_widget + .capture_thread_input_state() + .expect("expected queued follow-up state"); + + let (chat_widget, _app_event_tx, _rx, mut new_op_rx) = + make_chatwidget_manual_with_sender().await; + app.chat_widget = chat_widget; + app.chat_widget.handle_codex_event(session_configured); + while new_op_rx.try_recv().is_ok() {} + + app.replay_thread_snapshot( + ThreadEventSnapshot { + session_configured: None, + events: vec![Event { + id: "turn-aborted".to_string(), + msg: EventMsg::TurnAborted(TurnAbortedEvent { + turn_id: Some("turn-1".to_string()), + reason: TurnAbortReason::ReviewEnded, + }), + }], + input_state: Some(input_state), + }, + true, + ); + + assert_eq!( + app.chat_widget.composer_text_with_pending(), + "queued follow-up" + ); + assert!(app.chat_widget.queued_user_message_texts().is_empty()); + assert!( + new_op_rx.try_recv().is_err(), + "replayed interrupted turns should restore queued input for editing, not submit it" + ); + } + #[tokio::test] async fn open_agent_picker_keeps_missing_threads_for_replay() -> Result<()> { let mut app = make_test_app().await; @@ -4564,6 +5340,17 @@ mod tests { ) } + fn next_user_turn_op(op_rx: &mut tokio::sync::mpsc::UnboundedReceiver) -> Op { + let mut seen = Vec::new(); + while let Ok(op) = op_rx.try_recv() { + if matches!(op, Op::UserTurn { .. }) { + return op; + } + seen.push(format!("{op:?}")); + } + panic!("expected UserTurn op, saw: {seen:?}"); + } + fn test_otel_manager(config: &Config, model: &str) -> OtelManager { let model_info = codex_core::test_support::construct_model_info_offline(model, config); OtelManager::new( diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 74862df999..1e6e6fce0e 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -579,6 +579,10 @@ impl BottomPane { self.composer.current_text_with_pending() } + pub(crate) fn composer_pending_pastes(&self) -> Vec<(String, String)> { + self.composer.pending_pastes() + } + pub(crate) fn apply_external_edit(&mut self, text: String) { self.composer.apply_external_edit(text); self.request_redraw(); @@ -604,6 +608,11 @@ impl BottomPane { urls } + pub(crate) fn set_composer_pending_pastes(&mut self, pending_pastes: Vec<(String, String)>) { + self.composer.set_pending_pastes(pending_pastes); + self.request_redraw(); + } + /// Update the status indicator header (defaults to "Working") and details below it. /// /// Passing `None` clears any existing details. No-ops if the status indicator is not active. diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 840505f36b..fb9404a089 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -607,6 +607,7 @@ pub(crate) struct ChatWidget { retry_status_header: Option, // Set when commentary output completes; once stream queues go idle we restore the status row. pending_status_indicator_restore: bool, + suppress_queue_autosend: bool, thread_id: Option, thread_name: Option, forked_from: Option, @@ -721,6 +722,7 @@ pub(crate) struct ActiveCellTranscriptKey { pub(crate) animation_tick: Option, } +#[derive(Debug, Clone, PartialEq)] pub(crate) struct UserMessage { text: String, local_images: Vec, @@ -734,6 +736,36 @@ pub(crate) struct UserMessage { mention_bindings: Vec, } +#[derive(Debug, Clone, PartialEq, Default)] +struct ThreadComposerState { + text: String, + local_images: Vec, + remote_image_urls: Vec, + text_elements: Vec, + mention_bindings: Vec, + pending_pastes: Vec<(String, String)>, +} + +impl ThreadComposerState { + fn has_content(&self) -> bool { + !self.text.is_empty() + || !self.local_images.is_empty() + || !self.remote_image_urls.is_empty() + || !self.text_elements.is_empty() + || !self.mention_bindings.is_empty() + || !self.pending_pastes.is_empty() + } +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ThreadInputState { + composer: Option, + queued_user_messages: VecDeque, + current_collaboration_mode: CollaborationMode, + active_collaboration_mask: Option, + agent_turn_running: bool, +} + impl From for UserMessage { fn from(text: String) -> Self { Self { @@ -2021,6 +2053,80 @@ impl ChatWidget { ); } + pub(crate) fn capture_thread_input_state(&self) -> Option { + let composer = ThreadComposerState { + text: self.bottom_pane.composer_text(), + text_elements: self.bottom_pane.composer_text_elements(), + local_images: self.bottom_pane.composer_local_images(), + remote_image_urls: self.bottom_pane.remote_image_urls(), + mention_bindings: self.bottom_pane.composer_mention_bindings(), + pending_pastes: self.bottom_pane.composer_pending_pastes(), + }; + Some(ThreadInputState { + composer: composer.has_content().then_some(composer), + queued_user_messages: self.queued_user_messages.clone(), + current_collaboration_mode: self.current_collaboration_mode.clone(), + active_collaboration_mask: self.active_collaboration_mask.clone(), + agent_turn_running: self.agent_turn_running, + }) + } + + pub(crate) fn restore_thread_input_state(&mut self, input_state: Option) { + if let Some(input_state) = input_state { + self.current_collaboration_mode = input_state.current_collaboration_mode; + self.active_collaboration_mask = input_state.active_collaboration_mask; + self.agent_turn_running = input_state.agent_turn_running; + self.update_collaboration_mode_indicator(); + self.refresh_model_display(); + if let Some(composer) = input_state.composer { + let local_image_paths = composer + .local_images + .into_iter() + .map(|img| img.path) + .collect(); + self.set_remote_image_urls(composer.remote_image_urls); + self.bottom_pane.set_composer_text_with_mention_bindings( + composer.text, + composer.text_elements, + local_image_paths, + composer.mention_bindings, + ); + self.bottom_pane + .set_composer_pending_pastes(composer.pending_pastes); + } else { + self.set_remote_image_urls(Vec::new()); + self.bottom_pane.set_composer_text_with_mention_bindings( + String::new(), + Vec::new(), + Vec::new(), + Vec::new(), + ); + self.bottom_pane.set_composer_pending_pastes(Vec::new()); + } + self.queued_user_messages = input_state.queued_user_messages; + } else { + self.agent_turn_running = false; + self.set_remote_image_urls(Vec::new()); + self.bottom_pane.set_composer_text_with_mention_bindings( + String::new(), + Vec::new(), + Vec::new(), + Vec::new(), + ); + self.bottom_pane.set_composer_pending_pastes(Vec::new()); + self.queued_user_messages.clear(); + } + self.turn_sleep_inhibitor + .set_turn_running(self.agent_turn_running); + self.update_task_running_state(); + self.refresh_queued_user_messages(); + self.request_redraw(); + } + + pub(crate) fn set_queue_autosend_suppressed(&mut self, suppressed: bool) { + self.suppress_queue_autosend = suppressed; + } + fn on_plan_update(&mut self, update: UpdatePlanArgs) { self.saw_plan_update_this_turn = true; self.add_to_history(history_cell::new_plan_update(update)); @@ -2977,6 +3083,7 @@ impl ChatWidget { current_status_header: String::from("Working"), retry_status_header: None, pending_status_indicator_restore: false, + suppress_queue_autosend: false, thread_id: None, thread_name: None, forked_from: None, @@ -3158,6 +3265,7 @@ impl ChatWidget { current_status_header: String::from("Working"), retry_status_header: None, pending_status_indicator_restore: false, + suppress_queue_autosend: false, thread_id: None, thread_name: None, forked_from: None, @@ -3328,6 +3436,7 @@ impl ChatWidget { current_status_header: String::from("Working"), retry_status_header: None, pending_status_indicator_restore: false, + suppress_queue_autosend: false, thread_id: None, thread_name: None, forked_from: None, @@ -4881,7 +4990,10 @@ impl ChatWidget { } // If idle and there are queued inputs, submit exactly one to start the next turn. - fn maybe_send_next_queued_input(&mut self) { + pub(crate) fn maybe_send_next_queued_input(&mut self) { + if self.suppress_queue_autosend { + return; + } if self.bottom_pane.is_task_running() { return; } @@ -7827,6 +7939,14 @@ impl ChatWidget { self.bottom_pane.remote_image_urls() } + #[cfg(test)] + pub(crate) fn queued_user_message_texts(&self) -> Vec { + self.queued_user_messages + .iter() + .map(|message| message.text.clone()) + .collect() + } + #[cfg(test)] pub(crate) fn pending_thread_approvals(&self) -> &[String] { self.bottom_pane.pending_thread_approvals() diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 2861be570d..b9167d211c 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -1805,6 +1805,7 @@ async fn make_chatwidget_manual( current_status_header: String::from("Working"), retry_status_header: None, pending_status_indicator_restore: false, + suppress_queue_autosend: false, thread_id: None, thread_name: None, forked_from: None, @@ -3367,6 +3368,30 @@ async fn empty_enter_during_task_does_not_queue() { assert!(chat.queued_user_messages.is_empty()); } +#[tokio::test] +async fn restore_thread_input_state_syncs_sleep_inhibitor_state() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.set_feature_enabled(Feature::PreventIdleSleep, true); + + chat.restore_thread_input_state(Some(ThreadInputState { + composer: None, + queued_user_messages: VecDeque::new(), + current_collaboration_mode: chat.current_collaboration_mode.clone(), + active_collaboration_mask: chat.active_collaboration_mask.clone(), + agent_turn_running: true, + })); + + assert!(chat.agent_turn_running); + assert!(chat.turn_sleep_inhibitor.is_turn_running()); + assert!(chat.bottom_pane.is_task_running()); + + chat.restore_thread_input_state(None); + + assert!(!chat.agent_turn_running); + assert!(!chat.turn_sleep_inhibitor.is_turn_running()); + assert!(!chat.bottom_pane.is_task_running()); +} + #[tokio::test] async fn alt_up_edits_most_recent_queued_message() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; diff --git a/codex-rs/utils/sleep-inhibitor/src/lib.rs b/codex-rs/utils/sleep-inhibitor/src/lib.rs index 8c9c5a9ccd..0b3d2c9a30 100644 --- a/codex-rs/utils/sleep-inhibitor/src/lib.rs +++ b/codex-rs/utils/sleep-inhibitor/src/lib.rs @@ -29,6 +29,7 @@ use windows_inhibitor as imp; #[derive(Debug)] pub struct SleepInhibitor { enabled: bool, + turn_running: bool, platform: imp::SleepInhibitor, } @@ -36,12 +37,14 @@ impl SleepInhibitor { pub fn new(enabled: bool) -> Self { Self { enabled, + turn_running: false, platform: imp::SleepInhibitor::new(), } } /// Update the active turn state; turns sleep prevention on/off as needed. pub fn set_turn_running(&mut self, turn_running: bool) { + self.turn_running = turn_running; if !self.enabled { self.release(); return; @@ -61,6 +64,11 @@ impl SleepInhibitor { fn release(&mut self) { self.platform.release(); } + + /// Return the latest turn-running state requested by the caller. + pub fn is_turn_running(&self) -> bool { + self.turn_running + } } #[cfg(test)] @@ -71,14 +79,18 @@ mod tests { fn sleep_inhibitor_toggles_without_panicking() { let mut inhibitor = SleepInhibitor::new(true); inhibitor.set_turn_running(true); + assert!(inhibitor.is_turn_running()); inhibitor.set_turn_running(false); + assert!(!inhibitor.is_turn_running()); } #[test] fn sleep_inhibitor_disabled_does_not_panic() { let mut inhibitor = SleepInhibitor::new(false); inhibitor.set_turn_running(true); + assert!(inhibitor.is_turn_running()); inhibitor.set_turn_running(false); + assert!(!inhibitor.is_turn_running()); } #[test] From e6b2e3a9f7ab3e87626db8de34632d3d61c083b8 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 11:00:48 +0000 Subject: [PATCH 370/385] fix: bad merge (#13461) --- codex-rs/tui/src/app.rs | 9 +++++++++ codex-rs/tui/src/chatwidget.rs | 14 ++++++++++++-- codex-rs/tui/src/chatwidget/tests.rs | 1 + 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index da196ef2c5..fe8aca54fd 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -4020,6 +4020,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4096,6 +4097,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4176,6 +4178,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4255,6 +4258,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4328,6 +4332,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4440,6 +4445,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4508,6 +4514,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4610,6 +4617,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -4685,6 +4693,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index fb9404a089..8c4f4ef57b 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -760,6 +760,7 @@ impl ThreadComposerState { #[derive(Debug, Clone, PartialEq)] pub(crate) struct ThreadInputState { composer: Option, + pending_steers: VecDeque, queued_user_messages: VecDeque, current_collaboration_mode: CollaborationMode, active_collaboration_mask: Option, @@ -2064,6 +2065,11 @@ impl ChatWidget { }; Some(ThreadInputState { composer: composer.has_content().then_some(composer), + pending_steers: self + .pending_steers + .iter() + .map(|pending| pending.user_message.clone()) + .collect(), queued_user_messages: self.queued_user_messages.clone(), current_collaboration_mode: self.current_collaboration_mode.clone(), active_collaboration_mask: self.active_collaboration_mask.clone(), @@ -2103,9 +2109,13 @@ impl ChatWidget { ); self.bottom_pane.set_composer_pending_pastes(Vec::new()); } - self.queued_user_messages = input_state.queued_user_messages; + self.pending_steers.clear(); + self.queued_user_messages = input_state.pending_steers; + self.queued_user_messages + .extend(input_state.queued_user_messages); } else { self.agent_turn_running = false; + self.pending_steers.clear(); self.set_remote_image_urls(Vec::new()); self.bottom_pane.set_composer_text_with_mention_bindings( String::new(), @@ -2119,7 +2129,7 @@ impl ChatWidget { self.turn_sleep_inhibitor .set_turn_running(self.agent_turn_running); self.update_task_running_state(); - self.refresh_queued_user_messages(); + self.refresh_pending_input_preview(); self.request_redraw(); } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index b9167d211c..2ece156517 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -3375,6 +3375,7 @@ async fn restore_thread_input_state_syncs_sleep_inhibitor_state() { chat.restore_thread_input_state(Some(ThreadInputState { composer: None, + pending_steers: VecDeque::new(), queued_user_messages: VecDeque::new(), current_collaboration_mode: chat.current_collaboration_mode.clone(), active_collaboration_mask: chat.active_collaboration_mask.clone(), From bda3c49dc4a4ea052ed55faf9c4310e6875ca41e Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 11:25:49 +0000 Subject: [PATCH 371/385] feat: disable request input on sub agent (#13460) https://github.com/openai/codex/issues/13289 --- codex-rs/core/src/tools/spec.rs | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 5d9c6644cc..b0b3540990 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -57,6 +57,7 @@ pub(crate) struct ToolsConfig { pub js_repl_tools_only: bool, pub collab_tools: bool, pub artifact_tools: bool, + pub request_user_input: bool, pub default_mode_request_user_input: bool, pub experimental_supported_tools: Vec, pub agent_jobs_tools: bool, @@ -83,8 +84,9 @@ impl ToolsConfig { let include_js_repl_tools_only = include_js_repl && features.enabled(Feature::JsReplToolsOnly); let include_collab_tools = features.enabled(Feature::Collab); + let include_request_user_input = !matches!(session_source, SessionSource::SubAgent(_)); let include_default_mode_request_user_input = - features.enabled(Feature::DefaultModeRequestUserInput); + include_request_user_input && features.enabled(Feature::DefaultModeRequestUserInput); let include_search_tool = features.enabled(Feature::Apps); let include_artifact_tools = features.enabled(Feature::Artifact); let include_image_gen_tool = @@ -146,6 +148,7 @@ impl ToolsConfig { js_repl_tools_only: include_js_repl_tools_only, collab_tools: include_collab_tools, artifact_tools: include_artifact_tools, + request_user_input: include_request_user_input, default_mode_request_user_input: include_default_mode_request_user_input, experimental_supported_tools: model_info.experimental_supported_tools.clone(), agent_jobs_tools: include_agent_jobs, @@ -1877,10 +1880,12 @@ pub(crate) fn build_specs( builder.register_handler("js_repl_reset", js_repl_reset_handler); } - builder.push_spec(create_request_user_input_tool(CollaborationModesConfig { - default_mode_request_user_input: config.default_mode_request_user_input, - })); - builder.register_handler("request_user_input", request_user_input_handler); + if config.request_user_input { + builder.push_spec(create_request_user_input_tool(CollaborationModesConfig { + default_mode_request_user_input: config.default_mode_request_user_input, + })); + builder.register_handler("request_user_input", request_user_input_handler); + } if config.search_tool && let Some(app_tools) = app_tools @@ -2115,6 +2120,17 @@ mod tests { } } + fn assert_lacks_tool_name(tools: &[ConfiguredToolSpec], expected_absent: &str) { + let names = tools + .iter() + .map(|tool| tool_name(&tool.spec)) + .collect::>(); + assert!( + !names.contains(&expected_absent), + "expected tool {expected_absent} to be absent; had: {names:?}" + ); + } + fn shell_tool_name(config: &ToolsConfig) -> Option<&'static str> { match config.shell_type { ConfigShellToolType::Default => Some("shell"), @@ -2317,6 +2333,7 @@ mod tests { "report_agent_job_result", ], ); + assert_lacks_tool_name(&tools, "request_user_input"); } #[test] From e07eaff0d32caaec47cc4b0616d1b32c086e904f Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 11:25:58 +0000 Subject: [PATCH 372/385] feat: add metric for per-turn tool count and add tmp_mem flag (#13456) --- codex-rs/core/src/state/turn.rs | 1 + codex-rs/core/src/tasks/mod.rs | 27 ++++++++++++++++++++++----- codex-rs/core/src/tools/registry.rs | 8 ++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index 9366880aca..28ae8fec65 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -74,6 +74,7 @@ pub(crate) struct TurnState { pending_user_input: HashMap>, pending_dynamic_tools: HashMap>, pending_input: Vec, + pub(crate) tool_calls: u64, pub(crate) token_usage_at_turn_start: TokenUsage, } diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index a814d36dcc..301d25b6d0 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -38,6 +38,7 @@ use codex_protocol::models::ResponseItem; use codex_protocol::protocol::RolloutItem; use codex_protocol::user_input::UserInput; +use crate::features::Feature; pub(crate) use compact::CompactTask; pub(crate) use ghost_snapshot::GhostSnapshotTask; pub(crate) use regular::RegularTask; @@ -200,11 +201,13 @@ impl Session { let mut pending_input = Vec::::new(); let mut should_clear_active_turn = false; let mut token_usage_at_turn_start = None; + let mut turn_tool_calls = 0_u64; if let Some(at) = active.as_mut() && at.remove_task(&turn_context.sub_id) { let mut ts = at.turn_state.lock().await; pending_input = ts.take_pending_input(); + turn_tool_calls = ts.tool_calls; token_usage_at_turn_start = Some(ts.token_usage_at_turn_start.clone()); should_clear_active_turn = true; } @@ -239,6 +242,20 @@ impl Session { } // Emit token usage metrics. if let Some(token_usage_at_turn_start) = token_usage_at_turn_start { + // TODO(jif): drop this + let tmp_mem = ( + "tmp_mem_enabled", + if self.enabled(Feature::MemoryTool) { + "true" + } else { + "false" + }, + ); + self.services.otel_manager.histogram( + "codex.turn.tool.call", + i64::try_from(turn_tool_calls).unwrap_or(i64::MAX), + &[tmp_mem], + ); let total_token_usage = self.total_token_usage().await.unwrap_or_default(); let turn_token_usage = crate::protocol::TokenUsage { input_tokens: (total_token_usage.input_tokens @@ -260,27 +277,27 @@ impl Session { self.services.otel_manager.histogram( "codex.turn.token_usage", turn_token_usage.total_tokens, - &[("token_type", "total")], + &[("token_type", "total"), tmp_mem], ); self.services.otel_manager.histogram( "codex.turn.token_usage", turn_token_usage.input_tokens, - &[("token_type", "input")], + &[("token_type", "input"), tmp_mem], ); self.services.otel_manager.histogram( "codex.turn.token_usage", turn_token_usage.cached_input(), - &[("token_type", "cached_input")], + &[("token_type", "cached_input"), tmp_mem], ); self.services.otel_manager.histogram( "codex.turn.token_usage", turn_token_usage.output_tokens, - &[("token_type", "output")], + &[("token_type", "output"), tmp_mem], ); self.services.otel_manager.histogram( "codex.turn.token_usage", turn_token_usage.reasoning_output_tokens, - &[("token_type", "reasoning_output")], + &[("token_type", "reasoning_output"), tmp_mem], ); } let event = EventMsg::TurnComplete(TurnCompleteEvent { diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 3c021cc582..77d3c4150b 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -118,6 +118,14 @@ impl ToolRegistry { let mcp_server_ref = mcp_server.as_deref(); let mcp_server_origin_ref = mcp_server_origin.as_deref(); + { + let mut active = invocation.session.active_turn.lock().await; + if let Some(active_turn) = active.as_mut() { + let mut turn_state = active_turn.turn_state.lock().await; + turn_state.tool_calls = turn_state.tool_calls.saturating_add(1); + } + } + let handler = match self.handler(tool_name.as_ref()) { Some(handler) => handler, None => { From df619474f56999b5837da97b34df0eef083b1251 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 13:00:11 +0000 Subject: [PATCH 373/385] nit: citation prompt (#13468) --- codex-rs/core/templates/memories/read_path.md | 1 + 1 file changed, 1 insertion(+) diff --git a/codex-rs/core/templates/memories/read_path.md b/codex-rs/core/templates/memories/read_path.md index b80cc6d13b..0807beb5be 100644 --- a/codex-rs/core/templates/memories/read_path.md +++ b/codex-rs/core/templates/memories/read_path.md @@ -156,6 +156,7 @@ rollout_summaries/2026-02-17T21-23-02-LN3m-weekly_memory_report_pivot_from_git_h - an empty `` section is allowed if no rollout ids are available - you can find rollout ids in rollout summary files and MEMORY.md - do not include file paths or notes in this section + - For every `citation_entries`, try to find and cite the corresponding rollout id if possible - Never include memory citations inside pull-request messages. - Never cite blank lines; double-check ranges. From f72ab43fd193b31208cd3c306293b1b71a52a709 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 13:00:26 +0000 Subject: [PATCH 374/385] feat: memories in workspace write (#13467) --- codex-rs/README.md | 1 + codex-rs/core/src/codex.rs | 6 +-- codex-rs/core/src/config/mod.rs | 60 ++++++++++++++++++++++++ codex-rs/core/src/memories/control.rs | 33 +++++++++++++ codex-rs/core/src/memories/mod.rs | 2 + codex-rs/core/src/memories/tests.rs | 67 +++++++++++++++++++++++++++ 6 files changed, 165 insertions(+), 4 deletions(-) create mode 100644 codex-rs/core/src/memories/control.rs diff --git a/codex-rs/README.md b/codex-rs/README.md index 1c93852fe2..ad8a0506ff 100644 --- a/codex-rs/README.md +++ b/codex-rs/README.md @@ -88,6 +88,7 @@ codex --sandbox danger-full-access ``` The same setting can be persisted in `~/.codex/config.toml` via the top-level `sandbox_mode = "MODE"` key, e.g. `sandbox_mode = "workspace-write"`. +In `workspace-write`, Codex also includes `~/.codex/memories` in its writable roots so memory maintenance does not require an extra approval. ## Code Organization diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 0ac2b14f4b..6cb7b0f616 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -4454,11 +4454,9 @@ mod handlers { } let memory_root = crate::memories::memory_root(&config.codex_home); - if let Err(err) = tokio::fs::remove_dir_all(&memory_root).await - && err.kind() != std::io::ErrorKind::NotFound - { + if let Err(err) = crate::memories::clear_memory_root_contents(&memory_root).await { errors.push(format!( - "failed removing memory directory {}: {err}", + "failed clearing memory directory {}: {err}", memory_root.display() )); } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index ca99cce54b..7fe54289e9 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -40,6 +40,7 @@ use crate::features::FeatureOverrides; use crate::features::Features; use crate::features::FeaturesToml; use crate::git_info::resolve_root_git_project_for_trust; +use crate::memories::memory_root; use crate::model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID; use crate::model_provider_info::LMSTUDIO_OSS_PROVIDER_ID; use crate::model_provider_info::ModelProviderInfo; @@ -1805,6 +1806,15 @@ impl Config { Some(&constrained_sandbox_policy), ); if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = &mut sandbox_policy { + let memories_root = memory_root(&codex_home); + std::fs::create_dir_all(&memories_root)?; + let memories_root = AbsolutePathBuf::from_absolute_path(&memories_root)?; + if !writable_roots + .iter() + .any(|existing| existing == &memories_root) + { + writable_roots.push(memories_root); + } for path in additional_writable_roots { if !writable_roots.iter().any(|existing| existing == &path) { writable_roots.push(path); @@ -3156,6 +3166,56 @@ trust_level = "trusted" Ok(()) } + #[test] + fn workspace_write_always_includes_memories_root_once() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let memories_root = codex_home.path().join("memories"); + let config = Config::load_from_base_config_with_overrides( + ConfigToml { + sandbox_workspace_write: Some(SandboxWorkspaceWrite { + writable_roots: vec![AbsolutePathBuf::from_absolute_path(&memories_root)?], + ..Default::default() + }), + ..Default::default() + }, + ConfigOverrides { + sandbox_mode: Some(SandboxMode::WorkspaceWrite), + ..Default::default() + }, + codex_home.path().to_path_buf(), + )?; + + if cfg!(target_os = "windows") { + match config.permissions.sandbox_policy.get() { + SandboxPolicy::ReadOnly { .. } => {} + other => panic!("expected read-only policy on Windows, got {other:?}"), + } + } else { + assert!( + memories_root.is_dir(), + "expected memories root directory to exist at {}", + memories_root.display() + ); + let expected_memories_root = AbsolutePathBuf::from_absolute_path(&memories_root)?; + match config.permissions.sandbox_policy.get() { + SandboxPolicy::WorkspaceWrite { writable_roots, .. } => { + assert_eq!( + writable_roots + .iter() + .filter(|root| **root == expected_memories_root) + .count(), + 1, + "expected single writable root entry for {}", + expected_memories_root.display() + ); + } + other => panic!("expected workspace-write policy, got {other:?}"), + } + } + + Ok(()) + } + #[test] fn config_defaults_to_file_cli_auth_store_mode() -> std::io::Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/core/src/memories/control.rs b/codex-rs/core/src/memories/control.rs new file mode 100644 index 0000000000..10bd19246f --- /dev/null +++ b/codex-rs/core/src/memories/control.rs @@ -0,0 +1,33 @@ +use std::path::Path; + +pub(crate) async fn clear_memory_root_contents(memory_root: &Path) -> std::io::Result<()> { + match tokio::fs::symlink_metadata(memory_root).await { + Ok(metadata) if metadata.file_type().is_symlink() => { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "refusing to clear symlinked memory root {}", + memory_root.display() + ), + )); + } + Ok(_) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => return Err(err), + } + + tokio::fs::create_dir_all(memory_root).await?; + + let mut entries = tokio::fs::read_dir(memory_root).await?; + while let Some(entry) = entries.next_entry().await? { + let path = entry.path(); + let file_type = entry.file_type().await?; + if file_type.is_dir() { + tokio::fs::remove_dir_all(path).await?; + } else { + tokio::fs::remove_file(path).await?; + } + } + + Ok(()) +} diff --git a/codex-rs/core/src/memories/mod.rs b/codex-rs/core/src/memories/mod.rs index a90eba6bec..83604b6afa 100644 --- a/codex-rs/core/src/memories/mod.rs +++ b/codex-rs/core/src/memories/mod.rs @@ -5,6 +5,7 @@ //! - Phase 2: claim a global consolidation lock, materialize consolidation inputs, and dispatch one consolidation agent. pub(crate) mod citations; +mod control; mod phase1; mod phase2; pub(crate) mod prompts; @@ -16,6 +17,7 @@ pub(crate) mod usage; use codex_protocol::openai_models::ReasoningEffort; +pub(crate) use control::clear_memory_root_contents; /// Starts the memory startup pipeline for eligible root sessions. /// This is the single entrypoint that `codex` uses to trigger memory startup. /// diff --git a/codex-rs/core/src/memories/tests.rs b/codex-rs/core/src/memories/tests.rs index 0ebc0b8f16..1c0fa7b29b 100644 --- a/codex-rs/core/src/memories/tests.rs +++ b/codex-rs/core/src/memories/tests.rs @@ -1,6 +1,7 @@ use super::storage::rebuild_raw_memories_file_from_memories; use super::storage::sync_rollout_summaries_from_memories; use crate::config::types::DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION; +use crate::memories::clear_memory_root_contents; use crate::memories::ensure_layout; use crate::memories::memory_root; use crate::memories::raw_memories_file; @@ -63,6 +64,72 @@ fn stage_one_output_schema_requires_rollout_slug_and_keeps_it_nullable() { assert_eq!(rollout_slug_types, vec!["null", "string"]); } +#[tokio::test] +async fn clear_memory_root_contents_preserves_root_directory() { + let dir = tempdir().expect("tempdir"); + let root = dir.path().join("memory"); + let nested_dir = root.join("rollout_summaries"); + tokio::fs::create_dir_all(&nested_dir) + .await + .expect("create rollout summaries dir"); + tokio::fs::write(root.join("MEMORY.md"), "stale memory index\n") + .await + .expect("write memory index"); + tokio::fs::write(nested_dir.join("rollout.md"), "stale rollout\n") + .await + .expect("write rollout summary"); + + clear_memory_root_contents(&root) + .await + .expect("clear memory root contents"); + + assert!( + tokio::fs::try_exists(&root) + .await + .expect("check memory root existence"), + "memory root should still exist after clearing contents" + ); + let mut entries = tokio::fs::read_dir(&root) + .await + .expect("read memory root after clear"); + assert!( + entries + .next_entry() + .await + .expect("read next entry") + .is_none(), + "memory root should be empty after clearing contents" + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn clear_memory_root_contents_rejects_symlinked_root() { + let dir = tempdir().expect("tempdir"); + let target = dir.path().join("outside"); + tokio::fs::create_dir_all(&target) + .await + .expect("create symlink target dir"); + let target_file = target.join("keep.txt"); + tokio::fs::write(&target_file, "keep\n") + .await + .expect("write target file"); + + let root = dir.path().join("memory"); + std::os::unix::fs::symlink(&target, &root).expect("create memory root symlink"); + + let err = clear_memory_root_contents(&root) + .await + .expect_err("symlinked memory root should be rejected"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert!( + tokio::fs::try_exists(&target_file) + .await + .expect("check target file existence"), + "rejecting a symlinked memory root should not delete the symlink target" + ); +} + #[tokio::test] async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only() { let dir = tempdir().expect("tempdir"); From 8a593862736e5a3dc701b05838b682299551c36b Mon Sep 17 00:00:00 2001 From: Alex Daley Date: Wed, 4 Mar 2026 11:41:54 -0500 Subject: [PATCH 375/385] add new scopes to login (#12383) Validated login + refresh flows. Removing scopes from the refresh request until we have upgrade flow in place. Confirmed that tokens refresh with existing scopes. --- codex-rs/core/src/auth.rs | 2 -- codex-rs/login/src/server.rs | 3 ++- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index cca57d5c0f..546d53b79f 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -626,7 +626,6 @@ async fn request_chatgpt_token_refresh( client_id: CLIENT_ID, grant_type: "refresh_token", refresh_token, - scope: "openid profile email", }; let endpoint = refresh_token_endpoint(); @@ -722,7 +721,6 @@ struct RefreshRequest { client_id: &'static str, grant_type: &'static str, refresh_token: String, - scope: &'static str, } #[derive(Deserialize, Clone)] diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 53b4ad3601..73d6b1e154 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -431,7 +431,8 @@ fn build_authorize_url( ("redirect_uri".to_string(), redirect_uri.to_string()), ( "scope".to_string(), - "openid profile email offline_access".to_string(), + "openid profile email offline_access api.connectors.read api.connectors.invoke" + .to_string(), ), ( "code_challenge".to_string(), From 54a1c81d73f0060aab97ab8ed5025f813fbe0555 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Wed, 4 Mar 2026 10:54:30 -0800 Subject: [PATCH 376/385] allow apps to specify cwd for sandbox setup. (#13484) The electron app doesn't start up the app-server in a particular workspace directory. So sandbox setup happens in the app-installed directory instead of the project workspace. This allows the app do specify the workspace cwd so that the sandbox setup actually sets up the ACLs instead of exiting fast and then having the first shell command be slow. --- .../schema/json/ClientRequest.json | 8 +++- .../codex_app_server_protocol.schemas.json | 8 +++- .../codex_app_server_protocol.v2.schemas.json | 8 +++- .../v2/WindowsSandboxSetupStartParams.json | 8 +++- .../v2/WindowsSandboxSetupStartParams.ts | 2 +- .../app-server-protocol/src/protocol/v2.rs | 2 + codex-rs/app-server/README.md | 2 +- .../app-server/src/codex_message_processor.rs | 38 ++++++++++++++----- .../tests/suite/v2/windows_sandbox_setup.rs | 1 + 9 files changed, 61 insertions(+), 16 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index e57ffa12c9..62495a79a1 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -2864,6 +2864,12 @@ }, "WindowsSandboxSetupStartParams": { "properties": { + "cwd": { + "type": [ + "string", + "null" + ] + }, "mode": { "$ref": "#/definitions/WindowsSandboxSetupMode" } @@ -3908,4 +3914,4 @@ } ], "title": "ClientRequest" -} \ No newline at end of file +} diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 2ccd20466c..f09f2fc553 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -15325,6 +15325,12 @@ "WindowsSandboxSetupStartParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "cwd": { + "type": [ + "string", + "null" + ] + }, "mode": { "$ref": "#/definitions/v2/WindowsSandboxSetupMode" } @@ -15385,4 +15391,4 @@ }, "title": "CodexAppServerProtocol", "type": "object" -} \ No newline at end of file +} diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 1bbea24c8a..7f37aaecb9 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -14226,6 +14226,12 @@ "WindowsSandboxSetupStartParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "cwd": { + "type": [ + "string", + "null" + ] + }, "mode": { "$ref": "#/definitions/WindowsSandboxSetupMode" } @@ -14285,4 +14291,4 @@ }, "title": "CodexAppServerProtocolV2", "type": "object" -} \ No newline at end of file +} diff --git a/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json index 6f0663d200..663d360649 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json @@ -10,6 +10,12 @@ } }, "properties": { + "cwd": { + "type": [ + "string", + "null" + ] + }, "mode": { "$ref": "#/definitions/WindowsSandboxSetupMode" } @@ -19,4 +25,4 @@ ], "title": "WindowsSandboxSetupStartParams", "type": "object" -} \ No newline at end of file +} diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WindowsSandboxSetupStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WindowsSandboxSetupStartParams.ts index 21daf64628..cb342c24cd 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/WindowsSandboxSetupStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WindowsSandboxSetupStartParams.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { WindowsSandboxSetupMode } from "./WindowsSandboxSetupMode"; -export type WindowsSandboxSetupStartParams = { mode: WindowsSandboxSetupMode, }; +export type WindowsSandboxSetupStartParams = { mode: WindowsSandboxSetupMode, cwd?: string | null, }; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 2147295c9a..185d74fad4 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -3927,6 +3927,8 @@ pub enum WindowsSandboxSetupMode { #[ts(export_to = "v2/")] pub struct WindowsSandboxSetupStartParams { pub mode: WindowsSandboxSetupMode, + #[ts(optional = nullable)] + pub cwd: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 068d4ee18e..fa16272191 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -157,7 +157,7 @@ Example with notification opt-out: - `tool/requestUserInput` — prompt the user with 1–3 short questions for a tool call and return their answers (experimental). - `config/mcpServer/reload` — reload MCP server config from disk and queue a refresh for loaded threads (applied on each thread's next active turn); returns `{}`. Use this after editing `config.toml` without restarting the server. - `mcpServerStatus/list` — enumerate configured MCP servers with their tools, resources, resource templates, and auth status; supports cursor+limit pagination. -- `windowsSandbox/setupStart` — start Windows sandbox setup for the selected mode (`elevated` or `unelevated`); returns `{ started: true }` immediately and later emits `windowsSandbox/setupCompleted`. +- `windowsSandbox/setupStart` — start Windows sandbox setup for the selected mode (`elevated` or `unelevated`); accepts an optional `cwd` to target setup for a specific workspace, returns `{ started: true }` immediately, and later emits `windowsSandbox/setupCompleted`. - `feedback/upload` — submit a feedback report (classification + optional reason/logs, conversation_id, and optional `extraLogFiles` attachments array); returns the tracking thread id. - `command/exec` — run a single command under the server sandbox without starting a thread/turn (handy for utilities and validation). - `config/read` — fetch the effective config on disk after resolving config layering. diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 80558642cb..8d9f08ce60 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -6119,21 +6119,39 @@ impl CodexMessageProcessor { WindowsSandboxSetupMode::Unelevated => CoreWindowsSandboxSetupMode::Unelevated, }; let config = Arc::clone(&self.config); + let cli_overrides = self.cli_overrides.clone(); + let cloud_requirements = self.current_cloud_requirements(); + let command_cwd = params.cwd.unwrap_or_else(|| config.cwd.clone()); let outgoing = Arc::clone(&self.outgoing); let connection_id = request_id.connection_id; tokio::spawn(async move { - let setup_request = WindowsSandboxSetupRequest { - mode, - policy: config.permissions.sandbox_policy.get().clone(), - policy_cwd: config.cwd.clone(), - command_cwd: config.cwd.clone(), - env_map: std::env::vars().collect(), - codex_home: config.codex_home.clone(), - active_profile: config.active_profile.clone(), + let derived_config = derive_config_for_cwd( + &cli_overrides, + None, + ConfigOverrides { + cwd: Some(command_cwd.clone()), + ..Default::default() + }, + Some(command_cwd.clone()), + &cloud_requirements, + ) + .await; + let setup_result = match derived_config { + Ok(config) => { + let setup_request = WindowsSandboxSetupRequest { + mode, + policy: config.permissions.sandbox_policy.get().clone(), + policy_cwd: config.cwd.clone(), + command_cwd, + env_map: std::env::vars().collect(), + codex_home: config.codex_home.clone(), + active_profile: config.active_profile.clone(), + }; + codex_core::windows_sandbox::run_windows_sandbox_setup(setup_request).await + } + Err(err) => Err(err.into()), }; - let setup_result = - codex_core::windows_sandbox::run_windows_sandbox_setup(setup_request).await; let notification = WindowsSandboxSetupCompletedNotification { mode: match mode { CoreWindowsSandboxSetupMode::Elevated => WindowsSandboxSetupMode::Elevated, diff --git a/codex-rs/app-server/tests/suite/v2/windows_sandbox_setup.rs b/codex-rs/app-server/tests/suite/v2/windows_sandbox_setup.rs index 1f069b3cab..4512d9058f 100644 --- a/codex-rs/app-server/tests/suite/v2/windows_sandbox_setup.rs +++ b/codex-rs/app-server/tests/suite/v2/windows_sandbox_setup.rs @@ -37,6 +37,7 @@ async fn windows_sandbox_setup_start_emits_completion_notification() -> Result<( let request_id = mcp .send_windows_sandbox_setup_start_request(WindowsSandboxSetupStartParams { mode: WindowsSandboxSetupMode::Unelevated, + cwd: None, }) .await?; let response: JSONRPCResponse = timeout( From 27724f6ead1a47720ac14173d84bb4fa0d7812df Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Wed, 4 Mar 2026 11:09:17 -0800 Subject: [PATCH 377/385] feat(core, tracing): add a span representing a turn (#13424) This is PR 3 of the app-server tracing rollout. PRs https://github.com/openai/codex/pull/13285 and https://github.com/openai/codex/pull/13368 gave us inbound request spans in app-server and propagated trace context through Submission. This change finishes the next piece in core: when a request actually starts a turn, we now create a core-owned long-lived span that stays open for the real lifetime of the turn. What changed: - `Session::spawn_task` can now optionally create a long-lived turn span and run the spawned task inside it - `turn/start` uses that path, so normal turn execution stays under a single core-owned span after the async handoff - `review/start` uses the same pattern - added a unit test that verifies the spawned turn task inherits the submission dispatch trace ancestry **Why** The app-server request span is intentionally short-lived. Once work crosses into core, we still want one span that covers the actual execution window until completion or interruption. This keeps that ownership where it belongs: in the layer that owns the runtime lifecycle. --- codex-rs/core/src/codex.rs | 127 ++++++++++++++++++++-- codex-rs/core/src/tasks/compact.rs | 4 + codex-rs/core/src/tasks/ghost_snapshot.rs | 4 + codex-rs/core/src/tasks/mod.rs | 18 ++- codex-rs/core/src/tasks/regular.rs | 4 + codex-rs/core/src/tasks/review.rs | 4 + codex-rs/core/src/tasks/undo.rs | 4 + codex-rs/core/src/tasks/user_shell.rs | 4 + 8 files changed, 158 insertions(+), 11 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 6cb7b0f616..1e1d96d4a1 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -6710,6 +6710,7 @@ mod tests { use serde_json::json; use std::path::PathBuf; use std::sync::Arc; + use std::sync::Once; use std::time::Duration as StdDuration; struct InstructionsTestCase { @@ -8176,10 +8177,16 @@ mod tests { }) } - fn test_tracing_subscriber() -> impl tracing::Subscriber + Send + Sync { - let provider = SdkTracerProvider::builder().build(); - let tracer = provider.tracer("codex-core-tests"); - tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer)) + fn init_test_tracing() { + static INIT: Once = Once::new(); + INIT.call_once(|| { + let provider = SdkTracerProvider::builder().build(); + let tracer = provider.tracer("codex-core-tests"); + let subscriber = tracing_subscriber::registry() + .with(tracing_opentelemetry::layer().with_tracer(tracer)); + tracing::subscriber::set_global_default(subscriber) + .expect("global tracing subscriber should only be installed once"); + }); } async fn build_test_config(codex_home: &Path) -> Config { @@ -8525,8 +8532,7 @@ mod tests { session: Arc::new(session), }; - let subscriber = test_tracing_subscriber(); - let _guard = tracing::subscriber::set_default(subscriber); + init_test_tracing(); let request_parent = W3cTraceContext { traceparent: Some("00-00000000000000000000000000000011-0000000000000022-01".into()), @@ -8560,8 +8566,7 @@ mod tests { #[test] fn submission_dispatch_span_prefers_submission_trace_context() { - let subscriber = test_tracing_subscriber(); - let _guard = tracing::subscriber::set_default(subscriber); + init_test_tracing(); let ambient_parent = W3cTraceContext { traceparent: Some("00-00000000000000000000000000000033-0000000000000044-01".into()), @@ -8592,6 +8597,108 @@ mod tests { ); } + #[tokio::test] + async fn spawn_task_turn_span_inherits_dispatch_trace_context() { + struct TraceCaptureTask { + captured_trace: Arc>>, + } + + #[async_trait::async_trait] + impl SessionTask for TraceCaptureTask { + fn kind(&self) -> TaskKind { + TaskKind::Regular + } + + fn span_name(&self) -> &'static str { + "session_task.trace_capture" + } + + async fn run( + self: Arc, + _session: Arc, + _ctx: Arc, + _input: Vec, + _cancellation_token: CancellationToken, + ) -> Option { + let mut trace = self + .captured_trace + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + *trace = current_span_w3c_trace_context(); + None + } + } + + init_test_tracing(); + + let request_parent = W3cTraceContext { + traceparent: Some("00-00000000000000000000000000000011-0000000000000022-01".into()), + tracestate: Some("vendor=value".into()), + }; + let request_span = tracing::info_span!("app_server.request"); + assert!(set_parent_from_w3c_trace_context( + &request_span, + &request_parent + )); + + let submission_trace = async { + current_span_w3c_trace_context().expect("request span should have trace context") + } + .instrument(request_span) + .await; + + let dispatch_span = submission_dispatch_span(&Submission { + id: "sub-1".into(), + op: Op::Interrupt, + trace: Some(submission_trace.clone()), + }); + let dispatch_span_id = dispatch_span.context().span().span_context().span_id(); + + let (sess, tc, rx) = make_session_and_context_with_rx().await; + let captured_trace = Arc::new(std::sync::Mutex::new(None)); + + async { + sess.spawn_task( + Arc::clone(&tc), + vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + TraceCaptureTask { + captured_trace: Arc::clone(&captured_trace), + }, + ) + .await; + } + .instrument(dispatch_span) + .await; + + let evt = tokio::time::timeout(StdDuration::from_secs(2), rx.recv()) + .await + .expect("timeout waiting for turn completion") + .expect("event"); + assert!(matches!(evt.msg, EventMsg::TurnComplete(_))); + + let task_trace = captured_trace + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .expect("turn task should capture the current span trace context"); + let submission_context = + codex_otel::context_from_w3c_trace_context(&submission_trace).expect("submission"); + let task_context = + codex_otel::context_from_w3c_trace_context(&task_trace).expect("task trace"); + + assert_eq!( + task_context.span().span_context().trace_id(), + submission_context.span().span_context().trace_id() + ); + assert_ne!( + task_context.span().span_context().span_id(), + dispatch_span_id + ); + } + pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( dynamic_tools: Vec, ) -> ( @@ -9396,6 +9503,10 @@ mod tests { self.kind } + fn span_name(&self) -> &'static str { + "session_task.never_ending" + } + async fn run( self: Arc, _session: Arc, diff --git a/codex-rs/core/src/tasks/compact.rs b/codex-rs/core/src/tasks/compact.rs index db2a494c3e..a8c0a5e06d 100644 --- a/codex-rs/core/src/tasks/compact.rs +++ b/codex-rs/core/src/tasks/compact.rs @@ -17,6 +17,10 @@ impl SessionTask for CompactTask { TaskKind::Compact } + fn span_name(&self) -> &'static str { + "session_task.compact" + } + async fn run( self: Arc, session: Arc, diff --git a/codex-rs/core/src/tasks/ghost_snapshot.rs b/codex-rs/core/src/tasks/ghost_snapshot.rs index 48a6137c6d..ded8533a23 100644 --- a/codex-rs/core/src/tasks/ghost_snapshot.rs +++ b/codex-rs/core/src/tasks/ghost_snapshot.rs @@ -32,6 +32,10 @@ impl SessionTask for GhostSnapshotTask { TaskKind::Regular } + fn span_name(&self) -> &'static str { + "session_task.ghost_snapshot" + } + async fn run( self: Arc, session: Arc, diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 301d25b6d0..a8feeb5133 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -14,7 +14,7 @@ use tokio::sync::Notify; use tokio_util::sync::CancellationToken; use tokio_util::task::AbortOnDropHandle; use tracing::Instrument; -use tracing::Span; +use tracing::info_span; use tracing::trace; use tracing::warn; @@ -89,6 +89,9 @@ pub(crate) trait SessionTask: Send + Sync + 'static { /// surface it in telemetry and UI. fn kind(&self) -> TaskKind; + /// Returns the tracing name for a spawned task span. + fn span_name(&self) -> &'static str; + /// Executes the task until completion or cancellation. /// /// Implementations typically stream protocol events using `session` and @@ -127,6 +130,7 @@ impl Session { let task: Arc = Arc::new(task); let task_kind = task.kind(); + let span_name = task.span_name(); let cancellation_token = CancellationToken::new(); let done = Arc::new(Notify::new()); @@ -137,7 +141,15 @@ impl Session { let ctx = Arc::clone(&turn_context); let task_for_run = Arc::clone(&task); let task_cancellation_token = cancellation_token.child_token(); - let session_span = Span::current(); + // Task-owned turn spans keep a core-owned span open for the + // full task lifecycle after the submission dispatch span ends. + let task_span = info_span!( + "turn", + otel.name = span_name, + thread.id = %self.conversation_id, + turn.id = %turn_context.sub_id, + model = %turn_context.model_info.slug, + ); tokio::spawn( async move { let ctx_for_finish = Arc::clone(&ctx); @@ -158,7 +170,7 @@ impl Session { } done_clone.notify_waiters(); } - .instrument(session_span), + .instrument(task_span), ) }; diff --git a/codex-rs/core/src/tasks/regular.rs b/codex-rs/core/src/tasks/regular.rs index b4af4e11f3..e3a9ef4c38 100644 --- a/codex-rs/core/src/tasks/regular.rs +++ b/codex-rs/core/src/tasks/regular.rs @@ -68,6 +68,10 @@ impl SessionTask for RegularTask { TaskKind::Regular } + fn span_name(&self) -> &'static str { + "session_task.turn" + } + async fn run( self: Arc, session: Arc, diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index 4192236b48..4787ee7826 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -43,6 +43,10 @@ impl SessionTask for ReviewTask { TaskKind::Review } + fn span_name(&self) -> &'static str { + "session_task.review" + } + async fn run( self: Arc, session: Arc, diff --git a/codex-rs/core/src/tasks/undo.rs b/codex-rs/core/src/tasks/undo.rs index b2fb4577a8..95f51c1ec3 100644 --- a/codex-rs/core/src/tasks/undo.rs +++ b/codex-rs/core/src/tasks/undo.rs @@ -31,6 +31,10 @@ impl SessionTask for UndoTask { TaskKind::Regular } + fn span_name(&self) -> &'static str { + "session_task.undo" + } + async fn run( self: Arc, session: Arc, diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 18dc5006ed..deab56bc5a 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -66,6 +66,10 @@ impl SessionTask for UserShellCommandTask { TaskKind::Regular } + fn span_name(&self) -> &'static str { + "session_task.user_shell" + } + async fn run( self: Arc, session: Arc, From 26f4b8e2f149fec91ffa26f384e6e622a5dc9bb4 Mon Sep 17 00:00:00 2001 From: Val Kharitonov Date: Wed, 4 Mar 2026 11:12:40 -0800 Subject: [PATCH 378/385] remove serviceTier from app-server examples (#13489) Documentation-only --- codex-rs/app-server/README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index fa16272191..f7d7628761 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -180,7 +180,6 @@ Start a fresh thread when you need a new Codex conversation. "approvalPolicy": "never", "sandbox": "workspaceWrite", "personality": "friendly", - "serviceTier": "flex", "serviceName": "my_app_server_client", // optional metrics tag (`service_name`) // Experimental: requires opt-in "dynamicTools": [ @@ -209,7 +208,6 @@ Start a fresh thread when you need a new Codex conversation. ``` Valid `personality` values are `"friendly"`, `"pragmatic"`, and `"none"`. When `"none"` is selected, the personality placeholder is replaced with an empty string. -Valid `serviceTier` values are `"fast"` and `"flex"`. To continue a stored session, call `thread/resume` with the `thread.id` you previously recorded. The response shape matches `thread/start`, and no additional notifications are emitted. You can also pass the same configuration overrides supported by `thread/start`, such as `personality`: @@ -417,7 +415,6 @@ You can optionally specify config overrides on the new turn. If specified, these "networkAccess": true }, "model": "gpt-5.1-codex", - "serviceTier": "flex", "effort": "medium", "summary": "concise", "personality": "friendly", From b200a5f45bf6a81b16c7b2e6f04dbe5eb172863c Mon Sep 17 00:00:00 2001 From: pash-openai Date: Wed, 4 Mar 2026 11:30:51 -0800 Subject: [PATCH 379/385] [tui] Update Fast slash command description (#13458) ## Summary - update the /fast slash command description to mention fastest inference - mention the 3X plan usage tradeoff in the help copy ## Testing - cargo test -p codex-tui slash_command (currently blocked by an unrelated latest-main codex-tui compile error in chatwidget.rs: refresh_queued_user_messages missing) --------- Co-authored-by: Codex --- codex-rs/tui/src/slash_command.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 4bf3737033..e8830d8d47 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -90,7 +90,7 @@ impl SlashCommand { SlashCommand::MemoryDrop => "DO NOT USE", SlashCommand::MemoryUpdate => "DO NOT USE", SlashCommand::Model => "choose what model and reasoning effort to use", - SlashCommand::Fast => "toggle Fast mode for supported models", + SlashCommand::Fast => "toggle Fast mode to enable fastest inference at 3X plan usage", SlashCommand::Personality => "choose a communication style for Codex", SlashCommand::Realtime => "toggle realtime voice mode (experimental)", SlashCommand::Settings => "configure realtime microphone/speaker", From 98923e53ccd0481925cb26f7146e80a6a4c42405 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Wed, 4 Mar 2026 17:03:34 -0300 Subject: [PATCH 380/385] fix(tui): decode ANSI alpha-channel encoding in syntax themes (#13382) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem The `ansi`, `base16`, and `base16-256` syntax themes are designed to emit ANSI palette colors so that highlighted code respects the user's terminal color scheme. Syntect encodes this intent in the alpha channel of its `Color` struct — a convention shared with `bat` — but `convert_style` was ignoring it entirely, treating every foreground color as raw RGB. This caused ANSI-family themes to produce hard-coded RGB values (e.g. `Rgb(0x02, 0, 0)` instead of `Green`), defeating their purpose and rendering them as near-invisible dark colors on most terminals. Reported in #12890. ## Mental model Syntect themes use a compact encoding in their `Color` struct: | `alpha` | Meaning of `r` | Mapped to | |---------|----------------|-----------| | `0x00` | ANSI palette index (0–255) | `RtColor::Black`…`Gray` for 0–7, `Indexed(n)` for 8–255 | | `0x01` | Unused (sentinel) | `None` — inherit terminal default fg/bg | | `0xFF` | True RGB red channel | `RtColor::Rgb(r, g, b)` | | other | Unexpected | `RtColor::Rgb(r, g, b)` (silent fallback) | This encoding is a bat convention that three bundled themes rely on. The new `convert_syntect_color` function decodes it; `ansi_palette_color` maps indices 0–7 to ratatui's named ANSI variants. | macOS - Dark | macOS - Light | Windows - ansi | Windows - base16 | |---|---|---|---| | macos-dark | macos-light | ![windows-ansi](https://github.com/user-attachments/assets/d41029e6-ffd3-454e-ab72-6751607e5d5c) | ![windows-base16](https://github.com/user-attachments/assets/b48aafcc-0196-4977-8ee1-8f8eaddd1698) | ## Non-goals - Background color decoding — we intentionally skip backgrounds to preserve the terminal's own background. The decoder supports it, but `convert_style` does not apply it. - Italic/underline changes — those remain suppressed as before. - Custom `.tmTheme` support for ANSI encoding — only the bundled themes use this convention. ## Tradeoffs - The alpha-channel encoding is an undocumented bat/syntect convention, not a formal spec. We match bat's behavior exactly, trading formality for ecosystem compatibility. - Indices 0–7 are mapped to ratatui's named variants (`Black`, `Red`, …, `Gray`) rather than `Indexed(0)`…`Indexed(7)`. This lets terminals apply bold/bright semantics to named colors, which is the expected behavior for ANSI themes, but means the two representations are not perfectly round-trippable. ## Architecture All changes are in `codex-rs/tui/src/render/highlight.rs`, within the style-conversion layer between syntect and ratatui: ``` syntect::highlighting::Color └─ convert_syntect_color(color) [NEW — alpha-dispatch] ├─ a=0x00 → ansi_palette_color() [NEW — index→named/indexed] ├─ a=0x01 → None (terminal default) ├─ a=0xFF → Rgb(r,g,b) (standard opaque path) └─ other → Rgb(r,g,b) (silent fallback) ``` `convert_style` delegates foreground mapping to `convert_syntect_color` instead of inlining the `Rgb(r,g,b)` conversion. The core highlighter is refactored into `highlight_to_line_spans_with_theme` (accepts an explicit theme reference) so tests can highlight against specific themes without mutating process-global state. ### ANSI-family theme contract The ANSI-family themes (`ansi`, `base16`, `base16-256`) rely on upstream alpha-channel encoding from two_face/syntect. We intentionally do **not** validate this contract at runtime — if the upstream format changes, the `ansi_themes_use_only_ansi_palette_colors` test catches it at build time, long before it reaches users. A runtime warning would be unactionable noise. ### Warning copy cleanup User-facing warning messages were rewritten for clarity: - Removed internal jargon ("alpha-encoded ANSI color markers", "RGB fallback semantics", "persisted override config") - Dropped "syntax" prefix from "syntax theme" — users just think "theme" - Downgraded developer-only diagnostics (duplicate override, resolve fallback) from `warn` to `debug` ## Observability - The `ansi_themes_use_only_ansi_palette_colors` test enforces the ANSI-family contract at build time. - The snapshot test provides a regression tripwire for palette color output. - User-facing warnings are limited to actionable issues: unknown theme names and invalid custom `.tmTheme` files. ## Tests - **Unit tests for each alpha branch:** `alpha=0x00` with low index (named color), `alpha=0x00` with high index (`Indexed`), `alpha=0x01` (terminal default), unexpected alpha (falls back to RGB), ANSI white → Gray mapping. - **Integration test:** `ansi_family_themes_use_terminal_palette_colors_not_rgb` — highlights a Rust snippet with each ANSI-family theme and asserts zero `Rgb` foreground colors appear. - **Snapshot test:** `ansi_family_foreground_palette_snapshot` — records the exact set of unique foreground colors each ANSI-family theme produces, guarding against regressions. - **Warning validation tests:** verify user-facing warnings for missing custom themes, invalid `.tmTheme` files, and bundled theme resolution. ## Test plan - [ ] `cargo test -p codex-tui` passes all new and existing tests - [ ] Select `ansi`, `base16`, or `base16-256` theme and verify code blocks render with terminal palette colors (not near-black RGB) - [ ] Select a standard RGB theme (e.g. `dracula`) and verify no regression in color output --- codex-rs/tui/src/render/highlight.rs | 300 +++++++++++++++--- ...tests__ansi_family_foreground_palette.snap | 21 ++ 2 files changed, 284 insertions(+), 37 deletions(-) create mode 100644 codex-rs/tui/src/render/snapshots/codex_tui__render__highlight__tests__ansi_family_foreground_palette.snap diff --git a/codex-rs/tui/src/render/highlight.rs b/codex-rs/tui/src/render/highlight.rs index 2fd0abbb94..b44fc0a742 100644 --- a/codex-rs/tui/src/render/highlight.rs +++ b/codex-rs/tui/src/render/highlight.rs @@ -31,6 +31,7 @@ use std::path::PathBuf; use std::sync::OnceLock; use std::sync::RwLock; use syntect::easy::HighlightLines; +use syntect::highlighting::Color as SyntectColor; use syntect::highlighting::FontStyle; use syntect::highlighting::Highlighter; use syntect::highlighting::Style as SyntectStyle; @@ -49,10 +50,23 @@ static THEME: OnceLock> = OnceLock::new(); static THEME_OVERRIDE: OnceLock> = OnceLock::new(); static CODEX_HOME: OnceLock> = OnceLock::new(); +// Syntect/bat encode ANSI palette semantics in alpha: +// `a=0` => indexed ANSI palette via RGB payload, `a=1` => terminal default. +const ANSI_ALPHA_INDEX: u8 = 0x00; +const ANSI_ALPHA_DEFAULT: u8 = 0x01; +const OPAQUE_ALPHA: u8 = 0xFF; + fn syntax_set() -> &'static SyntaxSet { SYNTAX_SET.get_or_init(two_face::syntax::extra_newlines) } +// NOTE: We intentionally do NOT emit a runtime diagnostic when an ANSI-family +// theme (ansi, base16, base16-256) lacks the expected alpha-channel marker +// encoding. If the upstream two_face/syntect theme format changes, the +// `ansi_themes_use_only_ansi_palette_colors` test will catch it at build +// time — long before it reaches users. A runtime warning would be +// unactionable noise since users can't fix upstream themes. + /// Set the user-configured syntax theme override and codex home path. /// /// Call this with the **final resolved config** (after onboarding, resume, and @@ -62,15 +76,13 @@ fn syntax_set() -> &'static SyntaxSet { /// Subsequent calls cannot change the persisted `OnceLock` values, but they /// still update the runtime theme immediately for live preview flows. /// -/// Returns a warning message when the configured theme name cannot be -/// resolved to a bundled theme or a custom `.tmTheme` file on disk. -/// The caller should surface this via `Config::startup_warnings` so it -/// appears as a `⚠` banner in the TUI. +/// Returns user-facing warnings for actionable configuration issues, such as +/// unknown/invalid theme names or duplicate override persistence. pub(crate) fn set_theme_override( name: Option, codex_home: Option, ) -> Option { - let mut warning = validate_theme_name(name.as_deref(), codex_home.as_deref()); + let warning = validate_theme_name(name.as_deref(), codex_home.as_deref()); let override_set_ok = THEME_OVERRIDE.set(name.clone()).is_ok(); let codex_home_set_ok = CODEX_HOME.set(codex_home.clone()).is_ok(); if THEME.get().is_some() { @@ -80,11 +92,10 @@ pub(crate) fn set_theme_override( )); } if !override_set_ok || !codex_home_set_ok { - let duplicate_msg = "Ignoring duplicate or late syntax theme override persistence; runtime theme was updated from the latest override, but persisted override config can only be initialized once."; - tracing::warn!("{duplicate_msg}"); - if warning.is_none() { - warning = Some(duplicate_msg.to_string()); - } + // This should never happen in practice — set_theme_override is only + // called once at startup. Keep as a debug breadcrumb in case a second + // call site is added in the future. + tracing::debug!("set_theme_override called more than once; OnceLock values unchanged"); } warning } @@ -109,15 +120,15 @@ pub(crate) fn validate_theme_name(name: Option<&str>, codex_home: Option<&Path>) return None; } return Some(format!( - "Syntax theme \"{name}\" was found at {custom_theme_path_display} \ - but could not be parsed. Falling back to auto-detection." + "Custom theme \"{name}\" at {custom_theme_path_display} could not \ + be loaded (invalid .tmTheme format). Falling back to the default theme." )); } } Some(format!( - "Unknown syntax theme \"{name}\", falling back to auto-detection. \ - Use a bundled name or place a .tmTheme file at \ - {custom_theme_path_display}" + "Theme \"{name}\" not found. Using the default theme. \ + To use a custom theme, place a .tmTheme file at \ + {custom_theme_path_display}." )) } @@ -189,7 +200,7 @@ pub(crate) fn adaptive_default_theme_name() -> &'static str { adaptive_default_theme_selection().1 } -/// Build the theme from current override/auto-detection settings. +/// Build the theme from current override/default-theme settings. /// Extracted from the old `theme()` init closure so it can be reused. fn resolve_theme_with_override(name: Option<&str>, codex_home: Option<&Path>) -> Theme { let ts = two_face::theme::extra(); @@ -206,13 +217,13 @@ fn resolve_theme_with_override(name: Option<&str>, codex_home: Option<&Path>) -> { return theme; } - tracing::warn!("unknown syntax theme \"{name}\", falling back to auto-detection"); + tracing::debug!("Theme \"{name}\" not recognized; using default theme"); } ts.get(adaptive_default_embedded_theme_name()).clone() } -/// Build the theme from current override/auto-detection settings. +/// Build the theme from current override/default-theme settings. /// Extracted from the old `theme()` init closure so it can be reused. fn build_default_theme() -> Theme { let name = THEME_OVERRIDE.get().and_then(|name| name.as_deref()); @@ -412,20 +423,71 @@ const BUILTIN_THEME_NAMES: &[&str] = &[ // -- Style conversion (syntect -> ratatui) ------------------------------------ +/// Map a low ANSI palette index (0–7) to ratatui's named color variants, +/// falling back to `Indexed(n)` for indices 8–255. +/// +/// Named variants are preferred over `Indexed(0)`…`Indexed(7)` because many +/// terminals apply bold/bright treatment differently for named vs indexed +/// colors, and ANSI themes expect the named behavior. +/// +/// `clippy::disallowed_methods` is explicitly allowed here because this helper +/// intentionally constructs `ratatui::style::Color::Indexed`. +#[allow(clippy::disallowed_methods)] +fn ansi_palette_color(index: u8) -> RtColor { + match index { + 0x00 => RtColor::Black, + 0x01 => RtColor::Red, + 0x02 => RtColor::Green, + 0x03 => RtColor::Yellow, + 0x04 => RtColor::Blue, + 0x05 => RtColor::Magenta, + 0x06 => RtColor::Cyan, + // ANSI code 37 is "white", represented as `Gray` in ratatui. + 0x07 => RtColor::Gray, + n => RtColor::Indexed(n), + } +} + +/// Decode a syntect foreground `Color` into a ratatui color, respecting the +/// alpha-channel encoding that bat's `ansi`, `base16`, and `base16-256` themes +/// use to signal ANSI palette semantics instead of true RGB. +/// +/// Returns `None` when the color signals "use the terminal's default +/// foreground", allowing the caller to omit the foreground attribute entirely. +/// +/// Passing a color from a standard RGB theme (alpha 0xFF) returns +/// `Some(Rgb(..))`, so this function is backward-compatible with non-ANSI +/// themes. Unexpected intermediate alpha values are treated as RGB. +/// +/// `clippy::disallowed_methods` is explicitly allowed here because this helper +/// intentionally constructs `ratatui::style::Color::Rgb`. +#[allow(clippy::disallowed_methods)] +fn convert_syntect_color(color: SyntectColor) -> Option { + match color.a { + // Bat-compatible encoding used by `ansi`, `base16`, and `base16-256`: + // alpha 0x00 means `r` stores an ANSI palette index, not RGB red. + ANSI_ALPHA_INDEX => Some(ansi_palette_color(color.r)), + // alpha 0x01 means "use terminal default foreground/background". + ANSI_ALPHA_DEFAULT => None, + OPAQUE_ALPHA => Some(RtColor::Rgb(color.r, color.g, color.b)), + // Non-ANSI alpha values appear in some bundled themes; treat as plain RGB. + _ => Some(RtColor::Rgb(color.r, color.g, color.b)), + } +} + /// Convert a syntect `Style` to a ratatui `Style`. /// -/// Syntax highlighting themes inherently produce RGB colors, so we allow -/// `Color::Rgb` here despite the project-wide preference for ANSI colors. -#[allow(clippy::disallowed_methods)] +/// Most themes produce RGB colors. The built-in `ansi`/`base16`/`base16-256` +/// themes encode ANSI palette semantics in the alpha channel, matching bat. fn convert_style(syn_style: SyntectStyle) -> Style { let mut rt_style = Style::default(); - // Map foreground color when visible. - let fg = syn_style.foreground; - if fg.a > 0 { - rt_style = rt_style.fg(RtColor::Rgb(fg.r, fg.g, fg.b)); + if let Some(fg) = convert_syntect_color(syn_style.foreground) { + rt_style = rt_style.fg(fg); } // Intentionally skip background to avoid overwriting terminal bg. + // If background support is added later, decode with `convert_syntect_color` + // to reuse the same alpha-marker semantics as foreground. if syn_style.font_style.contains(FontStyle::BOLD) { rt_style.add_modifier |= Modifier::BOLD; @@ -500,10 +562,16 @@ pub(crate) fn exceeds_highlight_limits(total_bytes: usize, total_lines: usize) - // -- Core highlighting -------------------------------------------------------- -/// Parse `code` using syntect for `lang` and return per-line styled spans. -/// Each inner Vec represents one source line. Returns None when the language -/// is not recognized or the input exceeds safety limits. -fn highlight_to_line_spans(code: &str, lang: &str) -> Option>>> { +/// Core highlighter that accepts an explicit theme reference. +/// +/// This keeps production behavior and test behavior on the same code path: +/// production callers pass the global theme lock, while tests can pass a +/// concrete theme without mutating process-global state. +fn highlight_to_line_spans_with_theme( + code: &str, + lang: &str, + theme: &Theme, +) -> Option>>> { // Empty input has nothing to highlight; fall back to the plain text path // which correctly produces a single empty Line. if code.is_empty() { @@ -518,11 +586,7 @@ fn highlight_to_line_spans(code: &str, lang: &str) -> Option theme_guard, - Err(poisoned) => poisoned.into_inner(), - }; - let mut h = HighlightLines::new(syntax, &theme_guard); + let mut h = HighlightLines::new(syntax, theme); let mut lines: Vec>> = Vec::new(); for line in LinesWithEndings::from(code) { @@ -546,6 +610,17 @@ fn highlight_to_line_spans(code: &str, lang: &str) -> Option Option>>> { + let theme_guard = match theme_lock().read() { + Ok(theme_guard) => theme_guard, + Err(poisoned) => poisoned.into_inner(), + }; + highlight_to_line_spans_with_theme(code, lang, &theme_guard) +} + // -- Public API --------------------------------------------------------------- /// Highlight code in any supported language, returning styled ratatui `Line`s. @@ -596,6 +671,7 @@ pub(crate) fn highlight_code_to_styled_spans( #[cfg(test)] mod tests { use super::*; + use insta::assert_snapshot; use pretty_assertions::assert_eq; use std::str::FromStr; use syntect::highlighting::Color as SyntectColor; @@ -673,6 +749,25 @@ mod tests { .join("\n") } + fn unique_foreground_colors_for_theme(theme_name: &str) -> Vec { + let theme = resolve_theme_by_name(theme_name, None) + .unwrap_or_else(|| panic!("expected built-in theme {theme_name} to resolve")); + let lines = highlight_to_line_spans_with_theme( + "fn main() { let answer = 42; println!(\"hello\"); }\n", + "rust", + &theme, + ) + .expect("expected highlighted spans"); + let mut colors: Vec = lines + .iter() + .flat_map(|line| line.iter().filter_map(|span| span.style.fg)) + .map(|fg| format!("{fg:?}")) + .collect(); + colors.sort(); + colors.dedup(); + colors + } + fn theme_item(scope: &str, background: Option<(u8, u8, u8)>) -> ThemeItem { ThemeItem { scope: ScopeSelectors::from_str(scope).expect("scope selector should parse"), @@ -791,7 +886,6 @@ mod tests { } #[test] - #[allow(clippy::disallowed_methods)] fn convert_style_suppresses_underline() { // Dracula (and other themes) set FontStyle::UNDERLINE on type scopes, // producing distracting underlines on type names in terminal output. @@ -807,7 +901,7 @@ mod tests { r: 0, g: 0, b: 0, - a: 0, + a: 0xFF, }, font_style: FontStyle::UNDERLINE, }; @@ -820,6 +914,138 @@ mod tests { ); } + #[test] + fn style_conversion_uses_ansi_named_color_when_alpha_is_zero_low_index() { + let syn = SyntectStyle { + foreground: syntect::highlighting::Color { + r: 0x02, + g: 0, + b: 0, + a: 0, + }, + background: syntect::highlighting::Color { + r: 0, + g: 0, + b: 0, + a: 0xFF, + }, + font_style: FontStyle::empty(), + }; + let rt = convert_style(syn); + assert_eq!(rt.fg, Some(RtColor::Green)); + } + + #[test] + fn style_conversion_uses_indexed_color_when_alpha_is_zero_high_index() { + let syn = SyntectStyle { + foreground: syntect::highlighting::Color { + r: 0x9a, + g: 0, + b: 0, + a: 0, + }, + background: syntect::highlighting::Color { + r: 0, + g: 0, + b: 0, + a: 0xFF, + }, + font_style: FontStyle::empty(), + }; + let rt = convert_style(syn); + assert!(matches!(rt.fg, Some(RtColor::Indexed(0x9a)))); + } + + #[test] + fn style_conversion_uses_terminal_default_when_alpha_is_one() { + let syn = SyntectStyle { + foreground: syntect::highlighting::Color { + r: 0, + g: 0, + b: 0, + a: 1, + }, + background: syntect::highlighting::Color { + r: 0, + g: 0, + b: 0, + a: 0xFF, + }, + font_style: FontStyle::empty(), + }; + let rt = convert_style(syn); + assert_eq!(rt.fg, None); + } + + #[test] + fn style_conversion_unexpected_alpha_falls_back_to_rgb() { + let syn = SyntectStyle { + foreground: syntect::highlighting::Color { + r: 10, + g: 20, + b: 30, + a: 0x80, + }, + background: syntect::highlighting::Color { + r: 0, + g: 0, + b: 0, + a: 0xFF, + }, + font_style: FontStyle::empty(), + }; + let rt = convert_style(syn); + assert!(matches!(rt.fg, Some(RtColor::Rgb(10, 20, 30)))); + } + + #[test] + fn ansi_palette_color_maps_ansi_white_to_gray() { + assert_eq!(ansi_palette_color(0x07), RtColor::Gray); + } + + #[test] + fn ansi_family_themes_use_terminal_palette_colors_not_rgb() { + for theme_name in ["ansi", "base16", "base16-256"] { + let theme = resolve_theme_by_name(theme_name, None) + .unwrap_or_else(|| panic!("expected built-in theme {theme_name} to resolve")); + let lines = highlight_to_line_spans_with_theme( + "fn main() { let answer = 42; println!(\"hello\"); }\n", + "rust", + &theme, + ) + .expect("expected highlighted spans"); + let mut has_non_default_fg = false; + for line in &lines { + for span in line { + match span.style.fg { + Some(RtColor::Rgb(..)) => { + panic!("theme {theme_name} produced RGB foreground: {span:?}") + } + Some(_) => has_non_default_fg = true, + None => {} + } + } + } + assert!( + has_non_default_fg, + "theme {theme_name} should produce at least one non-default foreground color" + ); + } + } + + #[test] + fn ansi_family_foreground_palette_snapshot() { + let mut out = String::new(); + for theme_name in ["ansi", "base16", "base16-256"] { + let colors = unique_foreground_colors_for_theme(theme_name); + out.push_str(&format!("{theme_name}:\n")); + for color in colors { + out.push_str(&format!(" {color}\n")); + } + } + assert_snapshot!("ansi_family_foreground_palette", out); + } + #[test] fn highlight_multiline_python() { let code = "def hello():\n print(\"hi\")\n return 42"; @@ -1152,7 +1378,7 @@ mod tests { assert!( warning .as_deref() - .is_some_and(|msg| msg.contains("could not be parsed")), + .is_some_and(|msg| msg.contains("could not be loaded")), "warning should explain that the theme file is invalid" ); } diff --git a/codex-rs/tui/src/render/snapshots/codex_tui__render__highlight__tests__ansi_family_foreground_palette.snap b/codex-rs/tui/src/render/snapshots/codex_tui__render__highlight__tests__ansi_family_foreground_palette.snap new file mode 100644 index 0000000000..79e130916c --- /dev/null +++ b/codex-rs/tui/src/render/snapshots/codex_tui__render__highlight__tests__ansi_family_foreground_palette.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/render/highlight.rs +expression: out +--- +ansi: + Blue + Green + Magenta + Yellow +base16: + Blue + Gray + Green + Indexed(9) + Magenta +base16-256: + Blue + Gray + Green + Indexed(16) + Magenta From 2322e49549f477a351308969a15f8e6c622dc1d7 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 4 Mar 2026 20:22:34 +0000 Subject: [PATCH 381/385] feat: external artifacts builder (#13485) This PR reverts the built-in artifact render while a decision is being reached. No impact expected on any features --- MODULE.bazel.lock | 44 +- codex-rs/Cargo.lock | 698 +--- codex-rs/Cargo.toml | 14 +- codex-rs/artifact-presentation/BUILD.bazel | 6 - codex-rs/artifact-presentation/Cargo.toml | 28 - codex-rs/artifact-presentation/src/lib.rs | 6 - .../src/presentation_artifact/api.rs | 249 -- .../src/presentation_artifact/args.rs | 729 ---- .../src/presentation_artifact/inspect.rs | 871 ---- .../src/presentation_artifact/manager.rs | 3203 --------------- .../src/presentation_artifact/mod.rs | 10 - .../src/presentation_artifact/model.rs | 1934 --------- .../src/presentation_artifact/parsing.rs | 1273 ------ .../src/presentation_artifact/pptx.rs | 951 ----- .../src/presentation_artifact/proto.rs | 614 --- .../src/presentation_artifact/response.rs | 138 - .../src/presentation_artifact/snapshot.rs | 339 -- codex-rs/artifact-presentation/src/tests.rs | 3512 ----------------- codex-rs/artifact-spreadsheet/BUILD.bazel | 6 - codex-rs/artifact-spreadsheet/Cargo.toml | 25 - codex-rs/artifact-spreadsheet/src/address.rs | 245 -- codex-rs/artifact-spreadsheet/src/chart.rs | 357 -- .../artifact-spreadsheet/src/conditional.rs | 308 -- codex-rs/artifact-spreadsheet/src/error.rs | 39 - codex-rs/artifact-spreadsheet/src/formula.rs | 535 --- codex-rs/artifact-spreadsheet/src/lib.rs | 26 - codex-rs/artifact-spreadsheet/src/manager.rs | 3346 ---------------- codex-rs/artifact-spreadsheet/src/model.rs | 1787 --------- codex-rs/artifact-spreadsheet/src/pivot.rs | 177 - codex-rs/artifact-spreadsheet/src/render.rs | 373 -- codex-rs/artifact-spreadsheet/src/style.rs | 580 --- codex-rs/artifact-spreadsheet/src/table.rs | 630 --- codex-rs/artifact-spreadsheet/src/tests.rs | 1228 ------ codex-rs/artifact-spreadsheet/src/xlsx.rs | 860 ---- codex-rs/artifacts/BUILD.bazel | 6 + codex-rs/artifacts/Cargo.toml | 25 + codex-rs/artifacts/src/client.rs | 446 +++ codex-rs/artifacts/src/lib.rs | 23 + codex-rs/artifacts/src/runtime.rs | 522 +++ codex-rs/core/Cargo.toml | 3 +- codex-rs/core/src/codex.rs | 24 - codex-rs/core/src/state/session.rs | 10 - codex-rs/core/src/tools/handlers/artifacts.rs | 412 ++ codex-rs/core/src/tools/handlers/mod.rs | 6 +- .../tools/handlers/presentation_artifact.rs | 250 -- .../tools/handlers/spreadsheet_artifact.rs | 235 -- codex-rs/core/src/tools/spec.rs | 132 +- codex-rs/deny.toml | 1 - codex-rs/package-manager/BUILD.bazel | 6 + codex-rs/package-manager/Cargo.toml | 26 + codex-rs/package-manager/src/lib.rs | 793 ++++ 51 files changed, 2425 insertions(+), 25636 deletions(-) delete mode 100644 codex-rs/artifact-presentation/BUILD.bazel delete mode 100644 codex-rs/artifact-presentation/Cargo.toml delete mode 100644 codex-rs/artifact-presentation/src/lib.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/api.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/args.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/manager.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/mod.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/model.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/proto.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/response.rs delete mode 100644 codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs delete mode 100644 codex-rs/artifact-presentation/src/tests.rs delete mode 100644 codex-rs/artifact-spreadsheet/BUILD.bazel delete mode 100644 codex-rs/artifact-spreadsheet/Cargo.toml delete mode 100644 codex-rs/artifact-spreadsheet/src/address.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/chart.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/conditional.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/error.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/formula.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/lib.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/manager.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/model.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/pivot.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/render.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/style.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/table.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/tests.rs delete mode 100644 codex-rs/artifact-spreadsheet/src/xlsx.rs create mode 100644 codex-rs/artifacts/BUILD.bazel create mode 100644 codex-rs/artifacts/Cargo.toml create mode 100644 codex-rs/artifacts/src/client.rs create mode 100644 codex-rs/artifacts/src/lib.rs create mode 100644 codex-rs/artifacts/src/runtime.rs create mode 100644 codex-rs/core/src/tools/handlers/artifacts.rs delete mode 100644 codex-rs/core/src/tools/handlers/presentation_artifact.rs delete mode 100644 codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs create mode 100644 codex-rs/package-manager/BUILD.bazel create mode 100644 codex-rs/package-manager/Cargo.toml create mode 100644 codex-rs/package-manager/src/lib.rs diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 46220ab3cb..a25099cc97 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -684,7 +684,6 @@ "bytes_1.11.1": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"require-cas\"],\"name\":\"extra-platforms\",\"optional\":true,\"package\":\"portable-atomic\",\"req\":\"^1.3\"},{\"kind\":\"dev\",\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.60\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "bytestring_1.5.0": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"bytes\",\"req\":\"^1.2\"},{\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"}],\"features\":{\"serde\":[\"dep:serde_core\"]}}", "bzip2-sys_0.1.13+1.0.8": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.9\"}],\"features\":{\"__disabled\":[],\"static\":[]}}", - "bzip2_0.4.4": "{\"dependencies\":[{\"name\":\"bzip2-sys\",\"req\":\"^0.1.11\"},{\"name\":\"futures\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"features\":[\"quickcheck\"],\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck6\",\"package\":\"quickcheck\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"tokio-core\",\"req\":\"^0.1\"},{\"name\":\"tokio-io\",\"optional\":true,\"req\":\"^0.1\"}],\"features\":{\"static\":[\"bzip2-sys/static\"],\"tokio\":[\"tokio-io\",\"futures\"]}}", "bzip2_0.5.2": "{\"dependencies\":[{\"name\":\"bzip2-sys\",\"optional\":true,\"req\":\"^0.1.13\"},{\"default_features\":false,\"features\":[\"rust-allocator\",\"semver-prefix\"],\"name\":\"libbz2-rs-sys\",\"optional\":true,\"req\":\"^0.1.3\"},{\"features\":[\"quickcheck1\"],\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.5.4\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"}],\"features\":{\"default\":[\"dep:bzip2-sys\"],\"libbz2-rs-sys\":[\"dep:libbz2-rs-sys\",\"bzip2-sys?/__disabled\"],\"static\":[\"bzip2-sys?/static\"]}}", "cached_0.56.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ahash\",\"optional\":true,\"req\":\"^0.8\"},{\"features\":[\"attributes\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.6\"},{\"name\":\"async-trait\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"cached_proc_macro\",\"optional\":true,\"req\":\"^0.25.0\"},{\"name\":\"cached_proc_macro_types\",\"optional\":true,\"req\":\"^0.1.1\"},{\"kind\":\"dev\",\"name\":\"copy_dir\",\"req\":\"^0.1.3\"},{\"name\":\"directories\",\"optional\":true,\"req\":\"^6.0\"},{\"default_features\":false,\"name\":\"futures\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"googletest\",\"req\":\"^0.11.0\"},{\"default_features\":false,\"features\":[\"inline-more\"],\"name\":\"hashbrown\",\"req\":\"^0.15\"},{\"name\":\"once_cell\",\"req\":\"^1\"},{\"name\":\"r2d2\",\"optional\":true,\"req\":\"^0.8\"},{\"features\":[\"r2d2\"],\"name\":\"redis\",\"optional\":true,\"req\":\"^0.32\"},{\"name\":\"rmp-serde\",\"optional\":true,\"req\":\"^1.1\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^3\"},{\"name\":\"sled\",\"optional\":true,\"req\":\"^0.34\"},{\"kind\":\"dev\",\"name\":\"smartstring\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.10.1\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"macros\",\"time\",\"sync\",\"parking_lot\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"web-time\",\"req\":\"^1.1.0\"}],\"features\":{\"ahash\":[\"dep:ahash\",\"hashbrown/default\"],\"async\":[\"futures\",\"tokio\",\"async-trait\"],\"async_tokio_rt_multi_thread\":[\"async\",\"tokio/rt-multi-thread\"],\"default\":[\"proc_macro\",\"ahash\"],\"disk_store\":[\"sled\",\"serde\",\"rmp-serde\",\"directories\"],\"proc_macro\":[\"cached_proc_macro\",\"cached_proc_macro_types\"],\"redis_ahash\":[\"redis_store\",\"redis/ahash\"],\"redis_async_std\":[\"redis_store\",\"async\",\"redis/aio\",\"redis/async-std-comp\",\"redis/tls\",\"redis/async-std-tls-comp\"],\"redis_connection_manager\":[\"redis_store\",\"redis/connection-manager\"],\"redis_store\":[\"redis\",\"r2d2\",\"serde\",\"serde_json\"],\"redis_tokio\":[\"redis_store\",\"async\",\"redis/aio\",\"redis/tokio-comp\",\"redis/tls\",\"redis/tokio-native-tls-comp\"],\"wasm\":[]}}", "cached_proc_macro_0.25.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.20.8\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.49\"},{\"name\":\"quote\",\"req\":\"^1.0.6\"},{\"name\":\"syn\",\"req\":\"^2.0.52\"}],\"features\":{}}", @@ -725,7 +724,6 @@ "const-oid_0.9.6": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.2\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"}],\"features\":{\"db\":[],\"std\":[]}}", "const_format_0.2.35": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"arrayvec\",\"req\":\"^0.7.0\"},{\"name\":\"const_format_proc_macros\",\"req\":\"=0.2.34\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"fastrand\",\"req\":\"^1.3.5\"},{\"default_features\":false,\"name\":\"konst\",\"optional\":true,\"req\":\"^0.2.13\"}],\"features\":{\"__debug\":[\"const_format_proc_macros/debug\"],\"__docsrs\":[],\"__inline_const_pat_tests\":[\"__test\",\"fmt\"],\"__only_new_tests\":[\"__test\"],\"__test\":[],\"all\":[\"fmt\",\"derive\",\"rust_1_64\",\"assert\"],\"assert\":[\"assertc\"],\"assertc\":[\"fmt\",\"assertcp\"],\"assertcp\":[\"rust_1_51\"],\"const_generics\":[\"rust_1_51\"],\"constant_time_as_str\":[\"fmt\"],\"default\":[],\"derive\":[\"fmt\",\"const_format_proc_macros/derive\"],\"fmt\":[\"rust_1_83\"],\"more_str_macros\":[\"rust_1_64\"],\"nightly_const_generics\":[\"const_generics\"],\"rust_1_51\":[],\"rust_1_64\":[\"rust_1_51\",\"konst\",\"konst/rust_1_64\"],\"rust_1_83\":[\"rust_1_64\"]}}", "const_format_proc_macros_0.2.34": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"fastrand\",\"req\":\"^1.3.4\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.19\"},{\"name\":\"quote\",\"req\":\"^1.0.7\"},{\"default_features\":false,\"features\":[\"parsing\",\"proc-macro\"],\"name\":\"syn\",\"optional\":true,\"req\":\"^1.0.38\"},{\"name\":\"unicode-xid\",\"req\":\"^0.2\"}],\"features\":{\"all\":[\"derive\"],\"debug\":[\"syn/extra-traits\"],\"default\":[],\"derive\":[\"syn\",\"syn/derive\",\"syn/printing\"]}}", - "constant_time_eq_0.1.5": "{\"dependencies\":[],\"features\":{}}", "constant_time_eq_0.3.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"count_instructions\",\"req\":\"^0.1.3\"},{\"features\":[\"cargo_bench_support\",\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"}],\"features\":{\"count_instructions_test\":[]}}", "convert_case_0.10.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"unicode-segmentation\",\"req\":\"^1.9.0\"}],\"features\":{}}", "convert_case_0.6.0": "{\"dependencies\":[{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"strum\",\"req\":\"^0.18.0\"},{\"kind\":\"dev\",\"name\":\"strum_macros\",\"req\":\"^0.18.0\"},{\"name\":\"unicode-segmentation\",\"req\":\"^1.9.0\"}],\"features\":{\"random\":[\"rand\"]}}", @@ -749,8 +747,6 @@ "crossterm_winapi_0.9.1": "{\"dependencies\":[{\"features\":[\"winbase\",\"consoleapi\",\"processenv\",\"handleapi\",\"synchapi\",\"impl-default\"],\"name\":\"winapi\",\"req\":\"^0.3.8\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "crunchy_0.2.4": "{\"dependencies\":[],\"features\":{\"default\":[\"limit_128\"],\"limit_1024\":[],\"limit_128\":[],\"limit_2048\":[],\"limit_256\":[],\"limit_512\":[],\"limit_64\":[],\"std\":[]}}", "crypto-common_0.1.7": "{\"dependencies\":[{\"features\":[\"more_lengths\"],\"name\":\"generic-array\",\"req\":\"=0.14.7\"},{\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"typenum\",\"req\":\"^1.14\"}],\"features\":{\"getrandom\":[\"rand_core/getrandom\"],\"std\":[]}}", - "cssparser-macros_0.6.1": "{\"dependencies\":[{\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"full\",\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", - "cssparser_0.31.2": "{\"dependencies\":[{\"name\":\"cssparser-macros\",\"req\":\"^0.6.1\"},{\"kind\":\"dev\",\"name\":\"difference\",\"req\":\"^2.0\"},{\"name\":\"dtoa-short\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"encoding_rs\",\"req\":\"^0.8\"},{\"name\":\"itoa\",\"req\":\"^1.0\"},{\"features\":[\"macros\"],\"name\":\"phf\",\"req\":\">=0.8, <=0.11\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"smallvec\",\"req\":\"^1.0\"}],\"features\":{\"bench\":[],\"dummy_match_byte\":[]}}", "csv-core_0.1.13": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"arrayvec\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2\"}],\"features\":{\"default\":[],\"libc\":[\"memchr/libc\"]}}", "csv_1.4.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\",\"serde\"],\"kind\":\"dev\",\"name\":\"bstr\",\"req\":\"^1.7.0\"},{\"name\":\"csv-core\",\"req\":\"^0.1.11\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"name\":\"ryu\",\"req\":\"^1\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.221\"},{\"name\":\"serde_core\",\"req\":\"^1.0.221\"}],\"features\":{}}", "ctor-proc-macro_0.0.7": "{\"dependencies\":[],\"features\":{\"default\":[]}}", @@ -783,7 +779,6 @@ "derive_arbitrary_1.4.2": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"derive\",\"parsing\",\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "derive_more-impl_1.0.0": "{\"dependencies\":[{\"name\":\"convert_case\",\"optional\":true,\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.13.0\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"syn\",\"req\":\"^2.0.45\"},{\"name\":\"unicode-xid\",\"optional\":true,\"req\":\"^0.2.2\"}],\"features\":{\"add\":[],\"add_assign\":[],\"as_ref\":[\"syn/extra-traits\",\"syn/visit\"],\"constructor\":[],\"debug\":[\"syn/extra-traits\",\"dep:unicode-xid\"],\"default\":[],\"deref\":[],\"deref_mut\":[],\"display\":[\"syn/extra-traits\",\"dep:unicode-xid\"],\"error\":[\"syn/extra-traits\"],\"from\":[\"syn/extra-traits\"],\"from_str\":[],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[],\"index_mut\":[],\"into\":[\"syn/extra-traits\"],\"into_iterator\":[],\"is_variant\":[\"dep:convert_case\"],\"mul\":[\"syn/extra-traits\"],\"mul_assign\":[\"syn/extra-traits\"],\"not\":[\"syn/extra-traits\"],\"sum\":[],\"testing-helpers\":[\"dep:rustc_version\"],\"try_from\":[],\"try_into\":[\"syn/extra-traits\"],\"try_unwrap\":[\"dep:convert_case\"],\"unwrap\":[\"dep:convert_case\"]}}", "derive_more-impl_2.1.1": "{\"dependencies\":[{\"name\":\"convert_case\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.14.0\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"req\":\"^0.4\"},{\"name\":\"syn\",\"req\":\"^2.0.45\"},{\"name\":\"unicode-xid\",\"optional\":true,\"req\":\"^0.2.2\"}],\"features\":{\"add\":[\"syn/extra-traits\",\"syn/visit\"],\"add_assign\":[\"syn/extra-traits\",\"syn/visit\"],\"as_ref\":[\"syn/extra-traits\",\"syn/visit\"],\"constructor\":[],\"debug\":[\"syn/extra-traits\",\"dep:unicode-xid\"],\"default\":[],\"deref\":[],\"deref_mut\":[],\"display\":[\"syn/extra-traits\",\"dep:unicode-xid\",\"dep:convert_case\"],\"eq\":[\"syn/extra-traits\",\"syn/visit\"],\"error\":[\"syn/extra-traits\"],\"from\":[\"syn/extra-traits\"],\"from_str\":[\"syn/full\",\"syn/visit\",\"dep:convert_case\"],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"eq\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[],\"index_mut\":[],\"into\":[\"syn/extra-traits\",\"syn/visit-mut\"],\"into_iterator\":[],\"is_variant\":[\"dep:convert_case\"],\"mul\":[\"syn/extra-traits\",\"syn/visit\"],\"mul_assign\":[\"syn/extra-traits\",\"syn/visit\"],\"not\":[\"syn/extra-traits\"],\"sum\":[],\"testing-helpers\":[\"syn/full\"],\"try_from\":[],\"try_into\":[\"syn/extra-traits\",\"syn/full\",\"syn/visit-mut\"],\"try_unwrap\":[\"dep:convert_case\"],\"unwrap\":[\"dep:convert_case\"]}}", - "derive_more_0.99.20": "{\"dependencies\":[{\"name\":\"convert_case\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"build\",\"name\":\"peg\",\"optional\":true,\"req\":\"^0.5\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"add\":[],\"add_assign\":[],\"as_mut\":[],\"as_ref\":[],\"constructor\":[],\"default\":[\"add_assign\",\"add\",\"as_mut\",\"as_ref\",\"constructor\",\"deref\",\"deref_mut\",\"display\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"iterator\",\"mul_assign\",\"mul\",\"not\",\"sum\",\"try_into\",\"is_variant\",\"unwrap\"],\"deref\":[],\"deref_mut\":[],\"display\":[\"syn/extra-traits\"],\"error\":[\"syn/extra-traits\"],\"from\":[\"syn/extra-traits\"],\"from_str\":[],\"generate-parsing-rs\":[\"peg\"],\"index\":[],\"index_mut\":[],\"into\":[\"syn/extra-traits\"],\"into_iterator\":[],\"is_variant\":[\"convert_case\"],\"iterator\":[],\"mul\":[\"syn/extra-traits\"],\"mul_assign\":[\"syn/extra-traits\"],\"nightly\":[],\"not\":[\"syn/extra-traits\"],\"sum\":[],\"testing-helpers\":[\"rustc_version\"],\"track-caller\":[],\"try_into\":[\"syn/extra-traits\"],\"unwrap\":[\"convert_case\",\"rustc_version\"]}}", "derive_more_1.0.0": "{\"dependencies\":[{\"name\":\"derive_more-impl\",\"req\":\"=1.0.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.56\"}],\"features\":{\"add\":[\"derive_more-impl/add\"],\"add_assign\":[\"derive_more-impl/add_assign\"],\"as_ref\":[\"derive_more-impl/as_ref\"],\"constructor\":[\"derive_more-impl/constructor\"],\"debug\":[\"derive_more-impl/debug\"],\"default\":[\"std\"],\"deref\":[\"derive_more-impl/deref\"],\"deref_mut\":[\"derive_more-impl/deref_mut\"],\"display\":[\"derive_more-impl/display\"],\"error\":[\"derive_more-impl/error\"],\"from\":[\"derive_more-impl/from\"],\"from_str\":[\"derive_more-impl/from_str\"],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[\"derive_more-impl/index\"],\"index_mut\":[\"derive_more-impl/index_mut\"],\"into\":[\"derive_more-impl/into\"],\"into_iterator\":[\"derive_more-impl/into_iterator\"],\"is_variant\":[\"derive_more-impl/is_variant\"],\"mul\":[\"derive_more-impl/mul\"],\"mul_assign\":[\"derive_more-impl/mul_assign\"],\"not\":[\"derive_more-impl/not\"],\"std\":[],\"sum\":[\"derive_more-impl/sum\"],\"testing-helpers\":[\"derive_more-impl/testing-helpers\",\"dep:rustc_version\"],\"try_from\":[\"derive_more-impl/try_from\"],\"try_into\":[\"derive_more-impl/try_into\"],\"try_unwrap\":[\"derive_more-impl/try_unwrap\"],\"unwrap\":[\"derive_more-impl/unwrap\"]}}", "derive_more_2.1.1": "{\"dependencies\":[{\"name\":\"derive_more-impl\",\"req\":\"=2.1.1\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.56\"}],\"features\":{\"add\":[\"derive_more-impl/add\"],\"add_assign\":[\"derive_more-impl/add_assign\"],\"as_ref\":[\"derive_more-impl/as_ref\"],\"constructor\":[\"derive_more-impl/constructor\"],\"debug\":[\"derive_more-impl/debug\"],\"default\":[\"std\"],\"deref\":[\"derive_more-impl/deref\"],\"deref_mut\":[\"derive_more-impl/deref_mut\"],\"display\":[\"derive_more-impl/display\"],\"eq\":[\"derive_more-impl/eq\"],\"error\":[\"derive_more-impl/error\"],\"from\":[\"derive_more-impl/from\"],\"from_str\":[\"derive_more-impl/from_str\"],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"eq\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[\"derive_more-impl/index\"],\"index_mut\":[\"derive_more-impl/index_mut\"],\"into\":[\"derive_more-impl/into\"],\"into_iterator\":[\"derive_more-impl/into_iterator\"],\"is_variant\":[\"derive_more-impl/is_variant\"],\"mul\":[\"derive_more-impl/mul\"],\"mul_assign\":[\"derive_more-impl/mul_assign\"],\"not\":[\"derive_more-impl/not\"],\"std\":[],\"sum\":[\"derive_more-impl/sum\"],\"testing-helpers\":[\"derive_more-impl/testing-helpers\",\"dep:rustc_version\"],\"try_from\":[\"derive_more-impl/try_from\"],\"try_into\":[\"derive_more-impl/try_into\"],\"try_unwrap\":[\"derive_more-impl/try_unwrap\"],\"unwrap\":[\"derive_more-impl/unwrap\"]}}", "deunicode_1.6.2": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"default\":[\"alloc\"]}}", @@ -800,15 +795,12 @@ "displaydoc_0.2.5": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^0.6.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"name\":\"syn\",\"req\":\"^2.0\"},{\"kind\":\"dev\",\"name\":\"thiserror\",\"req\":\"^1.0.24\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "dotenvy_0.15.7": "{\"dependencies\":[{\"name\":\"clap\",\"optional\":true,\"req\":\"^3.2\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.16.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.3.0\"}],\"features\":{\"cli\":[\"clap\"]}}", "downcast-rs_1.2.1": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", - "dtoa-short_0.3.5": "{\"dependencies\":[{\"name\":\"dtoa\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"float-cmp\",\"req\":\"^0.4\"}],\"features\":{}}", - "dtoa_1.0.11": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\",\"target\":\"cfg(not(miri))\"},{\"name\":\"no-panic\",\"optional\":true,\"req\":\"^0.1\"}],\"features\":{}}", "dtor-proc-macro_0.0.6": "{\"dependencies\":[],\"features\":{\"default\":[]}}", "dtor_0.1.1": "{\"dependencies\":[{\"name\":\"dtor-proc-macro\",\"optional\":true,\"req\":\"=0.0.6\"},{\"kind\":\"dev\",\"name\":\"libc-print\",\"req\":\"^0.1.20\"}],\"features\":{\"__no_warn_on_missing_unsafe\":[],\"default\":[\"proc_macro\",\"__no_warn_on_missing_unsafe\"],\"proc_macro\":[\"dep:dtor-proc-macro\"],\"used_linker\":[]}}", "dunce_1.0.5": "{\"dependencies\":[],\"features\":{}}", "dupe_0.9.1": "{\"dependencies\":[{\"name\":\"dupe_derive\",\"req\":\"=0.9.1\"}],\"features\":{}}", "dupe_derive_0.9.1": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0.3\"},{\"features\":[\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "dyn-clone_1.0.20": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.66\"}],\"features\":{}}", - "ego-tree_0.6.3": "{\"dependencies\":[],\"features\":{}}", "either_1.15.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\",\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.95\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[],\"use_std\":[\"std\"]}}", "ena_0.14.3": "{\"dependencies\":[{\"name\":\"dogged\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"log\",\"req\":\"^0.4\"}],\"features\":{\"bench\":[],\"persistent\":[\"dogged\"]}}", "encode_unicode_1.0.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ascii\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.0\",\"target\":\"cfg(unix)\"},{\"features\":[\"https-native\"],\"kind\":\"dev\",\"name\":\"minreq\",\"req\":\"^2.6\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", @@ -839,6 +831,7 @@ "fdeflate_0.3.7": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"miniz_oxide\",\"req\":\"^0.7.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"name\":\"simd-adler32\",\"req\":\"^0.3.4\"}],\"features\":{}}", "fiat-crypto_0.2.9": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "filedescriptor_0.8.3": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^1.0\"},{\"features\":[\"winuser\",\"handleapi\",\"fileapi\",\"namedpipeapi\",\"processthreadsapi\",\"winsock2\",\"processenv\"],\"name\":\"winapi\",\"req\":\"^0.3\",\"target\":\"cfg(windows)\"}],\"features\":{}}", + "filetime_0.2.27": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"libc\",\"req\":\"^0.2.27\",\"target\":\"cfg(unix)\"},{\"name\":\"libredox\",\"req\":\"^0.1.0\",\"target\":\"cfg(target_os = \\\"redox\\\")\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{}}", "find-crate_0.6.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"quote\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"semver\",\"req\":\"^0.11\"},{\"name\":\"toml\",\"req\":\"^0.5.2\"}],\"features\":{}}", "find-msvc-tools_0.1.9": "{\"dependencies\":[],\"features\":{}}", "findshlibs_0.10.2": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.67\"},{\"name\":\"lazy_static\",\"req\":\"^1.4\",\"target\":\"cfg(any(target_os = \\\"macos\\\", target_os = \\\"ios\\\"))\"},{\"name\":\"libc\",\"req\":\"^0.2.104\"},{\"features\":[\"psapi\",\"memoryapi\",\"libloaderapi\",\"processthreadsapi\"],\"name\":\"winapi\",\"req\":\"^0.3.9\",\"target\":\"cfg(target_os = \\\"windows\\\")\"}],\"features\":{}}", @@ -861,7 +854,6 @@ "form_urlencoded_1.2.2": "{\"dependencies\":[{\"default_features\":false,\"name\":\"percent-encoding\",\"req\":\"^2.3.0\"}],\"features\":{\"alloc\":[\"percent-encoding/alloc\"],\"default\":[\"std\"],\"std\":[\"alloc\",\"percent-encoding/std\"]}}", "fs_extra_1.3.0": "{\"dependencies\":[],\"features\":{}}", "fsevent-sys_4.1.0": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.68\"}],\"features\":{}}", - "futf_0.1.5": "{\"dependencies\":[{\"name\":\"mac\",\"req\":\"^0.1.0\"},{\"name\":\"new_debug_unreachable\",\"req\":\"^1.0.2\"}],\"features\":{}}", "futures-channel_0.3.31": "{\"dependencies\":[{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-sink\",\"optional\":true,\"req\":\"^0.3.31\"}],\"features\":{\"alloc\":[\"futures-core/alloc\"],\"cfg-target-has-atomic\":[],\"default\":[\"std\"],\"sink\":[\"futures-sink\"],\"std\":[\"alloc\",\"futures-core/std\"],\"unstable\":[]}}", "futures-core_0.3.31": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"require-cas\"],\"name\":\"portable-atomic\",\"optional\":true,\"req\":\"^1.3\"}],\"features\":{\"alloc\":[],\"cfg-target-has-atomic\":[],\"default\":[\"std\"],\"std\":[\"alloc\"],\"unstable\":[]}}", "futures-executor_0.3.31": "{\"dependencies\":[{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-task\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3.31\"},{\"name\":\"num_cpus\",\"optional\":true,\"req\":\"^1.8.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"futures-core/std\",\"futures-task/std\",\"futures-util/std\"],\"thread-pool\":[\"std\",\"num_cpus\"]}}", @@ -891,7 +883,6 @@ "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=9200079d3b54a1ff51072e24d81fd354f085156f#9200079d3b54a1ff51072e24d81fd354f085156f_tungstenite": "{\"dependencies\":[{\"name\":\"bytes\"},{\"default_features\":true,\"features\":[],\"name\":\"data-encoding\",\"optional\":true},{\"default_features\":false,\"features\":[\"zlib\"],\"name\":\"flate2\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"headers\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"http\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"httparse\",\"optional\":true},{\"name\":\"log\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\"},{\"name\":\"rand\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rustls\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"rustls-native-certs\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"rustls-pki-types\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"sha1\",\"optional\":true},{\"name\":\"thiserror\"},{\"default_features\":true,\"features\":[],\"name\":\"url\",\"optional\":true},{\"name\":\"utf-8\"},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\"],\"default\":[\"handshake\"],\"deflate\":[\"headers\",\"flate2\"],\"handshake\":[\"data-encoding\",\"headers\",\"httparse\",\"sha1\"],\"headers\":[\"http\",\"dep:headers\"],\"native-tls\":[\"native-tls-crate\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\"],\"proxy\":[\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"url\":[\"dep:url\"]},\"strip_prefix\":\"\"}", "glob_0.3.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tempdir\",\"req\":\"^0.3\"}],\"features\":{}}", "globset_0.4.18": "{\"dependencies\":[{\"name\":\"aho-corasick\",\"req\":\"^1.1.1\"},{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.3.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"bstr\",\"req\":\"^1.6.2\"},{\"kind\":\"dev\",\"name\":\"glob\",\"req\":\"^0.3.1\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"default_features\":false,\"features\":[\"std\",\"perf\",\"syntax\",\"meta\",\"nfa\",\"hybrid\"],\"name\":\"regex-automata\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"regex-syntax\",\"req\":\"^0.8.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.188\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.107\"}],\"features\":{\"arbitrary\":[\"dep:arbitrary\"],\"default\":[\"log\"],\"serde1\":[\"serde\"],\"simd-accel\":[]}}", - "h2_0.3.27": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"features\":[\"std\"],\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"},{\"name\":\"slab\",\"req\":\"^0.4.2\"},{\"features\":[\"io-util\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"rt-multi-thread\",\"macros\",\"sync\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-rustls\",\"req\":\"^0.24\"},{\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"req\":\"^0.7.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^0.25\"}],\"features\":{\"stream\":[],\"unstable\":[]}}", "h2_0.4.13": "{\"dependencies\":[{\"name\":\"atomic-waker\",\"req\":\"^1.0.0\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"http\",\"req\":\"^1\"},{\"features\":[\"std\"],\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"},{\"name\":\"slab\",\"req\":\"^0.4.2\"},{\"features\":[\"io-util\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"rt-multi-thread\",\"macros\",\"sync\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-rustls\",\"req\":\"^0.26\"},{\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"req\":\"^0.7.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1\"}],\"features\":{\"stream\":[],\"unstable\":[]}}", "half_2.7.1": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.4.1\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"bytemuck\",\"optional\":true,\"req\":\"^1.4.1\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"crunchy\",\"req\":\"^0.2.2\",\"target\":\"cfg(target_arch = \\\"spirv\\\")\"},{\"kind\":\"dev\",\"name\":\"crunchy\",\"req\":\"^0.2.2\"},{\"default_features\":false,\"features\":[\"libm\"],\"name\":\"num-traits\",\"optional\":true,\"req\":\"^0.2.16\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"thread_rng\"],\"name\":\"rand\",\"optional\":true,\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9.0\"},{\"default_features\":false,\"name\":\"rand_distr\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"rkyv\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"derive\",\"simd\"],\"name\":\"zerocopy\",\"req\":\"^0.8.26\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"nightly\":[],\"rand_distr\":[\"dep:rand\",\"dep:rand_distr\"],\"std\":[\"alloc\"],\"use-intrinsics\":[],\"zerocopy\":[]}}", "hashbrown_0.12.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ahash\",\"optional\":true,\"req\":\"^0.7.0\"},{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"name\":\"bumpalo\",\"optional\":true,\"req\":\"^3.5.0\"},{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.2\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.1\"},{\"kind\":\"dev\",\"name\":\"fnv\",\"req\":\"^1.0.7\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.3\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.25\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"ahash-compile-time-rng\":[\"ahash/compile-time-rng\"],\"default\":[\"ahash\",\"inline-more\"],\"inline-more\":[],\"nightly\":[],\"raw\":[],\"rustc-dep-of-std\":[\"nightly\",\"core\",\"compiler_builtins\",\"alloc\",\"rustc-internal-api\"],\"rustc-internal-api\":[]}}", @@ -911,9 +902,7 @@ "home_0.5.12": "{\"dependencies\":[{\"features\":[\"Win32_Foundation\",\"Win32_UI_Shell\",\"Win32_System_Com\"],\"name\":\"windows-sys\",\"req\":\"^0.61\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "hostname_0.4.2": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(any(unix, target_os = \\\"redox\\\"))\"},{\"kind\":\"dev\",\"name\":\"similar-asserts\",\"req\":\"^1.6.1\"},{\"kind\":\"dev\",\"name\":\"version-sync\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"windows-bindgen\",\"req\":\"^0.65\"},{\"name\":\"windows-link\",\"req\":\"^0.2\",\"target\":\"cfg(target_os = \\\"windows\\\")\"}],\"features\":{\"default\":[],\"set\":[]}}", "hound_3.5.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"cpal\",\"req\":\"^0.2.12\"}],\"features\":{}}", - "html5ever_0.26.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\",\"target\":\"cfg(bench)\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"mac\",\"req\":\"^0.1\"},{\"name\":\"markup5ever\",\"req\":\"^0.11\"},{\"kind\":\"build\",\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"kind\":\"build\",\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"extra-traits\",\"full\",\"fold\"],\"kind\":\"build\",\"name\":\"syn\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"typed-arena\",\"req\":\"^1.3.0\"}],\"features\":{}}", "http-body-util_0.1.3": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1\"},{\"name\":\"http-body\",\"req\":\"^1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"macros\",\"rt\",\"sync\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"}],\"features\":{\"channel\":[\"dep:tokio\"],\"default\":[],\"full\":[\"channel\"]}}", - "http-body_0.4.6": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"macros\",\"rt\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"}],\"features\":{}}", "http-body_1.0.1": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"http\",\"req\":\"^1\"}],\"features\":{}}", "http-range-header_0.4.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.8.3\"}],\"features\":{}}", "http_0.2.12": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"kind\":\"dev\",\"name\":\"indexmap\",\"req\":\"<=1.8\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.7.0\"},{\"kind\":\"dev\",\"name\":\"seahash\",\"req\":\"^3.0.5\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{}}", @@ -922,10 +911,8 @@ "httpdate_1.0.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"}],\"features\":{}}", "hyper-rustls_0.27.7": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"http\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"hyper\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"client-legacy\",\"tokio\"],\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"server-auto\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.4\"},{\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"rustls\",\"req\":\"^0.23\"},{\"default_features\":false,\"features\":[\"tls12\"],\"kind\":\"dev\",\"name\":\"rustls\",\"req\":\"^0.23\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rustls-pemfile\",\"req\":\"^2\"},{\"name\":\"rustls-platform-verifier\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"tokio\",\"req\":\"^1.0\"},{\"features\":[\"io-std\",\"macros\",\"net\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"tokio-rustls\",\"req\":\"^0.26\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"aws-lc-rs\":[\"rustls/aws_lc_rs\"],\"default\":[\"native-tokio\",\"http1\",\"tls12\",\"logging\",\"aws-lc-rs\"],\"fips\":[\"aws-lc-rs\",\"rustls/fips\"],\"http1\":[\"hyper-util/http1\"],\"http2\":[\"hyper-util/http2\"],\"logging\":[\"log\",\"tokio-rustls/logging\",\"rustls/logging\"],\"native-tokio\":[\"rustls-native-certs\"],\"ring\":[\"rustls/ring\"],\"tls12\":[\"tokio-rustls/tls12\",\"rustls/tls12\"],\"webpki-tokio\":[\"webpki-roots\"]}}", "hyper-timeout_0.5.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"name\":\"hyper\",\"req\":\"^1.1\"},{\"features\":[\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"hyper-tls\",\"req\":\"^0.6\"},{\"features\":[\"client-legacy\",\"http1\"],\"name\":\"hyper-util\",\"req\":\"^0.1.10\"},{\"features\":[\"client-legacy\",\"http1\",\"server\",\"server-graceful\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.10\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"tokio\",\"req\":\"^1.35\"},{\"features\":[\"io-std\",\"io-util\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.35\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"}],\"features\":{}}", - "hyper-tls_0.5.0": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"tcp\",\"client\"],\"name\":\"hyper\",\"req\":\"^0.14.2\"},{\"default_features\":false,\"features\":[\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^0.14.2\"},{\"name\":\"native-tls\",\"req\":\"^0.2.1\"},{\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"io-std\",\"macros\",\"io-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0.0\"},{\"name\":\"tokio-native-tls\",\"req\":\"^0.3\"}],\"features\":{\"vendored\":[\"native-tls/vendored\"]}}", "hyper-tls_0.6.0": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"client-legacy\",\"tokio\"],\"name\":\"hyper-util\",\"req\":\"^0.1.0\"},{\"features\":[\"http1\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.0\"},{\"name\":\"native-tls\",\"req\":\"^0.2.1\"},{\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"io-std\",\"macros\",\"io-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0.0\"},{\"name\":\"tokio-native-tls\",\"req\":\"^0.3\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"}],\"features\":{\"alpn\":[\"native-tls/alpn\"],\"vendored\":[\"native-tls/vendored\"]}}", "hyper-util_0.1.19": "{\"dependencies\":[{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"req\":\"^1.7.1\"},{\"kind\":\"dev\",\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.16\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.16\"},{\"name\":\"http\",\"req\":\"^1.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"req\":\"^1.8.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.4.0\"},{\"name\":\"ipnet\",\"optional\":true,\"req\":\"^2.9\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"percent-encoding\",\"optional\":true,\"req\":\"^2.3\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.4\"},{\"kind\":\"dev\",\"name\":\"pnet_datalink\",\"req\":\"^0.35.0\",\"target\":\"cfg(any(target_os = \\\"linux\\\", target_os = \\\"macos\\\"))\"},{\"kind\":\"dev\",\"name\":\"pretty_env_logger\",\"req\":\"^0.5\"},{\"features\":[\"all\"],\"name\":\"socket2\",\"optional\":true,\"req\":\">=0.5.9, <0.7\"},{\"name\":\"system-configuration\",\"optional\":true,\"req\":\">=0.5, <0.7\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"default_features\":false,\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"macros\",\"test-util\",\"signal\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"name\":\"tower-layer\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tower-test\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"windows-registry\",\"optional\":true,\"req\":\">=0.3, <0.7\",\"target\":\"cfg(windows)\"}],\"features\":{\"__internal_happy_eyeballs_tests\":[],\"client\":[\"hyper/client\",\"tokio/net\",\"dep:tracing\",\"dep:futures-channel\",\"dep:tower-service\"],\"client-legacy\":[\"client\",\"dep:socket2\",\"tokio/sync\",\"dep:libc\",\"dep:futures-util\"],\"client-pool\":[\"client\",\"dep:futures-util\",\"dep:tower-layer\"],\"client-proxy\":[\"client\",\"dep:base64\",\"dep:ipnet\",\"dep:percent-encoding\"],\"client-proxy-system\":[\"dep:system-configuration\",\"dep:windows-registry\"],\"default\":[],\"full\":[\"client\",\"client-legacy\",\"client-pool\",\"client-proxy\",\"client-proxy-system\",\"server\",\"server-auto\",\"server-graceful\",\"service\",\"http1\",\"http2\",\"tokio\",\"tracing\"],\"http1\":[\"hyper/http1\"],\"http2\":[\"hyper/http2\"],\"server\":[\"hyper/server\"],\"server-auto\":[\"server\",\"http1\",\"http2\"],\"server-graceful\":[\"server\",\"tokio/sync\"],\"service\":[\"dep:tower-service\"],\"tokio\":[\"dep:tokio\",\"tokio/rt\",\"tokio/time\"],\"tracing\":[\"dep:tracing\"]}}", - "hyper_0.14.32": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"futures-channel\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"h2\",\"optional\":true,\"req\":\"^0.3.24\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"name\":\"http-body\",\"req\":\"^0.4\"},{\"name\":\"httparse\",\"req\":\"^1.8\"},{\"name\":\"httpdate\",\"req\":\"^1.0\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"matches\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.4\"},{\"kind\":\"dev\",\"name\":\"pnet_datalink\",\"req\":\"^0.27.2\",\"target\":\"cfg(any(target_os = \\\"linux\\\", target_os = \\\"macos\\\"))\"},{\"kind\":\"dev\",\"name\":\"pretty_env_logger\",\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"all\"],\"name\":\"socket2\",\"optional\":true,\"req\":\">=0.4.7, <0.6.0\"},{\"kind\":\"dev\",\"name\":\"spmc\",\"req\":\"^0.3\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"req\":\"^1.27\"},{\"features\":[\"fs\",\"macros\",\"io-std\",\"io-util\",\"rt\",\"rt-multi-thread\",\"sync\",\"time\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.27\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"features\":[\"codec\"],\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"make\",\"util\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.4\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.2\"},{\"name\":\"want\",\"req\":\"^0.3\"}],\"features\":{\"__internal_happy_eyeballs_tests\":[],\"backports\":[],\"client\":[],\"default\":[],\"deprecated\":[],\"ffi\":[\"libc\"],\"full\":[\"client\",\"http1\",\"http2\",\"server\",\"stream\",\"runtime\"],\"http1\":[],\"http2\":[\"h2\"],\"nightly\":[],\"runtime\":[\"tcp\",\"tokio/rt\",\"tokio/time\"],\"server\":[],\"stream\":[],\"tcp\":[\"socket2\",\"tokio/net\",\"tokio/rt\",\"tokio/time\"]}}", "hyper_1.8.1": "{\"dependencies\":[{\"name\":\"atomic-waker\",\"optional\":true,\"req\":\"^1.1.2\"},{\"name\":\"bytes\",\"req\":\"^1.2\"},{\"kind\":\"dev\",\"name\":\"form_urlencoded\",\"req\":\"^1\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\"},{\"features\":[\"sink\"],\"kind\":\"dev\",\"name\":\"futures-channel\",\"req\":\"^0.3\"},{\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3.31\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"h2\",\"optional\":true,\"req\":\"^0.4.2\"},{\"name\":\"http\",\"req\":\"^1\"},{\"name\":\"http-body\",\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"name\":\"httparse\",\"optional\":true,\"req\":\"^1.9\"},{\"name\":\"httpdate\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"itoa\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"pin-project-lite\",\"optional\":true,\"req\":\"^0.2.4\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.4\"},{\"name\":\"pin-utils\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"pretty_env_logger\",\"req\":\"^0.5\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"const_generics\",\"const_new\"],\"name\":\"smallvec\",\"optional\":true,\"req\":\"^1.12\"},{\"kind\":\"dev\",\"name\":\"spmc\",\"req\":\"^0.3\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"fs\",\"macros\",\"net\",\"io-std\",\"io-util\",\"rt\",\"rt-multi-thread\",\"sync\",\"time\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.7.10\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"want\",\"optional\":true,\"req\":\"^0.3\"}],\"features\":{\"capi\":[],\"client\":[\"dep:want\",\"dep:pin-project-lite\",\"dep:smallvec\"],\"default\":[],\"ffi\":[\"dep:http-body-util\",\"dep:futures-util\"],\"full\":[\"client\",\"http1\",\"http2\",\"server\"],\"http1\":[\"dep:atomic-waker\",\"dep:futures-channel\",\"dep:futures-core\",\"dep:httparse\",\"dep:itoa\",\"dep:pin-utils\"],\"http2\":[\"dep:futures-channel\",\"dep:futures-core\",\"dep:h2\"],\"nightly\":[],\"server\":[\"dep:httpdate\",\"dep:pin-project-lite\",\"dep:smallvec\"],\"tracing\":[\"dep:tracing\"]}}", "i18n-config_0.4.8": "{\"dependencies\":[{\"name\":\"basic-toml\",\"req\":\"^0.1\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"name\":\"thiserror\",\"req\":\"^1.0\"},{\"features\":[\"serde\"],\"name\":\"unic-langid\",\"req\":\"^0.9\"}],\"features\":{}}", "i18n-embed-fl_0.9.4": "{\"dependencies\":[{\"name\":\"dashmap\",\"optional\":true,\"req\":\"^6.0\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"name\":\"find-crate\",\"req\":\"^0.6\"},{\"name\":\"fluent\",\"req\":\"^0.16\"},{\"name\":\"fluent-syntax\",\"req\":\"^0.11\"},{\"name\":\"i18n-config\",\"req\":\"^0.4.7\"},{\"features\":[\"fluent-system\",\"filesystem-assets\"],\"name\":\"i18n-embed\",\"req\":\"^0.15.4\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.4\"},{\"name\":\"proc-macro-error2\",\"req\":\"^2.0.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rust-embed\",\"req\":\"^8.0\"},{\"name\":\"strsim\",\"req\":\"^0.11\"},{\"features\":[\"derive\",\"proc-macro\",\"parsing\",\"printing\",\"extra-traits\",\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"name\":\"unic-langid\",\"req\":\"^0.9\"}],\"features\":{\"dashmap\":[\"dep:dashmap\"]}}", @@ -1014,10 +1001,8 @@ "lsp-types_0.94.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^1.0.1\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0.34\"},{\"name\":\"serde_json\",\"req\":\"^1.0.50\"},{\"name\":\"serde_repr\",\"req\":\"^0.1\"},{\"features\":[\"serde\"],\"name\":\"url\",\"req\":\"^2.0.0\"}],\"features\":{\"default\":[],\"proposed\":[]}}", "lzma-rs_0.3.0": "{\"dependencies\":[{\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"name\":\"crc\",\"req\":\"^3.0.0\"},{\"name\":\"env_logger\",\"optional\":true,\"req\":\"^0.9.0\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.17\"},{\"kind\":\"dev\",\"name\":\"rust-lzma\",\"req\":\"^0.5\"}],\"features\":{\"enable_logging\":[\"env_logger\",\"log\"],\"raw_decoder\":[],\"stream\":[]}}", "lzma-sys_0.1.20": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.34\"},{\"name\":\"libc\",\"req\":\"^0.2.51\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.14\"}],\"features\":{\"static\":[]}}", - "mac_0.1.1": "{\"dependencies\":[],\"features\":{}}", "mach2_0.4.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_os = \\\"macos\\\", target_os = \\\"ios\\\"))\"}],\"features\":{\"default\":[],\"unstable\":[]}}", "maplit_1.0.2": "{\"dependencies\":[],\"features\":{}}", - "markup5ever_0.11.0": "{\"dependencies\":[{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"phf\",\"req\":\"^0.10\"},{\"kind\":\"build\",\"name\":\"phf_codegen\",\"req\":\"^0.10\"},{\"name\":\"string_cache\",\"req\":\"^0.8\"},{\"kind\":\"build\",\"name\":\"string_cache_codegen\",\"req\":\"^0.5.1\"},{\"name\":\"tendril\",\"req\":\"^0.4\"}],\"features\":{}}", "matchers_0.2.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"syntax\",\"dfa-build\",\"dfa-search\"],\"name\":\"regex-automata\",\"req\":\"^0.4\"}],\"features\":{\"unicode\":[\"regex-automata/unicode\"]}}", "matchit_0.8.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"actix-router\",\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.4\"},{\"kind\":\"dev\",\"name\":\"gonzales\",\"req\":\"^0.0.3-beta\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^0.14\"},{\"kind\":\"dev\",\"name\":\"path-tree\",\"req\":\"^0.2.2\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.5.4\"},{\"kind\":\"dev\",\"name\":\"route-recognizer\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"routefinder\",\"req\":\"^0.5.2\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"make\",\"util\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.4\"}],\"features\":{\"__test_helpers\":[],\"default\":[]}}", "matchit_0.9.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"actix-router\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"gonzales\",\"req\":\"^0.0.3-beta\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"features\":[\"http1\",\"server\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"path-tree\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"route-recognizer\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"routefinder\",\"req\":\"^0.5\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"make\",\"util\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"kind\":\"dev\",\"name\":\"wayfind\",\"req\":\"^0.8\"}],\"features\":{\"__test_helpers\":[],\"default\":[]}}", @@ -1109,26 +1094,17 @@ "parking_2.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"easy-parallel\",\"req\":\"^3.0.0\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\",\"target\":\"cfg(loom)\"}],\"features\":{}}", "parking_lot_0.12.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"name\":\"lock_api\",\"req\":\"^0.4.14\"},{\"name\":\"parking_lot_core\",\"req\":\"^0.9.12\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.3\"}],\"features\":{\"arc_lock\":[\"lock_api/arc_lock\"],\"deadlock_detection\":[\"parking_lot_core/deadlock_detection\"],\"default\":[],\"hardware-lock-elision\":[],\"nightly\":[\"parking_lot_core/nightly\",\"lock_api/nightly\"],\"owning_ref\":[\"lock_api/owning_ref\"],\"send_guard\":[],\"serde\":[\"lock_api/serde\"]}}", "parking_lot_core_0.9.12": "{\"dependencies\":[{\"name\":\"backtrace\",\"optional\":true,\"req\":\"^0.3.60\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"libc\",\"req\":\"^0.2.95\",\"target\":\"cfg(unix)\"},{\"name\":\"petgraph\",\"optional\":true,\"req\":\"^0.6.0\"},{\"name\":\"redox_syscall\",\"req\":\"^0.5\",\"target\":\"cfg(target_os = \\\"redox\\\")\"},{\"name\":\"smallvec\",\"req\":\"^1.6.1\"},{\"name\":\"windows-link\",\"req\":\"^0.2.0\",\"target\":\"cfg(windows)\"}],\"features\":{\"deadlock_detection\":[\"petgraph\",\"backtrace\"],\"nightly\":[]}}", - "password-hash_0.4.2": "{\"dependencies\":[{\"name\":\"base64ct\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"}],\"features\":{\"alloc\":[\"base64ct/alloc\"],\"default\":[\"rand_core\"],\"std\":[\"alloc\",\"base64ct/std\",\"rand_core/std\"]}}", "paste_1.0.15": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"paste-test-suite\",\"req\":\"^0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.49\"}],\"features\":{}}", "pastey_0.2.1": "{\"dependencies\":[],\"features\":{}}", "path-absolutize_3.1.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"path-dedot\",\"req\":\"^3.1.1\"},{\"kind\":\"dev\",\"name\":\"slash-formatter\",\"req\":\"^3\",\"target\":\"cfg(windows)\"}],\"features\":{\"lazy_static_cache\":[\"path-dedot/lazy_static_cache\"],\"once_cell_cache\":[\"path-dedot/once_cell_cache\"],\"unsafe_cache\":[\"path-dedot/unsafe_cache\"],\"use_unix_paths_on_wasm\":[\"path-dedot/use_unix_paths_on_wasm\"]}}", "path-dedot_3.1.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"lazy_static\",\"optional\":true,\"req\":\"^1.4\"},{\"name\":\"once_cell\",\"req\":\"^1.4\"}],\"features\":{\"lazy_static_cache\":[\"lazy_static\"],\"once_cell_cache\":[],\"unsafe_cache\":[],\"use_unix_paths_on_wasm\":[]}}", "pathdiff_0.2.3": "{\"dependencies\":[{\"name\":\"camino\",\"optional\":true,\"req\":\"^1.0.5\"},{\"kind\":\"dev\",\"name\":\"cfg-if\",\"req\":\"^1.0.0\"}],\"features\":{}}", - "pbkdf2_0.11.0": "{\"dependencies\":[{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.10.3\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"hmac\",\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.2\"},{\"default_features\":false,\"name\":\"sha1\",\"optional\":true,\"package\":\"sha-1\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha1\",\"package\":\"sha-1\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"streebog\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"simple\"],\"parallel\":[\"rayon\",\"std\"],\"simple\":[\"hmac\",\"password-hash\",\"sha2\"],\"std\":[\"password-hash/std\"]}}", "pbkdf2_0.12.2": "{\"dependencies\":[{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"hmac\",\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.7\"},{\"default_features\":false,\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha1\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"streebog\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"hmac\"],\"parallel\":[\"rayon\",\"std\"],\"simple\":[\"hmac\",\"password-hash\",\"sha2\"],\"std\":[\"password-hash/std\"]}}", "pem-rfc7468_0.7.0": "{\"dependencies\":[{\"name\":\"base64ct\",\"req\":\"^1.4\"}],\"features\":{\"alloc\":[\"base64ct/alloc\"],\"std\":[\"alloc\",\"base64ct/std\"]}}", "pem_3.0.6": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"base64\",\"req\":\"^0.22.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"}],\"features\":{\"default\":[\"std\"],\"serde\":[\"dep:serde_core\"],\"std\":[\"base64/std\",\"serde_core?/std\"]}}", "percent-encoding_2.3.2": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "petgraph_0.6.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.7.2\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"kind\":\"dev\",\"name\":\"defmac\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"name\":\"fixedbitset\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2.1\"},{\"name\":\"indexmap\",\"req\":\"^2.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.12.1\"},{\"kind\":\"dev\",\"name\":\"odds\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"quickcheck\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.5.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.5.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"all\":[\"unstable\",\"quickcheck\",\"matrix_graph\",\"stable_graph\",\"graphmap\",\"rayon\"],\"default\":[\"graphmap\",\"stable_graph\",\"matrix_graph\"],\"generate\":[],\"graphmap\":[],\"matrix_graph\":[],\"rayon\":[\"dep:rayon\",\"indexmap/rayon\"],\"serde-1\":[\"serde\",\"serde_derive\"],\"stable_graph\":[],\"unstable\":[\"generate\"]}}", "petgraph_0.8.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.7.2\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"kind\":\"dev\",\"name\":\"defmac\",\"req\":\"^0.2.1\"},{\"name\":\"dot-parser\",\"optional\":true,\"req\":\"^0.5.1\"},{\"name\":\"dot-parser-macros\",\"optional\":true,\"req\":\"^0.5.1\"},{\"default_features\":false,\"name\":\"fixedbitset\",\"req\":\"^0.5.7\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"features\":[\"default-hasher\",\"inline-more\"],\"name\":\"hashbrown\",\"req\":\"^0.15.0\"},{\"default_features\":false,\"name\":\"indexmap\",\"req\":\"^2.5.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.12.1\"},{\"kind\":\"dev\",\"name\":\"odds\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"quickcheck\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.5.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.5.3\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"all\":[\"unstable\",\"quickcheck\",\"matrix_graph\",\"stable_graph\",\"graphmap\",\"rayon\",\"dot_parser\"],\"default\":[\"std\",\"graphmap\",\"stable_graph\",\"matrix_graph\"],\"dot_parser\":[\"std\",\"dep:dot-parser\",\"dep:dot-parser-macros\"],\"generate\":[],\"graphmap\":[],\"matrix_graph\":[],\"quickcheck\":[\"std\",\"dep:quickcheck\",\"graphmap\",\"stable_graph\"],\"rayon\":[\"std\",\"dep:rayon\",\"indexmap/rayon\",\"hashbrown/rayon\"],\"serde-1\":[\"serde\",\"serde_derive\"],\"stable_graph\":[\"serde?/alloc\"],\"std\":[\"indexmap/std\"],\"unstable\":[\"generate\"]}}", - "phf_0.10.1": "{\"dependencies\":[{\"name\":\"phf_macros\",\"optional\":true,\"req\":\"^0.10.0\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.10.0\"},{\"name\":\"proc-macro-hack\",\"optional\":true,\"req\":\"^0.5.4\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"macros\":[\"phf_macros\",\"proc-macro-hack\"],\"std\":[\"phf_shared/std\"],\"uncased\":[\"phf_shared/uncased\"],\"unicase\":[\"phf_shared/unicase\"]}}", - "phf_0.11.3": "{\"dependencies\":[{\"name\":\"phf_macros\",\"optional\":true,\"req\":\"^0.11.3\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.11.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"macros\":[\"phf_macros\"],\"std\":[\"phf_shared/std\"],\"uncased\":[\"phf_shared/uncased\"],\"unicase\":[\"phf_macros?/unicase\",\"phf_shared/unicase\"]}}", - "phf_codegen_0.10.0": "{\"dependencies\":[{\"name\":\"phf_generator\",\"req\":\"^0.10.0\"},{\"name\":\"phf_shared\",\"req\":\"^0.10.0\"}],\"features\":{}}", - "phf_generator_0.10.0": "{\"dependencies\":[{\"name\":\"criterion\",\"optional\":true,\"req\":\"=0.3.4\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"=0.3.4\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.10.0\"},{\"features\":[\"small_rng\"],\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{}}", - "phf_generator_0.11.3": "{\"dependencies\":[{\"name\":\"criterion\",\"optional\":true,\"req\":\"^0.3.6\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.11.2\"},{\"default_features\":false,\"features\":[\"small_rng\"],\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{}}", - "phf_macros_0.11.3": "{\"dependencies\":[{\"name\":\"phf_generator\",\"req\":\"^0.11.1\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.11.2\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"},{\"name\":\"unicase_\",\"optional\":true,\"package\":\"unicase\",\"req\":\"^2.4.0\"}],\"features\":{\"unicase\":[\"unicase_\",\"phf_shared/unicase\"]}}", - "phf_shared_0.10.0": "{\"dependencies\":[{\"name\":\"siphasher\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"uncased\",\"optional\":true,\"req\":\"^0.9.6\"},{\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.4.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "phf_shared_0.11.3": "{\"dependencies\":[{\"name\":\"siphasher\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"uncased\",\"optional\":true,\"req\":\"^0.9.9\"},{\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.4.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "pin-project-internal_1.1.10": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"name\":\"quote\",\"req\":\"^1.0.25\"},{\"default_features\":false,\"features\":[\"parsing\",\"printing\",\"clone-impls\",\"proc-macro\",\"full\",\"visit-mut\"],\"name\":\"syn\",\"req\":\"^2.0.1\"}],\"features\":{}}", "pin-project-lite_0.2.16": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1\"}],\"features\":{}}", @@ -1147,7 +1123,6 @@ "portable-pty_0.9.0": "{\"dependencies\":[{\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"bitflags\",\"req\":\"^1.3\",\"target\":\"cfg(windows)\"},{\"name\":\"downcast-rs\",\"req\":\"^1.0\"},{\"name\":\"filedescriptor\",\"req\":\"^0.8.3\"},{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"lazy_static\",\"req\":\"^1.4\",\"target\":\"cfg(windows)\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"features\":[\"term\",\"fs\"],\"name\":\"nix\",\"req\":\"^0.28\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serial2\",\"req\":\"^0.2\"},{\"name\":\"shared_library\",\"req\":\"^0.1\",\"target\":\"cfg(windows)\"},{\"name\":\"shell-words\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"smol\",\"req\":\"^2.0\"},{\"features\":[\"winuser\",\"consoleapi\",\"handleapi\",\"fileapi\",\"namedpipeapi\",\"synchapi\"],\"name\":\"winapi\",\"req\":\"^0.3\",\"target\":\"cfg(windows)\"},{\"name\":\"winreg\",\"req\":\"^0.10\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[],\"serde_support\":[\"serde\",\"serde_derive\"]}}", "potential_utf_0.1.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"default_features\":false,\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.45\"},{\"default_features\":false,\"name\":\"writeable\",\"optional\":true,\"req\":\"^0.6.0\"},{\"default_features\":false,\"name\":\"zerovec\",\"optional\":true,\"req\":\"^0.11.3\"}],\"features\":{\"alloc\":[\"serde_core?/alloc\",\"writeable/alloc\",\"zerovec?/alloc\"],\"databake\":[\"dep:databake\"],\"default\":[\"alloc\"],\"serde\":[\"dep:serde_core\"],\"writeable\":[\"dep:writeable\"],\"zerovec\":[\"dep:zerovec\"]}}", "powerfmt_0.2.0": "{\"dependencies\":[{\"name\":\"powerfmt-macros\",\"optional\":true,\"req\":\"=0.1.0\"}],\"features\":{\"alloc\":[],\"default\":[\"std\",\"macros\"],\"macros\":[\"dep:powerfmt-macros\"],\"std\":[\"alloc\"]}}", - "ppt-rs_0.2.6": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"clock\",\"std\"],\"name\":\"chrono\",\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"name\":\"clap\",\"req\":\"^4.5\"},{\"name\":\"pulldown-cmark\",\"req\":\"^0.10\"},{\"name\":\"regex\",\"req\":\"^1.10\"},{\"features\":[\"blocking\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.11\"},{\"name\":\"scraper\",\"optional\":true,\"req\":\"^0.18\"},{\"name\":\"syntect\",\"req\":\"^5.2\"},{\"name\":\"thiserror\",\"req\":\"^1.0\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.5\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"req\":\"^1.0\"},{\"name\":\"xml-rs\",\"req\":\"^0.8\"},{\"name\":\"zip\",\"req\":\"^0.6\"}],\"features\":{\"default\":[\"web2ppt\"],\"web2ppt\":[\"reqwest\",\"scraper\",\"url\"]}}", "ppv-lite86_0.2.21": "{\"dependencies\":[{\"features\":[\"simd\"],\"name\":\"zerocopy\",\"req\":\"^0.8.23\"}],\"features\":{\"default\":[\"std\"],\"no_simd\":[],\"simd\":[],\"std\":[]}}", "precomputed-hash_0.1.1": "{\"dependencies\":[],\"features\":{}}", "predicates-core_1.0.9": "{\"dependencies\":[],\"features\":{}}", @@ -1214,7 +1189,6 @@ "regex-syntax_0.6.29": "{\"dependencies\":[],\"features\":{\"default\":[\"unicode\"],\"unicode\":[\"unicode-age\",\"unicode-bool\",\"unicode-case\",\"unicode-gencat\",\"unicode-perl\",\"unicode-script\",\"unicode-segment\"],\"unicode-age\":[],\"unicode-bool\":[],\"unicode-case\":[],\"unicode-gencat\":[],\"unicode-perl\":[],\"unicode-script\":[],\"unicode-segment\":[]}}", "regex-syntax_0.8.8": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.3.0\"}],\"features\":{\"arbitrary\":[\"dep:arbitrary\"],\"default\":[\"std\",\"unicode\"],\"std\":[],\"unicode\":[\"unicode-age\",\"unicode-bool\",\"unicode-case\",\"unicode-gencat\",\"unicode-perl\",\"unicode-script\",\"unicode-segment\"],\"unicode-age\":[],\"unicode-bool\":[],\"unicode-case\":[],\"unicode-gencat\":[],\"unicode-perl\":[],\"unicode-script\":[],\"unicode-segment\":[]}}", "regex_1.12.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aho-corasick\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.69\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"atty\",\"humantime\",\"termcolor\"],\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.9.3\"},{\"default_features\":false,\"name\":\"memchr\",\"optional\":true,\"req\":\"^2.6.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"default_features\":false,\"features\":[\"alloc\",\"syntax\",\"meta\",\"nfa-pikevm\"],\"name\":\"regex-automata\",\"req\":\"^0.4.12\"},{\"default_features\":false,\"name\":\"regex-syntax\",\"req\":\"^0.8.5\"},{\"kind\":\"dev\",\"name\":\"regex-test\",\"req\":\"^0.1.0\"}],\"features\":{\"default\":[\"std\",\"perf\",\"unicode\",\"regex-syntax/default\"],\"logging\":[\"aho-corasick?/logging\",\"memchr?/logging\",\"regex-automata/logging\"],\"pattern\":[],\"perf\":[\"perf-cache\",\"perf-dfa\",\"perf-onepass\",\"perf-backtrack\",\"perf-inline\",\"perf-literal\"],\"perf-backtrack\":[\"regex-automata/nfa-backtrack\"],\"perf-cache\":[],\"perf-dfa\":[\"regex-automata/hybrid\"],\"perf-dfa-full\":[\"regex-automata/dfa-build\",\"regex-automata/dfa-search\"],\"perf-inline\":[\"regex-automata/perf-inline\"],\"perf-literal\":[\"dep:aho-corasick\",\"dep:memchr\",\"regex-automata/perf-literal\"],\"perf-onepass\":[\"regex-automata/dfa-onepass\"],\"std\":[\"aho-corasick?/std\",\"memchr?/std\",\"regex-automata/std\",\"regex-syntax/std\"],\"unicode\":[\"unicode-age\",\"unicode-bool\",\"unicode-case\",\"unicode-gencat\",\"unicode-perl\",\"unicode-script\",\"unicode-segment\",\"regex-automata/unicode\",\"regex-syntax/unicode\"],\"unicode-age\":[\"regex-automata/unicode-age\",\"regex-syntax/unicode-age\"],\"unicode-bool\":[\"regex-automata/unicode-bool\",\"regex-syntax/unicode-bool\"],\"unicode-case\":[\"regex-automata/unicode-case\",\"regex-syntax/unicode-case\"],\"unicode-gencat\":[\"regex-automata/unicode-gencat\",\"regex-syntax/unicode-gencat\"],\"unicode-perl\":[\"regex-automata/unicode-perl\",\"regex-automata/unicode-word-boundary\",\"regex-syntax/unicode-perl\"],\"unicode-script\":[\"regex-automata/unicode-script\",\"regex-syntax/unicode-script\"],\"unicode-segment\":[\"regex-automata/unicode-segment\",\"regex-syntax/unicode-segment\"],\"unstable\":[\"pattern\"],\"use_std\":[\"std\"]}}", - "reqwest_0.11.27": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"tokio\"],\"name\":\"async-compression\",\"optional\":true,\"req\":\"^0.4.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"base64\",\"req\":\"^0.21\"},{\"kind\":\"dev\",\"name\":\"brotli_crate\",\"package\":\"brotli\",\"req\":\"^3.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"bytes\",\"req\":\"^1.0\"},{\"name\":\"cookie_crate\",\"optional\":true,\"package\":\"cookie\",\"req\":\"^0.17.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"cookie_store\",\"optional\":true,\"req\":\"^0.20.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"encoding_rs\",\"req\":\"^0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"features\":[\"std\",\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h2\",\"req\":\"^0.3.14\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3\",\"optional\":true,\"req\":\"^0.0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3-quinn\",\"optional\":true,\"req\":\"^0.0.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"tokio-runtime\"],\"name\":\"hickory-resolver\",\"optional\":true,\"req\":\"^0.24\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"name\":\"http-body\",\"req\":\"^0.4.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tcp\",\"http1\",\"http2\",\"client\",\"runtime\"],\"name\":\"hyper\",\"req\":\"^0.14.21\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tcp\",\"stream\",\"http1\",\"http2\",\"client\",\"server\",\"runtime\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^0.14\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"hyper-rustls\",\"optional\":true,\"req\":\"^0.24.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"hyper-tls\",\"optional\":true,\"req\":\"^0.5\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"ipnet\",\"req\":\"^2.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"js-sys\",\"req\":\"^0.3.45\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"libflate\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"log\",\"req\":\"^0.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"mime\",\"req\":\"^0.3.16\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0\"},{\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"^0.2.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"once_cell\",\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tls-rustls\",\"ring\",\"runtime-tokio\"],\"name\":\"quinn\",\"optional\":true,\"req\":\"^0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"dangerous_configuration\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.21.6\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.6\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"rustls-pemfile\",\"optional\":true,\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde_json\",\"req\":\"^1.0\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_urlencoded\",\"req\":\"^0.7.1\"},{\"name\":\"sync_wrapper\",\"req\":\"^0.1.2\"},{\"name\":\"system-configuration\",\"req\":\"^0.5.1\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"default_features\":false,\"features\":[\"net\",\"time\"],\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-native-tls\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"^0.24\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-socks\",\"optional\":true,\"req\":\"^0.5.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"optional\":true,\"req\":\"^0.7.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"url\",\"req\":\"^2.2\"},{\"name\":\"wasm-bindgen\",\"req\":\"^0.2.68\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"serde-serialize\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen\",\"req\":\"^0.2.68\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-bindgen-futures\",\"req\":\"^0.4.18\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-streams\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"AbortController\",\"AbortSignal\",\"Headers\",\"Request\",\"RequestInit\",\"RequestMode\",\"Response\",\"Window\",\"FormData\",\"Blob\",\"BlobPropertyBag\",\"ServiceWorkerGlobalScope\",\"RequestCredentials\",\"File\",\"ReadableStream\"],\"name\":\"web-sys\",\"req\":\"^0.3.25\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^0.25\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"winreg\",\"req\":\"^0.50.0\",\"target\":\"cfg(windows)\"}],\"features\":{\"__internal_proxy_sys_no_cache\":[],\"__rustls\":[\"hyper-rustls\",\"tokio-rustls\",\"rustls\",\"__tls\"],\"__tls\":[\"dep:rustls-pemfile\"],\"blocking\":[\"futures-util/io\",\"tokio/sync\"],\"brotli\":[\"async-compression\",\"async-compression/brotli\",\"tokio-util\"],\"cookies\":[\"cookie_crate\",\"cookie_store\"],\"default\":[\"default-tls\"],\"default-tls\":[\"hyper-tls\",\"native-tls-crate\",\"__tls\",\"tokio-native-tls\"],\"deflate\":[\"async-compression\",\"async-compression/zlib\",\"tokio-util\"],\"gzip\":[\"async-compression\",\"async-compression/gzip\",\"tokio-util\"],\"hickory-dns\":[\"hickory-resolver\"],\"http3\":[\"rustls-tls-manual-roots\",\"h3\",\"h3-quinn\",\"quinn\",\"futures-channel\"],\"json\":[\"serde_json\"],\"multipart\":[\"mime_guess\"],\"native-tls\":[\"default-tls\"],\"native-tls-alpn\":[\"native-tls\",\"native-tls-crate/alpn\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\"],\"rustls-tls\":[\"rustls-tls-webpki-roots\"],\"rustls-tls-manual-roots\":[\"__rustls\"],\"rustls-tls-native-roots\":[\"rustls-native-certs\",\"__rustls\"],\"rustls-tls-webpki-roots\":[\"webpki-roots\",\"__rustls\"],\"socks\":[\"tokio-socks\"],\"stream\":[\"tokio/fs\",\"tokio-util\",\"wasm-streams\"],\"trust-dns\":[\"hickory-dns\"]}}", "reqwest_0.12.28": "{\"dependencies\":[{\"name\":\"base64\",\"req\":\"^0.22\"},{\"kind\":\"dev\",\"name\":\"brotli_crate\",\"package\":\"brotli\",\"req\":\"^8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"bytes\",\"req\":\"^1.2\"},{\"name\":\"cookie_crate\",\"optional\":true,\"package\":\"cookie\",\"req\":\"^0.18.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"cookie_store\",\"optional\":true,\"req\":\"^0.22.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"encoding_rs\",\"optional\":true,\"req\":\"^0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0.13\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.28\"},{\"default_features\":false,\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.28\"},{\"default_features\":false,\"features\":[\"std\",\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.28\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h2\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3\",\"optional\":true,\"req\":\"^0.0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3-quinn\",\"optional\":true,\"req\":\"^0.0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"tokio\"],\"name\":\"hickory-resolver\",\"optional\":true,\"req\":\"^0.25\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http\",\"req\":\"^1.1\"},{\"name\":\"http-body\",\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.2\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"client\"],\"name\":\"hyper\",\"req\":\"^1.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"http1\",\"http2\",\"client\",\"server\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"http1\",\"tls12\"],\"name\":\"hyper-rustls\",\"optional\":true,\"req\":\"^0.27.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"hyper-tls\",\"optional\":true,\"req\":\"^0.6\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"client\",\"client-legacy\",\"client-proxy\",\"tokio\"],\"name\":\"hyper-util\",\"req\":\"^0.1.12\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"http2\",\"client\",\"client-legacy\",\"server-auto\",\"server-graceful\",\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.12\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"js-sys\",\"req\":\"^0.3.77\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0\"},{\"name\":\"log\",\"req\":\"^0.4.17\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"mime\",\"optional\":true,\"req\":\"^0.3.16\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0\"},{\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"^0.2.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.0\"},{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.18\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"percent-encoding\",\"req\":\"^2.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.11\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"rustls\",\"runtime-tokio\"],\"name\":\"quinn\",\"optional\":true,\"req\":\"^0.11.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"std\",\"tls12\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.23.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.8.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"std\"],\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"^1.9.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde_json\",\"req\":\"^1.0\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_urlencoded\",\"req\":\"^0.7.1\"},{\"features\":[\"futures\"],\"name\":\"sync_wrapper\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"net\",\"time\"],\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-native-tls\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tls12\"],\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"^0.26\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"io\"],\"name\":\"tokio-util\",\"optional\":true,\"req\":\"^0.7.9\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"retry\",\"timeout\",\"util\"],\"name\":\"tower\",\"req\":\"^0.5.2\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"limit\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"default_features\":false,\"features\":[\"follow-redirect\"],\"name\":\"tower-http\",\"req\":\"^0.6.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tower-service\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"url\",\"req\":\"^2.4\"},{\"name\":\"wasm-bindgen\",\"req\":\"^0.2.89\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"serde-serialize\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen\",\"req\":\"^0.2.89\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-bindgen-futures\",\"req\":\"^0.4.18\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-streams\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"AbortController\",\"AbortSignal\",\"Headers\",\"Request\",\"RequestInit\",\"RequestMode\",\"Response\",\"Window\",\"FormData\",\"Blob\",\"BlobPropertyBag\",\"ServiceWorkerGlobalScope\",\"RequestCredentials\",\"File\",\"ReadableStream\",\"RequestCache\"],\"name\":\"web-sys\",\"req\":\"^0.3.28\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"zstd_crate\",\"package\":\"zstd\",\"req\":\"^0.13\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"}],\"features\":{\"__rustls\":[\"dep:hyper-rustls\",\"dep:tokio-rustls\",\"dep:rustls\",\"__tls\"],\"__rustls-ring\":[\"hyper-rustls?/ring\",\"tokio-rustls?/ring\",\"rustls?/ring\",\"quinn?/ring\"],\"__tls\":[\"dep:rustls-pki-types\",\"tokio/io-util\"],\"blocking\":[\"dep:futures-channel\",\"futures-channel?/sink\",\"dep:futures-util\",\"futures-util?/io\",\"futures-util?/sink\",\"tokio/sync\"],\"brotli\":[\"tower-http/decompression-br\"],\"charset\":[\"dep:encoding_rs\",\"dep:mime\"],\"cookies\":[\"dep:cookie_crate\",\"dep:cookie_store\"],\"default\":[\"default-tls\",\"charset\",\"http2\",\"system-proxy\"],\"default-tls\":[\"dep:hyper-tls\",\"dep:native-tls-crate\",\"__tls\",\"dep:tokio-native-tls\"],\"deflate\":[\"tower-http/decompression-deflate\"],\"gzip\":[\"tower-http/decompression-gzip\"],\"hickory-dns\":[\"dep:hickory-resolver\",\"dep:once_cell\"],\"http2\":[\"h2\",\"hyper/http2\",\"hyper-util/http2\",\"hyper-rustls?/http2\"],\"http3\":[\"rustls-tls-manual-roots\",\"dep:h3\",\"dep:h3-quinn\",\"dep:quinn\",\"tokio/macros\"],\"json\":[\"dep:serde_json\"],\"macos-system-configuration\":[\"system-proxy\"],\"multipart\":[\"dep:mime_guess\",\"dep:futures-util\"],\"native-tls\":[\"default-tls\"],\"native-tls-alpn\":[\"native-tls\",\"native-tls-crate?/alpn\",\"hyper-tls?/alpn\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate?/vendored\"],\"rustls-tls\":[\"rustls-tls-webpki-roots\"],\"rustls-tls-manual-roots\":[\"rustls-tls-manual-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-manual-roots-no-provider\":[\"__rustls\"],\"rustls-tls-native-roots\":[\"rustls-tls-native-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-native-roots-no-provider\":[\"dep:rustls-native-certs\",\"hyper-rustls?/native-tokio\",\"__rustls\"],\"rustls-tls-no-provider\":[\"rustls-tls-manual-roots-no-provider\"],\"rustls-tls-webpki-roots\":[\"rustls-tls-webpki-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-webpki-roots-no-provider\":[\"dep:webpki-roots\",\"hyper-rustls?/webpki-tokio\",\"__rustls\"],\"socks\":[],\"stream\":[\"tokio/fs\",\"dep:futures-util\",\"dep:tokio-util\",\"dep:wasm-streams\"],\"system-proxy\":[\"hyper-util/client-proxy-system\"],\"trust-dns\":[],\"zstd\":[\"tower-http/decompression-zstd\"]}}", "resolv-conf_0.7.6": "{\"dependencies\":[],\"features\":{\"system\":[]}}", "ring_0.17.14": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.2.8\"},{\"default_features\":false,\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"getrandom\",\"req\":\"^0.2.10\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(all(any(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), all(target_arch = \\\"arm\\\", target_endian = \\\"little\\\")), any(target_os = \\\"android\\\", target_os = \\\"linux\\\")))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_vendor = \\\"apple\\\", any(target_os = \\\"ios\\\", target_os = \\\"macos\\\", target_os = \\\"tvos\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\")))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.37\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\"^0.52\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_os = \\\"windows\\\"))\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\",\"dev_urandom_fallback\"],\"dev_urandom_fallback\":[],\"less-safe-getrandom-custom-or-rdrand\":[],\"less-safe-getrandom-espidf\":[],\"slow_tests\":[],\"std\":[\"alloc\"],\"test_logging\":[],\"unstable-testing-arm-no-hw\":[],\"unstable-testing-arm-no-neon\":[],\"wasm32_unknown_unknown_js\":[\"getrandom/js\"]}}", @@ -1233,7 +1207,6 @@ "rustix_0.38.44": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2.4.0\"},{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.49\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4\",\"target\":\"cfg(all(criterion, not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"itoa\",\"optional\":true,\"req\":\"^1.0.13\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.161\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.161\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.161\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(windows)\"},{\"default_features\":false,\"name\":\"libc_errno\",\"optional\":true,\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\"},{\"default_features\":false,\"features\":[\"general\",\"ioctl\",\"no_std\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.4.14\",\"target\":\"cfg(all(any(target_os = \\\"android\\\", target_os = \\\"linux\\\"), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"features\":[\"general\",\"errno\",\"ioctl\",\"no_std\",\"elf\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.4.14\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"memoffset\",\"req\":\"^0.9.0\"},{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.5.2\",\"target\":\"cfg(any(target_os = \\\"android\\\", target_os = \\\"linux\\\"))\"},{\"name\":\"rustc-std-workspace-alloc\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.5.0\"},{\"features\":[\"Win32_Foundation\",\"Win32_Networking_WinSock\",\"Win32_NetworkManagement_IpHelper\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <=0.59\",\"target\":\"cfg(windows)\"}],\"features\":{\"all-apis\":[\"event\",\"fs\",\"io_uring\",\"mm\",\"mount\",\"net\",\"param\",\"pipe\",\"process\",\"procfs\",\"pty\",\"rand\",\"runtime\",\"shm\",\"stdio\",\"system\",\"termios\",\"thread\",\"time\"],\"alloc\":[],\"cc\":[],\"default\":[\"std\",\"use-libc-auxv\"],\"event\":[],\"fs\":[],\"io_uring\":[\"event\",\"fs\",\"net\",\"linux-raw-sys/io_uring\"],\"libc-extra-traits\":[\"libc?/extra_traits\"],\"linux_4_11\":[],\"linux_latest\":[\"linux_4_11\"],\"mm\":[],\"mount\":[],\"net\":[\"linux-raw-sys/net\",\"linux-raw-sys/netlink\",\"linux-raw-sys/if_ether\",\"linux-raw-sys/xdp\"],\"param\":[\"fs\"],\"pipe\":[],\"process\":[\"linux-raw-sys/prctl\"],\"procfs\":[\"once_cell\",\"itoa\",\"fs\"],\"pty\":[\"itoa\",\"fs\"],\"rand\":[],\"runtime\":[\"linux-raw-sys/prctl\"],\"rustc-dep-of-std\":[\"core\",\"rustc-std-workspace-alloc\",\"compiler_builtins\",\"linux-raw-sys/rustc-dep-of-std\",\"bitflags/rustc-dep-of-std\",\"compiler_builtins?/rustc-dep-of-std\"],\"shm\":[\"fs\"],\"std\":[\"bitflags/std\",\"alloc\",\"libc?/std\",\"libc_errno?/std\",\"libc-extra-traits\"],\"stdio\":[],\"system\":[\"linux-raw-sys/system\"],\"termios\":[],\"thread\":[\"linux-raw-sys/prctl\"],\"time\":[],\"try_close\":[],\"use-explicitly-provided-auxv\":[],\"use-libc\":[\"libc_errno\",\"libc\",\"libc-extra-traits\"],\"use-libc-auxv\":[]}}", "rustix_1.1.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2.4.0\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4\",\"target\":\"cfg(all(criterion, not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.177\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.177\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.171\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(windows)\"},{\"default_features\":false,\"name\":\"libc_errno\",\"optional\":true,\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\"},{\"default_features\":false,\"features\":[\"general\",\"ioctl\",\"no_std\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.11.0\",\"target\":\"cfg(all(any(target_os = \\\"linux\\\", target_os = \\\"android\\\"), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"features\":[\"auxvec\",\"general\",\"errno\",\"ioctl\",\"no_std\",\"elf\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.11.0\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"memoffset\",\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.20.3\",\"target\":\"cfg(windows)\"},{\"name\":\"rustc-std-workspace-alloc\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.5.0\"},{\"features\":[\"Win32_Foundation\",\"Win32_Networking_WinSock\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <0.62\",\"target\":\"cfg(windows)\"}],\"features\":{\"all-apis\":[\"event\",\"fs\",\"io_uring\",\"mm\",\"mount\",\"net\",\"param\",\"pipe\",\"process\",\"pty\",\"rand\",\"runtime\",\"shm\",\"stdio\",\"system\",\"termios\",\"thread\",\"time\"],\"alloc\":[],\"default\":[\"std\"],\"event\":[],\"fs\":[],\"io_uring\":[\"event\",\"fs\",\"net\",\"thread\",\"linux-raw-sys/io_uring\"],\"linux_4_11\":[],\"linux_5_1\":[\"linux_4_11\"],\"linux_5_11\":[\"linux_5_1\"],\"linux_latest\":[\"linux_5_11\"],\"mm\":[],\"mount\":[],\"net\":[\"linux-raw-sys/net\",\"linux-raw-sys/netlink\",\"linux-raw-sys/if_ether\",\"linux-raw-sys/xdp\"],\"param\":[],\"pipe\":[],\"process\":[\"linux-raw-sys/prctl\"],\"pty\":[\"fs\"],\"rand\":[],\"runtime\":[\"linux-raw-sys/prctl\"],\"rustc-dep-of-std\":[\"core\",\"rustc-std-workspace-alloc\",\"linux-raw-sys/rustc-dep-of-std\",\"bitflags/rustc-dep-of-std\"],\"shm\":[\"fs\"],\"std\":[\"bitflags/std\",\"alloc\",\"libc?/std\",\"libc_errno?/std\"],\"stdio\":[],\"system\":[\"linux-raw-sys/system\"],\"termios\":[],\"thread\":[\"linux-raw-sys/prctl\"],\"time\":[],\"try_close\":[],\"use-explicitly-provided-auxv\":[],\"use-libc\":[\"libc_errno\",\"libc\"],\"use-libc-auxv\":[]}}", "rustls-native-certs_0.8.3": "{\"dependencies\":[{\"name\":\"openssl-probe\",\"req\":\"^0.2\",\"target\":\"cfg(all(unix, not(target_os = \\\"macos\\\")))\"},{\"features\":[\"std\"],\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1.10\"},{\"kind\":\"dev\",\"name\":\"ring\",\"req\":\"^0.17\"},{\"kind\":\"dev\",\"name\":\"rustls\",\"req\":\"^0.23\"},{\"kind\":\"dev\",\"name\":\"rustls-webpki\",\"req\":\"^0.103\"},{\"name\":\"schannel\",\"req\":\"^0.1\",\"target\":\"cfg(windows)\"},{\"name\":\"security-framework\",\"req\":\"^3\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^3\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.5\"},{\"kind\":\"dev\",\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.18\"}],\"features\":{}}", - "rustls-pemfile_1.0.4": "{\"dependencies\":[{\"name\":\"base64\",\"req\":\"^0.21\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"}],\"features\":{}}", "rustls-pki-types_1.14.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"crabgrind\",\"req\":\"=0.1.9\",\"target\":\"cfg(all(target_os = \\\"linux\\\", target_arch = \\\"x86_64\\\"))\"},{\"name\":\"web-time\",\"optional\":true,\"req\":\"^1\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"alloc\":[\"dep:zeroize\"],\"default\":[\"alloc\"],\"std\":[\"alloc\"],\"web\":[\"web-time\"]}}", "rustls-webpki_0.103.9": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aws-lc-rs\",\"optional\":true,\"req\":\"^1.14\"},{\"kind\":\"dev\",\"name\":\"base64\",\"req\":\"^0.22\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"kind\":\"dev\",\"name\":\"bzip2\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.17.2\"},{\"default_features\":false,\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1.12\"},{\"default_features\":false,\"features\":[\"aws_lc_rs\"],\"kind\":\"dev\",\"name\":\"rcgen\",\"req\":\"^0.14.2\"},{\"default_features\":false,\"name\":\"ring\",\"optional\":true,\"req\":\"^0.17\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"}],\"features\":{\"alloc\":[\"ring?/alloc\",\"pki-types/alloc\"],\"aws-lc-rs\":[\"dep:aws-lc-rs\",\"aws-lc-rs/aws-lc-sys\",\"aws-lc-rs/prebuilt-nasm\"],\"aws-lc-rs-fips\":[\"dep:aws-lc-rs\",\"aws-lc-rs/fips\"],\"aws-lc-rs-unstable\":[\"aws-lc-rs\",\"aws-lc-rs/unstable\"],\"default\":[\"std\"],\"ring\":[\"dep:ring\"],\"std\":[\"alloc\",\"pki-types/std\"]}}", "rustls_0.23.36": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aws-lc-rs\",\"optional\":true,\"req\":\"^1.14\"},{\"kind\":\"dev\",\"name\":\"base64\",\"req\":\"^0.22\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"brotli\",\"optional\":true,\"req\":\"^8\"},{\"name\":\"brotli-decompressor\",\"optional\":true,\"req\":\"^5.0.0\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"default_features\":false,\"features\":[\"default-hasher\",\"inline-more\"],\"name\":\"hashbrown\",\"optional\":true,\"req\":\"^0.15\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.8\"},{\"kind\":\"dev\",\"name\":\"log\",\"req\":\"^0.4.8\"},{\"kind\":\"dev\",\"name\":\"macro_rules_attribute\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"num-bigint\",\"req\":\"^0.4.4\"},{\"default_features\":false,\"features\":[\"alloc\",\"race\"],\"name\":\"once_cell\",\"req\":\"^1.16\"},{\"features\":[\"alloc\"],\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1.12\"},{\"default_features\":false,\"features\":[\"pem\",\"aws_lc_rs\"],\"kind\":\"dev\",\"name\":\"rcgen\",\"req\":\"^0.14\"},{\"name\":\"ring\",\"optional\":true,\"req\":\"^0.17\"},{\"kind\":\"build\",\"name\":\"rustversion\",\"optional\":true,\"req\":\"^1.0.6\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2.5.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"webpki\",\"package\":\"rustls-webpki\",\"req\":\"^0.103.5\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.17\"},{\"name\":\"zeroize\",\"req\":\"^1.8\"},{\"name\":\"zlib-rs\",\"optional\":true,\"req\":\"^0.5\"}],\"features\":{\"aws-lc-rs\":[\"aws_lc_rs\"],\"aws_lc_rs\":[\"dep:aws-lc-rs\",\"webpki/aws-lc-rs\",\"aws-lc-rs/aws-lc-sys\",\"aws-lc-rs/prebuilt-nasm\"],\"brotli\":[\"dep:brotli\",\"dep:brotli-decompressor\",\"std\"],\"custom-provider\":[],\"default\":[\"aws_lc_rs\",\"logging\",\"prefer-post-quantum\",\"std\",\"tls12\"],\"fips\":[\"aws_lc_rs\",\"aws-lc-rs?/fips\",\"webpki/aws-lc-rs-fips\"],\"logging\":[\"log\"],\"prefer-post-quantum\":[\"aws_lc_rs\"],\"read_buf\":[\"rustversion\",\"std\"],\"ring\":[\"dep:ring\",\"webpki/ring\"],\"std\":[\"webpki/std\",\"pki-types/std\",\"once_cell/std\"],\"tls12\":[],\"zlib\":[\"dep:zlib-rs\"]}}", @@ -1254,7 +1227,6 @@ "schemars_derive_1.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.2.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.74\"},{\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"name\":\"serde_derive_internals\",\"req\":\"^0.29.1\"},{\"name\":\"syn\",\"req\":\"^2.0.46\"},{\"features\":[\"extra-traits\"],\"kind\":\"dev\",\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "scoped-tls_1.0.1": "{\"dependencies\":[],\"features\":{}}", "scopeguard_1.2.0": "{\"dependencies\":[],\"features\":{\"default\":[\"use_std\"],\"use_std\":[]}}", - "scraper_0.18.1": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"cssparser\",\"req\":\"^0.31.0\"},{\"name\":\"ego-tree\",\"req\":\"^0.6.2\"},{\"name\":\"getopts\",\"optional\":true,\"req\":\"^0.2.21\"},{\"name\":\"html5ever\",\"req\":\"^0.26\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.0.2\"},{\"name\":\"once_cell\",\"req\":\"^1.0\"},{\"name\":\"selectors\",\"req\":\"^0.25.0\"},{\"name\":\"tendril\",\"req\":\"^0.4.3\"}],\"features\":{\"atomic\":[],\"default\":[\"main\",\"errors\"],\"deterministic\":[\"indexmap\"],\"errors\":[],\"main\":[\"getopts\"]}}", "scrypt_0.11.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.5\"},{\"features\":[\"rand_core\"],\"kind\":\"dev\",\"name\":\"password-hash\",\"req\":\"^0.5\"},{\"name\":\"pbkdf2\",\"req\":\"^0.12\"},{\"default_features\":false,\"name\":\"salsa20\",\"req\":\"^0.10.2\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"simple\",\"std\"],\"simple\":[\"password-hash\"],\"std\":[\"password-hash/std\"]}}", "sdd_3.0.10": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.6\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"}],\"features\":{}}", "seccompiler_0.5.0": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.153\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.27\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.9\"}],\"features\":{\"json\":[\"serde\",\"serde_json\"]}}", @@ -1263,7 +1235,6 @@ "security-framework-sys_2.15.0": "{\"dependencies\":[{\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"name\":\"libc\",\"req\":\"^0.2.150\"}],\"features\":{\"OSX_10_10\":[\"OSX_10_9\"],\"OSX_10_11\":[\"OSX_10_10\"],\"OSX_10_12\":[\"OSX_10_11\"],\"OSX_10_13\":[\"OSX_10_12\"],\"OSX_10_14\":[\"OSX_10_13\"],\"OSX_10_15\":[\"OSX_10_14\"],\"OSX_10_9\":[],\"default\":[\"OSX_10_12\"]}}", "security-framework_2.11.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.6\"},{\"name\":\"core-foundation\",\"req\":\"^0.9.4\"},{\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"libc\",\"req\":\"^0.2.139\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"name\":\"num-bigint\",\"optional\":true,\"req\":\"^0.4.6\"},{\"default_features\":false,\"name\":\"security-framework-sys\",\"req\":\"^2.11.1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.3.0\"},{\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.17\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.16\"}],\"features\":{\"OSX_10_10\":[\"OSX_10_9\",\"security-framework-sys/OSX_10_10\"],\"OSX_10_11\":[\"OSX_10_10\",\"security-framework-sys/OSX_10_11\"],\"OSX_10_12\":[\"OSX_10_11\",\"security-framework-sys/OSX_10_12\"],\"OSX_10_13\":[\"OSX_10_12\",\"security-framework-sys/OSX_10_13\",\"alpn\",\"session-tickets\",\"serial-number-bigint\"],\"OSX_10_14\":[\"OSX_10_13\",\"security-framework-sys/OSX_10_14\"],\"OSX_10_15\":[\"OSX_10_14\",\"security-framework-sys/OSX_10_15\"],\"OSX_10_9\":[\"security-framework-sys/OSX_10_9\"],\"alpn\":[],\"default\":[\"OSX_10_12\"],\"job-bless\":[],\"nightly\":[],\"serial-number-bigint\":[\"dep:num-bigint\"],\"session-tickets\":[]}}", "security-framework_3.5.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.6\"},{\"name\":\"core-foundation\",\"req\":\"^0.10\"},{\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"libc\",\"req\":\"^0.2.139\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"default_features\":false,\"name\":\"security-framework-sys\",\"req\":\"^2.15\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.12.0\"},{\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.23\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.16\"}],\"features\":{\"OSX_10_12\":[\"security-framework-sys/OSX_10_12\"],\"OSX_10_13\":[\"OSX_10_12\",\"security-framework-sys/OSX_10_13\",\"alpn\",\"session-tickets\"],\"OSX_10_14\":[\"OSX_10_13\",\"security-framework-sys/OSX_10_14\"],\"OSX_10_15\":[\"OSX_10_14\",\"security-framework-sys/OSX_10_15\"],\"alpn\":[],\"default\":[\"OSX_10_12\"],\"job-bless\":[],\"nightly\":[],\"session-tickets\":[],\"sync-keychain\":[\"OSX_10_13\"]}}", - "selectors_0.25.0": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2\"},{\"name\":\"cssparser\",\"req\":\"^0.31\"},{\"default_features\":false,\"features\":[\"add\",\"add_assign\"],\"name\":\"derive_more\",\"req\":\"^0.99\"},{\"name\":\"fxhash\",\"req\":\"^0.2\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"new_debug_unreachable\",\"req\":\"^1\"},{\"name\":\"phf\",\"req\":\"^0.10\"},{\"kind\":\"build\",\"name\":\"phf_codegen\",\"req\":\"^0.10\"},{\"name\":\"precomputed-hash\",\"req\":\"^0.1\"},{\"name\":\"servo_arc\",\"req\":\"^0.3\"},{\"name\":\"smallvec\",\"req\":\"^1.0\"}],\"features\":{\"bench\":[]}}", "self_cell_0.10.3": "{\"dependencies\":[{\"name\":\"new_self_cell\",\"package\":\"self_cell\",\"req\":\"^1\"}],\"features\":{\"old_rust\":[\"new_self_cell/old_rust\"]}}", "self_cell_1.2.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"=1.1.0\"},{\"name\":\"rustversion\",\"optional\":true,\"req\":\">=1\"}],\"features\":{\"old_rust\":[\"rustversion\"]}}", "semver_1.0.27": "{\"dependencies\":[{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"package\":\"serde_core\",\"req\":\"^1.0.220\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.220\",\"target\":\"cfg(any())\"}],\"features\":{\"default\":[\"std\"],\"serde\":[\"dep:serde\"],\"std\":[]}}", @@ -1292,7 +1263,6 @@ "serial2_0.2.33": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert2\",\"req\":\"^0.3.11\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\",\"target\":\"cfg(unix)\"},{\"name\":\"libc\",\"req\":\"^0.2.109\",\"target\":\"cfg(unix)\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.108\"},{\"features\":[\"commapi\",\"fileapi\",\"handleapi\",\"ioapiset\",\"std\",\"synchapi\",\"winbase\",\"winerror\",\"winreg\"],\"name\":\"winapi\",\"req\":\"^0.3.9\",\"target\":\"cfg(windows)\"}],\"features\":{\"doc\":[],\"doc-cfg\":[],\"rs4xx\":[],\"serde\":[\"dep:serde\"],\"unix\":[],\"windows\":[]}}", "serial_test_3.3.1": "{\"dependencies\":[{\"name\":\"document-features\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"env_logger\",\"optional\":true,\"req\":\">=0.6.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"fslock\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-executor\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"use_std\"],\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\">=0.4\"},{\"name\":\"log\",\"optional\":true,\"req\":\">=0.4.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"once_cell\",\"req\":\"^1.19\"},{\"default_features\":false,\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"default_features\":false,\"name\":\"scc\",\"req\":\"^2\"},{\"name\":\"serial_test_derive\",\"req\":\"~3.3.1\"}],\"features\":{\"async\":[\"dep:futures-executor\",\"dep:futures-util\",\"serial_test_derive/async\"],\"default\":[\"logging\",\"async\"],\"docsrs\":[\"dep:document-features\"],\"file_locks\":[\"dep:fslock\"],\"logging\":[\"dep:log\"],\"test_logging\":[\"logging\",\"dep:env_logger\",\"serial_test_derive/test_logging\"]}}", "serial_test_derive_3.3.1": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\">=0.6.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"prettyplease\",\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"proc-macro\"],\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"full\",\"printing\",\"parsing\",\"clone-impls\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"async\":[],\"default\":[],\"file_locks\":[],\"test_logging\":[]}}", - "servo_arc_0.3.0": "{\"dependencies\":[{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"stable_deref_trait\",\"req\":\"^1.0.0\"}],\"features\":{\"gecko_refcount_logging\":[],\"servo\":[\"serde\"]}}", "sha1_0.10.6": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"cpufeatures\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86\\\", target_arch = \\\"x86_64\\\"))\"},{\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.2.2\"},{\"name\":\"sha1-asm\",\"optional\":true,\"req\":\"^0.5\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86\\\", target_arch = \\\"x86_64\\\"))\"}],\"features\":{\"asm\":[\"sha1-asm\"],\"compress\":[],\"default\":[\"std\"],\"force-soft\":[],\"loongarch64_asm\":[],\"oid\":[\"digest/oid\"],\"std\":[\"digest/std\"]}}", "sha1_smol_1.0.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"openssl\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.4\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"alloc\":[],\"std\":[\"alloc\"]}}", "sha2_0.10.9": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"cpufeatures\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86_64\\\", target_arch = \\\"x86\\\"))\"},{\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.2.2\"},{\"name\":\"sha2-asm\",\"optional\":true,\"req\":\"^0.6.1\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86_64\\\", target_arch = \\\"x86\\\"))\"}],\"features\":{\"asm\":[\"sha2-asm\"],\"asm-aarch64\":[\"asm\"],\"compress\":[],\"default\":[\"std\"],\"force-soft\":[],\"force-soft-compact\":[],\"loongarch64_asm\":[],\"oid\":[\"digest/oid\"],\"std\":[\"digest/std\"]}}", @@ -1307,7 +1277,6 @@ "simd-adler32_0.3.8": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"adler\",\"req\":\"^1.0.2\"},{\"kind\":\"dev\",\"name\":\"adler32\",\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"const-generics\":[],\"default\":[\"std\",\"const-generics\"],\"nightly\":[],\"std\":[]}}", "simdutf8_0.1.5": "{\"dependencies\":[],\"features\":{\"aarch64_neon\":[],\"aarch64_neon_prefetch\":[],\"default\":[\"std\"],\"hints\":[],\"public_imp\":[],\"std\":[]}}", "similar_2.7.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bstr\",\"optional\":true,\"req\":\"^1.5.0\"},{\"kind\":\"dev\",\"name\":\"console\",\"req\":\"^0.15.0\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.10.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.130\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.68\"},{\"name\":\"unicode-segmentation\",\"optional\":true,\"req\":\"^1.7.1\"},{\"name\":\"web-time\",\"optional\":true,\"req\":\"^1.1\"}],\"features\":{\"bytes\":[\"bstr\",\"text\"],\"default\":[\"text\"],\"inline\":[\"text\"],\"text\":[],\"unicode\":[\"text\",\"unicode-segmentation\",\"bstr?/unicode\",\"bstr?/std\"],\"wasm32_web_time\":[\"web-time\"]}}", - "siphasher_0.3.11": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"serde_no_std\":[\"serde/alloc\"],\"serde_std\":[\"std\",\"serde/std\"],\"std\":[]}}", "siphasher_1.0.2": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"serde_no_std\":[\"serde/alloc\"],\"serde_std\":[\"std\",\"serde/std\"],\"std\":[]}}", "slab_0.4.12": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.95\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "smallvec_1.15.1": "{\"dependencies\":[{\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"name\":\"bincode\",\"optional\":true,\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"bincode1\",\"package\":\"bincode\",\"req\":\"^1.0.1\"},{\"kind\":\"dev\",\"name\":\"debugger_test\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"debugger_test_parser\",\"req\":\"^0.1.0\"},{\"default_features\":false,\"name\":\"malloc_size_of\",\"optional\":true,\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"name\":\"unty\",\"optional\":true,\"req\":\"^0.0.4\"}],\"features\":{\"const_generics\":[],\"const_new\":[\"const_generics\"],\"debugger_visualizer\":[],\"drain_filter\":[],\"drain_keep_rest\":[\"drain_filter\"],\"impl_bincode\":[\"bincode\",\"unty\"],\"may_dangle\":[],\"specialization\":[],\"union\":[],\"write\":[]}}", @@ -1334,7 +1303,6 @@ "stop-words_0.9.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"human_regex\",\"req\":\"^0.3.0\"},{\"kind\":\"build\",\"name\":\"serde_json\",\"req\":\"^1\"}],\"features\":{\"constructed\":[],\"default\":[\"iso\"],\"iso\":[],\"nltk\":[],\"unimplemented\":[]}}", "streaming-iterator_0.1.9": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"std\":[\"alloc\"]}}", "string_cache_0.8.9": "{\"dependencies\":[{\"default_features\":false,\"name\":\"malloc_size_of\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"new_debug_unreachable\",\"req\":\"^1.0.2\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"phf_shared\",\"req\":\"^0.11\"},{\"name\":\"precomputed-hash\",\"req\":\"^0.1\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"default\":[\"serde_support\"],\"serde_support\":[\"serde\"]}}", - "string_cache_codegen_0.5.4": "{\"dependencies\":[{\"name\":\"phf_generator\",\"req\":\"^0.11\"},{\"name\":\"phf_shared\",\"req\":\"^0.11\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"}],\"features\":{}}", "stringprep_0.1.5": "{\"dependencies\":[{\"name\":\"unicode-bidi\",\"req\":\"^0.3\"},{\"name\":\"unicode-normalization\",\"req\":\"^0.1\"},{\"name\":\"unicode-properties\",\"req\":\"^0.1.1\"}],\"features\":{}}", "strsim_0.10.0": "{\"dependencies\":[],\"features\":{}}", "strsim_0.11.1": "{\"dependencies\":[],\"features\":{}}", @@ -1347,18 +1315,15 @@ "supports-color_3.0.2": "{\"dependencies\":[{\"name\":\"is_ci\",\"req\":\"^1.2.0\"}],\"features\":{}}", "syn_1.0.109": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.46\"},{\"default_features\":false,\"name\":\"quote\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"ref-cast\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.0\"},{\"features\":[\"blocking\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"syn-test-suite\",\"req\":\"^0\"},{\"kind\":\"dev\",\"name\":\"tar\",\"req\":\"^0.4.16\"},{\"kind\":\"dev\",\"name\":\"termcolor\",\"req\":\"^1.0\"},{\"name\":\"unicode-ident\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.1\"}],\"features\":{\"clone-impls\":[],\"default\":[\"derive\",\"parsing\",\"printing\",\"clone-impls\",\"proc-macro\"],\"derive\":[],\"extra-traits\":[],\"fold\":[],\"full\":[],\"parsing\":[],\"printing\":[\"quote\"],\"proc-macro\":[\"proc-macro2/proc-macro\",\"quote/proc-macro\"],\"test\":[\"syn-test-suite/all-features\"],\"visit\":[],\"visit-mut\":[]}}", "syn_2.0.114": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.91\"},{\"default_features\":false,\"name\":\"quote\",\"optional\":true,\"req\":\"^1.0.35\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"ref-cast\",\"req\":\"^1\"},{\"features\":[\"blocking\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.13\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"syn-test-suite\",\"req\":\"^0\"},{\"kind\":\"dev\",\"name\":\"tar\",\"req\":\"^0.4.16\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"termcolor\",\"req\":\"^1\"},{\"name\":\"unicode-ident\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\",\"target\":\"cfg(not(miri))\"}],\"features\":{\"clone-impls\":[],\"default\":[\"derive\",\"parsing\",\"printing\",\"clone-impls\",\"proc-macro\"],\"derive\":[],\"extra-traits\":[],\"fold\":[],\"full\":[],\"parsing\":[],\"printing\":[\"dep:quote\"],\"proc-macro\":[\"proc-macro2/proc-macro\",\"quote?/proc-macro\"],\"test\":[\"syn-test-suite/all-features\"],\"visit\":[],\"visit-mut\":[]}}", - "sync_wrapper_0.1.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"}],\"features\":{\"futures\":[\"futures-core\"]}}", "sync_wrapper_1.0.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"}],\"features\":{\"futures\":[\"futures-core\"]}}", "synstructure_0.13.2": "{\"dependencies\":[{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"derive\",\"parsing\",\"printing\",\"clone-impls\",\"visit\",\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"synstructure_test_traits\",\"req\":\"^0.1\"}],\"features\":{\"default\":[\"proc-macro\"],\"proc-macro\":[\"proc-macro2/proc-macro\",\"syn/proc-macro\",\"quote/proc-macro\"]}}", "syntect_5.3.0": "{\"dependencies\":[{\"name\":\"bincode\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"},{\"name\":\"fancy-regex\",\"optional\":true,\"req\":\"^0.16.2\"},{\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"fnv\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"getopts\",\"req\":\"^0.2\"},{\"name\":\"once_cell\",\"req\":\"^1.8\"},{\"default_features\":false,\"name\":\"onig\",\"optional\":true,\"req\":\"^6.5.1\"},{\"name\":\"plist\",\"optional\":true,\"req\":\"^1.3\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"public-api\",\"req\":\"^0.50.1\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.0\"},{\"name\":\"regex-syntax\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rustdoc-json\",\"req\":\"^0.9.7\"},{\"kind\":\"dev\",\"name\":\"rustup-toolchain\",\"req\":\"^0.1.5\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"thiserror\",\"req\":\"^2.0.12\"},{\"name\":\"walkdir\",\"req\":\"^2.0\"},{\"name\":\"yaml-rust\",\"optional\":true,\"req\":\"^0.4.5\"}],\"features\":{\"default\":[\"default-onig\"],\"default-fancy\":[\"parsing\",\"default-syntaxes\",\"default-themes\",\"html\",\"plist-load\",\"yaml-load\",\"dump-load\",\"dump-create\",\"regex-fancy\"],\"default-onig\":[\"parsing\",\"default-syntaxes\",\"default-themes\",\"html\",\"plist-load\",\"yaml-load\",\"dump-load\",\"dump-create\",\"regex-onig\"],\"default-syntaxes\":[\"parsing\",\"dump-load\"],\"default-themes\":[\"dump-load\"],\"dump-create\":[\"flate2\",\"bincode\"],\"dump-load\":[\"flate2\",\"bincode\"],\"html\":[\"parsing\"],\"metadata\":[\"parsing\",\"plist-load\",\"dep:serde_json\"],\"parsing\":[\"regex-syntax\",\"fnv\",\"dump-create\",\"dump-load\"],\"plist-load\":[\"plist\",\"dep:serde_json\"],\"regex-fancy\":[\"fancy-regex\"],\"regex-onig\":[\"onig\"],\"yaml-load\":[\"yaml-rust\",\"parsing\"]}}", "sys-locale_0.3.2": "{\"dependencies\":[{\"name\":\"js-sys\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(target_os = \\\"android\\\")\"},{\"name\":\"wasm-bindgen\",\"optional\":true,\"req\":\"^0.2\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"},{\"features\":[\"Window\",\"WorkerGlobalScope\",\"Navigator\",\"WorkerNavigator\"],\"name\":\"web-sys\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"}],\"features\":{\"js\":[\"js-sys\",\"wasm-bindgen\",\"web-sys\"]}}", - "system-configuration-sys_0.5.0": "{\"dependencies\":[{\"name\":\"core-foundation-sys\",\"req\":\"^0.8\"},{\"name\":\"libc\",\"req\":\"^0.2.49\"}],\"features\":{}}", "system-configuration-sys_0.6.0": "{\"dependencies\":[{\"name\":\"core-foundation-sys\",\"req\":\"^0.8\"},{\"name\":\"libc\",\"req\":\"^0.2.149\"}],\"features\":{}}", - "system-configuration_0.5.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^1\"},{\"name\":\"core-foundation\",\"req\":\"^0.9\"},{\"name\":\"system-configuration-sys\",\"req\":\"^0.5\"}],\"features\":{}}", "system-configuration_0.6.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2\"},{\"name\":\"core-foundation\",\"req\":\"^0.9\"},{\"name\":\"system-configuration-sys\",\"req\":\"^0.6\"}],\"features\":{}}", "tagptr_0.2.0": "{\"dependencies\":[],\"features\":{}}", + "tar_0.4.44": "{\"dependencies\":[{\"name\":\"filetime\",\"req\":\"^0.2.8\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"},{\"name\":\"xattr\",\"optional\":true,\"req\":\"^1.1.3\",\"target\":\"cfg(unix)\"}],\"features\":{\"default\":[\"xattr\"]}}", "tempfile_3.24.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"fastrand\",\"req\":\"^2.1.1\"},{\"default_features\":false,\"name\":\"getrandom\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"once_cell\",\"req\":\"^1.19.0\"},{\"features\":[\"fs\"],\"name\":\"rustix\",\"req\":\"^1.1.3\",\"target\":\"cfg(any(unix, target_os = \\\"wasi\\\"))\"},{\"features\":[\"Win32_Storage_FileSystem\",\"Win32_Foundation\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <0.62\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"getrandom\"],\"nightly\":[]}}", - "tendril_0.4.3": "{\"dependencies\":[{\"name\":\"encoding\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"encoding_rs\",\"optional\":true,\"req\":\"^0.8.12\"},{\"name\":\"futf\",\"req\":\"^0.1.5\"},{\"name\":\"mac\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.4\"},{\"name\":\"utf-8\",\"req\":\"^0.7\"}],\"features\":{\"bench\":[]}}", "term_0.7.0": "{\"dependencies\":[{\"name\":\"dirs-next\",\"req\":\"^2\"},{\"name\":\"rustversion\",\"req\":\"^1\",\"target\":\"cfg(windows)\"},{\"features\":[\"consoleapi\",\"wincon\",\"handleapi\",\"fileapi\"],\"name\":\"winapi\",\"req\":\"^0.3\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[]}}", "termcolor_1.4.1": "{\"dependencies\":[{\"name\":\"winapi-util\",\"req\":\"^0.1.3\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "terminal_size_0.4.3": "{\"dependencies\":[{\"features\":[\"termios\"],\"name\":\"rustix\",\"req\":\"^1.0.1\",\"target\":\"cfg(unix)\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Console\"],\"name\":\"windows-sys\",\"req\":\"^0.60.0\",\"target\":\"cfg(windows)\"}],\"features\":{}}", @@ -1568,8 +1533,8 @@ "x11rb_0.13.2": "{\"dependencies\":[{\"name\":\"as-raw-xcb-connection\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"gethostname\",\"req\":\"^1.0\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"libloading\",\"optional\":true,\"req\":\"^0.8.0\"},{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.19\"},{\"kind\":\"dev\",\"name\":\"polling\",\"req\":\"^3.4\"},{\"name\":\"raw-window-handle\",\"optional\":true,\"req\":\"^0.5.0\"},{\"default_features\":false,\"features\":[\"std\",\"event\",\"fs\",\"net\",\"system\"],\"name\":\"rustix\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"x11rb-protocol\",\"req\":\"^0.13.2\"},{\"name\":\"xcursor\",\"optional\":true,\"req\":\"^0.3.7\"}],\"features\":{\"all-extensions\":[\"x11rb-protocol/all-extensions\",\"composite\",\"damage\",\"dbe\",\"dpms\",\"dri2\",\"dri3\",\"glx\",\"present\",\"randr\",\"record\",\"render\",\"res\",\"screensaver\",\"shape\",\"shm\",\"sync\",\"xevie\",\"xf86dri\",\"xf86vidmode\",\"xfixes\",\"xinerama\",\"xinput\",\"xkb\",\"xprint\",\"xselinux\",\"xtest\",\"xv\",\"xvmc\"],\"allow-unsafe-code\":[\"libc\",\"as-raw-xcb-connection\"],\"composite\":[\"x11rb-protocol/composite\",\"xfixes\"],\"cursor\":[\"render\",\"resource_manager\",\"xcursor\"],\"damage\":[\"x11rb-protocol/damage\",\"xfixes\"],\"dbe\":[\"x11rb-protocol/dbe\"],\"dl-libxcb\":[\"allow-unsafe-code\",\"libloading\",\"once_cell\"],\"dpms\":[\"x11rb-protocol/dpms\"],\"dri2\":[\"x11rb-protocol/dri2\"],\"dri3\":[\"x11rb-protocol/dri3\"],\"extra-traits\":[\"x11rb-protocol/extra-traits\"],\"glx\":[\"x11rb-protocol/glx\"],\"image\":[],\"present\":[\"x11rb-protocol/present\",\"randr\",\"xfixes\",\"sync\"],\"randr\":[\"x11rb-protocol/randr\",\"render\"],\"record\":[\"x11rb-protocol/record\"],\"render\":[\"x11rb-protocol/render\"],\"request-parsing\":[\"x11rb-protocol/request-parsing\"],\"res\":[\"x11rb-protocol/res\"],\"resource_manager\":[\"x11rb-protocol/resource_manager\"],\"screensaver\":[\"x11rb-protocol/screensaver\"],\"shape\":[\"x11rb-protocol/shape\"],\"shm\":[\"x11rb-protocol/shm\"],\"sync\":[\"x11rb-protocol/sync\"],\"xevie\":[\"x11rb-protocol/xevie\"],\"xf86dri\":[\"x11rb-protocol/xf86dri\"],\"xf86vidmode\":[\"x11rb-protocol/xf86vidmode\"],\"xfixes\":[\"x11rb-protocol/xfixes\",\"render\",\"shape\"],\"xinerama\":[\"x11rb-protocol/xinerama\"],\"xinput\":[\"x11rb-protocol/xinput\",\"xfixes\"],\"xkb\":[\"x11rb-protocol/xkb\"],\"xprint\":[\"x11rb-protocol/xprint\"],\"xselinux\":[\"x11rb-protocol/xselinux\"],\"xtest\":[\"x11rb-protocol/xtest\"],\"xv\":[\"x11rb-protocol/xv\",\"shm\"],\"xvmc\":[\"x11rb-protocol/xvmc\",\"xv\"]}}", "x25519-dalek_2.0.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"curve25519-dalek\",\"req\":\"^4\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"features\":[\"getrandom\"],\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"zeroize_derive\"],\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"alloc\":[\"curve25519-dalek/alloc\",\"serde?/alloc\",\"zeroize?/alloc\"],\"default\":[\"alloc\",\"precomputed-tables\",\"zeroize\"],\"getrandom\":[\"rand_core/getrandom\"],\"precomputed-tables\":[\"curve25519-dalek/precomputed-tables\"],\"reusable_secrets\":[],\"serde\":[\"dep:serde\",\"curve25519-dalek/serde\"],\"static_secrets\":[],\"zeroize\":[\"dep:zeroize\",\"curve25519-dalek/zeroize\"]}}", "x509-parser_0.18.1": "{\"dependencies\":[{\"features\":[\"datetime\"],\"name\":\"asn1-rs\",\"req\":\"^0.7.0\"},{\"name\":\"aws-lc-rs\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"data-encoding\",\"req\":\"^2.2.1\"},{\"features\":[\"bigint\"],\"name\":\"der-parser\",\"req\":\"^10.0\"},{\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"name\":\"nom\",\"req\":\"^7.0\"},{\"features\":[\"crypto\",\"x509\",\"x962\"],\"name\":\"oid-registry\",\"req\":\"^0.8.1\"},{\"name\":\"ring\",\"optional\":true,\"req\":\"^0.17.12\"},{\"name\":\"rusticata-macros\",\"req\":\"^4.0\"},{\"name\":\"thiserror\",\"req\":\"^2.0\"},{\"features\":[\"formatting\"],\"name\":\"time\",\"req\":\"^0.3.35\"}],\"features\":{\"default\":[],\"validate\":[],\"verify\":[\"ring\"],\"verify-aws\":[\"aws-lc-rs\"]}}", + "xattr_1.6.1": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.150\",\"target\":\"cfg(any(target_os = \\\"freebsd\\\", target_os = \\\"netbsd\\\"))\"},{\"default_features\":false,\"features\":[\"fs\",\"std\"],\"name\":\"rustix\",\"req\":\"^1.0.0\",\"target\":\"cfg(any(target_os = \\\"android\\\", target_os = \\\"linux\\\", target_os = \\\"macos\\\", target_os = \\\"hurd\\\"))\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{\"default\":[\"unsupported\"],\"unsupported\":[]}}", "xdg-home_1.3.0": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"features\":[\"Win32_Foundation\",\"Win32_UI_Shell\",\"Win32_System_Com\"],\"name\":\"windows-sys\",\"req\":\"^0.59\",\"target\":\"cfg(windows)\"}],\"features\":{}}", - "xml-rs_0.8.28": "{\"dependencies\":[],\"features\":{}}", "xz2_0.1.7": "{\"dependencies\":[{\"name\":\"futures\",\"optional\":true,\"req\":\"^0.1.26\"},{\"name\":\"lzma-sys\",\"req\":\"^0.1.18\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.0\"},{\"kind\":\"dev\",\"name\":\"tokio-core\",\"req\":\"^0.1.17\"},{\"name\":\"tokio-io\",\"optional\":true,\"req\":\"^0.1.12\"}],\"features\":{\"static\":[\"lzma-sys/static\"],\"tokio\":[\"tokio-io\",\"futures\"]}}", "yaml-rust_0.4.5": "{\"dependencies\":[{\"name\":\"linked-hash-map\",\"req\":\"^0.5.3\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^0.9\"}],\"features\":{}}", "yansi_1.0.1": "{\"dependencies\":[{\"name\":\"is-terminal\",\"optional\":true,\"req\":\"^0.4.11\"}],\"features\":{\"_nightly\":[],\"alloc\":[],\"default\":[\"std\"],\"detect-env\":[\"std\"],\"detect-tty\":[\"is-terminal\",\"std\"],\"hyperlink\":[\"std\"],\"std\":[\"alloc\"]}}", @@ -1588,14 +1553,11 @@ "zerotrie_0.2.3": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"displaydoc\",\"req\":\"^0.2.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"litemap\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.220\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"yoke\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"name\":\"zerofrom\",\"optional\":true,\"req\":\"^0.1.3\"},{\"default_features\":false,\"name\":\"zerovec\",\"optional\":true,\"req\":\"^0.11.3\"}],\"features\":{\"alloc\":[],\"databake\":[\"dep:databake\",\"zerovec?/databake\"],\"default\":[],\"litemap\":[\"dep:litemap\",\"alloc\"],\"serde\":[\"dep:serde_core\",\"dep:litemap\",\"alloc\",\"litemap/serde\",\"zerovec?/serde\"],\"yoke\":[\"dep:yoke\"],\"zerofrom\":[\"dep:zerofrom\"]}}", "zerovec-derive_0.11.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.61\"},{\"name\":\"quote\",\"req\":\"^1.0.28\"},{\"default_features\":false,\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.45\"},{\"features\":[\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2.0.21\"}],\"features\":{}}", "zerovec_0.11.5": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.220\"},{\"default_features\":false,\"features\":[\"xxhash64\"],\"name\":\"twox-hash\",\"optional\":true,\"req\":\"^2.0.0\"},{\"default_features\":false,\"name\":\"yoke\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"name\":\"zerofrom\",\"req\":\"^0.1.3\"},{\"default_features\":false,\"name\":\"zerovec-derive\",\"optional\":true,\"req\":\"^0.11.1\"}],\"features\":{\"alloc\":[\"serde?/alloc\"],\"databake\":[\"dep:databake\"],\"derive\":[\"dep:zerovec-derive\"],\"hashmap\":[\"dep:twox-hash\",\"alloc\"],\"serde\":[\"dep:serde\"],\"std\":[],\"yoke\":[\"dep:yoke\"]}}", - "zip_0.6.6": "{\"dependencies\":[{\"name\":\"aes\",\"optional\":true,\"req\":\"^0.8.2\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"name\":\"bzip2\",\"optional\":true,\"req\":\"^0.4.3\"},{\"name\":\"constant_time_eq\",\"optional\":true,\"req\":\"^0.1.5\"},{\"name\":\"crc32fast\",\"req\":\"^1.3.2\"},{\"name\":\"crossbeam-utils\",\"req\":\"^0.8.8\",\"target\":\"cfg(any(all(target_arch = \\\"arm\\\", target_pointer_width = \\\"32\\\"), target_arch = \\\"mips\\\", target_arch = \\\"powerpc\\\"))\"},{\"default_features\":false,\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.0.23\"},{\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.2.5\"},{\"features\":[\"reset\"],\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12.1\"},{\"name\":\"pbkdf2\",\"optional\":true,\"req\":\"^0.11.0\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.7\"},{\"features\":[\"formatting\",\"macros\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.7\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"name\":\"zstd\",\"optional\":true,\"req\":\"^0.11.2\"}],\"features\":{\"aes-crypto\":[\"aes\",\"constant_time_eq\",\"hmac\",\"pbkdf2\",\"sha1\"],\"default\":[\"aes-crypto\",\"bzip2\",\"deflate\",\"time\",\"zstd\"],\"deflate\":[\"flate2/rust_backend\"],\"deflate-miniz\":[\"flate2/default\"],\"deflate-zlib\":[\"flate2/zlib\"],\"unreserved\":[]}}", "zip_2.4.2": "{\"dependencies\":[{\"name\":\"aes\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.95\"},{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"req\":\"^1.4.1\",\"target\":\"cfg(fuzzing)\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"bzip2\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"=4.4.18\"},{\"name\":\"constant_time_eq\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"crc32fast\",\"req\":\"^1.4\"},{\"name\":\"crossbeam-utils\",\"req\":\"^0.8.21\",\"target\":\"cfg(any(all(target_arch = \\\"arm\\\", target_pointer_width = \\\"32\\\"), target_arch = \\\"mips\\\", target_arch = \\\"powerpc\\\"))\"},{\"name\":\"deflate64\",\"optional\":true,\"req\":\"^0.1.9\"},{\"default_features\":false,\"name\":\"displaydoc\",\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"wasm_js\",\"std\"],\"name\":\"getrandom\",\"optional\":true,\"req\":\"^0.3.1\"},{\"features\":[\"wasm_js\",\"std\"],\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.3.1\"},{\"features\":[\"reset\"],\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12\"},{\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"lzma-rs\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"memchr\",\"req\":\"^2.7\"},{\"default_features\":false,\"name\":\"nt-time\",\"optional\":true,\"req\":\"^0.10.6\"},{\"name\":\"pbkdf2\",\"optional\":true,\"req\":\"^0.12\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.15\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.37\"},{\"default_features\":false,\"features\":[\"formatting\",\"macros\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.37\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.5\"},{\"name\":\"xz2\",\"optional\":true,\"req\":\"^0.1.7\"},{\"features\":[\"zeroize_derive\"],\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.8\"},{\"name\":\"zopfli\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"zstd\",\"optional\":true,\"req\":\"^0.13\"}],\"features\":{\"_all-features\":[],\"_deflate-any\":[],\"aes-crypto\":[\"aes\",\"constant_time_eq\",\"hmac\",\"pbkdf2\",\"sha1\",\"getrandom\",\"zeroize\"],\"chrono\":[\"chrono/default\"],\"default\":[\"aes-crypto\",\"bzip2\",\"deflate64\",\"deflate\",\"lzma\",\"time\",\"zstd\",\"xz\"],\"deflate\":[\"flate2/rust_backend\",\"deflate-zopfli\",\"deflate-flate2\"],\"deflate-flate2\":[\"_deflate-any\"],\"deflate-miniz\":[\"deflate\",\"deflate-flate2\"],\"deflate-zlib\":[\"flate2/zlib\",\"deflate-flate2\"],\"deflate-zlib-ng\":[\"flate2/zlib-ng\",\"deflate-flate2\"],\"deflate-zopfli\":[\"zopfli\",\"_deflate-any\"],\"lzma\":[\"lzma-rs/stream\"],\"nt-time\":[\"dep:nt-time\"],\"unreserved\":[],\"xz\":[\"dep:xz2\"]}}", "zmij_1.0.19": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\",\"target\":\"cfg(not(miri))\"},{\"name\":\"no-panic\",\"optional\":true,\"req\":\"^0.1.36\"},{\"kind\":\"dev\",\"name\":\"num-bigint\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"num-integer\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.8\"},{\"kind\":\"dev\",\"name\":\"opt-level\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"ryu\",\"req\":\"^1\"}],\"features\":{}}", "zopfli_0.8.3": "{\"dependencies\":[{\"name\":\"bumpalo\",\"req\":\"^3.19.0\"},{\"default_features\":false,\"name\":\"crc32fast\",\"optional\":true,\"req\":\"^1.5.0\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.28\"},{\"kind\":\"dev\",\"name\":\"miniz_oxide\",\"req\":\"^0.8.9\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.7.0\"},{\"kind\":\"dev\",\"name\":\"proptest-derive\",\"req\":\"^0.6.0\"},{\"default_features\":false,\"name\":\"simd-adler32\",\"optional\":true,\"req\":\"^0.3.7\"}],\"features\":{\"default\":[\"gzip\",\"std\",\"zlib\"],\"gzip\":[\"dep:crc32fast\"],\"nightly\":[\"crc32fast?/nightly\"],\"std\":[\"crc32fast?/std\",\"dep:log\",\"simd-adler32?/std\"],\"zlib\":[\"dep:simd-adler32\"]}}", - "zstd-safe_5.0.2+zstd.1.5.2": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.21\"},{\"default_features\":false,\"name\":\"zstd-sys\",\"req\":\"^2.0.1\"}],\"features\":{\"arrays\":[],\"bindgen\":[\"zstd-sys/bindgen\"],\"debug\":[\"zstd-sys/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-sys/experimental\"],\"legacy\":[\"zstd-sys/legacy\"],\"no_asm\":[\"zstd-sys/no_asm\"],\"pkg-config\":[\"zstd-sys/pkg-config\"],\"std\":[\"zstd-sys/std\"],\"thin\":[\"zstd-sys/thin\"],\"zdict_builder\":[\"zstd-sys/zdict_builder\"],\"zstdmt\":[\"zstd-sys/zstdmt\"]}}", "zstd-safe_7.2.4": "{\"dependencies\":[{\"default_features\":false,\"name\":\"zstd-sys\",\"req\":\"^2.0.15\"}],\"features\":{\"arrays\":[],\"bindgen\":[\"zstd-sys/bindgen\"],\"debug\":[\"zstd-sys/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-sys/experimental\"],\"fat-lto\":[\"zstd-sys/fat-lto\"],\"legacy\":[\"zstd-sys/legacy\"],\"no_asm\":[\"zstd-sys/no_asm\"],\"pkg-config\":[\"zstd-sys/pkg-config\"],\"seekable\":[\"zstd-sys/seekable\"],\"std\":[\"zstd-sys/std\"],\"thin\":[\"zstd-sys/thin\"],\"thin-lto\":[\"zstd-sys/thin-lto\"],\"zdict_builder\":[\"zstd-sys/zdict_builder\"],\"zstdmt\":[\"zstd-sys/zstdmt\"]}}", "zstd-sys_2.0.16+zstd.1.5.7": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"runtime\"],\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.72\"},{\"features\":[\"parallel\"],\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.45\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.28\"}],\"features\":{\"debug\":[],\"default\":[\"legacy\",\"zdict_builder\",\"bindgen\"],\"experimental\":[],\"fat-lto\":[],\"legacy\":[],\"no_asm\":[],\"no_wasm_shim\":[],\"non-cargo\":[],\"pkg-config\":[],\"seekable\":[],\"std\":[],\"thin\":[],\"thin-lto\":[],\"zdict_builder\":[],\"zstdmt\":[]}}", - "zstd_0.11.2+zstd.1.5.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^3.0\"},{\"kind\":\"dev\",\"name\":\"humansize\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"zstd-safe\",\"req\":\"^5.0.1\"}],\"features\":{\"arrays\":[\"zstd-safe/arrays\"],\"bindgen\":[\"zstd-safe/bindgen\"],\"debug\":[\"zstd-safe/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-safe/experimental\"],\"legacy\":[\"zstd-safe/legacy\"],\"no_asm\":[\"zstd-safe/no_asm\"],\"pkg-config\":[\"zstd-safe/pkg-config\"],\"thin\":[\"zstd-safe/thin\"],\"wasm\":[],\"zdict_builder\":[\"zstd-safe/zdict_builder\"],\"zstdmt\":[\"zstd-safe/zstdmt\"]}}", "zstd_0.13.3": "{\"dependencies\":[{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^4.0\"},{\"kind\":\"dev\",\"name\":\"humansize\",\"req\":\"^2.0\"},{\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"zstd-safe\",\"req\":\"^7.1.0\"}],\"features\":{\"arrays\":[\"zstd-safe/arrays\"],\"bindgen\":[\"zstd-safe/bindgen\"],\"debug\":[\"zstd-safe/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-safe/experimental\"],\"fat-lto\":[\"zstd-safe/fat-lto\"],\"legacy\":[\"zstd-safe/legacy\"],\"no_asm\":[\"zstd-safe/no_asm\"],\"pkg-config\":[\"zstd-safe/pkg-config\"],\"thin\":[\"zstd-safe/thin\"],\"thin-lto\":[\"zstd-safe/thin-lto\"],\"wasm\":[],\"zdict_builder\":[\"zstd-safe/zdict_builder\"],\"zstdmt\":[\"zstd-safe/zstdmt\"]}}", "zune-core_0.4.12": "{\"dependencies\":[{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.17\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.52\"}],\"features\":{\"std\":[]}}", "zune-core_0.5.1": "{\"dependencies\":[{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"std\":[]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 1974883dd4..ba3156dadd 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -831,9 +831,9 @@ dependencies = [ "form_urlencoded", "futures-util", "http 1.4.0", - "http-body 1.0.1", + "http-body", "http-body-util", - "hyper 1.8.1", + "hyper", "hyper-util", "itoa", "matchit 0.8.4", @@ -845,7 +845,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tower", "tower-layer", @@ -862,11 +862,11 @@ dependencies = [ "bytes", "futures-core", "http 1.4.0", - "http-body 1.0.1", + "http-body", "http-body-util", "mime", "pin-project-lite", - "sync_wrapper 1.0.2", + "sync_wrapper", "tower-layer", "tower-service", "tracing", @@ -1096,16 +1096,6 @@ dependencies = [ "bytes", ] -[[package]] -name = "bzip2" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8" -dependencies = [ - "bzip2-sys", - "libc", -] - [[package]] name = "bzip2" version = "0.5.2" @@ -1403,7 +1393,7 @@ dependencies = [ "http 1.4.0", "pretty_assertions", "regex-lite", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "thiserror 2.0.18", @@ -1539,36 +1529,21 @@ dependencies = [ ] [[package]] -name = "codex-artifact-presentation" +name = "codex-artifacts" version = "0.0.0" dependencies = [ - "base64 0.22.1", - "image", - "ppt-rs", + "codex-package-manager", "pretty_assertions", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", + "sha2", "tempfile", "thiserror 2.0.18", - "tiny_http", - "uuid", - "zip 2.4.2", -] - -[[package]] -name = "codex-artifact-spreadsheet" -version = "0.0.0" -dependencies = [ - "base64 0.22.1", - "pretty_assertions", - "regex", - "serde", - "serde_json", - "tempfile", - "thiserror 2.0.18", - "uuid", - "zip 2.4.2", + "tokio", + "url", + "wiremock", + "zip", ] [[package]] @@ -1590,7 +1565,7 @@ dependencies = [ "codex-core", "codex-protocol", "pretty_assertions", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", ] @@ -1678,7 +1653,7 @@ dependencies = [ "opentelemetry", "opentelemetry_sdk", "rand 0.9.2", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "thiserror 2.0.18", @@ -1686,7 +1661,7 @@ dependencies = [ "tracing", "tracing-opentelemetry", "tracing-subscriber", - "zstd 0.13.3", + "zstd", ] [[package]] @@ -1730,7 +1705,7 @@ dependencies = [ "owo-colors", "pretty_assertions", "ratatui", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "supports-color 3.0.2", @@ -1799,8 +1774,7 @@ dependencies = [ "codex-app-server-protocol", "codex-apply-patch", "codex-arg0", - "codex-artifact-presentation", - "codex-artifact-spreadsheet", + "codex-artifacts", "codex-async-utils", "codex-client", "codex-config", @@ -1858,7 +1832,7 @@ dependencies = [ "pretty_assertions", "rand 0.9.2", "regex-lite", - "reqwest 0.12.28", + "reqwest", "rmcp", "schemars 0.8.22", "seccompiler", @@ -1891,8 +1865,8 @@ dependencies = [ "wildmatch", "windows-sys 0.52.0", "wiremock", - "zip 2.4.2", - "zstd 0.13.3", + "zip", + "zstd", ] [[package]] @@ -2089,7 +2063,7 @@ name = "codex-lmstudio" version = "0.0.0" dependencies = [ "codex-core", - "reqwest 0.12.28", + "reqwest", "serde_json", "tokio", "tracing", @@ -2108,7 +2082,7 @@ dependencies = [ "codex-core", "core_test_support", "rand 0.9.2", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "sha2", @@ -2189,7 +2163,7 @@ dependencies = [ "codex-core", "futures", "pretty_assertions", - "reqwest 0.12.28", + "reqwest", "semver", "serde_json", "tokio", @@ -2216,7 +2190,7 @@ dependencies = [ "opentelemetry_sdk", "os_info", "pretty_assertions", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "strum_macros 0.27.2", @@ -2228,6 +2202,25 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "codex-package-manager" +version = "0.0.0" +dependencies = [ + "flate2", + "pretty_assertions", + "reqwest", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "thiserror 2.0.18", + "tokio", + "url", + "wiremock", + "zip", +] + [[package]] name = "codex-process-hardening" version = "0.0.0" @@ -2272,7 +2265,7 @@ dependencies = [ "codex-process-hardening", "ctor 0.6.3", "libc", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "tiny_http", @@ -2294,7 +2287,7 @@ dependencies = [ "keyring", "oauth2", "pretty_assertions", - "reqwest 0.12.28", + "reqwest", "rmcp", "schemars 0.8.22", "serde", @@ -2480,7 +2473,7 @@ dependencies = [ "ratatui", "ratatui-macros", "regex-lite", - "reqwest 0.12.28", + "reqwest", "rmcp", "serde", "serde_json", @@ -2822,12 +2815,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "constant_time_eq" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" - [[package]] name = "constant_time_eq" version = "0.3.1" @@ -2903,7 +2890,7 @@ dependencies = [ "notify", "pretty_assertions", "regex-lite", - "reqwest 0.12.28", + "reqwest", "serde_json", "shlex", "tempfile", @@ -2911,7 +2898,7 @@ dependencies = [ "tokio-tungstenite", "walkdir", "wiremock", - "zstd 0.13.3", + "zstd", ] [[package]] @@ -3080,29 +3067,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "cssparser" -version = "0.31.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3df4f93e5fbbe73ec01ec8d3f68bba73107993a5b1e7519273c32db9b0d5be" -dependencies = [ - "cssparser-macros", - "dtoa-short", - "itoa", - "phf 0.11.3", - "smallvec", -] - -[[package]] -name = "cssparser-macros" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" -dependencies = [ - "quote", - "syn 2.0.114", -] - [[package]] name = "csv" version = "1.4.0" @@ -3423,17 +3387,6 @@ dependencies = [ "syn 2.0.114", ] -[[package]] -name = "derive_more" -version = "0.99.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.114", -] - [[package]] name = "derive_more" version = "1.0.0" @@ -3603,21 +3556,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" -[[package]] -name = "dtoa" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" - -[[package]] -name = "dtoa-short" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" -dependencies = [ - "dtoa", -] - [[package]] name = "dtor" version = "0.1.1" @@ -3665,12 +3603,6 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" -[[package]] -name = "ego-tree" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12a0bb14ac04a9fcf170d0bbbef949b44cc492f4452bd20c095636956f653642" - [[package]] name = "either" version = "1.15.0" @@ -3940,6 +3872,17 @@ dependencies = [ "winapi", ] +[[package]] +name = "filetime" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db" +dependencies = [ + "cfg-if", + "libc", + "libredox", +] + [[package]] name = "find-crate" version = "0.6.3" @@ -4134,16 +4077,6 @@ dependencies = [ "libc", ] -[[package]] -name = "futf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" -dependencies = [ - "mac", - "new_debug_unreachable", -] - [[package]] name = "futures" version = "0.3.31" @@ -4372,25 +4305,6 @@ dependencies = [ "regex-syntax 0.8.8", ] -[[package]] -name = "h2" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap 2.13.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "h2" version = "0.4.13" @@ -4600,20 +4514,6 @@ version = "3.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f" -[[package]] -name = "html5ever" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7" -dependencies = [ - "log", - "mac", - "markup5ever", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "http" version = "0.2.12" @@ -4635,17 +4535,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.0.1" @@ -4665,7 +4554,7 @@ dependencies = [ "bytes", "futures-core", "http 1.4.0", - "http-body 1.0.1", + "http-body", "pin-project-lite", ] @@ -4687,30 +4576,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" -[[package]] -name = "hyper" -version = "0.14.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.3.27", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2 0.5.10", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.8.1" @@ -4721,9 +4586,9 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "h2 0.4.13", + "h2", "http 1.4.0", - "http-body 1.0.1", + "http-body", "httparse", "httpdate", "itoa", @@ -4741,7 +4606,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" dependencies = [ "http 1.4.0", - "hyper 1.8.1", + "hyper", "hyper-util", "rustls", "rustls-native-certs", @@ -4758,26 +4623,13 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper 1.8.1", + "hyper", "hyper-util", "pin-project-lite", "tokio", "tower-service", ] -[[package]] -name = "hyper-tls" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" -dependencies = [ - "bytes", - "hyper 0.14.32", - "native-tls", - "tokio", - "tokio-native-tls", -] - [[package]] name = "hyper-tls" version = "0.6.0" @@ -4786,7 +4638,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", "http-body-util", - "hyper 1.8.1", + "hyper", "hyper-util", "native-tls", "tokio", @@ -4806,14 +4658,14 @@ dependencies = [ "futures-core", "futures-util", "http 1.4.0", - "http-body 1.0.1", - "hyper 1.8.1", + "http-body", + "hyper", "ipnet", "libc", "percent-encoding", "pin-project-lite", "socket2 0.6.2", - "system-configuration 0.6.1", + "system-configuration", "tokio", "tower-service", "tracing", @@ -5721,12 +5573,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "mac" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" - [[package]] name = "mach2" version = "0.4.3" @@ -5742,20 +5588,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" -[[package]] -name = "markup5ever" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016" -dependencies = [ - "log", - "phf 0.10.1", - "phf_codegen", - "string_cache", - "string_cache_codegen", - "tendril", -] - [[package]] name = "matchers" version = "0.2.0" @@ -6253,7 +6085,7 @@ dependencies = [ "getrandom 0.2.17", "http 1.4.0", "rand 0.8.5", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "serde_path_to_error", @@ -6614,7 +6446,7 @@ dependencies = [ "bytes", "http 1.4.0", "opentelemetry", - "reqwest 0.12.28", + "reqwest", ] [[package]] @@ -6629,7 +6461,7 @@ dependencies = [ "opentelemetry-proto", "opentelemetry_sdk", "prost", - "reqwest 0.12.28", + "reqwest", "serde_json", "thiserror 2.0.18", "tokio", @@ -6758,17 +6590,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "password-hash" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700" -dependencies = [ - "base64ct", - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "paste" version = "1.0.15" @@ -6805,18 +6626,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" -[[package]] -name = "pbkdf2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" -dependencies = [ - "digest", - "hmac", - "password-hash", - "sha2", -] - [[package]] name = "pbkdf2" version = "0.12.2" @@ -6873,84 +6682,13 @@ dependencies = [ "indexmap 2.13.0", ] -[[package]] -name = "phf" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" -dependencies = [ - "phf_shared 0.10.0", -] - -[[package]] -name = "phf" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" -dependencies = [ - "phf_macros", - "phf_shared 0.11.3", -] - -[[package]] -name = "phf_codegen" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd" -dependencies = [ - "phf_generator 0.10.0", - "phf_shared 0.10.0", -] - -[[package]] -name = "phf_generator" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" -dependencies = [ - "phf_shared 0.10.0", - "rand 0.8.5", -] - -[[package]] -name = "phf_generator" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" -dependencies = [ - "phf_shared 0.11.3", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" -dependencies = [ - "phf_generator 0.11.3", - "phf_shared 0.11.3", - "proc-macro2", - "quote", - "syn 2.0.114", -] - -[[package]] -name = "phf_shared" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" -dependencies = [ - "siphasher 0.3.11", -] - [[package]] name = "phf_shared" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" dependencies = [ - "siphasher 1.0.2", + "siphasher", ] [[package]] @@ -7127,26 +6865,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" -[[package]] -name = "ppt-rs" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2135454fb8669ee8eef79c87a7e9ad6f5d563d13fb1041746e2d3e3e4d716749" -dependencies = [ - "chrono", - "clap", - "pulldown-cmark", - "regex", - "reqwest 0.11.27", - "scraper", - "syntect", - "thiserror 1.0.69", - "url", - "uuid", - "xml-rs", - "zip 0.6.6", -] - [[package]] name = "ppv-lite86" version = "0.2.21" @@ -7527,7 +7245,7 @@ version = "0.3.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3ff6a3c8ae690be8167e43777ba0bf6b0c8c2f6de165c538666affe2a32fd81" dependencies = [ - "h2 0.4.13", + "h2", "pin-project-lite", "rama-core", "rama-http", @@ -7599,7 +7317,7 @@ dependencies = [ "const_format", "fnv", "http 1.4.0", - "http-body 1.0.1", + "http-body", "http-body-util", "itoa", "memchr", @@ -7614,7 +7332,7 @@ dependencies = [ "rand 0.9.2", "serde", "serde_json", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", ] @@ -7984,46 +7702,6 @@ version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" -[[package]] -name = "reqwest" -version = "0.11.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" -dependencies = [ - "base64 0.21.7", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "h2 0.3.27", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.32", - "hyper-tls 0.5.0", - "ipnet", - "js-sys", - "log", - "mime", - "native-tls", - "once_cell", - "percent-encoding", - "pin-project-lite", - "rustls-pemfile", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper 0.1.2", - "system-configuration 0.5.1", - "tokio", - "tokio-native-tls", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "winreg 0.50.0", -] - [[package]] name = "reqwest" version = "0.12.28" @@ -8036,13 +7714,13 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "h2 0.4.13", + "h2", "http 1.4.0", - "http-body 1.0.1", + "http-body", "http-body-util", - "hyper 1.8.1", + "hyper", "hyper-rustls", - "hyper-tls 0.6.0", + "hyper-tls", "hyper-util", "js-sys", "log", @@ -8058,7 +7736,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tokio-native-tls", "tokio-rustls", @@ -8107,14 +7785,14 @@ dependencies = [ "chrono", "futures", "http 1.4.0", - "http-body 1.0.1", + "http-body", "http-body-util", "oauth2", "pastey", "pin-project-lite", "process-wrap", "rand 0.9.2", - "reqwest 0.12.28", + "reqwest", "rmcp-macros", "schemars 1.2.1", "serde", @@ -8302,15 +7980,6 @@ dependencies = [ "security-framework 3.5.1", ] -[[package]] -name = "rustls-pemfile" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" -dependencies = [ - "base64 0.21.7", -] - [[package]] name = "rustls-pki-types" version = "1.14.0" @@ -8519,29 +8188,13 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "scraper" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585480e3719b311b78a573db1c9d9c4c1f8010c2dee4cc59c2efe58ea4dbc3e1" -dependencies = [ - "ahash", - "cssparser", - "ego-tree", - "getopts", - "html5ever", - "once_cell", - "selectors", - "tendril", -] - [[package]] name = "scrypt" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" dependencies = [ - "pbkdf2 0.12.2", + "pbkdf2", "salsa20", "sha2", ] @@ -8625,25 +8278,6 @@ dependencies = [ "libc", ] -[[package]] -name = "selectors" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb30575f3638fc8f6815f448d50cb1a2e255b0897985c8c59f4d37b72a07b06" -dependencies = [ - "bitflags 2.10.0", - "cssparser", - "derive_more 0.99.20", - "fxhash", - "log", - "new_debug_unreachable", - "phf 0.10.1", - "phf_codegen", - "precomputed-hash", - "servo_arc", - "smallvec", -] - [[package]] name = "self_cell" version = "0.10.3" @@ -8673,7 +8307,7 @@ checksum = "2f925d575b468e88b079faf590a8dd0c9c99e2ec29e9bab663ceb8b45056312f" dependencies = [ "httpdate", "native-tls", - "reqwest 0.12.28", + "reqwest", "sentry-actix", "sentry-backtrace", "sentry-contexts", @@ -8978,15 +8612,6 @@ dependencies = [ "syn 2.0.114", ] -[[package]] -name = "servo_arc" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d036d71a959e00c77a63538b90a6c2390969f9772b096ea837205c6bd0491a44" -dependencies = [ - "stable_deref_trait", -] - [[package]] name = "sha1" version = "0.10.6" @@ -9105,12 +8730,6 @@ version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" -[[package]] -name = "siphasher" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" - [[package]] name = "siphasher" version = "1.0.2" @@ -9397,7 +9016,7 @@ checksum = "eb4dc4d33c68ec1f27d386b5610a351922656e1fdf5c05bbaad930cd1519479a" dependencies = [ "bytes", "futures-util", - "http-body 1.0.1", + "http-body", "http-body-util", "pin-project-lite", ] @@ -9527,21 +9146,8 @@ checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" dependencies = [ "new_debug_unreachable", "parking_lot", - "phf_shared 0.11.3", + "phf_shared", "precomputed-hash", - "serde", -] - -[[package]] -name = "string_cache_codegen" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" -dependencies = [ - "phf_generator 0.11.3", - "phf_shared 0.11.3", - "proc-macro2", - "quote", ] [[package]] @@ -9654,12 +9260,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "sync_wrapper" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" - [[package]] name = "sync_wrapper" version = "1.0.2" @@ -9710,17 +9310,6 @@ dependencies = [ "libc", ] -[[package]] -name = "system-configuration" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "system-configuration-sys 0.5.0", -] - [[package]] name = "system-configuration" version = "0.6.1" @@ -9729,17 +9318,7 @@ checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ "bitflags 2.10.0", "core-foundation 0.9.4", - "system-configuration-sys 0.6.0", -] - -[[package]] -name = "system-configuration-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" -dependencies = [ - "core-foundation-sys", - "libc", + "system-configuration-sys", ] [[package]] @@ -9758,6 +9337,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tar" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "tempfile" version = "3.24.0" @@ -9771,17 +9361,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "tendril" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" -dependencies = [ - "futf", - "mac", - "utf-8", -] - [[package]] name = "term" version = "0.7.0" @@ -10233,15 +9812,15 @@ dependencies = [ "base64 0.22.1", "bytes", "http 1.4.0", - "http-body 1.0.1", + "http-body", "http-body-util", - "hyper 1.8.1", + "hyper", "hyper-timeout", "hyper-util", "percent-encoding", "pin-project", "rustls-native-certs", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tokio-rustls", "tokio-stream", @@ -10273,7 +9852,7 @@ dependencies = [ "indexmap 2.13.0", "pin-project-lite", "slab", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tokio-util", "tower-layer", @@ -10291,7 +9870,7 @@ dependencies = [ "bytes", "futures-util", "http 1.4.0", - "http-body 1.0.1", + "http-body", "iri-string", "pin-project-lite", "tower", @@ -11732,7 +11311,7 @@ dependencies = [ "futures", "http 1.4.0", "http-body-util", - "hyper 1.8.1", + "hyper", "hyper-util", "log", "once_cell", @@ -11821,6 +11400,16 @@ dependencies = [ "time", ] +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.3", +] + [[package]] name = "xdg-home" version = "1.3.0" @@ -11831,12 +11420,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "xml-rs" -version = "0.8.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" - [[package]] name = "xz2" version = "0.1.7" @@ -12050,26 +11633,6 @@ dependencies = [ "syn 2.0.114", ] -[[package]] -name = "zip" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261" -dependencies = [ - "aes", - "byteorder", - "bzip2 0.4.4", - "constant_time_eq 0.1.5", - "crc32fast", - "crossbeam-utils", - "flate2", - "hmac", - "pbkdf2 0.11.0", - "sha1", - "time", - "zstd 0.11.2+zstd.1.5.2", -] - [[package]] name = "zip" version = "2.4.2" @@ -12078,8 +11641,8 @@ checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" dependencies = [ "aes", "arbitrary", - "bzip2 0.5.2", - "constant_time_eq 0.3.1", + "bzip2", + "constant_time_eq", "crc32fast", "crossbeam-utils", "deflate64", @@ -12090,14 +11653,14 @@ dependencies = [ "indexmap 2.13.0", "lzma-rs", "memchr", - "pbkdf2 0.12.2", + "pbkdf2", "sha1", "thiserror 2.0.18", "time", "xz2", "zeroize", "zopfli", - "zstd 0.13.3", + "zstd", ] [[package]] @@ -12118,32 +11681,13 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "zstd" -version = "0.11.2+zstd.1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" -dependencies = [ - "zstd-safe 5.0.2+zstd.1.5.2", -] - [[package]] name = "zstd" version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" dependencies = [ - "zstd-safe 7.2.4", -] - -[[package]] -name = "zstd-safe" -version = "5.0.2+zstd.1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db" -dependencies = [ - "libc", - "zstd-sys", + "zstd-safe", ] [[package]] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 9ee05e21b6..21cbad4b10 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -33,8 +33,6 @@ members = [ "mcp-server", "network-proxy", "ollama", - "artifact-presentation", - "artifact-spreadsheet", "process-hardening", "protocol", "rmcp-client", @@ -66,6 +64,8 @@ members = [ "state", "codex-experimental-api-macros", "test-macros", + "package-manager", + "artifacts", ] resolver = "2" @@ -83,6 +83,8 @@ license = "Apache-2.0" app_test_support = { path = "app-server/tests/common" } codex-ansi-escape = { path = "ansi-escape" } codex-api = { path = "codex-api" } +codex-artifacts = { path = "artifacts" } +codex-package-manager = { path = "package-manager" } codex-app-server = { path = "app-server" } codex-app-server-protocol = { path = "app-server-protocol" } codex-app-server-test-client = { path = "app-server-test-client" } @@ -111,8 +113,6 @@ codex-mcp-server = { path = "mcp-server" } codex-network-proxy = { path = "network-proxy" } codex-ollama = { path = "ollama" } codex-otel = { path = "otel" } -codex-artifact-presentation = { path = "artifact-presentation" } -codex-artifact-spreadsheet = { path = "artifact-spreadsheet" } codex-process-hardening = { path = "process-hardening" } codex-protocol = { path = "protocol" } codex-responses-api-proxy = { path = "responses-api-proxy" } @@ -181,6 +181,7 @@ encoding_rs = "0.8.35" env-flags = "0.1.1" env_logger = "0.11.9" eventsource-stream = "0.2.3" +flate2 = "1.1.4" futures = { version = "0.3", default-features = false } gethostname = "1.1.0" globset = "0.4" @@ -219,7 +220,6 @@ owo-colors = "4.3.0" path-absolutize = "3.1.1" pathdiff = "0.2" portable-pty = "0.9.0" -ppt-rs = "0.2.6" predicates = "3" pretty_assertions = "1.4.1" pulldown-cmark = "0.10" @@ -267,6 +267,7 @@ supports-color = "3.0.2" syntect = "5" sys-locale = "0.3.2" tempfile = "3.23.0" +tar = "0.4.44" test-log = "0.2.19" textwrap = "0.16.2" thiserror = "2.0.17" @@ -353,8 +354,7 @@ ignored = [ "icu_provider", "openssl-sys", "codex-utils-readiness", - "codex-secrets", - "codex-artifact-spreadsheet" + "codex-secrets" ] [profile.release] diff --git a/codex-rs/artifact-presentation/BUILD.bazel b/codex-rs/artifact-presentation/BUILD.bazel deleted file mode 100644 index d89e395b3f..0000000000 --- a/codex-rs/artifact-presentation/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "artifact-presentation", - crate_name = "codex_artifact_presentation", -) diff --git a/codex-rs/artifact-presentation/Cargo.toml b/codex-rs/artifact-presentation/Cargo.toml deleted file mode 100644 index 898beb40f0..0000000000 --- a/codex-rs/artifact-presentation/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "codex-artifact-presentation" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lib] -name = "codex_artifact_presentation" -path = "src/lib.rs" - -[lints] -workspace = true - -[dependencies] -base64 = { workspace = true } -image = { workspace = true, features = ["jpeg", "png"] } -ppt-rs = { workspace = true } -reqwest = { workspace = true, features = ["blocking"] } -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -thiserror = { workspace = true } -uuid = { workspace = true, features = ["v4"] } -zip = { workspace = true } - -[dev-dependencies] -pretty_assertions = { workspace = true } -tempfile = { workspace = true } -tiny_http = { workspace = true } diff --git a/codex-rs/artifact-presentation/src/lib.rs b/codex-rs/artifact-presentation/src/lib.rs deleted file mode 100644 index 34bca50a91..0000000000 --- a/codex-rs/artifact-presentation/src/lib.rs +++ /dev/null @@ -1,6 +0,0 @@ -mod presentation_artifact; - -#[cfg(test)] -mod tests; - -pub use presentation_artifact::*; diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/api.rs b/codex-rs/artifact-presentation/src/presentation_artifact/api.rs deleted file mode 100644 index 5680bf97fe..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/api.rs +++ /dev/null @@ -1,249 +0,0 @@ -use base64::Engine; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use image::GenericImageView; -use image::ImageFormat; -use image::codecs::jpeg::JpegEncoder; -use image::imageops::FilterType; -use ppt_rs::Chart; -use ppt_rs::ChartSeries; -use ppt_rs::ChartType; -use ppt_rs::Hyperlink as PptHyperlink; -use ppt_rs::HyperlinkAction as PptHyperlinkAction; -use ppt_rs::Image; -use ppt_rs::Presentation; -use ppt_rs::Shape; -use ppt_rs::ShapeFill; -use ppt_rs::ShapeLine; -use ppt_rs::ShapeType; -use ppt_rs::SlideContent; -use ppt_rs::SlideLayout; -use ppt_rs::TableBuilder; -use ppt_rs::TableCell; -use ppt_rs::TableRow; -use ppt_rs::generator::ArrowSize; -use ppt_rs::generator::ArrowType; -use ppt_rs::generator::CellAlign; -use ppt_rs::generator::Connector; -use ppt_rs::generator::ConnectorLine; -use ppt_rs::generator::ConnectorType; -use ppt_rs::generator::LineDash; -use ppt_rs::generator::generate_image_content_type; -use serde::Deserialize; -use serde::Serialize; -use serde_json::Value; -use std::collections::BTreeSet; -use std::collections::HashMap; -use std::collections::HashSet; -use std::io::Cursor; -use std::io::Read; -use std::io::Seek; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; -use thiserror::Error; -use uuid::Uuid; -use zip::ZipArchive; -use zip::ZipWriter; -use zip::write::SimpleFileOptions; - -const POINT_TO_EMU: u32 = 12_700; -const DEFAULT_SLIDE_WIDTH_POINTS: u32 = 720; -const DEFAULT_SLIDE_HEIGHT_POINTS: u32 = 540; -const DEFAULT_IMPORTED_TITLE_LEFT: u32 = 36; -const DEFAULT_IMPORTED_TITLE_TOP: u32 = 24; -const DEFAULT_IMPORTED_TITLE_WIDTH: u32 = 648; -const DEFAULT_IMPORTED_TITLE_HEIGHT: u32 = 48; -const DEFAULT_IMPORTED_CONTENT_LEFT: u32 = 48; -const DEFAULT_IMPORTED_CONTENT_TOP: u32 = 96; -const DEFAULT_IMPORTED_CONTENT_WIDTH: u32 = 624; -const DEFAULT_IMPORTED_CONTENT_HEIGHT: u32 = 324; - -#[derive(Debug, Error)] -pub enum PresentationArtifactError { - #[error("missing `artifact_id` for action `{action}`")] - MissingArtifactId { action: String }, - #[error("unknown artifact id `{artifact_id}` for action `{action}`")] - UnknownArtifactId { action: String, artifact_id: String }, - #[error("unknown action `{0}`")] - UnknownAction(String), - #[error("invalid args for action `{action}`: {message}")] - InvalidArgs { action: String, message: String }, - #[error("unsupported feature for action `{action}`: {message}")] - UnsupportedFeature { action: String, message: String }, - #[error("failed to import PPTX `{path}`: {message}")] - ImportFailed { path: PathBuf, message: String }, - #[error("failed to export PPTX `{path}`: {message}")] - ExportFailed { path: PathBuf, message: String }, -} - -#[derive(Debug, Clone, Deserialize)] -pub struct PresentationArtifactRequest { - pub artifact_id: Option, - pub action: String, - #[serde(default)] - pub args: Value, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PresentationArtifactToolRequest { - pub artifact_id: Option, - pub actions: Vec, -} - -#[derive(Debug, Clone)] -pub struct PresentationArtifactExecutionRequest { - pub artifact_id: Option, - pub requests: Vec, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PresentationArtifactToolAction { - pub action: String, - #[serde(default)] - pub args: Value, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PathAccessKind { - Read, - Write, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PathAccessRequirement { - pub action: String, - pub kind: PathAccessKind, - pub path: PathBuf, -} - -impl PresentationArtifactRequest { - pub fn is_mutating(&self) -> bool { - !is_read_only_action(&self.action) - } - - pub fn required_path_accesses( - &self, - cwd: &Path, - ) -> Result, PresentationArtifactError> { - let access = match self.action.as_str() { - "import_pptx" => { - let args: ImportPptxArgs = parse_args(&self.action, &self.args)?; - vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Read, - path: resolve_path(cwd, &args.path), - }] - } - "export_pptx" => { - let args: ExportPptxArgs = parse_args(&self.action, &self.args)?; - vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Write, - path: resolve_path(cwd, &args.path), - }] - } - "export_preview" => { - let args: ExportPreviewArgs = parse_args(&self.action, &self.args)?; - vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Write, - path: resolve_path(cwd, &args.path), - }] - } - "add_image" => { - let args: AddImageArgs = parse_args(&self.action, &self.args)?; - match args.image_source()? { - ImageInputSource::Path(path) => vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Read, - path: resolve_path(cwd, &path), - }], - ImageInputSource::DataUrl(_) - | ImageInputSource::Blob(_) - | ImageInputSource::Uri(_) - | ImageInputSource::Placeholder => Vec::new(), - } - } - "replace_image" => { - let args: ReplaceImageArgs = parse_args(&self.action, &self.args)?; - match ( - &args.path, - &args.data_url, - &args.blob, - &args.uri, - &args.prompt, - ) { - (Some(path), None, None, None, None) => vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Read, - path: resolve_path(cwd, path), - }], - (None, Some(_), None, None, None) - | (None, None, Some(_), None, None) - | (None, None, None, Some(_), None) - | (None, None, None, None, Some(_)) => Vec::new(), - _ => { - return Err(PresentationArtifactError::InvalidArgs { - action: self.action.clone(), - message: - "provide exactly one of `path`, `data_url`, `blob`, or `uri`, or provide `prompt` for a placeholder image" - .to_string(), - }); - } - } - } - _ => Vec::new(), - }; - Ok(access) - } -} - -impl PresentationArtifactToolRequest { - pub fn is_mutating(&self) -> Result { - Ok(self.actions.iter().any(|request| !is_read_only_action(&request.action))) - } - - pub fn into_execution_request( - self, - ) -> Result { - if self.actions.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: "presentation_artifact".to_string(), - message: "`actions` must contain at least one item".to_string(), - }); - } - Ok(PresentationArtifactExecutionRequest { - artifact_id: self.artifact_id, - requests: self - .actions - .into_iter() - .map(|request| PresentationArtifactRequest { - artifact_id: None, - action: request.action, - args: request.args, - }) - .collect(), - }) - } - - pub fn required_path_accesses( - &self, - cwd: &Path, - ) -> Result, PresentationArtifactError> { - let mut accesses = Vec::new(); - for request in &self.actions { - accesses.extend( - PresentationArtifactRequest { - artifact_id: None, - action: request.action.clone(), - args: request.args.clone(), - } - .required_path_accesses(cwd)?, - ); - } - Ok(accesses) - } -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/args.rs b/codex-rs/artifact-presentation/src/presentation_artifact/args.rs deleted file mode 100644 index a139dcb055..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/args.rs +++ /dev/null @@ -1,729 +0,0 @@ -#[derive(Debug, Deserialize)] -struct CreateArgs { - name: Option, - slide_size: Option, - theme: Option, -} - -#[derive(Debug, Deserialize)] -struct ImportPptxArgs { - path: PathBuf, -} - -#[derive(Debug, Deserialize)] -struct ExportPptxArgs { - path: PathBuf, -} - -#[derive(Debug, Deserialize)] -struct ExportPreviewArgs { - path: PathBuf, - slide_index: Option, - format: Option, - scale: Option, - quality: Option, -} - -#[derive(Debug, Default, Deserialize)] -struct AddSlideArgs { - layout: Option, - notes: Option, - background_fill: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateLayoutArgs { - name: String, - kind: Option, - parent_layout_id: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum PreviewOutputFormat { - Png, - Jpeg, - Svg, -} - -impl PreviewOutputFormat { - fn extension(self) -> &'static str { - match self { - Self::Png => "png", - Self::Jpeg => "jpg", - Self::Svg => "svg", - } - } -} - -#[derive(Debug, Deserialize)] -struct AddLayoutPlaceholderArgs { - layout_id: String, - name: String, - placeholder_type: String, - index: Option, - text: Option, - geometry: Option, - position: Option, -} - -#[derive(Debug, Deserialize)] -struct LayoutIdArgs { - layout_id: String, -} - -#[derive(Debug, Deserialize)] -struct SetSlideLayoutArgs { - slide_index: u32, - layout_id: String, -} - -#[derive(Debug, Deserialize)] -struct UpdatePlaceholderTextArgs { - slide_index: u32, - name: String, - text: String, -} - -#[derive(Debug, Deserialize)] -struct NotesArgs { - slide_index: u32, - text: Option, -} - -#[derive(Debug, Deserialize)] -struct NotesVisibilityArgs { - slide_index: u32, - visible: bool, -} - -#[derive(Debug, Deserialize)] -struct ThemeArgs { - color_scheme: HashMap, - major_font: Option, - minor_font: Option, -} - -#[derive(Debug, Deserialize)] -struct StyleNameArgs { - name: String, -} - -#[derive(Debug, Deserialize)] -struct AddStyleArgs { - name: String, - #[serde(flatten)] - styling: TextStylingArgs, -} - -#[derive(Debug, Deserialize)] -struct InspectArgs { - kind: Option, - include: Option, - exclude: Option, - search: Option, - target_id: Option, - target: Option, - max_chars: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct InspectTargetArgs { - id: String, - before_lines: Option, - after_lines: Option, -} - -#[derive(Debug, Deserialize)] -struct ResolveArgs { - id: String, -} - -#[derive(Debug, Clone, Deserialize)] -struct PatchOperationInput { - artifact_id: Option, - action: String, - #[serde(default)] - args: Value, -} - -#[derive(Debug, Deserialize)] -struct RecordPatchArgs { - operations: Vec, -} - -#[derive(Debug, Deserialize)] -struct ApplyPatchArgs { - operations: Option>, - patch: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -struct PresentationPatch { - version: u32, - artifact_id: String, - operations: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct PatchOperation { - action: String, - #[serde(default)] - args: Value, -} - -#[derive(Debug, Default, Deserialize)] -struct InsertSlideArgs { - index: Option, - after_slide_index: Option, - layout: Option, - notes: Option, - background_fill: Option, -} - -#[derive(Debug, Deserialize)] -struct SlideIndexArgs { - slide_index: u32, -} - -#[derive(Debug, Deserialize)] -struct MoveSlideArgs { - from_index: u32, - to_index: u32, -} - -#[derive(Debug, Deserialize)] -struct SetActiveSlideArgs { - slide_index: u32, -} - -#[derive(Debug, Deserialize)] -struct SetSlideBackgroundArgs { - slide_index: u32, - fill: String, -} - -#[derive(Debug, Clone, Deserialize)] -struct PositionArgs { - left: u32, - top: u32, - width: u32, - height: u32, - rotation: Option, - flip_horizontal: Option, - flip_vertical: Option, -} - -#[derive(Debug, Clone, Default, Deserialize)] -struct PartialPositionArgs { - left: Option, - top: Option, - width: Option, - height: Option, - rotation: Option, - flip_horizontal: Option, - flip_vertical: Option, -} - -#[derive(Debug, Clone, Default, Deserialize)] -struct TextStylingArgs { - style: Option, - font_size: Option, - font_family: Option, - color: Option, - fill: Option, - alignment: Option, - bold: Option, - italic: Option, - underline: Option, -} - -#[derive(Debug, Clone, Default, Deserialize)] -struct TextLayoutArgs { - insets: Option, - wrap: Option, - auto_fit: Option, - vertical_alignment: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct TextInsetsArgs { - left: u32, - right: u32, - top: u32, - bottom: u32, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(untagged)] -enum RichTextInput { - Plain(String), - Paragraphs(Vec), -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(untagged)] -enum RichParagraphInput { - Plain(String), - Runs(Vec), -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(untagged)] -enum RichRunInput { - Plain(String), - Styled(RichRunObjectInput), -} - -#[derive(Debug, Clone, Deserialize)] -struct RichRunObjectInput { - run: String, - #[serde(default)] - text_style: TextStylingArgs, - link: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct RichTextLinkInput { - uri: Option, - is_external: Option, -} - -#[derive(Debug, Deserialize)] -struct AddTextShapeArgs { - slide_index: u32, - text: String, - position: PositionArgs, - #[serde(flatten)] - styling: TextStylingArgs, - #[serde(default)] - text_layout: TextLayoutArgs, -} - -#[derive(Debug, Clone, Default, Deserialize)] -struct StrokeArgs { - color: String, - width: u32, - style: Option, -} - -#[derive(Debug, Deserialize)] -struct AddShapeArgs { - slide_index: u32, - geometry: String, - position: PositionArgs, - fill: Option, - stroke: Option, - text: Option, - rotation: Option, - flip_horizontal: Option, - flip_vertical: Option, - #[serde(default)] - text_style: TextStylingArgs, - #[serde(default)] - text_layout: TextLayoutArgs, -} - -#[derive(Debug, Clone, Default, Deserialize)] -struct ConnectorLineArgs { - color: Option, - width: Option, - style: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct PointArgs { - left: u32, - top: u32, -} - -#[derive(Debug, Deserialize)] -struct AddConnectorArgs { - slide_index: u32, - connector_type: String, - start: PointArgs, - end: PointArgs, - line: Option, - start_arrow: Option, - end_arrow: Option, - arrow_size: Option, - label: Option, -} - -#[derive(Debug, Deserialize)] -struct AddImageArgs { - slide_index: u32, - path: Option, - data_url: Option, - blob: Option, - uri: Option, - position: PositionArgs, - fit: Option, - crop: Option, - rotation: Option, - flip_horizontal: Option, - flip_vertical: Option, - lock_aspect_ratio: Option, - alt: Option, - prompt: Option, -} - -impl AddImageArgs { - fn image_source(&self) -> Result { - match (&self.path, &self.data_url, &self.blob, &self.uri) { - (Some(path), None, None, None) => Ok(ImageInputSource::Path(path.clone())), - (None, Some(data_url), None, None) => Ok(ImageInputSource::DataUrl(data_url.clone())), - (None, None, Some(blob), None) => Ok(ImageInputSource::Blob(blob.clone())), - (None, None, None, Some(uri)) => Ok(ImageInputSource::Uri(uri.clone())), - (None, None, None, None) if self.prompt.is_some() => Ok(ImageInputSource::Placeholder), - _ => Err(PresentationArtifactError::InvalidArgs { - action: "add_image".to_string(), - message: - "provide exactly one of `path`, `data_url`, `blob`, or `uri`, or provide `prompt` for a placeholder image" - .to_string(), - }), - } - } -} - -enum ImageInputSource { - Path(PathBuf), - DataUrl(String), - Blob(String), - Uri(String), - Placeholder, -} - -#[derive(Debug, Clone, Deserialize)] -struct ImageCropArgs { - left: f64, - top: f64, - right: f64, - bottom: f64, -} - -#[derive(Debug, Deserialize)] -struct AddTableArgs { - slide_index: u32, - position: PositionArgs, - rows: Vec>, - column_widths: Option>, - row_heights: Option>, - style: Option, - style_options: Option, - borders: Option, - right_to_left: Option, -} - -#[derive(Debug, Deserialize)] -struct AddChartArgs { - slide_index: u32, - position: PositionArgs, - chart_type: String, - categories: Vec, - series: Vec, - title: Option, - style_index: Option, - has_legend: Option, - legend_position: Option, - #[serde(default)] - legend_text_style: TextStylingArgs, - x_axis_title: Option, - y_axis_title: Option, - data_labels: Option, - chart_fill: Option, - plot_area_fill: Option, -} - -#[derive(Debug, Deserialize)] -struct ChartSeriesArgs { - name: String, - values: Vec, - categories: Option>, - x_values: Option>, - fill: Option, - stroke: Option, - marker: Option, - data_label_overrides: Option>, -} - -#[derive(Debug, Clone, Deserialize)] -struct ChartMarkerArgs { - symbol: Option, - size: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct ChartDataLabelsArgs { - show_value: Option, - show_category_name: Option, - show_leader_lines: Option, - position: Option, - #[serde(default)] - text_style: TextStylingArgs, -} - -#[derive(Debug, Clone, Deserialize)] -struct ChartDataLabelOverrideArgs { - idx: u32, - text: Option, - position: Option, - #[serde(default)] - text_style: TextStylingArgs, - fill: Option, - stroke: Option, -} - -#[derive(Debug, Deserialize)] -struct UpdateTextArgs { - element_id: String, - text: String, - #[serde(default)] - styling: TextStylingArgs, - #[serde(default)] - text_layout: TextLayoutArgs, -} - -#[derive(Debug, Deserialize)] -struct SetRichTextArgs { - element_id: Option, - slide_index: Option, - row: Option, - column: Option, - notes: Option, - text: RichTextInput, - #[serde(default)] - styling: TextStylingArgs, - #[serde(default)] - text_layout: TextLayoutArgs, -} - -#[derive(Debug, Deserialize)] -struct FormatTextRangeArgs { - element_id: Option, - slide_index: Option, - row: Option, - column: Option, - notes: Option, - query: Option, - occurrence: Option, - start_cp: Option, - length: Option, - #[serde(default)] - styling: TextStylingArgs, - #[serde(default)] - text_layout: TextLayoutArgs, - link: Option, - spacing_before: Option, - spacing_after: Option, - line_spacing: Option, -} - -#[derive(Debug, Deserialize)] -struct ReplaceTextArgs { - element_id: String, - search: String, - replace: String, -} - -#[derive(Debug, Deserialize)] -struct InsertTextAfterArgs { - element_id: String, - after: String, - insert: String, -} - -#[derive(Debug, Deserialize)] -struct SetHyperlinkArgs { - element_id: String, - link_type: Option, - url: Option, - slide_index: Option, - address: Option, - subject: Option, - path: Option, - tooltip: Option, - highlight_click: Option, - clear: Option, -} - -#[derive(Debug, Deserialize)] -struct UpdateShapeStyleArgs { - element_id: String, - position: Option, - fill: Option, - stroke: Option, - rotation: Option, - flip_horizontal: Option, - flip_vertical: Option, - fit: Option, - crop: Option, - lock_aspect_ratio: Option, - z_order: Option, - #[serde(default)] - text_layout: TextLayoutArgs, -} - -#[derive(Debug, Deserialize)] -struct ElementIdArgs { - element_id: String, -} - -#[derive(Debug, Deserialize)] -struct ReplaceImageArgs { - element_id: String, - path: Option, - data_url: Option, - blob: Option, - uri: Option, - fit: Option, - crop: Option, - rotation: Option, - flip_horizontal: Option, - flip_vertical: Option, - lock_aspect_ratio: Option, - alt: Option, - prompt: Option, -} - -#[derive(Debug, Deserialize)] -struct UpdateTableCellArgs { - element_id: String, - row: u32, - column: u32, - value: Value, - #[serde(default)] - styling: TextStylingArgs, - background_fill: Option, - alignment: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct TableStyleOptionsArgs { - header_row: Option, - banded_rows: Option, - banded_columns: Option, - first_column: Option, - last_column: Option, - total_row: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct TableBorderArgs { - color: String, - width: u32, -} - -#[derive(Debug, Clone, Deserialize)] -struct TableBordersArgs { - outside: Option, - inside: Option, - top: Option, - bottom: Option, - left: Option, - right: Option, -} - -#[derive(Debug, Deserialize)] -struct UpdateTableStyleArgs { - element_id: String, - style: Option, - style_options: Option, - borders: Option, - right_to_left: Option, -} - -#[derive(Debug, Deserialize)] -struct StyleTableBlockArgs { - element_id: String, - row: u32, - column: u32, - row_count: u32, - column_count: u32, - #[serde(default)] - styling: TextStylingArgs, - background_fill: Option, - alignment: Option, - borders: Option, -} - -#[derive(Debug, Deserialize)] -struct MergeTableCellsArgs { - element_id: String, - start_row: u32, - end_row: u32, - start_column: u32, - end_column: u32, -} - -#[derive(Debug, Deserialize)] -struct UpdateChartArgs { - element_id: String, - title: Option, - categories: Option>, - style_index: Option, - has_legend: Option, - legend_position: Option, - #[serde(default)] - legend_text_style: TextStylingArgs, - x_axis_title: Option, - y_axis_title: Option, - data_labels: Option, - chart_fill: Option, - plot_area_fill: Option, -} - -#[derive(Debug, Deserialize)] -struct AddChartSeriesArgs { - element_id: String, - name: String, - values: Vec, - categories: Option>, - x_values: Option>, - fill: Option, - stroke: Option, - marker: Option, -} - -#[derive(Debug, Deserialize)] -struct SetCommentAuthorArgs { - display_name: String, - initials: String, - email: Option, -} - -#[derive(Debug, Clone, Deserialize)] -struct CommentPositionArgs { - x: u32, - y: u32, -} - -#[derive(Debug, Deserialize)] -struct AddCommentThreadArgs { - slide_index: Option, - element_id: Option, - query: Option, - occurrence: Option, - start_cp: Option, - length: Option, - text: String, - position: Option, -} - -#[derive(Debug, Deserialize)] -struct AddCommentReplyArgs { - thread_id: String, - text: String, -} - -#[derive(Debug, Deserialize)] -struct ToggleCommentReactionArgs { - thread_id: String, - message_id: Option, - emoji: String, -} - -#[derive(Debug, Deserialize)] -struct CommentThreadIdArgs { - thread_id: String, -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs b/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs deleted file mode 100644 index 608e0734ee..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs +++ /dev/null @@ -1,871 +0,0 @@ -fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> String { - let include_kinds = args - .include - .as_deref() - .or(args.kind.as_deref()) - .unwrap_or( - "deck,slide,textbox,shape,connector,table,chart,image,notes,layoutList,textRange,comment", - ); - let included_kinds = include_kinds - .split(',') - .map(str::trim) - .filter(|entry| !entry.is_empty()) - .collect::>(); - let excluded_kinds = args - .exclude - .as_deref() - .unwrap_or_default() - .split(',') - .map(str::trim) - .filter(|entry| !entry.is_empty()) - .collect::>(); - let include = |name: &str| included_kinds.contains(name) && !excluded_kinds.contains(name); - let mut records: Vec<(Value, Option)> = Vec::new(); - if include("deck") { - records.push(( - serde_json::json!({ - "kind": "deck", - "id": format!("pr/{}", document.artifact_id), - "name": document.name, - "slides": document.slides.len(), - "styleIds": document - .named_text_styles() - .iter() - .map(|style| format!("st/{}", style.name)) - .collect::>(), - "activeSlideIndex": document.active_slide_index, - "activeSlideId": document.active_slide_index.and_then(|index| document.slides.get(index)).map(|slide| format!("sl/{}", slide.slide_id)), - "commentThreadIds": document - .comment_threads - .iter() - .map(|thread| format!("th/{}", thread.thread_id)) - .collect::>(), - }), - None, - )); - } - if include("styleList") { - for style in document.named_text_styles() { - records.push((named_text_style_to_json(&style, "st"), None)); - } - } - if include("layoutList") { - for layout in &document.layouts { - let placeholders = resolved_layout_placeholders(document, &layout.layout_id, "inspect") - .unwrap_or_default() - .into_iter() - .map(|placeholder| { - serde_json::json!({ - "name": placeholder.definition.name, - "type": placeholder.definition.placeholder_type, - "sourceLayoutId": placeholder.source_layout_id, - "textPreview": placeholder.definition.text, - }) - }) - .collect::>(); - records.push(( - serde_json::json!({ - "kind": "layout", - "id": format!("ly/{}", layout.layout_id), - "layoutId": layout.layout_id, - "name": layout.name, - "type": match layout.kind { LayoutKind::Layout => "layout", LayoutKind::Master => "master" }, - "parentLayoutId": layout.parent_layout_id, - "placeholders": placeholders, - }), - None, - )); - } - } - for (index, slide) in document.slides.iter().enumerate() { - let slide_id = format!("sl/{}", slide.slide_id); - if include("slide") { - records.push(( - serde_json::json!({ - "kind": "slide", - "id": slide_id, - "slide": index + 1, - "slideIndex": index, - "isActive": document.active_slide_index == Some(index), - "layoutId": slide.layout_id, - "elements": slide.elements.len(), - }), - Some(slide_id.clone()), - )); - } - if include("notes") && !slide.notes.text.is_empty() { - records.push(( - serde_json::json!({ - "kind": "notes", - "id": format!("nt/{}", slide.slide_id), - "slide": index + 1, - "visible": slide.notes.visible, - "text": slide.notes.text, - "textPreview": slide.notes.text.replace('\n', " | "), - "textChars": slide.notes.text.chars().count(), - "textLines": slide.notes.text.lines().count(), - "richText": rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text), - }), - Some(slide_id.clone()), - )); - } - if include("textRange") { - records.extend( - slide - .notes - .rich_text - .ranges - .iter() - .map(|range| { - let mut record = text_range_to_proto(&slide.notes.text, range); - record["kind"] = Value::String("textRange".to_string()); - record["slide"] = Value::from(index + 1); - record["slideIndex"] = Value::from(index); - record["hostAnchor"] = Value::String(format!("nt/{}", slide.slide_id)); - record["hostKind"] = Value::String("notes".to_string()); - (record, Some(slide_id.clone())) - }), - ); - } - for element in &slide.elements { - let mut record = match element { - PresentationElement::Text(text) => { - if !include("textbox") { - continue; - } - serde_json::json!({ - "kind": "textbox", - "id": format!("sh/{}", text.element_id), - "slide": index + 1, - "text": text.text, - "textStyle": text_style_to_proto(&text.style), - "textPreview": text.text.replace('\n', " | "), - "textChars": text.text.chars().count(), - "textLines": text.text.lines().count(), - "richText": rich_text_to_proto(&text.text, &text.rich_text), - "bbox": [text.frame.left, text.frame.top, text.frame.width, text.frame.height], - "bboxUnit": "points", - }) - } - PresentationElement::Shape(shape) => { - if !(include("shape") || include("textbox") && shape.text.is_some()) { - continue; - } - let kind = if shape.text.is_some() && include("textbox") { - "textbox" - } else { - "shape" - }; - let mut record = serde_json::json!({ - "kind": kind, - "id": format!("sh/{}", shape.element_id), - "slide": index + 1, - "geometry": format!("{:?}", shape.geometry), - "text": shape.text, - "textStyle": text_style_to_proto(&shape.text_style), - "richText": shape - .text - .as_ref() - .zip(shape.rich_text.as_ref()) - .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) - .unwrap_or(Value::Null), - "rotation": shape.rotation_degrees, - "flipHorizontal": shape.flip_horizontal, - "flipVertical": shape.flip_vertical, - "bbox": [shape.frame.left, shape.frame.top, shape.frame.width, shape.frame.height], - "bboxUnit": "points", - }); - if let Some(text) = &shape.text { - record["textPreview"] = Value::String(text.replace('\n', " | ")); - record["textChars"] = Value::from(text.chars().count()); - record["textLines"] = Value::from(text.lines().count()); - } - record - } - PresentationElement::Connector(connector) => { - if !include("shape") && !include("connector") { - continue; - } - serde_json::json!({ - "kind": "connector", - "id": format!("cn/{}", connector.element_id), - "slide": index + 1, - "connectorType": format!("{:?}", connector.connector_type), - "start": [connector.start.left, connector.start.top], - "end": [connector.end.left, connector.end.top], - "lineStyle": format!("{:?}", connector.line_style), - "label": connector.label, - }) - } - PresentationElement::Table(table) => { - if !include("table") { - continue; - } - serde_json::json!({ - "kind": "table", - "id": format!("tb/{}", table.element_id), - "slide": index + 1, - "rows": table.rows.len(), - "cols": table.rows.iter().map(std::vec::Vec::len).max().unwrap_or(0), - "columnWidths": table.column_widths, - "rowHeights": table.row_heights, - "preview": table.rows.first().map(|row| row.iter().map(|cell| cell.text.clone()).collect::>().join(" | ")), - "style": table.style, - "styleOptions": table_style_options_to_proto(&table.style_options), - "borders": table.borders.as_ref().map(table_borders_to_proto), - "rightToLeft": table.right_to_left, - "cellTextStyles": table - .rows - .iter() - .map(|row| row.iter().map(|cell| text_style_to_proto(&cell.text_style)).collect::>()) - .collect::>(), - "rowsData": table - .rows - .iter() - .map(|row| row.iter().map(table_cell_to_proto).collect::>()) - .collect::>(), - "bbox": [table.frame.left, table.frame.top, table.frame.width, table.frame.height], - "bboxUnit": "points", - }) - } - PresentationElement::Chart(chart) => { - if !include("chart") { - continue; - } - serde_json::json!({ - "kind": "chart", - "id": format!("ch/{}", chart.element_id), - "slide": index + 1, - "chartType": format!("{:?}", chart.chart_type), - "title": chart.title, - "styleIndex": chart.style_index, - "hasLegend": chart.has_legend, - "legend": chart.legend.as_ref().map(chart_legend_to_proto), - "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), - "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), - "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), - "chartFill": chart.chart_fill, - "plotAreaFill": chart.plot_area_fill, - "series": chart - .series - .iter() - .map(|series| serde_json::json!({ - "name": series.name, - "values": series.values, - "categories": series.categories, - "xValues": series.x_values, - "fill": series.fill, - "stroke": series.stroke.as_ref().map(stroke_to_proto), - "marker": series.marker.as_ref().map(chart_marker_to_proto), - "dataLabelOverrides": series - .data_label_overrides - .iter() - .map(chart_data_label_override_to_proto) - .collect::>(), - })) - .collect::>(), - "bbox": [chart.frame.left, chart.frame.top, chart.frame.width, chart.frame.height], - "bboxUnit": "points", - }) - } - PresentationElement::Image(image) => { - if !include("image") { - continue; - } - serde_json::json!({ - "kind": "image", - "id": format!("im/{}", image.element_id), - "slide": index + 1, - "alt": image.alt_text, - "prompt": image.prompt, - "fit": format!("{:?}", image.fit_mode), - "rotation": image.rotation_degrees, - "flipHorizontal": image.flip_horizontal, - "flipVertical": image.flip_vertical, - "crop": image.crop.map(|(left, top, right, bottom)| serde_json::json!({ - "left": left, - "top": top, - "right": right, - "bottom": bottom, - })), - "isPlaceholder": image.is_placeholder, - "lockAspectRatio": image.lock_aspect_ratio, - "bbox": [image.frame.left, image.frame.top, image.frame.width, image.frame.height], - "bboxUnit": "points", - }) - } - }; - if let Some(placeholder) = match element { - PresentationElement::Text(text) => text.placeholder.as_ref(), - PresentationElement::Shape(shape) => shape.placeholder.as_ref(), - PresentationElement::Connector(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => None, - PresentationElement::Image(image) => image.placeholder.as_ref(), - } { - record["placeholder"] = Value::String(placeholder.placeholder_type.clone()); - record["placeholderName"] = Value::String(placeholder.name.clone()); - record["placeholderIndex"] = - placeholder.index.map(Value::from).unwrap_or(Value::Null); - } - if let PresentationElement::Shape(shape) = element - && let Some(stroke) = &shape.stroke - { - record["stroke"] = serde_json::json!({ - "color": stroke.color, - "width": stroke.width, - "style": stroke.style.as_api_str(), - }); - } - if let Some(hyperlink) = match element { - PresentationElement::Text(text) => text.hyperlink.as_ref(), - PresentationElement::Shape(shape) => shape.hyperlink.as_ref(), - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => None, - } { - record["hyperlink"] = hyperlink.to_json(); - } - records.push((record, Some(slide_id.clone()))); - if include("textRange") { - match element { - PresentationElement::Text(text) => { - records.extend(text.rich_text.ranges.iter().map(|range| { - let mut record = text_range_to_proto(&text.text, range); - record["kind"] = Value::String("textRange".to_string()); - record["slide"] = Value::from(index + 1); - record["slideIndex"] = Value::from(index); - record["hostAnchor"] = Value::String(format!("sh/{}", text.element_id)); - record["hostKind"] = Value::String("textbox".to_string()); - (record, Some(slide_id.clone())) - })); - } - PresentationElement::Shape(shape) => { - if let Some((text, rich_text)) = shape.text.as_ref().zip(shape.rich_text.as_ref()) { - records.extend(rich_text.ranges.iter().map(|range| { - let mut record = text_range_to_proto(text, range); - record["kind"] = Value::String("textRange".to_string()); - record["slide"] = Value::from(index + 1); - record["slideIndex"] = Value::from(index); - record["hostAnchor"] = Value::String(format!("sh/{}", shape.element_id)); - record["hostKind"] = Value::String("textbox".to_string()); - (record, Some(slide_id.clone())) - })); - } - } - PresentationElement::Table(table) => { - for (row_index, row) in table.rows.iter().enumerate() { - for (column_index, cell) in row.iter().enumerate() { - records.extend(cell.rich_text.ranges.iter().map(|range| { - let mut record = text_range_to_proto(&cell.text, range); - record["kind"] = Value::String("textRange".to_string()); - record["slide"] = Value::from(index + 1); - record["slideIndex"] = Value::from(index); - record["hostAnchor"] = Value::String(format!( - "tb/{}#cell/{row_index}/{column_index}", - table.element_id - )); - record["hostKind"] = Value::String("tableCell".to_string()); - (record, Some(slide_id.clone())) - })); - } - } - } - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Chart(_) => {} - } - } - } - } - if include("comment") { - records.extend(document.comment_threads.iter().map(|thread| { - let mut record = comment_thread_to_proto(thread); - record["id"] = Value::String(format!("th/{}", thread.thread_id)); - (record, None) - })); - } - - if let Some(target_id) = args.target_id.as_deref() { - records.retain(|(record, slide_id)| { - legacy_target_matches(target_id, record, slide_id.as_deref()) - }); - if records.is_empty() { - records.push(( - serde_json::json!({ - "kind": "notice", - "noticeType": "targetNotFound", - "target": { "id": target_id }, - "message": format!("No inspect records matched target `{target_id}`."), - }), - None, - )); - } - } - - if let Some(search) = args.search.as_deref() { - let search_lowercase = search.to_ascii_lowercase(); - records.retain(|(record, _)| { - record - .to_string() - .to_ascii_lowercase() - .contains(&search_lowercase) - }); - if records.is_empty() { - records.push(( - serde_json::json!({ - "kind": "notice", - "noticeType": "noMatches", - "search": search, - "message": format!("No inspect records matched search `{search}`."), - }), - None, - )); - } - } - - if let Some(target) = args.target.as_ref() { - if let Some(target_index) = records.iter().position(|(record, _)| { - record.get("id").and_then(Value::as_str) == Some(target.id.as_str()) - }) { - let start = target_index.saturating_sub(target.before_lines.unwrap_or(0)); - let end = (target_index + target.after_lines.unwrap_or(0) + 1).min(records.len()); - records = records.into_iter().skip(start).take(end - start).collect(); - } else { - records = vec![( - serde_json::json!({ - "kind": "notice", - "noticeType": "targetNotFound", - "target": { - "id": target.id, - "beforeLines": target.before_lines, - "afterLines": target.after_lines, - }, - "message": format!("No inspect records matched target `{}`.", target.id), - }), - None, - )]; - } - } - - let mut lines = Vec::new(); - let mut omitted_lines = 0usize; - let mut omitted_chars = 0usize; - for line in records.into_iter().map(|(record, _)| record.to_string()) { - let separator_len = usize::from(!lines.is_empty()); - if let Some(max_chars) = args.max_chars - && lines.iter().map(String::len).sum::() + separator_len + line.len() > max_chars - { - omitted_lines += 1; - omitted_chars += line.len(); - continue; - } - lines.push(line); - } - if omitted_lines > 0 { - lines.push( - serde_json::json!({ - "kind": "notice", - "noticeType": "truncation", - "maxChars": args.max_chars, - "omittedLines": omitted_lines, - "omittedChars": omitted_chars, - "message": format!( - "Truncated inspect output by omitting {omitted_lines} lines. Increase maxChars or narrow the filter." - ), - }) - .to_string(), - ); - } - lines.join("\n") -} - -fn legacy_target_matches(target_id: &str, record: &Value, slide_id: Option<&str>) -> bool { - record.get("id").and_then(Value::as_str) == Some(target_id) || slide_id == Some(target_id) -} - -fn add_text_metadata(record: &mut Value, text: &str) { - record["textPreview"] = Value::String(text.replace('\n', " | ")); - record["textChars"] = Value::from(text.chars().count()); - record["textLines"] = Value::from(text.lines().count()); -} - -fn normalize_element_lookup_id(element_id: &str) -> &str { - element_id - .split_once('/') - .map(|(_, normalized)| normalized) - .unwrap_or(element_id) -} - -fn resolve_anchor( - document: &PresentationDocument, - id: &str, - action: &str, -) -> Result { - if id == format!("pr/{}", document.artifact_id) { - return Ok(serde_json::json!({ - "kind": "deck", - "id": id, - "artifactId": document.artifact_id, - "name": document.name, - "slideCount": document.slides.len(), - "styleIds": document - .named_text_styles() - .iter() - .map(|style| format!("st/{}", style.name)) - .collect::>(), - "activeSlideIndex": document.active_slide_index, - "activeSlideId": document.active_slide_index.and_then(|index| document.slides.get(index)).map(|slide| format!("sl/{}", slide.slide_id)), - })); - } - if let Some(style_name) = id.strip_prefix("st/") { - let named_style = document - .named_text_styles() - .into_iter() - .find(|style| style.name == style_name) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown style id `{id}`"), - })?; - return Ok(named_text_style_to_json(&named_style, "st")); - } - - for (slide_index, slide) in document.slides.iter().enumerate() { - let slide_id = format!("sl/{}", slide.slide_id); - if id == slide_id { - return Ok(serde_json::json!({ - "kind": "slide", - "id": slide_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "isActive": document.active_slide_index == Some(slide_index), - "layoutId": slide.layout_id, - "notesId": (!slide.notes.text.is_empty()).then(|| format!("nt/{}", slide.slide_id)), - "elementIds": slide.elements.iter().map(|element| { - let prefix = match element { - PresentationElement::Text(_) | PresentationElement::Shape(_) => "sh", - PresentationElement::Connector(_) => "cn", - PresentationElement::Image(_) => "im", - PresentationElement::Table(_) => "tb", - PresentationElement::Chart(_) => "ch", - }; - format!("{prefix}/{}", element.element_id()) - }).collect::>(), - })); - } - let notes_id = format!("nt/{}", slide.slide_id); - if id == notes_id { - let mut record = serde_json::json!({ - "kind": "notes", - "id": notes_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "visible": slide.notes.visible, - "text": slide.notes.text, - }); - add_text_metadata(&mut record, &slide.notes.text); - record["richText"] = rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text); - return Ok(record); - } - if let Some(range_id) = id.strip_prefix("tr/") - && let Some(record) = slide - .notes - .rich_text - .ranges - .iter() - .find(|range| range.range_id == range_id) - .map(|range| { - let mut record = text_range_to_proto(&slide.notes.text, range); - record["kind"] = Value::String("textRange".to_string()); - record["id"] = Value::String(id.to_string()); - record["slide"] = Value::from(slide_index + 1); - record["slideIndex"] = Value::from(slide_index); - record["hostAnchor"] = Value::String(notes_id.clone()); - record["hostKind"] = Value::String("notes".to_string()); - record - }) - { - return Ok(record); - } - for element in &slide.elements { - let mut record = match element { - PresentationElement::Text(text) => { - let mut record = serde_json::json!({ - "kind": "textbox", - "id": format!("sh/{}", text.element_id), - "elementId": text.element_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "text": text.text, - "textStyle": text_style_to_proto(&text.style), - "richText": rich_text_to_proto(&text.text, &text.rich_text), - "bbox": [text.frame.left, text.frame.top, text.frame.width, text.frame.height], - "bboxUnit": "points", - }); - add_text_metadata(&mut record, &text.text); - record - } - PresentationElement::Shape(shape) => { - let mut record = serde_json::json!({ - "kind": if shape.text.is_some() { "textbox" } else { "shape" }, - "id": format!("sh/{}", shape.element_id), - "elementId": shape.element_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "geometry": format!("{:?}", shape.geometry), - "text": shape.text, - "textStyle": text_style_to_proto(&shape.text_style), - "richText": shape - .text - .as_ref() - .zip(shape.rich_text.as_ref()) - .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) - .unwrap_or(Value::Null), - "rotation": shape.rotation_degrees, - "flipHorizontal": shape.flip_horizontal, - "flipVertical": shape.flip_vertical, - "bbox": [shape.frame.left, shape.frame.top, shape.frame.width, shape.frame.height], - "bboxUnit": "points", - }); - if let Some(text) = &shape.text { - add_text_metadata(&mut record, text); - } - record - } - PresentationElement::Connector(connector) => serde_json::json!({ - "kind": "connector", - "id": format!("cn/{}", connector.element_id), - "elementId": connector.element_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "connectorType": format!("{:?}", connector.connector_type), - "start": [connector.start.left, connector.start.top], - "end": [connector.end.left, connector.end.top], - "lineStyle": format!("{:?}", connector.line_style), - "label": connector.label, - }), - PresentationElement::Image(image) => serde_json::json!({ - "kind": "image", - "id": format!("im/{}", image.element_id), - "elementId": image.element_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "alt": image.alt_text, - "prompt": image.prompt, - "fit": format!("{:?}", image.fit_mode), - "rotation": image.rotation_degrees, - "flipHorizontal": image.flip_horizontal, - "flipVertical": image.flip_vertical, - "crop": image.crop.map(|(left, top, right, bottom)| serde_json::json!({ - "left": left, - "top": top, - "right": right, - "bottom": bottom, - })), - "isPlaceholder": image.is_placeholder, - "lockAspectRatio": image.lock_aspect_ratio, - "bbox": [image.frame.left, image.frame.top, image.frame.width, image.frame.height], - "bboxUnit": "points", - }), - PresentationElement::Table(table) => serde_json::json!({ - "kind": "table", - "id": format!("tb/{}", table.element_id), - "elementId": table.element_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "rows": table.rows.len(), - "cols": table.rows.iter().map(std::vec::Vec::len).max().unwrap_or(0), - "columnWidths": table.column_widths, - "rowHeights": table.row_heights, - "style": table.style, - "styleOptions": table_style_options_to_proto(&table.style_options), - "borders": table.borders.as_ref().map(table_borders_to_proto), - "rightToLeft": table.right_to_left, - "cellTextStyles": table - .rows - .iter() - .map(|row| row.iter().map(|cell| text_style_to_proto(&cell.text_style)).collect::>()) - .collect::>(), - "rowsData": table - .rows - .iter() - .map(|row| row.iter().map(table_cell_to_proto).collect::>()) - .collect::>(), - "bbox": [table.frame.left, table.frame.top, table.frame.width, table.frame.height], - "bboxUnit": "points", - }), - PresentationElement::Chart(chart) => serde_json::json!({ - "kind": "chart", - "id": format!("ch/{}", chart.element_id), - "elementId": chart.element_id, - "slide": slide_index + 1, - "slideIndex": slide_index, - "chartType": format!("{:?}", chart.chart_type), - "title": chart.title, - "styleIndex": chart.style_index, - "hasLegend": chart.has_legend, - "legend": chart.legend.as_ref().map(chart_legend_to_proto), - "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), - "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), - "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), - "chartFill": chart.chart_fill, - "plotAreaFill": chart.plot_area_fill, - "series": chart - .series - .iter() - .map(|series| serde_json::json!({ - "name": series.name, - "values": series.values, - "categories": series.categories, - "xValues": series.x_values, - "fill": series.fill, - "stroke": series.stroke.as_ref().map(stroke_to_proto), - "marker": series.marker.as_ref().map(chart_marker_to_proto), - "dataLabelOverrides": series - .data_label_overrides - .iter() - .map(chart_data_label_override_to_proto) - .collect::>(), - })) - .collect::>(), - "bbox": [chart.frame.left, chart.frame.top, chart.frame.width, chart.frame.height], - "bboxUnit": "points", - }), - }; - if let Some(hyperlink) = match element { - PresentationElement::Text(text) => text.hyperlink.as_ref(), - PresentationElement::Shape(shape) => shape.hyperlink.as_ref(), - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => None, - } { - record["hyperlink"] = hyperlink.to_json(); - } - if let PresentationElement::Shape(shape) = element - && let Some(stroke) = &shape.stroke - { - record["stroke"] = serde_json::json!({ - "color": stroke.color, - "width": stroke.width, - "style": stroke.style.as_api_str(), - }); - } - if let Some(placeholder) = match element { - PresentationElement::Text(text) => text.placeholder.as_ref(), - PresentationElement::Shape(shape) => shape.placeholder.as_ref(), - PresentationElement::Image(image) => image.placeholder.as_ref(), - PresentationElement::Connector(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => None, - } { - record["placeholder"] = Value::String(placeholder.placeholder_type.clone()); - record["placeholderName"] = Value::String(placeholder.name.clone()); - record["placeholderIndex"] = - placeholder.index.map(Value::from).unwrap_or(Value::Null); - } - if record.get("id").and_then(Value::as_str) == Some(id) { - return Ok(record); - } - if let Some(range_id) = id.strip_prefix("tr/") { - match element { - PresentationElement::Text(text) => { - if let Some(range) = - text.rich_text.ranges.iter().find(|range| range.range_id == range_id) - { - let mut range_record = text_range_to_proto(&text.text, range); - range_record["kind"] = Value::String("textRange".to_string()); - range_record["id"] = Value::String(id.to_string()); - range_record["slide"] = Value::from(slide_index + 1); - range_record["slideIndex"] = Value::from(slide_index); - range_record["hostAnchor"] = - Value::String(format!("sh/{}", text.element_id)); - range_record["hostKind"] = Value::String("textbox".to_string()); - return Ok(range_record); - } - } - PresentationElement::Shape(shape) => { - if let Some((text, rich_text)) = - shape.text.as_ref().zip(shape.rich_text.as_ref()) - && let Some(range) = - rich_text.ranges.iter().find(|range| range.range_id == range_id) - { - let mut range_record = text_range_to_proto(text, range); - range_record["kind"] = Value::String("textRange".to_string()); - range_record["id"] = Value::String(id.to_string()); - range_record["slide"] = Value::from(slide_index + 1); - range_record["slideIndex"] = Value::from(slide_index); - range_record["hostAnchor"] = - Value::String(format!("sh/{}", shape.element_id)); - range_record["hostKind"] = Value::String("textbox".to_string()); - return Ok(range_record); - } - } - PresentationElement::Table(table) => { - for (row_index, row) in table.rows.iter().enumerate() { - for (column_index, cell) in row.iter().enumerate() { - if let Some(range) = cell - .rich_text - .ranges - .iter() - .find(|range| range.range_id == range_id) - { - let mut range_record = text_range_to_proto(&cell.text, range); - range_record["kind"] = Value::String("textRange".to_string()); - range_record["id"] = Value::String(id.to_string()); - range_record["slide"] = Value::from(slide_index + 1); - range_record["slideIndex"] = Value::from(slide_index); - range_record["hostAnchor"] = Value::String(format!( - "tb/{}#cell/{row_index}/{column_index}", - table.element_id - )); - range_record["hostKind"] = - Value::String("tableCell".to_string()); - return Ok(range_record); - } - } - } - } - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Chart(_) => {} - } - } - } - } - - if let Some(thread_id) = id.strip_prefix("th/") - && let Some(thread) = document - .comment_threads - .iter() - .find(|thread| thread.thread_id == thread_id) - { - let mut record = comment_thread_to_proto(thread); - record["id"] = Value::String(id.to_string()); - return Ok(record); - } - - for layout in &document.layouts { - let layout_id = format!("ly/{}", layout.layout_id); - if id == layout_id { - return Ok(serde_json::json!({ - "kind": "layout", - "id": layout_id, - "layoutId": layout.layout_id, - "name": layout.name, - "type": match layout.kind { - LayoutKind::Layout => "layout", - LayoutKind::Master => "master", - }, - "parentLayoutId": layout.parent_layout_id, - "placeholders": layout_placeholder_list(document, &layout.layout_id, action)?, - })); - } - } - - Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown resolve id `{id}`"), - }) -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs b/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs deleted file mode 100644 index 8539b62c76..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs +++ /dev/null @@ -1,3203 +0,0 @@ -#[derive(Debug, Default)] -pub struct PresentationArtifactManager { - documents: HashMap, - undo_stack: Vec, - redo_stack: Vec, -} - -#[derive(Debug, Clone)] -struct HistoryEntry { - artifact_id: String, - action: String, - before: Option, - after: Option, -} - -impl PresentationArtifactManager { - pub fn execute_requests( - &mut self, - request: PresentationArtifactExecutionRequest, - cwd: &Path, - ) -> Result { - let PresentationArtifactExecutionRequest { - artifact_id, - requests, - } = request; - let request_count = requests.len(); - let mut current_artifact_id = artifact_id; - let mut executed_actions = Vec::with_capacity(request_count); - let mut exported_paths = Vec::new(); - let mut last_response = None; - - for mut request in requests { - if request.artifact_id.is_none() { - request.artifact_id = current_artifact_id.clone(); - } - let response = self.execute(request, cwd)?; - current_artifact_id = Some(response.artifact_id.clone()); - exported_paths.extend(response.exported_paths.iter().cloned()); - executed_actions.push(response.action.clone()); - last_response = Some(response); - } - - let mut response = last_response.ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: "presentation_artifact".to_string(), - message: "request sequence must contain at least one action".to_string(), - })?; - if request_count > 1 { - let final_summary = response.summary.clone(); - response.action = "batch".to_string(); - response.summary = - format!("Executed {request_count} actions sequentially. {final_summary}"); - response.executed_actions = Some(executed_actions); - response.exported_paths = exported_paths; - } - Ok(response) - } - - pub fn execute( - &mut self, - request: PresentationArtifactRequest, - cwd: &Path, - ) -> Result { - match request.action.as_str() { - "undo" => return self.undo(request), - "redo" => return self.redo(request), - "record_patch" => return self.record_patch(request), - "apply_patch" => return self.apply_patch(request, cwd), - _ => {} - } - - let action = request.action.clone(); - let before = if tracks_history(&action) { - request - .artifact_id - .as_ref() - .and_then(|artifact_id| self.documents.get(artifact_id).cloned()) - } else { - None - }; - let response = self.execute_action(request, cwd)?; - if tracks_history(&action) { - let after = self.documents.get(&response.artifact_id).cloned(); - self.push_history_entry(HistoryEntry { - artifact_id: response.artifact_id.clone(), - action, - before, - after, - }); - } - Ok(response) - } - - fn execute_action( - &mut self, - request: PresentationArtifactRequest, - cwd: &Path, - ) -> Result { - match request.action.as_str() { - "create" => self.create(request), - "import_pptx" => self.import_pptx(request, cwd), - "export_pptx" => self.export_pptx(request, cwd), - "export_preview" => self.export_preview(request, cwd), - "get_summary" => self.get_summary(request), - "list_slides" => self.list_slides(request), - "list_layouts" => self.list_layouts(request), - "list_layout_placeholders" => self.list_layout_placeholders(request), - "list_slide_placeholders" => self.list_slide_placeholders(request), - "inspect" => self.inspect(request), - "resolve" => self.resolve(request), - "to_proto" => self.proto_snapshot(request), - "add_slide" => self.add_slide(request), - "insert_slide" => self.insert_slide(request), - "duplicate_slide" => self.duplicate_slide(request), - "move_slide" => self.move_slide(request), - "delete_slide" => self.delete_slide(request), - "create_layout" => self.create_layout(request), - "add_layout_placeholder" => self.add_layout_placeholder(request), - "set_slide_layout" => self.set_slide_layout(request), - "update_placeholder_text" => self.update_placeholder_text(request), - "set_theme" => self.set_theme(request), - "add_style" => self.add_style(request), - "get_style" => self.get_style(request), - "describe_styles" => self.describe_styles(request), - "set_notes" => self.set_notes(request), - "set_notes_rich_text" => self.set_notes_rich_text(request), - "append_notes" => self.append_notes(request), - "clear_notes" => self.clear_notes(request), - "set_notes_visibility" => self.set_notes_visibility(request), - "set_active_slide" => self.set_active_slide(request), - "set_slide_background" => self.set_slide_background(request), - "add_text_shape" => self.add_text_shape(request), - "add_shape" => self.add_shape(request), - "add_connector" => self.add_connector(request), - "add_image" => self.add_image(request, cwd), - "replace_image" => self.replace_image(request, cwd), - "add_table" => self.add_table(request), - "update_table_style" => self.update_table_style(request), - "style_table_block" => self.style_table_block(request), - "update_table_cell" => self.update_table_cell(request), - "merge_table_cells" => self.merge_table_cells(request), - "add_chart" => self.add_chart(request), - "update_chart" => self.update_chart(request), - "add_chart_series" => self.add_chart_series(request), - "update_text" => self.update_text(request), - "set_rich_text" => self.set_rich_text(request), - "format_text_range" => self.format_text_range(request), - "replace_text" => self.replace_text(request), - "insert_text_after" => self.insert_text_after(request), - "set_hyperlink" => self.set_hyperlink(request), - "set_comment_author" => self.set_comment_author(request), - "add_comment_thread" => self.add_comment_thread(request), - "add_comment_reply" => self.add_comment_reply(request), - "toggle_comment_reaction" => self.toggle_comment_reaction(request), - "resolve_comment_thread" => self.resolve_comment_thread(request), - "reopen_comment_thread" => self.reopen_comment_thread(request), - "update_shape_style" => self.update_shape_style(request), - "bring_to_front" => self.bring_to_front(request), - "send_to_back" => self.send_to_back(request), - "delete_element" => self.delete_element(request), - "delete_artifact" => self.delete_artifact(request), - other => Err(PresentationArtifactError::UnknownAction(other.to_string())), - } - } - - fn push_history_entry(&mut self, entry: HistoryEntry) { - self.undo_stack.push(entry); - self.redo_stack.clear(); - } - - fn create( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: CreateArgs = parse_args(&request.action, &request.args)?; - let mut document = PresentationDocument::new(args.name); - if let Some(slide_size) = args.slide_size { - document.slide_size = parse_slide_size(&slide_size, &request.action)?; - } - if let Some(theme) = args.theme { - document.theme = normalize_theme(theme, &request.action)?; - } - let artifact_id = document.artifact_id.clone(); - let summary = format!( - "Created presentation artifact `{artifact_id}` with {} slides", - document.slides.len() - ); - let snapshot = snapshot_for_document(&document); - let mut response = - PresentationArtifactResponse::new(artifact_id, request.action, summary, snapshot); - response.theme = Some(document.theme_snapshot()); - self.documents - .insert(response.artifact_id.clone(), document); - Ok(response) - } - - fn import_pptx( - &mut self, - request: PresentationArtifactRequest, - cwd: &Path, - ) -> Result { - let args: ImportPptxArgs = parse_args(&request.action, &request.args)?; - let path = resolve_path(cwd, &args.path); - let document = if let Some(document) = import_codex_metadata_document(&path) - .map_err(|message| PresentationArtifactError::ImportFailed { - path: path.clone(), - message, - })? - { - document - } else { - let imported = Presentation::from_path(&path).map_err(|error| { - PresentationArtifactError::ImportFailed { - path: path.clone(), - message: error.to_string(), - } - })?; - let mut document = PresentationDocument::from_ppt_rs(imported); - import_pptx_images(&path, &mut document, &request.action)?; - document - }; - let artifact_id = document.artifact_id.clone(); - let slide_count = document.slides.len(); - let snapshot = snapshot_for_document(&document); - self.documents.insert(artifact_id.clone(), document); - let summary = format!( - "Imported `{}` as artifact `{artifact_id}` with {slide_count} slides", - path.display() - ); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - summary, - snapshot, - )) - } - - fn export_pptx( - &mut self, - request: PresentationArtifactRequest, - cwd: &Path, - ) -> Result { - let args: ExportPptxArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let path = resolve_path(cwd, &args.path); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: path.clone(), - message: error.to_string(), - } - })?; - } - - let bytes = build_pptx_bytes(document, &request.action).map_err(|message| { - PresentationArtifactError::ExportFailed { - path: path.clone(), - message, - } - })?; - std::fs::write(&path, bytes).map_err(|error| PresentationArtifactError::ExportFailed { - path: path.clone(), - message: error.to_string(), - })?; - - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Exported presentation to `{}`", path.display()), - snapshot_for_document(document), - ); - response.exported_paths.push(path); - Ok(response) - } - - fn export_preview( - &mut self, - request: PresentationArtifactRequest, - cwd: &Path, - ) -> Result { - let args: ExportPreviewArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let output_path = resolve_path(cwd, &args.path); - let preview_format = - parse_preview_output_format(args.format.as_deref(), &output_path, &request.action)?; - let scale = normalize_preview_scale(args.scale, &request.action)?; - let quality = normalize_preview_quality(args.quality, &request.action)?; - if let Some(parent) = output_path.parent() { - std::fs::create_dir_all(parent).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: output_path.clone(), - message: error.to_string(), - } - })?; - } - let temp_dir = - std::env::temp_dir().join(format!("presentation_preview_{}", Uuid::new_v4().simple())); - std::fs::create_dir_all(&temp_dir).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: output_path.clone(), - message: error.to_string(), - } - })?; - let preview_document = if let Some(slide_index) = args.slide_index { - let slide = document - .slides - .get(slide_index as usize) - .cloned() - .ok_or_else(|| { - index_out_of_range(&request.action, slide_index as usize, document.slides.len()) - })?; - let slide_id = slide.slide_id.clone(); - PresentationDocument { - artifact_id: document.artifact_id.clone(), - name: document.name.clone(), - slide_size: document.slide_size, - theme: document.theme.clone(), - custom_text_styles: document.custom_text_styles.clone(), - layouts: Vec::new(), - slides: vec![slide], - active_slide_index: Some(0), - comment_self: document.comment_self.clone(), - comment_threads: document - .comment_threads - .iter() - .filter(|thread| match &thread.target { - CommentTarget::Slide { slide_id: target_slide_id } - | CommentTarget::Element { slide_id: target_slide_id, .. } - | CommentTarget::TextRange { slide_id: target_slide_id, .. } => { - target_slide_id == &slide_id - } - }) - .cloned() - .collect(), - next_slide_seq: 1, - next_element_seq: 1, - next_layout_seq: 1, - next_text_range_seq: document.next_text_range_seq, - next_comment_thread_seq: document.next_comment_thread_seq, - next_comment_message_seq: document.next_comment_message_seq, - } - } else { - document.clone() - }; - write_preview_images(&preview_document, &temp_dir, &request.action)?; - let mut exported_paths = collect_pngs(&temp_dir)?; - if args.slide_index.is_some() { - let rendered = - exported_paths - .pop() - .ok_or_else(|| PresentationArtifactError::ExportFailed { - path: output_path.clone(), - message: "preview renderer produced no images".to_string(), - })?; - write_preview_image( - &rendered, - &output_path, - preview_format, - scale, - quality, - &request.action, - )?; - exported_paths = vec![output_path]; - } else { - std::fs::create_dir_all(&output_path).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: output_path.clone(), - message: error.to_string(), - } - })?; - let mut relocated = Vec::new(); - for rendered in exported_paths { - let filename = rendered.file_name().ok_or_else(|| { - PresentationArtifactError::ExportFailed { - path: output_path.clone(), - message: "rendered preview had no filename".to_string(), - } - })?; - let stem = Path::new(filename) - .file_stem() - .and_then(|value| value.to_str()) - .unwrap_or("preview"); - let target = output_path.join(format!("{stem}.{}", preview_format.extension())); - write_preview_image( - &rendered, - &target, - preview_format, - scale, - quality, - &request.action, - )?; - relocated.push(target); - } - exported_paths = relocated; - } - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - "Exported slide preview".to_string(), - snapshot_for_document(document), - ); - response.exported_paths = exported_paths; - Ok(response) - } - - fn get_summary( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Presentation `{}` has {} slides, {} elements, {} layouts, and active slide {}", - document.name.as_deref().unwrap_or("Untitled"), - document.slides.len(), - document.total_element_count(), - document.layouts.len(), - document - .active_slide_index - .map(|index| index.to_string()) - .unwrap_or_else(|| "none".to_string()) - ), - snapshot_for_document(document), - ); - response.slide_list = Some(slide_list(document)); - response.layout_list = Some(layout_list(document)); - response.theme = Some(document.theme_snapshot()); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn list_slides( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Listed {} slides", document.slides.len()), - snapshot_for_document(document), - ); - response.slide_list = Some(slide_list(document)); - response.theme = Some(document.theme_snapshot()); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn list_layouts( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Listed {} layouts", document.layouts.len()), - snapshot_for_document(document), - ); - response.layout_list = Some(layout_list(document)); - response.theme = Some(document.theme_snapshot()); - Ok(response) - } - - fn list_layout_placeholders( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: LayoutIdArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let placeholders = layout_placeholder_list(document, &args.layout_id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Listed {} placeholders for layout `{}`", - placeholders.len(), - args.layout_id - ), - snapshot_for_document(document), - ); - response.placeholder_list = Some(placeholders); - response.layout_list = Some(layout_list(document)); - Ok(response) - } - - fn list_slide_placeholders( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SlideIndexArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let slide_index = args.slide_index as usize; - let slide = document.slides.get(slide_index).ok_or_else(|| { - index_out_of_range(&request.action, slide_index, document.slides.len()) - })?; - let placeholders = slide_placeholder_list(slide, slide_index); - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Listed {} placeholders for slide {}", - placeholders.len(), - args.slide_index - ), - snapshot_for_document(document), - ); - response.placeholder_list = Some(placeholders); - response.slide_list = Some(slide_list(document)); - Ok(response) - } - - fn inspect( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: InspectArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let inspect_ndjson = inspect_document(document, &args); - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - "Generated inspection snapshot".to_string(), - snapshot_for_document(document), - ); - response.inspect_ndjson = Some(inspect_ndjson); - response.theme = Some(document.theme_snapshot()); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn resolve( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: ResolveArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let resolved_record = resolve_anchor(document, &args.id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Resolved `{}`", args.id), - snapshot_for_document(document), - ); - response.resolved_record = Some(resolved_record); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn proto_snapshot( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - "Generated proto snapshot".to_string(), - snapshot_for_document(document), - ); - response.proto_json = Some(document_to_proto(document, "to_proto")?); - response.theme = Some(document.theme_snapshot()); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn record_patch( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: RecordPatchArgs = parse_args(&request.action, &request.args)?; - let patch = self.normalize_patch( - request.artifact_id.as_deref(), - args.operations, - &request.action, - )?; - let document = self.get_document(&patch.artifact_id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - patch.artifact_id.clone(), - request.action, - format!("Recorded patch with {} operations", patch.operations.len()), - snapshot_for_document(document), - ); - response.patch = Some(serde_json::to_value(&patch).map_err(|error| { - PresentationArtifactError::InvalidArgs { - action: "record_patch".to_string(), - message: format!("failed to serialize patch: {error}"), - } - })?); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn apply_patch( - &mut self, - request: PresentationArtifactRequest, - _cwd: &Path, - ) -> Result { - let args: ApplyPatchArgs = parse_args(&request.action, &request.args)?; - let patch = if let Some(patch) = args.patch { - self.normalize_serialized_patch(request.artifact_id.as_deref(), patch, &request.action)? - } else { - let operations = - args.operations - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: "provide either `patch` or `operations`".to_string(), - })?; - self.normalize_patch(request.artifact_id.as_deref(), operations, &request.action)? - }; - let before = self.documents.get(&patch.artifact_id).cloned(); - let Some(before_document) = before else { - return Err(PresentationArtifactError::UnknownArtifactId { - action: request.action, - artifact_id: patch.artifact_id, - }); - }; - for operation in &patch.operations { - let nested_request = PresentationArtifactRequest { - artifact_id: Some(patch.artifact_id.clone()), - action: operation.action.clone(), - args: operation.args.clone(), - }; - if let Err(error) = self.execute_action(nested_request, Path::new(".")) { - self.documents - .insert(patch.artifact_id.clone(), before_document); - return Err(error); - } - } - let document = self - .get_document(&patch.artifact_id, &request.action)? - .clone(); - self.push_history_entry(HistoryEntry { - artifact_id: patch.artifact_id.clone(), - action: request.action.clone(), - before: Some(before_document), - after: Some(document.clone()), - }); - let mut response = PresentationArtifactResponse::new( - patch.artifact_id.clone(), - request.action, - format!("Applied patch with {} operations", patch.operations.len()), - snapshot_for_document(&document), - ); - response.patch = Some(serde_json::to_value(&patch).map_err(|error| { - PresentationArtifactError::InvalidArgs { - action: "apply_patch".to_string(), - message: format!("failed to serialize patch: {error}"), - } - })?); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn undo( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let position = self - .undo_stack - .iter() - .rposition(|entry| { - request - .artifact_id - .as_deref() - .is_none_or(|artifact_id| artifact_id == entry.artifact_id) - }) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: request.action.clone(), - message: "nothing to undo".to_string(), - })?; - let entry = self.undo_stack.remove(position); - match &entry.before { - Some(document) => { - self.documents - .insert(entry.artifact_id.clone(), document.clone()); - } - None => { - self.documents.remove(&entry.artifact_id); - } - } - self.redo_stack.push(entry.clone()); - Ok(response_for_document_state( - entry.artifact_id, - request.action, - format!("Undid `{}`", entry.action), - entry.before.as_ref(), - )) - } - - fn redo( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let position = self - .redo_stack - .iter() - .rposition(|entry| { - request - .artifact_id - .as_deref() - .is_none_or(|artifact_id| artifact_id == entry.artifact_id) - }) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: request.action.clone(), - message: "nothing to redo".to_string(), - })?; - let entry = self.redo_stack.remove(position); - match &entry.after { - Some(document) => { - self.documents - .insert(entry.artifact_id.clone(), document.clone()); - } - None => { - self.documents.remove(&entry.artifact_id); - } - } - self.undo_stack.push(entry.clone()); - Ok(response_for_document_state( - entry.artifact_id, - request.action, - format!("Redid `{}`", entry.action), - entry.after.as_ref(), - )) - } - - fn create_layout( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: CreateLayoutArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let layout_id = document.next_layout_id(); - let kind = match args.kind.as_deref() { - Some("master") => LayoutKind::Master, - Some("layout") | None => LayoutKind::Layout, - Some(other) => { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!("unsupported layout kind `{other}`"), - }); - } - }; - let parent_layout_id = args - .parent_layout_id - .map(|parent_layout_ref| { - document - .get_layout(&parent_layout_ref, &request.action) - .map(|layout| layout.layout_id.clone()) - }) - .transpose()?; - document.layouts.push(LayoutDocument { - layout_id: layout_id.clone(), - name: args.name, - kind, - parent_layout_id, - placeholders: Vec::new(), - }); - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Created layout `{layout_id}`"), - snapshot_for_document(document), - ); - response.layout_list = Some(layout_list(document)); - Ok(response) - } - - fn add_layout_placeholder( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddLayoutPlaceholderArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let geometry = args - .geometry - .as_deref() - .map(|value| parse_shape_geometry(value, &request.action)) - .transpose()? - .unwrap_or(ShapeGeometry::Rectangle); - let frame = args.position.unwrap_or(PositionArgs { - left: 48, - top: 72, - width: 624, - height: 96, - rotation: None, - flip_horizontal: None, - flip_vertical: None, - }); - let layout_id = document - .get_layout(&args.layout_id, &request.action)? - .layout_id - .clone(); - let layout = document - .layouts - .iter_mut() - .find(|layout| layout.layout_id == layout_id) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: request.action.clone(), - message: format!("unknown layout id `{}`", args.layout_id), - })?; - layout.placeholders.push(PlaceholderDefinition { - name: args.name, - placeholder_type: args.placeholder_type, - index: args.index, - text: args.text, - geometry, - frame: frame.into(), - }); - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Added placeholder to layout `{}`", layout.layout_id), - snapshot_for_document(document), - ); - response.layout_list = Some(layout_list(document)); - Ok(response) - } - - fn set_slide_layout( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SetSlideLayoutArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let layout = document - .get_layout(&args.layout_id, &request.action)? - .clone(); - let placeholders = - resolved_layout_placeholders(document, &layout.layout_id, &request.action)? - .into_iter() - .map(|resolved| resolved.definition) - .collect::>(); - let mut placeholder_elements = Vec::new(); - for placeholder in placeholders { - placeholder_elements.push(materialize_placeholder_element( - document.next_element_id(), - placeholder, - placeholder_elements.len(), - )); - } - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide.elements.retain(|element| match element { - PresentationElement::Text(text) => text.placeholder.is_none(), - PresentationElement::Shape(shape) => shape.placeholder.is_none(), - PresentationElement::Image(image) => image.placeholder.is_none(), - _ => true, - }); - slide.layout_id = Some(layout.layout_id.clone()); - slide.elements.extend(placeholder_elements); - resequence_z_order(slide); - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Applied layout `{}` to slide {}", - layout.layout_id, args.slide_index - ), - snapshot_for_document(document), - ); - response.slide_list = Some(slide_list(document)); - response.layout_list = Some(layout_list(document)); - Ok(response) - } - - fn update_placeholder_text( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: UpdatePlaceholderTextArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - let target_name = args.name.to_ascii_lowercase(); - let element = slide - .elements - .iter_mut() - .find(|element| match element { - PresentationElement::Text(text) => text - .placeholder - .as_ref() - .map(|placeholder| placeholder.name.eq_ignore_ascii_case(&target_name)) - .unwrap_or(false), - PresentationElement::Shape(shape) => shape - .placeholder - .as_ref() - .map(|placeholder| placeholder.name.eq_ignore_ascii_case(&target_name)) - .unwrap_or(false), - _ => false, - }) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: request.action.clone(), - message: format!( - "placeholder `{}` was not found on slide {}", - args.name, args.slide_index - ), - })?; - match element { - PresentationElement::Text(text) => text.text = args.text, - PresentationElement::Shape(shape) => shape.text = Some(args.text), - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => {} - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Updated placeholder `{}` on slide {}", - args.name, args.slide_index - ), - snapshot_for_document(document), - )) - } - - fn set_theme( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: ThemeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - document.theme = normalize_theme(args, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - "Updated theme".to_string(), - snapshot_for_document(document), - ); - response.theme = Some(document.theme_snapshot()); - Ok(response) - } - - fn add_style( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let style_name = normalize_style_name(&args.name, &request.action)?; - let mut style = - normalize_text_style_with_document(document, &args.styling, &request.action)?; - style.style_name = Some(style_name.clone()); - let style_record = NamedTextStyle { - name: style_name.clone(), - style: style.clone(), - built_in: false, - }; - document - .custom_text_styles - .insert(style_name.clone(), style); - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Added text style `{style_name}`"), - snapshot_for_document(document), - ); - response.resolved_record = Some(named_text_style_to_json(&style_record, "st")); - Ok(response) - } - - fn get_style( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: StyleNameArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let normalized_style_name = normalize_style_name(&args.name, &request.action)?; - let named_style = document - .named_text_styles() - .into_iter() - .find(|style| style.name == normalized_style_name) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: request.action.clone(), - message: format!("unknown text style `{}`", args.name), - })?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Resolved text style `{}`", args.name), - snapshot_for_document(document), - ); - response.resolved_record = Some(named_text_style_to_json(&named_style, "st")); - Ok(response) - } - - fn describe_styles( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document(&artifact_id, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - "Described text styles".to_string(), - snapshot_for_document(document), - ); - response.resolved_record = Some(serde_json::json!({ - "kind": "styleList", - "styles": document - .named_text_styles() - .iter() - .map(|style| named_text_style_to_json(style, "st")) - .collect::>(), - })); - Ok(response) - } - - fn set_notes( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: NotesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide.notes.text = args.text.unwrap_or_default(); - slide.notes.rich_text = RichTextState::default(); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated notes for slide {}", args.slide_index), - snapshot_for_document(document), - )) - } - - fn set_notes_rich_text( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SetRichTextArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: "`slide_index` is required for notes rich text".to_string(), - })?; - let (text, mut rich_text) = - normalize_rich_text_input(document, args.text, &request.action)?; - rich_text.layout = normalize_text_layout(&args.text_layout, &request.action)?; - let slide = document.get_slide_mut(slide_index, &request.action)?; - slide.notes.text = text; - slide.notes.rich_text = rich_text; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated rich notes for slide {slide_index}"), - snapshot_for_document(document), - )) - } - - fn append_notes( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: NotesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - let text = args.text.unwrap_or_default(); - if slide.notes.text.is_empty() { - slide.notes.text = text; - } else { - slide.notes.text = format!("{}\n{text}", slide.notes.text); - } - slide.notes.rich_text = RichTextState::default(); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Appended notes for slide {}", args.slide_index), - snapshot_for_document(document), - )) - } - - fn clear_notes( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: NotesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide.notes.text.clear(); - slide.notes.rich_text = RichTextState::default(); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Cleared notes for slide {}", args.slide_index), - snapshot_for_document(document), - )) - } - - fn set_notes_visibility( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: NotesVisibilityArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide.notes.visible = args.visible; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated notes visibility for slide {}", args.slide_index), - snapshot_for_document(document), - )) - } - - fn set_active_slide( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SetActiveSlideArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - document.set_active_slide_index(args.slide_index as usize, &request.action)?; - let mut response = PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Set active slide to {}", args.slide_index), - snapshot_for_document(document), - ); - response.slide_list = Some(slide_list(document)); - response.active_slide_index = document.active_slide_index; - Ok(response) - } - - fn add_slide( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddSlideArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let mut slide = document.new_slide(args.notes, args.background_fill, &request.action)?; - if let Some(layout_id) = args.layout { - apply_layout_to_slide(document, &mut slide, &layout_id, &request.action)?; - } - let index = document.append_slide(slide); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Added slide at index {index}"), - snapshot_for_document(document), - )) - } - - fn insert_slide( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: InsertSlideArgs = parse_args(&request.action, &request.args)?; - if args.index.is_some() && args.after_slide_index.is_some() { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: "provide at most one of `index` or `after_slide_index`".to_string(), - }); - } - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let index = if let Some(index) = args.index { - to_index(index)? - } else if let Some(after_slide_index) = args.after_slide_index { - after_slide_index as usize + 1 - } else { - document - .active_slide_index - .map(|active_slide_index| active_slide_index + 1) - .unwrap_or(document.slides.len()) - }; - if index > document.slides.len() { - return Err(index_out_of_range( - &request.action, - index, - document.slides.len(), - )); - } - let mut slide = document.new_slide(args.notes, args.background_fill, &request.action)?; - if let Some(layout_id) = args.layout { - apply_layout_to_slide(document, &mut slide, &layout_id, &request.action)?; - } - document.adjust_active_slide_for_insert(index); - document.slides.insert(index, slide); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Inserted slide at index {index}"), - snapshot_for_document(document), - )) - } - - fn duplicate_slide( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SlideIndexArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let source = document - .slides - .get(args.slide_index as usize) - .cloned() - .ok_or_else(|| { - index_out_of_range( - &request.action, - args.slide_index as usize, - document.slides.len(), - ) - })?; - let duplicated = document.clone_slide(source); - let insert_at = args.slide_index as usize + 1; - document.adjust_active_slide_for_insert(insert_at); - document.slides.insert(insert_at, duplicated); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Duplicated slide {} to index {insert_at}", args.slide_index), - snapshot_for_document(document), - )) - } - - fn move_slide( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: MoveSlideArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let from = args.from_index as usize; - let to = args.to_index as usize; - if from >= document.slides.len() { - return Err(index_out_of_range( - &request.action, - from, - document.slides.len(), - )); - } - if to >= document.slides.len() { - return Err(index_out_of_range( - &request.action, - to, - document.slides.len(), - )); - } - let slide = document.slides.remove(from); - document.slides.insert(to, slide); - document.adjust_active_slide_for_move(from, to); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Moved slide from index {from} to {to}"), - snapshot_for_document(document), - )) - } - - fn delete_slide( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SlideIndexArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let index = args.slide_index as usize; - if index >= document.slides.len() { - return Err(index_out_of_range( - &request.action, - index, - document.slides.len(), - )); - } - document.slides.remove(index); - document.adjust_active_slide_for_delete(index); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Deleted slide at index {index}"), - snapshot_for_document(document), - )) - } - - fn set_slide_background( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SetSlideBackgroundArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let fill = normalize_color_with_document(document, &args.fill, &request.action, "fill")?; - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide.background_fill = Some(fill); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated background for slide {}", args.slide_index), - snapshot_for_document(document), - )) - } - - fn add_text_shape( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddTextShapeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; - let fill = args - .styling - .fill - .as_deref() - .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) - .transpose()?; - let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; - let element_id = document.next_element_id(); - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide.elements.push(PresentationElement::Text(TextElement { - element_id: element_id.clone(), - text: args.text, - frame: args.position.into(), - fill, - style, - hyperlink: None, - rich_text: RichTextState { - ranges: Vec::new(), - layout: text_layout, - }, - placeholder: None, - z_order: slide.elements.len(), - })); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Added text element `{element_id}` to slide {}", - args.slide_index - ), - snapshot_for_document(document), - )) - } - - fn add_shape( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddShapeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let text_style = - normalize_text_style_with_document(document, &args.text_style, &request.action)?; - let fill = args - .fill - .as_deref() - .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) - .transpose()?; - let stroke = parse_stroke(document, args.stroke, &request.action)?; - let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; - let rich_text = args.text.as_ref().map(|_| RichTextState { - ranges: Vec::new(), - layout: text_layout, - }); - let element_id = document.next_element_id(); - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide - .elements - .push(PresentationElement::Shape(ShapeElement { - element_id: element_id.clone(), - geometry: parse_shape_geometry(&args.geometry, &request.action)?, - frame: args.position.clone().into(), - fill, - stroke, - text: args.text, - text_style, - hyperlink: None, - rich_text, - placeholder: None, - rotation_degrees: args.rotation.or(args.position.rotation), - flip_horizontal: args - .flip_horizontal - .or(args.position.flip_horizontal) - .unwrap_or(false), - flip_vertical: args - .flip_vertical - .or(args.position.flip_vertical) - .unwrap_or(false), - z_order: slide.elements.len(), - })); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Added shape element `{element_id}` to slide {}", - args.slide_index - ), - snapshot_for_document(document), - )) - } - - fn add_connector( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddConnectorArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let element_id = document.next_element_id(); - let line = parse_connector_line(document, args.line, &request.action)?; - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide - .elements - .push(PresentationElement::Connector(ConnectorElement { - element_id: element_id.clone(), - connector_type: parse_connector_kind(&args.connector_type, &request.action)?, - start: args.start, - end: args.end, - line: StrokeStyle { - color: line.color, - width: line.width, - style: LineStyle::Solid, - }, - line_style: line.style, - start_arrow: args - .start_arrow - .as_deref() - .map(|value| parse_connector_arrow(value, &request.action)) - .transpose()? - .unwrap_or(ConnectorArrowKind::None), - end_arrow: args - .end_arrow - .as_deref() - .map(|value| parse_connector_arrow(value, &request.action)) - .transpose()? - .unwrap_or(ConnectorArrowKind::None), - arrow_size: args - .arrow_size - .as_deref() - .map(|value| parse_connector_arrow_size(value, &request.action)) - .transpose()? - .unwrap_or(ConnectorArrowScale::Medium), - label: args.label, - z_order: slide.elements.len(), - })); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Added connector element `{element_id}` to slide {}", - args.slide_index - ), - snapshot_for_document(document), - )) - } - - fn add_image( - &mut self, - request: PresentationArtifactRequest, - cwd: &Path, - ) -> Result { - let args: AddImageArgs = parse_args(&request.action, &request.args)?; - let image_source = args.image_source()?; - let is_placeholder = matches!(image_source, ImageInputSource::Placeholder); - let image_payload = match image_source { - ImageInputSource::Path(path) => Some(load_image_payload_from_path( - &resolve_path(cwd, &path), - &request.action, - )?), - ImageInputSource::DataUrl(data_url) => Some(load_image_payload_from_data_url( - &data_url, - &request.action, - )?), - ImageInputSource::Blob(blob) => { - Some(load_image_payload_from_blob(&blob, &request.action)?) - } - ImageInputSource::Uri(uri) => Some(load_image_payload_from_uri(&uri, &request.action)?), - ImageInputSource::Placeholder => None, - }; - let fit_mode = args.fit.unwrap_or(ImageFitMode::Stretch); - let lock_aspect_ratio = args - .lock_aspect_ratio - .unwrap_or(fit_mode != ImageFitMode::Stretch); - let crop = args - .crop - .map(|crop| normalize_image_crop(crop, &request.action)) - .transpose()?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let element_id = document.next_element_id(); - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide - .elements - .push(PresentationElement::Image(ImageElement { - element_id: element_id.clone(), - frame: args.position.clone().into(), - payload: image_payload, - fit_mode, - crop, - rotation_degrees: args.rotation.or(args.position.rotation), - flip_horizontal: args - .flip_horizontal - .or(args.position.flip_horizontal) - .unwrap_or(false), - flip_vertical: args - .flip_vertical - .or(args.position.flip_vertical) - .unwrap_or(false), - lock_aspect_ratio, - alt_text: args.alt, - prompt: args.prompt, - is_placeholder, - placeholder: None, - z_order: slide.elements.len(), - })); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Added image element `{element_id}` to slide {}", - args.slide_index - ), - snapshot_for_document(document), - )) - } - - fn replace_image( - &mut self, - request: PresentationArtifactRequest, - cwd: &Path, - ) -> Result { - let args: ReplaceImageArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let image_source = match ( - &args.path, - &args.data_url, - &args.blob, - &args.uri, - &args.prompt, - ) { - (Some(path), None, None, None, None) => ImageInputSource::Path(path.clone()), - (None, Some(data_url), None, None, None) => ImageInputSource::DataUrl(data_url.clone()), - (None, None, Some(blob), None, None) => ImageInputSource::Blob(blob.clone()), - (None, None, None, Some(uri), None) => ImageInputSource::Uri(uri.clone()), - (None, None, None, None, Some(_)) => ImageInputSource::Placeholder, - _ => { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: - "provide exactly one of `path`, `data_url`, `blob`, or `uri`, or provide `prompt` for a placeholder image" - .to_string(), - }); - } - }; - let is_placeholder = matches!(image_source, ImageInputSource::Placeholder); - let image_payload = match image_source { - ImageInputSource::Path(path) => Some(load_image_payload_from_path( - &resolve_path(cwd, &path), - "replace_image", - )?), - ImageInputSource::DataUrl(data_url) => Some(load_image_payload_from_data_url( - &data_url, - "replace_image", - )?), - ImageInputSource::Blob(blob) => { - Some(load_image_payload_from_blob(&blob, "replace_image")?) - } - ImageInputSource::Uri(uri) => Some(load_image_payload_from_uri(&uri, "replace_image")?), - ImageInputSource::Placeholder => None, - }; - let fit_mode = args.fit.unwrap_or(ImageFitMode::Stretch); - let lock_aspect_ratio = args - .lock_aspect_ratio - .unwrap_or(fit_mode != ImageFitMode::Stretch); - let crop = args - .crop - .map(|crop| normalize_image_crop(crop, &request.action)) - .transpose()?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - let PresentationElement::Image(image) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{}` is not an image", args.element_id), - }); - }; - image.payload = image_payload; - image.fit_mode = fit_mode; - image.crop = crop; - if let Some(rotation) = args.rotation { - image.rotation_degrees = Some(rotation); - } - if let Some(flip_horizontal) = args.flip_horizontal { - image.flip_horizontal = flip_horizontal; - } - if let Some(flip_vertical) = args.flip_vertical { - image.flip_vertical = flip_vertical; - } - image.lock_aspect_ratio = lock_aspect_ratio; - image.alt_text = args.alt; - image.prompt = args.prompt; - image.is_placeholder = is_placeholder; - Ok(PresentationArtifactResponse::new( - artifact_id, - "replace_image".to_string(), - format!("Replaced image `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn add_table( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddTableArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let rows = coerce_table_rows(args.rows, &request.action)?; - let borders = parse_table_borders(document, args.borders, &request.action)?; - let style_options = parse_table_style_options(args.style_options); - let mut frame: Rect = args.position.into(); - let (column_widths, row_heights) = normalize_table_dimensions( - &rows, - frame, - args.column_widths, - args.row_heights, - &request.action, - )?; - frame.width = column_widths.iter().sum(); - frame.height = row_heights.iter().sum(); - let element_id = document.next_element_id(); - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide - .elements - .push(PresentationElement::Table(TableElement { - element_id: element_id.clone(), - frame, - rows, - column_widths, - row_heights, - style: args.style, - style_options, - borders, - right_to_left: args.right_to_left.unwrap_or(false), - merges: Vec::new(), - z_order: slide.elements.len(), - })); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Added table element `{element_id}` to slide {}", - args.slide_index - ), - snapshot_for_document(document), - )) - } - - fn update_table_cell( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: UpdateTableCellArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let text_style = - normalize_text_style_with_document(document, &args.styling, &request.action)?; - let background_fill = args - .background_fill - .as_deref() - .map(|fill| { - normalize_color_with_document(document, fill, &request.action, "background_fill") - }) - .transpose()?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - let PresentationElement::Table(table) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{}` is not a table", args.element_id), - }); - }; - let row = args.row as usize; - let column = args.column as usize; - if row >= table.rows.len() || column >= table.rows[row].len() { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!("cell ({row}, {column}) is out of bounds"), - }); - } - let cell = &mut table.rows[row][column]; - cell.text = cell_value_to_string(args.value); - cell.text_style = text_style; - cell.background_fill = background_fill; - cell.rich_text = RichTextState::default(); - cell.alignment = args - .alignment - .as_deref() - .map(|value| parse_alignment(value, &request.action)) - .transpose()?; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated table cell ({row}, {column})"), - snapshot_for_document(document), - )) - } - - fn update_table_style( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: UpdateTableStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let borders = parse_table_borders(document, args.borders, &request.action)?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - let PresentationElement::Table(table) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{}` is not a table", args.element_id), - }); - }; - table.style = args.style; - if let Some(borders) = borders { - if let Some(existing) = table.borders.as_mut() { - if borders.outside.is_some() { - existing.outside = borders.outside; - } - if borders.inside.is_some() { - existing.inside = borders.inside; - } - if borders.top.is_some() { - existing.top = borders.top; - } - if borders.bottom.is_some() { - existing.bottom = borders.bottom; - } - if borders.left.is_some() { - existing.left = borders.left; - } - if borders.right.is_some() { - existing.right = borders.right; - } - } else { - table.borders = Some(borders); - } - } - if let Some(style_options) = args.style_options { - if let Some(value) = style_options.header_row { - table.style_options.header_row = value; - } - if let Some(value) = style_options.banded_rows { - table.style_options.banded_rows = value; - } - if let Some(value) = style_options.banded_columns { - table.style_options.banded_columns = value; - } - if let Some(value) = style_options.first_column { - table.style_options.first_column = value; - } - if let Some(value) = style_options.last_column { - table.style_options.last_column = value; - } - if let Some(value) = style_options.total_row { - table.style_options.total_row = value; - } - } - if let Some(right_to_left) = args.right_to_left { - table.right_to_left = right_to_left; - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated table style for `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn style_table_block( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: StyleTableBlockArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let text_style = - normalize_text_style_with_document(document, &args.styling, &request.action)?; - let background_fill = args - .background_fill - .as_deref() - .map(|fill| { - normalize_color_with_document(document, fill, &request.action, "background_fill") - }) - .transpose()?; - let borders = parse_table_borders(document, args.borders, &request.action)?; - let alignment = args - .alignment - .as_deref() - .map(|value| parse_alignment(value, &request.action)) - .transpose()?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - let PresentationElement::Table(table) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{}` is not a table", args.element_id), - }); - }; - let end_row = (args.row + args.row_count) as usize; - let end_column = (args.column + args.column_count) as usize; - for row_index in args.row as usize..end_row { - if row_index >= table.rows.len() { - break; - } - for column_index in args.column as usize..end_column { - if column_index >= table.rows[row_index].len() { - break; - } - let cell = &mut table.rows[row_index][column_index]; - cell.text_style = text_style.clone(); - if let Some(fill) = background_fill.clone() { - cell.background_fill = Some(fill); - } - if let Some(alignment) = alignment { - cell.alignment = Some(alignment); - } - if let Some(borders) = borders.clone() { - cell.borders = Some(borders); - } - } - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Styled table block for `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn merge_table_cells( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: MergeTableCellsArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - let PresentationElement::Table(table) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{}` is not a table", args.element_id), - }); - }; - let region = TableMergeRegion { - start_row: args.start_row as usize, - end_row: args.end_row as usize, - start_column: args.start_column as usize, - end_column: args.end_column as usize, - }; - table.merges.push(region); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Merged table cells in `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn add_chart( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddChartArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let chart_type = parse_chart_type(&args.chart_type, &request.action)?; - let series = parse_chart_series(document, args.series, &request.action)?; - let legend_text_style = - normalize_text_style_with_document(document, &args.legend_text_style, &request.action)?; - let data_labels = parse_chart_data_labels(document, args.data_labels, &request.action)?; - let chart_fill = args - .chart_fill - .as_deref() - .map(|value| { - normalize_color_with_document(document, value, &request.action, "chart_fill") - }) - .transpose()?; - let plot_area_fill = args - .plot_area_fill - .as_deref() - .map(|value| { - normalize_color_with_document(document, value, &request.action, "plot_area_fill") - }) - .transpose()?; - let element_id = document.next_element_id(); - let slide = document.get_slide_mut(args.slide_index, &request.action)?; - slide - .elements - .push(PresentationElement::Chart(ChartElement { - element_id: element_id.clone(), - frame: args.position.into(), - chart_type, - categories: args.categories, - series, - title: args.title, - style_index: args.style_index, - has_legend: args.has_legend.unwrap_or(false), - legend: Some(ChartLegend { - position: args.legend_position, - text_style: legend_text_style, - }), - x_axis: Some(ChartAxisSpec { - title: args.x_axis_title, - }), - y_axis: Some(ChartAxisSpec { - title: args.y_axis_title, - }), - data_labels, - chart_fill, - plot_area_fill, - z_order: slide.elements.len(), - })); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!( - "Added chart element `{element_id}` to slide {}", - args.slide_index - ), - snapshot_for_document(document), - )) - } - - fn update_chart( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: UpdateChartArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let legend_text_style = - normalize_text_style_with_document(document, &args.legend_text_style, &request.action)?; - let data_labels = parse_chart_data_labels(document, args.data_labels, &request.action)?; - let chart_fill = args - .chart_fill - .as_deref() - .map(|value| normalize_color_with_document(document, value, &request.action, "chart_fill")) - .transpose()?; - let plot_area_fill = args - .plot_area_fill - .as_deref() - .map(|value| normalize_color_with_document(document, value, &request.action, "plot_area_fill")) - .transpose()?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - let PresentationElement::Chart(chart) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{}` is not a chart", args.element_id), - }); - }; - if let Some(title) = args.title { - chart.title = Some(title); - } - if let Some(categories) = args.categories { - chart.categories = categories; - } - if let Some(style_index) = args.style_index { - chart.style_index = Some(style_index); - } - if let Some(has_legend) = args.has_legend { - chart.has_legend = has_legend; - } - if args.legend_position.is_some() || !text_style_is_empty(&legend_text_style) { - chart.legend = Some(ChartLegend { - position: args.legend_position, - text_style: legend_text_style, - }); - } - if args.x_axis_title.is_some() { - chart.x_axis = Some(ChartAxisSpec { - title: args.x_axis_title, - }); - } - if args.y_axis_title.is_some() { - chart.y_axis = Some(ChartAxisSpec { - title: args.y_axis_title, - }); - } - if data_labels.is_some() { - chart.data_labels = data_labels; - } - if chart_fill.is_some() { - chart.chart_fill = chart_fill; - } - if plot_area_fill.is_some() { - chart.plot_area_fill = plot_area_fill; - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated chart `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn add_chart_series( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddChartSeriesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let series = parse_chart_series( - document, - vec![ChartSeriesArgs { - name: args.name, - values: args.values, - categories: args.categories, - x_values: args.x_values, - fill: args.fill, - stroke: args.stroke, - marker: args.marker, - data_label_overrides: None, - }], - &request.action, - )?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - let PresentationElement::Chart(chart) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{}` is not a chart", args.element_id), - }); - }; - chart.series.extend(series); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Added chart series to `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn update_text( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: UpdateTextArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; - let fill = args - .styling - .fill - .as_deref() - .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) - .transpose()?; - let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - match element { - PresentationElement::Text(text) => { - text.text = args.text; - if let Some(fill) = fill.clone() { - text.fill = Some(fill); - } - text.style = style; - text.rich_text = RichTextState { - ranges: Vec::new(), - layout: text_layout, - }; - } - PresentationElement::Shape(shape) => { - if shape.text.is_none() { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{}` does not contain editable text", - args.element_id - ), - }); - } - shape.text = Some(args.text); - if let Some(fill) = fill { - shape.fill = Some(fill); - } - shape.text_style = style; - shape.rich_text = Some(RichTextState { - ranges: Vec::new(), - layout: text_layout, - }); - } - other => { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{}` is `{}`; only text-bearing elements support `update_text`", - args.element_id, - other.kind() - ), - }); - } - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated text for element `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn set_rich_text( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SetRichTextArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let (text, mut rich_text) = - normalize_rich_text_input(document, args.text, &request.action)?; - rich_text.layout = normalize_text_layout(&args.text_layout, &request.action)?; - let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; - if args.notes.unwrap_or(false) { - let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: "`slide_index` is required for notes rich text".to_string(), - })?; - let slide = document.get_slide_mut(slide_index, &request.action)?; - slide.notes.text = text; - slide.notes.rich_text = rich_text; - return Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated rich text for notes on slide {slide_index}"), - snapshot_for_document(document), - )); - } - if let Some(element_id) = args.element_id { - if let (Some(row), Some(column)) = (args.row, args.column) { - let element = document.find_element_mut(&element_id, &request.action)?; - let PresentationElement::Table(table) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{element_id}` is not a table"), - }); - }; - let row = row as usize; - let column = column as usize; - if row >= table.rows.len() || column >= table.rows[row].len() { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!("cell ({row}, {column}) is out of bounds"), - }); - } - let cell = &mut table.rows[row][column]; - cell.text = text; - cell.text_style = style; - cell.rich_text = rich_text; - return Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated rich text for table cell ({row}, {column})"), - snapshot_for_document(document), - )); - } - let element = document.find_element_mut(&element_id, &request.action)?; - match element { - PresentationElement::Text(text_element) => { - text_element.text = text; - text_element.style = style; - text_element.rich_text = rich_text; - } - PresentationElement::Shape(shape) => { - if shape.text.is_none() { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{element_id}` does not contain editable text" - ), - }); - } - shape.text = Some(text); - shape.text_style = style; - shape.rich_text = Some(rich_text); - } - other => { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{element_id}` is `{}`; only text-bearing elements support `set_rich_text`", - other.kind() - ), - }); - } - } - return Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated rich text for element `{element_id}`"), - snapshot_for_document(document), - )); - } - Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: "provide `element_id` or `slide_index` with `notes: true`".to_string(), - }) - } - - fn format_text_range( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: FormatTextRangeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; - let hyperlink = args - .link - .as_ref() - .map(|link| parse_rich_text_link(link, &request.action)) - .transpose()?; - let layout = normalize_text_layout(&args.text_layout, &request.action)?; - let apply_annotation = - |range_id: String, - text: &str, - rich_text: &mut RichTextState| - -> Result<(), PresentationArtifactError> { - let (start_cp, length, _) = resolve_text_range_selector( - text, - args.query.as_deref(), - args.occurrence, - args.start_cp, - args.length, - &request.action, - )?; - rich_text.ranges.push(TextRangeAnnotation { - range_id, - start_cp, - length, - style: style.clone(), - hyperlink: hyperlink.clone(), - spacing_before: args.spacing_before.map(|value| value * 100), - spacing_after: args.spacing_after.map(|value| value * 100), - line_spacing: args.line_spacing, - }); - if layout.insets.is_some() - || layout.wrap.is_some() - || layout.auto_fit.is_some() - || layout.vertical_alignment.is_some() - { - rich_text.layout = layout.clone(); - } - Ok(()) - }; - if args.notes.unwrap_or(false) { - let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: "`slide_index` is required for notes text ranges".to_string(), - })?; - let range_id = document.next_text_range_id(); - let slide = document.get_slide_mut(slide_index, &request.action)?; - apply_annotation(range_id, &slide.notes.text, &mut slide.notes.rich_text)?; - return Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Formatted notes text range on slide {slide_index}"), - snapshot_for_document(document), - )); - } - let element_id = args.element_id.clone().ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: "`element_id` is required unless formatting notes".to_string(), - })?; - if let (Some(row), Some(column)) = (args.row, args.column) { - let range_id = document.next_text_range_id(); - let element = document.find_element_mut(&element_id, &request.action)?; - let PresentationElement::Table(table) = element else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!("element `{element_id}` is not a table"), - }); - }; - let row = row as usize; - let column = column as usize; - if row >= table.rows.len() || column >= table.rows[row].len() { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!("cell ({row}, {column}) is out of bounds"), - }); - } - let cell = &mut table.rows[row][column]; - apply_annotation(range_id, &cell.text, &mut cell.rich_text)?; - return Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Formatted table cell text range ({row}, {column})"), - snapshot_for_document(document), - )); - } - let range_id = document.next_text_range_id(); - let element = document.find_element_mut(&element_id, &request.action)?; - match element { - PresentationElement::Text(text) => { - apply_annotation(range_id, &text.text, &mut text.rich_text)?; - } - PresentationElement::Shape(shape) => { - let text_value = shape.text.as_ref().ok_or_else(|| { - PresentationArtifactError::UnsupportedFeature { - action: request.action.clone(), - message: format!("element `{element_id}` does not contain editable text"), - } - })?; - let rich_text = shape.rich_text.get_or_insert_with(RichTextState::default); - apply_annotation(range_id, text_value, rich_text)?; - } - other => { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{element_id}` is `{}`; only text-bearing elements support `format_text_range`", - other.kind() - ), - }); - } - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Formatted text range on element `{element_id}`"), - snapshot_for_document(document), - )) - } - - fn replace_text( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: ReplaceTextArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - match element { - PresentationElement::Text(text) => { - if !text.text.contains(&args.search) { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!( - "text `{}` was not found in element `{}`", - args.search, args.element_id - ), - }); - } - text.text = text.text.replace(&args.search, &args.replace); - } - PresentationElement::Shape(shape) => { - let Some(text) = &mut shape.text else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{}` does not contain editable text", - args.element_id - ), - }); - }; - if !text.contains(&args.search) { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!( - "text `{}` was not found in element `{}`", - args.search, args.element_id - ), - }); - } - *text = text.replace(&args.search, &args.replace); - } - other => { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{}` is `{}`; only text-bearing elements support `replace_text`", - args.element_id, - other.kind() - ), - }); - } - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Replaced text in element `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn insert_text_after( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: InsertTextAfterArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let element = document.find_element_mut(&args.element_id, &request.action)?; - match element { - PresentationElement::Text(text) => { - let Some(index) = text.text.find(&args.after) else { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!( - "text `{}` was not found in element `{}`", - args.after, args.element_id - ), - }); - }; - let insert_at = index + args.after.len(); - text.text.insert_str(insert_at, &args.insert); - } - PresentationElement::Shape(shape) => { - let Some(text) = &mut shape.text else { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{}` does not contain editable text", - args.element_id - ), - }); - }; - let Some(index) = text.find(&args.after) else { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: format!( - "text `{}` was not found in element `{}`", - args.after, args.element_id - ), - }); - }; - let insert_at = index + args.after.len(); - text.insert_str(insert_at, &args.insert); - } - other => { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{}` is `{}`; only text-bearing elements support `insert_text_after`", - args.element_id, - other.kind() - ), - }); - } - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Inserted text in element `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn set_hyperlink( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SetHyperlinkArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let clear = args.clear.unwrap_or(false); - let hyperlink = if clear { - None - } else { - Some(parse_hyperlink_state(document, &args, &request.action)?) - }; - let element = document.find_element_mut(&args.element_id, &request.action)?; - match element { - PresentationElement::Text(text) => text.hyperlink = hyperlink, - PresentationElement::Shape(shape) => shape.hyperlink = hyperlink, - other => { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: format!( - "element `{}` is `{}`; only text boxes and shapes support `set_hyperlink`", - args.element_id, - other.kind() - ), - }); - } - } - Ok(PresentationArtifactResponse::new( - artifact_id, - "set_hyperlink".to_string(), - if clear { - format!("Cleared hyperlink for element `{}`", args.element_id) - } else { - format!("Updated hyperlink for element `{}`", args.element_id) - }, - snapshot_for_document(document), - )) - } - - fn set_comment_author( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: SetCommentAuthorArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - document.comment_self = Some(CommentAuthorProfile { - display_name: args.display_name, - initials: args.initials, - email: args.email, - }); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - "Updated comment author".to_string(), - snapshot_for_document(document), - )) - } - - fn add_comment_thread( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddCommentThreadArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let author = document.comment_self.clone().ok_or_else(|| { - PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: "set a comment author first with `set_comment_author`".to_string(), - } - })?; - let target = if let Some(slide_index) = args.slide_index { - let slide = document.get_slide_mut(slide_index, &request.action)?; - if let Some(element_id) = args.element_id { - if args.query.is_some() || args.start_cp.is_some() { - let (text, _rich_text) = lookup_text_target( - slide, - &element_id, - None, - None, - &request.action, - )?; - let (start_cp, length, context) = resolve_text_range_selector( - text, - args.query.as_deref(), - args.occurrence, - args.start_cp, - args.length, - &request.action, - )?; - CommentTarget::TextRange { - slide_id: slide.slide_id.clone(), - element_id: normalize_element_lookup_id(&element_id).to_string(), - start_cp, - length, - context, - } - } else { - CommentTarget::Element { - slide_id: slide.slide_id.clone(), - element_id: normalize_element_lookup_id(&element_id).to_string(), - } - } - } else { - CommentTarget::Slide { - slide_id: slide.slide_id.clone(), - } - } - } else { - return Err(PresentationArtifactError::InvalidArgs { - action: request.action, - message: "`slide_index` is required for comment threads".to_string(), - }); - }; - let thread_id = document.next_comment_thread_id(); - let message_id = document.next_comment_message_id(); - document.comment_threads.push(CommentThread { - thread_id: thread_id.clone(), - target, - position: args.position.map(|position| CommentPosition { - x: position.x, - y: position.y, - }), - status: CommentThreadStatus::Active, - messages: vec![CommentMessage { - message_id, - author, - text: args.text, - created_at: "2026-03-03T00:00:00Z".to_string(), - reactions: Vec::new(), - }], - }); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Added comment thread `{thread_id}`"), - snapshot_for_document(document), - )) - } - - fn add_comment_reply( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: AddCommentReplyArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let author = document.comment_self.clone().ok_or_else(|| { - PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: "set a comment author first with `set_comment_author`".to_string(), - } - })?; - let message_id = document.next_comment_message_id(); - let thread = document - .comment_threads - .iter_mut() - .find(|thread| thread.thread_id == args.thread_id) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("unknown comment thread `{}`", args.thread_id), - })?; - thread.messages.push(CommentMessage { - message_id, - author, - text: args.text, - created_at: "2026-03-03T00:00:00Z".to_string(), - reactions: Vec::new(), - }); - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Added reply to `{}`", args.thread_id), - snapshot_for_document(document), - )) - } - - fn toggle_comment_reaction( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: ToggleCommentReactionArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let thread = document - .comment_threads - .iter_mut() - .find(|thread| thread.thread_id == args.thread_id) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("unknown comment thread `{}`", args.thread_id), - })?; - let target_message_id = args - .message_id - .clone() - .or_else(|| thread.messages.last().map(|message| message.message_id.clone())) - .unwrap_or_default(); - let message = thread - .messages - .iter_mut() - .find(|message| message.message_id == target_message_id) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("unknown comment message `{target_message_id}`"), - })?; - if let Some(index) = message.reactions.iter().position(|emoji| emoji == &args.emoji) { - message.reactions.remove(index); - } else { - message.reactions.push(args.emoji.clone()); - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Toggled reaction on `{}`", args.thread_id), - snapshot_for_document(document), - )) - } - - fn resolve_comment_thread( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: CommentThreadIdArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let thread = document - .comment_threads - .iter_mut() - .find(|thread| thread.thread_id == args.thread_id) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("unknown comment thread `{}`", args.thread_id), - })?; - thread.status = CommentThreadStatus::Resolved; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Resolved `{}`", args.thread_id), - snapshot_for_document(document), - )) - } - - fn reopen_comment_thread( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: CommentThreadIdArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let thread = document - .comment_threads - .iter_mut() - .find(|thread| thread.thread_id == args.thread_id) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("unknown comment thread `{}`", args.thread_id), - })?; - thread.status = CommentThreadStatus::Active; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Reopened `{}`", args.thread_id), - snapshot_for_document(document), - )) - } - - fn update_shape_style( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: UpdateShapeStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let fill = args - .fill - .as_deref() - .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) - .transpose()?; - let stroke = args - .stroke - .clone() - .map(|value| parse_required_stroke(document, value, &request.action)) - .transpose()?; - let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; - let has_text_layout = text_layout.insets.is_some() - || text_layout.wrap.is_some() - || text_layout.auto_fit.is_some() - || text_layout.vertical_alignment.is_some(); - let element = document.find_element_mut(&args.element_id, &request.action)?; - match element { - PresentationElement::Text(text) => { - if let Some(position) = args.position { - text.frame = apply_partial_position(text.frame, position); - } - if let Some(fill) = fill.clone() { - text.fill = Some(fill); - } - if has_text_layout { - text.rich_text.layout = text_layout; - } - if args.stroke.is_some() - || args.rotation.is_some() - || args.flip_horizontal.is_some() - || args.flip_vertical.is_some() - { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: - "text elements support only `position`, `z_order`, and `fill` updates" - .to_string(), - }); - } - } - PresentationElement::Shape(shape) => { - let position_rotation = args - .position - .as_ref() - .and_then(|position| position.rotation); - let position_flip_horizontal = args - .position - .as_ref() - .and_then(|position| position.flip_horizontal); - let position_flip_vertical = args - .position - .as_ref() - .and_then(|position| position.flip_vertical); - if let Some(position) = args.position { - shape.frame = apply_partial_position(shape.frame, position); - } - if let Some(fill) = fill { - shape.fill = Some(fill); - } - if let Some(stroke) = stroke { - shape.stroke = Some(stroke); - } - if let Some(rotation) = args.rotation.or(position_rotation) { - shape.rotation_degrees = Some(rotation); - } - if let Some(flip_horizontal) = args.flip_horizontal.or(position_flip_horizontal) { - shape.flip_horizontal = flip_horizontal; - } - if let Some(flip_vertical) = args.flip_vertical.or(position_flip_vertical) { - shape.flip_vertical = flip_vertical; - } - if shape.text.is_some() && has_text_layout { - shape.rich_text = Some(RichTextState { - ranges: shape.rich_text.take().unwrap_or_default().ranges, - layout: text_layout, - }); - } - } - PresentationElement::Connector(connector) => { - if args.fill.is_some() - || args.rotation.is_some() - || args.flip_horizontal.is_some() - || args.flip_vertical.is_some() - || args.fit.is_some() - || args.crop.is_some() - || args.lock_aspect_ratio.is_some() - { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: - "connector elements support only `position`, `stroke`, and `z_order` updates" - .to_string(), - }); - } - if let Some(position) = args.position { - let updated = apply_partial_position( - Rect { - left: connector.start.left, - top: connector.start.top, - width: connector.end.left.abs_diff(connector.start.left), - height: connector.end.top.abs_diff(connector.start.top), - }, - position, - ); - connector.start = PointArgs { - left: updated.left, - top: updated.top, - }; - connector.end = PointArgs { - left: updated.left.saturating_add(updated.width), - top: updated.top.saturating_add(updated.height), - }; - } - if let Some(stroke) = stroke { - connector.line = stroke; - } - } - PresentationElement::Image(image) => { - let position_rotation = args - .position - .as_ref() - .and_then(|position| position.rotation); - let position_flip_horizontal = args - .position - .as_ref() - .and_then(|position| position.flip_horizontal); - let position_flip_vertical = args - .position - .as_ref() - .and_then(|position| position.flip_vertical); - if args.fill.is_some() || args.stroke.is_some() { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: - "image elements support only `position`, `fit`, `crop`, `rotation`, `flip_horizontal`, `flip_vertical`, `lock_aspect_ratio`, and `z_order` updates" - .to_string(), - }); - } - if let Some(position) = args.position { - image.frame = apply_partial_position_to_image(image, position); - } - if let Some(fit) = args.fit { - image.fit_mode = fit; - if !matches!(fit, ImageFitMode::Stretch) && args.lock_aspect_ratio.is_none() { - image.lock_aspect_ratio = true; - } - } - if let Some(crop) = args.crop { - image.crop = Some(normalize_image_crop(crop, &request.action)?); - } - if let Some(rotation) = args.rotation.or(position_rotation) { - image.rotation_degrees = Some(rotation); - } - if let Some(flip_horizontal) = args.flip_horizontal.or(position_flip_horizontal) { - image.flip_horizontal = flip_horizontal; - } - if let Some(flip_vertical) = args.flip_vertical.or(position_flip_vertical) { - image.flip_vertical = flip_vertical; - } - if let Some(lock_aspect_ratio) = args.lock_aspect_ratio { - image.lock_aspect_ratio = lock_aspect_ratio; - } - } - PresentationElement::Table(table) => { - if args.fill.is_some() - || args.stroke.is_some() - || args.rotation.is_some() - || args.flip_horizontal.is_some() - || args.flip_vertical.is_some() - { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: "table elements support only `position` and `z_order` updates" - .to_string(), - }); - } - if let Some(position) = args.position { - table.frame = apply_partial_position(table.frame, position); - } - } - PresentationElement::Chart(chart) => { - if args.fill.is_some() - || args.stroke.is_some() - || args.rotation.is_some() - || args.flip_horizontal.is_some() - || args.flip_vertical.is_some() - { - return Err(PresentationArtifactError::UnsupportedFeature { - action: request.action, - message: "chart elements support only `position` and `z_order` updates" - .to_string(), - }); - } - if let Some(position) = args.position { - chart.frame = apply_partial_position(chart.frame, position); - } - } - } - if let Some(z_order) = args.z_order { - document.set_z_order(&args.element_id, z_order as usize, &request.action)?; - } - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Updated style for element `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn delete_element( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: ElementIdArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - document.remove_element(&args.element_id, &request.action)?; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Deleted element `{}`", args.element_id), - snapshot_for_document(document), - )) - } - - fn bring_to_front( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: ElementIdArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - let target_index = document.total_element_count(); - document.set_z_order(&args.element_id, target_index, &request.action)?; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Brought `{}` to front", args.element_id), - snapshot_for_document(document), - )) - } - - fn send_to_back( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let args: ElementIdArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let document = self.get_document_mut(&artifact_id, &request.action)?; - document.set_z_order(&args.element_id, 0, &request.action)?; - Ok(PresentationArtifactResponse::new( - artifact_id, - request.action, - format!("Sent `{}` to back", args.element_id), - snapshot_for_document(document), - )) - } - - fn delete_artifact( - &mut self, - request: PresentationArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let removed = self.documents.remove(&artifact_id).ok_or_else(|| { - PresentationArtifactError::UnknownArtifactId { - action: request.action.clone(), - artifact_id: artifact_id.clone(), - } - })?; - Ok(PresentationArtifactResponse { - artifact_id, - action: request.action, - summary: format!( - "Deleted in-memory artifact `{}` with {} slides", - removed.artifact_id, - removed.slides.len() - ), - executed_actions: None, - exported_paths: Vec::new(), - artifact_snapshot: None, - slide_list: None, - layout_list: None, - placeholder_list: None, - theme: None, - inspect_ndjson: None, - resolved_record: None, - proto_json: None, - patch: None, - active_slide_index: None, - }) - } - - fn get_document( - &self, - artifact_id: &str, - action: &str, - ) -> Result<&PresentationDocument, PresentationArtifactError> { - self.documents.get(artifact_id).ok_or_else(|| { - PresentationArtifactError::UnknownArtifactId { - action: action.to_string(), - artifact_id: artifact_id.to_string(), - } - }) - } - - fn get_document_mut( - &mut self, - artifact_id: &str, - action: &str, - ) -> Result<&mut PresentationDocument, PresentationArtifactError> { - self.documents.get_mut(artifact_id).ok_or_else(|| { - PresentationArtifactError::UnknownArtifactId { - action: action.to_string(), - artifact_id: artifact_id.to_string(), - } - }) - } - - fn normalize_patch( - &self, - request_artifact_id: Option<&str>, - operations: Vec, - action: &str, - ) -> Result { - if operations.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`operations` must contain at least one entry".to_string(), - }); - } - let mut patch_artifact_id = request_artifact_id.map(str::to_owned); - let mut normalized_operations = Vec::with_capacity(operations.len()); - for operation in operations { - let operation_artifact_id = operation - .artifact_id - .or_else(|| request_artifact_id.map(str::to_owned)) - .ok_or_else(|| PresentationArtifactError::MissingArtifactId { - action: action.to_string(), - })?; - if let Some(existing_artifact_id) = &patch_artifact_id { - if existing_artifact_id != &operation_artifact_id { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!( - "patch operations must target a single artifact, found both `{existing_artifact_id}` and `{operation_artifact_id}`" - ), - }); - } - } else { - patch_artifact_id = Some(operation_artifact_id.clone()); - } - if !patch_operation_supported(&operation.action) { - return Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!( - "patch operations do not support nested action `{}`", - operation.action - ), - }); - } - normalized_operations.push(PatchOperation { - action: operation.action, - args: operation.args, - }); - } - let artifact_id = - patch_artifact_id.ok_or_else(|| PresentationArtifactError::MissingArtifactId { - action: action.to_string(), - })?; - self.get_document(&artifact_id, action)?; - Ok(PresentationPatch { - version: 1, - artifact_id, - operations: normalized_operations, - }) - } - - fn normalize_serialized_patch( - &self, - request_artifact_id: Option<&str>, - patch: PresentationPatch, - action: &str, - ) -> Result { - if patch.version != 1 { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("unsupported patch version `{}`", patch.version), - }); - } - if patch.operations.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`patch.operations` must contain at least one entry".to_string(), - }); - } - if let Some(request_artifact_id) = request_artifact_id - && request_artifact_id != patch.artifact_id - { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!( - "request artifact `{request_artifact_id}` does not match patch artifact `{}`", - patch.artifact_id - ), - }); - } - for operation in &patch.operations { - if !patch_operation_supported(&operation.action) { - return Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!( - "patch operations do not support nested action `{}`", - operation.action - ), - }); - } - } - self.get_document(&patch.artifact_id, action)?; - Ok(patch) - } -} - -fn lookup_text_target<'a>( - slide: &'a PresentationSlide, - element_id: &str, - _row: Option, - _column: Option, - action: &str, -) -> Result<(&'a str, Option<&'a RichTextState>), PresentationArtifactError> { - let normalized_element_id = normalize_element_lookup_id(element_id); - let element = slide - .elements - .iter() - .find(|element| element.element_id() == normalized_element_id) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown element `{element_id}` on slide `{}`", slide.slide_id), - })?; - match element { - PresentationElement::Text(text) => Ok((&text.text, Some(&text.rich_text))), - PresentationElement::Shape(shape) => shape - .text - .as_deref() - .map(|text| (text, shape.rich_text.as_ref())) - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("element `{element_id}` does not contain editable text"), - }), - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!( - "element `{element_id}` does not support text-range comments" - ), - }), - } -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/mod.rs b/codex-rs/artifact-presentation/src/presentation_artifact/mod.rs deleted file mode 100644 index 8497062a91..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -include!("api.rs"); -include!("manager.rs"); -include!("response.rs"); -include!("model.rs"); -include!("args.rs"); -include!("parsing.rs"); -include!("proto.rs"); -include!("inspect.rs"); -include!("pptx.rs"); -include!("snapshot.rs"); diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/model.rs b/codex-rs/artifact-presentation/src/presentation_artifact/model.rs deleted file mode 100644 index b5cd5d00a3..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/model.rs +++ /dev/null @@ -1,1934 +0,0 @@ -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct ThemeState { - color_scheme: HashMap, - major_font: Option, - minor_font: Option, -} - -impl ThemeState { - fn resolve_color(&self, color: &str) -> Option { - let key = color.trim().to_ascii_lowercase(); - let alias = match key.as_str() { - "background1" => "bg1", - "background2" => "bg2", - "text1" => "tx1", - "text2" => "tx2", - "dark1" => "dk1", - "dark2" => "dk2", - "light1" => "lt1", - "light2" => "lt2", - other => other, - }; - self.color_scheme - .get(alias) - .or_else(|| self.color_scheme.get(&key)) - .cloned() - .map(|value| value.trim_start_matches('#').to_uppercase()) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum LayoutKind { - Layout, - Master, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct LayoutDocument { - layout_id: String, - name: String, - kind: LayoutKind, - parent_layout_id: Option, - placeholders: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct PlaceholderDefinition { - name: String, - placeholder_type: String, - index: Option, - text: Option, - geometry: ShapeGeometry, - frame: Rect, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct ResolvedPlaceholder { - source_layout_id: String, - definition: PlaceholderDefinition, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct NotesState { - text: String, - visible: bool, - #[serde(default)] - rich_text: RichTextState, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct TextStyle { - style_name: Option, - font_size: Option, - font_family: Option, - color: Option, - alignment: Option, - bold: bool, - italic: bool, - underline: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct NamedTextStyle { - name: String, - style: TextStyle, - built_in: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct HyperlinkState { - target: HyperlinkTarget, - tooltip: Option, - highlight_click: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -enum HyperlinkTarget { - Url(String), - Slide(u32), - FirstSlide, - LastSlide, - NextSlide, - PreviousSlide, - EndShow, - Email { - address: String, - subject: Option, - }, - File(String), -} - -impl HyperlinkTarget { - fn relationship_target(&self) -> String { - match self { - Self::Url(url) => url.clone(), - Self::Slide(slide_index) => format!("slide{}.xml", slide_index + 1), - Self::FirstSlide => "ppaction://hlinkshowjump?jump=firstslide".to_string(), - Self::LastSlide => "ppaction://hlinkshowjump?jump=lastslide".to_string(), - Self::NextSlide => "ppaction://hlinkshowjump?jump=nextslide".to_string(), - Self::PreviousSlide => "ppaction://hlinkshowjump?jump=previousslide".to_string(), - Self::EndShow => "ppaction://hlinkshowjump?jump=endshow".to_string(), - Self::Email { address, subject } => { - let mut mailto = format!("mailto:{address}"); - if let Some(subject) = subject { - mailto.push_str(&format!("?subject={subject}")); - } - mailto - } - Self::File(path) => format!("file:///{}", path.replace('\\', "/")), - } - } - - fn is_external(&self) -> bool { - matches!(self, Self::Url(_) | Self::Email { .. } | Self::File(_)) - } -} - -impl HyperlinkState { - fn to_ppt_rs(&self, relationship_id: &str) -> PptHyperlink { - let hyperlink = match &self.target { - HyperlinkTarget::Url(url) => PptHyperlink::new(PptHyperlinkAction::url(url)), - HyperlinkTarget::Slide(slide_index) => { - PptHyperlink::new(PptHyperlinkAction::slide(slide_index + 1)) - } - HyperlinkTarget::FirstSlide => PptHyperlink::new(PptHyperlinkAction::FirstSlide), - HyperlinkTarget::LastSlide => PptHyperlink::new(PptHyperlinkAction::LastSlide), - HyperlinkTarget::NextSlide => PptHyperlink::new(PptHyperlinkAction::NextSlide), - HyperlinkTarget::PreviousSlide => PptHyperlink::new(PptHyperlinkAction::PreviousSlide), - HyperlinkTarget::EndShow => PptHyperlink::new(PptHyperlinkAction::EndShow), - HyperlinkTarget::Email { address, subject } => PptHyperlink::new(match subject { - Some(subject) => PptHyperlinkAction::email_with_subject(address, subject), - None => PptHyperlinkAction::email(address), - }), - HyperlinkTarget::File(path) => PptHyperlink::new(PptHyperlinkAction::file(path)), - }; - let hyperlink = if let Some(tooltip) = &self.tooltip { - hyperlink.with_tooltip(tooltip) - } else { - hyperlink - }; - hyperlink - .with_highlight_click(self.highlight_click) - .with_r_id(relationship_id) - } - - fn to_json(&self) -> Value { - let mut record = match &self.target { - HyperlinkTarget::Url(url) => serde_json::json!({ - "type": "url", - "url": url, - }), - HyperlinkTarget::Slide(slide_index) => serde_json::json!({ - "type": "slide", - "slideIndex": slide_index, - }), - HyperlinkTarget::FirstSlide => serde_json::json!({ - "type": "firstSlide", - }), - HyperlinkTarget::LastSlide => serde_json::json!({ - "type": "lastSlide", - }), - HyperlinkTarget::NextSlide => serde_json::json!({ - "type": "nextSlide", - }), - HyperlinkTarget::PreviousSlide => serde_json::json!({ - "type": "previousSlide", - }), - HyperlinkTarget::EndShow => serde_json::json!({ - "type": "endShow", - }), - HyperlinkTarget::Email { address, subject } => serde_json::json!({ - "type": "email", - "address": address, - "subject": subject, - }), - HyperlinkTarget::File(path) => serde_json::json!({ - "type": "file", - "path": path, - }), - }; - record["tooltip"] = self - .tooltip - .as_ref() - .map(|tooltip| Value::String(tooltip.clone())) - .unwrap_or(Value::Null); - record["highlightClick"] = Value::Bool(self.highlight_click); - record - } - - fn relationship_xml(&self, relationship_id: &str) -> String { - let target_mode = if self.target.is_external() { - r#" TargetMode="External""# - } else { - "" - }; - format!( - r#""#, - ppt_rs::escape_xml(&self.target.relationship_target()), - ) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -enum TextAlignment { - Left, - Center, - Right, - Justify, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct RichTextState { - #[serde(default)] - ranges: Vec, - #[serde(default)] - layout: TextLayoutState, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct TextRangeAnnotation { - range_id: String, - start_cp: usize, - length: usize, - style: TextStyle, - hyperlink: Option, - spacing_before: Option, - spacing_after: Option, - line_spacing: Option, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct TextLayoutState { - insets: Option, - wrap: Option, - auto_fit: Option, - vertical_alignment: Option, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize)] -struct TextInsets { - left: u32, - right: u32, - top: u32, - bottom: u32, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum TextWrapMode { - Square, - None, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum TextAutoFitMode { - None, - ShrinkText, - ResizeShapeToFitText, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum TextVerticalAlignment { - Top, - Middle, - Bottom, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct CommentAuthorProfile { - display_name: String, - initials: String, - email: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct CommentPosition { - x: u32, - y: u32, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum CommentThreadStatus { - Active, - Resolved, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct CommentMessage { - message_id: String, - author: CommentAuthorProfile, - text: String, - created_at: String, - #[serde(default)] - reactions: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -enum CommentTarget { - Slide { - slide_id: String, - }, - Element { - slide_id: String, - element_id: String, - }, - TextRange { - slide_id: String, - element_id: String, - start_cp: usize, - length: usize, - context: Option, - }, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct CommentThread { - thread_id: String, - target: CommentTarget, - position: Option, - status: CommentThreadStatus, - messages: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct TableBorder { - color: String, - width: u32, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct TableBorders { - outside: Option, - inside: Option, - top: Option, - bottom: Option, - left: Option, - right: Option, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct TableStyleOptions { - header_row: bool, - banded_rows: bool, - banded_columns: bool, - first_column: bool, - last_column: bool, - total_row: bool, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct ChartMarkerStyle { - symbol: Option, - size: Option, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct ChartDataLabels { - show_value: bool, - show_category_name: bool, - show_leader_lines: bool, - position: Option, - text_style: TextStyle, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct ChartLegend { - position: Option, - text_style: TextStyle, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct ChartAxisSpec { - title: Option, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct ChartDataLabelOverride { - idx: usize, - text: Option, - position: Option, - text_style: TextStyle, - fill: Option, - stroke: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct PlaceholderRef { - name: String, - placeholder_type: String, - index: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct TableMergeRegion { - start_row: usize, - end_row: usize, - start_column: usize, - end_column: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct TableCellSpec { - text: String, - text_style: TextStyle, - background_fill: Option, - alignment: Option, - #[serde(default)] - rich_text: RichTextState, - borders: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct PresentationDocument { - artifact_id: String, - name: Option, - slide_size: Rect, - theme: ThemeState, - custom_text_styles: HashMap, - layouts: Vec, - slides: Vec, - active_slide_index: Option, - #[serde(default)] - comment_self: Option, - #[serde(default)] - comment_threads: Vec, - next_slide_seq: u32, - next_element_seq: u32, - next_layout_seq: u32, - next_text_range_seq: u32, - next_comment_thread_seq: u32, - next_comment_message_seq: u32, -} - -impl PresentationDocument { - fn new(name: Option) -> Self { - Self { - artifact_id: format!("presentation_{}", Uuid::new_v4().simple()), - name, - slide_size: Rect { - left: 0, - top: 0, - width: DEFAULT_SLIDE_WIDTH_POINTS, - height: DEFAULT_SLIDE_HEIGHT_POINTS, - }, - theme: ThemeState::default(), - custom_text_styles: HashMap::new(), - layouts: Vec::new(), - slides: Vec::new(), - active_slide_index: None, - comment_self: None, - comment_threads: Vec::new(), - next_slide_seq: 1, - next_element_seq: 1, - next_layout_seq: 1, - next_text_range_seq: 1, - next_comment_thread_seq: 1, - next_comment_message_seq: 1, - } - } - - fn from_ppt_rs(presentation: Presentation) -> Self { - let mut document = Self::new( - (!presentation.get_title().is_empty()).then(|| presentation.get_title().to_string()), - ); - for imported_slide in presentation.slides() { - let mut slide = PresentationSlide { - slide_id: format!("slide_{}", document.next_slide_seq), - notes: NotesState { - text: imported_slide.notes.clone().unwrap_or_default(), - visible: true, - rich_text: RichTextState::default(), - }, - background_fill: None, - layout_id: None, - elements: Vec::new(), - }; - document.next_slide_seq += 1; - - if !imported_slide.title.is_empty() { - slide.elements.push(PresentationElement::Text(TextElement { - element_id: document.next_element_id(), - text: imported_slide.title.clone(), - frame: Rect { - left: DEFAULT_IMPORTED_TITLE_LEFT, - top: DEFAULT_IMPORTED_TITLE_TOP, - width: DEFAULT_IMPORTED_TITLE_WIDTH, - height: DEFAULT_IMPORTED_TITLE_HEIGHT, - }, - fill: None, - style: TextStyle::default(), - hyperlink: None, - rich_text: RichTextState::default(), - placeholder: None, - z_order: slide.elements.len(), - })); - } - - if !imported_slide.content.is_empty() { - slide.elements.push(PresentationElement::Text(TextElement { - element_id: document.next_element_id(), - text: imported_slide.content.join("\n"), - frame: Rect { - left: DEFAULT_IMPORTED_CONTENT_LEFT, - top: DEFAULT_IMPORTED_CONTENT_TOP, - width: DEFAULT_IMPORTED_CONTENT_WIDTH, - height: DEFAULT_IMPORTED_CONTENT_HEIGHT, - }, - fill: None, - style: TextStyle::default(), - hyperlink: None, - rich_text: RichTextState::default(), - placeholder: None, - z_order: slide.elements.len(), - })); - } - - for imported_shape in &imported_slide.shapes { - slide - .elements - .push(PresentationElement::Shape(ShapeElement { - element_id: document.next_element_id(), - geometry: ShapeGeometry::from_shape_type(imported_shape.shape_type), - frame: Rect::from_emu( - imported_shape.x, - imported_shape.y, - imported_shape.width, - imported_shape.height, - ), - fill: imported_shape.fill.as_ref().map(|fill| fill.color.clone()), - stroke: imported_shape.line.as_ref().map(|line| StrokeStyle { - color: line.color.clone(), - width: emu_to_points(line.width), - style: LineStyle::Solid, - }), - text: imported_shape.text.clone(), - text_style: TextStyle::default(), - hyperlink: None, - rich_text: imported_shape - .text - .as_ref() - .map(|_| RichTextState::default()), - placeholder: None, - rotation_degrees: imported_shape.rotation, - flip_horizontal: false, - flip_vertical: false, - z_order: slide.elements.len(), - })); - } - - if let Some(imported_table) = &imported_slide.table { - slide - .elements - .push(PresentationElement::Table(TableElement { - element_id: document.next_element_id(), - frame: Rect::from_emu( - imported_table.x, - imported_table.y, - imported_table.width(), - imported_table.height(), - ), - rows: imported_table - .rows - .iter() - .map(|row| { - row.cells - .iter() - .map(|text| TableCellSpec { - text: text.text.clone(), - text_style: TextStyle::default(), - background_fill: None, - alignment: None, - rich_text: RichTextState::default(), - borders: None, - }) - .collect() - }) - .collect(), - column_widths: imported_table - .column_widths - .iter() - .copied() - .map(emu_to_points) - .collect(), - row_heights: imported_table - .rows - .iter() - .map(|row| row.height.map_or(400_000, |height| height)) - .map(emu_to_points) - .collect(), - style: None, - style_options: TableStyleOptions::default(), - borders: None, - right_to_left: false, - merges: Vec::new(), - z_order: slide.elements.len(), - })); - } - - document.slides.push(slide); - } - document.active_slide_index = (!document.slides.is_empty()).then_some(0); - document - } - - fn new_slide( - &mut self, - notes: Option, - background_fill: Option, - action: &str, - ) -> Result { - let normalized_fill = background_fill - .map(|value| { - normalize_color_with_palette(Some(&self.theme), &value, action, "background_fill") - }) - .transpose()?; - let slide = PresentationSlide { - slide_id: format!("slide_{}", self.next_slide_seq), - notes: NotesState { - text: notes.unwrap_or_default(), - visible: true, - rich_text: RichTextState::default(), - }, - background_fill: normalized_fill, - layout_id: None, - elements: Vec::new(), - }; - self.next_slide_seq += 1; - Ok(slide) - } - - fn append_slide(&mut self, slide: PresentationSlide) -> usize { - let index = self.slides.len(); - self.slides.push(slide); - if self.active_slide_index.is_none() { - self.active_slide_index = Some(index); - } - index - } - - fn clone_slide(&mut self, slide: PresentationSlide) -> PresentationSlide { - let mut clone = slide; - clone.slide_id = format!("slide_{}", self.next_slide_seq); - self.next_slide_seq += 1; - for element in &mut clone.elements { - element.set_element_id(self.next_element_id()); - } - clone - } - - fn next_element_id(&mut self) -> String { - let element_id = format!("element_{}", self.next_element_seq); - self.next_element_seq += 1; - element_id - } - - fn next_text_range_id(&mut self) -> String { - let range_id = format!("range_{}", self.next_text_range_seq); - self.next_text_range_seq += 1; - range_id - } - - fn next_comment_thread_id(&mut self) -> String { - let thread_id = format!("thread_{}", self.next_comment_thread_seq); - self.next_comment_thread_seq += 1; - thread_id - } - - fn next_comment_message_id(&mut self) -> String { - let message_id = format!("message_{}", self.next_comment_message_seq); - self.next_comment_message_seq += 1; - message_id - } - - fn total_element_count(&self) -> usize { - self.slides.iter().map(|slide| slide.elements.len()).sum() - } - - fn set_active_slide_index( - &mut self, - slide_index: usize, - action: &str, - ) -> Result<(), PresentationArtifactError> { - if slide_index >= self.slides.len() { - return Err(index_out_of_range(action, slide_index, self.slides.len())); - } - self.active_slide_index = Some(slide_index); - Ok(()) - } - - fn adjust_active_slide_for_insert(&mut self, inserted_index: usize) { - match self.active_slide_index { - None => self.active_slide_index = Some(inserted_index), - Some(active_index) if inserted_index <= active_index => { - self.active_slide_index = Some(active_index + 1); - } - Some(_) => {} - } - } - - fn adjust_active_slide_for_move(&mut self, from_index: usize, to_index: usize) { - if let Some(active_index) = self.active_slide_index { - self.active_slide_index = Some(if active_index == from_index { - to_index - } else if from_index < active_index && active_index <= to_index { - active_index - 1 - } else if to_index <= active_index && active_index < from_index { - active_index + 1 - } else { - active_index - }); - } - } - - fn adjust_active_slide_for_delete(&mut self, deleted_index: usize) { - self.active_slide_index = match self.active_slide_index { - None => None, - Some(_) if self.slides.is_empty() => None, - Some(active_index) if active_index == deleted_index => { - Some(deleted_index.min(self.slides.len() - 1)) - } - Some(active_index) if deleted_index < active_index => Some(active_index - 1), - Some(active_index) => Some(active_index), - }; - } - - fn next_layout_id(&mut self) -> String { - let layout_id = format!("layout_{}", self.next_layout_seq); - self.next_layout_seq += 1; - layout_id - } - - fn get_layout( - &self, - layout_ref: &str, - action: &str, - ) -> Result<&LayoutDocument, PresentationArtifactError> { - if let Some(layout) = self - .layouts - .iter() - .find(|layout| layout.layout_id == layout_ref) - { - return Ok(layout); - } - - let exact_name_matches = self - .layouts - .iter() - .filter(|layout| layout.name == layout_ref) - .collect::>(); - if exact_name_matches.len() > 1 { - return Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("layout name `{layout_ref}` is ambiguous"), - }); - } - if let Some(layout) = exact_name_matches.into_iter().next() { - return Ok(layout); - } - - let case_insensitive_name_matches = self - .layouts - .iter() - .filter(|layout| layout.name.eq_ignore_ascii_case(layout_ref)) - .collect::>(); - if case_insensitive_name_matches.len() > 1 { - return Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("layout name `{layout_ref}` is ambiguous"), - }); - } - case_insensitive_name_matches - .into_iter() - .next() - .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown layout id or name `{layout_ref}`"), - }) - } - - fn theme_snapshot(&self) -> ThemeSnapshot { - ThemeSnapshot { - color_scheme: self.theme.color_scheme.clone(), - hex_color_map: self.theme.color_scheme.clone(), - major_font: self.theme.major_font.clone(), - minor_font: self.theme.minor_font.clone(), - } - } - - fn named_text_styles(&self) -> Vec { - let mut styles = built_in_text_styles(&self.theme) - .into_iter() - .map(|(name, style)| NamedTextStyle { - name, - style, - built_in: true, - }) - .collect::>(); - styles.extend( - self.custom_text_styles - .iter() - .map(|(name, style)| NamedTextStyle { - name: name.clone(), - style: style.clone(), - built_in: false, - }), - ); - styles.sort_by_cached_key(|style| style.name.to_ascii_lowercase()); - styles - } - - fn resolve_named_text_style( - &self, - style_name: &str, - action: &str, - ) -> Result { - let normalized_style_name = style_name.trim().to_ascii_lowercase(); - if let Some(style) = self.custom_text_styles.get(&normalized_style_name) { - return Ok(style.clone()); - } - built_in_text_style(&self.theme, &normalized_style_name).ok_or_else(|| { - PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown text style `{style_name}`"), - } - }) - } - - fn find_element_mut( - &mut self, - element_id: &str, - action: &str, - ) -> Result<&mut PresentationElement, PresentationArtifactError> { - let element_id = normalize_element_lookup_id(element_id); - for slide in &mut self.slides { - if let Some(element) = slide - .elements - .iter_mut() - .find(|element| element.element_id() == element_id) - { - return Ok(element); - } - } - Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown element id `{element_id}`"), - }) - } - - fn get_slide_mut( - &mut self, - slide_index: u32, - action: &str, - ) -> Result<&mut PresentationSlide, PresentationArtifactError> { - let index = slide_index as usize; - if index >= self.slides.len() { - return Err(index_out_of_range(action, index, self.slides.len())); - } - Ok(&mut self.slides[index]) - } - - fn remove_element( - &mut self, - element_id: &str, - action: &str, - ) -> Result<(), PresentationArtifactError> { - let element_id = normalize_element_lookup_id(element_id); - for slide in &mut self.slides { - if let Some(index) = slide - .elements - .iter() - .position(|element| element.element_id() == element_id) - { - slide.elements.remove(index); - resequence_z_order(slide); - return Ok(()); - } - } - Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown element id `{element_id}`"), - }) - } - - fn set_z_order( - &mut self, - element_id: &str, - target_index: usize, - action: &str, - ) -> Result<(), PresentationArtifactError> { - let element_id = normalize_element_lookup_id(element_id); - for slide in &mut self.slides { - if let Some(current_index) = slide - .elements - .iter() - .position(|element| element.element_id() == element_id) - { - let destination = target_index.min(slide.elements.len().saturating_sub(1)); - let element = slide.elements.remove(current_index); - slide.elements.insert(destination, element); - resequence_z_order(slide); - return Ok(()); - } - } - Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("unknown element id `{element_id}`"), - }) - } - - fn to_ppt_rs(&self) -> Presentation { - let mut presentation = self - .name - .as_deref() - .map(Presentation::with_title) - .unwrap_or_default(); - for slide in &self.slides { - presentation = presentation.add_slide(slide.to_ppt_rs(self.slide_size)); - } - presentation - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct PresentationSlide { - slide_id: String, - notes: NotesState, - background_fill: Option, - layout_id: Option, - elements: Vec, -} - -struct ImportedPicture { - relationship_id: String, - frame: Rect, - crop: Option, - alt_text: Option, - rotation_degrees: Option, - flip_horizontal: bool, - flip_vertical: bool, - lock_aspect_ratio: bool, -} - -fn import_pptx_images( - path: &Path, - document: &mut PresentationDocument, - action: &str, -) -> Result<(), PresentationArtifactError> { - let file = - std::fs::File::open(path).map_err(|error| PresentationArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - let mut archive = - ZipArchive::new(file).map_err(|error| PresentationArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - for slide_index in 0..document.slides.len() { - let slide_number = slide_index + 1; - let slide_xml_path = format!("ppt/slides/slide{slide_number}.xml"); - let Some(slide_xml) = - zip_entry_string_if_exists(&mut archive, &slide_xml_path).map_err(|message| { - PresentationArtifactError::ImportFailed { - path: path.to_path_buf(), - message, - } - })? - else { - continue; - }; - let pictures = parse_imported_pictures(&slide_xml); - if pictures.is_empty() { - continue; - } - let relationships = zip_entry_string_if_exists( - &mut archive, - &format!("ppt/slides/_rels/slide{slide_number}.xml.rels"), - ) - .map_err(|message| PresentationArtifactError::ImportFailed { - path: path.to_path_buf(), - message, - })? - .map(|xml| parse_slide_image_relationship_targets(&xml)) - .unwrap_or_default(); - let mut imported_images = Vec::new(); - for picture in pictures { - let Some(target) = relationships.get(&picture.relationship_id) else { - continue; - }; - let media_path = resolve_zip_relative_path(&slide_xml_path, target); - let Some(bytes) = - zip_entry_bytes_if_exists(&mut archive, &media_path).map_err(|message| { - PresentationArtifactError::ImportFailed { - path: path.to_path_buf(), - message, - } - })? - else { - continue; - }; - let Some(filename) = Path::new(&media_path) - .file_name() - .and_then(|name| name.to_str()) - .map(str::to_owned) - else { - continue; - }; - let Ok(payload) = build_image_payload(bytes, filename, action) else { - continue; - }; - imported_images.push(ImageElement { - element_id: document.next_element_id(), - frame: picture.frame, - payload: Some(payload), - fit_mode: ImageFitMode::Stretch, - crop: picture.crop, - rotation_degrees: picture.rotation_degrees, - flip_horizontal: picture.flip_horizontal, - flip_vertical: picture.flip_vertical, - lock_aspect_ratio: picture.lock_aspect_ratio, - alt_text: picture.alt_text, - prompt: None, - is_placeholder: false, - placeholder: None, - z_order: 0, - }); - } - let slide = &mut document.slides[slide_index]; - for mut image in imported_images { - image.z_order = slide.elements.len(); - slide.elements.push(PresentationElement::Image(image)); - } - } - Ok(()) -} - -fn zip_entry_string_if_exists( - archive: &mut ZipArchive, - path: &str, -) -> Result, String> { - let Some(bytes) = zip_entry_bytes_if_exists(archive, path)? else { - return Ok(None); - }; - String::from_utf8(bytes) - .map(Some) - .map_err(|error| format!("zip entry `{path}` is not valid UTF-8: {error}")) -} - -fn zip_entry_bytes_if_exists( - archive: &mut ZipArchive, - path: &str, -) -> Result>, String> { - match archive.by_name(path) { - Ok(mut entry) => { - let mut bytes = Vec::new(); - entry - .read_to_end(&mut bytes) - .map_err(|error| format!("failed to read zip entry `{path}`: {error}"))?; - Ok(Some(bytes)) - } - Err(zip::result::ZipError::FileNotFound) => Ok(None), - Err(error) => Err(format!("failed to open zip entry `{path}`: {error}")), - } -} - -fn parse_imported_pictures(slide_xml: &str) -> Vec { - let mut pictures = Vec::new(); - let mut remaining = slide_xml; - while let Some(start) = remaining.find("") { - let block_start = start; - let Some(block_end_offset) = remaining[block_start..].find("") else { - break; - }; - let block_end = block_start + block_end_offset + "".len(); - let block = &remaining[block_start..block_end]; - remaining = &remaining[block_end..]; - - let Some(relationship_id) = xml_tag_attribute(block, "().unwrap_or(0.0) / 100_000.0, - xml_tag_attribute(block, "().ok()) - .unwrap_or(0.0) - / 100_000.0, - xml_tag_attribute(block, "().ok()) - .unwrap_or(0.0) - / 100_000.0, - xml_tag_attribute(block, "().ok()) - .unwrap_or(0.0) - / 100_000.0, - ) - }), - alt_text: xml_tag_attribute(block, "().ok()) - .map(|rotation| (rotation as f64 / 60_000.0).round() as i32), - flip_horizontal: xml_tag_attribute(block, " HashMap { - let mut relationships = HashMap::new(); - let mut remaining = rels_xml; - while let Some(start) = remaining.find("") else { - break; - }; - let tag_end = tag_start + tag_end_offset + 2; - let tag = &remaining[tag_start..tag_end]; - remaining = &remaining[tag_end..]; - if xml_attribute(tag, "Type").as_deref() - != Some("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") - { - continue; - } - let (Some(id), Some(target)) = (xml_attribute(tag, "Id"), xml_attribute(tag, "Target")) - else { - continue; - }; - relationships.insert(id, target); - } - relationships -} - -fn resolve_zip_relative_path(base_path: &str, target: &str) -> String { - let mut components = Path::new(base_path) - .parent() - .into_iter() - .flat_map(Path::components) - .filter_map(|component| match component { - std::path::Component::Normal(value) => Some(value.to_string_lossy().to_string()), - std::path::Component::CurDir => None, - std::path::Component::ParentDir => None, - std::path::Component::RootDir | std::path::Component::Prefix(_) => None, - }) - .collect::>(); - for component in Path::new(target).components() { - match component { - std::path::Component::Normal(value) => { - components.push(value.to_string_lossy().to_string()) - } - std::path::Component::ParentDir => { - components.pop(); - } - std::path::Component::CurDir => {} - std::path::Component::RootDir | std::path::Component::Prefix(_) => { - components.clear(); - } - } - } - components.join("/") -} - -fn xml_tag_attribute(xml: &str, tag_start: &str, attribute: &str) -> Option { - let start = xml.find(tag_start)?; - let tag = &xml[start..start + xml[start..].find('>')?]; - xml_attribute(tag, attribute) -} - -fn xml_attribute(tag: &str, attribute: &str) -> Option { - let pattern = format!(r#"{attribute}=""#); - let start = tag.find(&pattern)? + pattern.len(); - let end = start + tag[start..].find('"')?; - Some( - tag[start..end] - .replace(""", "\"") - .replace("'", "'") - .replace("<", "<") - .replace(">", ">") - .replace("&", "&"), - ) -} - -impl PresentationSlide { - fn to_ppt_rs(&self, slide_size: Rect) -> SlideContent { - let mut content = SlideContent::new("").layout(SlideLayout::Blank); - if self.notes.visible && !self.notes.text.is_empty() { - content = content.notes(&self.notes.text); - } - - if let Some(background_fill) = &self.background_fill { - content = content.add_shape( - Shape::new( - ShapeType::Rectangle, - 0, - 0, - points_to_emu(slide_size.width), - points_to_emu(slide_size.height), - ) - .with_fill(ShapeFill::new(background_fill)), - ); - } - - let mut ordered = self.elements.clone(); - ordered.sort_by_key(PresentationElement::z_order); - let mut hyperlink_seq = 1_u32; - for element in ordered { - match element { - PresentationElement::Text(text) => { - let mut shape = Shape::new( - ShapeType::Rectangle, - points_to_emu(text.frame.left), - points_to_emu(text.frame.top), - points_to_emu(text.frame.width), - points_to_emu(text.frame.height), - ) - .with_text(&text.text); - if let Some(fill) = text.fill { - shape = shape.with_fill(ShapeFill::new(&fill)); - } - if let Some(hyperlink) = &text.hyperlink { - let relationship_id = format!("rIdHyperlink{hyperlink_seq}"); - hyperlink_seq += 1; - shape = shape.with_hyperlink(hyperlink.to_ppt_rs(&relationship_id)); - } - content = content.add_shape(shape); - } - PresentationElement::Shape(shape) => { - let mut ppt_shape = Shape::new( - shape.geometry.to_ppt_rs(), - points_to_emu(shape.frame.left), - points_to_emu(shape.frame.top), - points_to_emu(shape.frame.width), - points_to_emu(shape.frame.height), - ); - if let Some(text) = shape.text { - ppt_shape = ppt_shape.with_text(&text); - } - if let Some(fill) = shape.fill { - ppt_shape = ppt_shape.with_fill(ShapeFill::new(&fill)); - } - if let Some(stroke) = shape.stroke { - ppt_shape = ppt_shape - .with_line(ShapeLine::new(&stroke.color, points_to_emu(stroke.width))); - } - if let Some(rotation) = shape.rotation_degrees { - ppt_shape = ppt_shape.with_rotation(rotation); - } - if let Some(hyperlink) = &shape.hyperlink { - let relationship_id = format!("rIdHyperlink{hyperlink_seq}"); - hyperlink_seq += 1; - ppt_shape = ppt_shape.with_hyperlink(hyperlink.to_ppt_rs(&relationship_id)); - } - content = content.add_shape(ppt_shape); - } - PresentationElement::Connector(connector) => { - let mut ppt_connector = Connector::new( - connector.connector_type.to_ppt_rs(), - points_to_emu(connector.start.left), - points_to_emu(connector.start.top), - points_to_emu(connector.end.left), - points_to_emu(connector.end.top), - ) - .with_line( - ConnectorLine::new( - &connector.line.color, - points_to_emu(connector.line.width), - ) - .with_dash(connector.line_style.to_ppt_rs()), - ) - .with_arrow_size(connector.arrow_size.to_ppt_rs()) - .with_start_arrow(connector.start_arrow.to_ppt_rs()) - .with_end_arrow(connector.end_arrow.to_ppt_rs()); - if let Some(label) = connector.label { - ppt_connector = ppt_connector.with_label(&label); - } - content = content.add_connector(ppt_connector); - } - PresentationElement::Image(image) => { - if let Some(ref payload) = image.payload { - let mut ppt_image = Image::from_bytes( - payload.bytes.clone(), - points_to_emu(image.frame.width), - points_to_emu(image.frame.height), - &payload.format, - ) - .position( - points_to_emu(image.frame.left), - points_to_emu(image.frame.top), - ); - if image.fit_mode != ImageFitMode::Stretch { - let (x, y, width, height, crop) = fit_image(&image); - ppt_image = Image::from_bytes( - payload.bytes.clone(), - points_to_emu(width), - points_to_emu(height), - &payload.format, - ) - .position(points_to_emu(x), points_to_emu(y)); - if let Some((left, top, right, bottom)) = crop { - ppt_image = ppt_image.with_crop(left, top, right, bottom); - } - } - if let Some((left, top, right, bottom)) = image.crop { - ppt_image = ppt_image.with_crop(left, top, right, bottom); - } - content = content.add_image(ppt_image); - } else { - let mut placeholder = Shape::new( - ShapeType::Rectangle, - points_to_emu(image.frame.left), - points_to_emu(image.frame.top), - points_to_emu(image.frame.width), - points_to_emu(image.frame.height), - ) - .with_text(image.prompt.as_deref().unwrap_or("Image placeholder")); - if let Some(rotation) = image.rotation_degrees { - placeholder = placeholder.with_rotation(rotation); - } - content = content.add_shape(placeholder); - } - } - PresentationElement::Table(table) => { - let mut builder = TableBuilder::new( - table - .column_widths - .iter() - .copied() - .map(points_to_emu) - .collect(), - ) - .position( - points_to_emu(table.frame.left), - points_to_emu(table.frame.top), - ); - for (row_index, row) in table.rows.into_iter().enumerate() { - let cells = row - .into_iter() - .enumerate() - .map(|(column_index, cell)| { - build_table_cell(cell, &table.merges, row_index, column_index) - }) - .collect::>(); - let mut table_row = TableRow::new(cells); - if let Some(height) = table.row_heights.get(row_index) { - table_row = table_row.with_height(points_to_emu(*height)); - } - builder = builder.add_row(table_row); - } - content = content.table(builder.build()); - } - PresentationElement::Chart(chart) => { - let mut ppt_chart = Chart::new( - chart.title.as_deref().unwrap_or("Chart"), - chart.chart_type.to_ppt_rs(), - chart.categories, - points_to_emu(chart.frame.left), - points_to_emu(chart.frame.top), - points_to_emu(chart.frame.width), - points_to_emu(chart.frame.height), - ); - for series in chart.series { - ppt_chart = - ppt_chart.add_series(ChartSeries::new(&series.name, series.values)); - } - content = content.add_chart(ppt_chart); - } - } - } - content - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -enum PresentationElement { - Text(TextElement), - Shape(ShapeElement), - Connector(ConnectorElement), - Image(ImageElement), - Table(TableElement), - Chart(ChartElement), -} - -impl PresentationElement { - fn element_id(&self) -> &str { - match self { - Self::Text(element) => &element.element_id, - Self::Shape(element) => &element.element_id, - Self::Connector(element) => &element.element_id, - Self::Image(element) => &element.element_id, - Self::Table(element) => &element.element_id, - Self::Chart(element) => &element.element_id, - } - } - - fn set_element_id(&mut self, new_id: String) { - match self { - Self::Text(element) => element.element_id = new_id, - Self::Shape(element) => element.element_id = new_id, - Self::Connector(element) => element.element_id = new_id, - Self::Image(element) => element.element_id = new_id, - Self::Table(element) => element.element_id = new_id, - Self::Chart(element) => element.element_id = new_id, - } - } - - fn kind(&self) -> &'static str { - match self { - Self::Text(_) => "text", - Self::Shape(_) => "shape", - Self::Connector(_) => "connector", - Self::Image(_) => "image", - Self::Table(_) => "table", - Self::Chart(_) => "chart", - } - } - - fn z_order(&self) -> usize { - match self { - Self::Text(element) => element.z_order, - Self::Shape(element) => element.z_order, - Self::Connector(element) => element.z_order, - Self::Image(element) => element.z_order, - Self::Table(element) => element.z_order, - Self::Chart(element) => element.z_order, - } - } - - fn set_z_order(&mut self, z_order: usize) { - match self { - Self::Text(element) => element.z_order = z_order, - Self::Shape(element) => element.z_order = z_order, - Self::Connector(element) => element.z_order = z_order, - Self::Image(element) => element.z_order = z_order, - Self::Table(element) => element.z_order = z_order, - Self::Chart(element) => element.z_order = z_order, - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct TextElement { - element_id: String, - text: String, - frame: Rect, - fill: Option, - style: TextStyle, - hyperlink: Option, - #[serde(default)] - rich_text: RichTextState, - placeholder: Option, - z_order: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct ShapeElement { - element_id: String, - geometry: ShapeGeometry, - frame: Rect, - fill: Option, - stroke: Option, - text: Option, - text_style: TextStyle, - hyperlink: Option, - rich_text: Option, - placeholder: Option, - rotation_degrees: Option, - flip_horizontal: bool, - flip_vertical: bool, - z_order: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct ConnectorElement { - element_id: String, - connector_type: ConnectorKind, - start: PointArgs, - end: PointArgs, - line: StrokeStyle, - line_style: LineStyle, - start_arrow: ConnectorArrowKind, - end_arrow: ConnectorArrowKind, - arrow_size: ConnectorArrowScale, - label: Option, - z_order: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct ImageElement { - pub(crate) element_id: String, - pub(crate) frame: Rect, - pub(crate) payload: Option, - pub(crate) fit_mode: ImageFitMode, - pub(crate) crop: Option, - pub(crate) rotation_degrees: Option, - pub(crate) flip_horizontal: bool, - pub(crate) flip_vertical: bool, - pub(crate) lock_aspect_ratio: bool, - pub(crate) alt_text: Option, - pub(crate) prompt: Option, - pub(crate) is_placeholder: bool, - pub(crate) placeholder: Option, - pub(crate) z_order: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct TableElement { - element_id: String, - frame: Rect, - rows: Vec>, - column_widths: Vec, - row_heights: Vec, - style: Option, - style_options: TableStyleOptions, - borders: Option, - right_to_left: bool, - merges: Vec, - z_order: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct ChartElement { - element_id: String, - frame: Rect, - chart_type: ChartTypeSpec, - categories: Vec, - series: Vec, - title: Option, - style_index: Option, - has_legend: bool, - legend: Option, - x_axis: Option, - y_axis: Option, - data_labels: Option, - chart_fill: Option, - plot_area_fill: Option, - z_order: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct ImagePayload { - pub(crate) bytes: Vec, - pub(crate) format: String, - pub(crate) width_px: u32, - pub(crate) height_px: u32, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct ChartSeriesSpec { - name: String, - values: Vec, - categories: Option>, - x_values: Option>, - fill: Option, - stroke: Option, - marker: Option, - #[serde(default)] - data_label_overrides: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum ShapeGeometry { - Rectangle, - RoundedRectangle, - Ellipse, - Triangle, - RightTriangle, - Diamond, - Pentagon, - Hexagon, - Octagon, - Star4, - Star5, - Star6, - Star8, - RightArrow, - LeftArrow, - UpArrow, - DownArrow, - LeftRightArrow, - UpDownArrow, - Chevron, - Heart, - Cloud, - Wave, - FlowChartProcess, - FlowChartDecision, - FlowChartConnector, - Parallelogram, - Trapezoid, -} - -impl ShapeGeometry { - fn from_shape_type(shape_type: ShapeType) -> Self { - match shape_type { - ShapeType::RoundedRectangle => Self::RoundedRectangle, - ShapeType::Ellipse | ShapeType::Circle => Self::Ellipse, - ShapeType::Triangle => Self::Triangle, - ShapeType::RightTriangle => Self::RightTriangle, - ShapeType::Diamond => Self::Diamond, - ShapeType::Pentagon => Self::Pentagon, - ShapeType::Hexagon => Self::Hexagon, - ShapeType::Octagon => Self::Octagon, - ShapeType::Star4 => Self::Star4, - ShapeType::Star5 => Self::Star5, - ShapeType::Star6 => Self::Star6, - ShapeType::Star8 => Self::Star8, - ShapeType::RightArrow => Self::RightArrow, - ShapeType::LeftArrow => Self::LeftArrow, - ShapeType::UpArrow => Self::UpArrow, - ShapeType::DownArrow => Self::DownArrow, - ShapeType::LeftRightArrow => Self::LeftRightArrow, - ShapeType::UpDownArrow => Self::UpDownArrow, - ShapeType::ChevronArrow => Self::Chevron, - ShapeType::Heart => Self::Heart, - ShapeType::Cloud => Self::Cloud, - ShapeType::Wave => Self::Wave, - ShapeType::FlowChartProcess => Self::FlowChartProcess, - ShapeType::FlowChartDecision => Self::FlowChartDecision, - ShapeType::FlowChartConnector => Self::FlowChartConnector, - ShapeType::Parallelogram => Self::Parallelogram, - ShapeType::Trapezoid => Self::Trapezoid, - _ => Self::Rectangle, - } - } - - fn to_ppt_rs(self) -> ShapeType { - match self { - Self::Rectangle => ShapeType::Rectangle, - Self::RoundedRectangle => ShapeType::RoundedRectangle, - Self::Ellipse => ShapeType::Ellipse, - Self::Triangle => ShapeType::Triangle, - Self::RightTriangle => ShapeType::RightTriangle, - Self::Diamond => ShapeType::Diamond, - Self::Pentagon => ShapeType::Pentagon, - Self::Hexagon => ShapeType::Hexagon, - Self::Octagon => ShapeType::Octagon, - Self::Star4 => ShapeType::Star4, - Self::Star5 => ShapeType::Star5, - Self::Star6 => ShapeType::Star6, - Self::Star8 => ShapeType::Star8, - Self::RightArrow => ShapeType::RightArrow, - Self::LeftArrow => ShapeType::LeftArrow, - Self::UpArrow => ShapeType::UpArrow, - Self::DownArrow => ShapeType::DownArrow, - Self::LeftRightArrow => ShapeType::LeftRightArrow, - Self::UpDownArrow => ShapeType::UpDownArrow, - Self::Chevron => ShapeType::ChevronArrow, - Self::Heart => ShapeType::Heart, - Self::Cloud => ShapeType::Cloud, - Self::Wave => ShapeType::Wave, - Self::FlowChartProcess => ShapeType::FlowChartProcess, - Self::FlowChartDecision => ShapeType::FlowChartDecision, - Self::FlowChartConnector => ShapeType::FlowChartConnector, - Self::Parallelogram => ShapeType::Parallelogram, - Self::Trapezoid => ShapeType::Trapezoid, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum ChartTypeSpec { - Bar, - BarHorizontal, - BarStacked, - BarStacked100, - Line, - LineMarkers, - LineStacked, - Pie, - Doughnut, - Area, - AreaStacked, - AreaStacked100, - Scatter, - ScatterLines, - ScatterSmooth, - Bubble, - Radar, - RadarFilled, - StockHlc, - StockOhlc, - Combo, -} - -impl ChartTypeSpec { - fn to_ppt_rs(self) -> ChartType { - match self { - Self::Bar => ChartType::Bar, - Self::BarHorizontal => ChartType::BarHorizontal, - Self::BarStacked => ChartType::BarStacked, - Self::BarStacked100 => ChartType::BarStacked100, - Self::Line => ChartType::Line, - Self::LineMarkers => ChartType::LineMarkers, - Self::LineStacked => ChartType::LineStacked, - Self::Pie => ChartType::Pie, - Self::Doughnut => ChartType::Doughnut, - Self::Area => ChartType::Area, - Self::AreaStacked => ChartType::AreaStacked, - Self::AreaStacked100 => ChartType::AreaStacked100, - Self::Scatter => ChartType::Scatter, - Self::ScatterLines => ChartType::ScatterLines, - Self::ScatterSmooth => ChartType::ScatterSmooth, - Self::Bubble => ChartType::Bubble, - Self::Radar => ChartType::Radar, - Self::RadarFilled => ChartType::RadarFilled, - Self::StockHlc => ChartType::StockHLC, - Self::StockOhlc => ChartType::StockOHLC, - Self::Combo => ChartType::Combo, - } - } -} - -impl ConnectorKind { - fn to_ppt_rs(self) -> ConnectorType { - match self { - Self::Straight => ConnectorType::Straight, - Self::Elbow => ConnectorType::Elbow, - Self::Curved => ConnectorType::Curved, - } - } -} - -impl ConnectorArrowKind { - fn to_ppt_rs(self) -> ArrowType { - match self { - Self::None => ArrowType::None, - Self::Triangle => ArrowType::Triangle, - Self::Stealth => ArrowType::Stealth, - Self::Diamond => ArrowType::Diamond, - Self::Oval => ArrowType::Oval, - Self::Open => ArrowType::Open, - } - } -} - -impl ConnectorArrowScale { - fn to_ppt_rs(self) -> ArrowSize { - match self { - Self::Small => ArrowSize::Small, - Self::Medium => ArrowSize::Medium, - Self::Large => ArrowSize::Large, - } - } -} - -impl LineStyle { - fn to_ppt_rs(self) -> LineDash { - match self { - Self::Solid => LineDash::Solid, - Self::Dashed => LineDash::Dash, - Self::Dotted => LineDash::Dot, - Self::DashDot => LineDash::DashDot, - Self::DashDotDot => LineDash::DashDotDot, - Self::LongDash => LineDash::LongDash, - Self::LongDashDot => LineDash::LongDashDot, - } - } - - fn to_ppt_xml(self) -> &'static str { - match self { - Self::Solid => "solid", - Self::Dashed => "dash", - Self::Dotted => "dot", - Self::DashDot => "dashDot", - Self::DashDotDot => "dashDotDot", - Self::LongDash => "lgDash", - Self::LongDashDot => "lgDashDot", - } - } - - fn as_api_str(self) -> &'static str { - match self { - Self::Solid => "solid", - Self::Dashed => "dashed", - Self::Dotted => "dotted", - Self::DashDot => "dash-dot", - Self::DashDotDot => "dash-dot-dot", - Self::LongDash => "long-dash", - Self::LongDashDot => "long-dash-dot", - } - } -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "lowercase")] -pub(crate) enum ImageFitMode { - Stretch, - Contain, - Cover, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct StrokeStyle { - color: String, - width: u32, - style: LineStyle, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum ConnectorKind { - Straight, - Elbow, - Curved, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum ConnectorArrowKind { - None, - Triangle, - Stealth, - Diamond, - Oval, - Open, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum ConnectorArrowScale { - Small, - Medium, - Large, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -enum LineStyle { - Solid, - Dashed, - Dotted, - DashDot, - DashDotDot, - LongDash, - LongDashDot, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize)] -pub(crate) struct Rect { - pub(crate) left: u32, - pub(crate) top: u32, - pub(crate) width: u32, - pub(crate) height: u32, -} - -impl Rect { - fn from_emu(left: u32, top: u32, width: u32, height: u32) -> Self { - Self { - left: emu_to_points(left), - top: emu_to_points(top), - width: emu_to_points(width), - height: emu_to_points(height), - } - } -} - -impl From for Rect { - fn from(value: PositionArgs) -> Self { - Self { - left: value.left, - top: value.top, - width: value.width, - height: value.height, - } - } -} - -fn apply_partial_position(rect: Rect, position: PartialPositionArgs) -> Rect { - Rect { - left: position.left.unwrap_or(rect.left), - top: position.top.unwrap_or(rect.top), - width: position.width.unwrap_or(rect.width), - height: position.height.unwrap_or(rect.height), - } -} - -fn apply_partial_position_to_image(image: &ImageElement, position: PartialPositionArgs) -> Rect { - let mut frame = apply_partial_position(image.frame, position.clone()); - if image.lock_aspect_ratio { - let base_ratio = image - .payload - .as_ref() - .map(|payload| payload.width_px as f64 / payload.height_px as f64) - .unwrap_or_else(|| image.frame.width as f64 / image.frame.height as f64); - if let Some(width) = position.width - && position.height.is_none() - { - frame.height = (width as f64 / base_ratio).round() as u32; - } else if let Some(height) = position.height - && position.width.is_none() - { - frame.width = (height as f64 * base_ratio).round() as u32; - } - } - frame -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs b/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs deleted file mode 100644 index efca31a99b..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs +++ /dev/null @@ -1,1273 +0,0 @@ -fn parse_args(action: &str, value: &Value) -> Result -where - T: for<'de> Deserialize<'de>, -{ - serde_json::from_value(value.clone()).map_err(|error| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: error.to_string(), - }) -} - -fn required_artifact_id( - request: &PresentationArtifactRequest, -) -> Result { - request - .artifact_id - .clone() - .ok_or_else(|| PresentationArtifactError::MissingArtifactId { - action: request.action.clone(), - }) -} - -fn is_read_only_action(action: &str) -> bool { - matches!( - action, - "get_summary" - | "list_slides" - | "list_layouts" - | "list_layout_placeholders" - | "list_slide_placeholders" - | "inspect" - | "resolve" - | "to_proto" - | "get_style" - | "describe_styles" - | "record_patch" - ) -} - -fn tracks_history(action: &str) -> bool { - !is_read_only_action(action) - && !matches!( - action, - "export_pptx" | "export_preview" | "undo" | "redo" | "apply_patch" - ) -} - -fn patch_operation_supported(action: &str) -> bool { - tracks_history(action) && !matches!(action, "create" | "import_pptx" | "delete_artifact") -} - -fn resolve_path(cwd: &Path, path: &Path) -> PathBuf { - if path.is_absolute() { - path.to_path_buf() - } else { - cwd.join(path) - } -} - -fn normalize_color( - color: &str, - action: &str, - field: &str, -) -> Result { - normalize_color_with_palette(None, color, action, field) -} - -fn normalize_color_with_document( - document: &PresentationDocument, - color: &str, - action: &str, - field: &str, -) -> Result { - normalize_color_with_palette(Some(&document.theme), color, action, field) -} - -fn normalize_color_with_palette( - theme: Option<&ThemeState>, - color: &str, - action: &str, - field: &str, -) -> Result { - let trimmed = color.trim(); - let normalized = theme - .and_then(|palette| palette.resolve_color(trimmed)) - .unwrap_or_else(|| trimmed.trim_start_matches('#').to_uppercase()); - if normalized.len() != 6 - || !normalized - .chars() - .all(|character| character.is_ascii_hexdigit()) - { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("field `{field}` must be a 6-digit RGB hex color"), - }); - } - Ok(normalized) -} - -fn parse_shape_geometry( - geometry: &str, - action: &str, -) -> Result { - match geometry { - "rectangle" | "rect" => Ok(ShapeGeometry::Rectangle), - "rounded_rectangle" | "roundedRect" => Ok(ShapeGeometry::RoundedRectangle), - "ellipse" | "circle" => Ok(ShapeGeometry::Ellipse), - "triangle" => Ok(ShapeGeometry::Triangle), - "right_triangle" => Ok(ShapeGeometry::RightTriangle), - "diamond" => Ok(ShapeGeometry::Diamond), - "pentagon" => Ok(ShapeGeometry::Pentagon), - "hexagon" => Ok(ShapeGeometry::Hexagon), - "octagon" => Ok(ShapeGeometry::Octagon), - "star4" => Ok(ShapeGeometry::Star4), - "star" | "star5" => Ok(ShapeGeometry::Star5), - "star6" => Ok(ShapeGeometry::Star6), - "star8" => Ok(ShapeGeometry::Star8), - "right_arrow" => Ok(ShapeGeometry::RightArrow), - "left_arrow" => Ok(ShapeGeometry::LeftArrow), - "up_arrow" => Ok(ShapeGeometry::UpArrow), - "down_arrow" => Ok(ShapeGeometry::DownArrow), - "left_right_arrow" | "leftRightArrow" => Ok(ShapeGeometry::LeftRightArrow), - "up_down_arrow" | "upDownArrow" => Ok(ShapeGeometry::UpDownArrow), - "chevron" => Ok(ShapeGeometry::Chevron), - "heart" => Ok(ShapeGeometry::Heart), - "cloud" => Ok(ShapeGeometry::Cloud), - "wave" => Ok(ShapeGeometry::Wave), - "flowChartProcess" | "flow_chart_process" => Ok(ShapeGeometry::FlowChartProcess), - "flowChartDecision" | "flow_chart_decision" => Ok(ShapeGeometry::FlowChartDecision), - "flowChartConnector" | "flow_chart_connector" => Ok(ShapeGeometry::FlowChartConnector), - "parallelogram" => Ok(ShapeGeometry::Parallelogram), - "trapezoid" => Ok(ShapeGeometry::Trapezoid), - _ => Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("geometry `{geometry}` is not supported"), - }), - } -} - -fn parse_chart_type( - chart_type: &str, - action: &str, -) -> Result { - match chart_type { - "bar" => Ok(ChartTypeSpec::Bar), - "bar_horizontal" => Ok(ChartTypeSpec::BarHorizontal), - "bar_stacked" => Ok(ChartTypeSpec::BarStacked), - "bar_stacked_100" => Ok(ChartTypeSpec::BarStacked100), - "line" => Ok(ChartTypeSpec::Line), - "line_markers" => Ok(ChartTypeSpec::LineMarkers), - "line_stacked" => Ok(ChartTypeSpec::LineStacked), - "pie" => Ok(ChartTypeSpec::Pie), - "doughnut" => Ok(ChartTypeSpec::Doughnut), - "area" => Ok(ChartTypeSpec::Area), - "area_stacked" => Ok(ChartTypeSpec::AreaStacked), - "area_stacked_100" => Ok(ChartTypeSpec::AreaStacked100), - "scatter" => Ok(ChartTypeSpec::Scatter), - "scatter_lines" => Ok(ChartTypeSpec::ScatterLines), - "scatter_smooth" => Ok(ChartTypeSpec::ScatterSmooth), - "bubble" => Ok(ChartTypeSpec::Bubble), - "radar" => Ok(ChartTypeSpec::Radar), - "radar_filled" => Ok(ChartTypeSpec::RadarFilled), - "stock_hlc" => Ok(ChartTypeSpec::StockHlc), - "stock_ohlc" => Ok(ChartTypeSpec::StockOhlc), - "combo" => Ok(ChartTypeSpec::Combo), - _ => Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("chart_type `{chart_type}` is not supported"), - }), - } -} - -fn parse_chart_marker(marker: Option) -> ChartMarkerStyle { - marker - .map(|marker| ChartMarkerStyle { - symbol: marker.symbol, - size: marker.size, - }) - .unwrap_or_default() -} - -fn parse_chart_data_labels( - document: &PresentationDocument, - data_labels: Option, - action: &str, -) -> Result, PresentationArtifactError> { - data_labels - .map(|data_labels| { - Ok(ChartDataLabels { - show_value: data_labels.show_value.unwrap_or(false), - show_category_name: data_labels.show_category_name.unwrap_or(false), - show_leader_lines: data_labels.show_leader_lines.unwrap_or(false), - position: data_labels.position, - text_style: normalize_text_style_with_document( - document, - &data_labels.text_style, - action, - )?, - }) - }) - .transpose() -} - -fn parse_chart_series( - document: &PresentationDocument, - series: Vec, - action: &str, -) -> Result, PresentationArtifactError> { - series - .into_iter() - .map(|entry| { - if entry.values.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("series `{}` must contain at least one value", entry.name), - }); - } - let fill = entry - .fill - .as_deref() - .map(|value| normalize_color_with_document(document, value, action, "series.fill")) - .transpose()?; - let stroke = entry - .stroke - .map(|stroke| { - Ok(StrokeStyle { - color: normalize_color_with_document( - document, - &stroke.color, - action, - "series.stroke.color", - )?, - width: stroke.width, - style: stroke - .style - .as_deref() - .map(|value| parse_line_style(value, action)) - .transpose()? - .unwrap_or(LineStyle::Solid), - }) - }) - .transpose()?; - let data_label_overrides = entry - .data_label_overrides - .unwrap_or_default() - .into_iter() - .map(|override_args| { - Ok(ChartDataLabelOverride { - idx: override_args.idx as usize, - text: override_args.text, - position: override_args.position, - text_style: normalize_text_style_with_document( - document, - &override_args.text_style, - action, - )?, - fill: override_args - .fill - .as_deref() - .map(|value| { - normalize_color_with_document(document, value, action, "fill") - }) - .transpose()?, - stroke: override_args - .stroke - .map(|stroke| { - Ok(StrokeStyle { - color: normalize_color_with_document( - document, - &stroke.color, - action, - "stroke.color", - )?, - width: stroke.width, - style: stroke - .style - .as_deref() - .map(|value| parse_line_style(value, action)) - .transpose()? - .unwrap_or(LineStyle::Solid), - }) - }) - .transpose()?, - }) - }) - .collect::, _>>()?; - Ok(ChartSeriesSpec { - name: entry.name, - values: entry.values, - categories: entry.categories, - x_values: entry.x_values, - fill, - stroke, - marker: Some(parse_chart_marker(entry.marker)), - data_label_overrides, - }) - }) - .collect() -} - -fn parse_stroke( - document: &PresentationDocument, - stroke: Option, - action: &str, -) -> Result, PresentationArtifactError> { - stroke - .map(|value| parse_required_stroke(document, value, action)) - .transpose() -} - -fn parse_required_stroke( - document: &PresentationDocument, - stroke: StrokeArgs, - action: &str, -) -> Result { - Ok(StrokeStyle { - color: normalize_color_with_document(document, &stroke.color, action, "stroke.color")?, - width: stroke.width, - style: stroke - .style - .as_deref() - .map(|style| parse_line_style(style, action)) - .transpose()? - .unwrap_or(LineStyle::Solid), - }) -} - -fn parse_connector_kind( - connector_type: &str, - action: &str, -) -> Result { - match connector_type { - "straight" => Ok(ConnectorKind::Straight), - "elbow" => Ok(ConnectorKind::Elbow), - "curved" => Ok(ConnectorKind::Curved), - _ => Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("connector_type `{connector_type}` is not supported"), - }), - } -} - -fn parse_connector_arrow( - value: &str, - action: &str, -) -> Result { - match value { - "none" => Ok(ConnectorArrowKind::None), - "triangle" => Ok(ConnectorArrowKind::Triangle), - "stealth" => Ok(ConnectorArrowKind::Stealth), - "diamond" => Ok(ConnectorArrowKind::Diamond), - "oval" => Ok(ConnectorArrowKind::Oval), - "open" => Ok(ConnectorArrowKind::Open), - _ => Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("connector arrow `{value}` is not supported"), - }), - } -} - -fn parse_connector_arrow_size( - value: &str, - action: &str, -) -> Result { - match value { - "small" => Ok(ConnectorArrowScale::Small), - "medium" => Ok(ConnectorArrowScale::Medium), - "large" => Ok(ConnectorArrowScale::Large), - _ => Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("connector arrow_size `{value}` is not supported"), - }), - } -} - -fn parse_line_style(value: &str, action: &str) -> Result { - match value { - "solid" => Ok(LineStyle::Solid), - "dashed" => Ok(LineStyle::Dashed), - "dotted" => Ok(LineStyle::Dotted), - "dash-dot" | "dash_dot" => Ok(LineStyle::DashDot), - "dash-dot-dot" | "dash_dot_dot" => Ok(LineStyle::DashDotDot), - "long-dash" | "long_dash" => Ok(LineStyle::LongDash), - "long-dash-dot" | "long_dash_dot" => Ok(LineStyle::LongDashDot), - _ => Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("line style `{value}` is not supported"), - }), - } -} - -fn parse_connector_line( - document: &PresentationDocument, - line: Option, - action: &str, -) -> Result { - let line = line.unwrap_or_default(); - Ok(ParsedConnectorLine { - color: line - .color - .as_deref() - .map(|value| normalize_color_with_document(document, value, action, "line.color")) - .transpose()? - .unwrap_or_else(|| "000000".to_string()), - width: line.width.unwrap_or(1), - style: line - .style - .as_deref() - .map(|value| parse_line_style(value, action)) - .transpose()? - .unwrap_or(LineStyle::Solid), - }) -} - -struct ParsedConnectorLine { - color: String, - width: u32, - style: LineStyle, -} - -fn normalize_text_style_with_document( - document: &PresentationDocument, - styling: &TextStylingArgs, - action: &str, -) -> Result { - normalize_text_style_with_palette(Some(&document.theme), styling, action, |style_name| { - document.resolve_named_text_style(style_name, action) - }) -} - -fn normalize_text_layout( - layout: &TextLayoutArgs, - action: &str, -) -> Result { - let wrap = layout - .wrap - .as_deref() - .map(|value| match value { - "square" => Ok(TextWrapMode::Square), - "none" => Ok(TextWrapMode::None), - _ => Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("unsupported wrap `{value}`"), - }), - }) - .transpose()?; - let auto_fit = layout - .auto_fit - .as_deref() - .map(|value| match value { - "none" => Ok(TextAutoFitMode::None), - "shrinkText" | "shrink_text" => Ok(TextAutoFitMode::ShrinkText), - "resizeShapeToFitText" | "resize_shape_to_fit_text" => { - Ok(TextAutoFitMode::ResizeShapeToFitText) - } - _ => Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("unsupported auto_fit `{value}`"), - }), - }) - .transpose()?; - let vertical_alignment = layout - .vertical_alignment - .as_deref() - .map(|value| match value { - "top" => Ok(TextVerticalAlignment::Top), - "middle" | "center" => Ok(TextVerticalAlignment::Middle), - "bottom" => Ok(TextVerticalAlignment::Bottom), - _ => Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("unsupported vertical_alignment `{value}`"), - }), - }) - .transpose()?; - Ok(TextLayoutState { - insets: layout.insets.as_ref().map(|insets| TextInsets { - left: insets.left, - right: insets.right, - top: insets.top, - bottom: insets.bottom, - }), - wrap, - auto_fit, - vertical_alignment, - }) -} - -fn normalize_rich_text_input( - document: &PresentationDocument, - input: RichTextInput, - action: &str, -) -> Result<(String, RichTextState), PresentationArtifactError> { - let mut text = String::new(); - let mut ranges = Vec::new(); - let paragraphs = match input { - RichTextInput::Plain(value) => vec![RichParagraphInput::Plain(value)], - RichTextInput::Paragraphs(paragraphs) => paragraphs, - }; - for (paragraph_index, paragraph) in paragraphs.into_iter().enumerate() { - if paragraph_index > 0 { - text.push('\n'); - } - let paragraph_start = text.chars().count(); - match paragraph { - RichParagraphInput::Plain(value) => text.push_str(&value), - RichParagraphInput::Runs(runs) => { - for run in runs { - match run { - RichRunInput::Plain(value) => text.push_str(&value), - RichRunInput::Styled(value) => { - let start_cp = text.chars().count(); - text.push_str(&value.run); - let length = value.run.chars().count(); - let style = normalize_text_style_with_document( - document, - &value.text_style, - action, - )?; - let hyperlink = value - .link - .as_ref() - .map(|link| parse_rich_text_link(link, action)) - .transpose()?; - if length > 0 - && (!text_style_is_empty(&style) || hyperlink.is_some()) - { - ranges.push(TextRangeAnnotation { - range_id: format!("inline_{paragraph_index}_{start_cp}"), - start_cp, - length, - style, - hyperlink, - spacing_before: None, - spacing_after: None, - line_spacing: None, - }); - } - } - } - } - } - } - let paragraph_len = text.chars().count() - paragraph_start; - if paragraph_len == 0 { - continue; - } - } - Ok(( - text, - RichTextState { - ranges, - layout: TextLayoutState::default(), - }, - )) -} - -fn parse_rich_text_link( - link: &RichTextLinkInput, - action: &str, -) -> Result { - let uri = link - .uri - .as_ref() - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`link.uri` is required".to_string(), - })?; - let target = if link.is_external.unwrap_or(true) { - HyperlinkTarget::Url(uri.clone()) - } else { - HyperlinkTarget::File(uri.clone()) - }; - Ok(HyperlinkState { - target, - tooltip: None, - highlight_click: true, - }) -} - -fn text_style_is_empty(style: &TextStyle) -> bool { - style.style_name.is_none() - && style.font_size.is_none() - && style.font_family.is_none() - && style.color.is_none() - && style.alignment.is_none() - && !style.bold - && !style.italic - && !style.underline -} - -fn resolve_text_range_selector( - text: &str, - query: Option<&str>, - occurrence: Option, - start_cp: Option, - length: Option, - action: &str, -) -> Result<(usize, usize, Option), PresentationArtifactError> { - if let Some(query) = query { - let occurrence = occurrence.unwrap_or(0); - let haystack = text.chars().collect::>(); - let needle = query.chars().collect::>(); - if needle.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`query` must not be empty".to_string(), - }); - } - let mut matches = Vec::new(); - for start in 0..=haystack.len().saturating_sub(needle.len()) { - if haystack[start..start + needle.len()] == needle[..] { - matches.push(start); - } - } - let Some(found) = matches.get(occurrence).copied() else { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("query `{query}` occurrence {occurrence} was not found"), - }); - }; - return Ok((found, needle.len(), Some(query.to_string()))); - } - let start_cp = start_cp.ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "provide either `query` or `start_cp`".to_string(), - })?; - let length = length.ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`length` is required with `start_cp`".to_string(), - })?; - if start_cp + length > text.chars().count() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "text range is out of bounds".to_string(), - }); - } - Ok((start_cp, length, None)) -} - -fn normalize_text_style_with_palette( - theme: Option<&ThemeState>, - styling: &TextStylingArgs, - action: &str, - resolve_style_name: impl Fn(&str) -> Result, -) -> Result { - let mut style = styling - .style - .as_deref() - .map(resolve_style_name) - .transpose()? - .unwrap_or_default(); - style.font_size = styling.font_size.or(style.font_size); - style.font_family = styling.font_family.clone().or(style.font_family); - style.color = styling - .color - .as_deref() - .map(|value| normalize_color_with_palette(theme, value, action, "color")) - .transpose()? - .or(style.color); - style.alignment = styling - .alignment - .as_deref() - .map(|value| parse_alignment(value, action)) - .transpose()? - .or(style.alignment); - style.bold = styling.bold.unwrap_or(style.bold); - style.italic = styling.italic.unwrap_or(style.italic); - style.underline = styling.underline.unwrap_or(style.underline); - if let Some(style_name) = &styling.style { - style.style_name = Some(normalize_style_name(style_name, action)?); - } - Ok(style) -} - -fn parse_hyperlink_state( - document: &PresentationDocument, - args: &SetHyperlinkArgs, - action: &str, -) -> Result { - let link_type = - args.link_type - .as_deref() - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`link_type` is required unless `clear` is true".to_string(), - })?; - let target = match link_type { - "url" => HyperlinkTarget::Url(required_hyperlink_field(&args.url, action, "url")?.clone()), - "slide" => { - let slide_index = - args.slide_index - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`slide_index` is required for slide hyperlinks".to_string(), - })?; - if slide_index as usize >= document.slides.len() { - return Err(index_out_of_range( - action, - slide_index as usize, - document.slides.len(), - )); - } - HyperlinkTarget::Slide(slide_index) - } - "first_slide" => HyperlinkTarget::FirstSlide, - "last_slide" => HyperlinkTarget::LastSlide, - "next_slide" => HyperlinkTarget::NextSlide, - "previous_slide" => HyperlinkTarget::PreviousSlide, - "end_show" => HyperlinkTarget::EndShow, - "email" => HyperlinkTarget::Email { - address: required_hyperlink_field(&args.address, action, "address")?.clone(), - subject: args.subject.clone(), - }, - "file" => { - HyperlinkTarget::File(required_hyperlink_field(&args.path, action, "path")?.clone()) - } - other => { - return Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("hyperlink type `{other}` is not supported"), - }); - } - }; - Ok(HyperlinkState { - target, - tooltip: args.tooltip.clone(), - highlight_click: args.highlight_click.unwrap_or(true), - }) -} - -fn required_hyperlink_field<'a>( - value: &'a Option, - action: &str, - field: &str, -) -> Result<&'a String, PresentationArtifactError> { - value - .as_ref() - .filter(|value| !value.trim().is_empty()) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("`{field}` is required for this hyperlink type"), - }) -} - -fn coerce_table_rows( - rows: Vec>, - action: &str, -) -> Result>, PresentationArtifactError> { - if rows.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`rows` must contain at least one row".to_string(), - }); - } - Ok(rows - .into_iter() - .map(|row| { - row.into_iter() - .map(|value| TableCellSpec { - text: cell_value_to_string(value), - text_style: TextStyle::default(), - background_fill: None, - alignment: None, - rich_text: RichTextState::default(), - borders: None, - }) - .collect() - }) - .collect()) -} - -fn parse_table_border( - document: &PresentationDocument, - border: &TableBorderArgs, - action: &str, - field: &str, -) -> Result { - Ok(TableBorder { - color: normalize_color_with_document(document, &border.color, action, field)?, - width: border.width, - }) -} - -fn parse_table_borders( - document: &PresentationDocument, - borders: Option, - action: &str, -) -> Result, PresentationArtifactError> { - borders - .map(|borders| { - Ok(TableBorders { - outside: borders - .outside - .as_ref() - .map(|border| parse_table_border(document, border, action, "borders.outside")) - .transpose()?, - inside: borders - .inside - .as_ref() - .map(|border| parse_table_border(document, border, action, "borders.inside")) - .transpose()?, - top: borders - .top - .as_ref() - .map(|border| parse_table_border(document, border, action, "borders.top")) - .transpose()?, - bottom: borders - .bottom - .as_ref() - .map(|border| parse_table_border(document, border, action, "borders.bottom")) - .transpose()?, - left: borders - .left - .as_ref() - .map(|border| parse_table_border(document, border, action, "borders.left")) - .transpose()?, - right: borders - .right - .as_ref() - .map(|border| parse_table_border(document, border, action, "borders.right")) - .transpose()?, - }) - }) - .transpose() -} - -fn parse_table_style_options(style_options: Option) -> TableStyleOptions { - style_options - .map(|style_options| TableStyleOptions { - header_row: style_options.header_row.unwrap_or(false), - banded_rows: style_options.banded_rows.unwrap_or(false), - banded_columns: style_options.banded_columns.unwrap_or(false), - first_column: style_options.first_column.unwrap_or(false), - last_column: style_options.last_column.unwrap_or(false), - total_row: style_options.total_row.unwrap_or(false), - }) - .unwrap_or_default() -} - -fn normalize_table_dimensions( - rows: &[Vec], - frame: Rect, - column_widths: Option>, - row_heights: Option>, - action: &str, -) -> Result<(Vec, Vec), PresentationArtifactError> { - let column_count = rows.iter().map(std::vec::Vec::len).max().unwrap_or(1); - let normalized_column_widths = match column_widths { - Some(widths) => { - if widths.len() != column_count { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!( - "`column_widths` must contain {column_count} entries for this table" - ), - }); - } - widths - } - None => split_points(frame.width, column_count), - }; - let normalized_row_heights = match row_heights { - Some(heights) => { - if heights.len() != rows.len() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!( - "`row_heights` must contain {} entries for this table", - rows.len() - ), - }); - } - heights - } - None => split_points(frame.height, rows.len()), - }; - Ok((normalized_column_widths, normalized_row_heights)) -} - -fn split_points(total: u32, count: usize) -> Vec { - if count == 0 { - return Vec::new(); - } - let base = total / count as u32; - let remainder = total % count as u32; - (0..count) - .map(|index| base + u32::from(index < remainder as usize)) - .collect() -} - -fn parse_alignment(value: &str, action: &str) -> Result { - match value { - "left" => Ok(TextAlignment::Left), - "center" | "middle" => Ok(TextAlignment::Center), - "right" => Ok(TextAlignment::Right), - "justify" => Ok(TextAlignment::Justify), - _ => Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("unsupported alignment `{value}`"), - }), - } -} - -fn normalize_theme(args: ThemeArgs, action: &str) -> Result { - let color_scheme = args - .color_scheme - .into_iter() - .map(|(key, value)| { - normalize_color(&value, action, &key) - .map(|normalized| (key.to_ascii_lowercase(), normalized)) - }) - .collect::, _>>()?; - Ok(ThemeState { - color_scheme, - major_font: args.major_font, - minor_font: args.minor_font, - }) -} - -fn normalize_style_name( - style_name: &str, - action: &str, -) -> Result { - let normalized_style_name = style_name.trim().to_ascii_lowercase(); - if normalized_style_name.is_empty() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`name` must not be empty".to_string(), - }); - } - Ok(normalized_style_name) -} - -fn built_in_text_styles(theme: &ThemeState) -> HashMap { - ["title", "heading1", "body", "list", "numberedlist"] - .into_iter() - .filter_map(|name| built_in_text_style(theme, name).map(|style| (name.to_string(), style))) - .collect() -} - -fn built_in_text_style(theme: &ThemeState, style_name: &str) -> Option { - let default_color = theme.resolve_color("tx1"); - let default_font = theme - .major_font - .clone() - .or_else(|| theme.minor_font.clone()); - let body_font = theme - .minor_font - .clone() - .or_else(|| theme.major_font.clone()); - let style = match style_name { - "title" => TextStyle { - style_name: Some("title".to_string()), - font_size: Some(28), - font_family: default_font, - color: default_color, - alignment: Some(TextAlignment::Left), - bold: true, - italic: false, - underline: false, - }, - "heading1" => TextStyle { - style_name: Some("heading1".to_string()), - font_size: Some(22), - font_family: default_font, - color: default_color, - alignment: Some(TextAlignment::Left), - bold: true, - italic: false, - underline: false, - }, - "body" => TextStyle { - style_name: Some("body".to_string()), - font_size: Some(14), - font_family: body_font, - color: default_color, - alignment: Some(TextAlignment::Left), - bold: false, - italic: false, - underline: false, - }, - "list" => TextStyle { - style_name: Some("list".to_string()), - font_size: Some(14), - font_family: body_font, - color: default_color, - alignment: Some(TextAlignment::Left), - bold: false, - italic: false, - underline: false, - }, - "numberedlist" => TextStyle { - style_name: Some("numberedlist".to_string()), - font_size: Some(14), - font_family: body_font, - color: default_color, - alignment: Some(TextAlignment::Left), - bold: false, - italic: false, - underline: false, - }, - _ => return None, - }; - Some(style) -} - -fn named_text_style_to_json(style: &NamedTextStyle, id_prefix: &str) -> Value { - serde_json::json!({ - "kind": "textStyle", - "id": format!("{id_prefix}/{}", style.name), - "name": style.name, - "builtIn": style.built_in, - "style": text_style_to_proto(&style.style), - }) -} - -fn parse_slide_size(value: &Value, action: &str) -> Result { - #[derive(Deserialize)] - struct SlideSizeArgs { - width: u32, - height: u32, - } - - let slide_size: SlideSizeArgs = serde_json::from_value(value.clone()).map_err(|error| { - PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("invalid slide_size: {error}"), - } - })?; - Ok(Rect { - left: 0, - top: 0, - width: slide_size.width, - height: slide_size.height, - }) -} - -fn apply_layout_to_slide( - document: &mut PresentationDocument, - slide: &mut PresentationSlide, - layout_ref: &str, - action: &str, -) -> Result<(), PresentationArtifactError> { - let layout = document.get_layout(layout_ref, action)?.clone(); - let placeholders = resolved_layout_placeholders(document, &layout.layout_id, action)?; - slide.layout_id = Some(layout.layout_id); - for resolved in placeholders { - slide.elements.push(materialize_placeholder_element( - document.next_element_id(), - resolved.definition, - slide.elements.len(), - )); - } - Ok(()) -} - -fn materialize_placeholder_element( - element_id: String, - placeholder: PlaceholderDefinition, - z_order: usize, -) -> PresentationElement { - let placeholder_ref = Some(PlaceholderRef { - name: placeholder.name.clone(), - placeholder_type: placeholder.placeholder_type.clone(), - index: placeholder.index, - }); - if placeholder_is_image(&placeholder.placeholder_type) { - return PresentationElement::Image(ImageElement { - element_id, - frame: placeholder.frame, - payload: None, - fit_mode: ImageFitMode::Stretch, - crop: None, - rotation_degrees: None, - flip_horizontal: false, - flip_vertical: false, - lock_aspect_ratio: true, - alt_text: Some(placeholder.name.clone()), - prompt: placeholder - .text - .clone() - .or_else(|| Some(format!("Image placeholder: {}", placeholder.name))), - is_placeholder: true, - placeholder: placeholder_ref, - z_order, - }); - } - if placeholder.geometry == ShapeGeometry::Rectangle { - PresentationElement::Text(TextElement { - element_id, - text: placeholder.text.unwrap_or_default(), - frame: placeholder.frame, - fill: None, - style: TextStyle::default(), - hyperlink: None, - rich_text: RichTextState::default(), - placeholder: placeholder_ref, - z_order, - }) - } else { - PresentationElement::Shape(ShapeElement { - element_id, - geometry: placeholder.geometry, - frame: placeholder.frame, - fill: None, - stroke: None, - text: placeholder.text, - text_style: TextStyle::default(), - hyperlink: None, - rich_text: None, - placeholder: placeholder_ref, - rotation_degrees: None, - flip_horizontal: false, - flip_vertical: false, - z_order, - }) - } -} - -fn resolved_layout_placeholders( - document: &PresentationDocument, - layout_id: &str, - action: &str, -) -> Result, PresentationArtifactError> { - let mut lineage = Vec::new(); - collect_layout_lineage( - document, - layout_id, - action, - &mut HashSet::new(), - &mut lineage, - )?; - let mut resolved: Vec = Vec::new(); - for layout in lineage { - for placeholder in &layout.placeholders { - if let Some(index) = resolved.iter().position(|entry| { - placeholder_key(&entry.definition) == placeholder_key(placeholder) - }) { - resolved[index] = ResolvedPlaceholder { - source_layout_id: layout.layout_id.clone(), - definition: placeholder.clone(), - }; - } else { - resolved.push(ResolvedPlaceholder { - source_layout_id: layout.layout_id.clone(), - definition: placeholder.clone(), - }); - } - } - } - Ok(resolved) -} - -fn collect_layout_lineage<'a>( - document: &'a PresentationDocument, - layout_id: &str, - action: &str, - seen: &mut HashSet, - lineage: &mut Vec<&'a LayoutDocument>, -) -> Result<(), PresentationArtifactError> { - if !seen.insert(layout_id.to_string()) { - return Err(PresentationArtifactError::UnsupportedFeature { - action: action.to_string(), - message: format!("layout inheritance cycle detected at `{layout_id}`"), - }); - } - let layout = document.get_layout(layout_id, action)?; - if let Some(parent_layout_id) = &layout.parent_layout_id { - collect_layout_lineage(document, parent_layout_id, action, seen, lineage)?; - } - lineage.push(layout); - Ok(()) -} - -fn placeholder_key(placeholder: &PlaceholderDefinition) -> (String, String, Option) { - ( - placeholder.name.to_ascii_lowercase(), - placeholder.placeholder_type.to_ascii_lowercase(), - placeholder.index, - ) -} - -fn layout_placeholder_list( - document: &PresentationDocument, - layout_id: &str, - action: &str, -) -> Result, PresentationArtifactError> { - resolved_layout_placeholders(document, layout_id, action).map(|placeholders| { - placeholders - .into_iter() - .map(|placeholder| PlaceholderListEntry { - scope: "layout".to_string(), - source_layout_id: Some(placeholder.source_layout_id), - slide_index: None, - element_id: None, - name: placeholder.definition.name, - placeholder_type: placeholder.definition.placeholder_type, - index: placeholder.definition.index, - geometry: Some(format!("{:?}", placeholder.definition.geometry)), - text_preview: placeholder.definition.text, - }) - .collect() - }) -} - -fn placeholder_is_image(placeholder_type: &str) -> bool { - matches!( - placeholder_type.to_ascii_lowercase().as_str(), - "image" | "picture" | "pic" | "photo" - ) -} - -fn slide_placeholder_list( - slide: &PresentationSlide, - slide_index: usize, -) -> Vec { - slide - .elements - .iter() - .filter_map(|element| match element { - PresentationElement::Text(text) => { - text.placeholder - .as_ref() - .map(|placeholder| PlaceholderListEntry { - scope: "slide".to_string(), - source_layout_id: slide.layout_id.clone(), - slide_index: Some(slide_index), - element_id: Some(text.element_id.clone()), - name: placeholder.name.clone(), - placeholder_type: placeholder.placeholder_type.clone(), - index: placeholder.index, - geometry: Some("Rectangle".to_string()), - text_preview: Some(text.text.clone()), - }) - } - PresentationElement::Shape(shape) => { - shape - .placeholder - .as_ref() - .map(|placeholder| PlaceholderListEntry { - scope: "slide".to_string(), - source_layout_id: slide.layout_id.clone(), - slide_index: Some(slide_index), - element_id: Some(shape.element_id.clone()), - name: placeholder.name.clone(), - placeholder_type: placeholder.placeholder_type.clone(), - index: placeholder.index, - geometry: Some(format!("{:?}", shape.geometry)), - text_preview: shape.text.clone(), - }) - } - PresentationElement::Image(image) => { - image - .placeholder - .as_ref() - .map(|placeholder| PlaceholderListEntry { - scope: "slide".to_string(), - source_layout_id: slide.layout_id.clone(), - slide_index: Some(slide_index), - element_id: Some(image.element_id.clone()), - name: placeholder.name.clone(), - placeholder_type: placeholder.placeholder_type.clone(), - index: placeholder.index, - geometry: Some("Image".to_string()), - text_preview: image.prompt.clone(), - }) - } - PresentationElement::Connector(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => None, - }) - .collect() -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs b/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs deleted file mode 100644 index a06abc7017..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs +++ /dev/null @@ -1,951 +0,0 @@ -const CODEX_METADATA_ENTRY: &str = "ppt/codex-document.json"; - -fn import_codex_metadata_document(path: &Path) -> Result, String> { - let file = std::fs::File::open(path).map_err(|error| error.to_string())?; - let mut archive = ZipArchive::new(file).map_err(|error| error.to_string())?; - let mut entry = match archive.by_name(CODEX_METADATA_ENTRY) { - Ok(entry) => entry, - Err(zip::result::ZipError::FileNotFound) => return Ok(None), - Err(error) => return Err(error.to_string()), - }; - let mut bytes = Vec::new(); - entry.read_to_end(&mut bytes) - .map_err(|error| error.to_string())?; - serde_json::from_slice(&bytes) - .map(Some) - .map_err(|error| error.to_string()) -} - -fn build_pptx_bytes(document: &PresentationDocument, action: &str) -> Result, String> { - let bytes = document - .to_ppt_rs() - .build() - .map_err(|error| format!("{action}: {error}"))?; - patch_pptx_package(bytes, document).map_err(|error| format!("{action}: {error}")) -} - -struct SlideImageAsset { - xml: String, - relationship_xml: String, - media_path: String, - media_bytes: Vec, - extension: String, -} - -fn normalized_image_extension(format: &str) -> String { - match format.to_ascii_lowercase().as_str() { - "jpeg" => "jpg".to_string(), - other => other.to_string(), - } -} - -fn image_relationship_xml(relationship_id: &str, target: &str) -> String { - format!( - r#""#, - ppt_rs::escape_xml(target) - ) -} - -fn image_picture_xml( - image: &ImageElement, - shape_id: usize, - relationship_id: &str, - frame: Rect, - crop: Option, -) -> String { - let blip_fill = if let Some((crop_left, crop_top, crop_right, crop_bottom)) = crop { - format!( - r#" - - - - - -"#, - (crop_left * 100_000.0).round() as u32, - (crop_top * 100_000.0).round() as u32, - (crop_right * 100_000.0).round() as u32, - (crop_bottom * 100_000.0).round() as u32, - ) - } else { - format!( - r#" - - - - -"# - ) - }; - let descr = image - .alt_text - .as_deref() - .map(|alt| format!(r#" descr="{}""#, ppt_rs::escape_xml(alt))) - .unwrap_or_default(); - let no_change_aspect = if image.lock_aspect_ratio { 1 } else { 0 }; - let rotation = image - .rotation_degrees - .map(|rotation| format!(r#" rot="{}""#, i64::from(rotation) * 60_000)) - .unwrap_or_default(); - let flip_horizontal = if image.flip_horizontal { - r#" flipH="1""# - } else { - "" - }; - let flip_vertical = if image.flip_vertical { - r#" flipV="1""# - } else { - "" - }; - format!( - r#" - - - - - - - -{blip_fill} - - - - - - - - - -"#, - points_to_emu(frame.left), - points_to_emu(frame.top), - points_to_emu(frame.width), - points_to_emu(frame.height), - ) -} - -fn slide_image_assets( - slide: &PresentationSlide, - next_media_index: &mut usize, -) -> Vec { - let mut ordered = slide.elements.iter().collect::>(); - ordered.sort_by_key(|element| element.z_order()); - let shape_count = ordered - .iter() - .filter(|element| { - matches!( - element, - PresentationElement::Text(_) - | PresentationElement::Shape(_) - | PresentationElement::Image(ImageElement { payload: None, .. }) - ) - }) - .count() - + usize::from(slide.background_fill.is_some()); - let mut image_index = 0_usize; - let mut assets = Vec::new(); - for element in ordered { - let PresentationElement::Image(image) = element else { - continue; - }; - let Some(payload) = &image.payload else { - continue; - }; - let (left, top, width, height, fitted_crop) = if image.fit_mode != ImageFitMode::Stretch { - fit_image(image) - } else { - ( - image.frame.left, - image.frame.top, - image.frame.width, - image.frame.height, - None, - ) - }; - image_index += 1; - let relationship_id = format!("rIdImage{image_index}"); - let extension = normalized_image_extension(&payload.format); - let media_name = format!("image{next_media_index}.{extension}"); - *next_media_index += 1; - assets.push(SlideImageAsset { - xml: image_picture_xml( - image, - 20 + shape_count + image_index - 1, - &relationship_id, - Rect { - left, - top, - width, - height, - }, - image.crop.or(fitted_crop), - ), - relationship_xml: image_relationship_xml( - &relationship_id, - &format!("../media/{media_name}"), - ), - media_path: format!("ppt/media/{media_name}"), - media_bytes: payload.bytes.clone(), - extension, - }); - } - assets -} - -fn patch_pptx_package( - source_bytes: Vec, - document: &PresentationDocument, -) -> Result, String> { - let mut archive = - ZipArchive::new(Cursor::new(source_bytes)).map_err(|error| error.to_string())?; - let mut writer = ZipWriter::new(Cursor::new(Vec::new())); - let mut next_media_index = 1_usize; - let mut pending_slide_relationships = HashMap::new(); - let mut pending_slide_images = HashMap::new(); - let mut pending_media = Vec::new(); - let mut image_extensions = BTreeSet::new(); - for (slide_index, slide) in document.slides.iter().enumerate() { - let slide_number = slide_index + 1; - let images = slide_image_assets(slide, &mut next_media_index); - let mut relationships = slide_hyperlink_relationships(slide); - relationships.extend(images.iter().map(|image| image.relationship_xml.clone())); - if !relationships.is_empty() { - pending_slide_relationships.insert(slide_number, relationships); - } - if !images.is_empty() { - image_extensions.extend(images.iter().map(|image| image.extension.clone())); - pending_media.extend( - images - .iter() - .map(|image| (image.media_path.clone(), image.media_bytes.clone())), - ); - pending_slide_images.insert(slide_number, images); - } - } - - for index in 0..archive.len() { - let mut file = archive.by_index(index).map_err(|error| error.to_string())?; - if file.is_dir() { - continue; - } - let name = file.name().to_string(); - if name == CODEX_METADATA_ENTRY { - continue; - } - let options = file.options(); - let mut bytes = Vec::new(); - file.read_to_end(&mut bytes) - .map_err(|error| error.to_string())?; - writer - .start_file(&name, options) - .map_err(|error| error.to_string())?; - if name == "[Content_Types].xml" { - writer - .write_all(update_content_types_xml(bytes, &image_extensions)?.as_bytes()) - .map_err(|error| error.to_string())?; - continue; - } - if name == "ppt/presentation.xml" { - writer - .write_all( - update_presentation_xml_dimensions(bytes, document.slide_size)?.as_bytes(), - ) - .map_err(|error| error.to_string())?; - continue; - } - if let Some(slide_number) = parse_slide_xml_path(&name) { - writer - .write_all( - update_slide_xml( - bytes, - &document.slides[slide_number - 1], - pending_slide_images - .get(&slide_number) - .map(std::vec::Vec::as_slice) - .unwrap_or(&[]), - )? - .as_bytes(), - ) - .map_err(|error| error.to_string())?; - continue; - } - if let Some(slide_number) = parse_slide_relationships_path(&name) - && let Some(relationships) = pending_slide_relationships.remove(&slide_number) - { - writer - .write_all(update_slide_relationships_xml(bytes, &relationships)?.as_bytes()) - .map_err(|error| error.to_string())?; - continue; - } - writer - .write_all(&bytes) - .map_err(|error| error.to_string())?; - } - - for (slide_number, relationships) in pending_slide_relationships { - writer - .start_file( - format!("ppt/slides/_rels/slide{slide_number}.xml.rels"), - SimpleFileOptions::default(), - ) - .map_err(|error| error.to_string())?; - writer - .write_all(slide_relationships_xml(&relationships).as_bytes()) - .map_err(|error| error.to_string())?; - } - - for (path, bytes) in pending_media { - writer - .start_file(path, SimpleFileOptions::default()) - .map_err(|error| error.to_string())?; - writer - .write_all(&bytes) - .map_err(|error| error.to_string())?; - } - - writer - .start_file(CODEX_METADATA_ENTRY, SimpleFileOptions::default()) - .map_err(|error| error.to_string())?; - writer - .write_all( - &serde_json::to_vec(document).map_err(|error| error.to_string())?, - ) - .map_err(|error| error.to_string())?; - - writer - .finish() - .map_err(|error| error.to_string()) - .map(Cursor::into_inner) -} - -fn update_presentation_xml_dimensions( - existing_bytes: Vec, - slide_size: Rect, -) -> Result { - let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; - let updated = replace_self_closing_xml_tag( - &existing, - "p:sldSz", - &format!( - r#""#, - points_to_emu(slide_size.width), - points_to_emu(slide_size.height) - ), - )?; - replace_self_closing_xml_tag( - &updated, - "p:notesSz", - &format!( - r#""#, - points_to_emu(slide_size.height), - points_to_emu(slide_size.width) - ), - ) -} - -fn replace_self_closing_xml_tag(xml: &str, tag: &str, replacement: &str) -> Result { - let start = xml - .find(&format!("<{tag} ")) - .ok_or_else(|| format!("presentation xml is missing `<{tag} .../>`"))?; - let end = xml[start..] - .find("/>") - .map(|offset| start + offset + 2) - .ok_or_else(|| format!("presentation xml tag `{tag}` is not self-closing"))?; - Ok(format!("{}{replacement}{}", &xml[..start], &xml[end..])) -} - -fn slide_hyperlink_relationships(slide: &PresentationSlide) -> Vec { - let mut ordered = slide.elements.iter().collect::>(); - ordered.sort_by_key(|element| element.z_order()); - let mut hyperlink_index = 1_u32; - let mut relationships = Vec::new(); - for element in ordered { - let Some(hyperlink) = (match element { - PresentationElement::Text(text) => text.hyperlink.as_ref(), - PresentationElement::Shape(shape) => shape.hyperlink.as_ref(), - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => None, - }) else { - continue; - }; - let relationship_id = format!("rIdHyperlink{hyperlink_index}"); - hyperlink_index += 1; - relationships.push(hyperlink.relationship_xml(&relationship_id)); - } - relationships -} - -fn parse_slide_relationships_path(path: &str) -> Option { - path.strip_prefix("ppt/slides/_rels/slide")? - .strip_suffix(".xml.rels")? - .parse::() - .ok() -} - -fn parse_slide_xml_path(path: &str) -> Option { - path.strip_prefix("ppt/slides/slide")? - .strip_suffix(".xml")? - .parse::() - .ok() -} - -fn update_slide_relationships_xml( - existing_bytes: Vec, - relationships: &[String], -) -> Result { - let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; - let injected = relationships.join("\n"); - existing - .contains("") - .then(|| existing.replace("", &format!("{injected}\n"))) - .ok_or_else(|| { - "slide relationships xml is missing a closing ``".to_string() - }) -} - -fn slide_relationships_xml(relationships: &[String]) -> String { - let body = relationships.join("\n"); - format!( - r#" - -{body} -"# - ) -} - -fn update_content_types_xml( - existing_bytes: Vec, - image_extensions: &BTreeSet, -) -> Result { - let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; - if image_extensions.is_empty() { - return Ok(existing); - } - let existing_lower = existing.to_ascii_lowercase(); - let additions = image_extensions - .iter() - .filter(|extension| { - !existing_lower.contains(&format!( - r#"extension="{}""#, - extension.to_ascii_lowercase() - )) - }) - .map(|extension| generate_image_content_type(extension)) - .collect::>(); - if additions.is_empty() { - return Ok(existing); - } - existing - .contains("") - .then(|| existing.replace("", &format!("{}\n", additions.join("\n")))) - .ok_or_else(|| "content types xml is missing a closing ``".to_string()) -} - -fn update_slide_xml( - existing_bytes: Vec, - slide: &PresentationSlide, - slide_images: &[SlideImageAsset], -) -> Result { - let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; - let existing = replace_image_placeholders(existing, slide_images)?; - let existing = apply_shape_block_patches(existing, slide)?; - let table_xml = slide_table_xml(slide); - if table_xml.is_empty() { - return Ok(existing); - } - existing - .contains("") - .then(|| existing.replace("", &format!("{table_xml}\n"))) - .ok_or_else(|| "slide xml is missing a closing ``".to_string()) -} - -fn replace_image_placeholders( - existing: String, - slide_images: &[SlideImageAsset], -) -> Result { - if slide_images.is_empty() { - return Ok(existing); - } - let mut updated = String::with_capacity(existing.len()); - let mut remaining = existing.as_str(); - for image in slide_images { - let marker = remaining - .find("name=\"Image Placeholder: ") - .ok_or_else(|| { - "slide xml is missing an image placeholder block for exported images".to_string() - })?; - let start = remaining[..marker].rfind("").ok_or_else(|| { - "slide xml is missing an opening `` for image placeholder".to_string() - })?; - let end = remaining[marker..] - .find("") - .map(|offset| marker + offset + "".len()) - .ok_or_else(|| { - "slide xml is missing a closing `` for image placeholder".to_string() - })?; - updated.push_str(&remaining[..start]); - updated.push_str(&image.xml); - remaining = &remaining[end..]; - } - updated.push_str(remaining); - Ok(updated) -} - -#[derive(Clone, Copy)] -struct ShapeXmlPatch { - line_style: Option, - flip_horizontal: bool, - flip_vertical: bool, -} - -fn apply_shape_block_patches( - existing: String, - slide: &PresentationSlide, -) -> Result { - let mut patches = Vec::new(); - if slide.background_fill.is_some() { - patches.push(None); - } - let mut ordered = slide.elements.iter().collect::>(); - ordered.sort_by_key(|element| element.z_order()); - for element in ordered { - match element { - PresentationElement::Text(_) => patches.push(None), - PresentationElement::Shape(shape) => patches.push(Some(ShapeXmlPatch { - line_style: shape - .stroke - .as_ref() - .map(|stroke| stroke.style) - .filter(|style| *style != LineStyle::Solid), - flip_horizontal: shape.flip_horizontal, - flip_vertical: shape.flip_vertical, - })), - PresentationElement::Image(ImageElement { payload: None, .. }) => patches.push(None), - PresentationElement::Connector(_) - | PresentationElement::Image(_) - | PresentationElement::Table(_) - | PresentationElement::Chart(_) => {} - } - } - if patches.iter().all(|patch| { - patch.is_none_or(|patch| { - patch.line_style.is_none() && !patch.flip_horizontal && !patch.flip_vertical - }) - }) { - return Ok(existing); - } - - let mut updated = String::with_capacity(existing.len()); - let mut remaining = existing.as_str(); - for patch in patches { - let Some(start) = remaining.find("") else { - return Err("slide xml is missing an expected `` block".to_string()); - }; - let end = remaining[start..] - .find("") - .map(|offset| start + offset + "".len()) - .ok_or_else(|| "slide xml is missing a closing `` block".to_string())?; - updated.push_str(&remaining[..start]); - let block = &remaining[start..end]; - if let Some(patch) = patch { - updated.push_str(&patch_shape_block(block, patch)?); - } else { - updated.push_str(block); - } - remaining = &remaining[end..]; - } - updated.push_str(remaining); - Ok(updated) -} - -fn patch_shape_block(block: &str, patch: ShapeXmlPatch) -> Result { - let block = if let Some(line_style) = patch.line_style { - patch_shape_block_dash(block, line_style)? - } else { - block.to_string() - }; - if patch.flip_horizontal || patch.flip_vertical { - patch_shape_block_flip(&block, patch.flip_horizontal, patch.flip_vertical) - } else { - Ok(block) - } -} - -fn patch_shape_block_dash(block: &str, line_style: LineStyle) -> Result { - let Some(line_start) = block.find("` entry for stroke styling".to_string()); - }; - if let Some(dash_start) = block[line_start..].find("") - .map(|offset| dash_start + offset + 2) - .ok_or_else(|| "shape line dash entry is missing a closing `/>`".to_string())?; - let mut patched = String::with_capacity(block.len() + 32); - patched.push_str(&block[..dash_start]); - patched.push_str(&format!( - r#""#, - line_style.to_ppt_xml() - )); - patched.push_str(&block[dash_end..]); - return Ok(patched); - } - - if let Some(line_end) = block[line_start..].find("") { - let line_end = line_start + line_end; - let mut patched = String::with_capacity(block.len() + 32); - patched.push_str(&block[..line_end]); - patched.push_str(&format!( - r#""#, - line_style.to_ppt_xml() - )); - patched.push_str(&block[line_end..]); - return Ok(patched); - } - - let line_end = block[line_start..] - .find("/>") - .map(|offset| line_start + offset + 2) - .ok_or_else(|| "shape line entry is missing a closing marker".to_string())?; - let line_tag = &block[line_start..line_end - 2]; - let mut patched = String::with_capacity(block.len() + 48); - patched.push_str(&block[..line_start]); - patched.push_str(line_tag); - patched.push('>'); - patched.push_str(&format!( - r#""#, - line_style.to_ppt_xml() - )); - patched.push_str(""); - patched.push_str(&block[line_end..]); - Ok(patched) -} - -fn patch_shape_block_flip( - block: &str, - flip_horizontal: bool, - flip_vertical: bool, -) -> Result { - let Some(xfrm_start) = block.find("` entry for flip styling".to_string()); - }; - let tag_end = block[xfrm_start..] - .find('>') - .map(|offset| xfrm_start + offset) - .ok_or_else(|| "shape transform entry is missing a closing `>`".to_string())?; - let tag = &block[xfrm_start..=tag_end]; - let mut patched_tag = tag.to_string(); - patched_tag = upsert_xml_attribute( - &patched_tag, - "flipH", - if flip_horizontal { "1" } else { "0" }, - ); - patched_tag = - upsert_xml_attribute(&patched_tag, "flipV", if flip_vertical { "1" } else { "0" }); - Ok(format!( - "{}{}{}", - &block[..xfrm_start], - patched_tag, - &block[tag_end + 1..] - )) -} - -fn upsert_xml_attribute(tag: &str, attribute: &str, value: &str) -> String { - let needle = format!(r#"{attribute}=""#); - if let Some(start) = tag.find(&needle) { - let value_start = start + needle.len(); - if let Some(end_offset) = tag[value_start..].find('"') { - let end = value_start + end_offset; - return format!("{}{}{}", &tag[..value_start], value, &tag[end..]); - } - } - let insert_at = tag.len() - 1; - format!(r#"{} {attribute}="{value}""#, &tag[..insert_at]) + &tag[insert_at..] -} - -fn slide_table_xml(slide: &PresentationSlide) -> String { - let mut ordered = slide.elements.iter().collect::>(); - ordered.sort_by_key(|element| element.z_order()); - let mut table_index = 0_usize; - ordered - .into_iter() - .filter_map(|element| { - let PresentationElement::Table(table) = element else { - return None; - }; - table_index += 1; - let rows = table - .rows - .clone() - .into_iter() - .enumerate() - .map(|(row_index, row)| { - let cells = row - .into_iter() - .enumerate() - .map(|(column_index, cell)| { - build_table_cell(cell, &table.merges, row_index, column_index) - }) - .collect::>(); - let mut table_row = TableRow::new(cells); - if let Some(height) = table.row_heights.get(row_index) { - table_row = table_row.with_height(points_to_emu(*height)); - } - Some(table_row) - }) - .collect::>>()?; - Some(ppt_rs::generator::table::generate_table_xml( - &ppt_rs::generator::table::Table::new( - rows, - table - .column_widths - .iter() - .copied() - .map(points_to_emu) - .collect(), - points_to_emu(table.frame.left), - points_to_emu(table.frame.top), - ), - 300 + table_index, - )) - }) - .collect::>() - .join("\n") -} - -fn write_preview_images( - document: &PresentationDocument, - output_dir: &Path, - action: &str, -) -> Result<(), PresentationArtifactError> { - let pptx_path = output_dir.join("preview.pptx"); - let bytes = build_pptx_bytes(document, action).map_err(|message| { - PresentationArtifactError::ExportFailed { - path: pptx_path.clone(), - message, - } - })?; - std::fs::write(&pptx_path, bytes).map_err(|error| PresentationArtifactError::ExportFailed { - path: pptx_path.clone(), - message: error.to_string(), - })?; - render_pptx_to_pngs(&pptx_path, output_dir, action) -} - -fn render_pptx_to_pngs( - pptx_path: &Path, - output_dir: &Path, - action: &str, -) -> Result<(), PresentationArtifactError> { - let soffice_cmd = if cfg!(target_os = "macos") - && Path::new("/Applications/LibreOffice.app/Contents/MacOS/soffice").exists() - { - "/Applications/LibreOffice.app/Contents/MacOS/soffice" - } else { - "soffice" - }; - let conversion = Command::new(soffice_cmd) - .arg("--headless") - .arg("--convert-to") - .arg("pdf") - .arg(pptx_path) - .arg("--outdir") - .arg(output_dir) - .output() - .map_err(|error| PresentationArtifactError::ExportFailed { - path: pptx_path.to_path_buf(), - message: format!("{action}: failed to execute LibreOffice: {error}"), - })?; - if !conversion.status.success() { - return Err(PresentationArtifactError::ExportFailed { - path: pptx_path.to_path_buf(), - message: format!( - "{action}: LibreOffice conversion failed: {}", - String::from_utf8_lossy(&conversion.stderr) - ), - }); - } - - let pdf_path = output_dir.join( - pptx_path - .file_stem() - .and_then(|stem| stem.to_str()) - .map(|stem| format!("{stem}.pdf")) - .ok_or_else(|| PresentationArtifactError::ExportFailed { - path: pptx_path.to_path_buf(), - message: format!("{action}: preview pptx filename is invalid"), - })?, - ); - let prefix = output_dir.join("slide"); - let conversion = Command::new("pdftoppm") - .arg("-png") - .arg(&pdf_path) - .arg(&prefix) - .output() - .map_err(|error| PresentationArtifactError::ExportFailed { - path: pdf_path.clone(), - message: format!("{action}: failed to execute pdftoppm: {error}"), - })?; - std::fs::remove_file(&pdf_path).ok(); - if !conversion.status.success() { - return Err(PresentationArtifactError::ExportFailed { - path: output_dir.to_path_buf(), - message: format!( - "{action}: pdftoppm conversion failed: {}", - String::from_utf8_lossy(&conversion.stderr) - ), - }); - } - Ok(()) -} - -pub(crate) fn write_preview_image( - source_path: &Path, - target_path: &Path, - format: PreviewOutputFormat, - scale: f32, - quality: u8, - action: &str, -) -> Result<(), PresentationArtifactError> { - if matches!(format, PreviewOutputFormat::Png) && scale == 1.0 { - std::fs::rename(source_path, target_path).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: target_path.to_path_buf(), - message: error.to_string(), - } - })?; - return Ok(()); - } - let mut preview = - image::open(source_path).map_err(|error| PresentationArtifactError::ExportFailed { - path: source_path.to_path_buf(), - message: format!("{action}: {error}"), - })?; - if scale != 1.0 { - let width = (preview.width() as f32 * scale).round().max(1.0) as u32; - let height = (preview.height() as f32 * scale).round().max(1.0) as u32; - preview = preview.resize_exact(width, height, FilterType::Lanczos3); - } - let file = std::fs::File::create(target_path).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: target_path.to_path_buf(), - message: error.to_string(), - } - })?; - let mut writer = std::io::BufWriter::new(file); - match format { - PreviewOutputFormat::Png => { - preview - .write_to(&mut writer, ImageFormat::Png) - .map_err(|error| PresentationArtifactError::ExportFailed { - path: target_path.to_path_buf(), - message: format!("{action}: {error}"), - })? - } - PreviewOutputFormat::Jpeg => { - let rgb = preview.to_rgb8(); - let mut encoder = JpegEncoder::new_with_quality(&mut writer, quality); - encoder.encode_image(&rgb).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: target_path.to_path_buf(), - message: format!("{action}: {error}"), - } - })?; - } - PreviewOutputFormat::Svg => { - let mut png_bytes = Cursor::new(Vec::new()); - preview - .write_to(&mut png_bytes, ImageFormat::Png) - .map_err(|error| PresentationArtifactError::ExportFailed { - path: target_path.to_path_buf(), - message: format!("{action}: {error}"), - })?; - let embedded_png = BASE64_STANDARD.encode(png_bytes.into_inner()); - let svg = format!( - r#""#, - preview.width(), - preview.height(), - preview.width(), - preview.height(), - preview.width(), - preview.height(), - ); - writer.write_all(svg.as_bytes()).map_err(|error| { - PresentationArtifactError::ExportFailed { - path: target_path.to_path_buf(), - message: format!("{action}: {error}"), - } - })?; - } - } - std::fs::remove_file(source_path).ok(); - Ok(()) -} - -fn collect_pngs(output_dir: &Path) -> Result, PresentationArtifactError> { - let mut files = std::fs::read_dir(output_dir) - .map_err(|error| PresentationArtifactError::ExportFailed { - path: output_dir.to_path_buf(), - message: error.to_string(), - })? - .filter_map(Result::ok) - .map(|entry| entry.path()) - .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("png")) - .collect::>(); - files.sort(); - Ok(files) -} - -fn parse_preview_output_format( - format: Option<&str>, - path: &Path, - action: &str, -) -> Result { - let value = format - .map(str::to_owned) - .or_else(|| { - path.extension() - .and_then(|extension| extension.to_str()) - .map(str::to_owned) - }) - .unwrap_or_else(|| "png".to_string()); - match value.to_ascii_lowercase().as_str() { - "png" => Ok(PreviewOutputFormat::Png), - "jpg" | "jpeg" => Ok(PreviewOutputFormat::Jpeg), - "svg" => Ok(PreviewOutputFormat::Svg), - other => Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("preview format `{other}` is not supported"), - }), - } -} - -fn normalize_preview_scale( - scale: Option, - action: &str, -) -> Result { - let scale = scale.unwrap_or(1.0); - if !scale.is_finite() || scale <= 0.0 { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`scale` must be a positive number".to_string(), - }); - } - Ok(scale) -} - -fn normalize_preview_quality( - quality: Option, - action: &str, -) -> Result { - let quality = quality.unwrap_or(90); - if quality == 0 || quality > 100 { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "`quality` must be between 1 and 100".to_string(), - }); - } - Ok(quality) -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs b/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs deleted file mode 100644 index 05741303ac..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs +++ /dev/null @@ -1,614 +0,0 @@ -fn document_to_proto( - document: &PresentationDocument, - action: &str, -) -> Result { - let layouts = document - .layouts - .iter() - .map(|layout| layout_to_proto(document, layout, action)) - .collect::, _>>()?; - let slides = document - .slides - .iter() - .enumerate() - .map(|(slide_index, slide)| slide_to_proto(slide, slide_index)) - .collect::>(); - Ok(serde_json::json!({ - "kind": "presentation", - "artifactId": document.artifact_id, - "anchor": format!("pr/{}", document.artifact_id), - "name": document.name, - "slideSize": rect_to_proto(document.slide_size), - "activeSlideIndex": document.active_slide_index, - "activeSlideId": document.active_slide_index.and_then(|index| document.slides.get(index)).map(|slide| slide.slide_id.clone()), - "theme": serde_json::json!({ - "colorScheme": document.theme.color_scheme, - "hexColorMap": document.theme.color_scheme, - "majorFont": document.theme.major_font, - "minorFont": document.theme.minor_font, - }), - "styles": document - .named_text_styles() - .iter() - .map(|style| named_text_style_to_json(style, "st")) - .collect::>(), - "masters": document.layouts.iter().filter(|layout| layout.kind == LayoutKind::Master).map(|layout| layout.layout_id.clone()).collect::>(), - "layouts": layouts, - "slides": slides, - "commentAuthor": document.comment_self.as_ref().map(comment_author_to_proto), - "commentThreads": document - .comment_threads - .iter() - .map(comment_thread_to_proto) - .collect::>(), - })) -} - -fn layout_to_proto( - document: &PresentationDocument, - layout: &LayoutDocument, - action: &str, -) -> Result { - let placeholders = layout - .placeholders - .iter() - .map(placeholder_definition_to_proto) - .collect::>(); - let resolved_placeholders = resolved_layout_placeholders(document, &layout.layout_id, action)? - .into_iter() - .map(|placeholder| { - let mut value = placeholder_definition_to_proto(&placeholder.definition); - value["sourceLayoutId"] = Value::String(placeholder.source_layout_id); - value - }) - .collect::>(); - Ok(serde_json::json!({ - "layoutId": layout.layout_id, - "anchor": format!("ly/{}", layout.layout_id), - "name": layout.name, - "kind": match layout.kind { - LayoutKind::Layout => "layout", - LayoutKind::Master => "master", - }, - "parentLayoutId": layout.parent_layout_id, - "placeholders": placeholders, - "resolvedPlaceholders": resolved_placeholders, - })) -} - -fn placeholder_definition_to_proto(placeholder: &PlaceholderDefinition) -> Value { - serde_json::json!({ - "name": placeholder.name, - "placeholderType": placeholder.placeholder_type, - "index": placeholder.index, - "text": placeholder.text, - "geometry": format!("{:?}", placeholder.geometry), - "frame": rect_to_proto(placeholder.frame), - }) -} - -fn slide_to_proto(slide: &PresentationSlide, slide_index: usize) -> Value { - serde_json::json!({ - "slideId": slide.slide_id, - "anchor": format!("sl/{}", slide.slide_id), - "index": slide_index, - "layoutId": slide.layout_id, - "backgroundFill": slide.background_fill, - "notes": serde_json::json!({ - "anchor": format!("nt/{}", slide.slide_id), - "text": slide.notes.text, - "visible": slide.notes.visible, - "textPreview": slide.notes.text.replace('\n', " | "), - "textChars": slide.notes.text.chars().count(), - "textLines": slide.notes.text.lines().count(), - "richText": rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text), - }), - "elements": slide.elements.iter().map(element_to_proto).collect::>(), - }) -} - -fn element_to_proto(element: &PresentationElement) -> Value { - match element { - PresentationElement::Text(text) => { - let mut record = serde_json::json!({ - "kind": "text", - "elementId": text.element_id, - "anchor": format!("sh/{}", text.element_id), - "frame": rect_to_proto(text.frame), - "text": text.text, - "textPreview": text.text.replace('\n', " | "), - "textChars": text.text.chars().count(), - "textLines": text.text.lines().count(), - "fill": text.fill, - "style": text_style_to_proto(&text.style), - "richText": rich_text_to_proto(&text.text, &text.rich_text), - "zOrder": text.z_order, - }); - if let Some(placeholder) = &text.placeholder { - record["placeholder"] = placeholder_ref_to_proto(placeholder); - } - if let Some(hyperlink) = &text.hyperlink { - record["hyperlink"] = hyperlink.to_json(); - } - record - } - PresentationElement::Shape(shape) => { - let mut record = serde_json::json!({ - "kind": "shape", - "elementId": shape.element_id, - "anchor": format!("sh/{}", shape.element_id), - "geometry": format!("{:?}", shape.geometry), - "frame": rect_to_proto(shape.frame), - "fill": shape.fill, - "stroke": shape.stroke.as_ref().map(stroke_to_proto), - "text": shape.text, - "textStyle": text_style_to_proto(&shape.text_style), - "richText": shape - .text - .as_ref() - .zip(shape.rich_text.as_ref()) - .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) - .unwrap_or(Value::Null), - "rotation": shape.rotation_degrees, - "flipHorizontal": shape.flip_horizontal, - "flipVertical": shape.flip_vertical, - "zOrder": shape.z_order, - }); - if let Some(text) = &shape.text { - record["textPreview"] = Value::String(text.replace('\n', " | ")); - record["textChars"] = Value::from(text.chars().count()); - record["textLines"] = Value::from(text.lines().count()); - } - if let Some(placeholder) = &shape.placeholder { - record["placeholder"] = placeholder_ref_to_proto(placeholder); - } - if let Some(hyperlink) = &shape.hyperlink { - record["hyperlink"] = hyperlink.to_json(); - } - record - } - PresentationElement::Connector(connector) => serde_json::json!({ - "kind": "connector", - "elementId": connector.element_id, - "anchor": format!("cn/{}", connector.element_id), - "connectorType": format!("{:?}", connector.connector_type), - "start": serde_json::json!({ - "left": connector.start.left, - "top": connector.start.top, - "unit": "points", - }), - "end": serde_json::json!({ - "left": connector.end.left, - "top": connector.end.top, - "unit": "points", - }), - "line": stroke_to_proto(&connector.line), - "lineStyle": connector.line_style.as_api_str(), - "startArrow": format!("{:?}", connector.start_arrow), - "endArrow": format!("{:?}", connector.end_arrow), - "arrowSize": format!("{:?}", connector.arrow_size), - "label": connector.label, - "zOrder": connector.z_order, - }), - PresentationElement::Image(image) => { - let mut record = serde_json::json!({ - "kind": "image", - "elementId": image.element_id, - "anchor": format!("im/{}", image.element_id), - "frame": rect_to_proto(image.frame), - "fit": format!("{:?}", image.fit_mode), - "crop": image.crop.map(|(left, top, right, bottom)| serde_json::json!({ - "left": left, - "top": top, - "right": right, - "bottom": bottom, - })), - "rotation": image.rotation_degrees, - "flipHorizontal": image.flip_horizontal, - "flipVertical": image.flip_vertical, - "lockAspectRatio": image.lock_aspect_ratio, - "alt": image.alt_text, - "prompt": image.prompt, - "isPlaceholder": image.is_placeholder, - "payload": image.payload.as_ref().map(image_payload_to_proto), - "zOrder": image.z_order, - }); - if let Some(placeholder) = &image.placeholder { - record["placeholder"] = placeholder_ref_to_proto(placeholder); - } - record - } - PresentationElement::Table(table) => serde_json::json!({ - "kind": "table", - "elementId": table.element_id, - "anchor": format!("tb/{}", table.element_id), - "frame": rect_to_proto(table.frame), - "rows": table.rows.iter().map(|row| { - row.iter().map(table_cell_to_proto).collect::>() - }).collect::>(), - "columnWidths": table.column_widths, - "rowHeights": table.row_heights, - "style": table.style, - "styleOptions": table_style_options_to_proto(&table.style_options), - "borders": table.borders.as_ref().map(table_borders_to_proto), - "rightToLeft": table.right_to_left, - "merges": table.merges.iter().map(|merge| serde_json::json!({ - "startRow": merge.start_row, - "endRow": merge.end_row, - "startColumn": merge.start_column, - "endColumn": merge.end_column, - })).collect::>(), - "zOrder": table.z_order, - }), - PresentationElement::Chart(chart) => serde_json::json!({ - "kind": "chart", - "elementId": chart.element_id, - "anchor": format!("ch/{}", chart.element_id), - "frame": rect_to_proto(chart.frame), - "chartType": format!("{:?}", chart.chart_type), - "title": chart.title, - "categories": chart.categories, - "styleIndex": chart.style_index, - "hasLegend": chart.has_legend, - "legend": chart.legend.as_ref().map(chart_legend_to_proto), - "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), - "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), - "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), - "chartFill": chart.chart_fill, - "plotAreaFill": chart.plot_area_fill, - "series": chart.series.iter().map(|series| serde_json::json!({ - "name": series.name, - "values": series.values, - "categories": series.categories, - "xValues": series.x_values, - "fill": series.fill, - "stroke": series.stroke.as_ref().map(stroke_to_proto), - "marker": series.marker.as_ref().map(chart_marker_to_proto), - "dataLabelOverrides": series - .data_label_overrides - .iter() - .map(chart_data_label_override_to_proto) - .collect::>(), - })).collect::>(), - "zOrder": chart.z_order, - }), - } -} - -fn rect_to_proto(rect: Rect) -> Value { - serde_json::json!({ - "left": rect.left, - "top": rect.top, - "width": rect.width, - "height": rect.height, - "unit": "points", - }) -} - -fn stroke_to_proto(stroke: &StrokeStyle) -> Value { - serde_json::json!({ - "color": stroke.color, - "width": stroke.width, - "style": stroke.style.as_api_str(), - "unit": "points", - }) -} - -fn text_style_to_proto(style: &TextStyle) -> Value { - serde_json::json!({ - "styleName": style.style_name, - "fontSize": style.font_size, - "fontFamily": style.font_family, - "color": style.color, - "alignment": style.alignment, - "bold": style.bold, - "italic": style.italic, - "underline": style.underline, - }) -} - -fn rich_text_to_proto(text: &str, rich_text: &RichTextState) -> Value { - serde_json::json!({ - "layout": text_layout_to_proto(&rich_text.layout), - "ranges": rich_text - .ranges - .iter() - .map(|range| text_range_to_proto(text, range)) - .collect::>(), - }) -} - -fn text_range_to_proto(text: &str, range: &TextRangeAnnotation) -> Value { - serde_json::json!({ - "rangeId": range.range_id, - "anchor": format!("tr/{}", range.range_id), - "startCp": range.start_cp, - "length": range.length, - "text": text_slice_by_codepoint_range(text, range.start_cp, range.length), - "style": text_style_to_proto(&range.style), - "hyperlink": range.hyperlink.as_ref().map(HyperlinkState::to_json), - "spacingBefore": range.spacing_before, - "spacingAfter": range.spacing_after, - "lineSpacing": range.line_spacing, - }) -} - -fn text_layout_to_proto(layout: &TextLayoutState) -> Value { - serde_json::json!({ - "insets": layout.insets.map(|insets| serde_json::json!({ - "left": insets.left, - "right": insets.right, - "top": insets.top, - "bottom": insets.bottom, - "unit": "points", - })), - "wrap": layout.wrap.map(text_wrap_mode_to_proto), - "autoFit": layout.auto_fit.map(text_auto_fit_mode_to_proto), - "verticalAlignment": layout - .vertical_alignment - .map(text_vertical_alignment_to_proto), - }) -} - -fn text_wrap_mode_to_proto(mode: TextWrapMode) -> &'static str { - match mode { - TextWrapMode::Square => "square", - TextWrapMode::None => "none", - } -} - -fn text_auto_fit_mode_to_proto(mode: TextAutoFitMode) -> &'static str { - match mode { - TextAutoFitMode::None => "none", - TextAutoFitMode::ShrinkText => "shrinkText", - TextAutoFitMode::ResizeShapeToFitText => "resizeShapeToFitText", - } -} - -fn text_vertical_alignment_to_proto(alignment: TextVerticalAlignment) -> &'static str { - match alignment { - TextVerticalAlignment::Top => "top", - TextVerticalAlignment::Middle => "middle", - TextVerticalAlignment::Bottom => "bottom", - } -} - -fn placeholder_ref_to_proto(placeholder: &PlaceholderRef) -> Value { - serde_json::json!({ - "name": placeholder.name, - "placeholderType": placeholder.placeholder_type, - "index": placeholder.index, - }) -} - -fn image_payload_to_proto(payload: &ImagePayload) -> Value { - serde_json::json!({ - "format": payload.format, - "widthPx": payload.width_px, - "heightPx": payload.height_px, - "bytesBase64": BASE64_STANDARD.encode(&payload.bytes), - }) -} - -fn table_cell_to_proto(cell: &TableCellSpec) -> Value { - serde_json::json!({ - "text": cell.text, - "textStyle": text_style_to_proto(&cell.text_style), - "richText": rich_text_to_proto(&cell.text, &cell.rich_text), - "backgroundFill": cell.background_fill, - "alignment": cell.alignment, - "borders": cell.borders.as_ref().map(table_borders_to_proto), - }) -} - -fn table_style_options_to_proto(style_options: &TableStyleOptions) -> Value { - serde_json::json!({ - "headerRow": style_options.header_row, - "bandedRows": style_options.banded_rows, - "bandedColumns": style_options.banded_columns, - "firstColumn": style_options.first_column, - "lastColumn": style_options.last_column, - "totalRow": style_options.total_row, - }) -} - -fn table_borders_to_proto(borders: &TableBorders) -> Value { - serde_json::json!({ - "outside": borders.outside.as_ref().map(table_border_to_proto), - "inside": borders.inside.as_ref().map(table_border_to_proto), - "top": borders.top.as_ref().map(table_border_to_proto), - "bottom": borders.bottom.as_ref().map(table_border_to_proto), - "left": borders.left.as_ref().map(table_border_to_proto), - "right": borders.right.as_ref().map(table_border_to_proto), - }) -} - -fn table_border_to_proto(border: &TableBorder) -> Value { - serde_json::json!({ - "color": border.color, - "width": border.width, - "unit": "points", - }) -} - -fn chart_marker_to_proto(marker: &ChartMarkerStyle) -> Value { - serde_json::json!({ - "symbol": marker.symbol, - "size": marker.size, - }) -} - -fn chart_data_labels_to_proto(data_labels: &ChartDataLabels) -> Value { - serde_json::json!({ - "showValue": data_labels.show_value, - "showCategoryName": data_labels.show_category_name, - "showLeaderLines": data_labels.show_leader_lines, - "position": data_labels.position, - "textStyle": text_style_to_proto(&data_labels.text_style), - }) -} - -fn chart_legend_to_proto(legend: &ChartLegend) -> Value { - serde_json::json!({ - "position": legend.position, - "textStyle": text_style_to_proto(&legend.text_style), - }) -} - -fn chart_axis_to_proto(axis: &ChartAxisSpec) -> Value { - serde_json::json!({ - "title": axis.title, - }) -} - -fn chart_data_label_override_to_proto(override_spec: &ChartDataLabelOverride) -> Value { - serde_json::json!({ - "idx": override_spec.idx, - "text": override_spec.text, - "position": override_spec.position, - "textStyle": text_style_to_proto(&override_spec.text_style), - "fill": override_spec.fill, - "stroke": override_spec.stroke.as_ref().map(stroke_to_proto), - }) -} - -fn comment_author_to_proto(author: &CommentAuthorProfile) -> Value { - serde_json::json!({ - "displayName": author.display_name, - "initials": author.initials, - "email": author.email, - }) -} - -fn comment_thread_to_proto(thread: &CommentThread) -> Value { - serde_json::json!({ - "kind": "comment", - "threadId": thread.thread_id, - "anchor": format!("th/{}", thread.thread_id), - "target": comment_target_to_proto(&thread.target), - "position": thread.position.as_ref().map(comment_position_to_proto), - "status": comment_status_to_proto(thread.status), - "messages": thread.messages.iter().map(comment_message_to_proto).collect::>(), - }) -} - -fn comment_target_to_proto(target: &CommentTarget) -> Value { - match target { - CommentTarget::Slide { slide_id } => serde_json::json!({ - "type": "slide", - "slideId": slide_id, - "slideAnchor": format!("sl/{slide_id}"), - }), - CommentTarget::Element { - slide_id, - element_id, - } => serde_json::json!({ - "type": "element", - "slideId": slide_id, - "slideAnchor": format!("sl/{slide_id}"), - "elementId": element_id, - "elementAnchor": format!("sh/{element_id}"), - }), - CommentTarget::TextRange { - slide_id, - element_id, - start_cp, - length, - context, - } => serde_json::json!({ - "type": "textRange", - "slideId": slide_id, - "slideAnchor": format!("sl/{slide_id}"), - "elementId": element_id, - "elementAnchor": format!("sh/{element_id}"), - "startCp": start_cp, - "length": length, - "context": context, - }), - } -} - -fn comment_position_to_proto(position: &CommentPosition) -> Value { - serde_json::json!({ - "x": position.x, - "y": position.y, - "unit": "points", - }) -} - -fn comment_message_to_proto(message: &CommentMessage) -> Value { - serde_json::json!({ - "messageId": message.message_id, - "author": comment_author_to_proto(&message.author), - "text": message.text, - "createdAt": message.created_at, - "reactions": message.reactions, - }) -} - -fn comment_status_to_proto(status: CommentThreadStatus) -> &'static str { - match status { - CommentThreadStatus::Active => "active", - CommentThreadStatus::Resolved => "resolved", - } -} - -fn text_slice_by_codepoint_range(text: &str, start_cp: usize, length: usize) -> String { - text.chars().skip(start_cp).take(length).collect() -} - -fn build_table_cell( - cell: TableCellSpec, - merges: &[TableMergeRegion], - row_index: usize, - column_index: usize, -) -> TableCell { - let mut table_cell = TableCell::new(&cell.text); - if cell.text_style.bold { - table_cell = table_cell.bold(); - } - if cell.text_style.italic { - table_cell = table_cell.italic(); - } - if cell.text_style.underline { - table_cell = table_cell.underline(); - } - if let Some(color) = cell.text_style.color { - table_cell = table_cell.text_color(&color); - } - if let Some(fill) = cell.background_fill { - table_cell = table_cell.background_color(&fill); - } - if let Some(size) = cell.text_style.font_size { - table_cell = table_cell.font_size(size); - } - if let Some(font_family) = cell.text_style.font_family { - table_cell = table_cell.font_family(&font_family); - } - if let Some(alignment) = cell.alignment.or(cell.text_style.alignment) { - table_cell = match alignment { - TextAlignment::Left => table_cell.align_left(), - TextAlignment::Center => table_cell.align_center(), - TextAlignment::Right => table_cell.align_right(), - TextAlignment::Justify => table_cell.align(CellAlign::Justify), - }; - } - for merge in merges { - if row_index == merge.start_row && column_index == merge.start_column { - table_cell = table_cell - .grid_span((merge.end_column - merge.start_column + 1) as u32) - .row_span((merge.end_row - merge.start_row + 1) as u32); - } else if row_index >= merge.start_row - && row_index <= merge.end_row - && column_index >= merge.start_column - && column_index <= merge.end_column - { - if row_index == merge.start_row { - table_cell = table_cell.h_merge(); - } else { - table_cell = table_cell.v_merge(); - } - } - } - table_cell -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/response.rs b/codex-rs/artifact-presentation/src/presentation_artifact/response.rs deleted file mode 100644 index 241cce570d..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/response.rs +++ /dev/null @@ -1,138 +0,0 @@ -#[derive(Debug, Clone, Serialize)] -pub struct PresentationArtifactResponse { - pub artifact_id: String, - pub action: String, - pub summary: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub executed_actions: Option>, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub exported_paths: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub artifact_snapshot: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub slide_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub placeholder_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub theme: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub inspect_ndjson: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub resolved_record: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub proto_json: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub patch: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub active_slide_index: Option, -} - -impl PresentationArtifactResponse { - fn new( - artifact_id: String, - action: String, - summary: String, - artifact_snapshot: ArtifactSnapshot, - ) -> Self { - Self { - artifact_id, - action, - summary, - executed_actions: None, - exported_paths: Vec::new(), - artifact_snapshot: Some(artifact_snapshot), - slide_list: None, - layout_list: None, - placeholder_list: None, - theme: None, - inspect_ndjson: None, - resolved_record: None, - proto_json: None, - patch: None, - active_slide_index: None, - } - } -} - -fn response_for_document_state( - artifact_id: String, - action: String, - summary: String, - document: Option<&PresentationDocument>, -) -> PresentationArtifactResponse { - PresentationArtifactResponse { - artifact_id, - action, - summary, - executed_actions: None, - exported_paths: Vec::new(), - artifact_snapshot: document.map(snapshot_for_document), - slide_list: None, - layout_list: None, - placeholder_list: None, - theme: document.map(PresentationDocument::theme_snapshot), - inspect_ndjson: None, - resolved_record: None, - proto_json: None, - patch: None, - active_slide_index: document.and_then(|current| current.active_slide_index), - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct ArtifactSnapshot { - pub slide_count: usize, - pub slides: Vec, -} - -#[derive(Debug, Clone, Serialize)] -pub struct SlideSnapshot { - pub slide_id: String, - pub index: usize, - pub element_ids: Vec, - pub element_types: Vec, -} - -#[derive(Debug, Clone, Serialize)] -pub struct SlideListEntry { - pub slide_id: String, - pub index: usize, - pub is_active: bool, - pub notes: Option, - pub notes_visible: bool, - pub background_fill: Option, - pub layout_id: Option, - pub element_count: usize, -} - -#[derive(Debug, Clone, Serialize)] -pub struct LayoutListEntry { - pub layout_id: String, - pub name: String, - pub kind: String, - pub parent_layout_id: Option, - pub placeholder_count: usize, -} - -#[derive(Debug, Clone, Serialize)] -pub struct PlaceholderListEntry { - pub scope: String, - pub source_layout_id: Option, - pub slide_index: Option, - pub element_id: Option, - pub name: String, - pub placeholder_type: String, - pub index: Option, - pub geometry: Option, - pub text_preview: Option, -} - -#[derive(Debug, Clone, Serialize)] -pub struct ThemeSnapshot { - pub color_scheme: HashMap, - pub hex_color_map: HashMap, - pub major_font: Option, - pub minor_font: Option, -} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs b/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs deleted file mode 100644 index 8606649c38..0000000000 --- a/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs +++ /dev/null @@ -1,339 +0,0 @@ -fn cell_value_to_string(value: Value) -> String { - match value { - Value::Null => String::new(), - Value::String(text) => text, - Value::Bool(boolean) => boolean.to_string(), - Value::Number(number) => number.to_string(), - other => other.to_string(), - } -} - -fn snapshot_for_document(document: &PresentationDocument) -> ArtifactSnapshot { - ArtifactSnapshot { - slide_count: document.slides.len(), - slides: document - .slides - .iter() - .enumerate() - .map(|(index, slide)| SlideSnapshot { - slide_id: slide.slide_id.clone(), - index, - element_ids: slide - .elements - .iter() - .map(|element| element.element_id().to_string()) - .collect(), - element_types: slide - .elements - .iter() - .map(|element| element.kind().to_string()) - .collect(), - }) - .collect(), - } -} - -fn slide_list(document: &PresentationDocument) -> Vec { - document - .slides - .iter() - .enumerate() - .map(|(index, slide)| SlideListEntry { - slide_id: slide.slide_id.clone(), - index, - is_active: document.active_slide_index == Some(index), - notes: (slide.notes.visible && !slide.notes.text.is_empty()) - .then(|| slide.notes.text.clone()), - notes_visible: slide.notes.visible, - background_fill: slide.background_fill.clone(), - layout_id: slide.layout_id.clone(), - element_count: slide.elements.len(), - }) - .collect() -} - -fn layout_list(document: &PresentationDocument) -> Vec { - document - .layouts - .iter() - .map(|layout| LayoutListEntry { - layout_id: layout.layout_id.clone(), - name: layout.name.clone(), - kind: match layout.kind { - LayoutKind::Layout => "layout".to_string(), - LayoutKind::Master => "master".to_string(), - }, - parent_layout_id: layout.parent_layout_id.clone(), - placeholder_count: layout.placeholders.len(), - }) - .collect() -} - -fn points_to_emu(points: u32) -> u32 { - points.saturating_mul(POINT_TO_EMU) -} - -fn emu_to_points(emu: u32) -> u32 { - emu / POINT_TO_EMU -} - -type ImageCrop = (f64, f64, f64, f64); -type FittedImage = (u32, u32, u32, u32, Option); - -pub(crate) fn fit_image(image: &ImageElement) -> FittedImage { - let Some(payload) = image.payload.as_ref() else { - return ( - image.frame.left, - image.frame.top, - image.frame.width, - image.frame.height, - None, - ); - }; - let frame = image.frame; - let source_width = payload.width_px as f64; - let source_height = payload.height_px as f64; - let target_width = frame.width as f64; - let target_height = frame.height as f64; - let source_ratio = source_width / source_height; - let target_ratio = target_width / target_height; - - match image.fit_mode { - ImageFitMode::Stretch => (frame.left, frame.top, frame.width, frame.height, None), - ImageFitMode::Contain => { - let scale = if source_ratio > target_ratio { - target_width / source_width - } else { - target_height / source_height - }; - let width = (source_width * scale).round() as u32; - let height = (source_height * scale).round() as u32; - let left = frame.left + frame.width.saturating_sub(width) / 2; - let top = frame.top + frame.height.saturating_sub(height) / 2; - (left, top, width, height, None) - } - ImageFitMode::Cover => { - let scale = if source_ratio > target_ratio { - target_height / source_height - } else { - target_width / source_width - }; - let width = source_width * scale; - let height = source_height * scale; - let crop_x = ((width - target_width).max(0.0) / width) / 2.0; - let crop_y = ((height - target_height).max(0.0) / height) / 2.0; - ( - frame.left, - frame.top, - frame.width, - frame.height, - Some((crop_x, crop_y, crop_x, crop_y)), - ) - } - } -} - -fn normalize_image_crop( - crop: ImageCropArgs, - action: &str, -) -> Result { - for (name, value) in [ - ("left", crop.left), - ("top", crop.top), - ("right", crop.right), - ("bottom", crop.bottom), - ] { - if !(0.0..=1.0).contains(&value) { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("image crop `{name}` must be between 0.0 and 1.0"), - }); - } - } - Ok((crop.left, crop.top, crop.right, crop.bottom)) -} - -fn load_image_payload_from_path( - path: &Path, - action: &str, -) -> Result { - let bytes = std::fs::read(path).map_err(|error| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("failed to read image `{}`: {error}", path.display()), - })?; - build_image_payload( - bytes, - path.file_name() - .and_then(|name| name.to_str()) - .unwrap_or("image") - .to_string(), - action, - ) -} - -fn load_image_payload_from_data_url( - data_url: &str, - action: &str, -) -> Result { - let (header, payload) = - data_url - .split_once(',') - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "data_url must include a MIME header and base64 payload".to_string(), - })?; - let mime = header - .strip_prefix("data:") - .and_then(|prefix| prefix.strip_suffix(";base64")) - .ok_or_else(|| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: "data_url must be base64-encoded".to_string(), - })?; - let bytes = BASE64_STANDARD.decode(payload).map_err(|error| { - PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("failed to decode image data_url: {error}"), - } - })?; - build_image_payload( - bytes, - format!("image.{}", image_extension_from_mime(mime)), - action, - ) -} - -fn load_image_payload_from_blob( - blob: &str, - action: &str, -) -> Result { - let bytes = BASE64_STANDARD.decode(blob.trim()).map_err(|error| { - PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("failed to decode image blob: {error}"), - } - })?; - let extension = image::guess_format(&bytes) - .ok() - .map(image_extension_from_format) - .unwrap_or("png"); - build_image_payload(bytes, format!("image.{extension}"), action) -} - -fn load_image_payload_from_uri( - uri: &str, - action: &str, -) -> Result { - let response = - reqwest::blocking::get(uri).map_err(|error| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("failed to fetch image `{uri}`: {error}"), - })?; - let status = response.status(); - if !status.is_success() { - return Err(PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("failed to fetch image `{uri}`: HTTP {status}"), - }); - } - let content_type = response - .headers() - .get(reqwest::header::CONTENT_TYPE) - .and_then(|value| value.to_str().ok()) - .map(|value| value.split(';').next().unwrap_or(value).trim().to_string()); - let bytes = response - .bytes() - .map_err(|error| PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("failed to read image `{uri}`: {error}"), - })?; - build_image_payload( - bytes.to_vec(), - infer_remote_image_filename(uri, content_type.as_deref()), - action, - ) -} - -fn infer_remote_image_filename(uri: &str, content_type: Option<&str>) -> String { - let path_name = reqwest::Url::parse(uri) - .ok() - .and_then(|url| { - url.path_segments() - .and_then(Iterator::last) - .map(str::to_owned) - }) - .filter(|segment| !segment.is_empty()); - match (path_name, content_type) { - (Some(path_name), _) if Path::new(&path_name).extension().is_some() => path_name, - (Some(path_name), Some(content_type)) => { - format!("{path_name}.{}", image_extension_from_mime(content_type)) - } - (Some(path_name), None) => path_name, - (None, Some(content_type)) => format!("image.{}", image_extension_from_mime(content_type)), - (None, None) => "image.png".to_string(), - } -} - -fn build_image_payload( - bytes: Vec, - filename: String, - action: &str, -) -> Result { - let image = image::load_from_memory(&bytes).map_err(|error| { - PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("failed to decode image bytes: {error}"), - } - })?; - let (width_px, height_px) = image.dimensions(); - let format = Path::new(&filename) - .extension() - .and_then(|extension| extension.to_str()) - .unwrap_or("png") - .to_uppercase(); - Ok(ImagePayload { - bytes, - format, - width_px, - height_px, - }) -} - -fn image_extension_from_mime(mime: &str) -> &'static str { - match mime { - "image/jpeg" => "jpg", - "image/gif" => "gif", - "image/webp" => "webp", - _ => "png", - } -} - -fn image_extension_from_format(format: image::ImageFormat) -> &'static str { - match format { - image::ImageFormat::Jpeg => "jpg", - image::ImageFormat::Gif => "gif", - image::ImageFormat::WebP => "webp", - image::ImageFormat::Bmp => "bmp", - image::ImageFormat::Tiff => "tiff", - _ => "png", - } -} - -fn index_out_of_range(action: &str, index: usize, len: usize) -> PresentationArtifactError { - PresentationArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("slide index {index} is out of range for {len} slides"), - } -} - -fn to_index(value: u32) -> Result { - usize::try_from(value).map_err(|_| PresentationArtifactError::InvalidArgs { - action: "insert_slide".to_string(), - message: "index does not fit in usize".to_string(), - }) -} - -fn resequence_z_order(slide: &mut PresentationSlide) { - for (index, element) in slide.elements.iter_mut().enumerate() { - element.set_z_order(index); - } -} diff --git a/codex-rs/artifact-presentation/src/tests.rs b/codex-rs/artifact-presentation/src/tests.rs deleted file mode 100644 index 2ced6ad642..0000000000 --- a/codex-rs/artifact-presentation/src/tests.rs +++ /dev/null @@ -1,3512 +0,0 @@ -use super::presentation_artifact::*; -use base64::Engine; -use pretty_assertions::assert_eq; -use std::io::Read; - -fn zip_entry_text( - path: &std::path::Path, - entry_name: &str, -) -> Result> { - let file = std::fs::File::open(path)?; - let mut archive = zip::ZipArchive::new(file)?; - let mut entry = archive.by_name(entry_name)?; - let mut text = String::new(); - entry.read_to_string(&mut text)?; - Ok(text) -} - -fn zip_entry_names(path: &std::path::Path) -> Result, Box> { - let file = std::fs::File::open(path)?; - let archive = zip::ZipArchive::new(file)?; - Ok(archive.file_names().map(str::to_owned).collect()) -} - -fn parse_ndjson_lines(ndjson: &str) -> Result, serde_json::Error> { - ndjson - .lines() - .filter(|line| !line.is_empty()) - .map(serde_json::from_str) - .collect() -} - -#[test] -fn manager_can_create_add_text_and_export() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let create_response = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Demo" }), - }, - temp_dir.path(), - )?; - let artifact_id = create_response.artifact_id; - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - - let add_text = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "hello", - "position": { "left": 40, "top": 40, "width": 200, "height": 80 } - }), - }, - temp_dir.path(), - )?; - assert_eq!( - add_text - .artifact_snapshot - .as_ref() - .map(|snapshot| snapshot.slide_count), - Some(1) - ); - - let export_path = temp_dir.path().join("deck.pptx"); - let export = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - assert_eq!(export.exported_paths.len(), 1); - assert!(export.exported_paths[0].exists()); - Ok(()) -} - -#[test] -fn manager_can_import_exported_presentation() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Roundtrip" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id.clone(); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "add_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "geometry": "rectangle", - "position": { "left": 24, "top": 24, "width": 180, "height": 120 }, - "text": "shape" - }), - }, - temp_dir.path(), - )?; - let export_path = temp_dir.path().join("roundtrip.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - - let imported = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "import_pptx".to_string(), - args: serde_json::json!({ "path": "roundtrip.pptx" }), - }, - temp_dir.path(), - )?; - assert_eq!( - imported - .artifact_snapshot - .as_ref() - .map(|snapshot| snapshot.slide_count), - Some(1) - ); - Ok(()) -} - -#[test] -fn custom_slide_size_is_written_to_exported_pptx() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ - "name": "Custom Size", - "slide_size": { "width": 960, "height": 540 } - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let export_path = temp_dir.path().join("custom-size.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - - let presentation_xml = zip_entry_text( - &temp_dir.path().join("custom-size.pptx"), - "ppt/presentation.xml", - )?; - assert!(presentation_xml.contains(r#"cx="12192000" cy="6858000""#)); - assert!(presentation_xml.contains(r#"p:notesSz cx="6858000" cy="12192000""#)); - Ok(()) -} - -#[test] -fn exported_images_are_real_pictures_with_media_parts() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let source_path = temp_dir.path().join("source.png"); - image::RgbaImage::from_pixel(24, 16, image::Rgba([0x20, 0x90, 0xD0, 0xFF])) - .save(&source_path)?; - - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Image Export" }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "add_image".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "path": "source.png", - "position": { "left": 36, "top": 48, "width": 144, "height": 96 }, - "rotation": 15, - "flip_horizontal": true, - "alt": "Company logo" - }), - }, - temp_dir.path(), - )?; - - let export_path = temp_dir.path().join("images.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - - let pptx_path = temp_dir.path().join("images.pptx"); - let slide_xml = zip_entry_text(&pptx_path, "ppt/slides/slide1.xml")?; - let rels_xml = zip_entry_text(&pptx_path, "ppt/slides/_rels/slide1.xml.rels")?; - let content_types_xml = zip_entry_text(&pptx_path, "[Content_Types].xml")?; - let entry_names = zip_entry_names(&pptx_path)?; - - assert!(slide_xml.contains("")); - assert!(slide_xml.contains(r#"descr="Company logo""#)); - assert!(slide_xml.contains(r#"r:embed="rIdImage1""#)); - assert!(slide_xml.contains(r#""#)); - assert!(!slide_xml.contains("Image Placeholder:")); - assert!(rels_xml.contains("relationships/image")); - assert!(rels_xml.contains(r#"Target="../media/image1.png""#)); - assert!(content_types_xml.contains(r#"Extension="png" ContentType="image/png""#)); - assert!(entry_names.contains(&"ppt/media/image1.png".to_string())); - Ok(()) -} - -#[test] -fn tool_request_accepts_sequential_actions() -> Result<(), Box> { - let request: PresentationArtifactToolRequest = serde_json::from_value(serde_json::json!({ - "actions": [ - { - "action": "create", - "args": { "name": "Batch Deck" } - }, - { - "action": "export_pptx", - "args": { "path": "deck.pptx" } - } - ] - }))?; - - let execution = request.into_execution_request()?; - assert_eq!(execution.artifact_id, None); - assert_eq!(execution.requests.len(), 2); - assert_eq!(execution.requests[0].action, "create"); - assert_eq!(execution.requests[1].action, "export_pptx"); - Ok(()) -} - -#[test] -fn manager_can_execute_sequential_actions() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let response = manager.execute_requests( - PresentationArtifactExecutionRequest { - artifact_id: None, - requests: vec![ - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Batch Deck" }), - }, - PresentationArtifactRequest { - artifact_id: None, - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - PresentationArtifactRequest { - artifact_id: None, - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "hello", - "position": { "left": 40, "top": 40, "width": 200, "height": 80 } - }), - }, - ], - }, - temp_dir.path(), - )?; - - assert_eq!(response.action, "batch"); - assert_eq!( - response.executed_actions, - Some(vec![ - "create".to_string(), - "add_slide".to_string(), - "add_text_shape".to_string(), - ]) - ); - assert_eq!( - response - .artifact_snapshot - .as_ref() - .map(|snapshot| snapshot.slide_count), - Some(1) - ); - assert!( - response - .summary - .contains("Executed 3 actions sequentially.") - ); - Ok(()) -} - -#[test] -fn imported_pptx_surfaces_image_elements() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let source_path = temp_dir.path().join("import-source.png"); - image::RgbaImage::from_pixel(20, 20, image::Rgba([0xD0, 0x60, 0x20, 0xFF])) - .save(&source_path)?; - - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Image Import" }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "add_image".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "path": "import-source.png", - "position": { "left": 40, "top": 52, "width": 120, "height": 120 }, - "crop": { "left": 0.1, "top": 0.0, "right": 0.05, "bottom": 0.0 }, - "rotation": -10, - "flip_horizontal": true, - "flip_vertical": true, - "lock_aspect_ratio": true, - "alt": "Imported logo" - }), - }, - temp_dir.path(), - )?; - let export_path = temp_dir.path().join("image-import-roundtrip.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - - let imported = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "import_pptx".to_string(), - args: serde_json::json!({ "path": "image-import-roundtrip.pptx" }), - }, - temp_dir.path(), - )?; - assert_eq!( - imported - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .map(|slide| slide.element_types.clone()), - Some(vec!["image".to_string()]) - ); - let image_anchor = imported - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .map(|id| format!("im/{id}")) - .expect("image anchor"); - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(imported.artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": image_anchor }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("alt")) - .and_then(serde_json::Value::as_str), - Some("Imported logo") - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("rotation")) - .and_then(serde_json::Value::as_i64), - Some(-10) - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("flipHorizontal")) - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("flipVertical")) - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("lockAspectRatio")) - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("crop")) - .and_then(|crop| crop.get("left")) - .and_then(serde_json::Value::as_f64), - Some(0.1) - ); - Ok(()) -} - -#[test] -fn image_fit_contain_preserves_aspect_ratio() { - let image = ImageElement { - element_id: "element_1".to_string(), - frame: Rect { - left: 10, - top: 10, - width: 200, - height: 200, - }, - payload: Some(ImagePayload { - bytes: Vec::new(), - format: "PNG".to_string(), - width_px: 400, - height_px: 200, - }), - fit_mode: ImageFitMode::Contain, - crop: None, - rotation_degrees: None, - flip_horizontal: false, - flip_vertical: false, - lock_aspect_ratio: true, - alt_text: None, - prompt: None, - is_placeholder: false, - placeholder: None, - z_order: 0, - }; - - let (left, top, width, height, crop) = fit_image(&image); - assert_eq!((left, top, width, height), (10, 60, 200, 100)); - assert_eq!(crop, None); -} - -#[test] -fn preview_image_writer_supports_jpeg_scale_and_svg() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let source_path = temp_dir.path().join("preview.png"); - image::RgbaImage::from_pixel(80, 40, image::Rgba([0x22, 0x66, 0xAA, 0xFF])) - .save(&source_path)?; - let target_path = temp_dir.path().join("preview.jpg"); - write_preview_image( - &source_path, - &target_path, - PreviewOutputFormat::Jpeg, - 0.5, - 82, - "test", - )?; - let rendered = image::open(&target_path)?; - assert_eq!((rendered.width(), rendered.height()), (40, 20)); - assert_eq!( - image::ImageFormat::from_path(&target_path)?, - image::ImageFormat::Jpeg - ); - assert!(!source_path.exists()); - - let svg_source_path = temp_dir.path().join("preview-svg.png"); - image::RgbaImage::from_pixel(32, 16, image::Rgba([0x55, 0xAA, 0x44, 0xFF])) - .save(&svg_source_path)?; - let svg_target_path = temp_dir.path().join("preview.svg"); - write_preview_image( - &svg_source_path, - &svg_target_path, - PreviewOutputFormat::Svg, - 0.5, - 90, - "test", - )?; - let svg = std::fs::read_to_string(&svg_target_path)?; - assert!(svg.contains(r#" Result<(), Box> { - let mut image_bytes = std::io::Cursor::new(Vec::new()); - image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( - 16, - 8, - image::Rgba([0x11, 0x88, 0xCC, 0xFF]), - )) - .write_to(&mut image_bytes, image::ImageFormat::Png)?; - let png = image_bytes.into_inner(); - - let server = tiny_http::Server::http("127.0.0.1:0").expect("server"); - let port = server.server_addr().to_ip().expect("ip addr").port(); - let server_thread = std::thread::spawn(move || { - for request in server.incoming_requests().take(2) { - let response = tiny_http::Response::from_data(png.clone()).with_header( - tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"image/png"[..]) - .expect("header"), - ); - request.respond(response).expect("respond"); - } - }); - - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Remote Images" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let remote_uri = format!("http://127.0.0.1:{port}/image.png"); - let added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_image".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "uri": remote_uri, - "position": { "left": 32, "top": 48, "width": 120, "height": 60 } - }), - }, - temp_dir.path(), - )?; - let element_id = added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.last()) - .cloned() - .expect("image id"); - assert_eq!( - added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .map(|slide| slide.element_types.clone()), - Some(vec!["image".to_string()]) - ); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "replace_image".to_string(), - args: serde_json::json!({ - "element_id": format!("im/{element_id}"), - "uri": format!("http://127.0.0.1:{port}/updated.png"), - "fit": "contain" - }), - }, - temp_dir.path(), - )?; - let inspect = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "inspect".to_string(), - args: serde_json::json!({ "kind": "image" }), - }, - temp_dir.path(), - )?; - assert!( - inspect - .inspect_ndjson - .expect("image inspect") - .contains("\"fit\":\"Contain\"") - ); - server_thread.join().expect("server thread"); - Ok(()) -} - -#[test] -fn image_blobs_can_add_images() -> Result<(), Box> { - let mut image_bytes = std::io::Cursor::new(Vec::new()); - image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( - 10, - 6, - image::Rgba([0xAA, 0x55, 0x22, 0xFF]), - )) - .write_to(&mut image_bytes, image::ImageFormat::Png)?; - let blob = base64::engine::general_purpose::STANDARD.encode(image_bytes.into_inner()); - - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Blob Images" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_image".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "blob": blob, - "position": { "left": 32, "top": 48, "width": 100, "height": 60 } - }), - }, - temp_dir.path(), - )?; - let image_id = added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("image id"); - let proto = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "to_proto".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!( - proto - .proto_json - .as_ref() - .and_then(|proto| proto.get("slides")) - .and_then(serde_json::Value::as_array) - .and_then(|slides| slides.first()) - .and_then(|slide| slide.get("elements")) - .and_then(serde_json::Value::as_array) - .and_then(|elements| elements.iter().find(|element| { - element.get("elementId").and_then(serde_json::Value::as_str) - == Some(image_id.as_str()) - })) - .and_then(|record| record.get("payload")) - .and_then(|payload| payload.get("format")) - .and_then(serde_json::Value::as_str), - Some("PNG") - ); - Ok(()) -} - -#[test] -fn active_slide_can_be_set_and_tracks_reorders() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Active Slide" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - for _ in 0..3 { - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - } - let set_active = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_active_slide".to_string(), - args: serde_json::json!({ "slide_index": 2 }), - }, - temp_dir.path(), - )?; - assert_eq!(set_active.active_slide_index, Some(2)); - assert_eq!( - set_active.slide_list.as_ref().map(|slides| slides - .iter() - .map(|slide| slide.is_active) - .collect::>()), - Some(vec![false, false, true]) - ); - - let moved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "move_slide".to_string(), - args: serde_json::json!({ "from_index": 2, "to_index": 0 }), - }, - temp_dir.path(), - )?; - let summary = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_summary".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!(summary.active_slide_index, Some(0)); - assert_eq!( - summary.slide_list.as_ref().map(|slides| slides - .iter() - .map(|slide| slide.is_active) - .collect::>()), - Some(vec![true, false, false]) - ); - - let inspect = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "inspect".to_string(), - args: serde_json::json!({ "kind": "deck,slide" }), - }, - temp_dir.path(), - )?; - let inspect_ndjson = inspect.inspect_ndjson.expect("inspect"); - assert!(inspect_ndjson.contains("\"activeSlideIndex\":0")); - assert!(inspect_ndjson.contains("\"isActive\":true")); - - let active_slide_id = moved - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .map(|slide| slide.slide_id.clone()) - .expect("active slide id"); - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sl/{active_slide_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("isActive")) - .and_then(serde_json::Value::as_bool), - Some(true) - ); - - let deleted = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "delete_slide".to_string(), - args: serde_json::json!({ "slide_index": 0 }), - }, - temp_dir.path(), - )?; - assert_eq!( - deleted - .artifact_snapshot - .as_ref() - .map(|snapshot| snapshot.slide_count), - Some(2) - ); - let after_delete = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(deleted.artifact_id), - action: "list_slides".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!(after_delete.active_slide_index, Some(0)); - assert_eq!( - after_delete.slide_list.as_ref().map(|slides| slides - .iter() - .map(|slide| slide.is_active) - .collect::>()), - Some(vec![true, false]) - ); - Ok(()) -} - -#[test] -fn text_replace_and_insert_helpers_update_text_elements() -> Result<(), Box> -{ - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Text Helpers" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "Revenue up 24%", - "position": { "left": 24, "top": 24, "width": 240, "height": 80 } - }), - }, - temp_dir.path(), - )?; - let element_id = added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("text id"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "replace_text".to_string(), - args: serde_json::json!({ - "element_id": format!("sh/{element_id}"), - "search": "24%", - "replace": "31%" - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "insert_text_after".to_string(), - args: serde_json::json!({ - "element_id": format!("sh/{element_id}"), - "after": "Revenue", - "insert": " QoQ" - }), - }, - temp_dir.path(), - )?; - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sh/{element_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("text")) - .and_then(serde_json::Value::as_str), - Some("Revenue QoQ up 31%") - ); - Ok(()) -} - -#[test] -fn hyperlinks_are_inspectable_and_exported() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Hyperlinks" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - for _ in 0..2 { - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - } - - let text = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "Open roadmap", - "position": { "left": 24, "top": 24, "width": 220, "height": 60 } - }), - }, - temp_dir.path(), - )?; - let text_id = text - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("text id"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_hyperlink".to_string(), - args: serde_json::json!({ - "element_id": format!("sh/{text_id}"), - "link_type": "url", - "url": "https://example.com/roadmap", - "tooltip": "Roadmap", - "highlight_click": false - }), - }, - temp_dir.path(), - )?; - - let shape = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "geometry": "rounded_rectangle", - "position": { "left": 24, "top": 120, "width": 220, "height": 72 }, - "text": "Jump to appendix" - }), - }, - temp_dir.path(), - )?; - let shape_id = shape - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.last()) - .cloned() - .expect("shape id"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_hyperlink".to_string(), - args: serde_json::json!({ - "element_id": format!("sh/{shape_id}"), - "link_type": "slide", - "slide_index": 1, - "tooltip": "Appendix" - }), - }, - temp_dir.path(), - )?; - - let inspect = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "inspect".to_string(), - args: serde_json::json!({ "kind": "textbox,shape" }), - }, - temp_dir.path(), - )?; - let inspect_ndjson = inspect.inspect_ndjson.expect("inspect"); - assert!(inspect_ndjson.contains("\"type\":\"url\"")); - assert!(inspect_ndjson.contains("\"url\":\"https://example.com/roadmap\"")); - assert!(inspect_ndjson.contains("\"type\":\"slide\"")); - assert!(inspect_ndjson.contains("\"slideIndex\":1")); - - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sh/{text_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("hyperlink")) - .and_then(|hyperlink| hyperlink.get("url")) - .and_then(serde_json::Value::as_str), - Some("https://example.com/roadmap") - ); - - let export_path = temp_dir.path().join("hyperlinks.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - let slide_xml = zip_entry_text( - &temp_dir.path().join("hyperlinks.pptx"), - "ppt/slides/slide1.xml", - )?; - let rels_xml = zip_entry_text( - &temp_dir.path().join("hyperlinks.pptx"), - "ppt/slides/_rels/slide1.xml.rels", - )?; - assert!(slide_xml.contains("hlinkClick")); - assert!(rels_xml.contains("https://example.com/roadmap")); - assert!(rels_xml.contains("slide2.xml")); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_hyperlink".to_string(), - args: serde_json::json!({ - "element_id": format!("sh/{text_id}"), - "clear": true - }), - }, - temp_dir.path(), - )?; - let cleared = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sh/{text_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - cleared - .resolved_record - .as_ref() - .and_then(|record| record.get("hyperlink")), - None - ); - Ok(()) -} - -#[test] -fn manager_supports_layout_theme_notes_and_inspect() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ - "name": "Deck", - "theme": { - "color_scheme": { - "accent1": "#123456", - "bg1": "#FFFFFF", - "tx1": "#111111" - }, - "major_font": "Aptos" - } - }), - }, - temp_dir.path(), - )?; - assert_eq!( - created - .theme - .as_ref() - .map(|theme| theme.hex_color_map.clone()), - Some( - [ - ("accent1".to_string(), "123456".to_string()), - ("bg1".to_string(), "FFFFFF".to_string()), - ("tx1".to_string(), "111111".to_string()), - ] - .into_iter() - .collect() - ) - ); - let artifact_id = created.artifact_id.clone(); - - let master_layouts = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_layout".to_string(), - args: serde_json::json!({ "name": "Brand Master", "kind": "master" }), - }, - temp_dir.path(), - )?; - assert_eq!(master_layouts.layout_list.as_ref().map(Vec::len), Some(1)); - let master_id = master_layouts.layout_list.unwrap()[0].layout_id.clone(); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_layout_placeholder".to_string(), - args: serde_json::json!({ - "layout_id": master_id, - "name": "title", - "placeholder_type": "title", - "text": "Placeholder title", - "position": { "left": 48, "top": 48, "width": 500, "height": 60 } - }), - }, - temp_dir.path(), - )?; - - let child_layouts = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_layout".to_string(), - args: serde_json::json!({ - "name": "Title Slide", - "kind": "layout", - "parent_layout_id": master_id - }), - }, - temp_dir.path(), - )?; - assert_eq!(child_layouts.layout_list.as_ref().map(Vec::len), Some(2)); - let layout_id = child_layouts - .layout_list - .as_ref() - .and_then(|layouts| layouts.iter().find(|layout| layout.kind == "layout")) - .map(|layout| layout.layout_id.clone()) - .expect("child layout id"); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_layout_placeholder".to_string(), - args: serde_json::json!({ - "layout_id": "Title Slide", - "name": "subtitle", - "placeholder_type": "subtitle", - "text": "Placeholder subtitle", - "position": { "left": 48, "top": 128, "width": 500, "height": 48 } - }), - }, - temp_dir.path(), - )?; - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_layout_placeholder".to_string(), - args: serde_json::json!({ - "layout_id": "title slide", - "name": "hero-image", - "placeholder_type": "picture", - "text": "Add cover image", - "position": { "left": 420, "top": 40, "width": 180, "height": 120 } - }), - }, - temp_dir.path(), - )?; - - let added_slide = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({ "layout": layout_id }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_notes".to_string(), - args: serde_json::json!({ "slide_index": 0, "text": "Speaker notes" }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "append_notes".to_string(), - args: serde_json::json!({ "slide_index": 0, "text": "More context" }), - }, - temp_dir.path(), - )?; - let layout_placeholders = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "list_layout_placeholders".to_string(), - args: serde_json::json!({ "layout_id": layout_id }), - }, - temp_dir.path(), - )?; - assert_eq!( - layout_placeholders.placeholder_list.as_ref().map(Vec::len), - Some(3) - ); - - let slide_placeholders = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "list_slide_placeholders".to_string(), - args: serde_json::json!({ "slide_index": 0 }), - }, - temp_dir.path(), - )?; - assert_eq!( - slide_placeholders.placeholder_list.as_ref().map(Vec::len), - Some(3) - ); - assert_eq!( - slide_placeholders - .placeholder_list - .as_ref() - .and_then(|placeholders| placeholders - .iter() - .find(|placeholder| placeholder.placeholder_type == "picture") - .map(|placeholder| ( - placeholder.geometry.clone(), - placeholder.text_preview.clone() - ))), - Some(( - Some("Image".to_string()), - Some("Add cover image".to_string()) - )) - ); - let image_placeholder_id = added_slide - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.last()) - .cloned() - .expect("image placeholder id"); - - let resolved_layout = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("ly/{layout_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_layout - .resolved_record - .as_ref() - .and_then(|record| record.get("kind")) - .and_then(serde_json::Value::as_str), - Some("layout") - ); - - let inspect = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "inspect".to_string(), - args: serde_json::json!({ "kind": "deck,slide,textbox,image,notes,layoutList" }), - }, - temp_dir.path(), - )?; - let inspect_ndjson = inspect.inspect_ndjson.expect("inspect output"); - assert!(inspect_ndjson.contains("\"kind\":\"layout\"")); - assert!(inspect_ndjson.contains("\"kind\":\"notes\"")); - assert!(inspect_ndjson.contains("\"placeholder\":\"title\"")); - assert!(inspect_ndjson.contains("\"placeholder\":\"picture\"")); - assert!(inspect_ndjson.contains("\"kind\":\"image\"")); - - let resolved_image_placeholder = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("im/{image_placeholder_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_image_placeholder - .resolved_record - .as_ref() - .and_then(|record| record.get("isPlaceholder")) - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - resolved_image_placeholder - .resolved_record - .as_ref() - .and_then(|record| record.get("placeholder")) - .and_then(serde_json::Value::as_str), - Some("picture") - ); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_slide_layout".to_string(), - args: serde_json::json!({ "slide_index": 1, "layout_id": "title slide" }), - }, - temp_dir.path(), - )?; - let inherited_placeholders = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "list_slide_placeholders".to_string(), - args: serde_json::json!({ "slide_index": 1 }), - }, - temp_dir.path(), - )?; - assert_eq!( - inherited_placeholders - .placeholder_list - .as_ref() - .map(Vec::len), - Some(3) - ); - assert_eq!( - inherited_placeholders - .placeholder_list - .as_ref() - .and_then(|placeholders| placeholders - .iter() - .find(|placeholder| placeholder.placeholder_type == "title") - .map(|placeholder| placeholder.name.clone())), - Some("title".to_string()) - ); - assert_eq!( - inherited_placeholders - .placeholder_list - .as_ref() - .and_then(|placeholders| placeholders - .iter() - .find(|placeholder| placeholder.placeholder_type == "picture") - .map(|placeholder| placeholder.geometry.clone())), - Some(Some("Image".to_string())) - ); - - let truncated = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id), - action: "inspect".to_string(), - args: serde_json::json!({ - "kind": "deck,slide,textbox,image,notes,layoutList", - "max_chars": 250 - }), - }, - temp_dir.path(), - )?; - assert!( - truncated - .inspect_ndjson - .expect("truncated inspect") - .contains("\"noticeType\":\"truncation\"") - ); - Ok(()) -} - -#[test] -fn named_text_styles_apply_to_text_and_tables() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ - "name": "Styles", - "theme": { - "color_scheme": { - "tx1": "#222222" - }, - "major_font": "Aptos Display", - "minor_font": "Aptos" - } - }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - let described = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "describe_styles".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!( - described - .resolved_record - .as_ref() - .and_then(|record| record.get("styles")) - .and_then(serde_json::Value::as_array) - .map(Vec::len), - Some(5) - ); - let title_style = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_style".to_string(), - args: serde_json::json!({ "name": "title" }), - }, - temp_dir.path(), - )?; - assert_eq!( - title_style.resolved_record, - Some(serde_json::json!({ - "kind": "textStyle", - "id": "st/title", - "name": "title", - "builtIn": true, - "style": { - "styleName": "title", - "fontSize": 28, - "fontFamily": "Aptos Display", - "color": "222222", - "alignment": "left", - "bold": true, - "italic": false, - "underline": false - } - })) - ); - let custom_style = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_style".to_string(), - args: serde_json::json!({ - "name": "callout", - "font_size": 18, - "color": "#336699", - "italic": true, - "underline": true - }), - }, - temp_dir.path(), - )?; - assert_eq!( - custom_style.resolved_record, - Some(serde_json::json!({ - "kind": "textStyle", - "id": "st/callout", - "name": "callout", - "builtIn": false, - "style": { - "styleName": "callout", - "fontSize": 18, - "fontFamily": serde_json::Value::Null, - "color": "336699", - "alignment": serde_json::Value::Null, - "bold": false, - "italic": true, - "underline": true - } - })) - ); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let text_added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "Styled title", - "position": { "left": 40, "top": 40, "width": 220, "height": 50 }, - "style": "title", - "underline": true - }), - }, - temp_dir.path(), - )?; - let text_id = text_added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("text id"); - let table_added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_table".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "position": { "left": 40, "top": 120, "width": 180, "height": 80 }, - "rows": [["A"]], - }), - }, - temp_dir.path(), - )?; - let table_id = table_added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.last()) - .cloned() - .expect("table id"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "update_table_cell".to_string(), - args: serde_json::json!({ - "element_id": table_id, - "row": 0, - "column": 0, - "value": "Styled cell", - "styling": { - "style": "callout" - } - }), - }, - temp_dir.path(), - )?; - - let resolved_text = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sh/{text_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_text - .resolved_record - .as_ref() - .and_then(|record| record.get("textStyle")) - .cloned(), - Some(serde_json::json!({ - "styleName": "title", - "fontSize": 28, - "fontFamily": "Aptos Display", - "color": "222222", - "alignment": "left", - "bold": true, - "italic": false, - "underline": true - })) - ); - let resolved_table = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("tb/{table_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_table - .resolved_record - .as_ref() - .and_then(|record| record.get("cellTextStyles")) - .cloned(), - Some(serde_json::json!([ - [ - { - "styleName": "callout", - "fontSize": 18, - "fontFamily": serde_json::Value::Null, - "color": "336699", - "alignment": serde_json::Value::Null, - "bold": false, - "italic": true, - "underline": true - } - ] - ])) - ); - Ok(()) -} - -#[test] -fn layout_names_resolve_in_slide_actions_and_insert_defaults_after_active_slide() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Layouts by Name" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - - let layout_created = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_layout".to_string(), - args: serde_json::json!({ "name": "Title Slide" }), - }, - temp_dir.path(), - )?; - let layout_id = layout_created - .layout_list - .as_ref() - .and_then(|layouts| layouts.first()) - .map(|layout| layout.layout_id.clone()) - .expect("layout id"); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_layout_placeholder".to_string(), - args: serde_json::json!({ - "layout_id": layout_id, - "name": "title", - "placeholder_type": "title", - "text": "Placeholder title" - }), - }, - temp_dir.path(), - )?; - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({ "layout": "Title Slide" }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_active_slide".to_string(), - args: serde_json::json!({ "slide_index": 0 }), - }, - temp_dir.path(), - )?; - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "insert_slide".to_string(), - args: serde_json::json!({ "layout": "title slide" }), - }, - temp_dir.path(), - )?; - let inserted = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "list_slides".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!( - inserted.slide_list.as_ref().map(|slides| slides - .iter() - .map(|slide| slide.layout_id.clone()) - .collect::>()), - Some(vec![ - Some("layout_1".to_string()), - Some("layout_1".to_string()), - None - ]) - ); - assert_eq!( - inserted.slide_list.as_ref().map(|slides| slides - .iter() - .map(|slide| slide.is_active) - .collect::>()), - Some(vec![true, false, false]) - ); - - let placeholders = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "list_layout_placeholders".to_string(), - args: serde_json::json!({ "layout_id": "TITLE SLIDE" }), - }, - temp_dir.path(), - )?; - assert_eq!( - placeholders.placeholder_list.as_ref().map(|entries| entries - .iter() - .map(|entry| entry.name.clone()) - .collect::>()), - Some(vec!["title".to_string()]) - ); - - let child_layout = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(placeholders.artifact_id), - action: "create_layout".to_string(), - args: serde_json::json!({ - "name": "Child Layout", - "parent_layout_id": "title slide" - }), - }, - temp_dir.path(), - )?; - assert_eq!( - child_layout.layout_list.as_ref().map(|layouts| layouts - .iter() - .find(|layout| layout.name == "Child Layout") - .and_then(|layout| layout.parent_layout_id.clone())), - Some(Some("layout_1".to_string())) - ); - Ok(()) -} - -#[test] -fn inspect_supports_filters_target_windows_and_shape_text_metadata() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Inspect Filters" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - - let first_text = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "First KPI", - "position": { "left": 10, "top": 10, "width": 120, "height": 40 } - }), - }, - temp_dir.path(), - )?; - let second_text = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "Second KPI", - "position": { "left": 10, "top": 60, "width": 120, "height": 40 } - }), - }, - temp_dir.path(), - )?; - let third_text = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "Third KPI", - "position": { "left": 10, "top": 110, "width": 120, "height": 40 } - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_notes".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "Speaker note" - }), - }, - temp_dir.path(), - )?; - let shape = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "geometry": "rectangle", - "position": { "left": 180, "top": 10, "width": 180, "height": 90 }, - "text": "Detailed\nShape KPI" - }), - }, - temp_dir.path(), - )?; - - let middle_text_id = second_text - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.get(1)) - .cloned() - .expect("middle text id"); - let first_text_id = first_text - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("first text id"); - let third_text_id = third_text - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.get(2)) - .cloned() - .expect("third text id"); - let shape_id = shape - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.get(3)) - .cloned() - .expect("shape id"); - let slide_id = shape - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .map(|slide| slide.slide_id.clone()) - .expect("slide id"); - - let filtered = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "inspect".to_string(), - args: serde_json::json!({ - "include": "shape,notes", - "exclude": "notes", - "search": "Detailed" - }), - }, - temp_dir.path(), - )?; - let filtered_records = parse_ndjson_lines( - filtered - .inspect_ndjson - .as_deref() - .expect("filtered inspect"), - )?; - assert_eq!(filtered_records.len(), 1); - assert_eq!( - filtered_records[0], - serde_json::json!({ - "kind": "shape", - "id": format!("sh/{shape_id}"), - "slide": 1, - "geometry": "Rectangle", - "text": "Detailed\nShape KPI", - "textStyle": { - "styleName": serde_json::Value::Null, - "fontSize": serde_json::Value::Null, - "fontFamily": serde_json::Value::Null, - "color": serde_json::Value::Null, - "alignment": serde_json::Value::Null, - "bold": false, - "italic": false, - "underline": false - }, - "richText": { - "layout": { - "insets": serde_json::Value::Null, - "wrap": serde_json::Value::Null, - "autoFit": serde_json::Value::Null, - "verticalAlignment": serde_json::Value::Null - }, - "ranges": [] - }, - "rotation": serde_json::Value::Null, - "flipHorizontal": false, - "flipVertical": false, - "bbox": [180, 10, 180, 90], - "bboxUnit": "points", - "textPreview": "Detailed | Shape KPI", - "textChars": 18, - "textLines": 2 - }) - ); - - let targeted = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "inspect".to_string(), - args: serde_json::json!({ - "include": "textbox", - "target": { - "id": format!("sh/{middle_text_id}"), - "before_lines": 1, - "after_lines": 1 - } - }), - }, - temp_dir.path(), - )?; - let targeted_records = parse_ndjson_lines( - targeted - .inspect_ndjson - .as_deref() - .expect("targeted inspect"), - )?; - assert_eq!( - targeted_records - .iter() - .filter_map(|record| record.get("id").and_then(serde_json::Value::as_str)) - .map(str::to_owned) - .collect::>(), - vec![ - format!("sh/{first_text_id}"), - format!("sh/{middle_text_id}"), - format!("sh/{third_text_id}") - ] - ); - - let missing_target = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "inspect".to_string(), - args: serde_json::json!({ - "include": "textbox", - "target": { - "id": "sh/missing", - "before_lines": 1, - "after_lines": 1 - } - }), - }, - temp_dir.path(), - )?; - let missing_target_records = parse_ndjson_lines( - missing_target - .inspect_ndjson - .as_deref() - .expect("missing target inspect"), - )?; - assert_eq!( - missing_target_records, - vec![serde_json::json!({ - "kind": "notice", - "noticeType": "targetNotFound", - "target": { - "id": "sh/missing", - "beforeLines": 1, - "afterLines": 1 - }, - "message": "No inspect records matched target `sh/missing`." - })] - ); - - let resolved_shape = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(missing_target.artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sh/{shape_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_shape - .resolved_record - .as_ref() - .and_then(|record| record.get("textPreview")) - .and_then(serde_json::Value::as_str), - Some("Detailed | Shape KPI") - ); - assert_eq!( - resolved_shape - .resolved_record - .as_ref() - .and_then(|record| record.get("textChars")) - .and_then(serde_json::Value::as_u64), - Some(18) - ); - assert_eq!( - resolved_shape - .resolved_record - .as_ref() - .and_then(|record| record.get("textLines")) - .and_then(serde_json::Value::as_u64), - Some(2) - ); - - let resolved_notes = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(missing_target.artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("nt/{slide_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_notes - .resolved_record - .as_ref() - .and_then(|record| record.get("textPreview")) - .and_then(serde_json::Value::as_str), - Some("Speaker note") - ); - assert_eq!( - resolved_notes - .resolved_record - .as_ref() - .and_then(|record| record.get("textChars")) - .and_then(serde_json::Value::as_u64), - Some(12) - ); - assert_eq!( - resolved_notes - .resolved_record - .as_ref() - .and_then(|record| record.get("textLines")) - .and_then(serde_json::Value::as_u64), - Some(1) - ); - Ok(()) -} - -#[test] -fn notes_visibility_controls_exported_notes() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Notes" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({ "notes": "Hidden notes" }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_notes_visibility".to_string(), - args: serde_json::json!({ "slide_index": 0, "visible": false }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": "notes-hidden.pptx" }), - }, - temp_dir.path(), - )?; - - let imported = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "import_pptx".to_string(), - args: serde_json::json!({ "path": "notes-hidden.pptx" }), - }, - temp_dir.path(), - )?; - let summary = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(imported.artifact_id), - action: "list_slides".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!( - summary - .slide_list - .as_ref() - .and_then(|slides| slides.first()) - .and_then(|slide| slide.notes.clone()), - None - ); - Ok(()) -} - -#[test] -fn image_placeholders_and_anchor_updates_work() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Images" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let placeholder = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_image".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "position": { "left": 24, "top": 24, "width": 200, "height": 120 }, - "fit": "contain", - "prompt": "Generate a hero illustration", - "alt": "Hero placeholder" - }), - }, - temp_dir.path(), - )?; - let image_anchor = placeholder - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .map(|id| format!("im/{id}")) - .expect("image anchor"); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "update_shape_style".to_string(), - args: serde_json::json!({ - "element_id": image_anchor, - "fit": "cover", - "crop": { "left": 0.1, "top": 0.0, "right": 0.1, "bottom": 0.0 }, - "rotation": 12, - "flip_horizontal": true, - "lock_aspect_ratio": true - }), - }, - temp_dir.path(), - )?; - - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": image_anchor }), - }, - temp_dir.path(), - )?; - let record = resolved.resolved_record.expect("resolved image"); - assert_eq!( - record.get("kind").and_then(serde_json::Value::as_str), - Some("image") - ); - assert_eq!( - record - .get("isPlaceholder") - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - record - .get("lockAspectRatio") - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - record.get("rotation").and_then(serde_json::Value::as_i64), - Some(12) - ); - assert_eq!( - record - .get("flipHorizontal") - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - record - .get("flipVertical") - .and_then(serde_json::Value::as_bool), - Some(false) - ); - Ok(()) -} - -#[test] -fn image_partial_resize_respects_lock_aspect_ratio() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Image Resize" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_image".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "position": { "left": 10, "top": 10, "width": 200, "height": 100 }, - "prompt": "Placeholder image", - "lock_aspect_ratio": true - }), - }, - temp_dir.path(), - )?; - let image_anchor = added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .map(|id| format!("im/{id}")) - .expect("image anchor"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "update_shape_style".to_string(), - args: serde_json::json!({ - "element_id": image_anchor, - "position": { "width": 120 } - }), - }, - temp_dir.path(), - )?; - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": image_anchor }), - }, - temp_dir.path(), - )?; - let bbox = resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("bbox")) - .and_then(serde_json::Value::as_array) - .expect("bbox"); - assert_eq!(bbox[2].as_u64(), Some(120)); - assert_eq!(bbox[3].as_u64(), Some(60)); - Ok(()) -} - -#[test] -fn connectors_support_arrows_and_inspect() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Connectors" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_connector".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "connector_type": "elbow", - "start": { "left": 20, "top": 20 }, - "end": { "left": 180, "top": 160 }, - "line": { "color": "#ff0000", "width": 2, "style": "dash-dot" }, - "start_arrow": "none", - "end_arrow": "triangle", - "arrow_size": "large", - "label": "flow" - }), - }, - temp_dir.path(), - )?; - let connector_id = added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .map(|id| format!("cn/{id}")) - .expect("connector id"); - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": connector_id }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("kind")) - .and_then(serde_json::Value::as_str), - Some("connector") - ); - let inspect = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "inspect".to_string(), - args: serde_json::json!({ "kind": "connector" }), - }, - temp_dir.path(), - )?; - assert!( - inspect - .inspect_ndjson - .expect("connector inspect") - .contains("\"kind\":\"connector\"") - ); - Ok(()) -} - -#[test] -fn shapes_support_stroke_dash_styles() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Shape Strokes" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let added_shape = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "geometry": "rectangle", - "position": { - "left": 24, - "top": 24, - "width": 180, - "height": 120, - "rotation": 15, - "flip_horizontal": true, - "flip_vertical": true - }, - "stroke": { "color": "#ff0000", "width": 2, "style": "dash-dot" } - }), - }, - temp_dir.path(), - )?; - let shape_id = added_shape - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("shape id"); - - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sh/{shape_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("stroke")) - .and_then(|stroke| stroke.get("style")) - .and_then(serde_json::Value::as_str), - Some("dash-dot") - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("rotation")) - .and_then(serde_json::Value::as_i64), - Some(15) - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("flipHorizontal")) - .and_then(serde_json::Value::as_bool), - Some(true) - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("flipVertical")) - .and_then(serde_json::Value::as_bool), - Some(true) - ); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "update_shape_style".to_string(), - args: serde_json::json!({ - "element_id": format!("sh/{shape_id}"), - "position": { - "rotation": 30, - "flip_horizontal": false, - "flip_vertical": true - } - }), - }, - temp_dir.path(), - )?; - let updated = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("sh/{shape_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - updated - .resolved_record - .as_ref() - .and_then(|record| record.get("rotation")) - .and_then(serde_json::Value::as_i64), - Some(30) - ); - assert_eq!( - updated - .resolved_record - .as_ref() - .and_then(|record| record.get("flipHorizontal")) - .and_then(serde_json::Value::as_bool), - Some(false) - ); - - let export_path = temp_dir.path().join("shape-strokes.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - - let slide_xml = zip_entry_text( - &temp_dir.path().join("shape-strokes.pptx"), - "ppt/slides/slide1.xml", - )?; - assert!(slide_xml.contains(r#""#)); - assert!(slide_xml.contains(r#""#)); - Ok(()) -} - -#[test] -fn z_order_helpers_resequence_elements() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Z Order" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let first = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "A", - "position": { "left": 10, "top": 10, "width": 100, "height": 40 } - }), - }, - temp_dir.path(), - )?; - let second = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "B", - "position": { "left": 20, "top": 20, "width": 100, "height": 40 } - }), - }, - temp_dir.path(), - )?; - let first_id = first - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("first id"); - let second_id = second - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.last()) - .cloned() - .expect("second id"); - let sent_back = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "send_to_back".to_string(), - args: serde_json::json!({ "element_id": format!("sh/{second_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - sent_back - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .map(|slide| slide.element_ids.clone()), - Some(vec![second_id.clone(), first_id.clone()]) - ); - let brought_front = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "bring_to_front".to_string(), - args: serde_json::json!({ "element_id": format!("sh/{second_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - brought_front - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .map(|slide| slide.element_ids.clone()), - Some(vec![first_id, second_id]) - ); - Ok(()) -} - -#[test] -fn manager_supports_table_cell_updates_and_merges() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Tables" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let table = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_table".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "position": { "left": 24, "top": 24, "width": 240, "height": 120 }, - "rows": [["A", "B"], ["C", "D"]], - "column_widths": [90, 150], - "row_heights": [40, 80], - "style": "TableStyleMedium9" - }), - }, - temp_dir.path(), - )?; - let table_id = table - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("table id"); - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "update_table_cell".to_string(), - args: serde_json::json!({ - "element_id": table_id, - "row": 0, - "column": 1, - "value": "Updated", - "background_fill": "#eeeeee", - "alignment": "right", - "styling": { "bold": true } - }), - }, - temp_dir.path(), - )?; - let inspect = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "inspect".to_string(), - args: serde_json::json!({ "kind": "table" }), - }, - temp_dir.path(), - )?; - assert!( - inspect - .inspect_ndjson - .expect("inspect") - .contains("\"kind\":\"table\"") - ); - let resolved = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": format!("tb/{table_id}") }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("columnWidths")) - .and_then(serde_json::Value::as_array) - .map(|widths| widths - .iter() - .filter_map(serde_json::Value::as_u64) - .collect::>()), - Some(vec![90, 150]) - ); - assert_eq!( - resolved - .resolved_record - .as_ref() - .and_then(|record| record.get("rowHeights")) - .and_then(serde_json::Value::as_array) - .map(|heights| heights - .iter() - .filter_map(serde_json::Value::as_u64) - .collect::>()), - Some(vec![40, 80]) - ); - - let merged = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "merge_table_cells".to_string(), - args: serde_json::json!({ - "element_id": table_id, - "start_row": 0, - "end_row": 0, - "start_column": 0, - "end_column": 1 - }), - }, - temp_dir.path(), - )?; - assert_eq!( - merged - .artifact_snapshot - .as_ref() - .map(|snapshot| snapshot.slide_count), - Some(1) - ); - let export_path = temp_dir.path().join("tables.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(merged.artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - let slide_xml = zip_entry_text( - &temp_dir.path().join("tables.pptx"), - "ppt/slides/slide1.xml", - )?; - assert!( - slide_xml.contains(r#""#), - "{slide_xml}" - ); - assert!(slide_xml.contains(r#""#)); - assert!(slide_xml.contains(r#""#)); - assert!(slide_xml.contains(r#""#)); - Ok(()) -} - -#[test] -fn rich_text_comments_tables_and_charts_roundtrip_through_metadata() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Parity Roundtrip" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - - let text_added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_text_shape".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "text": "Placeholder", - "position": { "left": 32, "top": 28, "width": 280, "height": 72 } - }), - }, - temp_dir.path(), - )?; - let text_id = text_added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.first()) - .cloned() - .expect("text id"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_rich_text".to_string(), - args: serde_json::json!({ - "element_id": text_id, - "text": [[ - { - "run": "Quarterly ", - "text_style": { "bold": true, "color": "#114488" } - }, - "update pipeline" - ]], - "text_layout": { - "wrap": "square", - "auto_fit": "shrinkText", - "vertical_alignment": "middle", - "insets": { "left": 6, "right": 6, "top": 4, "bottom": 4 } - } - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "format_text_range".to_string(), - args: serde_json::json!({ - "element_id": text_id, - "query": "update", - "styling": { "italic": true }, - "link": { "uri": "https://example.com/update", "is_external": true } - }), - }, - temp_dir.path(), - )?; - - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_comment_author".to_string(), - args: serde_json::json!({ - "display_name": "Jamie Fox", - "initials": "JF", - "email": "jamie@example.com" - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_comment_thread".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "element_id": text_id, - "query": "Quarterly", - "text": "Tighten this headline", - "position": { "x": 240, "y": 44 } - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_comment_reply".to_string(), - args: serde_json::json!({ - "thread_id": "thread_1", - "text": "Applied to the slide draft." - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "toggle_comment_reaction".to_string(), - args: serde_json::json!({ - "thread_id": "thread_1", - "emoji": "eyes" - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "resolve_comment_thread".to_string(), - args: serde_json::json!({ "thread_id": "thread_1" }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "reopen_comment_thread".to_string(), - args: serde_json::json!({ "thread_id": "thread_1" }), - }, - temp_dir.path(), - )?; - - let table_added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_table".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "position": { "left": 32, "top": 124, "width": 320, "height": 120 }, - "rows": [["Metric", "Value"], ["Status", "Beta"]], - "style": "TableStyleMedium2", - "style_options": { - "header_row": true, - "banded_rows": true, - "first_column": true - }, - "borders": { - "outside": { "color": "#222222", "width": 2 } - }, - "right_to_left": true - }), - }, - temp_dir.path(), - )?; - let table_id = table_added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.last()) - .cloned() - .expect("table id"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "update_table_style".to_string(), - args: serde_json::json!({ - "element_id": table_id, - "style_options": { "last_column": true, "total_row": true }, - "borders": { - "inside": { "color": "#999999", "width": 1 } - } - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "style_table_block".to_string(), - args: serde_json::json!({ - "element_id": table_id, - "row": 1, - "column": 0, - "row_count": 1, - "column_count": 2, - "background_fill": "#FFF2CC", - "alignment": "center", - "styling": { "bold": true } - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "format_text_range".to_string(), - args: serde_json::json!({ - "element_id": table_id, - "row": 1, - "column": 1, - "query": "Beta", - "styling": { "italic": true, "color": "#AA0000" } - }), - }, - temp_dir.path(), - )?; - - let chart_added = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_chart".to_string(), - args: serde_json::json!({ - "slide_index": 0, - "position": { "left": 372, "top": 120, "width": 280, "height": 210 }, - "chart_type": "bar", - "categories": ["Q1", "Q2"], - "series": [{ - "name": "Revenue", - "values": [10.0, 12.0], - "fill": "#4472C4", - "stroke": { "color": "#1F4E79", "width": 2 }, - "marker": { "symbol": "circle", "size": 7 }, - "data_label_overrides": [{ - "idx": 1, - "text": "12M", - "position": "outsideEnd", - "fill": "#FFFFFF" - }] - }], - "title": "Revenue", - "style_index": 7, - "has_legend": true, - "legend_position": "right", - "legend_text_style": { "italic": true }, - "x_axis_title": "Quarter", - "y_axis_title": "USD", - "data_labels": { - "show_value": true, - "position": "outsideEnd", - "text_style": { "bold": true } - }, - "chart_fill": "#F8F8F8", - "plot_area_fill": "#FFFFFF" - }), - }, - temp_dir.path(), - )?; - let chart_id = chart_added - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .and_then(|slide| slide.element_ids.last()) - .cloned() - .expect("chart id"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "update_chart".to_string(), - args: serde_json::json!({ - "element_id": chart_id, - "title": "Revenue outlook", - "style_index": 12, - "legend_position": "bottom", - "y_axis_title": "USD (millions)" - }), - }, - temp_dir.path(), - )?; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_chart_series".to_string(), - args: serde_json::json!({ - "element_id": chart_id, - "name": "Target", - "values": [11.0, 13.0], - "fill": "#70AD47", - "marker": { "symbol": "diamond", "size": 6 } - }), - }, - temp_dir.path(), - )?; - - let export_path = temp_dir.path().join("parity-roundtrip.pptx"); - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "export_pptx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - let metadata = zip_entry_text( - &temp_dir.path().join("parity-roundtrip.pptx"), - "ppt/codex-document.json", - )?; - assert!(metadata.contains("\"thread_id\":\"thread_1\"")); - assert!(metadata.contains("\"style_index\":12")); - assert!(metadata.contains("\"right_to_left\":true")); - - let imported = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "import_pptx".to_string(), - args: serde_json::json!({ "path": "parity-roundtrip.pptx" }), - }, - temp_dir.path(), - )?; - let imported_artifact_id = imported.artifact_id; - - let proto = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(imported_artifact_id.clone()), - action: "to_proto".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let proto = proto.proto_json.expect("proto"); - let comments = proto["commentThreads"].as_array().expect("comments"); - assert_eq!(comments.len(), 1); - assert_eq!(comments[0]["status"], "active"); - assert_eq!(comments[0]["messages"].as_array().map(Vec::len), Some(2)); - assert_eq!( - comments[0]["messages"][1]["reactions"], - serde_json::json!(["eyes"]) - ); - - let elements = proto["slides"][0]["elements"].as_array().expect("elements"); - let text_record = elements - .iter() - .find(|element| element["elementId"] == text_id) - .expect("text record"); - assert_eq!(text_record["richText"]["layout"]["wrap"], "square"); - assert_eq!(text_record["richText"]["layout"]["autoFit"], "shrinkText"); - assert_eq!( - text_record["richText"]["layout"]["verticalAlignment"], - "middle" - ); - assert_eq!( - text_record["richText"]["ranges"].as_array().map(Vec::len), - Some(2) - ); - assert!( - text_record["richText"]["ranges"] - .as_array() - .expect("text ranges") - .iter() - .any(|range| range["text"] == "update") - ); - - let table_record = elements - .iter() - .find(|element| element["elementId"] == table_id) - .expect("table record"); - assert_eq!(table_record["styleOptions"]["headerRow"], true); - assert_eq!(table_record["styleOptions"]["lastColumn"], true); - assert_eq!(table_record["rightToLeft"], true); - assert_eq!(table_record["borders"]["outside"]["color"], "222222"); - assert_eq!( - table_record["rows"][1][1]["richText"]["ranges"] - .as_array() - .map(Vec::len), - Some(1) - ); - - let chart_record = elements - .iter() - .find(|element| element["elementId"] == chart_id) - .expect("chart record"); - assert_eq!(chart_record["styleIndex"], 12); - assert_eq!(chart_record["legend"]["position"], "bottom"); - assert_eq!(chart_record["series"].as_array().map(Vec::len), Some(2)); - assert_eq!(chart_record["series"][1]["name"], "Target"); - - let inspect = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(imported_artifact_id.clone()), - action: "inspect".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let inspect_ndjson = inspect.inspect_ndjson.expect("inspect"); - assert!(inspect_ndjson.contains("\"kind\":\"comment\"")); - assert!(inspect_ndjson.contains("\"kind\":\"textRange\"")); - assert!(inspect_ndjson.contains("\"chartType\":\"Bar\"")); - - let resolved_thread = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(imported_artifact_id.clone()), - action: "resolve".to_string(), - args: serde_json::json!({ "id": "th/thread_1" }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_thread - .resolved_record - .as_ref() - .and_then(|record| record.get("target")) - .and_then(|target| target.get("type")), - Some(&serde_json::json!("textRange")) - ); - - let resolved_range = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(imported_artifact_id), - action: "resolve".to_string(), - args: serde_json::json!({ "id": "tr/range_1" }), - }, - temp_dir.path(), - )?; - assert_eq!( - resolved_range - .resolved_record - .as_ref() - .and_then(|record| record.get("text")), - Some(&serde_json::json!("update")) - ); - Ok(()) -} - -#[test] -fn history_can_undo_and_redo_created_artifact() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "History" }), - }, - temp_dir.path(), - )?; - - let undone = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "undo".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!(undone.artifact_id, created.artifact_id); - assert!(undone.artifact_snapshot.is_none()); - assert!( - manager - .execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "get_summary".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - ) - .is_err() - ); - - let redone = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(created.artifact_id.clone()), - action: "redo".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!(redone.artifact_id, created.artifact_id); - assert_eq!( - redone - .artifact_snapshot - .as_ref() - .map(|snapshot| snapshot.slide_count), - Some(0) - ); - Ok(()) -} - -#[test] -fn proto_and_patch_actions_work_and_patch_history_is_atomic() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = PresentationArtifactManager::default(); - let created = manager.execute( - PresentationArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Proto Patch" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "add_slide".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - - let patch_ops = serde_json::json!([ - { - "action": "add_text_shape", - "args": { - "slide_index": 0, - "text": "Patch text", - "position": { "left": 40, "top": 60, "width": 180, "height": 50 } - } - }, - { - "action": "set_slide_background", - "args": { - "slide_index": 0, - "fill": "#ffeecc" - } - } - ]); - let recorded = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "record_patch".to_string(), - args: serde_json::json!({ "operations": patch_ops }), - }, - temp_dir.path(), - )?; - let expected_patch = serde_json::json!({ - "version": 1, - "artifactId": artifact_id, - "operations": [ - { - "action": "add_text_shape", - "args": { - "slide_index": 0, - "text": "Patch text", - "position": { "left": 40, "top": 60, "width": 180, "height": 50 } - } - }, - { - "action": "set_slide_background", - "args": { - "slide_index": 0, - "fill": "#ffeecc" - } - } - ] - }); - assert_eq!(recorded.patch.as_ref(), Some(&expected_patch)); - - let applied = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "apply_patch".to_string(), - args: serde_json::json!({ "patch": expected_patch }), - }, - temp_dir.path(), - )?; - let slide_snapshot = applied - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .cloned() - .expect("slide snapshot"); - let slide_id = slide_snapshot.slide_id.clone(); - let element_id = slide_snapshot - .element_ids - .first() - .cloned() - .expect("element id"); - - let proto = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "to_proto".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - let proto = proto.proto_json.expect("proto"); - assert_eq!(proto["kind"], "presentation"); - assert_eq!(proto["artifactId"], artifact_id); - assert_eq!(proto["activeSlideId"], slide_id); - assert_eq!(proto["commentAuthor"], serde_json::Value::Null); - assert_eq!(proto["commentThreads"], serde_json::json!([])); - assert_eq!(proto["masters"], serde_json::json!([])); - assert_eq!(proto["layouts"], serde_json::json!([])); - assert_eq!(proto["theme"]["hexColorMap"], serde_json::json!({})); - assert_eq!(proto["styles"].as_array().map(Vec::len), Some(5)); - assert_eq!(proto["slides"].as_array().map(Vec::len), Some(1)); - assert_eq!(proto["slides"][0]["slideId"], slide_id); - assert_eq!(proto["slides"][0]["backgroundFill"], "FFEECC"); - assert_eq!( - proto["slides"][0]["notes"]["richText"]["ranges"], - serde_json::json!([]) - ); - assert_eq!( - proto["slides"][0]["elements"].as_array().map(Vec::len), - Some(1) - ); - assert_eq!(proto["slides"][0]["elements"][0]["elementId"], element_id); - assert_eq!(proto["slides"][0]["elements"][0]["text"], "Patch text"); - assert_eq!( - proto["slides"][0]["elements"][0]["richText"]["ranges"], - serde_json::json!([]) - ); - - let undone = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "undo".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!( - undone - .artifact_snapshot - .as_ref() - .and_then(|snapshot| snapshot.slides.first()) - .map(|slide| slide.element_ids.clone()), - Some(Vec::new()) - ); - let undone_proto = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "to_proto".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!( - undone_proto - .proto_json - .as_ref() - .and_then(|proto| proto.get("slides")) - .and_then(serde_json::Value::as_array) - .and_then(|slides| slides.first()) - .and_then(|slide| slide.get("backgroundFill")), - Some(&serde_json::Value::Null) - ); - assert_eq!( - undone_proto - .proto_json - .as_ref() - .and_then(|proto| proto.get("slides")) - .and_then(serde_json::Value::as_array) - .and_then(|slides| slides.first()) - .and_then(|slide| slide.get("elements")) - .and_then(serde_json::Value::as_array) - .map(Vec::len), - Some(0) - ); - - let redone = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "redo".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!(redone.patch, None); - let redone_proto = manager.execute( - PresentationArtifactRequest { - artifact_id: Some(artifact_id), - action: "to_proto".to_string(), - args: serde_json::json!({}), - }, - temp_dir.path(), - )?; - assert_eq!(redone_proto.proto_json, Some(proto)); - Ok(()) -} diff --git a/codex-rs/artifact-spreadsheet/BUILD.bazel b/codex-rs/artifact-spreadsheet/BUILD.bazel deleted file mode 100644 index 07d1337283..0000000000 --- a/codex-rs/artifact-spreadsheet/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "artifact-spreadsheet", - crate_name = "codex_artifact_spreadsheet", -) diff --git a/codex-rs/artifact-spreadsheet/Cargo.toml b/codex-rs/artifact-spreadsheet/Cargo.toml deleted file mode 100644 index 66e030ea43..0000000000 --- a/codex-rs/artifact-spreadsheet/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "codex-artifact-spreadsheet" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lib] -name = "codex_artifact_spreadsheet" -path = "src/lib.rs" - -[lints] -workspace = true - -[dependencies] -base64 = { workspace = true } -regex = { workspace = true } -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -thiserror = { workspace = true } -uuid = { workspace = true, features = ["v4"] } -zip = { workspace = true } - -[dev-dependencies] -pretty_assertions = { workspace = true } -tempfile = { workspace = true } diff --git a/codex-rs/artifact-spreadsheet/src/address.rs b/codex-rs/artifact-spreadsheet/src/address.rs deleted file mode 100644 index 28e4da5e3a..0000000000 --- a/codex-rs/artifact-spreadsheet/src/address.rs +++ /dev/null @@ -1,245 +0,0 @@ -use serde::Deserialize; -use serde::Serialize; - -use crate::SpreadsheetArtifactError; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -pub struct CellAddress { - pub column: u32, - pub row: u32, -} - -impl CellAddress { - pub fn parse(address: &str) -> Result { - let trimmed = address.trim(); - if trimmed.is_empty() { - return Err(SpreadsheetArtifactError::InvalidAddress { - address: address.to_string(), - message: "address is empty".to_string(), - }); - } - - let mut split = 0usize; - for (index, ch) in trimmed.char_indices() { - if ch.is_ascii_alphabetic() { - split = index + ch.len_utf8(); - } else { - break; - } - } - - let (letters, digits) = trimmed.split_at(split); - if letters.is_empty() || digits.is_empty() { - return Err(SpreadsheetArtifactError::InvalidAddress { - address: address.to_string(), - message: "expected A1-style address".to_string(), - }); - } - - if !letters.chars().all(|ch| ch.is_ascii_alphabetic()) - || !digits.chars().all(|ch| ch.is_ascii_digit()) - { - return Err(SpreadsheetArtifactError::InvalidAddress { - address: address.to_string(), - message: "expected letters followed by digits".to_string(), - }); - } - - let column = column_letters_to_index(letters)?; - let row = digits - .parse::() - .map_err(|_| SpreadsheetArtifactError::InvalidAddress { - address: address.to_string(), - message: "row must be a positive integer".to_string(), - })?; - - if row == 0 { - return Err(SpreadsheetArtifactError::InvalidAddress { - address: address.to_string(), - message: "row must be positive".to_string(), - }); - } - - Ok(Self { column, row }) - } - - pub fn to_a1(self) -> String { - format!("{}{}", column_index_to_letters(self.column), self.row) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CellRange { - pub start: CellAddress, - pub end: CellAddress, -} - -impl CellRange { - pub fn parse(address: &str) -> Result { - let trimmed = address.trim(); - if trimmed.is_empty() { - return Err(SpreadsheetArtifactError::InvalidAddress { - address: address.to_string(), - message: "range is empty".to_string(), - }); - } - - let (start, end) = if let Some((left, right)) = trimmed.split_once(':') { - (CellAddress::parse(left)?, CellAddress::parse(right)?) - } else { - let cell = CellAddress::parse(trimmed)?; - (cell, cell) - }; - - let normalized = Self { - start: CellAddress { - column: start.column.min(end.column), - row: start.row.min(end.row), - }, - end: CellAddress { - column: start.column.max(end.column), - row: start.row.max(end.row), - }, - }; - Ok(normalized) - } - - pub fn from_start_end(start: CellAddress, end: CellAddress) -> Self { - Self { - start: CellAddress { - column: start.column.min(end.column), - row: start.row.min(end.row), - }, - end: CellAddress { - column: start.column.max(end.column), - row: start.row.max(end.row), - }, - } - } - - pub fn to_a1(&self) -> String { - if self.is_single_cell() { - self.start.to_a1() - } else { - format!("{}:{}", self.start.to_a1(), self.end.to_a1()) - } - } - - pub fn is_single_cell(&self) -> bool { - self.start == self.end - } - - pub fn is_single_row(&self) -> bool { - self.start.row == self.end.row - } - - pub fn is_single_column(&self) -> bool { - self.start.column == self.end.column - } - - pub fn width(&self) -> usize { - (self.end.column - self.start.column + 1) as usize - } - - pub fn height(&self) -> usize { - (self.end.row - self.start.row + 1) as usize - } - - pub fn contains(&self, address: CellAddress) -> bool { - self.start.column <= address.column - && address.column <= self.end.column - && self.start.row <= address.row - && address.row <= self.end.row - } - - pub fn contains_range(&self, other: &CellRange) -> bool { - self.contains(other.start) && self.contains(other.end) - } - - pub fn intersects(&self, other: &CellRange) -> bool { - !(self.end.column < other.start.column - || other.end.column < self.start.column - || self.end.row < other.start.row - || other.end.row < self.start.row) - } - - pub fn addresses(&self) -> impl Iterator { - let range = self.clone(); - (range.start.row..=range.end.row).flat_map(move |row| { - let range = range.clone(); - (range.start.column..=range.end.column).map(move |column| CellAddress { column, row }) - }) - } -} - -pub fn column_letters_to_index(column: &str) -> Result { - let trimmed = column.trim(); - if trimmed.is_empty() { - return Err(SpreadsheetArtifactError::InvalidAddress { - address: column.to_string(), - message: "column is empty".to_string(), - }); - } - - let mut result = 0u32; - for ch in trimmed.chars() { - if !ch.is_ascii_alphabetic() { - return Err(SpreadsheetArtifactError::InvalidAddress { - address: column.to_string(), - message: "column must contain only letters".to_string(), - }); - } - result = result - .checked_mul(26) - .and_then(|value| value.checked_add((ch.to_ascii_uppercase() as u8 - b'A' + 1) as u32)) - .ok_or_else(|| SpreadsheetArtifactError::InvalidAddress { - address: column.to_string(), - message: "column is too large".to_string(), - })?; - } - Ok(result) -} - -pub fn column_index_to_letters(mut index: u32) -> String { - if index == 0 { - return String::new(); - } - - let mut letters = Vec::new(); - while index > 0 { - let remainder = (index - 1) % 26; - letters.push((b'A' + remainder as u8) as char); - index = (index - 1) / 26; - } - letters.iter().rev().collect() -} - -pub fn parse_column_reference(reference: &str) -> Result<(u32, u32), SpreadsheetArtifactError> { - let trimmed = reference.trim(); - if let Some((left, right)) = trimmed.split_once(':') { - let start = column_letters_to_index(left)?; - let end = column_letters_to_index(right)?; - Ok((start.min(end), start.max(end))) - } else { - let column = column_letters_to_index(trimmed)?; - Ok((column, column)) - } -} - -pub fn is_valid_cell_reference(address: &str) -> bool { - CellAddress::parse(address).is_ok() -} - -pub fn is_valid_range_reference(address: &str) -> bool { - CellRange::parse(address).is_ok() -} - -pub fn is_valid_row_reference(address: &str) -> bool { - CellRange::parse(address) - .map(|range| range.is_single_row()) - .unwrap_or(false) -} - -pub fn is_valid_column_reference(address: &str) -> bool { - parse_column_reference(address).is_ok() -} diff --git a/codex-rs/artifact-spreadsheet/src/chart.rs b/codex-rs/artifact-spreadsheet/src/chart.rs deleted file mode 100644 index 83b02b6be1..0000000000 --- a/codex-rs/artifact-spreadsheet/src/chart.rs +++ /dev/null @@ -1,357 +0,0 @@ -use serde::Deserialize; -use serde::Serialize; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetSheet; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum SpreadsheetChartType { - Area, - Bar, - Doughnut, - Line, - Pie, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum SpreadsheetChartLegendPosition { - Bottom, - Top, - Left, - Right, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetChartLegend { - pub visible: bool, - pub position: SpreadsheetChartLegendPosition, - pub overlay: bool, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetChartAxis { - pub linked_number_format: bool, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetChartSeries { - pub id: u32, - pub name: Option, - pub category_sheet_name: Option, - pub category_range: String, - pub value_sheet_name: Option, - pub value_range: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetChart { - pub id: u32, - pub chart_type: SpreadsheetChartType, - pub source_sheet_name: Option, - pub source_range: Option, - pub title: Option, - pub style_index: u32, - pub display_blanks_as: String, - pub legend: SpreadsheetChartLegend, - pub category_axis: SpreadsheetChartAxis, - pub value_axis: SpreadsheetChartAxis, - #[serde(default)] - pub series: Vec, -} - -#[derive(Debug, Clone, Default)] -pub struct SpreadsheetChartLookup { - pub id: Option, - pub index: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetChartCreateOptions { - pub id: Option, - pub title: Option, - pub legend_visible: Option, - pub legend_position: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetChartProperties { - pub title: Option, - pub legend_visible: Option, - pub legend_position: Option, -} - -impl SpreadsheetSheet { - pub fn list_charts( - &self, - range: Option<&CellRange>, - ) -> Result, SpreadsheetArtifactError> { - Ok(self - .charts - .iter() - .filter(|chart| { - range.is_none_or(|target| { - chart - .source_range - .as_deref() - .map(CellRange::parse) - .transpose() - .ok() - .flatten() - .is_some_and(|chart_range| chart_range.intersects(target)) - }) - }) - .cloned() - .collect()) - } - - pub fn get_chart( - &self, - action: &str, - lookup: SpreadsheetChartLookup, - ) -> Result<&SpreadsheetChart, SpreadsheetArtifactError> { - if let Some(id) = lookup.id { - return self - .charts - .iter() - .find(|chart| chart.id == id) - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("chart id `{id}` was not found"), - }); - } - if let Some(index) = lookup.index { - return self.charts.get(index).ok_or_else(|| { - SpreadsheetArtifactError::IndexOutOfRange { - action: action.to_string(), - index, - len: self.charts.len(), - } - }); - } - Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "chart id or index is required".to_string(), - }) - } - - pub fn create_chart( - &mut self, - action: &str, - chart_type: SpreadsheetChartType, - source_sheet_name: Option, - source_range: &CellRange, - options: SpreadsheetChartCreateOptions, - ) -> Result { - if source_range.width() < 2 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "chart source range must include at least two columns".to_string(), - }); - } - let id = if let Some(id) = options.id { - if self.charts.iter().any(|chart| chart.id == id) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("chart id `{id}` already exists"), - }); - } - id - } else { - self.charts.iter().map(|chart| chart.id).max().unwrap_or(0) + 1 - }; - let series = (source_range.start.column + 1..=source_range.end.column) - .enumerate() - .map(|(index, value_column)| SpreadsheetChartSeries { - id: index as u32 + 1, - name: None, - category_sheet_name: source_sheet_name.clone(), - category_range: CellRange::from_start_end( - source_range.start, - CellAddress { - column: source_range.start.column, - row: source_range.end.row, - }, - ) - .to_a1(), - value_sheet_name: source_sheet_name.clone(), - value_range: CellRange::from_start_end( - CellAddress { - column: value_column, - row: source_range.start.row, - }, - CellAddress { - column: value_column, - row: source_range.end.row, - }, - ) - .to_a1(), - }) - .collect::>(); - self.charts.push(SpreadsheetChart { - id, - chart_type, - source_sheet_name, - source_range: Some(source_range.to_a1()), - title: options.title, - style_index: 102, - display_blanks_as: "gap".to_string(), - legend: SpreadsheetChartLegend { - visible: options.legend_visible.unwrap_or(true), - position: options - .legend_position - .unwrap_or(SpreadsheetChartLegendPosition::Bottom), - overlay: false, - }, - category_axis: SpreadsheetChartAxis { - linked_number_format: true, - }, - value_axis: SpreadsheetChartAxis { - linked_number_format: true, - }, - series, - }); - Ok(id) - } - - pub fn add_chart_series( - &mut self, - action: &str, - lookup: SpreadsheetChartLookup, - mut series: SpreadsheetChartSeries, - ) -> Result { - validate_chart_series(action, &series)?; - let chart = self.get_chart_mut(action, lookup)?; - let next_id = chart.series.iter().map(|entry| entry.id).max().unwrap_or(0) + 1; - series.id = next_id; - chart.series.push(series); - Ok(next_id) - } - - pub fn delete_chart( - &mut self, - action: &str, - lookup: SpreadsheetChartLookup, - ) -> Result<(), SpreadsheetArtifactError> { - let index = if let Some(id) = lookup.id { - self.charts - .iter() - .position(|chart| chart.id == id) - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("chart id `{id}` was not found"), - })? - } else if let Some(index) = lookup.index { - if index >= self.charts.len() { - return Err(SpreadsheetArtifactError::IndexOutOfRange { - action: action.to_string(), - index, - len: self.charts.len(), - }); - } - index - } else { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "chart id or index is required".to_string(), - }); - }; - self.charts.remove(index); - Ok(()) - } - - pub fn set_chart_properties( - &mut self, - action: &str, - lookup: SpreadsheetChartLookup, - properties: SpreadsheetChartProperties, - ) -> Result<(), SpreadsheetArtifactError> { - let chart = self.get_chart_mut(action, lookup)?; - if let Some(title) = properties.title { - chart.title = Some(title); - } - if let Some(visible) = properties.legend_visible { - chart.legend.visible = visible; - } - if let Some(position) = properties.legend_position { - chart.legend.position = position; - } - Ok(()) - } - - pub fn validate_charts(&self, action: &str) -> Result<(), SpreadsheetArtifactError> { - for chart in &self.charts { - if let Some(source_range) = &chart.source_range { - let range = CellRange::parse(source_range)?; - if range.width() < 2 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!( - "chart `{}` source range `{source_range}` is too narrow", - chart.id - ), - }); - } - } - for series in &chart.series { - validate_chart_series(action, series)?; - } - } - Ok(()) - } - - fn get_chart_mut( - &mut self, - action: &str, - lookup: SpreadsheetChartLookup, - ) -> Result<&mut SpreadsheetChart, SpreadsheetArtifactError> { - if let Some(id) = lookup.id { - return self - .charts - .iter_mut() - .find(|chart| chart.id == id) - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("chart id `{id}` was not found"), - }); - } - if let Some(index) = lookup.index { - let len = self.charts.len(); - return self.charts.get_mut(index).ok_or_else(|| { - SpreadsheetArtifactError::IndexOutOfRange { - action: action.to_string(), - index, - len, - } - }); - } - Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "chart id or index is required".to_string(), - }) - } -} - -fn validate_chart_series( - action: &str, - series: &SpreadsheetChartSeries, -) -> Result<(), SpreadsheetArtifactError> { - let category_range = CellRange::parse(&series.category_range)?; - let value_range = CellRange::parse(&series.value_range)?; - if !category_range.is_single_column() || !value_range.is_single_column() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "chart category and value ranges must be single-column ranges".to_string(), - }); - } - if category_range.height() != value_range.height() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "chart category and value series lengths must match".to_string(), - }); - } - Ok(()) -} diff --git a/codex-rs/artifact-spreadsheet/src/conditional.rs b/codex-rs/artifact-spreadsheet/src/conditional.rs deleted file mode 100644 index 96c0c8ebd8..0000000000 --- a/codex-rs/artifact-spreadsheet/src/conditional.rs +++ /dev/null @@ -1,308 +0,0 @@ -use serde::Deserialize; -use serde::Serialize; - -use crate::CellRange; -use crate::SpreadsheetArtifact; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetSheet; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum SpreadsheetConditionalFormatType { - Expression, - CellIs, - ColorScale, - DataBar, - IconSet, - Top10, - UniqueValues, - DuplicateValues, - ContainsText, - NotContainsText, - BeginsWith, - EndsWith, - ContainsBlanks, - NotContainsBlanks, - ContainsErrors, - NotContainsErrors, - TimePeriod, - AboveAverage, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetColorScale { - pub min_type: Option, - pub mid_type: Option, - pub max_type: Option, - pub min_value: Option, - pub mid_value: Option, - pub max_value: Option, - pub min_color: String, - pub mid_color: Option, - pub max_color: String, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetDataBar { - pub color: String, - pub min_length: Option, - pub max_length: Option, - pub show_value: Option, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetIconSet { - pub style: String, - pub show_value: Option, - pub reverse_order: Option, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetConditionalFormat { - pub id: u32, - pub range: String, - pub rule_type: SpreadsheetConditionalFormatType, - pub operator: Option, - #[serde(default)] - pub formulas: Vec, - pub text: Option, - pub dxf_id: Option, - pub stop_if_true: bool, - pub priority: u32, - pub rank: Option, - pub percent: Option, - pub time_period: Option, - pub above_average: Option, - pub equal_average: Option, - pub color_scale: Option, - pub data_bar: Option, - pub icon_set: Option, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetConditionalFormatCollection { - pub sheet_name: String, - pub range: String, -} - -impl SpreadsheetConditionalFormatCollection { - pub fn new(sheet_name: String, range: &CellRange) -> Self { - Self { - sheet_name, - range: range.to_a1(), - } - } - - pub fn range(&self) -> Result { - CellRange::parse(&self.range) - } - - pub fn list( - &self, - artifact: &SpreadsheetArtifact, - ) -> Result, SpreadsheetArtifactError> { - let sheet = artifact.sheet_lookup( - "conditional_format_collection", - Some(&self.sheet_name), - None, - )?; - Ok(sheet.list_conditional_formats(Some(&self.range()?))) - } - - pub fn add( - &self, - artifact: &mut SpreadsheetArtifact, - mut format: SpreadsheetConditionalFormat, - ) -> Result { - format.range = self.range.clone(); - artifact.add_conditional_format("conditional_format_collection", &self.sheet_name, format) - } - - pub fn delete( - &self, - artifact: &mut SpreadsheetArtifact, - id: u32, - ) -> Result<(), SpreadsheetArtifactError> { - artifact.delete_conditional_format("conditional_format_collection", &self.sheet_name, id) - } -} - -impl SpreadsheetArtifact { - pub fn validate_conditional_formats( - &self, - action: &str, - sheet_name: &str, - ) -> Result<(), SpreadsheetArtifactError> { - let sheet = self.sheet_lookup(action, Some(sheet_name), None)?; - for format in &sheet.conditional_formats { - validate_conditional_format(self, format, action)?; - } - Ok(()) - } - - pub fn add_conditional_format( - &mut self, - action: &str, - sheet_name: &str, - mut format: SpreadsheetConditionalFormat, - ) -> Result { - validate_conditional_format(self, &format, action)?; - let sheet = self.sheet_lookup_mut(action, Some(sheet_name), None)?; - let next_id = sheet - .conditional_formats - .iter() - .map(|entry| entry.id) - .max() - .unwrap_or(0) - + 1; - format.id = next_id; - format.priority = if format.priority == 0 { - next_id - } else { - format.priority - }; - sheet.conditional_formats.push(format); - Ok(next_id) - } - - pub fn delete_conditional_format( - &mut self, - action: &str, - sheet_name: &str, - id: u32, - ) -> Result<(), SpreadsheetArtifactError> { - let sheet = self.sheet_lookup_mut(action, Some(sheet_name), None)?; - let previous_len = sheet.conditional_formats.len(); - sheet.conditional_formats.retain(|entry| entry.id != id); - if sheet.conditional_formats.len() == previous_len { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("conditional format `{id}` was not found"), - }); - } - Ok(()) - } -} - -impl SpreadsheetSheet { - pub fn conditional_format_collection( - &self, - range: &CellRange, - ) -> SpreadsheetConditionalFormatCollection { - SpreadsheetConditionalFormatCollection::new(self.name.clone(), range) - } - - pub fn list_conditional_formats( - &self, - range: Option<&CellRange>, - ) -> Vec { - self.conditional_formats - .iter() - .filter(|entry| { - range.is_none_or(|target| { - CellRange::parse(&entry.range) - .map(|entry_range| entry_range.intersects(target)) - .unwrap_or(false) - }) - }) - .cloned() - .collect() - } -} - -fn validate_conditional_format( - artifact: &SpreadsheetArtifact, - format: &SpreadsheetConditionalFormat, - action: &str, -) -> Result<(), SpreadsheetArtifactError> { - CellRange::parse(&format.range)?; - if let Some(dxf_id) = format.dxf_id - && artifact.get_differential_format(dxf_id).is_none() - { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("differential format `{dxf_id}` was not found"), - }); - } - - let has_style = format.dxf_id.is_some(); - let has_intrinsic_visual = - format.color_scale.is_some() || format.data_bar.is_some() || format.icon_set.is_some(); - - match format.rule_type { - SpreadsheetConditionalFormatType::Expression | SpreadsheetConditionalFormatType::CellIs => { - if format.formulas.is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "conditional format formulas are required".to_string(), - }); - } - } - SpreadsheetConditionalFormatType::ContainsText - | SpreadsheetConditionalFormatType::NotContainsText - | SpreadsheetConditionalFormatType::BeginsWith - | SpreadsheetConditionalFormatType::EndsWith => { - if format.text.as_deref().unwrap_or_default().is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "conditional format text is required".to_string(), - }); - } - } - SpreadsheetConditionalFormatType::ColorScale => { - if format.color_scale.is_none() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "color scale settings are required".to_string(), - }); - } - } - SpreadsheetConditionalFormatType::DataBar => { - if format.data_bar.is_none() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "data bar settings are required".to_string(), - }); - } - } - SpreadsheetConditionalFormatType::IconSet => { - if format.icon_set.is_none() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "icon set settings are required".to_string(), - }); - } - } - SpreadsheetConditionalFormatType::Top10 => { - if format.rank.is_none() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "top10 rank is required".to_string(), - }); - } - } - SpreadsheetConditionalFormatType::TimePeriod => { - if format.time_period.as_deref().unwrap_or_default().is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "time period is required".to_string(), - }); - } - } - SpreadsheetConditionalFormatType::AboveAverage => {} - SpreadsheetConditionalFormatType::UniqueValues - | SpreadsheetConditionalFormatType::DuplicateValues - | SpreadsheetConditionalFormatType::ContainsBlanks - | SpreadsheetConditionalFormatType::NotContainsBlanks - | SpreadsheetConditionalFormatType::ContainsErrors - | SpreadsheetConditionalFormatType::NotContainsErrors => {} - } - - if !has_style && !has_intrinsic_visual { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "conditional formatting requires at least one style component".to_string(), - }); - } - Ok(()) -} diff --git a/codex-rs/artifact-spreadsheet/src/error.rs b/codex-rs/artifact-spreadsheet/src/error.rs deleted file mode 100644 index d6d0b31bc5..0000000000 --- a/codex-rs/artifact-spreadsheet/src/error.rs +++ /dev/null @@ -1,39 +0,0 @@ -use std::path::PathBuf; - -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum SpreadsheetArtifactError { - #[error("missing `artifact_id` for action `{action}`")] - MissingArtifactId { action: String }, - #[error("unknown artifact id `{artifact_id}` for action `{action}`")] - UnknownArtifactId { action: String, artifact_id: String }, - #[error("unknown action `{0}`")] - UnknownAction(String), - #[error("invalid args for action `{action}`: {message}")] - InvalidArgs { action: String, message: String }, - #[error("invalid address `{address}`: {message}")] - InvalidAddress { address: String, message: String }, - #[error("sheet lookup failed for action `{action}`: {message}")] - SheetLookup { action: String, message: String }, - #[error("index `{index}` is out of range for action `{action}`; len={len}")] - IndexOutOfRange { - action: String, - index: usize, - len: usize, - }, - #[error("merge conflict for action `{action}` on range `{range}` with `{conflict}`")] - MergeConflict { - action: String, - range: String, - conflict: String, - }, - #[error("formula error at `{location}`: {message}")] - Formula { location: String, message: String }, - #[error("serialization failed: {message}")] - Serialization { message: String }, - #[error("failed to import XLSX `{path}`: {message}")] - ImportFailed { path: PathBuf, message: String }, - #[error("failed to export XLSX `{path}`: {message}")] - ExportFailed { path: PathBuf, message: String }, -} diff --git a/codex-rs/artifact-spreadsheet/src/formula.rs b/codex-rs/artifact-spreadsheet/src/formula.rs deleted file mode 100644 index 9ee8d0824f..0000000000 --- a/codex-rs/artifact-spreadsheet/src/formula.rs +++ /dev/null @@ -1,535 +0,0 @@ -use std::collections::BTreeSet; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifact; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetCellValue; - -#[derive(Debug, Clone)] -enum Token { - Number(f64), - Cell(String), - Ident(String), - Plus, - Minus, - Star, - Slash, - LParen, - RParen, - Colon, - Comma, -} - -#[derive(Debug, Clone)] -enum Expr { - Number(f64), - Cell(CellAddress), - Range(CellRange), - UnaryMinus(Box), - Binary { - op: BinaryOp, - left: Box, - right: Box, - }, - Function { - name: String, - args: Vec, - }, -} - -#[derive(Debug, Clone, Copy)] -enum BinaryOp { - Add, - Subtract, - Multiply, - Divide, -} - -#[derive(Debug, Clone)] -enum EvalValue { - Scalar(Option), - Range(Vec>), -} - -pub(crate) fn recalculate_workbook(artifact: &mut SpreadsheetArtifact) { - let updates = artifact - .sheets - .iter() - .enumerate() - .flat_map(|(sheet_index, sheet)| { - sheet.cells.iter().filter_map(move |(address, cell)| { - cell.formula - .as_ref() - .map(|formula| (sheet_index, *address, formula.clone())) - }) - }) - .map(|(sheet_index, address, formula)| { - let mut stack = BTreeSet::new(); - let value = evaluate_formula(artifact, sheet_index, &formula, &mut stack) - .unwrap_or_else(|error| { - Some(SpreadsheetCellValue::Error(map_error_to_code(&error))) - }); - (sheet_index, address, value) - }) - .collect::>(); - - for (sheet_index, address, value) in updates { - if let Some(sheet) = artifact.sheets.get_mut(sheet_index) - && let Some(cell) = sheet.cells.get_mut(&address) - { - cell.value = value; - } - } -} - -fn evaluate_formula( - artifact: &SpreadsheetArtifact, - sheet_index: usize, - formula: &str, - stack: &mut BTreeSet<(usize, CellAddress)>, -) -> Result, SpreadsheetArtifactError> { - let source = formula.trim().trim_start_matches('='); - let tokens = tokenize(source)?; - let mut parser = Parser::new(tokens); - let expr = parser.parse_expression()?; - if parser.has_remaining() { - return Err(SpreadsheetArtifactError::Formula { - location: formula.to_string(), - message: "unexpected trailing tokens".to_string(), - }); - } - match evaluate_expr(artifact, sheet_index, &expr, stack)? { - EvalValue::Scalar(value) => Ok(value), - EvalValue::Range(_) => Err(SpreadsheetArtifactError::Formula { - location: formula.to_string(), - message: "range expressions are only allowed inside functions".to_string(), - }), - } -} - -fn evaluate_expr( - artifact: &SpreadsheetArtifact, - sheet_index: usize, - expr: &Expr, - stack: &mut BTreeSet<(usize, CellAddress)>, -) -> Result { - match expr { - Expr::Number(value) => Ok(EvalValue::Scalar(Some(number_to_value(*value)))), - Expr::Cell(address) => evaluate_cell_reference(artifact, sheet_index, *address, stack), - Expr::Range(range) => { - let sheet = artifact.sheets.get(sheet_index).ok_or_else(|| { - SpreadsheetArtifactError::Formula { - location: range.to_a1(), - message: "sheet index was not found".to_string(), - } - })?; - let values = range - .addresses() - .map(|address| sheet.get_cell(address).and_then(|cell| cell.value.clone())) - .collect::>(); - Ok(EvalValue::Range(values)) - } - Expr::UnaryMinus(inner) => { - let value = evaluate_scalar(artifact, sheet_index, inner, stack)?; - Ok(EvalValue::Scalar(match value { - None => Some(SpreadsheetCellValue::Integer(0)), - Some(SpreadsheetCellValue::Integer(value)) => { - Some(SpreadsheetCellValue::Integer(-value)) - } - Some(SpreadsheetCellValue::Float(value)) => { - Some(SpreadsheetCellValue::Float(-value)) - } - Some(SpreadsheetCellValue::Error(value)) => { - Some(SpreadsheetCellValue::Error(value)) - } - Some(_) => Some(SpreadsheetCellValue::Error("#VALUE!".to_string())), - })) - } - Expr::Binary { op, left, right } => { - let left = evaluate_scalar(artifact, sheet_index, left, stack)?; - let right = evaluate_scalar(artifact, sheet_index, right, stack)?; - Ok(EvalValue::Scalar(Some(apply_binary_op(*op, left, right)?))) - } - Expr::Function { name, args } => { - let mut numeric = Vec::new(); - for arg in args { - match evaluate_expr(artifact, sheet_index, arg, stack)? { - EvalValue::Scalar(value) => { - if let Some(number) = scalar_to_number(value.clone())? { - numeric.push(number); - } - } - EvalValue::Range(values) => { - for value in values { - if let Some(number) = scalar_to_number(value.clone())? { - numeric.push(number); - } - } - } - } - } - let upper = name.to_ascii_uppercase(); - let result = match upper.as_str() { - "SUM" => numeric.iter().sum::(), - "AVERAGE" => { - if numeric.is_empty() { - return Ok(EvalValue::Scalar(None)); - } - numeric.iter().sum::() / numeric.len() as f64 - } - "MIN" => numeric.iter().copied().reduce(f64::min).unwrap_or(0.0), - "MAX" => numeric.iter().copied().reduce(f64::max).unwrap_or(0.0), - _ => { - return Ok(EvalValue::Scalar(Some(SpreadsheetCellValue::Error( - "#NAME?".to_string(), - )))); - } - }; - Ok(EvalValue::Scalar(Some(number_to_value(result)))) - } - } -} - -fn evaluate_scalar( - artifact: &SpreadsheetArtifact, - sheet_index: usize, - expr: &Expr, - stack: &mut BTreeSet<(usize, CellAddress)>, -) -> Result, SpreadsheetArtifactError> { - match evaluate_expr(artifact, sheet_index, expr, stack)? { - EvalValue::Scalar(value) => Ok(value), - EvalValue::Range(_) => Err(SpreadsheetArtifactError::Formula { - location: format!("{expr:?}"), - message: "expected a scalar expression".to_string(), - }), - } -} - -fn evaluate_cell_reference( - artifact: &SpreadsheetArtifact, - sheet_index: usize, - address: CellAddress, - stack: &mut BTreeSet<(usize, CellAddress)>, -) -> Result { - let Some(sheet) = artifact.sheets.get(sheet_index) else { - return Err(SpreadsheetArtifactError::Formula { - location: address.to_a1(), - message: "sheet index was not found".to_string(), - }); - }; - let key = (sheet_index, address); - if !stack.insert(key) { - return Ok(EvalValue::Scalar(Some(SpreadsheetCellValue::Error( - "#CYCLE!".to_string(), - )))); - } - - let value = if let Some(cell) = sheet.get_cell(address) { - if let Some(formula) = &cell.formula { - evaluate_formula(artifact, sheet_index, formula, stack)? - } else { - cell.value.clone() - } - } else { - None - }; - stack.remove(&key); - Ok(EvalValue::Scalar(value)) -} - -fn apply_binary_op( - op: BinaryOp, - left: Option, - right: Option, -) -> Result { - if let Some(SpreadsheetCellValue::Error(value)) = &left { - return Ok(SpreadsheetCellValue::Error(value.clone())); - } - if let Some(SpreadsheetCellValue::Error(value)) = &right { - return Ok(SpreadsheetCellValue::Error(value.clone())); - } - - let left = scalar_to_number(left)?; - let right = scalar_to_number(right)?; - let left = left.unwrap_or(0.0); - let right = right.unwrap_or(0.0); - let result = match op { - BinaryOp::Add => left + right, - BinaryOp::Subtract => left - right, - BinaryOp::Multiply => left * right, - BinaryOp::Divide => { - if right == 0.0 { - return Ok(SpreadsheetCellValue::Error("#DIV/0!".to_string())); - } - left / right - } - }; - Ok(number_to_value(result)) -} - -fn scalar_to_number( - value: Option, -) -> Result, SpreadsheetArtifactError> { - match value { - None => Ok(None), - Some(SpreadsheetCellValue::Integer(value)) => Ok(Some(value as f64)), - Some(SpreadsheetCellValue::Float(value)) => Ok(Some(value)), - Some(SpreadsheetCellValue::Bool(value)) => Ok(Some(if value { 1.0 } else { 0.0 })), - Some(SpreadsheetCellValue::Error(value)) => Err(SpreadsheetArtifactError::Formula { - location: value, - message: "encountered error value".to_string(), - }), - Some(other) => Err(SpreadsheetArtifactError::Formula { - location: format!("{other:?}"), - message: "value is not numeric".to_string(), - }), - } -} - -fn number_to_value(number: f64) -> SpreadsheetCellValue { - if number.fract() == 0.0 { - SpreadsheetCellValue::Integer(number as i64) - } else { - SpreadsheetCellValue::Float(number) - } -} - -fn map_error_to_code(error: &SpreadsheetArtifactError) -> String { - match error { - SpreadsheetArtifactError::Formula { message, .. } => { - if message.contains("cycle") { - "#CYCLE!".to_string() - } else if message.contains("not numeric") || message.contains("scalar") { - "#VALUE!".to_string() - } else { - "#ERROR!".to_string() - } - } - SpreadsheetArtifactError::InvalidAddress { .. } => "#REF!".to_string(), - _ => "#ERROR!".to_string(), - } -} - -fn tokenize(source: &str) -> Result, SpreadsheetArtifactError> { - let chars = source.chars().collect::>(); - let mut index = 0usize; - let mut tokens = Vec::new(); - while index < chars.len() { - let ch = chars[index]; - if ch.is_ascii_whitespace() { - index += 1; - continue; - } - match ch { - '+' => { - tokens.push(Token::Plus); - index += 1; - } - '-' => { - tokens.push(Token::Minus); - index += 1; - } - '*' => { - tokens.push(Token::Star); - index += 1; - } - '/' => { - tokens.push(Token::Slash); - index += 1; - } - '(' => { - tokens.push(Token::LParen); - index += 1; - } - ')' => { - tokens.push(Token::RParen); - index += 1; - } - ':' => { - tokens.push(Token::Colon); - index += 1; - } - ',' => { - tokens.push(Token::Comma); - index += 1; - } - '0'..='9' | '.' => { - let start = index; - index += 1; - while index < chars.len() && (chars[index].is_ascii_digit() || chars[index] == '.') - { - index += 1; - } - let number = source[start..index].parse::().map_err(|_| { - SpreadsheetArtifactError::Formula { - location: source.to_string(), - message: "invalid numeric literal".to_string(), - } - })?; - tokens.push(Token::Number(number)); - } - 'A'..='Z' | 'a'..='z' | '_' => { - let start = index; - index += 1; - while index < chars.len() - && (chars[index].is_ascii_alphanumeric() || chars[index] == '_') - { - index += 1; - } - let text = source[start..index].to_string(); - if text.chars().any(|part| part.is_ascii_digit()) - && text.chars().any(|part| part.is_ascii_alphabetic()) - { - tokens.push(Token::Cell(text)); - } else { - tokens.push(Token::Ident(text)); - } - } - other => { - return Err(SpreadsheetArtifactError::Formula { - location: source.to_string(), - message: format!("unsupported token `{other}`"), - }); - } - } - } - Ok(tokens) -} - -struct Parser { - tokens: Vec, - index: usize, -} - -impl Parser { - fn new(tokens: Vec) -> Self { - Self { tokens, index: 0 } - } - - fn has_remaining(&self) -> bool { - self.index < self.tokens.len() - } - - fn parse_expression(&mut self) -> Result { - let mut expr = self.parse_term()?; - while let Some(token) = self.peek() { - let op = match token { - Token::Plus => BinaryOp::Add, - Token::Minus => BinaryOp::Subtract, - _ => break, - }; - self.index += 1; - let right = self.parse_term()?; - expr = Expr::Binary { - op, - left: Box::new(expr), - right: Box::new(right), - }; - } - Ok(expr) - } - - fn parse_term(&mut self) -> Result { - let mut expr = self.parse_factor()?; - while let Some(token) = self.peek() { - let op = match token { - Token::Star => BinaryOp::Multiply, - Token::Slash => BinaryOp::Divide, - _ => break, - }; - self.index += 1; - let right = self.parse_factor()?; - expr = Expr::Binary { - op, - left: Box::new(expr), - right: Box::new(right), - }; - } - Ok(expr) - } - - fn parse_factor(&mut self) -> Result { - match self.peek() { - Some(Token::Minus) => { - self.index += 1; - Ok(Expr::UnaryMinus(Box::new(self.parse_factor()?))) - } - _ => self.parse_primary(), - } - } - - fn parse_primary(&mut self) -> Result { - match self.next().cloned() { - Some(Token::Number(value)) => Ok(Expr::Number(value)), - Some(Token::Cell(address)) => { - let start = CellAddress::parse(&address)?; - if matches!(self.peek(), Some(Token::Colon)) { - self.index += 1; - let Some(Token::Cell(end)) = self.next().cloned() else { - return Err(SpreadsheetArtifactError::Formula { - location: address, - message: "expected cell after `:`".to_string(), - }); - }; - Ok(Expr::Range(CellRange::from_start_end( - start, - CellAddress::parse(&end)?, - ))) - } else { - Ok(Expr::Cell(start)) - } - } - Some(Token::Ident(name)) => { - if !matches!(self.next(), Some(Token::LParen)) { - return Err(SpreadsheetArtifactError::Formula { - location: name, - message: "expected `(` after function name".to_string(), - }); - } - let mut args = Vec::new(); - if !matches!(self.peek(), Some(Token::RParen)) { - loop { - args.push(self.parse_expression()?); - if matches!(self.peek(), Some(Token::Comma)) { - self.index += 1; - continue; - } - break; - } - } - if !matches!(self.next(), Some(Token::RParen)) { - return Err(SpreadsheetArtifactError::Formula { - location: name, - message: "expected `)`".to_string(), - }); - } - Ok(Expr::Function { name, args }) - } - Some(Token::LParen) => { - let expr = self.parse_expression()?; - if !matches!(self.next(), Some(Token::RParen)) { - return Err(SpreadsheetArtifactError::Formula { - location: format!("{expr:?}"), - message: "expected `)`".to_string(), - }); - } - Ok(expr) - } - other => Err(SpreadsheetArtifactError::Formula { - location: format!("{other:?}"), - message: "unexpected token".to_string(), - }), - } - } - - fn peek(&self) -> Option<&Token> { - self.tokens.get(self.index) - } - - fn next(&mut self) -> Option<&Token> { - let token = self.tokens.get(self.index); - self.index += usize::from(token.is_some()); - token - } -} diff --git a/codex-rs/artifact-spreadsheet/src/lib.rs b/codex-rs/artifact-spreadsheet/src/lib.rs deleted file mode 100644 index bd9f6ed8fb..0000000000 --- a/codex-rs/artifact-spreadsheet/src/lib.rs +++ /dev/null @@ -1,26 +0,0 @@ -mod address; -mod chart; -mod conditional; -mod error; -mod formula; -mod manager; -mod model; -mod pivot; -mod render; -mod style; -mod table; -mod xlsx; - -#[cfg(test)] -mod tests; - -pub use address::*; -pub use chart::*; -pub use conditional::*; -pub use error::*; -pub use manager::*; -pub use model::*; -pub use pivot::*; -pub use render::*; -pub use style::*; -pub use table::*; diff --git a/codex-rs/artifact-spreadsheet/src/manager.rs b/codex-rs/artifact-spreadsheet/src/manager.rs deleted file mode 100644 index 392b685c48..0000000000 --- a/codex-rs/artifact-spreadsheet/src/manager.rs +++ /dev/null @@ -1,3346 +0,0 @@ -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::path::Path; -use std::path::PathBuf; - -use base64::Engine; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use serde::Deserialize; -use serde::Serialize; -use serde_json::Value; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifact; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetCellRangeRef; -use crate::SpreadsheetCellRef; -use crate::SpreadsheetCellValue; -use crate::SpreadsheetCitation; -use crate::SpreadsheetRangeView; -use crate::SpreadsheetSheetSummary; -use crate::SpreadsheetSummary; - -#[derive(Debug, Clone, Deserialize)] -pub struct SpreadsheetArtifactRequest { - pub artifact_id: Option, - pub action: String, - #[serde(default)] - pub args: Value, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PathAccessKind { - Read, - Write, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PathAccessRequirement { - pub action: String, - pub kind: PathAccessKind, - pub path: PathBuf, -} - -impl SpreadsheetArtifactRequest { - pub fn required_path_accesses( - &self, - cwd: &Path, - ) -> Result, SpreadsheetArtifactError> { - let access = match self.action.as_str() { - "import_xlsx" | "load" | "read" => { - let args: PathArgs = parse_args(&self.action, &self.args)?; - vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Read, - path: resolve_path(cwd, &args.path), - }] - } - "export_xlsx" => { - let args: PathArgs = parse_args(&self.action, &self.args)?; - vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Write, - path: resolve_path(cwd, &args.path), - }] - } - "save" => { - let args: SaveArgs = parse_args(&self.action, &self.args)?; - vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Write, - path: resolve_path(cwd, &args.path), - }] - } - "render_workbook" | "render_sheet" | "render_range" => { - let args: RenderArgs = parse_args(&self.action, &self.args)?; - args.output_path - .map(|path| { - vec![PathAccessRequirement { - action: self.action.clone(), - kind: PathAccessKind::Write, - path: resolve_path(cwd, &path), - }] - }) - .unwrap_or_default() - } - _ => Vec::new(), - }; - Ok(access) - } -} - -#[derive(Debug, Default)] -pub struct SpreadsheetArtifactManager { - documents: HashMap, -} - -impl SpreadsheetArtifactManager { - pub fn execute( - &mut self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - match request.action.as_str() { - "create" => self.create(request), - "import_xlsx" | "load" | "read" => self.import_xlsx(request, cwd), - "export_xlsx" => self.export_xlsx(request, cwd), - "save" => self.save(request, cwd), - "render_workbook" => self.render_workbook(request, cwd), - "render_sheet" => self.render_sheet(request, cwd), - "render_range" => self.render_range(request, cwd), - "get_summary" => self.get_summary(request), - "list_sheets" => self.list_sheets(request), - "get_sheet" => self.get_sheet(request), - "inspect" => self.inspect(request), - "list_charts" => self.list_charts(request), - "get_chart" => self.get_chart(request), - "create_chart" => self.create_chart(request), - "add_chart_series" => self.add_chart_series(request), - "set_chart_properties" => self.set_chart_properties(request), - "delete_chart" => self.delete_chart(request), - "list_tables" => self.list_tables(request), - "get_table" => self.get_table(request), - "create_table" => self.create_table(request), - "set_table_style" => self.set_table_style(request), - "clear_table_filters" => self.clear_table_filters(request), - "reapply_table_filters" => self.reapply_table_filters(request), - "rename_table_column" => self.rename_table_column(request), - "set_table_column_totals" => self.set_table_column_totals(request), - "delete_table" => self.delete_table(request), - "list_conditional_formats" => self.list_conditional_formats(request), - "add_conditional_format" => self.add_conditional_format(request), - "delete_conditional_format" => self.delete_conditional_format(request), - "list_pivot_tables" => self.list_pivot_tables(request), - "get_pivot_table" => self.get_pivot_table(request), - "create_sheet" => self.create_sheet(request), - "rename_sheet" => self.rename_sheet(request), - "delete_sheet" => self.delete_sheet(request), - "set_sheet_properties" => self.set_sheet_properties(request), - "set_column_widths" => self.set_column_widths(request), - "set_column_widths_bulk" => self.set_column_widths_bulk(request), - "set_row_height" => self.set_row_height(request), - "set_row_heights" => self.set_row_heights(request), - "set_row_heights_bulk" => self.set_row_heights_bulk(request), - "get_row_height" => self.get_row_height(request), - "cleanup_and_validate_sheet" => self.cleanup_and_validate_sheet(request), - "create_text_style" => self.create_text_style(request), - "get_text_style" => self.get_text_style(request), - "create_fill" => self.create_fill(request), - "get_fill" => self.get_fill(request), - "create_border" => self.create_border(request), - "get_border" => self.get_border(request), - "create_number_format" => self.create_number_format(request), - "get_number_format" => self.get_number_format(request), - "create_cell_format" => self.create_cell_format(request), - "get_cell_format" => self.get_cell_format(request), - "create_differential_format" => self.create_differential_format(request), - "get_differential_format" => self.get_differential_format(request), - "get_cell_format_summary" => self.get_cell_format_summary(request), - "get_range_format_summary" => self.get_range_format_summary(request), - "get_reference" => self.get_reference(request), - "get_cell" => self.get_cell(request), - "get_cell_by_indices" => self.get_cell_by_indices(request), - "get_cell_field" => self.get_cell_field(request), - "get_cell_field_by_indices" => self.get_cell_field_by_indices(request), - "get_range" => self.get_range(request), - "set_cell_value" => self.set_cell_value(request), - "set_range_value" => self.set_range_value(request), - "set_range_values" => self.set_range_values(request), - "set_cell_formula" => self.set_cell_formula(request), - "set_range_formula" => self.set_range_formula(request), - "set_range_formulas" => self.set_range_formulas(request), - "set_cell_style" => self.set_cell_style(request), - "set_range_style" => self.set_range_style(request), - "clear_range" => self.clear_range(request), - "merge_range" => self.merge_range(request), - "unmerge_range" => self.unmerge_range(request), - "cite_cell" => self.cite_cell(request), - "cite_range" => self.cite_range(request), - "calculate" | "recalculate" => self.calculate(request), - "serialize_dict" => self.serialize_dict(request), - "serialize_json" => self.serialize_json(request), - "serialize_bytes" => self.serialize_bytes(request), - "deserialize_dict" => self.deserialize_dict(request), - "deserialize_json" => self.deserialize_json(request), - "deserialize_bytes" => self.deserialize_bytes(request), - "delete_artifact" => self.delete_artifact(request), - other => Err(SpreadsheetArtifactError::UnknownAction(other.to_string())), - } - } - - fn create( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateArgs = parse_args(&request.action, &request.args)?; - let mut artifact = SpreadsheetArtifact::new(args.name); - if let Some(auto_recalculate) = args.auto_recalculate { - artifact.auto_recalculate = auto_recalculate; - } - let artifact_id = artifact.artifact_id.clone(); - let summary = format!("Created spreadsheet artifact `{artifact_id}`"); - let snapshot = snapshot_for_artifact(&artifact); - self.documents.insert(artifact_id.clone(), artifact); - Ok(SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - summary, - snapshot, - )) - } - - fn import_xlsx( - &mut self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - let args: PathArgs = parse_args(&request.action, &request.args)?; - let path = resolve_path(cwd, &args.path); - let artifact = SpreadsheetArtifact::from_source_file(&path, None)?; - let artifact_id = artifact.artifact_id.clone(); - let snapshot = snapshot_for_artifact(&artifact); - let summary = format!( - "Imported `{}` as spreadsheet artifact `{artifact_id}` with {} sheets", - path.display(), - artifact.sheets.len() - ); - self.documents.insert(artifact_id.clone(), artifact); - Ok(SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - summary, - snapshot, - )) - } - - fn export_xlsx( - &mut self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - let args: PathArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let path = resolve_path(cwd, &args.path); - let exported = artifact.export(&path)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Exported spreadsheet to `{}`", exported.display()), - snapshot_for_artifact(artifact), - ); - response.exported_paths.push(exported); - response.workbook_summary = Some(artifact.summary()); - response.sheet_list = Some( - artifact - .sheets - .iter() - .map(super::model::SpreadsheetSheet::summary) - .collect(), - ); - Ok(response) - } - - fn save( - &mut self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - let args: SaveArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let path = resolve_path(cwd, &args.path); - let exported = artifact.save(&path, args.file_type.as_deref())?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Saved spreadsheet to `{}`", exported.display()), - snapshot_for_artifact(artifact), - ); - response.exported_paths.push(exported); - response.workbook_summary = Some(artifact.summary()); - Ok(response) - } - - fn get_summary( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Spreadsheet has {} sheets and {} bytes of serialized state", - artifact.sheets.len(), - artifact.summary().size_bytes - ), - snapshot_for_artifact(artifact), - ); - response.workbook_summary = Some(artifact.summary()); - response.sheet_list = Some( - artifact - .sheets - .iter() - .map(super::model::SpreadsheetSheet::summary) - .collect(), - ); - Ok(response) - } - - fn render_workbook( - &mut self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - let args: RenderArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let rendered = artifact.render_workbook_previews(cwd, &render_options_from_args(args)?)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Rendered workbook to {} preview files", rendered.len()), - snapshot_for_artifact(artifact), - ); - response.exported_paths = rendered.into_iter().map(|output| output.path).collect(); - Ok(response) - } - - fn render_sheet( - &mut self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - let args: RenderArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let rendered = - artifact.render_sheet_preview(cwd, sheet, &render_options_from_args(args)?)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Rendered sheet `{}`", sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.exported_paths.push(rendered.path); - response.rendered_html = Some(rendered.html); - response.rendered_text = Some(sheet.to_rendered_text(None)); - Ok(response) - } - - fn render_range( - &mut self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - let args: RenderArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range_text = - args.range - .clone() - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: request.action.clone(), - message: "range is required".to_string(), - })?; - let range = CellRange::parse(&range_text)?; - let rendered = - artifact.render_range_preview(cwd, sheet, &range, &render_options_from_args(args)?)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Rendered range `{range_text}` from `{}`", sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - response.exported_paths.push(rendered.path); - response.rendered_html = Some(rendered.html); - response.rendered_text = Some(sheet.to_rendered_text(Some(&range))); - Ok(response) - } - - fn list_sheets( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Listed {} sheets", artifact.sheets.len()), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some( - artifact - .sheets - .iter() - .map(super::model::SpreadsheetSheet::summary) - .collect(), - ); - Ok(response) - } - - fn get_sheet( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range = if let Some(range) = args.range.as_deref() { - Some(CellRange::parse(range)?) - } else { - sheet.minimum_range() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved sheet `{}`", sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet.summary()]); - response.sheet_ref = Some(sheet_reference(sheet)); - response.range_ref = range - .as_ref() - .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); - response.rendered_text = Some(sheet.to_rendered_text(range.as_ref())); - response.range = range.as_ref().map(|entry| sheet.get_range_view(entry)); - response.top_left_style_index = range - .as_ref() - .map(|entry| sheet.top_left_style_index(entry)); - response.range_format = range.as_ref().map(|entry| sheet.range_format(entry)); - response.cell_format_summary = response - .top_left_style_index - .and_then(|style_index| artifact.cell_format_summary(style_index)); - response.serialized_dict = Some(sheet.to_dict()?); - Ok(response) - } - - fn inspect( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let inspected = if args.sheet_name.is_none() && args.sheet_index.is_none() { - artifact.to_dict()? - } else { - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - serde_json::to_value(sheet).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })? - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Generated inspection snapshot".to_string(), - snapshot_for_artifact(artifact), - ); - response.serialized_dict = Some(inspected); - Ok(response) - } - - fn create_sheet( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateSheetArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let name = args.name.clone(); - artifact.create_sheet(args.name)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created sheet `{name}`"), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some( - artifact - .sheets - .iter() - .map(super::model::SpreadsheetSheet::summary) - .collect(), - ); - Ok(response) - } - - fn list_charts( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range = args.range.as_deref().map(CellRange::parse).transpose()?; - let charts = sheet.list_charts(range.as_ref())?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Listed {} charts on `{}`", charts.len(), sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.range_ref = range - .as_ref() - .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); - response.chart_list = Some(charts); - Ok(response) - } - - fn get_chart( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: ChartLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let chart = sheet - .get_chart(&request.action, chart_lookup_from_args(&args))? - .clone(); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved chart `{}` from `{}`", chart.id, sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.chart_list = Some(vec![chart]); - Ok(response) - } - - fn create_chart( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateChartArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - if let Some(source_sheet_name) = args.source_sheet_name.as_deref() { - artifact.sheet_lookup(&request.action, Some(source_sheet_name), None)?; - } - let source_range = CellRange::parse(&args.source_range)?; - let chart = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let chart_id = sheet.create_chart( - &request.action, - args.chart_type, - args.source_sheet_name.or_else(|| Some(sheet.name.clone())), - &source_range, - args.options.unwrap_or_default(), - )?; - sheet - .get_chart( - &request.action, - crate::SpreadsheetChartLookup { - id: Some(chart_id), - index: None, - }, - )? - .clone() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created chart `{}`", chart.id), - snapshot_for_artifact(artifact), - ); - response.chart_list = Some(vec![chart]); - Ok(response) - } - - fn add_chart_series( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: AddChartSeriesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let chart = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let series_id = sheet.add_chart_series( - &request.action, - crate::SpreadsheetChartLookup { - id: args.chart_id, - index: args.chart_index.map(|value| value as usize), - }, - args.series, - )?; - let chart = sheet.get_chart( - &request.action, - crate::SpreadsheetChartLookup { - id: args.chart_id.or(Some(series_id).and(None)), - index: args.chart_index.map(|value| value as usize), - }, - ); - match chart { - Ok(chart) => chart.clone(), - Err(_) => sheet - .get_chart( - &request.action, - crate::SpreadsheetChartLookup { - id: None, - index: args.chart_index.map(|value| value as usize), - }, - )? - .clone(), - } - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Added chart series to chart `{}`", chart.id), - snapshot_for_artifact(artifact), - ); - response.chart_list = Some(vec![chart]); - Ok(response) - } - - fn set_chart_properties( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetChartPropertiesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let chart = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.lookup.sheet_name.as_deref(), - args.lookup.sheet_index.map(|value| value as usize), - )?; - let lookup = chart_lookup_from_args(&args.lookup); - sheet.set_chart_properties(&request.action, lookup.clone(), args.properties)?; - sheet.get_chart(&request.action, lookup)?.clone() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Updated chart `{}`", chart.id), - snapshot_for_artifact(artifact), - ); - response.chart_list = Some(vec![chart]); - Ok(response) - } - - fn delete_chart( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: ChartLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_name = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let name = sheet.name.clone(); - sheet.delete_chart(&request.action, chart_lookup_from_args(&args))?; - name - }; - let action = request.action.clone(); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Deleted chart from `{sheet_name}`"), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![ - artifact - .sheet_lookup(&action, Some(&sheet_name), None)? - .summary(), - ]); - Ok(response) - } - - fn list_tables( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range = args.range.as_deref().map(CellRange::parse).transpose()?; - let tables = sheet.list_tables(range.as_ref())?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Listed {} tables on `{}`", tables.len(), sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.range_ref = range - .as_ref() - .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); - response.table_list = Some(tables); - Ok(response) - } - - fn get_table( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: TableLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let table = sheet.get_table_view(&request.action, table_lookup_from_args(&args))?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved table `{}` from `{}`", table.name, sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.table_list = Some(vec![table]); - Ok(response) - } - - fn create_table( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateTableArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - let table = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let table_id = sheet.create_table(&request.action, &range, args.options)?; - sheet.get_table_view( - &request.action, - crate::SpreadsheetTableLookup { - name: None, - display_name: None, - id: Some(table_id), - }, - )? - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created table `{}`", table.name), - snapshot_for_artifact(artifact), - ); - response.table_list = Some(vec![table]); - Ok(response) - } - - fn set_table_style( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetTableStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let table = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.lookup.sheet_name.as_deref(), - args.lookup.sheet_index.map(|value| value as usize), - )?; - let lookup = table_lookup_from_args(&args.lookup); - sheet.set_table_style(&request.action, lookup.clone(), args.options)?; - sheet.get_table_view(&request.action, lookup)? - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Updated table style for `{}`", table.name), - snapshot_for_artifact(artifact), - ); - response.table_list = Some(vec![table]); - Ok(response) - } - - fn clear_table_filters( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: TableLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let table = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let lookup = table_lookup_from_args(&args); - sheet.clear_table_filters(&request.action, lookup.clone())?; - sheet.get_table_view(&request.action, lookup)? - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Cleared table filters for `{}`", table.name), - snapshot_for_artifact(artifact), - ); - response.table_list = Some(vec![table]); - Ok(response) - } - - fn reapply_table_filters( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: TableLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let table = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let lookup = table_lookup_from_args(&args); - sheet.reapply_table_filters(&request.action, lookup.clone())?; - sheet.get_table_view(&request.action, lookup)? - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Reapplied table filters for `{}`", table.name), - snapshot_for_artifact(artifact), - ); - response.table_list = Some(vec![table]); - Ok(response) - } - - fn rename_table_column( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: RenameTableColumnArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let column = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.lookup.sheet_name.as_deref(), - args.lookup.sheet_index.map(|value| value as usize), - )?; - sheet.rename_table_column( - &request.action, - table_lookup_from_args(&args.lookup), - args.column_id, - args.column_name.as_deref(), - args.new_name, - )? - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Renamed table column to `{}`", column.name), - snapshot_for_artifact(artifact), - ); - response.serialized_dict = Some(to_serialized_value(column)?); - Ok(response) - } - - fn set_table_column_totals( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetTableColumnTotalsArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let column = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.lookup.sheet_name.as_deref(), - args.lookup.sheet_index.map(|value| value as usize), - )?; - sheet.set_table_column_totals( - &request.action, - table_lookup_from_args(&args.lookup), - args.column_id, - args.column_name.as_deref(), - args.totals_row_label, - args.totals_row_function, - )? - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Updated totals metadata for column `{}`", column.name), - snapshot_for_artifact(artifact), - ); - response.serialized_dict = Some(to_serialized_value(column)?); - Ok(response) - } - - fn delete_table( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: TableLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_name = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let name = sheet.name.clone(); - sheet.delete_table(&request.action, table_lookup_from_args(&args))?; - name - }; - let action = request.action.clone(); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Deleted table from `{sheet_name}`"), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![ - artifact - .sheet_lookup(&action, Some(&sheet_name), None)? - .summary(), - ]); - Ok(response) - } - - fn list_conditional_formats( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range = args.range.as_deref().map(CellRange::parse).transpose()?; - let formats = sheet.list_conditional_formats(range.as_ref()); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Listed {} conditional formats on `{}`", - formats.len(), - sheet.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.range_ref = range - .as_ref() - .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); - response.conditional_format_list = Some(formats); - Ok(response) - } - - fn add_conditional_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: AddConditionalFormatArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_name = artifact - .sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )? - .name - .clone(); - let format_id = - artifact.add_conditional_format(&request.action, &sheet_name, args.format)?; - let format = artifact - .sheet_lookup(&request.action, Some(&sheet_name), None)? - .conditional_formats - .iter() - .find(|entry| entry.id == format_id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::Serialization { - message: format!("created conditional format `{format_id}` was not available"), - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created conditional format `{format_id}`"), - snapshot_for_artifact(artifact), - ); - response.conditional_format_list = Some(vec![format]); - Ok(response) - } - - fn delete_conditional_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: DeleteConditionalFormatArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_name = artifact - .sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )? - .name - .clone(); - artifact.delete_conditional_format(&request.action, &sheet_name, args.id)?; - let action = request.action.clone(); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Deleted conditional format `{}`", args.id), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![ - artifact - .sheet_lookup(&action, Some(&sheet_name), None)? - .summary(), - ]); - Ok(response) - } - - fn list_pivot_tables( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range = args.range.as_deref().map(CellRange::parse).transpose()?; - let pivots = sheet.list_pivot_tables(range.as_ref())?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Listed {} pivot tables on `{}`", pivots.len(), sheet.name), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.range_ref = range - .as_ref() - .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); - response.pivot_table_list = Some(pivots); - Ok(response) - } - - fn get_pivot_table( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: PivotTableLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let pivot = sheet - .get_pivot_table(&request.action, pivot_lookup_from_args(&args))? - .clone(); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Retrieved pivot table `{}` from `{}`", - pivot.name, sheet.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.pivot_table_list = Some(vec![pivot]); - Ok(response) - } - - fn rename_sheet( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: RenameSheetArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let new_name = args.new_name.clone(); - artifact.rename_sheet( - args.new_name, - args.old_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Renamed sheet to `{new_name}`"), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some( - artifact - .sheets - .iter() - .map(super::model::SpreadsheetSheet::summary) - .collect(), - ); - Ok(response) - } - - fn delete_sheet( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: DeleteSheetArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - artifact.delete_sheet( - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Deleted sheet".to_string(), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some( - artifact - .sheets - .iter() - .map(super::model::SpreadsheetSheet::summary) - .collect(), - ); - Ok(response) - } - - fn set_sheet_properties( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetSheetPropertiesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_summary = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - if let Some(default_row_height) = args.default_row_height { - sheet.default_row_height = Some(default_row_height); - } - if let Some(default_column_width) = args.default_column_width { - sheet.default_column_width = Some(default_column_width); - } - if let Some(show_grid_lines) = args.show_grid_lines { - sheet.show_grid_lines = show_grid_lines; - } - sheet.summary() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Updated sheet `{}` properties", sheet_summary.name), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet_summary]); - Ok(response) - } - - fn set_column_widths( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetColumnWidthsArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_summary = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_column_widths(&args.reference, args.width)?; - sheet.summary() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Updated column widths `{}` on `{}`", - args.reference, sheet_summary.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet_summary]); - Ok(response) - } - - fn set_column_widths_bulk( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetColumnWidthsBulkArgs = parse_args(&request.action, &request.args)?; - let width_count = args.widths.len(); - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_summary = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_column_widths_bulk(&args.widths)?; - sheet.summary() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Updated {width_count} column width references on `{}`", - sheet_summary.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet_summary]); - Ok(response) - } - - fn set_row_height( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetRowHeightArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let (sheet_summary, row_height) = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_row_height(args.row_index, args.height)?; - (sheet.summary(), sheet.get_row_height(args.row_index)) - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Updated row height for row {} on `{}`", - args.row_index, sheet_summary.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet_summary]); - response.row_height = row_height; - Ok(response) - } - - fn set_row_heights( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetRowHeightsArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let start = args.start_row_index.min(args.end_row_index); - let end = args.start_row_index.max(args.end_row_index); - let sheet_summary = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_row_heights(args.start_row_index, args.end_row_index, args.height)?; - sheet.summary() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Updated row heights {start}:{end} on `{}`", - sheet_summary.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet_summary]); - Ok(response) - } - - fn set_row_heights_bulk( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetRowHeightsBulkArgs = parse_args(&request.action, &request.args)?; - let height_count = args.heights.len(); - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_summary = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_row_heights_bulk(&args.heights)?; - sheet.summary() - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Updated {height_count} row height entries on `{}`", - sheet_summary.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet_summary]); - Ok(response) - } - - fn get_row_height( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: GetRowHeightArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Retrieved row height for row {} from `{}`", - args.row_index, sheet.name - ), - snapshot_for_artifact(artifact), - ); - response.sheet_ref = Some(sheet_reference(sheet)); - response.sheet_list = Some(vec![sheet.summary()]); - response.row_height = sheet.get_row_height(args.row_index); - Ok(response) - } - - fn cleanup_and_validate_sheet( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let sheet_summary = { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.cleanup_and_validate_sheet()?; - sheet.summary() - }; - artifact.validate_conditional_formats(&request.action, &sheet_summary.name)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Cleaned and validated `{}`", sheet_summary.name), - snapshot_for_artifact(artifact), - ); - response.sheet_list = Some(vec![sheet_summary]); - Ok(response) - } - - fn create_text_style( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateTextStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let style_id = artifact.create_text_style( - args.style, - args.source_style_id, - args.merge_with_existing_components.unwrap_or(false), - )?; - let style = artifact.get_text_style(style_id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::Serialization { - message: format!("created text style `{style_id}` was not available"), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created text style `{style_id}`"), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(style_id); - response.serialized_dict = Some(to_serialized_value(style)?); - Ok(response) - } - - fn get_text_style( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: GetStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let style = artifact.get_text_style(args.id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("text style `{}` was not found", args.id), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved text style `{}`", args.id), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(args.id); - response.serialized_dict = Some(to_serialized_value(style)?); - Ok(response) - } - - fn create_fill( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateFillArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let style_id = artifact.create_fill( - args.fill, - args.source_fill_id, - args.merge_with_existing_components.unwrap_or(false), - )?; - let fill = artifact.get_fill(style_id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::Serialization { - message: format!("created fill `{style_id}` was not available"), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created fill `{style_id}`"), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(style_id); - response.serialized_dict = Some(to_serialized_value(fill)?); - Ok(response) - } - - fn get_fill( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: GetStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let fill = artifact.get_fill(args.id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("fill `{}` was not found", args.id), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved fill `{}`", args.id), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(args.id); - response.serialized_dict = Some(to_serialized_value(fill)?); - Ok(response) - } - - fn create_border( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateBorderArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let style_id = artifact.create_border( - args.border, - args.source_border_id, - args.merge_with_existing_components.unwrap_or(false), - )?; - let border = artifact.get_border(style_id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::Serialization { - message: format!("created border `{style_id}` was not available"), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created border `{style_id}`"), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(style_id); - response.serialized_dict = Some(to_serialized_value(border)?); - Ok(response) - } - - fn get_border( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: GetStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let border = artifact.get_border(args.id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("border `{}` was not found", args.id), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved border `{}`", args.id), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(args.id); - response.serialized_dict = Some(to_serialized_value(border)?); - Ok(response) - } - - fn create_number_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateNumberFormatArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let style_id = artifact.create_number_format( - args.number_format, - args.source_number_format_id, - args.merge_with_existing_components.unwrap_or(false), - )?; - let number_format = artifact - .get_number_format(style_id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::Serialization { - message: format!("created number format `{style_id}` was not available"), - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created number format `{style_id}`"), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(style_id); - response.serialized_dict = Some(to_serialized_value(number_format)?); - Ok(response) - } - - fn get_number_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: GetStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let number_format = artifact - .get_number_format(args.id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("number format `{}` was not found", args.id), - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved number format `{}`", args.id), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(args.id); - response.serialized_dict = Some(to_serialized_value(number_format)?); - Ok(response) - } - - fn create_cell_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateCellFormatArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let style_id = artifact.create_cell_format( - args.format, - args.source_format_id, - args.merge_with_existing_components.unwrap_or(false), - )?; - let format = artifact.get_cell_format(style_id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::Serialization { - message: format!("created cell format `{style_id}` was not available"), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created cell format `{style_id}`"), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(style_id); - response.serialized_dict = Some(to_serialized_value(format)?); - response.cell_format_summary = artifact.cell_format_summary(style_id); - Ok(response) - } - - fn get_cell_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: GetStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let format = artifact.get_cell_format(args.id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("cell format `{}` was not found", args.id), - } - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved cell format `{}`", args.id), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(args.id); - response.serialized_dict = Some(to_serialized_value(format)?); - response.cell_format_summary = artifact.cell_format_summary(args.id); - Ok(response) - } - - fn create_differential_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CreateDifferentialFormatArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let style_id = artifact.create_differential_format(args.format); - let format = artifact - .get_differential_format(style_id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::Serialization { - message: format!("created differential format `{style_id}` was not available"), - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Created differential format `{style_id}`"), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(style_id); - response.serialized_dict = Some(to_serialized_value(format)?); - Ok(response) - } - - fn get_differential_format( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: GetStyleArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let format = artifact - .get_differential_format(args.id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: request.action.clone(), - message: format!("differential format `{}` was not found", args.id), - })?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved differential format `{}`", args.id), - snapshot_for_artifact(artifact), - ); - response.style_id = Some(args.id); - response.serialized_dict = Some(to_serialized_value(format)?); - Ok(response) - } - - fn get_cell_format_summary( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CellAddressArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let cell = sheet.get_cell_view(CellAddress::parse(&args.address)?); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved cell format summary for `{}`", args.address), - snapshot_for_artifact(artifact), - ); - response.cell_ref = Some(sheet.cell_ref(&args.address)?); - response.cell = Some(cell.clone()); - response.cell_format_summary = artifact.cell_format_summary(cell.style_index); - Ok(response) - } - - fn get_range_format_summary( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: RangeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range = CellRange::parse(&args.range)?; - let top_left_style_index = sheet.top_left_style_index(&range); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved range format summary for `{}`", args.range), - snapshot_for_artifact(artifact), - ); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - response.range_format = Some(sheet.range_format(&range)); - response.range = Some(sheet.get_range_view(&range)); - response.top_left_style_index = Some(top_left_style_index); - response.cell_format_summary = artifact.cell_format_summary(top_left_style_index); - Ok(response) - } - - fn get_reference( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: ReferenceArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Resolved reference `{}` on `{}`", - args.reference, sheet.name - ), - snapshot_for_artifact(artifact), - ); - match sheet.reference(&args.reference)? { - crate::SpreadsheetSheetReference::Cell { cell_ref } => { - let address = cell_ref.cell_address()?; - let cell = sheet.get_cell_view(address); - response.cell_format_summary = artifact.cell_format_summary(cell.style_index); - response.cell = Some(cell); - response.raw_cell = sheet.get_raw_cell(address); - response.cell_ref = Some(cell_ref); - } - crate::SpreadsheetSheetReference::Range { range_ref } => { - let range = range_ref.range()?; - let top_left_style_index = sheet.top_left_style_index(&range); - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(range_ref); - response.range_format = Some(sheet.range_format(&range)); - response.top_left_style_index = Some(top_left_style_index); - response.cell_format_summary = artifact.cell_format_summary(top_left_style_index); - response.rendered_text = Some(sheet.to_rendered_text(Some(&range))); - } - } - Ok(response) - } - - fn get_cell( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CellAddressArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let cell = sheet.get_cell_view(CellAddress::parse(&args.address)?); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved cell `{}` from `{}`", args.address, sheet.name), - snapshot_for_artifact(artifact), - ); - response.cell_format_summary = artifact.cell_format_summary(cell.style_index); - response.cell = Some(cell); - response.raw_cell = sheet.get_raw_cell(CellAddress::parse(&args.address)?); - response.cell_ref = Some(sheet.cell_ref(&args.address)?); - Ok(response) - } - - fn get_cell_by_indices( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CellIndicesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let address = CellAddress { - column: args.column_index, - row: args.row_index, - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Retrieved cell by indices ({}, {}) from `{}`", - args.column_index, args.row_index, sheet.name - ), - snapshot_for_artifact(artifact), - ); - let cell = sheet.get_cell_view_by_indices(args.column_index, args.row_index); - response.cell_format_summary = artifact.cell_format_summary(cell.style_index); - response.cell = Some(cell); - response.raw_cell = sheet.get_raw_cell(address); - response.cell_ref = Some(sheet.cell_ref(address.to_a1())?); - Ok(response) - } - - fn get_cell_field( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CellFieldArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let value = sheet.get_cell_field(CellAddress::parse(&args.address)?, &args.field)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Retrieved field `{}` from `{}` on `{}`", - args.field, args.address, sheet.name - ), - snapshot_for_artifact(artifact), - ); - response.cell_field = value; - response.cell_ref = Some(sheet.cell_ref(&args.address)?); - Ok(response) - } - - fn get_cell_field_by_indices( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: CellFieldByIndicesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let value = - sheet.get_cell_field_by_indices(args.column_index, args.row_index, &args.field)?; - let address = CellAddress { - column: args.column_index, - row: args.row_index, - }; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!( - "Retrieved field `{}` from indices ({}, {}) on `{}`", - args.field, args.column_index, args.row_index, sheet.name - ), - snapshot_for_artifact(artifact), - ); - response.cell_field = value; - response.cell_ref = Some(sheet.cell_ref(address.to_a1())?); - Ok(response) - } - - fn get_range( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: RangeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let sheet = artifact.sheet_lookup( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let range = CellRange::parse(&args.range)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - format!("Retrieved range `{}` from `{}`", args.range, sheet.name), - snapshot_for_artifact(artifact), - ); - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - response.range_format = Some(sheet.range_format(&range)); - response.top_left_style_index = Some(sheet.top_left_style_index(&range)); - response.cell_format_summary = - artifact.cell_format_summary(sheet.top_left_style_index(&range)); - response.rendered_text = Some(sheet.to_rendered_text(Some(&range))); - Ok(response) - } - - fn set_cell_value( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: SetCellValueArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let address = CellAddress::parse(&args.address)?; - let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let value = normalize_optional_cell_value(args.value)?; - sheet.set_value(address, value)?; - } - if recalculate { - artifact.recalculate(); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Updated cell `{}`", args.address), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.cell = Some(sheet.get_cell_view(address)); - response.cell_ref = Some(sheet.cell_ref(&args.address)?); - Ok(response) - } - - fn set_range_value( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: SetRangeValueArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_range_to_value(&range, normalize_optional_cell_value(args.value)?)?; - } - if recalculate { - artifact.recalculate(); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Updated range `{}` to a single value", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - Ok(response) - } - - fn set_range_values( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: SetRangeValuesArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); - let values = normalize_value_matrix(args.values, &request.action)?; - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_values_matrix(&range, &values)?; - } - if recalculate { - artifact.recalculate(); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Updated range `{}`", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - Ok(response) - } - - fn set_cell_formula( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: SetCellFormulaArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let address = CellAddress::parse(&args.address)?; - let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_formula(address, Some(normalize_formula(args.formula)))?; - } - if recalculate { - artifact.recalculate(); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Updated formula in `{}`", args.address), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.cell = Some(sheet.get_cell_view(address)); - response.cell_ref = Some(sheet.cell_ref(&args.address)?); - Ok(response) - } - - fn set_range_formula( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: SetRangeFormulaArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_range_to_formula(&range, Some(normalize_formula(args.formula)))?; - } - if recalculate { - artifact.recalculate(); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Updated range `{}` to a single formula", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - Ok(response) - } - - fn set_range_formulas( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: SetRangeFormulasArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); - let formulas = args - .formulas - .into_iter() - .map(|row| { - row.into_iter() - .map(|value| value.map(normalize_formula)) - .collect() - }) - .collect::>>>(); - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.set_formulas_matrix(&range, &formulas)?; - } - if recalculate { - artifact.recalculate(); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Updated formulas in `{}`", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - Ok(response) - } - - fn set_cell_style( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetCellStyleArgs = parse_args(&request.action, &request.args)?; - let range = CellRange::parse(&args.address)?; - self.set_style_impl( - request, - args.sheet_name, - args.sheet_index, - range, - args.style_index, - ) - } - - fn set_range_style( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: SetRangeStyleArgs = parse_args(&request.action, &request.args)?; - let range = CellRange::parse(&args.range)?; - self.set_style_impl( - request, - args.sheet_name, - args.sheet_index, - range, - args.style_index, - ) - } - - fn set_style_impl( - &mut self, - request: SpreadsheetArtifactRequest, - sheet_name: Option, - sheet_index: Option, - range: CellRange, - style_index: u32, - ) -> Result { - let action = request.action.clone(); - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - sheet_name.as_deref(), - sheet_index.map(|value| value as usize), - )?; - sheet.set_style_index(&range, style_index)?; - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Updated style index {} on `{}`", style_index, range.to_a1()), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - sheet_name.as_deref(), - sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - Ok(response) - } - - fn clear_range( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: ClearRangeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.clear_range(&range, args.fields.as_deref())?; - } - if recalculate { - artifact.recalculate(); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Cleared range `{}`", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - Ok(response) - } - - fn merge_range( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: MergeRangeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.merge_cells(&range, args.raise_on_conflict.unwrap_or(false))?; - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Merged `{}`", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); - Ok(response) - } - - fn cite_cell( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: CiteCellArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let address = CellAddress::parse(&args.address)?; - let citation = SpreadsheetCitation { - tether_id: args.tether_id, - start_line: args.start_line, - end_line: args.end_line, - content_reference_type: args.content_reference_type, - source_type: args.source_type, - }; - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - let cell_ref = sheet.cell_ref(&args.address)?; - cell_ref.cite(sheet, citation)?; - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Attached citation to cell `{}`", args.address), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.cell = Some(sheet.get_cell_view(address)); - response.cell_ref = Some(sheet.cell_ref(&args.address)?); - Ok(response) - } - - fn unmerge_range( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: RangeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.unmerge_cells(&range); - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Unmerged `{}`", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - Ok(response) - } - - fn cite_range( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let action = request.action.clone(); - let args: CiteRangeArgs = parse_args(&request.action, &request.args)?; - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - let range = CellRange::parse(&args.range)?; - let citation = SpreadsheetCitation { - tether_id: args.tether_id, - start_line: args.start_line, - end_line: args.end_line, - content_reference_type: args.content_reference_type, - source_type: args.source_type, - }; - { - let sheet = artifact.sheet_lookup_mut( - &request.action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - sheet.cite_range(&range, citation)?; - } - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - action.clone(), - format!("Attached citation to `{}`", args.range), - snapshot_for_artifact(artifact), - ); - let sheet = artifact.sheet_lookup( - &action, - args.sheet_name.as_deref(), - args.sheet_index.map(|value| value as usize), - )?; - response.range = Some(sheet.get_range_view(&range)); - Ok(response) - } - - fn calculate( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; - artifact.recalculate(); - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Recalculated workbook".to_string(), - snapshot_for_artifact(artifact), - ); - response.workbook_summary = Some(artifact.summary()); - Ok(response) - } - - fn serialize_dict( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Serialized workbook to dict".to_string(), - snapshot_for_artifact(artifact), - ); - response.serialized_dict = Some(artifact.to_dict()?); - Ok(response) - } - - fn serialize_json( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Serialized workbook to JSON".to_string(), - snapshot_for_artifact(artifact), - ); - response.serialized_json = Some(artifact.to_json()?); - Ok(response) - } - - fn serialize_bytes( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let artifact = self.get_artifact(&artifact_id, &request.action)?; - let mut response = SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Serialized workbook to bytes".to_string(), - snapshot_for_artifact(artifact), - ); - response.serialized_bytes_base64 = Some(artifact.to_bytes_base64()); - Ok(response) - } - - fn deserialize_dict( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: DeserializeDictArgs = parse_args(&request.action, &request.args)?; - let artifact = SpreadsheetArtifact::from_dict(args.data, args.artifact_id)?; - let artifact_id = artifact.artifact_id.clone(); - let snapshot = snapshot_for_artifact(&artifact); - self.documents.insert(artifact_id.clone(), artifact); - Ok(SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Deserialized workbook from dict".to_string(), - snapshot, - )) - } - - fn deserialize_json( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: DeserializeJsonArgs = parse_args(&request.action, &request.args)?; - let artifact = SpreadsheetArtifact::from_json(args.json, args.artifact_id)?; - let artifact_id = artifact.artifact_id.clone(); - let snapshot = snapshot_for_artifact(&artifact); - self.documents.insert(artifact_id.clone(), artifact); - Ok(SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Deserialized workbook from JSON".to_string(), - snapshot, - )) - } - - fn deserialize_bytes( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let args: DeserializeBytesArgs = parse_args(&request.action, &request.args)?; - let bytes = BASE64_STANDARD.decode(args.bytes_base64).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - let artifact = SpreadsheetArtifact::from_bytes(&bytes, args.artifact_id)?; - let artifact_id = artifact.artifact_id.clone(); - let snapshot = snapshot_for_artifact(&artifact); - self.documents.insert(artifact_id.clone(), artifact); - Ok(SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Deserialized workbook from bytes".to_string(), - snapshot, - )) - } - - fn delete_artifact( - &mut self, - request: SpreadsheetArtifactRequest, - ) -> Result { - let artifact_id = required_artifact_id(&request)?; - let artifact = self.documents.remove(&artifact_id).ok_or_else(|| { - SpreadsheetArtifactError::UnknownArtifactId { - action: request.action.clone(), - artifact_id: artifact_id.clone(), - } - })?; - let snapshot = snapshot_for_artifact(&artifact); - Ok(SpreadsheetArtifactResponse::new( - artifact_id, - request.action, - "Deleted spreadsheet artifact".to_string(), - snapshot, - )) - } - - fn get_artifact( - &self, - artifact_id: &str, - action: &str, - ) -> Result<&SpreadsheetArtifact, SpreadsheetArtifactError> { - self.documents - .get(artifact_id) - .ok_or_else(|| SpreadsheetArtifactError::UnknownArtifactId { - action: action.to_string(), - artifact_id: artifact_id.to_string(), - }) - } - - fn get_artifact_mut( - &mut self, - artifact_id: &str, - action: &str, - ) -> Result<&mut SpreadsheetArtifact, SpreadsheetArtifactError> { - self.documents.get_mut(artifact_id).ok_or_else(|| { - SpreadsheetArtifactError::UnknownArtifactId { - action: action.to_string(), - artifact_id: artifact_id.to_string(), - } - }) - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct SpreadsheetArtifactResponse { - pub artifact_id: String, - pub action: String, - pub summary: String, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub exported_paths: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub artifact_snapshot: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub workbook_summary: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub sheet_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub chart_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub table_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub conditional_format_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub pivot_table_list: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub sheet_ref: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cell_ref: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub range_ref: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub range_format: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cell: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub raw_cell: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub style_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cell_field: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub range: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub top_left_style_index: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cell_format_summary: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub rendered_text: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub rendered_html: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub row_height: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub serialized_dict: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub serialized_json: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub serialized_bytes_base64: Option, -} - -impl SpreadsheetArtifactResponse { - fn new( - artifact_id: String, - action: String, - summary: String, - artifact_snapshot: SpreadsheetArtifactSnapshot, - ) -> Self { - Self { - artifact_id, - action, - summary, - exported_paths: Vec::new(), - artifact_snapshot: Some(artifact_snapshot), - workbook_summary: None, - sheet_list: None, - chart_list: None, - table_list: None, - conditional_format_list: None, - pivot_table_list: None, - sheet_ref: None, - cell_ref: None, - range_ref: None, - range_format: None, - cell: None, - raw_cell: None, - style_id: None, - cell_field: None, - range: None, - top_left_style_index: None, - cell_format_summary: None, - rendered_text: None, - rendered_html: None, - row_height: None, - serialized_dict: None, - serialized_json: None, - serialized_bytes_base64: None, - } - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct SpreadsheetSheetRef { - pub sheet_name: String, -} - -#[derive(Debug, Clone, Serialize)] -pub struct SpreadsheetArtifactSnapshot { - pub sheet_count: usize, - pub sheet_names: Vec, - pub sheets: Vec, -} - -#[derive(Debug, Clone, Serialize)] -pub struct SpreadsheetSheetSnapshot { - pub sheet_id: String, - pub name: String, - pub filled_rows: usize, - pub filled_columns: usize, - pub minimum_range_filled: String, - pub merged_range_count: usize, - pub chart_count: usize, - pub table_count: usize, - pub conditional_format_count: usize, - pub pivot_table_count: usize, -} - -#[derive(Debug, Deserialize)] -struct CreateArgs { - name: Option, - auto_recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct PathArgs { - path: PathBuf, -} - -#[derive(Debug, Deserialize)] -struct SaveArgs { - path: PathBuf, - file_type: Option, -} - -#[derive(Debug, Deserialize)] -struct RenderArgs { - output_path: Option, - sheet_name: Option, - sheet_index: Option, - range: Option, - center_address: Option, - width: Option, - height: Option, - include_headers: Option, - scale: Option, - performance_mode: Option, -} - -#[derive(Debug, Deserialize)] -struct SheetLookupArgs { - sheet_name: Option, - sheet_index: Option, - range: Option, -} - -#[derive(Debug, Deserialize)] -struct ChartLookupArgs { - sheet_name: Option, - sheet_index: Option, - chart_id: Option, - chart_index: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateChartArgs { - sheet_name: Option, - sheet_index: Option, - chart_type: crate::SpreadsheetChartType, - source_sheet_name: Option, - source_range: String, - options: Option, -} - -#[derive(Debug, Deserialize)] -struct AddChartSeriesArgs { - sheet_name: Option, - sheet_index: Option, - chart_id: Option, - chart_index: Option, - series: crate::SpreadsheetChartSeries, -} - -#[derive(Debug, Deserialize)] -struct SetChartPropertiesArgs { - #[serde(flatten)] - lookup: ChartLookupArgs, - properties: crate::SpreadsheetChartProperties, -} - -#[derive(Debug, Deserialize)] -struct TableLookupArgs { - sheet_name: Option, - sheet_index: Option, - name: Option, - display_name: Option, - id: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateTableArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - options: crate::SpreadsheetCreateTableOptions, -} - -#[derive(Debug, Deserialize)] -struct SetTableStyleArgs { - #[serde(flatten)] - lookup: TableLookupArgs, - options: crate::SpreadsheetTableStyleOptions, -} - -#[derive(Debug, Deserialize)] -struct RenameTableColumnArgs { - #[serde(flatten)] - lookup: TableLookupArgs, - column_id: Option, - column_name: Option, - new_name: String, -} - -#[derive(Debug, Deserialize)] -struct SetTableColumnTotalsArgs { - #[serde(flatten)] - lookup: TableLookupArgs, - column_id: Option, - column_name: Option, - totals_row_label: Option, - totals_row_function: Option, -} - -#[derive(Debug, Deserialize)] -struct AddConditionalFormatArgs { - sheet_name: Option, - sheet_index: Option, - format: crate::SpreadsheetConditionalFormat, -} - -#[derive(Debug, Deserialize)] -struct DeleteConditionalFormatArgs { - sheet_name: Option, - sheet_index: Option, - id: u32, -} - -#[derive(Debug, Deserialize)] -struct PivotTableLookupArgs { - sheet_name: Option, - sheet_index: Option, - name: Option, - index: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateSheetArgs { - name: String, -} - -#[derive(Debug, Deserialize)] -struct RenameSheetArgs { - old_name: Option, - sheet_index: Option, - new_name: String, -} - -#[derive(Debug, Deserialize)] -struct DeleteSheetArgs { - sheet_name: Option, - sheet_index: Option, -} - -#[derive(Debug, Deserialize)] -struct SetSheetPropertiesArgs { - sheet_name: Option, - sheet_index: Option, - default_row_height: Option, - default_column_width: Option, - show_grid_lines: Option, -} - -#[derive(Debug, Deserialize)] -struct SetColumnWidthsArgs { - sheet_name: Option, - sheet_index: Option, - reference: String, - width: f64, -} - -#[derive(Debug, Deserialize)] -struct SetColumnWidthsBulkArgs { - sheet_name: Option, - sheet_index: Option, - widths: BTreeMap, -} - -#[derive(Debug, Deserialize)] -struct SetRowHeightArgs { - sheet_name: Option, - sheet_index: Option, - row_index: u32, - height: Option, -} - -#[derive(Debug, Deserialize)] -struct SetRowHeightsArgs { - sheet_name: Option, - sheet_index: Option, - start_row_index: u32, - end_row_index: u32, - height: Option, -} - -#[derive(Debug, Deserialize)] -struct SetRowHeightsBulkArgs { - sheet_name: Option, - sheet_index: Option, - heights: BTreeMap>, -} - -#[derive(Debug, Deserialize)] -struct GetRowHeightArgs { - sheet_name: Option, - sheet_index: Option, - row_index: u32, -} - -#[derive(Debug, Deserialize)] -struct CreateTextStyleArgs { - style: crate::SpreadsheetTextStyle, - source_style_id: Option, - merge_with_existing_components: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateFillArgs { - fill: crate::SpreadsheetFill, - source_fill_id: Option, - merge_with_existing_components: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateBorderArgs { - border: crate::SpreadsheetBorder, - source_border_id: Option, - merge_with_existing_components: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateNumberFormatArgs { - number_format: crate::SpreadsheetNumberFormat, - source_number_format_id: Option, - merge_with_existing_components: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateCellFormatArgs { - format: crate::SpreadsheetCellFormat, - source_format_id: Option, - merge_with_existing_components: Option, -} - -#[derive(Debug, Deserialize)] -struct CreateDifferentialFormatArgs { - format: crate::SpreadsheetDifferentialFormat, -} - -#[derive(Debug, Deserialize)] -struct GetStyleArgs { - id: u32, -} - -#[derive(Debug, Deserialize)] -struct CellAddressArgs { - sheet_name: Option, - sheet_index: Option, - address: String, -} - -#[derive(Debug, Deserialize)] -struct ReferenceArgs { - sheet_name: Option, - sheet_index: Option, - reference: String, -} - -#[derive(Debug, Deserialize)] -struct CellIndicesArgs { - sheet_name: Option, - sheet_index: Option, - column_index: u32, - row_index: u32, -} - -#[derive(Debug, Deserialize)] -struct CellFieldArgs { - sheet_name: Option, - sheet_index: Option, - address: String, - field: String, -} - -#[derive(Debug, Deserialize)] -struct CellFieldByIndicesArgs { - sheet_name: Option, - sheet_index: Option, - column_index: u32, - row_index: u32, - field: String, -} - -#[derive(Debug, Deserialize)] -struct RangeArgs { - sheet_name: Option, - sheet_index: Option, - range: String, -} - -#[derive(Debug, Deserialize)] -struct SetCellValueArgs { - sheet_name: Option, - sheet_index: Option, - address: String, - value: Value, - recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct SetRangeValuesArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - values: Vec>, - recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct SetRangeValueArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - value: Value, - recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct SetCellFormulaArgs { - sheet_name: Option, - sheet_index: Option, - address: String, - formula: String, - recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct SetRangeFormulasArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - formulas: Vec>>, - recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct SetRangeFormulaArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - formula: String, - recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct SetCellStyleArgs { - sheet_name: Option, - sheet_index: Option, - address: String, - style_index: u32, -} - -#[derive(Debug, Deserialize)] -struct SetRangeStyleArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - style_index: u32, -} - -#[derive(Debug, Deserialize)] -struct ClearRangeArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - fields: Option>, - recalculate: Option, -} - -#[derive(Debug, Deserialize)] -struct MergeRangeArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - raise_on_conflict: Option, -} - -#[derive(Debug, Deserialize)] -struct CiteRangeArgs { - sheet_name: Option, - sheet_index: Option, - range: String, - tether_id: String, - start_line: Option, - end_line: Option, - content_reference_type: Option, - source_type: Option, -} - -#[derive(Debug, Deserialize)] -struct CiteCellArgs { - sheet_name: Option, - sheet_index: Option, - address: String, - tether_id: String, - start_line: Option, - end_line: Option, - content_reference_type: Option, - source_type: Option, -} - -#[derive(Debug, Deserialize)] -struct DeserializeDictArgs { - data: Value, - artifact_id: Option, -} - -#[derive(Debug, Deserialize)] -struct DeserializeJsonArgs { - json: String, - artifact_id: Option, -} - -#[derive(Debug, Deserialize)] -struct DeserializeBytesArgs { - bytes_base64: String, - artifact_id: Option, -} - -fn snapshot_for_artifact(artifact: &SpreadsheetArtifact) -> SpreadsheetArtifactSnapshot { - SpreadsheetArtifactSnapshot { - sheet_count: artifact.sheets.len(), - sheet_names: artifact.list_sheet_names(), - sheets: artifact - .sheets - .iter() - .map(|sheet| SpreadsheetSheetSnapshot { - sheet_id: sheet.sheet_id.clone(), - name: sheet.name.clone(), - filled_rows: sheet.filled_rows(), - filled_columns: sheet.filled_columns(), - minimum_range_filled: sheet.minimum_range_filled(), - merged_range_count: sheet.merged_ranges.len(), - chart_count: sheet.charts.len(), - table_count: sheet.tables.len(), - conditional_format_count: sheet.conditional_formats.len(), - pivot_table_count: sheet.pivot_tables.len(), - }) - .collect(), - } -} - -fn chart_lookup_from_args(args: &ChartLookupArgs) -> crate::SpreadsheetChartLookup { - crate::SpreadsheetChartLookup { - id: args.chart_id, - index: args.chart_index.map(|value| value as usize), - } -} - -fn table_lookup_from_args(args: &TableLookupArgs) -> crate::SpreadsheetTableLookup<'_> { - crate::SpreadsheetTableLookup { - name: args.name.as_deref(), - display_name: args.display_name.as_deref(), - id: args.id, - } -} - -fn pivot_lookup_from_args(args: &PivotTableLookupArgs) -> crate::SpreadsheetPivotTableLookup<'_> { - crate::SpreadsheetPivotTableLookup { - name: args.name.as_deref(), - index: args.index.map(|value| value as usize), - } -} - -fn sheet_reference(sheet: &crate::SpreadsheetSheet) -> SpreadsheetSheetRef { - SpreadsheetSheetRef { - sheet_name: sheet.name.clone(), - } -} - -fn normalize_optional_cell_value( - value: Value, -) -> Result, SpreadsheetArtifactError> { - if value.is_null() { - Ok(None) - } else { - Ok(Some(SpreadsheetCellValue::try_from(value)?)) - } -} - -fn normalize_value_matrix( - values: Vec>, - action: &str, -) -> Result>>, SpreadsheetArtifactError> { - if values.is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "values matrix cannot be empty".to_string(), - }); - } - let width = values.first().map(Vec::len).unwrap_or(0); - if width == 0 || values.iter().any(|row| row.len() != width) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "values matrix must be rectangular".to_string(), - }); - } - values - .into_iter() - .map(|row| { - row.into_iter() - .map(normalize_optional_cell_value) - .collect::, _>>() - }) - .collect::, _>>() -} - -fn normalize_formula(formula: String) -> String { - let trimmed = formula.trim(); - if trimmed.starts_with('=') { - trimmed.to_string() - } else { - format!("={trimmed}") - } -} - -fn render_options_from_args( - args: RenderArgs, -) -> Result { - let scale = args.scale.unwrap_or(1.0); - if scale <= 0.0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "render".to_string(), - message: "render scale must be positive".to_string(), - }); - } - Ok(crate::SpreadsheetRenderOptions { - output_path: args.output_path, - center_address: args.center_address, - width: args.width, - height: args.height, - include_headers: args.include_headers.unwrap_or(true), - scale, - performance_mode: args.performance_mode.unwrap_or(false), - }) -} - -fn required_artifact_id( - request: &SpreadsheetArtifactRequest, -) -> Result { - request - .artifact_id - .clone() - .ok_or_else(|| SpreadsheetArtifactError::MissingArtifactId { - action: request.action.clone(), - }) -} - -fn parse_args Deserialize<'de>>( - action: &str, - value: &Value, -) -> Result { - serde_json::from_value(value.clone()).map_err(|error| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: error.to_string(), - }) -} - -fn resolve_path(cwd: &Path, path: &Path) -> PathBuf { - if path.is_absolute() { - path.to_path_buf() - } else { - cwd.join(path) - } -} - -fn to_serialized_value(value: T) -> Result { - serde_json::to_value(value).map_err(|error| SpreadsheetArtifactError::Serialization { - message: error.to_string(), - }) -} diff --git a/codex-rs/artifact-spreadsheet/src/model.rs b/codex-rs/artifact-spreadsheet/src/model.rs deleted file mode 100644 index 747eedbcea..0000000000 --- a/codex-rs/artifact-spreadsheet/src/model.rs +++ /dev/null @@ -1,1787 +0,0 @@ -use std::collections::BTreeMap; -use std::collections::BTreeSet; -use std::path::Path; -use std::path::PathBuf; - -use base64::Engine; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use serde::Deserialize; -use serde::Serialize; -use serde_json::Value; -use uuid::Uuid; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifactError; -use crate::formula::recalculate_workbook; -use crate::parse_column_reference; -use crate::xlsx::import_xlsx; -use crate::xlsx::write_xlsx; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum SpreadsheetFileType { - Xlsx, - Json, - Binary, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", content = "value", rename_all = "snake_case")] -pub enum SpreadsheetCellValue { - Bool(bool), - Integer(i64), - Float(f64), - String(String), - DateTime(String), - Error(String), -} - -impl SpreadsheetCellValue { - pub fn to_json_value(&self) -> Value { - match self { - Self::Bool(value) => Value::Bool(*value), - Self::Integer(value) => Value::Number((*value).into()), - Self::Float(value) => serde_json::Number::from_f64(*value) - .map(Value::Number) - .unwrap_or_else(|| Value::String(value.to_string())), - Self::String(value) | Self::DateTime(value) | Self::Error(value) => { - Value::String(value.clone()) - } - } - } - - pub fn as_f64(&self) -> Option { - match self { - Self::Integer(value) => Some(*value as f64), - Self::Float(value) => Some(*value), - _ => None, - } - } -} - -impl TryFrom for SpreadsheetCellValue { - type Error = SpreadsheetArtifactError; - - fn try_from(value: Value) -> Result { - match value { - Value::Object(_) => serde_json::from_value(value).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - }), - Value::Bool(value) => Ok(Self::Bool(value)), - Value::Number(value) => { - if let Some(integer) = value.as_i64() { - Ok(Self::Integer(integer)) - } else if let Some(float) = value.as_f64() { - Ok(Self::Float(float)) - } else { - Err(SpreadsheetArtifactError::Serialization { - message: "unsupported JSON number".to_string(), - }) - } - } - Value::String(value) => Ok(Self::String(value)), - Value::Null => Err(SpreadsheetArtifactError::Serialization { - message: "null is represented as an empty cell, not a cell value".to_string(), - }), - other => Err(SpreadsheetArtifactError::Serialization { - message: format!("unsupported JSON cell value `{other}`"), - }), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetCitation { - pub tether_id: String, - pub start_line: Option, - pub end_line: Option, - pub content_reference_type: Option, - pub source_type: Option, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetCell { - pub value: Option, - pub formula: Option, - pub style_index: u32, - #[serde(default)] - pub citations: Vec, -} - -impl SpreadsheetCell { - pub fn to_dict(&self) -> Result { - serde_json::to_value(self).map_err(|error| SpreadsheetArtifactError::Serialization { - message: error.to_string(), - }) - } - - pub fn data(&self) -> Option { - if let Some(formula) = &self.formula { - return Some(Value::String(formula.clone())); - } - self.value.as_ref().map(SpreadsheetCellValue::to_json_value) - } - - pub fn is_empty(&self) -> bool { - self.value.is_none() - && self.formula.is_none() - && self.style_index == 0 - && self.citations.is_empty() - } - - pub fn is_calculation_error(&self) -> bool { - matches!( - self.value, - Some(SpreadsheetCellValue::Error(ref value)) - if matches!( - value.as_str(), - "#DIV/0!" - | "#N/A" - | "#NAME?" - | "#NUM!" - | "#REF!" - | "#VALUE!" - | "#CYCLE!" - | "#ERROR!" - | "#LIC!" - ) - ) - } - - pub fn calculation_error_message(&self) -> Option<&'static str> { - match self.value.as_ref() { - Some(SpreadsheetCellValue::Error(value)) => match value.as_str() { - "#DIV/0!" => Some("Division by zero"), - "#N/A" => Some("Value is not available"), - "#NAME?" => Some("Unknown function or name"), - "#NUM!" => Some("Invalid numeric result"), - "#REF!" => Some("Invalid cell reference"), - "#VALUE!" => Some("Invalid value type"), - "#CYCLE!" => Some("Formula cycle detected"), - "#ERROR!" => Some("Formula parse error"), - "#LIC!" => Some("Calculation engine license error"), - _ => None, - }, - _ => None, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetCellRef { - pub sheet_name: String, - pub address: String, -} - -impl SpreadsheetCellRef { - pub fn new(sheet_name: String, address: CellAddress) -> Self { - Self { - sheet_name, - address: address.to_a1(), - } - } - - pub fn cell_address(&self) -> Result { - CellAddress::parse(&self.address) - } - - pub fn get( - &self, - sheet: &SpreadsheetSheet, - ) -> Result { - self.ensure_sheet(sheet)?; - Ok(sheet.get_cell_view(self.cell_address()?)) - } - - pub fn data( - &self, - sheet: &SpreadsheetSheet, - ) -> Result, SpreadsheetArtifactError> { - Ok(self.get(sheet)?.data) - } - - pub fn raw_cell( - &self, - sheet: &SpreadsheetSheet, - ) -> Result, SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - Ok(sheet.get_cell(self.cell_address()?).cloned()) - } - - pub fn to_dict(&self, sheet: &SpreadsheetSheet) -> Result { - Ok(match self.raw_cell(sheet)? { - Some(cell) => cell.to_dict()?, - None => Value::Object(Default::default()), - }) - } - - pub fn set_value( - &self, - sheet: &mut SpreadsheetSheet, - value: Option, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_value(self.cell_address()?, value) - } - - pub fn set_formula( - &self, - sheet: &mut SpreadsheetSheet, - formula: Option, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_formula(self.cell_address()?, formula) - } - - pub fn cite( - &self, - sheet: &mut SpreadsheetSheet, - citation: SpreadsheetCitation, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.cite_range( - &CellRange::from_start_end(self.cell_address()?, self.cell_address()?), - citation, - ) - } - - pub fn set_style_index( - &self, - sheet: &mut SpreadsheetSheet, - style_index: u32, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_style_index( - &CellRange::from_start_end(self.cell_address()?, self.cell_address()?), - style_index, - ) - } - - pub fn is_calculation_error( - &self, - sheet: &SpreadsheetSheet, - ) -> Result { - Ok(self.get(sheet)?.is_calculation_error) - } - - pub fn get_calculation_error_message( - &self, - sheet: &SpreadsheetSheet, - ) -> Result, SpreadsheetArtifactError> { - Ok(self.get(sheet)?.calculation_error_message) - } - - fn ensure_sheet(&self, sheet: &SpreadsheetSheet) -> Result<(), SpreadsheetArtifactError> { - if self.sheet_name != sheet.name { - return Err(SpreadsheetArtifactError::SheetLookup { - action: "cell_ref".to_string(), - message: format!( - "cell ref points to `{}` but sheet is `{}`", - self.sheet_name, sheet.name - ), - }); - } - Ok(()) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetCellRangeRef { - pub sheet_name: String, - pub address: String, -} - -impl SpreadsheetCellRangeRef { - pub fn new(sheet_name: String, range: &CellRange) -> Self { - Self { - sheet_name, - address: range.to_a1(), - } - } - - pub fn range(&self) -> Result { - CellRange::parse(&self.address) - } - - pub fn get( - &self, - sheet: &SpreadsheetSheet, - ) -> Result { - self.ensure_sheet(sheet)?; - Ok(sheet.get_range_view(&self.range()?)) - } - - pub fn get_values( - &self, - sheet: &SpreadsheetSheet, - ) -> Result>>, SpreadsheetArtifactError> { - Ok(self.get(sheet)?.values) - } - - pub fn get_formulas( - &self, - sheet: &SpreadsheetSheet, - ) -> Result>>, SpreadsheetArtifactError> { - Ok(self.get(sheet)?.formulas) - } - - pub fn get_style_indices( - &self, - sheet: &SpreadsheetSheet, - ) -> Result>, SpreadsheetArtifactError> { - Ok(self.get(sheet)?.style_indices) - } - - pub fn get_data( - &self, - sheet: &SpreadsheetSheet, - ) -> Result>>, SpreadsheetArtifactError> { - Ok(self.get(sheet)?.data) - } - - pub fn top_left_style_index( - &self, - sheet: &SpreadsheetSheet, - ) -> Result { - self.ensure_sheet(sheet)?; - Ok(sheet.top_left_style_index(&self.range()?)) - } - - pub fn set_value( - &self, - sheet: &mut SpreadsheetSheet, - value: Option, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_range_to_value(&self.range()?, value) - } - - pub fn set_values( - &self, - sheet: &mut SpreadsheetSheet, - values: &[Vec>], - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_values_matrix(&self.range()?, values) - } - - pub fn set_formula( - &self, - sheet: &mut SpreadsheetSheet, - formula: Option, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_range_to_formula(&self.range()?, formula) - } - - pub fn set_formulas( - &self, - sheet: &mut SpreadsheetSheet, - formulas: &[Vec>], - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_formulas_matrix(&self.range()?, formulas) - } - - pub fn set_style_index( - &self, - sheet: &mut SpreadsheetSheet, - style_index: u32, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.set_style_index(&self.range()?, style_index) - } - - pub fn merge( - &self, - sheet: &mut SpreadsheetSheet, - raise_on_conflict: bool, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.merge_cells(&self.range()?, raise_on_conflict) - } - - pub fn unmerge(&self, sheet: &mut SpreadsheetSheet) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.unmerge_cells(&self.range()?); - Ok(()) - } - - pub fn cite( - &self, - sheet: &mut SpreadsheetSheet, - citation: SpreadsheetCitation, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_sheet(sheet)?; - sheet.cite_range(&self.range()?, citation) - } - - fn ensure_sheet(&self, sheet: &SpreadsheetSheet) -> Result<(), SpreadsheetArtifactError> { - if self.sheet_name != sheet.name { - return Err(SpreadsheetArtifactError::SheetLookup { - action: "range_ref".to_string(), - message: format!( - "range ref points to `{}` but sheet is `{}`", - self.sheet_name, sheet.name - ), - }); - } - Ok(()) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum SpreadsheetSheetReference { - Cell { cell_ref: SpreadsheetCellRef }, - Range { range_ref: SpreadsheetCellRangeRef }, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetSheetSummary { - pub name: String, - pub filled_rows: usize, - pub filled_columns: usize, - pub minimum_range_filled: String, - pub min_row_idx: Option, - pub max_row_idx: Option, - pub min_column_idx: Option, - pub max_column_idx: Option, - pub min_column_letter: Option, - pub max_column_letter: Option, - pub first_row_address_range: Option, - pub default_row_height: Option, - pub default_column_width: Option, - pub show_grid_lines: bool, - pub merged_range_count: usize, - pub chart_count: usize, - pub table_count: usize, - pub conditional_format_count: usize, - pub pivot_table_count: usize, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetSummary { - pub artifact_id: String, - pub sheets: Vec, - pub size_bytes: usize, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetCellView { - pub sheet_name: String, - pub address: String, - pub effective_address: String, - pub exists: bool, - pub value: Option, - pub formula: Option, - pub style_index: u32, - pub data: Option, - pub is_calculation_error: bool, - pub calculation_error_message: Option, - pub citations: Vec, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetRangeView { - pub sheet_name: String, - pub address: String, - pub values: Vec>>, - pub formulas: Vec>>, - pub style_indices: Vec>, - pub data: Vec>>, - pub is_single_cell: bool, - pub is_single_row: bool, - pub is_single_column: bool, - pub contains_merged_cells: bool, - pub is_exactly_one_merged_cell: bool, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetSheet { - pub sheet_id: String, - pub name: String, - #[serde(default, with = "cell_map_serde")] - pub cells: BTreeMap, - #[serde(default)] - pub merged_ranges: Vec, - #[serde(default)] - pub charts: Vec, - #[serde(default)] - pub tables: Vec, - #[serde(default)] - pub conditional_formats: Vec, - #[serde(default)] - pub pivot_tables: Vec, - pub default_row_height: Option, - pub default_column_width: Option, - pub show_grid_lines: bool, - #[serde(default)] - pub column_widths: BTreeMap, - #[serde(default)] - pub row_heights: BTreeMap, -} - -mod cell_map_serde { - use std::collections::BTreeMap; - - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; - - use crate::CellAddress; - use crate::SpreadsheetCell; - #[derive(Serialize, Deserialize)] - struct CellEntry { - address: String, - cell: SpreadsheetCell, - } - - pub fn serialize( - cells: &BTreeMap, - serializer: S, - ) -> Result - where - S: Serializer, - { - let entries = cells - .iter() - .map(|(address, cell)| CellEntry { - address: address.to_a1(), - cell: cell.clone(), - }) - .collect::>(); - entries.serialize(serializer) - } - - pub fn deserialize<'de, D>( - deserializer: D, - ) -> Result, D::Error> - where - D: Deserializer<'de>, - { - let entries = Vec::::deserialize(deserializer)?; - let mut cells = BTreeMap::new(); - for entry in entries { - let address = CellAddress::parse(&entry.address).map_err(serde::de::Error::custom)?; - cells.insert(address, entry.cell); - } - Ok(cells) - } -} - -impl SpreadsheetSheet { - pub fn new(name: String) -> Self { - Self { - sheet_id: format!("sheet_{}", Uuid::new_v4().simple()), - name, - cells: BTreeMap::new(), - merged_ranges: Vec::new(), - charts: Vec::new(), - tables: Vec::new(), - conditional_formats: Vec::new(), - pivot_tables: Vec::new(), - default_row_height: None, - default_column_width: None, - show_grid_lines: true, - column_widths: BTreeMap::new(), - row_heights: BTreeMap::new(), - } - } - - pub fn filled_rows(&self) -> usize { - self.cells - .keys() - .map(|address| address.row) - .collect::>() - .len() - } - - pub fn filled_columns(&self) -> usize { - self.cells - .keys() - .map(|address| address.column) - .collect::>() - .len() - } - - pub fn is_empty(&self) -> bool { - self.cells.is_empty() - } - - pub fn minimum_range(&self) -> Option { - let mut iter = self.cells.keys(); - let first = *iter.next()?; - let mut min_row = first.row; - let mut max_row = first.row; - let mut min_column = first.column; - let mut max_column = first.column; - - for address in iter { - min_row = min_row.min(address.row); - max_row = max_row.max(address.row); - min_column = min_column.min(address.column); - max_column = max_column.max(address.column); - } - - Some(CellRange::from_start_end( - CellAddress { - column: min_column, - row: min_row, - }, - CellAddress { - column: max_column, - row: max_row, - }, - )) - } - - pub fn minimum_range_ref(&self) -> Option { - self.minimum_range() - .map(|range| SpreadsheetCellRangeRef::new(self.name.clone(), &range)) - } - - pub fn minimum_range_filled(&self) -> String { - self.minimum_range() - .map(|range| range.to_a1()) - .unwrap_or_default() - } - - pub fn min_column_letter(&self) -> Option { - self.minimum_range() - .map(|range| crate::column_index_to_letters(range.start.column)) - } - - pub fn max_column_letter(&self) -> Option { - self.minimum_range() - .map(|range| crate::column_index_to_letters(range.end.column)) - } - - pub fn first_row_address_range(&self) -> Option { - self.minimum_range().map(|range| { - CellRange::from_start_end( - CellAddress { - column: range.start.column, - row: range.start.row, - }, - CellAddress { - column: range.end.column, - row: range.start.row, - }, - ) - .to_a1() - }) - } - - pub fn summary(&self) -> SpreadsheetSheetSummary { - let minimum = self.minimum_range(); - SpreadsheetSheetSummary { - name: self.name.clone(), - filled_rows: self.filled_rows(), - filled_columns: self.filled_columns(), - minimum_range_filled: self.minimum_range_filled(), - min_row_idx: minimum.as_ref().map(|range| range.start.row), - max_row_idx: minimum.as_ref().map(|range| range.end.row), - min_column_idx: minimum.as_ref().map(|range| range.start.column), - max_column_idx: minimum.as_ref().map(|range| range.end.column), - min_column_letter: self.min_column_letter(), - max_column_letter: self.max_column_letter(), - first_row_address_range: self.first_row_address_range(), - default_row_height: self.default_row_height, - default_column_width: self.default_column_width, - show_grid_lines: self.show_grid_lines, - merged_range_count: self.merged_ranges.len(), - chart_count: self.charts.len(), - table_count: self.tables.len(), - conditional_format_count: self.conditional_formats.len(), - pivot_table_count: self.pivot_tables.len(), - } - } - - pub fn to_dict(&self) -> Result { - serde_json::to_value(self).map_err(|error| SpreadsheetArtifactError::Serialization { - message: error.to_string(), - }) - } - - pub fn cell_ref( - &self, - address: impl AsRef, - ) -> Result { - Ok(SpreadsheetCellRef::new( - self.name.clone(), - CellAddress::parse(address.as_ref())?, - )) - } - - pub fn range_ref( - &self, - address: impl AsRef, - ) -> Result { - let range = CellRange::parse(address.as_ref())?; - Ok(SpreadsheetCellRangeRef::new(self.name.clone(), &range)) - } - - pub fn reference( - &self, - address: impl AsRef, - ) -> Result { - let address = address.as_ref(); - if let Ok(cell_ref) = self.cell_ref(address) { - return Ok(SpreadsheetSheetReference::Cell { cell_ref }); - } - Ok(SpreadsheetSheetReference::Range { - range_ref: self.range_ref(address)?, - }) - } - - pub fn set_column_widths( - &mut self, - reference: &str, - width: f64, - ) -> Result<(), SpreadsheetArtifactError> { - if width <= 0.0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "set_column_widths".to_string(), - message: "column width must be positive".to_string(), - }); - } - let (start, end) = parse_column_reference(reference)?; - for column in start..=end { - self.column_widths.insert(column, width); - } - Ok(()) - } - - pub fn set_column_widths_bulk( - &mut self, - widths: &BTreeMap, - ) -> Result<(), SpreadsheetArtifactError> { - for (reference, width) in widths { - self.set_column_widths(reference, *width)?; - } - Ok(()) - } - - pub fn get_column_width( - &self, - reference: &str, - ) -> Result, SpreadsheetArtifactError> { - let (start, end) = parse_column_reference(reference)?; - if start != end { - return Ok((start..=end) - .find_map(|column| self.column_widths.get(&column).copied()) - .or(self.default_column_width)); - } - Ok(self - .column_widths - .get(&start) - .copied() - .or(self.default_column_width)) - } - - pub fn set_row_height( - &mut self, - row_index: u32, - height: Option, - ) -> Result<(), SpreadsheetArtifactError> { - if row_index == 0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "set_row_height".to_string(), - message: "row index must be positive".to_string(), - }); - } - if let Some(height) = height { - if height <= 0.0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "set_row_height".to_string(), - message: "row height must be positive".to_string(), - }); - } - self.row_heights.insert(row_index, height); - } else { - self.row_heights.remove(&row_index); - } - Ok(()) - } - - pub fn set_row_heights( - &mut self, - start_row_index: u32, - end_row_index: u32, - height: Option, - ) -> Result<(), SpreadsheetArtifactError> { - if start_row_index == 0 || end_row_index == 0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "set_row_heights".to_string(), - message: "row indices must be positive".to_string(), - }); - } - let start = start_row_index.min(end_row_index); - let end = start_row_index.max(end_row_index); - for row_index in start..=end { - self.set_row_height(row_index, height)?; - } - Ok(()) - } - - pub fn set_row_heights_bulk( - &mut self, - heights: &BTreeMap>, - ) -> Result<(), SpreadsheetArtifactError> { - for (row_index, height) in heights { - self.set_row_height(*row_index, *height)?; - } - Ok(()) - } - - pub fn get_row_height(&self, row_index: u32) -> Option { - self.row_heights - .get(&row_index) - .copied() - .or(self.default_row_height) - } - - pub fn cell_exists(&self, address: CellAddress) -> bool { - self.cells.contains_key(&address) - } - - pub fn merged_range_for(&self, address: CellAddress) -> Option<&CellRange> { - self.merged_ranges - .iter() - .find(|range| range.contains(address)) - } - - pub fn effective_address(&self, address: CellAddress) -> CellAddress { - self.merged_range_for(address) - .map(|range| range.start) - .unwrap_or(address) - } - - pub fn get_cell(&self, address: CellAddress) -> Option<&SpreadsheetCell> { - let effective = self.effective_address(address); - self.cells.get(&effective) - } - - pub fn get_cell_by_indices(&self, column: u32, row: u32) -> Option<&SpreadsheetCell> { - self.get_cell(CellAddress { column, row }) - } - - pub fn get_cell_mut(&mut self, address: CellAddress) -> Option<&mut SpreadsheetCell> { - let effective = self.effective_address(address); - self.cells.get_mut(&effective) - } - - pub fn get_or_create_cell_mut(&mut self, address: CellAddress) -> &mut SpreadsheetCell { - let effective = self.effective_address(address); - self.cells.entry(effective).or_insert(SpreadsheetCell { - value: None, - formula: None, - style_index: 0, - citations: Vec::new(), - }) - } - - pub fn clear_range( - &mut self, - range: &CellRange, - fields: Option<&[String]>, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_range_write_allowed(range, false, "clear_range")?; - for address in range.addresses() { - if let Some(cell) = self.get_cell_mut(address) { - match fields { - Some(fields) => { - for field in fields { - match field.as_str() { - "value" => cell.value = None, - "formula" => cell.formula = None, - "style_index" => cell.style_index = 0, - "citations" => cell.citations.clear(), - other => { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "clear_range".to_string(), - message: format!("unsupported cell field `{other}`"), - }); - } - } - } - } - None => { - cell.value = None; - cell.formula = None; - cell.style_index = 0; - cell.citations.clear(); - } - } - } - } - self.cells.retain(|_, cell| !cell.is_empty()); - Ok(()) - } - - pub fn set_value( - &mut self, - address: CellAddress, - value: Option, - ) -> Result<(), SpreadsheetArtifactError> { - let range = CellRange::from_start_end(address, address); - self.ensure_range_write_allowed(&range, false, "set_value")?; - let cell = self.get_or_create_cell_mut(address); - cell.formula = None; - cell.value = value; - if cell.is_empty() { - self.cells.remove(&address); - } - Ok(()) - } - - pub fn set_range_to_value( - &mut self, - range: &CellRange, - value: Option, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_range_write_allowed(range, false, "set_range_to_value")?; - for address in range.addresses() { - let cell = self.get_or_create_cell_mut(address); - cell.formula = None; - cell.value = value.clone(); - } - self.cells.retain(|_, cell| !cell.is_empty()); - Ok(()) - } - - pub fn set_formula( - &mut self, - address: CellAddress, - formula: Option, - ) -> Result<(), SpreadsheetArtifactError> { - let range = CellRange::from_start_end(address, address); - self.ensure_range_write_allowed(&range, false, "set_formula")?; - let cell = self.get_or_create_cell_mut(address); - cell.formula = formula; - if cell.formula.is_none() { - cell.value = None; - } - if cell.is_empty() { - self.cells.remove(&address); - } - Ok(()) - } - - pub fn set_range_to_formula( - &mut self, - range: &CellRange, - formula: Option, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_range_write_allowed(range, false, "set_range_to_formula")?; - for address in range.addresses() { - let cell = self.get_or_create_cell_mut(address); - cell.formula = formula.clone(); - } - self.cells.retain(|_, cell| !cell.is_empty()); - Ok(()) - } - - pub fn set_cell_values_to( - &mut self, - address: &str, - value: Option, - ) -> Result<(), SpreadsheetArtifactError> { - let range = CellRange::parse(address)?; - self.set_range_to_value(&range, value) - } - - pub fn set_cell_formulas_to( - &mut self, - address: &str, - formula: Option, - ) -> Result<(), SpreadsheetArtifactError> { - let range = CellRange::parse(address)?; - self.set_range_to_formula(&range, formula) - } - - pub fn set_style_index( - &mut self, - range: &CellRange, - style_index: u32, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_range_write_allowed(range, false, "set_style_index")?; - for address in range.addresses() { - let cell = self.get_or_create_cell_mut(address); - cell.style_index = style_index; - } - self.cells.retain(|_, cell| !cell.is_empty()); - Ok(()) - } - - pub fn cite_range( - &mut self, - range: &CellRange, - citation: SpreadsheetCitation, - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_range_write_allowed(range, true, "cite_range")?; - for address in range.addresses() { - let cell = self.get_or_create_cell_mut(address); - cell.citations.push(citation.clone()); - } - Ok(()) - } - - pub fn set_values_matrix( - &mut self, - range: &CellRange, - values: &[Vec>], - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_range_write_allowed(range, false, "set_values_matrix")?; - if values.len() != range.height() || values.iter().any(|row| row.len() != range.width()) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "set_range_values".to_string(), - message: format!( - "matrix dimensions {}x{} do not match range {}x{}", - values.len(), - values.first().map(Vec::len).unwrap_or(0), - range.height(), - range.width() - ), - }); - } - - for (row_offset, row) in values.iter().enumerate() { - for (column_offset, value) in row.iter().enumerate() { - let address = CellAddress { - column: range.start.column + column_offset as u32, - row: range.start.row + row_offset as u32, - }; - let cell = self.get_or_create_cell_mut(address); - cell.formula = None; - cell.value = value.clone(); - } - } - self.cells.retain(|_, cell| !cell.is_empty()); - Ok(()) - } - - pub fn set_formulas_matrix( - &mut self, - range: &CellRange, - formulas: &[Vec>], - ) -> Result<(), SpreadsheetArtifactError> { - self.ensure_range_write_allowed(range, false, "set_formulas_matrix")?; - if formulas.len() != range.height() || formulas.iter().any(|row| row.len() != range.width()) - { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "set_range_formulas".to_string(), - message: format!( - "matrix dimensions {}x{} do not match range {}x{}", - formulas.len(), - formulas.first().map(Vec::len).unwrap_or(0), - range.height(), - range.width() - ), - }); - } - - for (row_offset, row) in formulas.iter().enumerate() { - for (column_offset, formula) in row.iter().enumerate() { - let address = CellAddress { - column: range.start.column + column_offset as u32, - row: range.start.row + row_offset as u32, - }; - let cell = self.get_or_create_cell_mut(address); - cell.formula = formula.clone(); - } - } - self.cells.retain(|_, cell| !cell.is_empty()); - Ok(()) - } - - pub fn merge_cells( - &mut self, - range: &CellRange, - raise_on_conflict: bool, - ) -> Result<(), SpreadsheetArtifactError> { - for existing in &self.merged_ranges { - if existing.intersects(range) && existing != range { - if raise_on_conflict { - return Err(SpreadsheetArtifactError::MergeConflict { - action: "merge_range".to_string(), - range: range.to_a1(), - conflict: existing.to_a1(), - }); - } - return Ok(()); - } - } - self.merged_ranges.push(range.clone()); - self.merged_ranges - .sort_by_key(|entry| (entry.start.row, entry.start.column)); - Ok(()) - } - - pub fn unmerge_cells(&mut self, range: &CellRange) { - self.merged_ranges.retain(|entry| entry != range); - } - - pub fn contains_merged_cells(&self, range: &CellRange) -> bool { - self.merged_ranges - .iter() - .any(|entry| entry.intersects(range)) - } - - pub fn is_exactly_one_merged_cell(&self, range: &CellRange) -> bool { - self.merged_ranges.iter().any(|entry| entry == range) - } - - pub fn get_cell_view(&self, address: CellAddress) -> SpreadsheetCellView { - let effective = self.effective_address(address); - let cell = self.get_cell(address); - SpreadsheetCellView { - sheet_name: self.name.clone(), - address: address.to_a1(), - effective_address: effective.to_a1(), - exists: cell.is_some(), - value: cell.and_then(|entry| entry.value.clone()), - formula: cell.and_then(|entry| entry.formula.clone()), - style_index: cell.map(|entry| entry.style_index).unwrap_or(0), - data: cell.and_then(SpreadsheetCell::data), - is_calculation_error: cell - .map(SpreadsheetCell::is_calculation_error) - .unwrap_or(false), - calculation_error_message: cell - .and_then(SpreadsheetCell::calculation_error_message) - .map(str::to_string), - citations: cell - .map(|entry| entry.citations.clone()) - .unwrap_or_default(), - } - } - - pub fn get_cell_view_by_indices(&self, column: u32, row: u32) -> SpreadsheetCellView { - self.get_cell_view(CellAddress { column, row }) - } - - pub fn get_cell_field( - &self, - address: CellAddress, - field: &str, - ) -> Result, SpreadsheetArtifactError> { - let cell = self.get_cell(address); - Ok(match field { - "value" => cell.and_then(|entry| { - entry - .value - .as_ref() - .map(SpreadsheetCellValue::to_json_value) - }), - "formula" => cell.and_then(|entry| entry.formula.clone().map(Value::String)), - "style_index" => cell.map(|entry| Value::Number(entry.style_index.into())), - "data" => cell.and_then(SpreadsheetCell::data), - "citations" => cell - .map(|entry| serde_json::to_value(&entry.citations)) - .transpose() - .map_err(|error| SpreadsheetArtifactError::Serialization { - message: error.to_string(), - })?, - other => { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "get_cell_field".to_string(), - message: format!("unsupported field `{other}`"), - }); - } - }) - } - - pub fn get_cell_field_by_indices( - &self, - column: u32, - row: u32, - field: &str, - ) -> Result, SpreadsheetArtifactError> { - self.get_cell_field(CellAddress { column, row }, field) - } - - pub fn get_raw_cell(&self, address: CellAddress) -> Option { - self.get_cell(address).cloned() - } - - pub fn top_left_style_index(&self, range: &CellRange) -> u32 { - self.get_cell(range.start) - .map(|cell| cell.style_index) - .unwrap_or(0) - } - - pub fn get_range_view(&self, range: &CellRange) -> SpreadsheetRangeView { - let mut values = Vec::new(); - let mut formulas = Vec::new(); - let mut style_indices = Vec::new(); - let mut data = Vec::new(); - - for row in range.start.row..=range.end.row { - let mut value_row = Vec::new(); - let mut formula_row = Vec::new(); - let mut style_row = Vec::new(); - let mut data_row = Vec::new(); - for column in range.start.column..=range.end.column { - let cell = self.get_cell(CellAddress { column, row }); - value_row.push(cell.and_then(|entry| entry.value.clone())); - formula_row.push(cell.and_then(|entry| entry.formula.clone())); - style_row.push(cell.map(|entry| entry.style_index).unwrap_or(0)); - data_row.push(cell.and_then(SpreadsheetCell::data)); - } - values.push(value_row); - formulas.push(formula_row); - style_indices.push(style_row); - data.push(data_row); - } - - SpreadsheetRangeView { - sheet_name: self.name.clone(), - address: range.to_a1(), - values, - formulas, - style_indices, - data, - is_single_cell: range.is_single_cell(), - is_single_row: range.is_single_row(), - is_single_column: range.is_single_column(), - contains_merged_cells: self.contains_merged_cells(range), - is_exactly_one_merged_cell: self.is_exactly_one_merged_cell(range), - } - } - - pub fn to_rendered_text(&self, range: Option<&CellRange>) -> String { - let target = range - .cloned() - .or_else(|| self.minimum_range()) - .unwrap_or_else(|| { - CellRange::from_start_end( - CellAddress { column: 1, row: 1 }, - CellAddress { column: 1, row: 1 }, - ) - }); - let mut lines = Vec::new(); - for row in target.start.row..=target.end.row { - let mut entries = Vec::new(); - for column in target.start.column..=target.end.column { - let view = self.get_cell_view(CellAddress { column, row }); - let text = match view.data { - Some(Value::String(value)) => value, - Some(Value::Bool(value)) => value.to_string(), - Some(Value::Number(value)) => value.to_string(), - Some(Value::Null) | None => String::new(), - Some(other) => other.to_string(), - }; - entries.push(text); - } - lines.push(entries.join("\t")); - } - lines.join("\n") - } - - pub fn cleanup_and_validate_sheet(&mut self) -> Result<(), SpreadsheetArtifactError> { - self.cells.retain(|_, cell| !cell.is_empty()); - - for (column, width) in &self.column_widths { - if *column == 0 || *width <= 0.0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "cleanup_and_validate_sheet".to_string(), - message: format!("invalid column width entry for column {column}"), - }); - } - } - for (row, height) in &self.row_heights { - if *row == 0 || *height <= 0.0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "cleanup_and_validate_sheet".to_string(), - message: format!("invalid row height entry for row {row}"), - }); - } - } - - self.merged_ranges.sort_by_key(|range| { - ( - range.start.row, - range.start.column, - range.end.row, - range.end.column, - ) - }); - self.merged_ranges.dedup(); - for index in 0..self.merged_ranges.len() { - for other in index + 1..self.merged_ranges.len() { - if self.merged_ranges[index].intersects(&self.merged_ranges[other]) { - return Err(SpreadsheetArtifactError::MergeConflict { - action: "cleanup_and_validate_sheet".to_string(), - range: self.merged_ranges[index].to_a1(), - conflict: self.merged_ranges[other].to_a1(), - }); - } - } - } - self.validate_tables("cleanup_and_validate_sheet")?; - self.validate_charts("cleanup_and_validate_sheet")?; - self.validate_pivot_tables("cleanup_and_validate_sheet")?; - Ok(()) - } - - fn ensure_range_write_allowed( - &self, - range: &CellRange, - allow_exact_merged_cell: bool, - action: &str, - ) -> Result<(), SpreadsheetArtifactError> { - for merged in &self.merged_ranges { - if !merged.intersects(range) { - continue; - } - if allow_exact_merged_cell && merged == range { - continue; - } - if merged.contains_range(range) || range.contains_range(merged) { - if allow_exact_merged_cell || merged != range { - return Err(SpreadsheetArtifactError::MergeConflict { - action: action.to_string(), - range: range.to_a1(), - conflict: merged.to_a1(), - }); - } - } else { - return Err(SpreadsheetArtifactError::MergeConflict { - action: action.to_string(), - range: range.to_a1(), - conflict: merged.to_a1(), - }); - } - } - Ok(()) - } -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetArtifact { - pub artifact_id: String, - pub name: Option, - #[serde(default)] - pub sheets: Vec, - pub auto_recalculate: bool, - #[serde(default)] - pub text_styles: BTreeMap, - #[serde(default)] - pub fills: BTreeMap, - #[serde(default)] - pub borders: BTreeMap, - #[serde(default)] - pub number_formats: BTreeMap, - #[serde(default)] - pub cell_formats: BTreeMap, - #[serde(default)] - pub differential_formats: BTreeMap, -} - -impl SpreadsheetArtifact { - pub fn new(name: Option) -> Self { - Self { - artifact_id: format!("spreadsheet_{}", Uuid::new_v4().simple()), - name, - sheets: Vec::new(), - auto_recalculate: false, - text_styles: BTreeMap::new(), - fills: BTreeMap::new(), - borders: BTreeMap::new(), - number_formats: BTreeMap::new(), - cell_formats: BTreeMap::new(), - differential_formats: BTreeMap::new(), - } - } - - pub fn allowed_file_extensions() -> &'static [&'static str] { - &["xlsx", "json", "bin"] - } - - pub fn allowed_file_mime_types() -> &'static [&'static str] { - &[ - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "application/json", - "application/octet-stream", - ] - } - - pub fn allowed_file_types() -> &'static [SpreadsheetFileType] { - &[ - SpreadsheetFileType::Xlsx, - SpreadsheetFileType::Json, - SpreadsheetFileType::Binary, - ] - } - - pub fn get_output_file_name( - &self, - suffix: Option<&str>, - file_type: SpreadsheetFileType, - ) -> String { - let extension = match file_type { - SpreadsheetFileType::Xlsx => "xlsx", - SpreadsheetFileType::Json => "json", - SpreadsheetFileType::Binary => "bin", - }; - match suffix { - Some(suffix) => format!("{}_{}.{}", self.artifact_id, suffix, extension), - None => format!("{}.{}", self.artifact_id, extension), - } - } - - pub fn create_sheet( - &mut self, - name: String, - ) -> Result<&mut SpreadsheetSheet, SpreadsheetArtifactError> { - if name.trim().is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "create_sheet".to_string(), - message: "sheet name cannot be empty".to_string(), - }); - } - if self.sheets.iter().any(|sheet| sheet.name == name) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "create_sheet".to_string(), - message: format!("sheet `{name}` already exists"), - }); - } - self.sheets.push(SpreadsheetSheet::new(name)); - self.sheets - .last_mut() - .ok_or_else(|| SpreadsheetArtifactError::Serialization { - message: "created sheet was not available".to_string(), - }) - } - - pub fn get_sheet(&self, name: Option<&str>, index: Option) -> Option<&SpreadsheetSheet> { - if let Some(name) = name { - self.sheets.iter().find(|sheet| sheet.name == name) - } else if let Some(index) = index { - self.sheets.get(index) - } else { - None - } - } - - pub fn get_sheet_mut( - &mut self, - name: Option<&str>, - index: Option, - ) -> Option<&mut SpreadsheetSheet> { - if let Some(name) = name { - self.sheets.iter_mut().find(|sheet| sheet.name == name) - } else if let Some(index) = index { - self.sheets.get_mut(index) - } else { - None - } - } - - pub fn sheet_lookup( - &self, - action: &str, - name: Option<&str>, - index: Option, - ) -> Result<&SpreadsheetSheet, SpreadsheetArtifactError> { - self.get_sheet(name, index) - .ok_or_else(|| SpreadsheetArtifactError::SheetLookup { - action: action.to_string(), - message: match (name, index) { - (Some(name), _) => format!("sheet `{name}` was not found"), - (None, Some(index)) => format!("sheet index {index} was not found"), - (None, None) => "sheet name or index is required".to_string(), - }, - }) - } - - pub fn sheet_lookup_mut( - &mut self, - action: &str, - name: Option<&str>, - index: Option, - ) -> Result<&mut SpreadsheetSheet, SpreadsheetArtifactError> { - self.get_sheet_mut(name, index) - .ok_or_else(|| SpreadsheetArtifactError::SheetLookup { - action: action.to_string(), - message: match (name, index) { - (Some(name), _) => format!("sheet `{name}` was not found"), - (None, Some(index)) => format!("sheet index {index} was not found"), - (None, None) => "sheet name or index is required".to_string(), - }, - }) - } - - pub fn rename_sheet( - &mut self, - new_name: String, - old_name: Option<&str>, - index: Option, - ) -> Result<(), SpreadsheetArtifactError> { - if self.sheets.iter().any(|sheet| sheet.name == new_name) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "rename_sheet".to_string(), - message: format!("sheet `{new_name}` already exists"), - }); - } - let sheet = self.sheet_lookup_mut("rename_sheet", old_name, index)?; - sheet.name = new_name; - Ok(()) - } - - pub fn delete_sheet( - &mut self, - name: Option<&str>, - index: Option, - ) -> Result<(), SpreadsheetArtifactError> { - let remove_index = if let Some(name) = name { - self.sheets - .iter() - .position(|sheet| sheet.name == name) - .ok_or_else(|| SpreadsheetArtifactError::SheetLookup { - action: "delete_sheet".to_string(), - message: format!("sheet `{name}` was not found"), - })? - } else if let Some(index) = index { - if index >= self.sheets.len() { - return Err(SpreadsheetArtifactError::IndexOutOfRange { - action: "delete_sheet".to_string(), - index, - len: self.sheets.len(), - }); - } - index - } else { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: "delete_sheet".to_string(), - message: "sheet name or index is required".to_string(), - }); - }; - self.sheets.remove(remove_index); - Ok(()) - } - - pub fn list_sheet_names(&self) -> Vec { - self.sheets.iter().map(|sheet| sheet.name.clone()).collect() - } - - pub fn summary(&self) -> SpreadsheetSummary { - SpreadsheetSummary { - artifact_id: self.artifact_id.clone(), - sheets: self.sheets.iter().map(SpreadsheetSheet::summary).collect(), - size_bytes: self.to_bytes().len(), - } - } - - pub fn calculate(&mut self) { - recalculate_workbook(self); - } - - pub fn recalculate(&mut self) { - self.calculate(); - } - - pub fn to_dict(&self) -> Result { - serde_json::to_value(self).map_err(|error| SpreadsheetArtifactError::Serialization { - message: error.to_string(), - }) - } - - pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(self).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - }) - } - - pub fn to_bytes(&self) -> Vec { - self.to_json() - .unwrap_or_else(|_| "{}".to_string()) - .into_bytes() - } - - pub fn to_bytes_base64(&self) -> String { - BASE64_STANDARD.encode(self.to_bytes()) - } - - pub fn from_dict( - data: Value, - artifact_id: Option, - ) -> Result { - let mut artifact: Self = serde_json::from_value(data).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - if let Some(artifact_id) = artifact_id { - artifact.artifact_id = artifact_id; - } else if artifact.artifact_id.is_empty() { - artifact.artifact_id = format!("spreadsheet_{}", Uuid::new_v4().simple()); - } - Ok(artifact) - } - - pub fn from_json( - json: impl AsRef<[u8]>, - artifact_id: Option, - ) -> Result { - let text = std::str::from_utf8(json.as_ref()).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - Self::from_dict( - serde_json::from_str(text).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?, - artifact_id, - ) - } - - pub fn from_bytes( - bytes: &[u8], - artifact_id: Option, - ) -> Result { - Self::from_json(bytes, artifact_id) - } - - pub fn from_source_file( - path: &Path, - artifact_id: Option, - ) -> Result { - match path - .extension() - .and_then(|value| value.to_str()) - .unwrap_or_default() - .to_ascii_lowercase() - .as_str() - { - "xlsx" => import_xlsx(path, artifact_id), - "json" => { - let bytes = std::fs::read(path).map_err(|error| { - SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - Self::from_json(bytes, artifact_id) - } - "bin" => { - let bytes = std::fs::read(path).map_err(|error| { - SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - Self::from_bytes(&bytes, artifact_id) - } - other => Err(SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: format!("unsupported import file type `{other}`"), - }), - } - } - - pub fn read( - path: &Path, - artifact_id: Option, - ) -> Result { - Self::from_source_file(path, artifact_id) - } - - pub fn load( - path: &Path, - artifact_id: Option, - ) -> Result { - Self::from_source_file(path, artifact_id) - } - - pub fn save( - &mut self, - path: &Path, - file_type: Option<&str>, - ) -> Result { - self.to_source_file(path, file_type) - } - - pub fn export(&mut self, path: &Path) -> Result { - self.to_source_file(path, Some("xlsx")) - } - - pub fn to_source_file( - &mut self, - path: &Path, - file_type: Option<&str>, - ) -> Result { - let selected = file_type - .map(str::to_string) - .or_else(|| { - path.extension() - .and_then(|value| value.to_str()) - .map(str::to_string) - }) - .unwrap_or_else(|| "xlsx".to_string()) - .to_ascii_lowercase(); - - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - } - - match selected.as_str() { - "xlsx" => { - for sheet in &self.sheets { - if !sheet.charts.is_empty() - || !sheet.tables.is_empty() - || !sheet.conditional_formats.is_empty() - || !sheet.pivot_tables.is_empty() - { - return Err(SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: format!( - "xlsx export does not yet support charts, tables, conditional formats, or pivot tables on sheet `{}`; use json or bin export instead", - sheet.name - ), - }); - } - } - write_xlsx(self, path) - } - "json" => { - let json = self.to_json()?; - std::fs::write(path, json).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - Ok(path.to_path_buf()) - } - "bin" => { - std::fs::write(path, self.to_bytes()).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - Ok(path.to_path_buf()) - } - other => Err(SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: format!("unsupported export file type `{other}`"), - }), - } - } -} diff --git a/codex-rs/artifact-spreadsheet/src/pivot.rs b/codex-rs/artifact-spreadsheet/src/pivot.rs deleted file mode 100644 index c0c42985c9..0000000000 --- a/codex-rs/artifact-spreadsheet/src/pivot.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::collections::BTreeMap; - -use serde::Deserialize; -use serde::Serialize; - -use crate::CellRange; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetCellRangeRef; -use crate::SpreadsheetSheet; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotFieldItem { - pub item_type: Option, - pub index: Option, - pub hidden: bool, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotField { - pub index: u32, - pub name: Option, - pub axis: Option, - #[serde(default)] - pub items: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotFieldReference { - pub field_index: u32, - pub field_name: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotPageField { - pub field_index: u32, - pub field_name: Option, - pub selected_item: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotDataField { - pub field_index: u32, - pub field_name: Option, - pub name: Option, - pub subtotal: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotFilter { - pub field_index: Option, - pub field_name: Option, - pub filter_type: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotTable { - pub name: String, - pub cache_id: u32, - pub address: Option, - #[serde(default)] - pub row_fields: Vec, - #[serde(default)] - pub column_fields: Vec, - #[serde(default)] - pub page_fields: Vec, - #[serde(default)] - pub data_fields: Vec, - #[serde(default)] - pub filters: Vec, - #[serde(default)] - pub pivot_fields: Vec, - pub style_name: Option, - pub part_path: Option, -} - -#[derive(Debug, Clone, Default)] -pub struct SpreadsheetPivotTableLookup<'a> { - pub name: Option<&'a str>, - pub index: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetPivotCacheDefinition { - pub definition_path: String, - #[serde(default)] - pub field_names: Vec>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct SpreadsheetPivotPreservation { - #[serde(default)] - pub caches: BTreeMap, - #[serde(default)] - pub parts: BTreeMap, -} - -impl SpreadsheetPivotTable { - pub fn range(&self) -> Result, SpreadsheetArtifactError> { - self.address.as_deref().map(CellRange::parse).transpose() - } - - pub fn range_ref( - &self, - sheet_name: &str, - ) -> Result, SpreadsheetArtifactError> { - Ok(self - .range()? - .map(|range| SpreadsheetCellRangeRef::new(sheet_name.to_string(), &range))) - } -} - -impl SpreadsheetSheet { - pub fn list_pivot_tables( - &self, - range: Option<&CellRange>, - ) -> Result, SpreadsheetArtifactError> { - Ok(self - .pivot_tables - .iter() - .filter(|pivot_table| { - range.is_none_or(|target| { - pivot_table - .range() - .ok() - .flatten() - .is_some_and(|pivot_range| pivot_range.intersects(target)) - }) - }) - .cloned() - .collect()) - } - - pub fn get_pivot_table( - &self, - action: &str, - lookup: SpreadsheetPivotTableLookup, - ) -> Result<&SpreadsheetPivotTable, SpreadsheetArtifactError> { - if let Some(name) = lookup.name { - return self - .pivot_tables - .iter() - .find(|pivot_table| pivot_table.name == name) - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("pivot table `{name}` was not found"), - }); - } - if let Some(index) = lookup.index { - return self.pivot_tables.get(index).ok_or_else(|| { - SpreadsheetArtifactError::IndexOutOfRange { - action: action.to_string(), - index, - len: self.pivot_tables.len(), - } - }); - } - Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "pivot table name or index is required".to_string(), - }) - } - - pub fn validate_pivot_tables(&self, action: &str) -> Result<(), SpreadsheetArtifactError> { - for pivot_table in &self.pivot_tables { - if pivot_table.name.trim().is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "pivot table name cannot be empty".to_string(), - }); - } - if let Some(address) = &pivot_table.address { - CellRange::parse(address)?; - } - } - Ok(()) - } -} diff --git a/codex-rs/artifact-spreadsheet/src/render.rs b/codex-rs/artifact-spreadsheet/src/render.rs deleted file mode 100644 index 05e41b6083..0000000000 --- a/codex-rs/artifact-spreadsheet/src/render.rs +++ /dev/null @@ -1,373 +0,0 @@ -use std::fs; -use std::path::Path; -use std::path::PathBuf; - -use serde::Deserialize; -use serde::Serialize; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifact; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetSheet; - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetRenderOptions { - pub output_path: Option, - pub center_address: Option, - pub width: Option, - pub height: Option, - pub include_headers: bool, - pub scale: f64, - pub performance_mode: bool, -} - -impl Default for SpreadsheetRenderOptions { - fn default() -> Self { - Self { - output_path: None, - center_address: None, - width: None, - height: None, - include_headers: true, - scale: 1.0, - performance_mode: false, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SpreadsheetRenderedOutput { - pub path: PathBuf, - pub html: String, -} - -impl SpreadsheetSheet { - pub fn render_html( - &self, - range: Option<&CellRange>, - options: &SpreadsheetRenderOptions, - ) -> Result { - let center = options - .center_address - .as_deref() - .map(CellAddress::parse) - .transpose()?; - let viewport = render_viewport(self, range, center, options)?; - let title = range - .map(CellRange::to_a1) - .unwrap_or_else(|| self.name.clone()); - Ok(format!( - concat!( - "", - "{}", - "", - "", - "
", - "

{}

{}

", - "
", - "{}
", - "
" - ), - html_escape(&title), - preview_css(), - html_escape(&self.name), - options.performance_mode, - html_escape(&title), - html_escape(&viewport.to_a1()), - viewport_style(options), - render_table(self, &viewport, options), - )) - } -} - -impl SpreadsheetArtifact { - pub fn render_workbook_previews( - &self, - cwd: &Path, - options: &SpreadsheetRenderOptions, - ) -> Result, SpreadsheetArtifactError> { - let sheets = if self.sheets.is_empty() { - vec![SpreadsheetSheet::new("Sheet1".to_string())] - } else { - self.sheets.clone() - }; - let output_paths = workbook_output_paths(self, cwd, options, &sheets); - sheets - .iter() - .zip(output_paths) - .map(|(sheet, path)| { - let html = sheet.render_html(None, options)?; - write_rendered_output(&path, &html)?; - Ok(SpreadsheetRenderedOutput { path, html }) - }) - .collect() - } - - pub fn render_sheet_preview( - &self, - cwd: &Path, - sheet: &SpreadsheetSheet, - options: &SpreadsheetRenderOptions, - ) -> Result { - let path = single_output_path( - cwd, - self, - options.output_path.as_deref(), - &format!("render_{}", sanitize_file_component(&sheet.name)), - ); - let html = sheet.render_html(None, options)?; - write_rendered_output(&path, &html)?; - Ok(SpreadsheetRenderedOutput { path, html }) - } - - pub fn render_range_preview( - &self, - cwd: &Path, - sheet: &SpreadsheetSheet, - range: &CellRange, - options: &SpreadsheetRenderOptions, - ) -> Result { - let path = single_output_path( - cwd, - self, - options.output_path.as_deref(), - &format!( - "render_{}_{}", - sanitize_file_component(&sheet.name), - sanitize_file_component(&range.to_a1()) - ), - ); - let html = sheet.render_html(Some(range), options)?; - write_rendered_output(&path, &html)?; - Ok(SpreadsheetRenderedOutput { path, html }) - } -} - -fn render_viewport( - sheet: &SpreadsheetSheet, - range: Option<&CellRange>, - center: Option, - options: &SpreadsheetRenderOptions, -) -> Result { - let base = range - .cloned() - .or_else(|| sheet.minimum_range()) - .unwrap_or_else(|| { - CellRange::from_start_end( - CellAddress { column: 1, row: 1 }, - CellAddress { column: 1, row: 1 }, - ) - }); - let Some(center) = center else { - return Ok(base); - }; - let visible_columns = options - .width - .map(|width| estimated_visible_count(width, 96.0, options.scale)) - .unwrap_or(base.width() as u32); - let visible_rows = options - .height - .map(|height| estimated_visible_count(height, 28.0, options.scale)) - .unwrap_or(base.height() as u32); - - let half_columns = visible_columns / 2; - let half_rows = visible_rows / 2; - let start_column = center - .column - .saturating_sub(half_columns) - .max(base.start.column); - let start_row = center.row.saturating_sub(half_rows).max(base.start.row); - let end_column = (start_column + visible_columns.saturating_sub(1)).min(base.end.column); - let end_row = (start_row + visible_rows.saturating_sub(1)).min(base.end.row); - Ok(CellRange::from_start_end( - CellAddress { - column: start_column, - row: start_row, - }, - CellAddress { - column: end_column.max(start_column), - row: end_row.max(start_row), - }, - )) -} - -fn estimated_visible_count(dimension: u32, cell_size: f64, scale: f64) -> u32 { - ((dimension as f64 / (cell_size * scale.max(0.1))).floor() as u32).max(1) -} - -fn render_table( - sheet: &SpreadsheetSheet, - range: &CellRange, - options: &SpreadsheetRenderOptions, -) -> String { - let mut rows = Vec::new(); - if options.include_headers { - let mut header = vec!["".to_string()]; - for column in range.start.column..=range.end.column { - header.push(format!( - "{}", - crate::column_index_to_letters(column) - )); - } - header.push("".to_string()); - rows.push(header.join("")); - } - for row in range.start.row..=range.end.row { - let mut cells = Vec::new(); - if options.include_headers { - cells.push(format!("{row}")); - } - for column in range.start.column..=range.end.column { - let address = CellAddress { column, row }; - let view = sheet.get_cell_view(address); - let value = view - .data - .as_ref() - .map(render_data_value) - .unwrap_or_default(); - cells.push(format!( - "{}", - address.to_a1(), - view.style_index, - html_escape(&value) - )); - } - rows.push(format!("{}", cells.join(""))); - } - rows.join("") -} - -fn render_data_value(value: &serde_json::Value) -> String { - match value { - serde_json::Value::String(value) => value.clone(), - serde_json::Value::Bool(value) => value.to_string(), - serde_json::Value::Number(value) => value.to_string(), - serde_json::Value::Null => String::new(), - other => other.to_string(), - } -} - -fn viewport_style(options: &SpreadsheetRenderOptions) -> String { - let mut style = vec![ - format!("--scale: {}", options.scale.max(0.1)), - format!( - "--headers: {}", - if options.include_headers { "1" } else { "0" } - ), - ]; - if let Some(width) = options.width { - style.push(format!("width: {width}px")); - } - if let Some(height) = options.height { - style.push(format!("height: {height}px")); - } - style.push("overflow: auto".to_string()); - style.join("; ") -} - -fn preview_css() -> &'static str { - concat!( - "body{margin:0;padding:24px;background:#f5f3ee;color:#1e1e1e;font-family:Georgia,serif;}", - ".spreadsheet-preview{display:flex;flex-direction:column;gap:16px;}", - "header h1{margin:0;font-size:24px;}header p{margin:0;color:#6b6257;font-size:13px;}", - ".viewport{border:1px solid #d6d0c7;background:#fff;box-shadow:0 12px 30px rgba(0,0,0,.08);}", - "table{border-collapse:collapse;transform:scale(var(--scale));transform-origin:top left;}", - "th,td{border:1px solid #ddd3c6;padding:6px 10px;min-width:72px;max-width:240px;font-size:13px;text-align:left;vertical-align:top;}", - "th{background:#f0ebe3;font-weight:600;position:sticky;top:0;z-index:1;}", - ".corner{background:#e7e0d6;left:0;z-index:2;}", - "td{white-space:pre-wrap;}" - ) -} - -fn write_rendered_output(path: &Path, html: &str) -> Result<(), SpreadsheetArtifactError> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - } - fs::write(path, html).map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - }) -} - -fn workbook_output_paths( - artifact: &SpreadsheetArtifact, - cwd: &Path, - options: &SpreadsheetRenderOptions, - sheets: &[SpreadsheetSheet], -) -> Vec { - if let Some(output_path) = options.output_path.as_deref() { - if output_path.extension().is_some_and(|ext| ext == "html") { - let stem = output_path - .file_stem() - .and_then(|value| value.to_str()) - .unwrap_or("render"); - let parent = output_path.parent().unwrap_or(cwd); - return sheets - .iter() - .map(|sheet| { - parent.join(format!( - "{}_{}.html", - stem, - sanitize_file_component(&sheet.name) - )) - }) - .collect(); - } - return sheets - .iter() - .map(|sheet| output_path.join(format!("{}.html", sanitize_file_component(&sheet.name)))) - .collect(); - } - sheets - .iter() - .map(|sheet| { - cwd.join(format!( - "{}_render_{}.html", - artifact.artifact_id, - sanitize_file_component(&sheet.name) - )) - }) - .collect() -} - -fn single_output_path( - cwd: &Path, - artifact: &SpreadsheetArtifact, - output_path: Option<&Path>, - suffix: &str, -) -> PathBuf { - if let Some(output_path) = output_path { - return if output_path.extension().is_some_and(|ext| ext == "html") { - output_path.to_path_buf() - } else { - output_path.join(format!("{suffix}.html")) - }; - } - cwd.join(format!("{}_{}.html", artifact.artifact_id, suffix)) -} - -fn sanitize_file_component(value: &str) -> String { - value - .chars() - .map(|character| { - if character.is_ascii_alphanumeric() { - character - } else { - '_' - } - }) - .collect() -} - -fn html_escape(value: &str) -> String { - value - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) - .replace('\'', "'") -} diff --git a/codex-rs/artifact-spreadsheet/src/style.rs b/codex-rs/artifact-spreadsheet/src/style.rs deleted file mode 100644 index 0c9a3782a5..0000000000 --- a/codex-rs/artifact-spreadsheet/src/style.rs +++ /dev/null @@ -1,580 +0,0 @@ -use std::collections::BTreeMap; - -use serde::Deserialize; -use serde::Serialize; - -use crate::CellRange; -use crate::SpreadsheetArtifact; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetCellRangeRef; -use crate::SpreadsheetSheet; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct SpreadsheetFontFace { - pub font_family: Option, - pub font_scheme: Option, - pub typeface: Option, -} - -impl SpreadsheetFontFace { - fn merge(&self, patch: &Self) -> Self { - Self { - font_family: patch - .font_family - .clone() - .or_else(|| self.font_family.clone()), - font_scheme: patch - .font_scheme - .clone() - .or_else(|| self.font_scheme.clone()), - typeface: patch.typeface.clone().or_else(|| self.typeface.clone()), - } - } -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] -pub struct SpreadsheetTextStyle { - pub bold: Option, - pub italic: Option, - pub underline: Option, - pub font_size: Option, - pub font_color: Option, - pub text_alignment: Option, - pub anchor: Option, - pub vertical_text_orientation: Option, - pub text_rotation: Option, - pub paragraph_spacing: Option, - pub bottom_inset: Option, - pub left_inset: Option, - pub right_inset: Option, - pub top_inset: Option, - pub font_family: Option, - pub font_scheme: Option, - pub typeface: Option, - pub font_face: Option, -} - -impl SpreadsheetTextStyle { - fn merge(&self, patch: &Self) -> Self { - Self { - bold: patch.bold.or(self.bold), - italic: patch.italic.or(self.italic), - underline: patch.underline.or(self.underline), - font_size: patch.font_size.or(self.font_size), - font_color: patch.font_color.clone().or_else(|| self.font_color.clone()), - text_alignment: patch - .text_alignment - .clone() - .or_else(|| self.text_alignment.clone()), - anchor: patch.anchor.clone().or_else(|| self.anchor.clone()), - vertical_text_orientation: patch - .vertical_text_orientation - .clone() - .or_else(|| self.vertical_text_orientation.clone()), - text_rotation: patch.text_rotation.or(self.text_rotation), - paragraph_spacing: patch.paragraph_spacing.or(self.paragraph_spacing), - bottom_inset: patch.bottom_inset.or(self.bottom_inset), - left_inset: patch.left_inset.or(self.left_inset), - right_inset: patch.right_inset.or(self.right_inset), - top_inset: patch.top_inset.or(self.top_inset), - font_family: patch - .font_family - .clone() - .or_else(|| self.font_family.clone()), - font_scheme: patch - .font_scheme - .clone() - .or_else(|| self.font_scheme.clone()), - typeface: patch.typeface.clone().or_else(|| self.typeface.clone()), - font_face: match (&self.font_face, &patch.font_face) { - (Some(base), Some(update)) => Some(base.merge(update)), - (None, Some(update)) => Some(update.clone()), - (Some(base), None) => Some(base.clone()), - (None, None) => None, - }, - } - } -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetGradientStop { - pub position: f64, - pub color: String, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetFillRectangle { - pub left: f64, - pub right: f64, - pub top: f64, - pub bottom: f64, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] -pub struct SpreadsheetFill { - pub solid_fill_color: Option, - pub pattern_type: Option, - pub pattern_foreground_color: Option, - pub pattern_background_color: Option, - #[serde(default)] - pub color_transforms: Vec, - pub gradient_fill_type: Option, - #[serde(default)] - pub gradient_stops: Vec, - pub gradient_kind: Option, - pub angle: Option, - pub scaled: Option, - pub path_type: Option, - pub fill_rectangle: Option, - pub image_reference: Option, -} - -impl SpreadsheetFill { - fn merge(&self, patch: &Self) -> Self { - Self { - solid_fill_color: patch - .solid_fill_color - .clone() - .or_else(|| self.solid_fill_color.clone()), - pattern_type: patch - .pattern_type - .clone() - .or_else(|| self.pattern_type.clone()), - pattern_foreground_color: patch - .pattern_foreground_color - .clone() - .or_else(|| self.pattern_foreground_color.clone()), - pattern_background_color: patch - .pattern_background_color - .clone() - .or_else(|| self.pattern_background_color.clone()), - color_transforms: if patch.color_transforms.is_empty() { - self.color_transforms.clone() - } else { - patch.color_transforms.clone() - }, - gradient_fill_type: patch - .gradient_fill_type - .clone() - .or_else(|| self.gradient_fill_type.clone()), - gradient_stops: if patch.gradient_stops.is_empty() { - self.gradient_stops.clone() - } else { - patch.gradient_stops.clone() - }, - gradient_kind: patch - .gradient_kind - .clone() - .or_else(|| self.gradient_kind.clone()), - angle: patch.angle.or(self.angle), - scaled: patch.scaled.or(self.scaled), - path_type: patch.path_type.clone().or_else(|| self.path_type.clone()), - fill_rectangle: patch - .fill_rectangle - .clone() - .or_else(|| self.fill_rectangle.clone()), - image_reference: patch - .image_reference - .clone() - .or_else(|| self.image_reference.clone()), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct SpreadsheetBorderLine { - pub style: Option, - pub color: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct SpreadsheetBorder { - pub top: Option, - pub right: Option, - pub bottom: Option, - pub left: Option, -} - -impl SpreadsheetBorder { - fn merge(&self, patch: &Self) -> Self { - Self { - top: patch.top.clone().or_else(|| self.top.clone()), - right: patch.right.clone().or_else(|| self.right.clone()), - bottom: patch.bottom.clone().or_else(|| self.bottom.clone()), - left: patch.left.clone().or_else(|| self.left.clone()), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct SpreadsheetAlignment { - pub horizontal: Option, - pub vertical: Option, -} - -impl SpreadsheetAlignment { - fn merge(&self, patch: &Self) -> Self { - Self { - horizontal: patch.horizontal.clone().or_else(|| self.horizontal.clone()), - vertical: patch.vertical.clone().or_else(|| self.vertical.clone()), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct SpreadsheetNumberFormat { - pub format_id: Option, - pub format_code: Option, -} - -impl SpreadsheetNumberFormat { - fn merge(&self, patch: &Self) -> Self { - Self { - format_id: patch.format_id.or(self.format_id), - format_code: patch - .format_code - .clone() - .or_else(|| self.format_code.clone()), - } - } - - fn normalized(mut self) -> Self { - if self.format_code.is_none() { - self.format_code = self.format_id.and_then(builtin_number_format_code); - } - self - } -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] -pub struct SpreadsheetCellFormat { - pub text_style_id: Option, - pub fill_id: Option, - pub border_id: Option, - pub alignment: Option, - pub number_format_id: Option, - pub wrap_text: Option, - pub base_cell_style_format_id: Option, -} - -impl SpreadsheetCellFormat { - pub fn wrap(mut self) -> Self { - self.wrap_text = Some(true); - self - } - - pub fn unwrap(mut self) -> Self { - self.wrap_text = Some(false); - self - } - - fn merge(&self, patch: &Self) -> Self { - Self { - text_style_id: patch.text_style_id.or(self.text_style_id), - fill_id: patch.fill_id.or(self.fill_id), - border_id: patch.border_id.or(self.border_id), - alignment: match (&self.alignment, &patch.alignment) { - (Some(base), Some(update)) => Some(base.merge(update)), - (None, Some(update)) => Some(update.clone()), - (Some(base), None) => Some(base.clone()), - (None, None) => None, - }, - number_format_id: patch.number_format_id.or(self.number_format_id), - wrap_text: patch.wrap_text.or(self.wrap_text), - base_cell_style_format_id: patch - .base_cell_style_format_id - .or(self.base_cell_style_format_id), - } - } -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] -pub struct SpreadsheetDifferentialFormat { - pub text_style_id: Option, - pub fill_id: Option, - pub border_id: Option, - pub alignment: Option, - pub number_format_id: Option, - pub wrap_text: Option, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetCellFormatSummary { - pub style_index: u32, - pub text_style: Option, - pub fill: Option, - pub border: Option, - pub alignment: Option, - pub number_format: Option, - pub wrap_text: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetRangeFormat { - pub sheet_name: String, - pub range: String, -} - -impl SpreadsheetRangeFormat { - pub fn new(sheet_name: String, range: &CellRange) -> Self { - Self { - sheet_name, - range: range.to_a1(), - } - } - - pub fn range_ref(&self) -> Result { - let range = CellRange::parse(&self.range)?; - Ok(SpreadsheetCellRangeRef::new( - self.sheet_name.clone(), - &range, - )) - } - - pub fn top_left_style_index( - &self, - sheet: &SpreadsheetSheet, - ) -> Result { - self.range_ref()?.top_left_style_index(sheet) - } - - pub fn top_left_cell_format( - &self, - artifact: &SpreadsheetArtifact, - sheet: &SpreadsheetSheet, - ) -> Result, SpreadsheetArtifactError> { - let range = self.range_ref()?.range()?; - Ok(artifact.cell_format_summary(sheet.top_left_style_index(&range))) - } -} - -impl SpreadsheetArtifact { - pub fn create_text_style( - &mut self, - style: SpreadsheetTextStyle, - source_style_id: Option, - merge_with_existing_components: bool, - ) -> Result { - let created = if let Some(source_style_id) = source_style_id { - let source = self - .text_styles - .get(&source_style_id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: "create_text_style".to_string(), - message: format!("text style `{source_style_id}` was not found"), - })?; - if merge_with_existing_components { - source.merge(&style) - } else { - style - } - } else { - style - }; - Ok(insert_with_next_id(&mut self.text_styles, created)) - } - - pub fn get_text_style(&self, style_id: u32) -> Option<&SpreadsheetTextStyle> { - self.text_styles.get(&style_id) - } - - pub fn create_fill( - &mut self, - fill: SpreadsheetFill, - source_fill_id: Option, - merge_with_existing_components: bool, - ) -> Result { - let created = if let Some(source_fill_id) = source_fill_id { - let source = self.fills.get(&source_fill_id).cloned().ok_or_else(|| { - SpreadsheetArtifactError::InvalidArgs { - action: "create_fill".to_string(), - message: format!("fill `{source_fill_id}` was not found"), - } - })?; - if merge_with_existing_components { - source.merge(&fill) - } else { - fill - } - } else { - fill - }; - Ok(insert_with_next_id(&mut self.fills, created)) - } - - pub fn get_fill(&self, fill_id: u32) -> Option<&SpreadsheetFill> { - self.fills.get(&fill_id) - } - - pub fn create_border( - &mut self, - border: SpreadsheetBorder, - source_border_id: Option, - merge_with_existing_components: bool, - ) -> Result { - let created = if let Some(source_border_id) = source_border_id { - let source = self - .borders - .get(&source_border_id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: "create_border".to_string(), - message: format!("border `{source_border_id}` was not found"), - })?; - if merge_with_existing_components { - source.merge(&border) - } else { - border - } - } else { - border - }; - Ok(insert_with_next_id(&mut self.borders, created)) - } - - pub fn get_border(&self, border_id: u32) -> Option<&SpreadsheetBorder> { - self.borders.get(&border_id) - } - - pub fn create_number_format( - &mut self, - format: SpreadsheetNumberFormat, - source_number_format_id: Option, - merge_with_existing_components: bool, - ) -> Result { - let created = if let Some(source_number_format_id) = source_number_format_id { - let source = self - .number_formats - .get(&source_number_format_id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: "create_number_format".to_string(), - message: format!("number format `{source_number_format_id}` was not found"), - })?; - if merge_with_existing_components { - source.merge(&format) - } else { - format - } - } else { - format - }; - Ok(insert_with_next_id( - &mut self.number_formats, - created.normalized(), - )) - } - - pub fn get_number_format(&self, number_format_id: u32) -> Option<&SpreadsheetNumberFormat> { - self.number_formats.get(&number_format_id) - } - - pub fn create_cell_format( - &mut self, - format: SpreadsheetCellFormat, - source_format_id: Option, - merge_with_existing_components: bool, - ) -> Result { - let created = if let Some(source_format_id) = source_format_id { - let source = self - .cell_formats - .get(&source_format_id) - .cloned() - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: "create_cell_format".to_string(), - message: format!("cell format `{source_format_id}` was not found"), - })?; - if merge_with_existing_components { - source.merge(&format) - } else { - format - } - } else { - format - }; - Ok(insert_with_next_id(&mut self.cell_formats, created)) - } - - pub fn get_cell_format(&self, format_id: u32) -> Option<&SpreadsheetCellFormat> { - self.cell_formats.get(&format_id) - } - - pub fn create_differential_format(&mut self, format: SpreadsheetDifferentialFormat) -> u32 { - insert_with_next_id(&mut self.differential_formats, format) - } - - pub fn get_differential_format( - &self, - format_id: u32, - ) -> Option<&SpreadsheetDifferentialFormat> { - self.differential_formats.get(&format_id) - } - - pub fn resolve_cell_format(&self, style_index: u32) -> Option { - let format = self.cell_formats.get(&style_index)?.clone(); - resolve_cell_format_recursive(&self.cell_formats, &format, 0) - } - - pub fn cell_format_summary(&self, style_index: u32) -> Option { - let resolved = self.resolve_cell_format(style_index)?; - Some(SpreadsheetCellFormatSummary { - style_index, - text_style: resolved - .text_style_id - .and_then(|id| self.text_styles.get(&id).cloned()), - fill: resolved.fill_id.and_then(|id| self.fills.get(&id).cloned()), - border: resolved - .border_id - .and_then(|id| self.borders.get(&id).cloned()), - alignment: resolved.alignment, - number_format: resolved - .number_format_id - .and_then(|id| self.number_formats.get(&id).cloned()), - wrap_text: resolved.wrap_text, - }) - } -} - -impl SpreadsheetSheet { - pub fn range_format(&self, range: &CellRange) -> SpreadsheetRangeFormat { - SpreadsheetRangeFormat::new(self.name.clone(), range) - } -} - -fn insert_with_next_id(map: &mut BTreeMap, value: T) -> u32 { - let next_id = map.last_key_value().map(|(key, _)| key + 1).unwrap_or(1); - map.insert(next_id, value); - next_id -} - -fn resolve_cell_format_recursive( - cell_formats: &BTreeMap, - format: &SpreadsheetCellFormat, - depth: usize, -) -> Option { - if depth > 32 { - return None; - } - let base = format - .base_cell_style_format_id - .and_then(|id| cell_formats.get(&id)) - .and_then(|base| resolve_cell_format_recursive(cell_formats, base, depth + 1)); - Some(match base { - Some(base) => base.merge(format), - None => format.clone(), - }) -} - -fn builtin_number_format_code(format_id: u32) -> Option { - match format_id { - 0 => Some("General".to_string()), - 1 => Some("0".to_string()), - 2 => Some("0.00".to_string()), - 3 => Some("#,##0".to_string()), - 4 => Some("#,##0.00".to_string()), - 9 => Some("0%".to_string()), - 10 => Some("0.00%".to_string()), - _ => None, - } -} diff --git a/codex-rs/artifact-spreadsheet/src/table.rs b/codex-rs/artifact-spreadsheet/src/table.rs deleted file mode 100644 index be04c188e2..0000000000 --- a/codex-rs/artifact-spreadsheet/src/table.rs +++ /dev/null @@ -1,630 +0,0 @@ -use std::collections::BTreeMap; -use std::collections::BTreeSet; - -use serde::Deserialize; -use serde::Serialize; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetCellValue; -use crate::SpreadsheetSheet; - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetTableColumn { - pub id: u32, - pub name: String, - pub totals_row_label: Option, - pub totals_row_function: Option, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetTable { - pub id: u32, - pub name: String, - pub display_name: String, - pub range: String, - pub header_row_count: u32, - pub totals_row_count: u32, - pub style_name: Option, - pub show_first_column: bool, - pub show_last_column: bool, - pub show_row_stripes: bool, - pub show_column_stripes: bool, - #[serde(default)] - pub columns: Vec, - #[serde(default)] - pub filters: BTreeMap, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SpreadsheetTableView { - pub id: u32, - pub name: String, - pub display_name: String, - pub address: String, - pub full_range: String, - pub header_row_count: u32, - pub totals_row_count: u32, - pub totals_row_visible: bool, - pub header_row_range: Option, - pub data_body_range: Option, - pub totals_row_range: Option, - pub style_name: Option, - pub show_first_column: bool, - pub show_last_column: bool, - pub show_row_stripes: bool, - pub show_column_stripes: bool, - pub columns: Vec, -} - -#[derive(Debug, Clone, Default)] -pub struct SpreadsheetTableLookup<'a> { - pub name: Option<&'a str>, - pub display_name: Option<&'a str>, - pub id: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetCreateTableOptions { - pub name: Option, - pub display_name: Option, - pub header_row_count: u32, - pub totals_row_count: u32, - pub style_name: Option, - pub show_first_column: bool, - pub show_last_column: bool, - pub show_row_stripes: bool, - pub show_column_stripes: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpreadsheetTableStyleOptions { - pub style_name: Option, - pub show_first_column: Option, - pub show_last_column: Option, - pub show_row_stripes: Option, - pub show_column_stripes: Option, -} - -impl SpreadsheetTable { - pub fn range(&self) -> Result { - CellRange::parse(&self.range) - } - - pub fn address(&self) -> String { - self.range.clone() - } - - pub fn full_range(&self) -> String { - self.range.clone() - } - - pub fn totals_row_visible(&self) -> bool { - self.totals_row_count > 0 - } - - pub fn header_row_range(&self) -> Result, SpreadsheetArtifactError> { - if self.header_row_count == 0 { - return Ok(None); - } - let range = self.range()?; - Ok(Some(CellRange::from_start_end( - range.start, - CellAddress { - column: range.end.column, - row: range.start.row + self.header_row_count - 1, - }, - ))) - } - - pub fn data_body_range(&self) -> Result, SpreadsheetArtifactError> { - let range = self.range()?; - let start_row = range.start.row + self.header_row_count; - let end_row = range.end.row.saturating_sub(self.totals_row_count); - if start_row > end_row { - return Ok(None); - } - Ok(Some(CellRange::from_start_end( - CellAddress { - column: range.start.column, - row: start_row, - }, - CellAddress { - column: range.end.column, - row: end_row, - }, - ))) - } - - pub fn totals_row_range(&self) -> Result, SpreadsheetArtifactError> { - if self.totals_row_count == 0 { - return Ok(None); - } - let range = self.range()?; - Ok(Some(CellRange::from_start_end( - CellAddress { - column: range.start.column, - row: range.end.row - self.totals_row_count + 1, - }, - range.end, - ))) - } - - pub fn view(&self) -> Result { - Ok(SpreadsheetTableView { - id: self.id, - name: self.name.clone(), - display_name: self.display_name.clone(), - address: self.address(), - full_range: self.full_range(), - header_row_count: self.header_row_count, - totals_row_count: self.totals_row_count, - totals_row_visible: self.totals_row_visible(), - header_row_range: self.header_row_range()?.map(|range| range.to_a1()), - data_body_range: self.data_body_range()?.map(|range| range.to_a1()), - totals_row_range: self.totals_row_range()?.map(|range| range.to_a1()), - style_name: self.style_name.clone(), - show_first_column: self.show_first_column, - show_last_column: self.show_last_column, - show_row_stripes: self.show_row_stripes, - show_column_stripes: self.show_column_stripes, - columns: self.columns.clone(), - }) - } -} - -impl SpreadsheetSheet { - pub fn create_table( - &mut self, - action: &str, - range: &CellRange, - options: SpreadsheetCreateTableOptions, - ) -> Result { - validate_table_geometry( - action, - range, - options.header_row_count, - options.totals_row_count, - )?; - for table in &self.tables { - let table_range = table.range()?; - if table_range.intersects(range) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!( - "table range `{}` intersects existing table `{}`", - range.to_a1(), - table.name - ), - }); - } - } - - let next_id = self.tables.iter().map(|table| table.id).max().unwrap_or(0) + 1; - let name = options.name.unwrap_or_else(|| format!("Table{next_id}")); - if name.trim().is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "table name cannot be empty".to_string(), - }); - } - let display_name = options.display_name.unwrap_or_else(|| name.clone()); - if display_name.trim().is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "table display_name cannot be empty".to_string(), - }); - } - ensure_unique_table_name(&self.tables, action, &name, &display_name, None)?; - - let columns = build_table_columns(self, range, options.header_row_count); - self.tables.push(SpreadsheetTable { - id: next_id, - name, - display_name, - range: range.to_a1(), - header_row_count: options.header_row_count, - totals_row_count: options.totals_row_count, - style_name: options.style_name, - show_first_column: options.show_first_column, - show_last_column: options.show_last_column, - show_row_stripes: options.show_row_stripes, - show_column_stripes: options.show_column_stripes, - columns, - filters: BTreeMap::new(), - }); - Ok(next_id) - } - - pub fn list_tables( - &self, - range: Option<&CellRange>, - ) -> Result, SpreadsheetArtifactError> { - self.tables - .iter() - .filter(|table| { - range.is_none_or(|target| { - table - .range() - .map(|table_range| table_range.intersects(target)) - .unwrap_or(false) - }) - }) - .map(SpreadsheetTable::view) - .collect() - } - - pub fn get_table( - &self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result<&SpreadsheetTable, SpreadsheetArtifactError> { - self.table_lookup_internal(action, lookup) - } - - pub fn get_table_view( - &self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result { - self.get_table(action, lookup)?.view() - } - - pub fn delete_table( - &mut self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result<(), SpreadsheetArtifactError> { - let index = self.table_index(action, lookup)?; - self.tables.remove(index); - Ok(()) - } - - pub fn set_table_style( - &mut self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - options: SpreadsheetTableStyleOptions, - ) -> Result<(), SpreadsheetArtifactError> { - let table = self.table_lookup_mut(action, lookup)?; - table.style_name = options.style_name; - if let Some(value) = options.show_first_column { - table.show_first_column = value; - } - if let Some(value) = options.show_last_column { - table.show_last_column = value; - } - if let Some(value) = options.show_row_stripes { - table.show_row_stripes = value; - } - if let Some(value) = options.show_column_stripes { - table.show_column_stripes = value; - } - Ok(()) - } - - pub fn clear_table_filters( - &mut self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result<(), SpreadsheetArtifactError> { - self.table_lookup_mut(action, lookup)?.filters.clear(); - Ok(()) - } - - pub fn reapply_table_filters( - &mut self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result<(), SpreadsheetArtifactError> { - let _ = self.table_lookup_mut(action, lookup)?; - Ok(()) - } - - pub fn rename_table_column( - &mut self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - column_id: Option, - column_name: Option<&str>, - new_name: String, - ) -> Result { - if new_name.trim().is_empty() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "table column name cannot be empty".to_string(), - }); - } - let table = self.table_lookup_mut(action, lookup)?; - if table - .columns - .iter() - .any(|column| column.name == new_name && Some(column.id) != column_id) - { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("table column `{new_name}` already exists"), - }); - } - let column = table_column_lookup_mut(&mut table.columns, action, column_id, column_name)?; - column.name = new_name; - Ok(column.clone()) - } - - pub fn set_table_column_totals( - &mut self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - column_id: Option, - column_name: Option<&str>, - totals_row_label: Option, - totals_row_function: Option, - ) -> Result { - let table = self.table_lookup_mut(action, lookup)?; - let column = table_column_lookup_mut(&mut table.columns, action, column_id, column_name)?; - column.totals_row_label = totals_row_label; - column.totals_row_function = totals_row_function; - Ok(column.clone()) - } - - pub fn validate_tables(&self, action: &str) -> Result<(), SpreadsheetArtifactError> { - let mut seen_names = BTreeSet::new(); - let mut seen_display_names = BTreeSet::new(); - for table in &self.tables { - let range = table.range()?; - validate_table_geometry( - action, - &range, - table.header_row_count, - table.totals_row_count, - )?; - if !seen_names.insert(table.name.clone()) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("duplicate table name `{}`", table.name), - }); - } - if !seen_display_names.insert(table.display_name.clone()) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("duplicate table display_name `{}`", table.display_name), - }); - } - let column_names = table - .columns - .iter() - .map(|column| column.name.clone()) - .collect::>(); - if column_names.len() != table.columns.len() { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("table `{}` has duplicate column names", table.name), - }); - } - } - - for index in 0..self.tables.len() { - for other in index + 1..self.tables.len() { - if self.tables[index] - .range()? - .intersects(&self.tables[other].range()?) - { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!( - "table `{}` intersects table `{}`", - self.tables[index].name, self.tables[other].name - ), - }); - } - } - } - Ok(()) - } - - fn table_index( - &self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result { - self.tables - .iter() - .position(|table| table_matches_lookup(table, lookup.clone())) - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: describe_missing_table(lookup), - }) - } - - fn table_lookup_internal( - &self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result<&SpreadsheetTable, SpreadsheetArtifactError> { - self.tables - .iter() - .find(|table| table_matches_lookup(table, lookup.clone())) - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: describe_missing_table(lookup), - }) - } - - fn table_lookup_mut( - &mut self, - action: &str, - lookup: SpreadsheetTableLookup<'_>, - ) -> Result<&mut SpreadsheetTable, SpreadsheetArtifactError> { - let index = self.table_index(action, lookup)?; - Ok(&mut self.tables[index]) - } -} - -fn table_matches_lookup(table: &SpreadsheetTable, lookup: SpreadsheetTableLookup<'_>) -> bool { - if let Some(name) = lookup.name { - table.name == name - } else if let Some(display_name) = lookup.display_name { - table.display_name == display_name - } else if let Some(id) = lookup.id { - table.id == id - } else { - false - } -} - -fn describe_missing_table(lookup: SpreadsheetTableLookup<'_>) -> String { - if let Some(name) = lookup.name { - format!("table name `{name}` was not found") - } else if let Some(display_name) = lookup.display_name { - format!("table display_name `{display_name}` was not found") - } else if let Some(id) = lookup.id { - format!("table id `{id}` was not found") - } else { - "table name, display_name, or id is required".to_string() - } -} - -fn ensure_unique_table_name( - tables: &[SpreadsheetTable], - action: &str, - name: &str, - display_name: &str, - exclude_id: Option, -) -> Result<(), SpreadsheetArtifactError> { - if tables.iter().any(|table| { - Some(table.id) != exclude_id && (table.name == name || table.display_name == name) - }) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("table name `{name}` already exists"), - }); - } - if tables.iter().any(|table| { - Some(table.id) != exclude_id - && (table.display_name == display_name || table.name == display_name) - }) { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: format!("table display_name `{display_name}` already exists"), - }); - } - Ok(()) -} - -fn validate_table_geometry( - action: &str, - range: &CellRange, - header_row_count: u32, - totals_row_count: u32, -) -> Result<(), SpreadsheetArtifactError> { - if range.width() == 0 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "table range must include at least one column".to_string(), - }); - } - if header_row_count + totals_row_count > range.height() as u32 { - return Err(SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: "table range is smaller than header and totals rows".to_string(), - }); - } - Ok(()) -} - -fn build_table_columns( - sheet: &SpreadsheetSheet, - range: &CellRange, - header_row_count: u32, -) -> Vec { - let header_row = range.start.row + header_row_count.saturating_sub(1); - let default_names = (0..range.width()) - .map(|index| format!("Column{}", index + 1)) - .collect::>(); - let names = unique_table_column_names( - (range.start.column..=range.end.column) - .enumerate() - .map(|(index, column)| { - if header_row_count == 0 { - return default_names[index].clone(); - } - sheet - .get_cell(CellAddress { - column, - row: header_row, - }) - .and_then(|cell| cell.value.as_ref()) - .map(cell_value_to_table_header) - .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| default_names[index].clone()) - }) - .collect::>(), - ); - names - .into_iter() - .enumerate() - .map(|(index, name)| SpreadsheetTableColumn { - id: index as u32 + 1, - name, - totals_row_label: None, - totals_row_function: None, - }) - .collect() -} - -fn unique_table_column_names(names: Vec) -> Vec { - let mut seen = BTreeMap::::new(); - names - .into_iter() - .map(|name| { - let entry = seen.entry(name.clone()).or_insert(0); - *entry += 1; - if *entry == 1 { - name - } else { - format!("{name}_{}", *entry) - } - }) - .collect() -} - -fn cell_value_to_table_header(value: &SpreadsheetCellValue) -> String { - match value { - SpreadsheetCellValue::Bool(value) => value.to_string(), - SpreadsheetCellValue::Integer(value) => value.to_string(), - SpreadsheetCellValue::Float(value) => value.to_string(), - SpreadsheetCellValue::String(value) - | SpreadsheetCellValue::DateTime(value) - | SpreadsheetCellValue::Error(value) => value.clone(), - } -} - -fn table_column_lookup_mut<'a>( - columns: &'a mut [SpreadsheetTableColumn], - action: &str, - column_id: Option, - column_name: Option<&str>, -) -> Result<&'a mut SpreadsheetTableColumn, SpreadsheetArtifactError> { - columns - .iter_mut() - .find(|column| { - if let Some(column_id) = column_id { - column.id == column_id - } else if let Some(column_name) = column_name { - column.name == column_name - } else { - false - } - }) - .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { - action: action.to_string(), - message: if let Some(column_id) = column_id { - format!("table column id `{column_id}` was not found") - } else if let Some(column_name) = column_name { - format!("table column `{column_name}` was not found") - } else { - "table column id or name is required".to_string() - }, - }) -} diff --git a/codex-rs/artifact-spreadsheet/src/tests.rs b/codex-rs/artifact-spreadsheet/src/tests.rs deleted file mode 100644 index 608ac7b392..0000000000 --- a/codex-rs/artifact-spreadsheet/src/tests.rs +++ /dev/null @@ -1,1228 +0,0 @@ -use std::collections::BTreeMap; - -use pretty_assertions::assert_eq; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifact; -use crate::SpreadsheetArtifactManager; -use crate::SpreadsheetArtifactRequest; -use crate::SpreadsheetCell; -use crate::SpreadsheetCellFormat; -use crate::SpreadsheetCellFormatSummary; -use crate::SpreadsheetCellValue; -use crate::SpreadsheetFileType; -use crate::SpreadsheetFill; -use crate::SpreadsheetFontFace; -use crate::SpreadsheetNumberFormat; -use crate::SpreadsheetRenderOptions; -use crate::SpreadsheetSheet; -use crate::SpreadsheetSheetReference; -use crate::SpreadsheetTextStyle; - -#[test] -fn manager_can_create_edit_recalculate_and_export() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = SpreadsheetArtifactManager::default(); - - let created = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Budget" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_sheet".to_string(), - args: serde_json::json!({ "name": "Sheet1" }), - }, - temp_dir.path(), - )?; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_range_values".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "range": "A1:B2", - "values": [[1, 2], [3, 4]] - }), - }, - temp_dir.path(), - )?; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_cell_formula".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "address": "C1", - "formula": "=SUM(A1:B2)", - "recalculate": true - }), - }, - temp_dir.path(), - )?; - - let cell = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_cell".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "address": "C1" - }), - }, - temp_dir.path(), - )?; - assert_eq!( - cell.cell.and_then(|entry| entry.value), - Some(SpreadsheetCellValue::Integer(10)) - ); - - let export_path = temp_dir.path().join("budget.xlsx"); - let export = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id), - action: "export_xlsx".to_string(), - args: serde_json::json!({ "path": export_path }), - }, - temp_dir.path(), - )?; - assert_eq!(export.exported_paths.len(), 1); - assert!(export.exported_paths[0].exists()); - Ok(()) -} - -#[test] -fn spreadsheet_serialization_roundtrip_preserves_cells() -> Result<(), Box> { - let mut artifact = SpreadsheetArtifact::new(Some("Roundtrip".to_string())); - let sheet = artifact.create_sheet("Sheet1".to_string())?; - sheet.set_value( - crate::CellAddress::parse("A1")?, - Some(SpreadsheetCellValue::String("hello".to_string())), - )?; - sheet.set_formula(crate::CellAddress::parse("B1")?, Some("=A1".to_string()))?; - artifact.recalculate(); - - let json = artifact.to_json()?; - let restored = SpreadsheetArtifact::from_json(json, None)?; - let restored_sheet = restored.get_sheet(Some("Sheet1"), None).expect("sheet"); - let cell = restored_sheet.get_cell_view(crate::CellAddress::parse("A1")?); - assert_eq!( - cell.value, - Some(SpreadsheetCellValue::String("hello".to_string())) - ); - Ok(()) -} - -#[test] -fn xlsx_roundtrip_preserves_merged_ranges_and_style_indices() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let path = temp_dir.path().join("styled.xlsx"); - - let mut artifact = SpreadsheetArtifact::new(Some("Styled".to_string())); - let sheet = artifact.create_sheet("Sheet1".to_string())?; - sheet.set_value( - crate::CellAddress::parse("A1")?, - Some(SpreadsheetCellValue::Integer(42)), - )?; - sheet.set_style_index(&crate::CellRange::parse("A1:B1")?, 3)?; - sheet.merge_cells(&crate::CellRange::parse("A1:B1")?, true)?; - artifact.export(&path)?; - - let restored = SpreadsheetArtifact::from_source_file(&path, None)?; - let restored_sheet = restored.get_sheet(Some("Sheet1"), None).expect("sheet"); - assert_eq!(restored_sheet.merged_ranges.len(), 1); - assert_eq!( - restored_sheet - .get_cell_view(crate::CellAddress::parse("A1")?) - .style_index, - 3 - ); - Ok(()) -} - -#[test] -fn path_accesses_cover_import_and_export() -> Result<(), Box> { - let cwd = tempfile::tempdir()?; - let request = crate::SpreadsheetArtifactRequest { - artifact_id: Some("spreadsheet_1".to_string()), - action: "export_xlsx".to_string(), - args: serde_json::json!({ "path": "out/report.xlsx" }), - }; - let accesses = request.required_path_accesses(cwd.path())?; - assert_eq!(accesses.len(), 1); - assert!(accesses[0].path.ends_with("out/report.xlsx")); - Ok(()) -} - -#[test] -fn render_options_write_deterministic_html_previews() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut artifact = SpreadsheetArtifact::new(Some("Preview".to_string())); - artifact.create_sheet("Sheet 1".to_string())?; - { - let sheet = artifact - .get_sheet_mut(Some("Sheet 1"), None) - .expect("sheet"); - sheet.set_value( - CellAddress::parse("A1")?, - Some(SpreadsheetCellValue::String("Name".to_string())), - )?; - sheet.set_value( - CellAddress::parse("B1")?, - Some(SpreadsheetCellValue::String("Value".to_string())), - )?; - sheet.set_value( - CellAddress::parse("A2")?, - Some(SpreadsheetCellValue::String("Alpha".to_string())), - )?; - sheet.set_value( - CellAddress::parse("B2")?, - Some(SpreadsheetCellValue::Integer(42)), - )?; - } - - let rendered = artifact.render_range_preview( - temp_dir.path(), - artifact.get_sheet(Some("Sheet 1"), None).expect("sheet"), - &CellRange::parse("A1:B2")?, - &SpreadsheetRenderOptions { - output_path: Some(temp_dir.path().join("range-preview.html")), - width: Some(320), - height: Some(200), - include_headers: true, - scale: 1.25, - performance_mode: true, - ..Default::default() - }, - )?; - assert!(rendered.path.exists()); - assert_eq!(std::fs::read_to_string(&rendered.path)?, rendered.html); - assert!(rendered.html.contains("")); - assert!(rendered.html.contains("data-performance-mode=\"true\"")); - assert!(rendered.html.contains( - "style=\"--scale: 1.25; --headers: 1; width: 320px; height: 200px; overflow: auto\"" - )); - assert!(rendered.html.contains("A")); - assert!(rendered.html.contains("data-address=\"B2\"")); - assert!(rendered.html.contains(">42")); - - let workbook = artifact.render_workbook_previews( - temp_dir.path(), - &SpreadsheetRenderOptions { - output_path: Some(temp_dir.path().join("workbook")), - include_headers: false, - ..Default::default() - }, - )?; - assert_eq!(workbook.len(), 1); - assert!(workbook[0].path.ends_with("Sheet_1.html")); - assert!(!workbook[0].html.contains("A")); - Ok(()) -} - -#[test] -fn sheet_refs_support_handle_and_field_apis() -> Result<(), Box> { - let mut artifact = SpreadsheetArtifact::new(Some("Handles".to_string())); - let (range_ref, cell_ref) = { - let sheet = artifact.create_sheet("Sheet1".to_string())?; - let range_ref = sheet.range_ref("A1:B2")?; - range_ref.set_value(sheet, Some(SpreadsheetCellValue::Integer(7)))?; - let cell_ref = sheet.cell_ref("B2")?; - cell_ref.set_formula(sheet, Some("=SUM(A1:B2)".to_string()))?; - (range_ref, cell_ref) - }; - artifact.recalculate(); - let sheet = artifact.get_sheet(Some("Sheet1"), None).expect("sheet"); - - let values = range_ref.get_values(sheet)?; - assert_eq!(values[0][0], Some(SpreadsheetCellValue::Integer(7))); - assert_eq!( - cell_ref.get(sheet)?.value, - Some(SpreadsheetCellValue::Integer(28)) - ); - assert_eq!( - sheet.get_cell_field_by_indices(2, 2, "formula")?, - Some(serde_json::Value::String("=SUM(A1:B2)".to_string())) - ); - assert_eq!( - sheet.minimum_range_ref().map(|entry| entry.address), - Some("A1:B2".to_string()) - ); - assert!(matches!( - sheet.to_dict()?, - serde_json::Value::Object(_) | serde_json::Value::Array(_) - )); - Ok(()) -} - -#[test] -fn manager_supports_single_value_formula_and_cite_cell_actions() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = SpreadsheetArtifactManager::default(); - let created = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Actions" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_sheet".to_string(), - args: serde_json::json!({ "name": "Sheet1" }), - }, - temp_dir.path(), - )?; - - let uniform = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_range_value".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "range": "A1:B2", - "value": 5 - }), - }, - temp_dir.path(), - )?; - assert_eq!( - uniform - .range_ref - .as_ref() - .map(|entry| entry.address.clone()), - Some("A1:B2".to_string()) - ); - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_range_formula".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "range": "C1:C2", - "formula": "=SUM(A1:B2)", - "recalculate": true - }), - }, - temp_dir.path(), - )?; - - let cited = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "cite_cell".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "address": "C1", - "tether_id": "source-1", - "start_line": 3, - "end_line": 8 - }), - }, - temp_dir.path(), - )?; - assert_eq!( - cited.cell.as_ref().map(|entry| entry.citations.len()), - Some(1) - ); - - let by_indices = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_cell_by_indices".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "column_index": 3, - "row_index": 1 - }), - }, - temp_dir.path(), - )?; - assert_eq!( - by_indices - .cell - .as_ref() - .and_then(|entry| entry.value.clone()), - Some(SpreadsheetCellValue::Integer(20)) - ); - - let field = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id), - action: "get_cell_field".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "address": "C1", - "field": "formula" - }), - }, - temp_dir.path(), - )?; - assert_eq!( - field.cell_field, - Some(serde_json::Value::String("=SUM(A1:B2)".to_string())) - ); - Ok(()) -} - -#[test] -fn artifact_file_type_helpers_and_source_files_work() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut artifact = SpreadsheetArtifact::new(Some("Files".to_string())); - artifact.artifact_id = "spreadsheet_fixed".to_string(); - artifact.create_sheet("Sheet1".to_string())?.set_value( - CellAddress::parse("A1")?, - Some(SpreadsheetCellValue::String("hello".to_string())), - )?; - - assert_eq!( - SpreadsheetArtifact::allowed_file_extensions(), - &["xlsx", "json", "bin"] - ); - assert_eq!( - SpreadsheetArtifact::allowed_file_mime_types(), - &[ - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "application/json", - "application/octet-stream", - ] - ); - assert_eq!( - SpreadsheetArtifact::allowed_file_types().to_vec(), - vec![ - SpreadsheetFileType::Xlsx, - SpreadsheetFileType::Json, - SpreadsheetFileType::Binary, - ] - ); - assert_eq!( - artifact.get_output_file_name(Some("preview"), SpreadsheetFileType::Json), - "spreadsheet_fixed_preview.json".to_string() - ); - - let json_path = temp_dir - .path() - .join(artifact.get_output_file_name(None, SpreadsheetFileType::Json)); - artifact.save(&json_path, Some("json"))?; - let restored_json = SpreadsheetArtifact::load(&json_path, None)?; - assert_eq!(restored_json.to_dict()?, artifact.to_dict()?); - - let bytes_path = temp_dir - .path() - .join(artifact.get_output_file_name(Some("bytes"), SpreadsheetFileType::Binary)); - artifact.save(&bytes_path, Some("bin"))?; - let restored_bytes = SpreadsheetArtifact::read(&bytes_path, None)?; - assert_eq!(restored_bytes.to_dict()?, artifact.to_dict()?); - Ok(()) -} - -#[test] -fn sheet_cleanup_and_row_sizing_helpers_work() -> Result<(), Box> { - let mut sheet = SpreadsheetSheet::new("Sheet1".to_string()); - sheet.default_row_height = Some(15.0); - sheet.set_column_widths_bulk(&BTreeMap::from([ - ("A".to_string(), 12.0), - ("C:D".to_string(), 20.0), - ]))?; - sheet.set_row_height(2, Some(18.0))?; - sheet.set_row_heights(3, 4, Some(22.0))?; - sheet.set_row_heights_bulk(&BTreeMap::from([(4, None), (5, Some(30.0))]))?; - - assert_eq!(sheet.get_column_width("A")?, Some(12.0)); - assert_eq!(sheet.get_column_width("B")?, None); - assert_eq!(sheet.get_column_width("D")?, Some(20.0)); - assert_eq!(sheet.get_row_height(2), Some(18.0)); - assert_eq!(sheet.get_row_height(3), Some(22.0)); - assert_eq!(sheet.get_row_height(4), Some(15.0)); - assert_eq!(sheet.get_row_height(5), Some(30.0)); - - sheet.cells.insert( - CellAddress::parse("A1")?, - SpreadsheetCell { - value: None, - formula: None, - style_index: 0, - citations: Vec::new(), - }, - ); - let merged = CellRange::parse("B2:C3")?; - sheet.merged_ranges = vec![merged.clone(), merged.clone()]; - sheet.cleanup_and_validate_sheet()?; - - assert_eq!(sheet.cells, BTreeMap::new()); - assert_eq!(sheet.merged_ranges, vec![merged]); - Ok(()) -} - -#[test] -fn xlsx_roundtrip_preserves_row_and_column_sizes() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let path = temp_dir.path().join("sizing.xlsx"); - - let mut artifact = SpreadsheetArtifact::new(Some("Sizing".to_string())); - let (expected_column_widths, expected_row_heights, expected_show_grid_lines) = { - let sheet = artifact.create_sheet("Sheet1".to_string())?; - sheet.show_grid_lines = false; - sheet.set_value( - CellAddress::parse("A1")?, - Some(SpreadsheetCellValue::Integer(42)), - )?; - sheet.set_column_widths_bulk(&BTreeMap::from([ - ("A:B".to_string(), 12.5), - ("D".to_string(), 18.0), - ]))?; - sheet.set_row_heights_bulk(&BTreeMap::from([(2, Some(24.0)), (6, Some(19.5))]))?; - ( - sheet.column_widths.clone(), - sheet.row_heights.clone(), - sheet.show_grid_lines, - ) - }; - artifact.export(&path)?; - - let restored = SpreadsheetArtifact::from_source_file(&path, None)?; - let restored_sheet = restored.get_sheet(Some("Sheet1"), None).expect("sheet"); - assert_eq!(restored_sheet.column_widths, expected_column_widths); - assert_eq!(restored_sheet.row_heights, expected_row_heights); - assert_eq!(restored_sheet.show_grid_lines, expected_show_grid_lines); - Ok(()) -} - -#[test] -fn manager_supports_bulk_sizes_and_row_heights() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = SpreadsheetArtifactManager::default(); - let created = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Sizing" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_sheet".to_string(), - args: serde_json::json!({ "name": "Sheet1" }), - }, - temp_dir.path(), - )?; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_column_widths_bulk".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "widths": { - "A:B": 12.0, - "D": 20.0 - } - }), - }, - temp_dir.path(), - )?; - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_row_height".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "row_index": 2, - "height": 18.0 - }), - }, - temp_dir.path(), - )?; - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_row_heights".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "start_row_index": 3, - "end_row_index": 4, - "height": 21.0 - }), - }, - temp_dir.path(), - )?; - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_row_heights_bulk".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "heights": { - "4": null, - "5": 25.0 - } - }), - }, - temp_dir.path(), - )?; - - let row_height = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_row_height".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "row_index": 5 - }), - }, - temp_dir.path(), - )?; - assert_eq!(row_height.row_height, Some(25.0)); - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "cleanup_and_validate_sheet".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1" - }), - }, - temp_dir.path(), - )?; - - let sheet = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id), - action: "get_sheet".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1" - }), - }, - temp_dir.path(), - )?; - let restored: SpreadsheetSheet = - serde_json::from_value(sheet.serialized_dict.expect("sheet dict"))?; - assert_eq!( - restored.column_widths, - BTreeMap::from([(1, 12.0), (2, 12.0), (4, 20.0)]) - ); - assert_eq!( - restored.row_heights, - BTreeMap::from([(2, 18.0), (3, 21.0), (5, 25.0)]) - ); - Ok(()) -} - -#[test] -fn manager_style_registry_and_format_summaries_work() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = SpreadsheetArtifactManager::default(); - let created = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Styles" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_sheet".to_string(), - args: serde_json::json!({ "name": "Sheet1" }), - }, - temp_dir.path(), - )?; - - let text_style = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_text_style".to_string(), - args: serde_json::json!({ - "style": { - "bold": true, - "italic": true, - "underline": true, - "font_size": 14.0, - "font_color": "#112233", - "text_alignment": "center", - "anchor": "middle", - "vertical_text_orientation": "stacked", - "text_rotation": 90, - "paragraph_spacing": true, - "bottom_inset": 1.0, - "left_inset": 2.0, - "right_inset": 3.0, - "top_inset": 4.0, - "font_family": "IBM Plex Sans", - "font_scheme": "minor", - "typeface": "IBM Plex Sans", - "font_face": { - "font_family": "IBM Plex Sans", - "font_scheme": "minor", - "typeface": "IBM Plex Sans" - } - } - }), - }, - temp_dir.path(), - )?; - let text_style_id = text_style.style_id.expect("text style id"); - - let fill = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_fill".to_string(), - args: serde_json::json!({ - "fill": { - "solid_fill_color": "#ffeeaa", - "pattern_type": "solid", - "pattern_foreground_color": "#ffeeaa", - "pattern_background_color": "#221100", - "color_transforms": ["tint:0.2"], - "gradient_fill_type": "linear", - "gradient_stops": [ - { "position": 0.0, "color": "#ffeeaa" }, - { "position": 1.0, "color": "#aa5500" } - ], - "gradient_kind": "linear", - "angle": 45.0, - "scaled": true, - "path_type": "rect", - "fill_rectangle": { - "left": 0.0, - "right": 1.0, - "top": 0.0, - "bottom": 1.0 - }, - "image_reference": "image://fill" - } - }), - }, - temp_dir.path(), - )?; - let fill_id = fill.style_id.expect("fill id"); - - let border = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_border".to_string(), - args: serde_json::json!({ - "border": { - "top": { "style": "solid", "color": "#111111" }, - "right": { "style": "dashed", "color": "#222222" }, - "bottom": { "style": "double", "color": "#333333" }, - "left": { "style": "solid", "color": "#444444" } - } - }), - }, - temp_dir.path(), - )?; - let border_id = border.style_id.expect("border id"); - - let number_format = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_number_format".to_string(), - args: serde_json::json!({ - "number_format": { - "format_id": 4 - } - }), - }, - temp_dir.path(), - )?; - let number_format_id = number_format.style_id.expect("number format id"); - - let base_format = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_cell_format".to_string(), - args: serde_json::json!({ - "format": { - "text_style_id": text_style_id, - "number_format_id": number_format_id, - "alignment": { - "horizontal": "center", - "vertical": "middle" - } - } - }), - }, - temp_dir.path(), - )?; - let base_format_id = base_format.style_id.expect("base format id"); - - let derived_format = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_cell_format".to_string(), - args: serde_json::json!({ - "format": { - "fill_id": fill_id, - "border_id": border_id, - "wrap_text": true, - "base_cell_style_format_id": base_format_id - } - }), - }, - temp_dir.path(), - )?; - let derived_format_id = derived_format.style_id.expect("derived format id"); - - let merged_format = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_cell_format".to_string(), - args: serde_json::json!({ - "source_format_id": derived_format_id, - "merge_with_existing_components": true, - "format": { - "alignment": { - "vertical": "bottom" - } - } - }), - }, - temp_dir.path(), - )?; - let merged_format_id = merged_format.style_id.expect("merged format id"); - - let differential_format = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_differential_format".to_string(), - args: serde_json::json!({ - "format": { - "fill_id": fill_id, - "wrap_text": true - } - }), - }, - temp_dir.path(), - )?; - let differential_format_id = differential_format.style_id.expect("dxf id"); - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_cell_style".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "address": "A1", - "style_index": merged_format_id - }), - }, - temp_dir.path(), - )?; - - let summary = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_cell_format_summary".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "address": "A1" - }), - }, - temp_dir.path(), - )?; - assert_eq!( - summary.cell_format_summary, - Some(SpreadsheetCellFormatSummary { - style_index: merged_format_id, - text_style: Some(SpreadsheetTextStyle { - bold: Some(true), - italic: Some(true), - underline: Some(true), - font_size: Some(14.0), - font_color: Some("#112233".to_string()), - text_alignment: Some("center".to_string()), - anchor: Some("middle".to_string()), - vertical_text_orientation: Some("stacked".to_string()), - text_rotation: Some(90), - paragraph_spacing: Some(true), - bottom_inset: Some(1.0), - left_inset: Some(2.0), - right_inset: Some(3.0), - top_inset: Some(4.0), - font_family: Some("IBM Plex Sans".to_string()), - font_scheme: Some("minor".to_string()), - typeface: Some("IBM Plex Sans".to_string()), - font_face: Some(SpreadsheetFontFace { - font_family: Some("IBM Plex Sans".to_string()), - font_scheme: Some("minor".to_string()), - typeface: Some("IBM Plex Sans".to_string()), - }), - }), - fill: Some(SpreadsheetFill { - solid_fill_color: Some("#ffeeaa".to_string()), - pattern_type: Some("solid".to_string()), - pattern_foreground_color: Some("#ffeeaa".to_string()), - pattern_background_color: Some("#221100".to_string()), - color_transforms: vec!["tint:0.2".to_string()], - gradient_fill_type: Some("linear".to_string()), - gradient_stops: vec![ - crate::SpreadsheetGradientStop { - position: 0.0, - color: "#ffeeaa".to_string(), - }, - crate::SpreadsheetGradientStop { - position: 1.0, - color: "#aa5500".to_string(), - }, - ], - gradient_kind: Some("linear".to_string()), - angle: Some(45.0), - scaled: Some(true), - path_type: Some("rect".to_string()), - fill_rectangle: Some(crate::SpreadsheetFillRectangle { - left: 0.0, - right: 1.0, - top: 0.0, - bottom: 1.0, - }), - image_reference: Some("image://fill".to_string()), - }), - border: Some(crate::SpreadsheetBorder { - top: Some(crate::SpreadsheetBorderLine { - style: Some("solid".to_string()), - color: Some("#111111".to_string()), - }), - right: Some(crate::SpreadsheetBorderLine { - style: Some("dashed".to_string()), - color: Some("#222222".to_string()), - }), - bottom: Some(crate::SpreadsheetBorderLine { - style: Some("double".to_string()), - color: Some("#333333".to_string()), - }), - left: Some(crate::SpreadsheetBorderLine { - style: Some("solid".to_string()), - color: Some("#444444".to_string()), - }), - }), - alignment: Some(crate::SpreadsheetAlignment { - horizontal: Some("center".to_string()), - vertical: Some("bottom".to_string()), - }), - number_format: Some(SpreadsheetNumberFormat { - format_id: Some(4), - format_code: Some("#,##0.00".to_string()), - }), - wrap_text: Some(true), - }) - ); - - let retrieved_format = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_cell_format".to_string(), - args: serde_json::json!({ "id": merged_format_id }), - }, - temp_dir.path(), - )?; - let retrieved_format: SpreadsheetCellFormat = - serde_json::from_value(retrieved_format.serialized_dict.expect("cell format"))?; - assert_eq!( - retrieved_format, - SpreadsheetCellFormat { - text_style_id: None, - fill_id: Some(fill_id), - border_id: Some(border_id), - alignment: Some(crate::SpreadsheetAlignment { - horizontal: None, - vertical: Some("bottom".to_string()), - }), - number_format_id: None, - wrap_text: Some(true), - base_cell_style_format_id: Some(base_format_id), - } - ); - - let retrieved_number_format = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_number_format".to_string(), - args: serde_json::json!({ "id": number_format_id }), - }, - temp_dir.path(), - )?; - assert_eq!( - serde_json::from_value::( - retrieved_number_format - .serialized_dict - .expect("number format") - )?, - SpreadsheetNumberFormat { - format_id: Some(4), - format_code: Some("#,##0.00".to_string()), - } - ); - - let retrieved_text_style = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_text_style".to_string(), - args: serde_json::json!({ "id": text_style_id }), - }, - temp_dir.path(), - )?; - assert_eq!( - serde_json::from_value::( - retrieved_text_style.serialized_dict.expect("text style") - )? - .bold, - Some(true) - ); - - let range_summary = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_range_format_summary".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "range": "A1:B2" - }), - }, - temp_dir.path(), - )?; - assert_eq!(range_summary.top_left_style_index, Some(merged_format_id)); - assert_eq!( - range_summary - .range_format - .as_ref() - .map(|format| format.range.clone()), - Some("A1:B2".to_string()) - ); - - let retrieved_dxf = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id), - action: "get_differential_format".to_string(), - args: serde_json::json!({ "id": differential_format_id }), - }, - temp_dir.path(), - )?; - assert_eq!( - serde_json::from_value::( - retrieved_dxf.serialized_dict.expect("differential format") - )? - .wrap_text, - Some(true) - ); - Ok(()) -} - -#[test] -fn sheet_references_resolve_cells_and_ranges() -> Result<(), Box> { - let sheet = SpreadsheetSheet::new("Sheet1".to_string()); - assert_eq!( - sheet.reference("A1")?, - SpreadsheetSheetReference::Cell { - cell_ref: sheet.cell_ref("A1")?, - } - ); - assert_eq!( - sheet.reference("A1:B2")?, - SpreadsheetSheetReference::Range { - range_ref: sheet.range_ref("A1:B2")?, - } - ); - Ok(()) -} - -#[test] -fn manager_get_reference_and_xlsx_import_preserve_workbook_name() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let path = temp_dir.path().join("named.xlsx"); - - let mut artifact = SpreadsheetArtifact::new(Some("Named Workbook".to_string())); - artifact.create_sheet("Sheet1".to_string())?.set_value( - CellAddress::parse("A1")?, - Some(SpreadsheetCellValue::Integer(9)), - )?; - artifact.export(&path)?; - - let restored = SpreadsheetArtifact::from_source_file(&path, None)?; - assert_eq!(restored.name, Some("Named Workbook".to_string())); - - let mut manager = SpreadsheetArtifactManager::default(); - let imported = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: None, - action: "read".to_string(), - args: serde_json::json!({ "path": path }), - }, - temp_dir.path(), - )?; - let artifact_id = imported.artifact_id; - - let cell_reference = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "get_reference".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "reference": "A1" - }), - }, - temp_dir.path(), - )?; - assert_eq!( - cell_reference - .raw_cell - .as_ref() - .and_then(|cell| cell.value.clone()), - Some(SpreadsheetCellValue::Integer(9)) - ); - - let range_reference = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id), - action: "get_reference".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "reference": "A1:B2" - }), - }, - temp_dir.path(), - )?; - assert_eq!( - range_reference - .range_ref - .as_ref() - .map(|range_ref| range_ref.address.clone()), - Some("A1:B2".to_string()) - ); - Ok(()) -} - -#[test] -fn manager_render_actions_support_workbook_sheet_and_range() --> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let mut manager = SpreadsheetArtifactManager::default(); - let created = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: None, - action: "create".to_string(), - args: serde_json::json!({ "name": "Render" }), - }, - temp_dir.path(), - )?; - let artifact_id = created.artifact_id; - - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "create_sheet".to_string(), - args: serde_json::json!({ "name": "Sheet1" }), - }, - temp_dir.path(), - )?; - manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "set_range_values".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "range": "A1:C4", - "values": [ - ["h1", "h2", "h3"], - ["a", 1, 2], - ["b", 3, 4], - ["c", 5, 6] - ] - }), - }, - temp_dir.path(), - )?; - - let workbook = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "render_workbook".to_string(), - args: serde_json::json!({ - "output_path": temp_dir.path().join("workbook-previews"), - "include_headers": false - }), - }, - temp_dir.path(), - )?; - assert_eq!(workbook.exported_paths.len(), 1); - assert!(workbook.exported_paths[0].exists()); - - let sheet = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id.clone()), - action: "render_sheet".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "output_path": temp_dir.path().join("sheet-preview.html"), - "center_address": "B3", - "width": 220, - "height": 90, - "scale": 1.5, - "performance_mode": true - }), - }, - temp_dir.path(), - )?; - assert_eq!(sheet.exported_paths.len(), 1); - assert!(sheet.exported_paths[0].exists()); - assert!( - sheet - .rendered_html - .as_ref() - .is_some_and(|html| html.contains("data-performance-mode=\"true\"")) - ); - - let range = manager.execute( - SpreadsheetArtifactRequest { - artifact_id: Some(artifact_id), - action: "render_range".to_string(), - args: serde_json::json!({ - "sheet_name": "Sheet1", - "range": "A2:C4", - "output_path": temp_dir.path().join("range-preview.html"), - "include_headers": true - }), - }, - temp_dir.path(), - )?; - assert_eq!(range.exported_paths.len(), 1); - assert_eq!( - range - .range_ref - .as_ref() - .map(|range_ref| range_ref.address.clone()), - Some("A2:C4".to_string()) - ); - assert!( - range - .rendered_html - .as_ref() - .is_some_and(|html| html.contains("A")) - ); - Ok(()) -} diff --git a/codex-rs/artifact-spreadsheet/src/xlsx.rs b/codex-rs/artifact-spreadsheet/src/xlsx.rs deleted file mode 100644 index 5175f3b51e..0000000000 --- a/codex-rs/artifact-spreadsheet/src/xlsx.rs +++ /dev/null @@ -1,860 +0,0 @@ -use std::collections::BTreeMap; -use std::fs::File; -use std::io::Read; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; - -use regex::Regex; -use zip::ZipArchive; -use zip::ZipWriter; -use zip::write::SimpleFileOptions; - -use crate::CellAddress; -use crate::CellRange; -use crate::SpreadsheetArtifact; -use crate::SpreadsheetArtifactError; -use crate::SpreadsheetCell; -use crate::SpreadsheetCellValue; -use crate::SpreadsheetSheet; - -pub(crate) fn write_xlsx( - artifact: &mut SpreadsheetArtifact, - path: &Path, -) -> Result { - if artifact.auto_recalculate { - artifact.recalculate(); - } - for sheet in &mut artifact.sheets { - sheet.cleanup_and_validate_sheet()?; - } - - let file = File::create(path).map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - let mut zip = ZipWriter::new(file); - let options = SimpleFileOptions::default(); - - let sheet_count = artifact.sheets.len().max(1); - zip.start_file("[Content_Types].xml", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.write_all(content_types_xml(sheet_count).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - zip.add_directory("_rels/", options).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - zip.start_file("_rels/.rels", options).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - zip.write_all(root_relationships_xml().as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - zip.add_directory("docProps/", options).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - zip.start_file("docProps/app.xml", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.write_all(app_xml(artifact).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - zip.start_file("docProps/core.xml", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.write_all(core_xml(artifact).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - zip.add_directory("xl/", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.start_file("xl/workbook.xml", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.write_all(workbook_xml(artifact).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - zip.add_directory("xl/_rels/", options).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - zip.start_file("xl/_rels/workbook.xml.rels", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.write_all(workbook_relationships_xml(artifact).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - zip.start_file("xl/styles.xml", options).map_err(|error| { - SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - } - })?; - zip.write_all(styles_xml(artifact).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - zip.add_directory("xl/worksheets/", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - if artifact.sheets.is_empty() { - let empty = SpreadsheetSheet::new("Sheet1".to_string()); - zip.start_file("xl/worksheets/sheet1.xml", options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.write_all(sheet_xml(&empty).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - } else { - for (index, sheet) in artifact.sheets.iter().enumerate() { - zip.start_file(format!("xl/worksheets/sheet{}.xml", index + 1), options) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - zip.write_all(sheet_xml(sheet).as_bytes()) - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - } - } - - zip.finish() - .map_err(|error| SpreadsheetArtifactError::ExportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - Ok(path.to_path_buf()) -} - -pub(crate) fn import_xlsx( - path: &Path, - artifact_id: Option, -) -> Result { - let file = File::open(path).map_err(|error| SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - let mut archive = - ZipArchive::new(file).map_err(|error| SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - - let workbook_xml = read_zip_entry(&mut archive, "xl/workbook.xml", path)?; - let workbook_rels = read_zip_entry(&mut archive, "xl/_rels/workbook.xml.rels", path)?; - let workbook_name = if archive.by_name("docProps/core.xml").is_ok() { - let title = - extract_workbook_title(&read_zip_entry(&mut archive, "docProps/core.xml", path)?); - (!title.trim().is_empty()).then_some(title) - } else { - None - }; - let shared_strings = if archive.by_name("xl/sharedStrings.xml").is_ok() { - Some(parse_shared_strings(&read_zip_entry( - &mut archive, - "xl/sharedStrings.xml", - path, - )?)?) - } else { - None - }; - - let relationships = parse_relationships(&workbook_rels)?; - let sheets = parse_sheet_definitions(&workbook_xml)? - .into_iter() - .map(|(name, relation)| { - let target = relationships.get(&relation).ok_or_else(|| { - SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: format!("missing relationship `{relation}` for sheet `{name}`"), - } - })?; - let normalized = if target.starts_with('/') { - target.trim_start_matches('/').to_string() - } else if target.starts_with("xl/") { - target.clone() - } else { - format!("xl/{target}") - }; - Ok((name, normalized)) - }) - .collect::, SpreadsheetArtifactError>>()?; - - let mut artifact = SpreadsheetArtifact::new(workbook_name.or_else(|| { - path.file_stem() - .and_then(|value| value.to_str()) - .map(str::to_string) - })); - if let Some(artifact_id) = artifact_id { - artifact.artifact_id = artifact_id; - } - artifact.sheets.clear(); - - for (name, target) in sheets { - let xml = read_zip_entry(&mut archive, &target, path)?; - let sheet = parse_sheet(&name, &xml, shared_strings.as_deref())?; - artifact.sheets.push(sheet); - } - - Ok(artifact) -} - -fn read_zip_entry( - archive: &mut ZipArchive, - entry: &str, - path: &Path, -) -> Result { - let mut file = - archive - .by_name(entry) - .map_err(|error| SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - let mut text = String::new(); - file.read_to_string(&mut text) - .map_err(|error| SpreadsheetArtifactError::ImportFailed { - path: path.to_path_buf(), - message: error.to_string(), - })?; - Ok(text) -} - -fn parse_sheet_definitions( - workbook_xml: &str, -) -> Result, SpreadsheetArtifactError> { - let regex = Regex::new(r#"]*)/?>"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - let mut sheets = Vec::new(); - for captures in regex.captures_iter(workbook_xml) { - let Some(attributes) = captures.get(1).map(|value| value.as_str()) else { - continue; - }; - let Some(name) = extract_attribute(attributes, "name") else { - continue; - }; - let relation = extract_attribute(attributes, "r:id") - .or_else(|| extract_attribute(attributes, "id")) - .unwrap_or_default(); - sheets.push((xml_unescape(&name), relation)); - } - Ok(sheets) -} - -fn parse_relationships(xml: &str) -> Result, SpreadsheetArtifactError> { - let regex = Regex::new(r#"]*)/?>"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - Ok(regex - .captures_iter(xml) - .filter_map(|captures| { - let attributes = captures.get(1)?.as_str(); - let id = extract_attribute(attributes, "Id")?; - let target = extract_attribute(attributes, "Target")?; - Some((id, target)) - }) - .collect()) -} - -fn parse_shared_strings(xml: &str) -> Result, SpreadsheetArtifactError> { - let regex = Regex::new(r#"(?s)]*>(.*?)"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - regex - .captures_iter(xml) - .filter_map(|captures| captures.get(1).map(|value| value.as_str())) - .map(all_text_nodes) - .collect() -} - -fn parse_sheet( - name: &str, - xml: &str, - shared_strings: Option<&[String]>, -) -> Result { - let mut sheet = SpreadsheetSheet::new(name.to_string()); - - if let Some(sheet_view) = first_tag_attributes(xml, "sheetView") - && let Some(show_grid_lines) = extract_attribute(&sheet_view, "showGridLines") - { - sheet.show_grid_lines = show_grid_lines != "0"; - } - if let Some(format_pr) = first_tag_attributes(xml, "sheetFormatPr") { - sheet.default_row_height = extract_attribute(&format_pr, "defaultRowHeight") - .and_then(|value| value.parse::().ok()); - sheet.default_column_width = extract_attribute(&format_pr, "defaultColWidth") - .and_then(|value| value.parse::().ok()); - } - - let col_regex = Regex::new(r#"]*)/?>"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - for captures in col_regex.captures_iter(xml) { - let Some(attributes) = captures.get(1).map(|value| value.as_str()) else { - continue; - }; - let Some(min) = - extract_attribute(attributes, "min").and_then(|value| value.parse::().ok()) - else { - continue; - }; - let Some(max) = - extract_attribute(attributes, "max").and_then(|value| value.parse::().ok()) - else { - continue; - }; - let Some(width) = - extract_attribute(attributes, "width").and_then(|value| value.parse::().ok()) - else { - continue; - }; - for column in min..=max { - sheet.column_widths.insert(column, width); - } - } - - let row_regex = Regex::new(r#"(?s)]*)>(.*?)
"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - let cell_regex = Regex::new(r#"(?s)]*)>(.*?)"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - for row_captures in row_regex.captures_iter(xml) { - let row_attributes = row_captures - .get(1) - .map(|value| value.as_str()) - .unwrap_or_default(); - if let Some(row_index) = - extract_attribute(row_attributes, "r").and_then(|value| value.parse::().ok()) - && let Some(height) = - extract_attribute(row_attributes, "ht").and_then(|value| value.parse::().ok()) - && row_index > 0 - && height > 0.0 - { - sheet.row_heights.insert(row_index, height); - } - let Some(row_body) = row_captures.get(2).map(|value| value.as_str()) else { - continue; - }; - for cell_captures in cell_regex.captures_iter(row_body) { - let Some(attributes) = cell_captures.get(1).map(|value| value.as_str()) else { - continue; - }; - let Some(body) = cell_captures.get(2).map(|value| value.as_str()) else { - continue; - }; - let Some(address) = extract_attribute(attributes, "r") else { - continue; - }; - let address = CellAddress::parse(&address)?; - let style_index = extract_attribute(attributes, "s") - .and_then(|value| value.parse::().ok()) - .unwrap_or(0); - let cell_type = extract_attribute(attributes, "t").unwrap_or_default(); - let formula = first_tag_text(body, "f").map(|value| format!("={value}")); - let value = parse_cell_value(body, &cell_type, shared_strings)?; - - let cell = SpreadsheetCell { - value, - formula, - style_index, - citations: Vec::new(), - }; - if !cell.is_empty() { - sheet.cells.insert(address, cell); - } - } - } - - let merge_regex = Regex::new(r#"]*)/?>"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - for captures in merge_regex.captures_iter(xml) { - let Some(attributes) = captures.get(1).map(|value| value.as_str()) else { - continue; - }; - if let Some(reference) = extract_attribute(attributes, "ref") { - sheet.merged_ranges.push(CellRange::parse(&reference)?); - } - } - - Ok(sheet) -} - -fn parse_cell_value( - body: &str, - cell_type: &str, - shared_strings: Option<&[String]>, -) -> Result, SpreadsheetArtifactError> { - let inline_text = first_tag_text(body, "t").map(|value| xml_unescape(&value)); - let raw_value = first_tag_text(body, "v").map(|value| xml_unescape(&value)); - - let parsed = match cell_type { - "inlineStr" => inline_text.map(SpreadsheetCellValue::String), - "s" => raw_value - .and_then(|value| value.parse::().ok()) - .and_then(|index| shared_strings.and_then(|entries| entries.get(index).cloned())) - .map(SpreadsheetCellValue::String), - "b" => raw_value.map(|value| SpreadsheetCellValue::Bool(value == "1")), - "str" => raw_value.map(SpreadsheetCellValue::String), - "e" => raw_value.map(SpreadsheetCellValue::Error), - _ => match raw_value { - Some(value) => { - if let Ok(integer) = value.parse::() { - Some(SpreadsheetCellValue::Integer(integer)) - } else if let Ok(float) = value.parse::() { - Some(SpreadsheetCellValue::Float(float)) - } else { - Some(SpreadsheetCellValue::String(value)) - } - } - None => None, - }, - }; - Ok(parsed) -} - -fn content_types_xml(sheet_count: usize) -> String { - let mut overrides = String::new(); - for index in 1..=sheet_count { - overrides.push_str(&format!( - r#""# - )); - } - format!( - "{}{}{}{}{}{}{}{}{}{}", - r#""#, - r#""#, - r#""#, - r#""#, - r#""#, - r#""#, - r#""#, - r#""#, - overrides, - r#""# - ) -} - -fn root_relationships_xml() -> &'static str { - concat!( - r#""#, - r#""#, - r#""#, - r#""#, - r#""#, - r#""# - ) -} - -fn app_xml(artifact: &SpreadsheetArtifact) -> String { - let title = artifact - .name - .clone() - .unwrap_or_else(|| "Spreadsheet".to_string()); - format!( - concat!( - r#""#, - r#""#, - r#"Codex"#, - r#"0"#, - r#"false"#, - r#"Worksheets{}"#, - r#"{}"#, - r#"OpenAI"#, - r#"{}"#, - r#""# - ), - artifact.sheets.len(), - artifact.sheets.len(), - artifact - .sheets - .iter() - .map(|sheet| format!(r#"{}"#, xml_escape(&sheet.name))) - .collect::>() - .join(""), - xml_escape(&title), - ) -} - -fn core_xml(artifact: &SpreadsheetArtifact) -> String { - let title = artifact - .name - .clone() - .unwrap_or_else(|| artifact.artifact_id.clone()); - format!( - concat!( - r#""#, - r#""#, - r#"{}"#, - r#"Codex"#, - r#"Codex"#, - r#""# - ), - xml_escape(&title), - ) -} - -fn workbook_xml(artifact: &SpreadsheetArtifact) -> String { - let sheets = if artifact.sheets.is_empty() { - r#""#.to_string() - } else { - artifact - .sheets - .iter() - .enumerate() - .map(|(index, sheet)| { - format!( - r#""#, - xml_escape(&sheet.name), - index + 1, - index + 1 - ) - }) - .collect::>() - .join("") - }; - format!( - "{}{}{}{}{}", - r#""#, - r#""#, - r#""#, - sheets, - r#""# - ) -} - -fn workbook_relationships_xml(artifact: &SpreadsheetArtifact) -> String { - let sheet_relationships = if artifact.sheets.is_empty() { - r#""#.to_string() - } else { - artifact - .sheets - .iter() - .enumerate() - .map(|(index, _)| { - format!( - r#""#, - index + 1, - index + 1 - ) - }) - .collect::>() - .join("") - }; - let style_relation_id = artifact.sheets.len().max(1) + 1; - format!( - "{}{}{}{}", - r#""#, - r#""#, - sheet_relationships, - style_relation_id, - r#""# - ) -} - -fn styles_xml(artifact: &SpreadsheetArtifact) -> String { - let max_style_index = artifact - .sheets - .iter() - .flat_map(|sheet| sheet.cells.values().map(|cell| cell.style_index)) - .max() - .unwrap_or(0); - let cell_xfs = (0..=max_style_index) - .map(|_| r#""#) - .collect::>() - .join(""); - format!( - concat!( - r#""#, - r#""#, - r#""#, - r#""#, - r#""#, - r#""#, - r#"{}"#, - r#""#, - r#""# - ), - max_style_index + 1, - cell_xfs, - ) -} - -fn sheet_xml(sheet: &SpreadsheetSheet) -> String { - let mut rows = BTreeMap::>::new(); - for row_index in sheet.row_heights.keys() { - rows.entry(*row_index).or_default(); - } - for (address, cell) in &sheet.cells { - rows.entry(address.row).or_default().push((*address, cell)); - } - - let sheet_data = rows - .into_iter() - .map(|(row_index, mut entries)| { - entries.sort_by_key(|(address, _)| address.column); - let cells = entries - .into_iter() - .map(|(address, cell)| cell_xml(address, cell)) - .collect::>() - .join(""); - let height = sheet - .row_heights - .get(&row_index) - .map(|value| format!(r#" ht="{value}" customHeight="1""#)) - .unwrap_or_default(); - format!(r#"{cells}"#) - }) - .collect::>() - .join(""); - - let cols = if sheet.column_widths.is_empty() { - String::new() - } else { - let mut groups = Vec::new(); - let mut iter = sheet.column_widths.iter().peekable(); - while let Some((&start, &width)) = iter.next() { - let mut end = start; - while let Some((next_column, next_width)) = - iter.peek().map(|(column, width)| (**column, **width)) - { - if next_column == end + 1 && (next_width - width).abs() < f64::EPSILON { - end = next_column; - iter.next(); - } else { - break; - } - } - groups.push(format!( - r#""# - )); - } - format!("{}", groups.join("")) - }; - - let merge_cells = if sheet.merged_ranges.is_empty() { - String::new() - } else { - format!( - r#"{}"#, - sheet.merged_ranges.len(), - sheet - .merged_ranges - .iter() - .map(|range| format!(r#""#, range.to_a1())) - .collect::>() - .join("") - ) - }; - - let default_row_height = sheet.default_row_height.unwrap_or(15.0); - let default_column_width = sheet.default_column_width.unwrap_or(8.43); - let grid_lines = if sheet.show_grid_lines { "1" } else { "0" }; - - format!( - "{}{}{}{}{}{}", - r#""#, - r#""#, - grid_lines, - default_row_height, - default_column_width, - cols, - sheet_data, - merge_cells, - r#""# - ) -} - -fn cell_xml(address: CellAddress, cell: &SpreadsheetCell) -> String { - let style = if cell.style_index == 0 { - String::new() - } else { - format!(r#" s="{}""#, cell.style_index) - }; - - if let Some(formula) = &cell.formula { - let formula = xml_escape(formula.trim_start_matches('=')); - let value_xml = match &cell.value { - Some(SpreadsheetCellValue::Bool(value)) => { - format!( - r#" t="b">{formula}{}"#, - usize::from(*value) - ) - } - Some(SpreadsheetCellValue::Integer(value)) => { - format!(r#">{formula}{value}"#) - } - Some(SpreadsheetCellValue::Float(value)) => { - format!(r#">{formula}{value}"#) - } - Some(SpreadsheetCellValue::String(value)) - | Some(SpreadsheetCellValue::DateTime(value)) => format!( - r#" t="str">{formula}{}"#, - xml_escape(value) - ), - Some(SpreadsheetCellValue::Error(value)) => { - format!(r#" t="e">{formula}{}"#, xml_escape(value)) - } - None => format!(r#">{formula}"#), - }; - return format!(r#" format!( - r#"{}"#, - address.to_a1(), - usize::from(*value) - ), - Some(SpreadsheetCellValue::Integer(value)) => { - format!(r#"{value}"#, address.to_a1()) - } - Some(SpreadsheetCellValue::Float(value)) => { - format!(r#"{value}"#, address.to_a1()) - } - Some(SpreadsheetCellValue::String(value)) | Some(SpreadsheetCellValue::DateTime(value)) => { - format!( - r#"{}"#, - address.to_a1(), - xml_escape(value) - ) - } - Some(SpreadsheetCellValue::Error(value)) => format!( - r#"{}"#, - address.to_a1(), - xml_escape(value) - ), - None => format!(r#""#, address.to_a1()), - } -} - -fn first_tag_attributes(xml: &str, tag: &str) -> Option { - let regex = Regex::new(&format!(r#"<{tag}\b([^>]*)/?>"#)).ok()?; - let captures = regex.captures(xml)?; - captures.get(1).map(|value| value.as_str().to_string()) -} - -fn first_tag_text(xml: &str, tag: &str) -> Option { - let regex = Regex::new(&format!(r#"(?s)<{tag}\b[^>]*>(.*?)"#)).ok()?; - let captures = regex.captures(xml)?; - captures.get(1).map(|value| value.as_str().to_string()) -} - -fn extract_workbook_title(xml: &str) -> String { - let Ok(regex) = - Regex::new(r#"(?s)<(?:[A-Za-z0-9_]+:)?title\b[^>]*>(.*?)"#) - else { - return String::new(); - }; - regex - .captures(xml) - .and_then(|captures| captures.get(1).map(|value| xml_unescape(value.as_str()))) - .unwrap_or_default() -} - -fn all_text_nodes(xml: &str) -> Result { - let regex = Regex::new(r#"(?s)]*>(.*?)
"#).map_err(|error| { - SpreadsheetArtifactError::Serialization { - message: error.to_string(), - } - })?; - Ok(regex - .captures_iter(xml) - .filter_map(|captures| captures.get(1).map(|value| xml_unescape(value.as_str()))) - .collect::>() - .join("")) -} - -fn extract_attribute(attributes: &str, name: &str) -> Option { - let pattern = format!(r#"{name}="([^"]*)""#); - let regex = Regex::new(&pattern).ok()?; - let captures = regex.captures(attributes)?; - captures.get(1).map(|value| xml_unescape(value.as_str())) -} - -fn xml_escape(value: &str) -> String { - value - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) - .replace('\'', "'") -} - -fn xml_unescape(value: &str) -> String { - value - .replace("'", "'") - .replace(""", "\"") - .replace(">", ">") - .replace("<", "<") - .replace("&", "&") -} diff --git a/codex-rs/artifacts/BUILD.bazel b/codex-rs/artifacts/BUILD.bazel new file mode 100644 index 0000000000..300e9b0fc6 --- /dev/null +++ b/codex-rs/artifacts/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "artifacts", + crate_name = "codex_artifacts", +) diff --git a/codex-rs/artifacts/Cargo.toml b/codex-rs/artifacts/Cargo.toml new file mode 100644 index 0000000000..fc2e4190a9 --- /dev/null +++ b/codex-rs/artifacts/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "codex-artifacts" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +codex-package-manager = { workspace = true } +reqwest = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +tempfile = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = ["fs", "io-util", "process", "time"] } +url = { workspace = true } + +[lints] +workspace = true + +[dev-dependencies] +pretty_assertions = { workspace = true } +sha2 = { workspace = true } +tokio = { workspace = true, features = ["fs", "io-util", "macros", "process", "rt", "rt-multi-thread", "time"] } +wiremock = { workspace = true } +zip = { workspace = true } diff --git a/codex-rs/artifacts/src/client.rs b/codex-rs/artifacts/src/client.rs new file mode 100644 index 0000000000..7b2ff56da6 --- /dev/null +++ b/codex-rs/artifacts/src/client.rs @@ -0,0 +1,446 @@ +use crate::ArtifactRuntimeError; +use crate::ArtifactRuntimeManager; +use crate::InstalledArtifactRuntime; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::process::Stdio; +use std::time::Duration; +use tempfile::TempDir; +use thiserror::Error; +use tokio::fs; +use tokio::io::AsyncReadExt; +use tokio::process::Command; +use tokio::time::timeout; + +const DEFAULT_EXECUTION_TIMEOUT: Duration = Duration::from_secs(30); + +#[derive(Clone, Debug)] +pub struct ArtifactsClient { + runtime_source: RuntimeSource, +} + +#[derive(Clone, Debug)] +enum RuntimeSource { + Managed(ArtifactRuntimeManager), + Installed(InstalledArtifactRuntime), +} + +impl ArtifactsClient { + pub fn from_runtime_manager(runtime_manager: ArtifactRuntimeManager) -> Self { + Self { + runtime_source: RuntimeSource::Managed(runtime_manager), + } + } + + pub fn from_installed_runtime(runtime: InstalledArtifactRuntime) -> Self { + Self { + runtime_source: RuntimeSource::Installed(runtime), + } + } + + pub async fn execute_build( + &self, + request: ArtifactBuildRequest, + ) -> Result { + let runtime = self.resolve_runtime().await?; + let staging_dir = TempDir::new().map_err(|source| ArtifactsError::Io { + context: "failed to create build staging directory".to_string(), + source, + })?; + let script_path = staging_dir.path().join("artifact-build.mjs"); + let wrapped_script = build_wrapped_script(&request.source); + fs::write(&script_path, wrapped_script) + .await + .map_err(|source| ArtifactsError::Io { + context: format!("failed to write {}", script_path.display()), + source, + })?; + + let mut command = Command::new(runtime.node_path()); + command + .arg(&script_path) + .current_dir(&request.cwd) + .env("CODEX_ARTIFACT_BUILD_ENTRYPOINT", runtime.build_js_path()) + .env( + "CODEX_ARTIFACT_RENDER_ENTRYPOINT", + runtime.render_cli_path(), + ) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + for (key, value) in &request.env { + command.env(key, value); + } + + run_command( + command, + request.timeout.unwrap_or(DEFAULT_EXECUTION_TIMEOUT), + ) + .await + } + + pub async fn execute_render( + &self, + request: ArtifactRenderCommandRequest, + ) -> Result { + let runtime = self.resolve_runtime().await?; + let mut command = Command::new(runtime.node_path()); + command + .arg(runtime.render_cli_path()) + .args(request.target.to_args()) + .current_dir(&request.cwd) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + for (key, value) in &request.env { + command.env(key, value); + } + + run_command( + command, + request.timeout.unwrap_or(DEFAULT_EXECUTION_TIMEOUT), + ) + .await + } + + async fn resolve_runtime(&self) -> Result { + match &self.runtime_source { + RuntimeSource::Installed(runtime) => Ok(runtime.clone()), + RuntimeSource::Managed(manager) => manager.ensure_installed().await.map_err(Into::into), + } + } +} + +#[derive(Clone, Debug, Default)] +pub struct ArtifactBuildRequest { + pub source: String, + pub cwd: PathBuf, + pub timeout: Option, + pub env: BTreeMap, +} + +#[derive(Clone, Debug)] +pub struct ArtifactRenderCommandRequest { + pub cwd: PathBuf, + pub timeout: Option, + pub env: BTreeMap, + pub target: ArtifactRenderTarget, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ArtifactRenderTarget { + Presentation(PresentationRenderTarget), + Spreadsheet(SpreadsheetRenderTarget), +} + +impl ArtifactRenderTarget { + pub fn to_args(&self) -> Vec { + match self { + Self::Presentation(target) => { + vec![ + "pptx".to_string(), + "render".to_string(), + "--in".to_string(), + target.input_path.display().to_string(), + "--slide".to_string(), + target.slide_number.to_string(), + "--out".to_string(), + target.output_path.display().to_string(), + ] + } + Self::Spreadsheet(target) => { + let mut args = vec![ + "xlsx".to_string(), + "render".to_string(), + "--in".to_string(), + target.input_path.display().to_string(), + "--sheet".to_string(), + target.sheet_name.clone(), + "--out".to_string(), + target.output_path.display().to_string(), + ]; + if let Some(range) = &target.range { + args.push("--range".to_string()); + args.push(range.clone()); + } + args + } + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PresentationRenderTarget { + pub input_path: PathBuf, + pub output_path: PathBuf, + pub slide_number: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SpreadsheetRenderTarget { + pub input_path: PathBuf, + pub output_path: PathBuf, + pub sheet_name: String, + pub range: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ArtifactCommandOutput { + pub exit_code: Option, + pub stdout: String, + pub stderr: String, +} + +impl ArtifactCommandOutput { + pub fn success(&self) -> bool { + self.exit_code == Some(0) + } +} + +#[derive(Debug, Error)] +pub enum ArtifactsError { + #[error(transparent)] + Runtime(#[from] ArtifactRuntimeError), + #[error("{context}")] + Io { + context: String, + #[source] + source: std::io::Error, + }, + #[error("artifact command timed out after {timeout:?}")] + TimedOut { timeout: Duration }, +} + +fn build_wrapped_script(source: &str) -> String { + format!( + concat!( + "import {{ pathToFileURL }} from \"node:url\";\n", + "const artifactTool = await import(pathToFileURL(process.env.CODEX_ARTIFACT_BUILD_ENTRYPOINT).href);\n", + "globalThis.artifactTool = artifactTool;\n", + "globalThis.artifacts = artifactTool;\n", + "globalThis.codexArtifacts = artifactTool;\n", + "for (const [name, value] of Object.entries(artifactTool)) {{\n", + " if (name === \"default\" || Object.prototype.hasOwnProperty.call(globalThis, name)) {{\n", + " continue;\n", + " }}\n", + " globalThis[name] = value;\n", + "}}\n\n", + "{}\n" + ), + source + ) +} + +async fn run_command( + mut command: Command, + execution_timeout: Duration, +) -> Result { + let mut child = command.spawn().map_err(|source| ArtifactsError::Io { + context: "failed to spawn artifact command".to_string(), + source, + })?; + let mut stdout = child.stdout.take().ok_or_else(|| ArtifactsError::Io { + context: "artifact command stdout was not captured".to_string(), + source: std::io::Error::other("missing stdout pipe"), + })?; + let mut stderr = child.stderr.take().ok_or_else(|| ArtifactsError::Io { + context: "artifact command stderr was not captured".to_string(), + source: std::io::Error::other("missing stderr pipe"), + })?; + let stdout_task = tokio::spawn(async move { + let mut bytes = Vec::new(); + stdout.read_to_end(&mut bytes).await.map(|_| bytes) + }); + let stderr_task = tokio::spawn(async move { + let mut bytes = Vec::new(); + stderr.read_to_end(&mut bytes).await.map(|_| bytes) + }); + + let status = match timeout(execution_timeout, child.wait()).await { + Ok(result) => result.map_err(|source| ArtifactsError::Io { + context: "failed while waiting for artifact command".to_string(), + source, + })?, + Err(_) => { + let _ = child.kill().await; + let _ = child.wait().await; + return Err(ArtifactsError::TimedOut { + timeout: execution_timeout, + }); + } + }; + let stdout_bytes = stdout_task + .await + .map_err(|source| ArtifactsError::Io { + context: "failed to join stdout reader".to_string(), + source: std::io::Error::other(source.to_string()), + })? + .map_err(|source| ArtifactsError::Io { + context: "failed to read artifact command stdout".to_string(), + source, + })?; + let stderr_bytes = stderr_task + .await + .map_err(|source| ArtifactsError::Io { + context: "failed to join stderr reader".to_string(), + source: std::io::Error::other(source.to_string()), + })? + .map_err(|source| ArtifactsError::Io { + context: "failed to read artifact command stderr".to_string(), + source, + })?; + + Ok(ArtifactCommandOutput { + exit_code: status.code(), + stdout: String::from_utf8_lossy(&stdout_bytes).into_owned(), + stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + #[cfg(unix)] + use crate::ArtifactRuntimePlatform; + #[cfg(unix)] + use crate::ExtractedRuntimeManifest; + #[cfg(unix)] + use crate::RuntimeEntrypoints; + #[cfg(unix)] + use crate::RuntimePathEntry; + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; + + #[test] + fn wrapped_build_script_exposes_artifact_tool_surface() { + let wrapped = build_wrapped_script("console.log(Object.keys(artifactTool).length);"); + assert!(wrapped.contains("const artifactTool = await import(")); + assert!(wrapped.contains("globalThis.artifactTool = artifactTool;")); + assert!(wrapped.contains("globalThis.artifacts = artifactTool;")); + assert!(wrapped.contains("globalThis.codexArtifacts = artifactTool;")); + assert!(wrapped.contains("Object.entries(artifactTool)")); + assert!(wrapped.contains("globalThis[name] = value;")); + } + + #[test] + fn presentation_render_target_builds_expected_args() { + let args = ArtifactRenderTarget::Presentation(PresentationRenderTarget { + input_path: PathBuf::from("deck.pptx"), + output_path: PathBuf::from("slide.png"), + slide_number: 2, + }) + .to_args(); + + assert_eq!( + args, + vec![ + "pptx", + "render", + "--in", + "deck.pptx", + "--slide", + "2", + "--out", + "slide.png" + ] + ); + } + + #[test] + fn spreadsheet_render_target_builds_expected_args() { + let args = ArtifactRenderTarget::Spreadsheet(SpreadsheetRenderTarget { + input_path: PathBuf::from("book.xlsx"), + output_path: PathBuf::from("sheet.png"), + sheet_name: "Summary".to_string(), + range: Some("A1:C3".to_string()), + }) + .to_args(); + + assert_eq!( + args, + vec![ + "xlsx", + "render", + "--in", + "book.xlsx", + "--sheet", + "Summary", + "--out", + "sheet.png", + "--range", + "A1:C3" + ] + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn execute_build_invokes_runtime_node_with_expected_environment() { + let temp = TempDir::new().unwrap_or_else(|error| panic!("{error}")); + let cwd = temp.path().join("cwd"); + fs::create_dir_all(&cwd) + .await + .unwrap_or_else(|error| panic!("{error}")); + let log_path = temp.path().join("build.log"); + let fake_node = temp.path().join("fake-node.sh"); + let build_entrypoint = temp.path().join("artifact_tool.mjs"); + let render_entrypoint = temp.path().join("render_cli.mjs"); + fs::write( + &fake_node, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$1\" > \"{}\"\nprintf '%s\\n' \"$CODEX_ARTIFACT_BUILD_ENTRYPOINT\" >> \"{}\"\n", + log_path.display(), + log_path.display() + ), + ) + .await + .unwrap_or_else(|error| panic!("{error}")); + std::fs::set_permissions(&fake_node, std::fs::Permissions::from_mode(0o755)) + .unwrap_or_else(|error| panic!("{error}")); + + let runtime = InstalledArtifactRuntime::new( + temp.path().join("runtime"), + "0.1.0".to_string(), + ArtifactRuntimePlatform::LinuxX64, + sample_manifest("0.1.0"), + fake_node.clone(), + build_entrypoint.clone(), + render_entrypoint, + ); + let client = ArtifactsClient::from_installed_runtime(runtime); + + let output = client + .execute_build(ArtifactBuildRequest { + source: "console.log('hello');".to_string(), + cwd: cwd.clone(), + timeout: Some(Duration::from_secs(5)), + env: BTreeMap::new(), + }) + .await + .unwrap_or_else(|error| panic!("{error}")); + + assert!(output.success()); + let logged = fs::read_to_string(&log_path) + .await + .unwrap_or_else(|error| panic!("{error}")); + assert!(logged.contains("artifact-build.mjs")); + assert!(logged.contains(&build_entrypoint.display().to_string())); + } + + #[cfg(unix)] + fn sample_manifest(runtime_version: &str) -> ExtractedRuntimeManifest { + ExtractedRuntimeManifest { + schema_version: 1, + runtime_version: runtime_version.to_string(), + node: RuntimePathEntry { + relative_path: "node/bin/node".to_string(), + }, + entrypoints: RuntimeEntrypoints { + build_js: RuntimePathEntry { + relative_path: "artifact-tool/dist/artifact_tool.mjs".to_string(), + }, + render_cli: RuntimePathEntry { + relative_path: "granola-render/dist/cli.mjs".to_string(), + }, + }, + } + } +} diff --git a/codex-rs/artifacts/src/lib.rs b/codex-rs/artifacts/src/lib.rs new file mode 100644 index 0000000000..f178052177 --- /dev/null +++ b/codex-rs/artifacts/src/lib.rs @@ -0,0 +1,23 @@ +mod client; +mod runtime; + +pub use client::ArtifactBuildRequest; +pub use client::ArtifactCommandOutput; +pub use client::ArtifactRenderCommandRequest; +pub use client::ArtifactRenderTarget; +pub use client::ArtifactsClient; +pub use client::ArtifactsError; +pub use client::PresentationRenderTarget; +pub use client::SpreadsheetRenderTarget; +pub use runtime::ArtifactRuntimeError; +pub use runtime::ArtifactRuntimeManager; +pub use runtime::ArtifactRuntimeManagerConfig; +pub use runtime::ArtifactRuntimePlatform; +pub use runtime::ArtifactRuntimeReleaseLocator; +pub use runtime::DEFAULT_CACHE_ROOT_RELATIVE; +pub use runtime::DEFAULT_RELEASE_TAG_PREFIX; +pub use runtime::ExtractedRuntimeManifest; +pub use runtime::InstalledArtifactRuntime; +pub use runtime::ReleaseManifest; +pub use runtime::RuntimeEntrypoints; +pub use runtime::RuntimePathEntry; diff --git a/codex-rs/artifacts/src/runtime.rs b/codex-rs/artifacts/src/runtime.rs new file mode 100644 index 0000000000..2ed6b6e111 --- /dev/null +++ b/codex-rs/artifacts/src/runtime.rs @@ -0,0 +1,522 @@ +use codex_package_manager::ManagedPackage; +use codex_package_manager::PackageManager; +use codex_package_manager::PackageManagerConfig; +use codex_package_manager::PackageManagerError; +pub use codex_package_manager::PackagePlatform as ArtifactRuntimePlatform; +use codex_package_manager::PackageReleaseArchive; +use reqwest::Client; +use serde::Deserialize; +use serde::Serialize; +use std::collections::BTreeMap; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; +use thiserror::Error; +use url::Url; + +pub const DEFAULT_RELEASE_TAG_PREFIX: &str = "artifact-runtime-v"; +pub const DEFAULT_CACHE_ROOT_RELATIVE: &str = "packages/artifacts"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ArtifactRuntimeReleaseLocator { + base_url: Url, + runtime_version: String, + release_tag_prefix: String, +} + +impl ArtifactRuntimeReleaseLocator { + pub fn new(base_url: Url, runtime_version: impl Into) -> Self { + Self { + base_url, + runtime_version: runtime_version.into(), + release_tag_prefix: DEFAULT_RELEASE_TAG_PREFIX.to_string(), + } + } + + pub fn with_tag_prefix(mut self, release_tag_prefix: impl Into) -> Self { + self.release_tag_prefix = release_tag_prefix.into(); + self + } + + pub fn base_url(&self) -> &Url { + &self.base_url + } + + pub fn runtime_version(&self) -> &str { + &self.runtime_version + } + + pub fn release_tag(&self) -> String { + format!("{}{}", self.release_tag_prefix, self.runtime_version) + } + + pub fn manifest_file_name(&self) -> String { + format!("{}-manifest.json", self.release_tag()) + } + + pub fn manifest_url(&self) -> Result { + self.base_url + .join(&self.manifest_file_name()) + .map_err(PackageManagerError::InvalidBaseUrl) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ArtifactRuntimeManagerConfig { + package_manager: PackageManagerConfig, +} + +impl ArtifactRuntimeManagerConfig { + pub fn new(codex_home: PathBuf, release: ArtifactRuntimeReleaseLocator) -> Self { + Self { + package_manager: PackageManagerConfig::new( + codex_home, + ArtifactRuntimePackage::new(release), + ), + } + } + + pub fn with_cache_root(mut self, cache_root: PathBuf) -> Self { + self.package_manager = self.package_manager.with_cache_root(cache_root); + self + } + + pub fn cache_root(&self) -> PathBuf { + self.package_manager.cache_root() + } + + pub fn release(&self) -> &ArtifactRuntimeReleaseLocator { + &self.package_manager.package().release + } + + pub fn codex_home(&self) -> &Path { + self.package_manager.codex_home() + } +} + +#[derive(Clone, Debug)] +pub struct ArtifactRuntimeManager { + package_manager: PackageManager, + config: ArtifactRuntimeManagerConfig, +} + +impl ArtifactRuntimeManager { + pub fn new(config: ArtifactRuntimeManagerConfig) -> Self { + let package_manager = PackageManager::new(config.package_manager.clone()); + Self { + package_manager, + config, + } + } + + pub fn with_client(config: ArtifactRuntimeManagerConfig, client: Client) -> Self { + let package_manager = PackageManager::with_client(config.package_manager.clone(), client); + Self { + package_manager, + config, + } + } + + pub fn config(&self) -> &ArtifactRuntimeManagerConfig { + &self.config + } + + pub async fn resolve_cached( + &self, + ) -> Result, ArtifactRuntimeError> { + self.package_manager.resolve_cached().await + } + + pub async fn ensure_installed(&self) -> Result { + self.package_manager.ensure_installed().await + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ArtifactRuntimePackage { + release: ArtifactRuntimeReleaseLocator, +} + +impl ArtifactRuntimePackage { + fn new(release: ArtifactRuntimeReleaseLocator) -> Self { + Self { release } + } +} + +impl ManagedPackage for ArtifactRuntimePackage { + type Error = ArtifactRuntimeError; + type Installed = InstalledArtifactRuntime; + type ReleaseManifest = ReleaseManifest; + + fn default_cache_root_relative(&self) -> &str { + DEFAULT_CACHE_ROOT_RELATIVE + } + + fn version(&self) -> &str { + self.release.runtime_version() + } + + fn manifest_url(&self) -> Result { + self.release.manifest_url() + } + + fn archive_url(&self, archive: &PackageReleaseArchive) -> Result { + self.release + .base_url() + .join(&archive.archive) + .map_err(PackageManagerError::InvalidBaseUrl) + } + + fn release_version<'a>(&self, manifest: &'a Self::ReleaseManifest) -> &'a str { + &manifest.runtime_version + } + + fn platform_archive( + &self, + manifest: &Self::ReleaseManifest, + platform: ArtifactRuntimePlatform, + ) -> Result { + manifest + .platforms + .get(platform.as_str()) + .cloned() + .ok_or_else(|| { + PackageManagerError::MissingPlatform(platform.as_str().to_string()).into() + }) + } + + fn install_dir(&self, cache_root: &Path, platform: ArtifactRuntimePlatform) -> PathBuf { + cache_root.join(self.version()).join(platform.as_str()) + } + + fn installed_version<'a>(&self, package: &'a Self::Installed) -> &'a str { + package.runtime_version() + } + + fn load_installed( + &self, + root_dir: PathBuf, + platform: ArtifactRuntimePlatform, + ) -> Result { + InstalledArtifactRuntime::load(root_dir, platform) + } +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct ReleaseManifest { + pub schema_version: u32, + pub runtime_version: String, + pub release_tag: String, + #[serde(default)] + pub node_version: Option, + pub platforms: BTreeMap, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct ExtractedRuntimeManifest { + pub schema_version: u32, + pub runtime_version: String, + pub node: RuntimePathEntry, + pub entrypoints: RuntimeEntrypoints, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct RuntimePathEntry { + pub relative_path: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct RuntimeEntrypoints { + pub build_js: RuntimePathEntry, + pub render_cli: RuntimePathEntry, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstalledArtifactRuntime { + root_dir: PathBuf, + runtime_version: String, + platform: ArtifactRuntimePlatform, + manifest: ExtractedRuntimeManifest, + node_path: PathBuf, + build_js_path: PathBuf, + render_cli_path: PathBuf, +} + +impl InstalledArtifactRuntime { + pub fn new( + root_dir: PathBuf, + runtime_version: String, + platform: ArtifactRuntimePlatform, + manifest: ExtractedRuntimeManifest, + node_path: PathBuf, + build_js_path: PathBuf, + render_cli_path: PathBuf, + ) -> Self { + Self { + root_dir, + runtime_version, + platform, + manifest, + node_path, + build_js_path, + render_cli_path, + } + } + + pub fn load( + root_dir: PathBuf, + platform: ArtifactRuntimePlatform, + ) -> Result { + let manifest_path = root_dir.join("manifest.json"); + let manifest_bytes = + std::fs::read(&manifest_path).map_err(|source| ArtifactRuntimeError::Io { + context: format!("failed to read {}", manifest_path.display()), + source, + })?; + let manifest = serde_json::from_slice::(&manifest_bytes) + .map_err(|source| ArtifactRuntimeError::InvalidManifest { + path: manifest_path, + source, + })?; + let node_path = resolve_relative_runtime_path(&root_dir, &manifest.node.relative_path)?; + let build_js_path = + resolve_relative_runtime_path(&root_dir, &manifest.entrypoints.build_js.relative_path)?; + let render_cli_path = resolve_relative_runtime_path( + &root_dir, + &manifest.entrypoints.render_cli.relative_path, + )?; + + Ok(Self::new( + root_dir, + manifest.runtime_version.clone(), + platform, + manifest, + node_path, + build_js_path, + render_cli_path, + )) + } + + pub fn root_dir(&self) -> &Path { + &self.root_dir + } + + pub fn runtime_version(&self) -> &str { + &self.runtime_version + } + + pub fn platform(&self) -> ArtifactRuntimePlatform { + self.platform + } + + pub fn manifest(&self) -> &ExtractedRuntimeManifest { + &self.manifest + } + + pub fn node_path(&self) -> &Path { + &self.node_path + } + + pub fn build_js_path(&self) -> &Path { + &self.build_js_path + } + + pub fn render_cli_path(&self) -> &Path { + &self.render_cli_path + } +} + +#[derive(Debug, Error)] +pub enum ArtifactRuntimeError { + #[error(transparent)] + PackageManager(#[from] PackageManagerError), + #[error("{context}")] + Io { + context: String, + #[source] + source: std::io::Error, + }, + #[error("invalid manifest at {path}")] + InvalidManifest { + path: PathBuf, + #[source] + source: serde_json::Error, + }, + #[error("runtime path `{0}` is invalid")] + InvalidRuntimePath(String), +} + +fn resolve_relative_runtime_path( + root_dir: &Path, + relative_path: &str, +) -> Result { + let relative = Path::new(relative_path); + if relative.as_os_str().is_empty() || relative.is_absolute() { + return Err(ArtifactRuntimeError::InvalidRuntimePath( + relative_path.to_string(), + )); + } + if relative.components().any(|component| { + matches!( + component, + Component::ParentDir | Component::Prefix(_) | Component::RootDir + ) + }) { + return Err(ArtifactRuntimeError::InvalidRuntimePath( + relative_path.to_string(), + )); + } + Ok(root_dir.join(relative)) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use sha2::Digest; + use sha2::Sha256; + use std::io::Cursor; + use std::io::Write; + use tempfile::TempDir; + use wiremock::Mock; + use wiremock::MockServer; + use wiremock::ResponseTemplate; + use wiremock::matchers::method; + use wiremock::matchers::path; + use zip::ZipWriter; + use zip::write::SimpleFileOptions; + + #[test] + fn release_locator_builds_manifest_url() { + let locator = ArtifactRuntimeReleaseLocator::new( + Url::parse("https://example.test/releases/").unwrap_or_else(|error| panic!("{error}")), + "0.1.0", + ); + let url = locator + .manifest_url() + .unwrap_or_else(|error| panic!("{error}")); + assert_eq!( + url.as_str(), + "https://example.test/releases/artifact-runtime-v0.1.0-manifest.json" + ); + } + + #[tokio::test] + async fn ensure_installed_downloads_and_extracts_zip_runtime() { + let server = MockServer::start().await; + let runtime_version = "0.1.0"; + let platform = + ArtifactRuntimePlatform::detect_current().unwrap_or_else(|error| panic!("{error}")); + let archive_name = format!( + "artifact-runtime-v{runtime_version}-{}.zip", + platform.as_str() + ); + let archive_bytes = build_zip_archive(runtime_version); + let archive_sha = format!("{:x}", Sha256::digest(&archive_bytes)); + let manifest = ReleaseManifest { + schema_version: 1, + runtime_version: runtime_version.to_string(), + release_tag: format!("artifact-runtime-v{runtime_version}"), + node_version: Some("22.0.0".to_string()), + platforms: BTreeMap::from([( + platform.as_str().to_string(), + PackageReleaseArchive { + archive: archive_name.clone(), + sha256: archive_sha, + format: codex_package_manager::ArchiveFormat::Zip, + size_bytes: Some(archive_bytes.len() as u64), + }, + )]), + }; + Mock::given(method("GET")) + .and(path(format!( + "/artifact-runtime-v{runtime_version}-manifest.json" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(&manifest)) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/{archive_name}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(archive_bytes)) + .mount(&server) + .await; + + let codex_home = TempDir::new().unwrap_or_else(|error| panic!("{error}")); + let locator = ArtifactRuntimeReleaseLocator::new( + Url::parse(&format!("{}/", server.uri())).unwrap_or_else(|error| panic!("{error}")), + runtime_version, + ); + let manager = ArtifactRuntimeManager::new(ArtifactRuntimeManagerConfig::new( + codex_home.path().to_path_buf(), + locator, + )); + + let runtime = manager + .ensure_installed() + .await + .unwrap_or_else(|error| panic!("{error}")); + + assert_eq!(runtime.runtime_version(), runtime_version); + assert_eq!(runtime.platform(), platform); + assert!(runtime.node_path().ends_with(Path::new("node/bin/node"))); + assert!( + runtime + .build_js_path() + .ends_with(Path::new("artifact-tool/dist/artifact_tool.mjs")) + ); + assert!( + runtime + .render_cli_path() + .ends_with(Path::new("granola-render/dist/cli.mjs")) + ); + } + + fn build_zip_archive(runtime_version: &str) -> Vec { + let mut bytes = Cursor::new(Vec::new()); + { + let mut zip = ZipWriter::new(&mut bytes); + let options = SimpleFileOptions::default(); + let manifest = serde_json::to_vec(&sample_extracted_manifest(runtime_version)) + .unwrap_or_else(|error| panic!("{error}")); + zip.start_file("artifact-runtime/manifest.json", options) + .unwrap_or_else(|error| panic!("{error}")); + zip.write_all(&manifest) + .unwrap_or_else(|error| panic!("{error}")); + zip.start_file("artifact-runtime/node/bin/node", options) + .unwrap_or_else(|error| panic!("{error}")); + zip.write_all(b"#!/bin/sh\n") + .unwrap_or_else(|error| panic!("{error}")); + zip.start_file( + "artifact-runtime/artifact-tool/dist/artifact_tool.mjs", + options, + ) + .unwrap_or_else(|error| panic!("{error}")); + zip.write_all(b"export const ok = true;\n") + .unwrap_or_else(|error| panic!("{error}")); + zip.start_file("artifact-runtime/granola-render/dist/cli.mjs", options) + .unwrap_or_else(|error| panic!("{error}")); + zip.write_all(b"export const ok = true;\n") + .unwrap_or_else(|error| panic!("{error}")); + zip.finish().unwrap_or_else(|error| panic!("{error}")); + } + bytes.into_inner() + } + + fn sample_extracted_manifest(runtime_version: &str) -> ExtractedRuntimeManifest { + ExtractedRuntimeManifest { + schema_version: 1, + runtime_version: runtime_version.to_string(), + node: RuntimePathEntry { + relative_path: "node/bin/node".to_string(), + }, + entrypoints: RuntimeEntrypoints { + build_js: RuntimePathEntry { + relative_path: "artifact-tool/dist/artifact_tool.mjs".to_string(), + }, + render_cli: RuntimePathEntry { + relative_path: "granola-render/dist/cli.mjs".to_string(), + }, + }, + } + } +} diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index ebb01edc4e..e406586524 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -42,8 +42,7 @@ codex-hooks = { workspace = true } codex-keyring-store = { workspace = true } codex-network-proxy = { workspace = true } codex-otel = { workspace = true } -codex-artifact-presentation = { workspace = true } -codex-artifact-spreadsheet = { workspace = true } +codex-artifacts = { workspace = true } codex-protocol = { workspace = true } codex-rmcp-client = { workspace = true } codex-state = { workspace = true } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 1e1d96d4a1..5ba2d7f634 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -55,12 +55,6 @@ use async_channel::Receiver; use async_channel::Sender; use chrono::Local; use chrono::Utc; -use codex_artifact_presentation::PresentationArtifactError; -use codex_artifact_presentation::PresentationArtifactExecutionRequest; -use codex_artifact_presentation::PresentationArtifactResponse; -use codex_artifact_spreadsheet::SpreadsheetArtifactError; -use codex_artifact_spreadsheet::SpreadsheetArtifactRequest; -use codex_artifact_spreadsheet::SpreadsheetArtifactResponse; use codex_hooks::HookEvent; use codex_hooks::HookEventAfterAgent; use codex_hooks::HookPayload; @@ -1798,24 +1792,6 @@ impl Session { state.clear_connector_selection(); } - pub(crate) async fn execute_presentation_artifact( - &self, - request: PresentationArtifactExecutionRequest, - cwd: &Path, - ) -> Result { - let mut state = self.state.lock().await; - state.artifacts.presentation.execute_requests(request, cwd) - } - - pub(crate) async fn execute_spreadsheet_artifact( - &self, - request: SpreadsheetArtifactRequest, - cwd: &Path, - ) -> Result { - let mut state = self.state.lock().await; - state.artifacts.spreadsheet.execute(request, cwd) - } - async fn record_initial_history(&self, conversation_history: InitialHistory) { let turn_context = self.new_default_turn().await; self.clear_mcp_tool_selection().await; diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index babfb044d8..576db7cf3c 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -1,7 +1,5 @@ //! Session-wide mutable state. -use codex_artifact_presentation::PresentationArtifactManager; -use codex_artifact_spreadsheet::SpreadsheetArtifactManager; use codex_protocol::models::ResponseItem; use std::collections::HashMap; use std::collections::HashSet; @@ -18,12 +16,6 @@ use crate::tasks::RegularTask; use crate::truncate::TruncationPolicy; use codex_protocol::protocol::TurnContextItem; -#[derive(Default)] -pub(crate) struct SessionArtifacts { - pub(crate) presentation: PresentationArtifactManager, - pub(crate) spreadsheet: SpreadsheetArtifactManager, -} - /// Persistent, session-scoped state previously stored directly on `Session`. pub(crate) struct SessionState { pub(crate) session_configuration: SessionConfiguration, @@ -40,7 +32,6 @@ pub(crate) struct SessionState { pub(crate) startup_regular_task: Option>>, pub(crate) active_mcp_tool_selection: Option>, pub(crate) active_connector_selection: HashSet, - pub(crate) artifacts: SessionArtifacts, } impl SessionState { @@ -58,7 +49,6 @@ impl SessionState { startup_regular_task: None, active_mcp_tool_selection: None, active_connector_selection: HashSet::new(), - artifacts: SessionArtifacts::default(), } } diff --git a/codex-rs/core/src/tools/handlers/artifacts.rs b/codex-rs/core/src/tools/handlers/artifacts.rs new file mode 100644 index 0000000000..156a2b4642 --- /dev/null +++ b/codex-rs/core/src/tools/handlers/artifacts.rs @@ -0,0 +1,412 @@ +use async_trait::async_trait; +use codex_artifacts::ArtifactBuildRequest; +use codex_artifacts::ArtifactCommandOutput; +use codex_artifacts::ArtifactRuntimeError; +use codex_artifacts::ArtifactRuntimePlatform; +use codex_artifacts::ArtifactsClient; +use codex_artifacts::ArtifactsError; +use codex_artifacts::InstalledArtifactRuntime; +use serde_json::Value as JsonValue; +use std::path::Path; +use std::time::Duration; +use std::time::Instant; + +use crate::codex::Session; +use crate::codex::TurnContext; +use crate::exec::ExecToolCallOutput; +use crate::exec::StreamOutput; +use crate::features::Feature; +use crate::function_tool::FunctionCallError; +use crate::protocol::ExecCommandSource; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolOutput; +use crate::tools::context::ToolPayload; +use crate::tools::events::ToolEmitter; +use crate::tools::events::ToolEventCtx; +use crate::tools::events::ToolEventFailure; +use crate::tools::events::ToolEventStage; +use crate::tools::registry::ToolHandler; +use crate::tools::registry::ToolKind; +use codex_protocol::models::FunctionCallOutputBody; + +const ARTIFACTS_TOOL_NAME: &str = "artifacts"; +const ARTIFACTS_PRAGMA_PREFIXES: [&str; 2] = ["// codex-artifacts:", "// codex-artifact-tool:"]; +const PINNED_ARTIFACT_RUNTIME_VERSION: &str = "2.4.0"; +const DEFAULT_EXECUTION_TIMEOUT: Duration = Duration::from_secs(30); + +pub struct ArtifactsHandler; + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ArtifactsToolArgs { + source: String, + timeout_ms: Option, +} + +#[async_trait] +impl ToolHandler for ArtifactsHandler { + fn kind(&self) -> ToolKind { + ToolKind::Function + } + + fn matches_kind(&self, payload: &ToolPayload) -> bool { + matches!(payload, ToolPayload::Custom { .. }) + } + + async fn is_mutating(&self, _invocation: &ToolInvocation) -> bool { + true + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + + if !session.enabled(Feature::Artifact) { + return Err(FunctionCallError::RespondToModel( + "artifacts is disabled by feature flag".to_string(), + )); + } + + let args = match payload { + ToolPayload::Custom { input } => parse_freeform_args(&input)?, + _ => { + return Err(FunctionCallError::RespondToModel( + "artifacts expects freeform JavaScript input authored against the preloaded @oai/artifact-tool surface".to_string(), + )); + } + }; + + let runtime = resolve_preinstalled_runtime(&turn.config.codex_home) + .await + .map_err(artifacts_error)?; + let client = ArtifactsClient::from_installed_runtime(runtime); + + let started_at = Instant::now(); + emit_exec_begin(session.as_ref(), turn.as_ref(), &call_id).await; + + let result = client + .execute_build(ArtifactBuildRequest { + source: args.source, + cwd: turn.cwd.clone(), + timeout: Some(Duration::from_millis( + args.timeout_ms + .unwrap_or(DEFAULT_EXECUTION_TIMEOUT.as_millis() as u64), + )), + env: Default::default(), + }) + .await; + + let (success, output) = match result { + Ok(output) => (output.success(), output), + Err(error) => (false, error_output(&error)), + }; + + emit_exec_end( + session.as_ref(), + turn.as_ref(), + &call_id, + &output, + started_at.elapsed(), + success, + ) + .await; + + Ok(ToolOutput::Function { + body: FunctionCallOutputBody::Text(format_artifact_output(&output)), + success: Some(success), + }) + } +} + +async fn resolve_preinstalled_runtime( + codex_home: &Path, +) -> Result { + let platform = ArtifactRuntimePlatform::detect_current() + .map_err(ArtifactRuntimeError::from) + .map_err(ArtifactsError::Runtime)?; + let install_dir = codex_home + .join("packages") + .join("artifacts") + .join(PINNED_ARTIFACT_RUNTIME_VERSION) + .join(platform.as_str()); + if !install_dir.exists() { + return Err(ArtifactsError::Io { + context: format!( + "artifact runtime {} is not installed at {}", + PINNED_ARTIFACT_RUNTIME_VERSION, + install_dir.display() + ), + source: std::io::Error::new(std::io::ErrorKind::NotFound, "missing artifact runtime"), + }); + } + + InstalledArtifactRuntime::load(install_dir, platform).map_err(ArtifactsError::Runtime) +} + +fn parse_freeform_args(input: &str) -> Result { + if input.trim().is_empty() { + return Err(FunctionCallError::RespondToModel( + "artifacts expects raw JavaScript source text (non-empty) authored against the preloaded @oai/artifact-tool surface. Provide JS only, optionally with first-line `// codex-artifacts: timeout_ms=15000` or `// codex-artifact-tool: timeout_ms=15000`." + .to_string(), + )); + } + + let mut args = ArtifactsToolArgs { + source: input.to_string(), + timeout_ms: None, + }; + + let mut lines = input.splitn(2, '\n'); + let first_line = lines.next().unwrap_or_default(); + let rest = lines.next().unwrap_or_default(); + let trimmed = first_line.trim_start(); + let Some(pragma) = parse_pragma_prefix(trimmed) else { + reject_json_or_quoted_source(&args.source)?; + return Ok(args); + }; + + let mut timeout_ms = None; + let directive = pragma.trim(); + if !directive.is_empty() { + for token in directive.split_whitespace() { + let (key, value) = token.split_once('=').ok_or_else(|| { + FunctionCallError::RespondToModel(format!( + "artifacts pragma expects space-separated key=value pairs (supported keys: timeout_ms); got `{token}`" + )) + })?; + match key { + "timeout_ms" => { + if timeout_ms.is_some() { + return Err(FunctionCallError::RespondToModel( + "artifacts pragma specifies timeout_ms more than once".to_string(), + )); + } + let parsed = value.parse::().map_err(|_| { + FunctionCallError::RespondToModel(format!( + "artifacts pragma timeout_ms must be an integer; got `{value}`" + )) + })?; + timeout_ms = Some(parsed); + } + _ => { + return Err(FunctionCallError::RespondToModel(format!( + "artifacts pragma only supports timeout_ms; got `{key}`" + ))); + } + } + } + } + + if rest.trim().is_empty() { + return Err(FunctionCallError::RespondToModel( + "artifacts pragma must be followed by JavaScript source on subsequent lines" + .to_string(), + )); + } + + reject_json_or_quoted_source(rest)?; + args.source = rest.to_string(); + args.timeout_ms = timeout_ms; + Ok(args) +} + +fn reject_json_or_quoted_source(code: &str) -> Result<(), FunctionCallError> { + let trimmed = code.trim(); + if trimmed.starts_with("```") { + return Err(FunctionCallError::RespondToModel( + "artifacts expects raw JavaScript source, not markdown code fences. Resend plain JS only (optional first line `// codex-artifacts: ...` or `// codex-artifact-tool: ...`)." + .to_string(), + )); + } + let Ok(value) = serde_json::from_str::(trimmed) else { + return Ok(()); + }; + match value { + JsonValue::Object(_) | JsonValue::String(_) => Err(FunctionCallError::RespondToModel( + "artifacts is a freeform tool and expects raw JavaScript source authored against the preloaded @oai/artifact-tool surface. Resend plain JS only (optional first line `// codex-artifacts: ...` or `// codex-artifact-tool: ...`); do not send JSON (`{\"code\":...}`), quoted code, or markdown fences." + .to_string(), + )), + _ => Ok(()), + } +} + +fn parse_pragma_prefix(line: &str) -> Option<&str> { + ARTIFACTS_PRAGMA_PREFIXES + .iter() + .find_map(|prefix| line.strip_prefix(prefix)) +} + +fn artifacts_error(error: ArtifactsError) -> FunctionCallError { + FunctionCallError::RespondToModel(error.to_string()) +} + +async fn emit_exec_begin(session: &Session, turn: &TurnContext, call_id: &str) { + let emitter = ToolEmitter::shell( + vec![ARTIFACTS_TOOL_NAME.to_string()], + turn.cwd.clone(), + ExecCommandSource::Agent, + true, + ); + let ctx = ToolEventCtx::new(session, turn, call_id, None); + emitter.emit(ctx, ToolEventStage::Begin).await; +} + +async fn emit_exec_end( + session: &Session, + turn: &TurnContext, + call_id: &str, + output: &ArtifactCommandOutput, + duration: Duration, + success: bool, +) { + let exec_output = ExecToolCallOutput { + exit_code: output.exit_code.unwrap_or(1), + stdout: StreamOutput::new(output.stdout.clone()), + stderr: StreamOutput::new(output.stderr.clone()), + aggregated_output: StreamOutput::new(format_artifact_output(output)), + duration, + timed_out: false, + }; + let emitter = ToolEmitter::shell( + vec![ARTIFACTS_TOOL_NAME.to_string()], + turn.cwd.clone(), + ExecCommandSource::Agent, + true, + ); + let ctx = ToolEventCtx::new(session, turn, call_id, None); + let stage = if success { + ToolEventStage::Success(exec_output) + } else { + ToolEventStage::Failure(ToolEventFailure::Output(exec_output)) + }; + emitter.emit(ctx, stage).await; +} + +fn format_artifact_output(output: &ArtifactCommandOutput) -> String { + let stdout = output.stdout.trim(); + let stderr = output.stderr.trim(); + let mut sections = vec![format!( + "exit_code: {}", + output + .exit_code + .map(|code| code.to_string()) + .unwrap_or_else(|| "null".to_string()) + )]; + if !stdout.is_empty() { + sections.push(format!("stdout:\n{stdout}")); + } + if !stderr.is_empty() { + sections.push(format!("stderr:\n{stderr}")); + } + if stdout.is_empty() && stderr.is_empty() && output.success() { + sections.push("artifact JS completed successfully.".to_string()); + } + sections.join("\n\n") +} + +fn error_output(error: &ArtifactsError) -> ArtifactCommandOutput { + ArtifactCommandOutput { + exit_code: Some(1), + stdout: String::new(), + stderr: error.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use codex_artifacts::RuntimeEntrypoints; + use codex_artifacts::RuntimePathEntry; + use tempfile::TempDir; + + #[test] + fn parse_freeform_args_without_pragma() { + let args = parse_freeform_args("console.log('ok');").expect("parse args"); + assert_eq!(args.source, "console.log('ok');"); + assert_eq!(args.timeout_ms, None); + } + + #[test] + fn parse_freeform_args_with_pragma() { + let args = parse_freeform_args("// codex-artifacts: timeout_ms=45000\nconsole.log('ok');") + .expect("parse args"); + assert_eq!(args.source, "console.log('ok');"); + assert_eq!(args.timeout_ms, Some(45_000)); + } + + #[test] + fn parse_freeform_args_with_artifact_tool_pragma() { + let args = + parse_freeform_args("// codex-artifact-tool: timeout_ms=45000\nconsole.log('ok');") + .expect("parse args"); + assert_eq!(args.source, "console.log('ok');"); + assert_eq!(args.timeout_ms, Some(45_000)); + } + + #[test] + fn parse_freeform_args_rejects_json_wrapped_code() { + let err = + parse_freeform_args("{\"code\":\"console.log('ok')\"}").expect_err("expected error"); + assert!( + err.to_string() + .contains("artifacts is a freeform tool and expects raw JavaScript source") + ); + } + + #[tokio::test] + async fn resolve_preinstalled_runtime_reads_pinned_cache_path() { + let codex_home = TempDir::new().expect("create temp codex home"); + let platform = ArtifactRuntimePlatform::detect_current().expect("detect platform"); + let install_dir = codex_home + .path() + .join("packages") + .join("artifacts") + .join(PINNED_ARTIFACT_RUNTIME_VERSION) + .join(platform.as_str()); + std::fs::create_dir_all(&install_dir).expect("create install dir"); + std::fs::write( + install_dir.join("manifest.json"), + serde_json::json!({ + "schema_version": 1, + "runtime_version": PINNED_ARTIFACT_RUNTIME_VERSION, + "node": { "relative_path": "node/bin/node" }, + "entrypoints": { + "build_js": { "relative_path": "artifact-tool/dist/artifact_tool.mjs" }, + "render_cli": { "relative_path": "granola-render/dist/render_cli.mjs" } + } + }) + .to_string(), + ) + .expect("write manifest"); + + let runtime = resolve_preinstalled_runtime(codex_home.path()) + .await + .expect("resolve runtime"); + assert_eq!(runtime.runtime_version(), PINNED_ARTIFACT_RUNTIME_VERSION); + assert_eq!( + runtime.manifest().entrypoints, + RuntimeEntrypoints { + build_js: RuntimePathEntry { + relative_path: "artifact-tool/dist/artifact_tool.mjs".to_string(), + }, + render_cli: RuntimePathEntry { + relative_path: "granola-render/dist/render_cli.mjs".to_string(), + }, + } + ); + } + + #[test] + fn format_artifact_output_includes_success_message_when_silent() { + let formatted = format_artifact_output(&ArtifactCommandOutput { + exit_code: Some(0), + stdout: String::new(), + stderr: String::new(), + }); + assert!(formatted.contains("artifact JS completed successfully.")); + } +} diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index 908f3d18d0..d985768093 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod agent_jobs; pub mod apply_patch; +mod artifacts; mod dynamic; mod grep_files; mod js_repl; @@ -8,12 +9,10 @@ mod mcp; mod mcp_resource; pub(crate) mod multi_agents; mod plan; -mod presentation_artifact; mod read_file; mod request_user_input; mod search_tool_bm25; mod shell; -mod spreadsheet_artifact; mod test_sync; pub(crate) mod unified_exec; mod view_image; @@ -29,6 +28,7 @@ use crate::function_tool::FunctionCallError; use crate::sandboxing::SandboxPermissions; use crate::sandboxing::normalize_additional_permissions; pub use apply_patch::ApplyPatchHandler; +pub use artifacts::ArtifactsHandler; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; pub use dynamic::DynamicToolHandler; @@ -40,7 +40,6 @@ pub use mcp::McpHandler; pub use mcp_resource::McpResourceHandler; pub use multi_agents::MultiAgentHandler; pub use plan::PlanHandler; -pub use presentation_artifact::PresentationArtifactHandler; pub use read_file::ReadFileHandler; pub use request_user_input::RequestUserInputHandler; pub(crate) use request_user_input::request_user_input_tool_description; @@ -49,7 +48,6 @@ pub(crate) use search_tool_bm25::SEARCH_TOOL_BM25_TOOL_NAME; pub use search_tool_bm25::SearchToolBm25Handler; pub use shell::ShellCommandHandler; pub use shell::ShellHandler; -pub use spreadsheet_artifact::SpreadsheetArtifactHandler; pub use test_sync::TestSyncHandler; pub use unified_exec::UnifiedExecHandler; pub use view_image::ViewImageHandler; diff --git a/codex-rs/core/src/tools/handlers/presentation_artifact.rs b/codex-rs/core/src/tools/handlers/presentation_artifact.rs deleted file mode 100644 index 23b80d6912..0000000000 --- a/codex-rs/core/src/tools/handlers/presentation_artifact.rs +++ /dev/null @@ -1,250 +0,0 @@ -use async_trait::async_trait; -use codex_artifact_presentation::PathAccessKind; -use codex_artifact_presentation::PathAccessRequirement; -use codex_artifact_presentation::PresentationArtifactError; -use codex_artifact_presentation::PresentationArtifactToolRequest; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::ReviewDecision; -use serde_json::to_string; -use std::path::Component; -use std::path::Path; -use std::path::PathBuf; - -use crate::codex::Session; -use crate::codex::TurnContext; -use crate::features::Feature; -use crate::function_tool::FunctionCallError; -use crate::path_utils::normalize_for_path_comparison; -use crate::path_utils::resolve_symlink_write_paths; -use crate::tools::context::ToolInvocation; -use crate::tools::context::ToolOutput; -use crate::tools::context::ToolPayload; -use crate::tools::handlers::parse_arguments; -use crate::tools::registry::ToolHandler; -use crate::tools::registry::ToolKind; -use crate::tools::sandboxing::with_cached_approval; -use codex_protocol::models::FunctionCallOutputBody; - -pub struct PresentationArtifactHandler; - -#[async_trait] -impl ToolHandler for PresentationArtifactHandler { - fn kind(&self) -> ToolKind { - ToolKind::Function - } - - async fn is_mutating(&self, invocation: &ToolInvocation) -> bool { - let ToolPayload::Function { arguments } = &invocation.payload else { - return true; - }; - let Ok(request) = parse_arguments::(arguments) else { - return true; - }; - request.is_mutating().unwrap_or(true) - } - - async fn handle(&self, invocation: ToolInvocation) -> Result { - let ToolInvocation { - session, - turn, - payload, - call_id, - .. - } = invocation; - - if !session.enabled(Feature::Artifact) { - return Err(FunctionCallError::RespondToModel( - "presentation_artifact is disabled by feature flag".to_string(), - )); - } - - let arguments = match payload { - ToolPayload::Function { arguments } => arguments, - _ => { - return Err(FunctionCallError::RespondToModel( - "presentation_artifact handler received unsupported payload".to_string(), - )); - } - }; - - let request: PresentationArtifactToolRequest = parse_arguments(&arguments)?; - for access in request - .required_path_accesses(&turn.cwd) - .map_err(presentation_error)? - { - authorize_path_access(session.as_ref(), turn.as_ref(), &call_id, &access).await?; - } - - let response = session - .execute_presentation_artifact( - request - .into_execution_request() - .map_err(presentation_error)?, - &turn.cwd, - ) - .await - .map_err(presentation_error)?; - - Ok(ToolOutput::Function { - body: FunctionCallOutputBody::Text(to_string(&response).map_err(|error| { - FunctionCallError::RespondToModel(format!( - "failed to serialize presentation_artifact response: {error}" - )) - })?), - success: Some(true), - }) - } -} - -fn presentation_error(error: PresentationArtifactError) -> FunctionCallError { - FunctionCallError::RespondToModel(error.to_string()) -} - -async fn authorize_path_access( - session: &Session, - turn: &TurnContext, - call_id: &str, - access: &PathAccessRequirement, -) -> Result<(), FunctionCallError> { - let effective_path = match access.kind { - PathAccessKind::Read => effective_read_path(&access.path), - PathAccessKind::Write => effective_write_path(&access.path), - }; - let allowed = match access.kind { - PathAccessKind::Read => path_is_readable(turn, &effective_path), - PathAccessKind::Write => path_is_writable(turn, &effective_path), - }; - if allowed { - return Ok(()); - } - - let approval_policy = turn.approval_policy.value(); - if !matches!( - approval_policy, - AskForApproval::OnRequest | AskForApproval::UnlessTrusted - ) { - return Err(FunctionCallError::RespondToModel(format!( - "{} path `{}` is outside the current sandbox policy", - access_kind_label(access.kind), - access.path.display() - ))); - } - - let key = format!( - "presentation_artifact:{:?}:{}", - access.kind, - effective_path.display() - ); - let path = access.path.clone(); - let action = access.action.clone(); - let decision = with_cached_approval( - &session.services, - "presentation_artifact", - vec![key], - || { - let path = path.clone(); - let action = action.clone(); - async move { - session - .request_command_approval( - turn, - call_id.to_string(), - None, - vec![ - "presentation_artifact".to_string(), - action, - path.display().to_string(), - ], - turn.cwd.clone(), - Some(format!( - "Allow presentation_artifact to {} `{}`?", - access_kind_verb(access.kind), - path.display() - )), - None, - None, - None, - None, - ) - .await - } - }, - ) - .await; - - if matches!( - decision, - ReviewDecision::Approved - | ReviewDecision::ApprovedForSession - | ReviewDecision::ApprovedExecpolicyAmendment { .. } - ) { - return Ok(()); - } - - Err(FunctionCallError::RespondToModel(format!( - "{} path `{}` was not approved", - access_kind_label(access.kind), - access.path.display() - ))) -} - -fn path_is_readable(turn: &TurnContext, path: &Path) -> bool { - if turn.sandbox_policy.has_full_disk_read_access() { - return true; - } - - turn.sandbox_policy - .get_readable_roots_with_cwd(&turn.cwd) - .iter() - .any(|root| path.starts_with(root.as_path())) -} - -fn path_is_writable(turn: &TurnContext, path: &Path) -> bool { - if turn.sandbox_policy.has_full_disk_write_access() { - return true; - } - - turn.sandbox_policy - .get_writable_roots_with_cwd(&turn.cwd) - .iter() - .any(|root| root.is_path_writable(path)) -} - -fn effective_read_path(path: &Path) -> PathBuf { - normalize_for_path_comparison(path).unwrap_or_else(|_| normalize_without_fs(path)) -} - -fn effective_write_path(path: &Path) -> PathBuf { - let write_path = resolve_symlink_write_paths(path) - .map(|paths| paths.write_path) - .unwrap_or_else(|_| path.to_path_buf()); - normalize_for_path_comparison(&write_path).unwrap_or_else(|_| normalize_without_fs(&write_path)) -} - -fn normalize_without_fs(path: &Path) -> PathBuf { - let mut normalized = PathBuf::new(); - for component in path.components() { - match component { - Component::ParentDir => { - normalized.pop(); - } - Component::CurDir => {} - other => normalized.push(other.as_os_str()), - } - } - normalized -} - -fn access_kind_label(kind: PathAccessKind) -> &'static str { - match kind { - PathAccessKind::Read => "read", - PathAccessKind::Write => "write", - } -} - -fn access_kind_verb(kind: PathAccessKind) -> &'static str { - match kind { - PathAccessKind::Read => "read from", - PathAccessKind::Write => "write to", - } -} diff --git a/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs b/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs deleted file mode 100644 index be4eb7fc58..0000000000 --- a/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs +++ /dev/null @@ -1,235 +0,0 @@ -use async_trait::async_trait; -use codex_artifact_spreadsheet::PathAccessKind; -use codex_artifact_spreadsheet::PathAccessRequirement; -use codex_artifact_spreadsheet::SpreadsheetArtifactError; -use codex_artifact_spreadsheet::SpreadsheetArtifactRequest; -use codex_protocol::models::FunctionCallOutputBody; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::ReviewDecision; -use serde_json::to_string; -use std::path::Component; -use std::path::Path; -use std::path::PathBuf; - -use crate::codex::Session; -use crate::codex::TurnContext; -use crate::features::Feature; -use crate::function_tool::FunctionCallError; -use crate::path_utils::normalize_for_path_comparison; -use crate::path_utils::resolve_symlink_write_paths; -use crate::tools::context::ToolInvocation; -use crate::tools::context::ToolOutput; -use crate::tools::context::ToolPayload; -use crate::tools::handlers::parse_arguments; -use crate::tools::registry::ToolHandler; -use crate::tools::registry::ToolKind; -use crate::tools::sandboxing::with_cached_approval; - -pub struct SpreadsheetArtifactHandler; - -#[async_trait] -impl ToolHandler for SpreadsheetArtifactHandler { - fn kind(&self) -> ToolKind { - ToolKind::Function - } - - async fn is_mutating(&self, _invocation: &ToolInvocation) -> bool { - true - } - - async fn handle(&self, invocation: ToolInvocation) -> Result { - let ToolInvocation { - session, - turn, - payload, - call_id, - .. - } = invocation; - - if !session.enabled(Feature::Artifact) { - return Err(FunctionCallError::RespondToModel( - "spreadsheet_artifact is disabled by feature flag".to_string(), - )); - } - - let arguments = match payload { - ToolPayload::Function { arguments } => arguments, - _ => { - return Err(FunctionCallError::RespondToModel( - "spreadsheet_artifact handler received unsupported payload".to_string(), - )); - } - }; - - let request: SpreadsheetArtifactRequest = parse_arguments(&arguments)?; - for access in request - .required_path_accesses(&turn.cwd) - .map_err(spreadsheet_error)? - { - authorize_path_access(session.as_ref(), turn.as_ref(), &call_id, &access).await?; - } - - let response = session - .execute_spreadsheet_artifact(request, &turn.cwd) - .await - .map_err(spreadsheet_error)?; - - Ok(ToolOutput::Function { - body: FunctionCallOutputBody::Text(to_string(&response).map_err(|error| { - FunctionCallError::RespondToModel(format!( - "failed to serialize spreadsheet_artifact response: {error}" - )) - })?), - success: Some(true), - }) - } -} - -fn spreadsheet_error(error: SpreadsheetArtifactError) -> FunctionCallError { - FunctionCallError::RespondToModel(error.to_string()) -} - -async fn authorize_path_access( - session: &Session, - turn: &TurnContext, - call_id: &str, - access: &PathAccessRequirement, -) -> Result<(), FunctionCallError> { - let effective_path = match access.kind { - PathAccessKind::Read => effective_read_path(&access.path), - PathAccessKind::Write => effective_write_path(&access.path), - }; - let allowed = match access.kind { - PathAccessKind::Read => path_is_readable(turn, &effective_path), - PathAccessKind::Write => path_is_writable(turn, &effective_path), - }; - if allowed { - return Ok(()); - } - - let approval_policy = turn.approval_policy.value(); - if !matches!( - approval_policy, - AskForApproval::OnRequest | AskForApproval::UnlessTrusted - ) { - return Err(FunctionCallError::RespondToModel(format!( - "{} path `{}` is outside the current sandbox policy", - access_kind_label(access.kind), - access.path.display() - ))); - } - - let key = format!( - "spreadsheet_artifact:{:?}:{}", - access.kind, - effective_path.display() - ); - let path = access.path.clone(); - let action = access.action.clone(); - let decision = - with_cached_approval(&session.services, "spreadsheet_artifact", vec![key], || { - let path = path.clone(); - let action = action.clone(); - async move { - session - .request_command_approval( - turn, - call_id.to_string(), - None, - vec![ - "spreadsheet_artifact".to_string(), - action, - path.display().to_string(), - ], - turn.cwd.clone(), - Some(format!( - "Allow spreadsheet_artifact to {} `{}`?", - access_kind_verb(access.kind), - path.display() - )), - None, - None, - None, - None, - ) - .await - } - }) - .await; - - if matches!( - decision, - ReviewDecision::Approved - | ReviewDecision::ApprovedForSession - | ReviewDecision::ApprovedExecpolicyAmendment { .. } - ) { - return Ok(()); - } - - Err(FunctionCallError::RespondToModel(format!( - "{} path `{}` was not approved", - access_kind_label(access.kind), - access.path.display() - ))) -} - -fn path_is_readable(turn: &TurnContext, path: &Path) -> bool { - if turn.sandbox_policy.has_full_disk_read_access() { - return true; - } - - turn.sandbox_policy - .get_readable_roots_with_cwd(&turn.cwd) - .iter() - .any(|root| path.starts_with(root.as_path())) -} - -fn path_is_writable(turn: &TurnContext, path: &Path) -> bool { - if turn.sandbox_policy.has_full_disk_write_access() { - return true; - } - - turn.sandbox_policy - .get_writable_roots_with_cwd(&turn.cwd) - .iter() - .any(|root| root.is_path_writable(path)) -} - -fn effective_read_path(path: &Path) -> PathBuf { - normalize_for_path_comparison(path).unwrap_or_else(|_| normalize_without_fs(path)) -} - -fn effective_write_path(path: &Path) -> PathBuf { - let write_path = resolve_symlink_write_paths(path) - .map(|paths| paths.write_path) - .unwrap_or_else(|_| path.to_path_buf()); - normalize_for_path_comparison(&write_path).unwrap_or_else(|_| normalize_without_fs(&write_path)) -} - -fn normalize_without_fs(path: &Path) -> PathBuf { - let mut normalized = PathBuf::new(); - for component in path.components() { - match component { - Component::ParentDir => { - normalized.pop(); - } - Component::CurDir => {} - other => normalized.push(other.as_os_str()), - } - } - normalized -} - -fn access_kind_label(kind: PathAccessKind) -> &'static str { - match kind { - PathAccessKind::Read => "read", - PathAccessKind::Write => "write", - } -} - -fn access_kind_verb(kind: PathAccessKind) -> &'static str { - match kind { - PathAccessKind::Read => "read from", - PathAccessKind::Write => "write to", - } -} diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index b0b3540990..dcdb48500e 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -575,97 +575,6 @@ fn create_view_image_tool() -> ToolSpec { }) } -fn create_presentation_artifact_tool() -> ToolSpec { - let action_step_schema = JsonSchema::Object { - properties: BTreeMap::from([ - ( - "action".to_string(), - JsonSchema::String { - description: Some("Action name to run for this step.".to_string()), - }, - ), - ( - "args".to_string(), - JsonSchema::Object { - properties: BTreeMap::new(), - required: None, - additional_properties: Some(true.into()), - }, - ), - ]), - required: Some(vec!["action".to_string(), "args".to_string()]), - additional_properties: Some(false.into()), - }; - let properties = BTreeMap::from([ - ( - "artifact_id".to_string(), - JsonSchema::String { - description: Some( - "Artifact id returned by an earlier presentation_artifact call.".to_string(), - ), - }, - ), - ( - "actions".to_string(), - JsonSchema::Array { - items: Box::new(action_step_schema), - description: Some( - "Array of `(action, args)` steps to execute sequentially.".to_string(), - ), - }, - ), - ]); - - ToolSpec::Function(ResponsesApiTool { - name: "presentation_artifact".to_string(), - description: "Create or edit a presentation artifact for the current thread.".to_string(), - strict: false, - parameters: JsonSchema::Object { - properties, - required: Some(vec!["actions".to_string()]), - additional_properties: Some(false.into()), - }, - }) -} - -fn create_spreadsheet_artifact_tool() -> ToolSpec { - let properties = BTreeMap::from([ - ( - "artifact_id".to_string(), - JsonSchema::String { - description: Some( - "Artifact id returned by an earlier spreadsheet_artifact call.".to_string(), - ), - }, - ), - ( - "action".to_string(), - JsonSchema::String { - description: Some("Action name to run for this request.".to_string()), - }, - ), - ( - "args".to_string(), - JsonSchema::Object { - properties: BTreeMap::new(), - required: None, - additional_properties: Some(true.into()), - }, - ), - ]); - - ToolSpec::Function(ResponsesApiTool { - name: "spreadsheet_artifact".to_string(), - description: "Create or edit a spreadsheet artifact for the current thread.".to_string(), - strict: false, - parameters: JsonSchema::Object { - properties, - required: Some(vec!["action".to_string(), "args".to_string()]), - additional_properties: Some(false.into()), - }, - }) -} - fn create_collab_input_items_schema() -> JsonSchema { let properties = BTreeMap::from([ ( @@ -1461,6 +1370,33 @@ JS_SOURCE: /(?:\s*)(?:[^\s{\"`]|`[^`]|``[^`])[\s\S]*/ }) } +fn create_artifacts_tool() -> ToolSpec { + const ARTIFACTS_FREEFORM_GRAMMAR: &str = r#" +start: pragma_source | plain_source + +pragma_source: PRAGMA_LINE NEWLINE js_source +plain_source: PLAIN_JS_SOURCE + +js_source: JS_SOURCE + +PRAGMA_LINE: /[ \t]*\/\/ codex-artifacts:[^\r\n]*/ | /[ \t]*\/\/ codex-artifact-tool:[^\r\n]*/ +NEWLINE: /\r?\n/ +PLAIN_JS_SOURCE: /(?:\s*)(?:[^\s{\"`]|`[^`]|``[^`])[\s\S]*/ +JS_SOURCE: /(?:\s*)(?:[^\s{\"`]|`[^`]|``[^`])[\s\S]*/ +"#; + + ToolSpec::Freeform(FreeformTool { + name: "artifacts".to_string(), + description: "Runs raw JavaScript against the preinstalled Codex @oai/artifact-tool runtime for creating presentations or spreadsheets. This is plain JavaScript executed by Node with top-level await, not TypeScript: do not use type annotations, `interface`, `type`, or `import type`. Author code the same way you would for `import { Presentation, Workbook, PresentationFile, SpreadsheetFile, FileBlob, ... } from \"@oai/artifact-tool\"`, but omit that import line because the package surface is already preloaded. Named exports are available directly on `globalThis`, and the full module is available as `globalThis.artifactTool` (also aliased as `globalThis.artifacts` and `globalThis.codexArtifacts`). Node built-ins such as `node:fs/promises` may still be imported when needed for saving preview bytes. This is a freeform tool: send raw JavaScript source text, optionally with a first-line pragma like `// codex-artifacts: timeout_ms=15000` or `// codex-artifact-tool: timeout_ms=15000`; do not send JSON/quotes/markdown fences." + .to_string(), + format: FreeformToolFormat { + r#type: "grammar".to_string(), + syntax: "lark".to_string(), + definition: ARTIFACTS_FREEFORM_GRAMMAR.to_string(), + }, + }) +} + fn create_js_repl_reset_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "js_repl_reset".to_string(), @@ -1781,6 +1717,7 @@ pub(crate) fn build_specs( dynamic_tools: &[DynamicToolSpec], ) -> ToolRegistryBuilder { use crate::tools::handlers::ApplyPatchHandler; + use crate::tools::handlers::ArtifactsHandler; use crate::tools::handlers::DynamicToolHandler; use crate::tools::handlers::GrepFilesHandler; use crate::tools::handlers::JsReplHandler; @@ -1790,13 +1727,11 @@ pub(crate) fn build_specs( use crate::tools::handlers::McpResourceHandler; use crate::tools::handlers::MultiAgentHandler; use crate::tools::handlers::PlanHandler; - use crate::tools::handlers::PresentationArtifactHandler; use crate::tools::handlers::ReadFileHandler; use crate::tools::handlers::RequestUserInputHandler; use crate::tools::handlers::SearchToolBm25Handler; use crate::tools::handlers::ShellCommandHandler; use crate::tools::handlers::ShellHandler; - use crate::tools::handlers::SpreadsheetArtifactHandler; use crate::tools::handlers::TestSyncHandler; use crate::tools::handlers::UnifiedExecHandler; use crate::tools::handlers::ViewImageHandler; @@ -1819,8 +1754,7 @@ pub(crate) fn build_specs( let search_tool_handler = Arc::new(SearchToolBm25Handler); let js_repl_handler = Arc::new(JsReplHandler); let js_repl_reset_handler = Arc::new(JsReplResetHandler); - let presentation_artifact_handler = Arc::new(PresentationArtifactHandler); - let spreadsheet_artifact_handler = Arc::new(SpreadsheetArtifactHandler); + let artifacts_handler = Arc::new(ArtifactsHandler); let request_permission_enabled = config.request_permission_enabled; match &config.shell_type { @@ -1965,10 +1899,8 @@ pub(crate) fn build_specs( builder.register_handler("view_image", view_image_handler); if config.artifact_tools { - builder.push_spec(create_presentation_artifact_tool()); - builder.push_spec(create_spreadsheet_artifact_tool()); - builder.register_handler("presentation_artifact", presentation_artifact_handler); - builder.register_handler("spreadsheet_artifact", spreadsheet_artifact_handler); + builder.push_spec(create_artifacts_tool()); + builder.register_handler("artifacts", artifacts_handler); } if config.collab_tools { @@ -2301,7 +2233,7 @@ mod tests { session_source: SessionSource::Cli, }); let (tools, _) = build_specs(&tools_config, None, None, &[]).build(); - assert_contains_tool_names(&tools, &["presentation_artifact", "spreadsheet_artifact"]); + assert_contains_tool_names(&tools, &["artifacts"]); } #[test] diff --git a/codex-rs/deny.toml b/codex-rs/deny.toml index d2de502498..29bf6c5880 100644 --- a/codex-rs/deny.toml +++ b/codex-rs/deny.toml @@ -78,7 +78,6 @@ ignore = [ # TODO(fcoury): remove this exception when syntect drops yaml-rust and bincode, or updates to versions that have fixed the vulnerabilities. { id = "RUSTSEC-2024-0320", reason = "yaml-rust is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, { id = "RUSTSEC-2025-0141", reason = "bincode is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, - { id = "RUSTSEC-2025-0134", reason = "rustls-pemfile is unmaintained; pulled in via reqwest -> ppt-rs -> codex-artifact-presentation; no safe upgrade available yet" }, ] # If this is true, then cargo deny will use the git executable to fetch advisory database. # If this is false, then it uses a built-in git library. diff --git a/codex-rs/package-manager/BUILD.bazel b/codex-rs/package-manager/BUILD.bazel new file mode 100644 index 0000000000..bbbc725cbf --- /dev/null +++ b/codex-rs/package-manager/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "package-manager", + crate_name = "codex_package_manager", +) diff --git a/codex-rs/package-manager/Cargo.toml b/codex-rs/package-manager/Cargo.toml new file mode 100644 index 0000000000..8a77bfda15 --- /dev/null +++ b/codex-rs/package-manager/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "codex-package-manager" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +flate2 = { workspace = true } +reqwest = { workspace = true, features = ["json", "stream"] } +serde = { workspace = true, features = ["derive"] } +sha2 = { workspace = true } +tar = { workspace = true } +tempfile = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = ["fs", "rt", "sync"] } +url = { workspace = true } +zip = { workspace = true } + +[lints] +workspace = true + +[dev-dependencies] +pretty_assertions = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["fs", "macros", "rt", "rt-multi-thread"] } +wiremock = { workspace = true } diff --git a/codex-rs/package-manager/src/lib.rs b/codex-rs/package-manager/src/lib.rs new file mode 100644 index 0000000000..77e2138d61 --- /dev/null +++ b/codex-rs/package-manager/src/lib.rs @@ -0,0 +1,793 @@ +use flate2::read::GzDecoder; +use reqwest::Client; +use serde::de::DeserializeOwned; +use sha2::Digest; +use sha2::Sha256; +use std::fs::File; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; +use tar::Archive; +use tempfile::tempdir_in; +use thiserror::Error; +use tokio::fs; +use url::Url; +use zip::ZipArchive; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PackageManagerConfig

{ + codex_home: PathBuf, + package: P, + cache_root: Option, +} + +impl

PackageManagerConfig

{ + pub fn new(codex_home: PathBuf, package: P) -> Self { + Self { + codex_home, + package, + cache_root: None, + } + } + + pub fn with_cache_root(mut self, cache_root: PathBuf) -> Self { + self.cache_root = Some(cache_root); + self + } + + pub fn codex_home(&self) -> &Path { + &self.codex_home + } + + pub fn package(&self) -> &P { + &self.package + } +} + +impl PackageManagerConfig

{ + pub fn cache_root(&self) -> PathBuf { + self.cache_root.clone().unwrap_or_else(|| { + self.codex_home.join( + self.package + .default_cache_root_relative() + .replace('/', std::path::MAIN_SEPARATOR_STR), + ) + }) + } +} + +#[derive(Clone, Debug)] +pub struct PackageManager

{ + client: Client, + config: PackageManagerConfig

, +} + +impl

PackageManager

{ + pub fn new(config: PackageManagerConfig

) -> Self { + Self { + client: Client::new(), + config, + } + } + + pub fn with_client(config: PackageManagerConfig

, client: Client) -> Self { + Self { client, config } + } + + pub fn config(&self) -> &PackageManagerConfig

{ + &self.config + } +} + +impl PackageManager

{ + pub async fn resolve_cached(&self) -> Result, P::Error> { + let platform = PackagePlatform::detect_current().map_err(P::Error::from)?; + let install_dir = self + .config + .package() + .install_dir(&self.config.cache_root(), platform); + if !fs::try_exists(&install_dir) + .await + .map_err(|source| PackageManagerError::Io { + context: format!("failed to read {}", install_dir.display()), + source, + }) + .map_err(P::Error::from)? + { + return Ok(None); + } + + let package = self + .config + .package() + .load_installed(install_dir, platform)?; + if self.config.package().installed_version(&package) != self.config.package().version() { + return Ok(None); + } + Ok(Some(package)) + } + + pub async fn ensure_installed(&self) -> Result { + if let Some(package) = self.resolve_cached().await? { + return Ok(package); + } + + let platform = PackagePlatform::detect_current().map_err(P::Error::from)?; + let manifest = self.fetch_release_manifest().await?; + if self.config.package().release_version(&manifest) != self.config.package().version() { + return Err(PackageManagerError::UnexpectedPackageVersion { + expected: self.config.package().version().to_string(), + actual: self.config.package().release_version(&manifest).to_string(), + } + .into()); + } + + let platform_archive = self + .config + .package() + .platform_archive(&manifest, platform)?; + let archive_url = self + .config + .package() + .archive_url(&platform_archive) + .map_err(P::Error::from)?; + let archive_bytes = self.download_bytes(&archive_url).await?; + verify_sha256(&archive_bytes, &platform_archive.sha256).map_err(P::Error::from)?; + + let install_dir = self + .config + .package() + .install_dir(&self.config.cache_root(), platform); + if fs::try_exists(&install_dir) + .await + .map_err(|source| PackageManagerError::Io { + context: format!("failed to read {}", install_dir.display()), + source, + }) + .map_err(P::Error::from)? + { + fs::remove_dir_all(&install_dir) + .await + .map_err(|source| PackageManagerError::Io { + context: format!("failed to remove {}", install_dir.display()), + source, + }) + .map_err(P::Error::from)?; + } + + let cache_root = self.config.cache_root(); + fs::create_dir_all(&cache_root) + .await + .map_err(|source| PackageManagerError::Io { + context: format!("failed to create {}", cache_root.display()), + source, + }) + .map_err(P::Error::from)?; + + let staging_dir = tempdir_in(&cache_root) + .map_err(|source| PackageManagerError::Io { + context: format!( + "failed to create staging directory in {}", + cache_root.display() + ), + source, + }) + .map_err(P::Error::from)?; + let archive_path = staging_dir.path().join(&platform_archive.archive); + fs::write(&archive_path, &archive_bytes) + .await + .map_err(|source| PackageManagerError::Io { + context: format!("failed to write {}", archive_path.display()), + source, + }) + .map_err(P::Error::from)?; + let extraction_root = staging_dir.path().join("extract"); + fs::create_dir_all(&extraction_root) + .await + .map_err(|source| PackageManagerError::Io { + context: format!("failed to create {}", extraction_root.display()), + source, + }) + .map_err(P::Error::from)?; + + extract_archive(&archive_path, &extraction_root, platform_archive.format) + .map_err(P::Error::from)?; + let extracted_root = self + .config + .package() + .detect_extracted_root(&extraction_root)?; + let package = self + .config + .package() + .load_installed(extracted_root.clone(), platform)?; + if self.config.package().installed_version(&package) != self.config.package().version() { + return Err(PackageManagerError::UnexpectedPackageVersion { + expected: self.config.package().version().to_string(), + actual: self + .config + .package() + .installed_version(&package) + .to_string(), + } + .into()); + } + + if let Some(parent) = install_dir.parent() { + fs::create_dir_all(parent) + .await + .map_err(|source| PackageManagerError::Io { + context: format!("failed to create {}", parent.display()), + source, + }) + .map_err(P::Error::from)?; + } + + fs::rename(&extracted_root, &install_dir) + .await + .map_err(|source| PackageManagerError::Io { + context: format!( + "failed to move {} to {}", + extracted_root.display(), + install_dir.display() + ), + source, + }) + .map_err(P::Error::from)?; + + self.config.package().load_installed(install_dir, platform) + } + + async fn fetch_release_manifest(&self) -> Result { + let manifest_url = self + .config + .package() + .manifest_url() + .map_err(P::Error::from)?; + let response = self + .client + .get(manifest_url.clone()) + .send() + .await + .map_err(|source| PackageManagerError::Http { + context: format!("failed to fetch {manifest_url}"), + source, + }) + .map_err(P::Error::from)? + .error_for_status() + .map_err(|source| PackageManagerError::Http { + context: format!("manifest request failed for {manifest_url}"), + source, + }) + .map_err(P::Error::from)?; + + response + .json::() + .await + .map_err(|source| PackageManagerError::Http { + context: format!("failed to decode manifest from {manifest_url}"), + source, + }) + .map_err(P::Error::from) + } + + async fn download_bytes(&self, url: &Url) -> Result, P::Error> { + let response = self + .client + .get(url.clone()) + .send() + .await + .map_err(|source| PackageManagerError::Http { + context: format!("failed to download {url}"), + source, + }) + .map_err(P::Error::from)? + .error_for_status() + .map_err(|source| PackageManagerError::Http { + context: format!("archive request failed for {url}"), + source, + }) + .map_err(P::Error::from)?; + let bytes = response + .bytes() + .await + .map_err(|source| PackageManagerError::Http { + context: format!("failed to read response body for {url}"), + source, + }) + .map_err(P::Error::from)?; + Ok(bytes.to_vec()) + } +} + +pub trait ManagedPackage: Clone { + type Error: From; + type Installed: Clone; + type ReleaseManifest: DeserializeOwned; + + fn default_cache_root_relative(&self) -> &str; + fn version(&self) -> &str; + fn manifest_url(&self) -> Result; + fn archive_url(&self, archive: &PackageReleaseArchive) -> Result; + fn release_version<'a>(&self, manifest: &'a Self::ReleaseManifest) -> &'a str; + fn platform_archive( + &self, + manifest: &Self::ReleaseManifest, + platform: PackagePlatform, + ) -> Result; + fn install_dir(&self, cache_root: &Path, platform: PackagePlatform) -> PathBuf; + fn installed_version<'a>(&self, package: &'a Self::Installed) -> &'a str; + fn load_installed( + &self, + root_dir: PathBuf, + platform: PackagePlatform, + ) -> Result; + + fn detect_extracted_root(&self, extraction_root: &Path) -> Result { + detect_single_package_root(extraction_root).map_err(Self::Error::from) + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PackagePlatform { + DarwinArm64, + DarwinX64, + LinuxArm64, + LinuxX64, + WindowsArm64, + WindowsX64, +} + +impl PackagePlatform { + pub fn detect_current() -> Result { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("macos", "aarch64") | ("macos", "arm64") => Ok(Self::DarwinArm64), + ("macos", "x86_64") => Ok(Self::DarwinX64), + ("linux", "aarch64") | ("linux", "arm64") => Ok(Self::LinuxArm64), + ("linux", "x86_64") => Ok(Self::LinuxX64), + ("windows", "aarch64") | ("windows", "arm64") => Ok(Self::WindowsArm64), + ("windows", "x86_64") => Ok(Self::WindowsX64), + (os, arch) => Err(PackageManagerError::UnsupportedPlatform { + os: os.to_string(), + arch: arch.to_string(), + }), + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::DarwinArm64 => "darwin-arm64", + Self::DarwinX64 => "darwin-x64", + Self::LinuxArm64 => "linux-arm64", + Self::LinuxX64 => "linux-x64", + Self::WindowsArm64 => "windows-arm64", + Self::WindowsX64 => "windows-x64", + } + } +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)] +pub struct PackageReleaseArchive { + pub archive: String, + pub sha256: String, + pub format: ArchiveFormat, + pub size_bytes: Option, +} + +#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)] +pub enum ArchiveFormat { + #[serde(rename = "zip")] + Zip, + #[serde(rename = "tar.gz")] + TarGz, +} + +#[derive(Debug, Error)] +pub enum PackageManagerError { + #[error("unsupported platform: {os}-{arch}")] + UnsupportedPlatform { os: String, arch: String }, + #[error("invalid release base url")] + InvalidBaseUrl(#[source] url::ParseError), + #[error("{context}")] + Http { + context: String, + #[source] + source: reqwest::Error, + }, + #[error("{context}")] + Io { + context: String, + #[source] + source: std::io::Error, + }, + #[error("missing platform entry `{0}` in release manifest")] + MissingPlatform(String), + #[error("unexpected package version: expected `{expected}`, got `{actual}`")] + UnexpectedPackageVersion { expected: String, actual: String }, + #[error("checksum mismatch: expected `{expected}`, got `{actual}`")] + ChecksumMismatch { expected: String, actual: String }, + #[error("archive extraction failed: {0}")] + ArchiveExtraction(String), + #[error("archive did not contain a package root with manifest.json under {0}")] + MissingPackageRoot(PathBuf), +} + +pub fn detect_single_package_root(extraction_root: &Path) -> Result { + let direct_manifest = extraction_root.join("manifest.json"); + if direct_manifest.exists() { + return Ok(extraction_root.to_path_buf()); + } + + let mut directory_candidates = Vec::new(); + for entry in std::fs::read_dir(extraction_root).map_err(|source| PackageManagerError::Io { + context: format!("failed to read {}", extraction_root.display()), + source, + })? { + let entry = entry.map_err(|source| PackageManagerError::Io { + context: format!("failed to read entry in {}", extraction_root.display()), + source, + })?; + let path = entry.path(); + if path.is_dir() { + directory_candidates.push(path); + } + } + + if directory_candidates.len() == 1 { + let candidate = &directory_candidates[0]; + if candidate.join("manifest.json").exists() { + return Ok(candidate.clone()); + } + } + + Err(PackageManagerError::MissingPackageRoot( + extraction_root.to_path_buf(), + )) +} + +fn verify_sha256(bytes: &[u8], expected: &str) -> Result<(), PackageManagerError> { + let actual = format!("{:x}", Sha256::digest(bytes)); + if actual == expected.to_ascii_lowercase() { + return Ok(()); + } + Err(PackageManagerError::ChecksumMismatch { + expected: expected.to_string(), + actual, + }) +} + +fn extract_archive( + archive_path: &Path, + destination: &Path, + format: ArchiveFormat, +) -> Result<(), PackageManagerError> { + match format { + ArchiveFormat::Zip => extract_zip_archive(archive_path, destination), + ArchiveFormat::TarGz => extract_tar_gz_archive(archive_path, destination), + } +} + +fn extract_zip_archive(archive_path: &Path, destination: &Path) -> Result<(), PackageManagerError> { + let file = File::open(archive_path).map_err(|source| PackageManagerError::Io { + context: format!("failed to open {}", archive_path.display()), + source, + })?; + let mut archive = ZipArchive::new(file) + .map_err(|error| PackageManagerError::ArchiveExtraction(error.to_string()))?; + for index in 0..archive.len() { + let mut entry = archive + .by_index(index) + .map_err(|error| PackageManagerError::ArchiveExtraction(error.to_string()))?; + let Some(relative_path) = entry.enclosed_name() else { + return Err(PackageManagerError::ArchiveExtraction(format!( + "zip entry `{}` escapes extraction root", + entry.name() + ))); + }; + let output_path = destination.join(relative_path); + if entry.is_dir() { + std::fs::create_dir_all(&output_path).map_err(|source| PackageManagerError::Io { + context: format!("failed to create {}", output_path.display()), + source, + })?; + continue; + } + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent).map_err(|source| PackageManagerError::Io { + context: format!("failed to create {}", parent.display()), + source, + })?; + } + let mut output = File::create(&output_path).map_err(|source| PackageManagerError::Io { + context: format!("failed to create {}", output_path.display()), + source, + })?; + std::io::copy(&mut entry, &mut output).map_err(|source| PackageManagerError::Io { + context: format!("failed to write {}", output_path.display()), + source, + })?; + } + Ok(()) +} + +fn extract_tar_gz_archive( + archive_path: &Path, + destination: &Path, +) -> Result<(), PackageManagerError> { + let file = File::open(archive_path).map_err(|source| PackageManagerError::Io { + context: format!("failed to open {}", archive_path.display()), + source, + })?; + let decoder = GzDecoder::new(file); + let mut archive = Archive::new(decoder); + for entry in archive + .entries() + .map_err(|error| PackageManagerError::ArchiveExtraction(error.to_string()))? + { + let mut entry = + entry.map_err(|error| PackageManagerError::ArchiveExtraction(error.to_string()))?; + let path = entry + .path() + .map_err(|error| PackageManagerError::ArchiveExtraction(error.to_string()))?; + let output_path = safe_extract_path(destination, path.as_ref())?; + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent).map_err(|source| PackageManagerError::Io { + context: format!("failed to create {}", parent.display()), + source, + })?; + } + entry + .unpack(&output_path) + .map_err(|error| PackageManagerError::ArchiveExtraction(error.to_string()))?; + } + Ok(()) +} + +fn safe_extract_path(root: &Path, relative_path: &Path) -> Result { + let mut clean_relative = PathBuf::new(); + for component in relative_path.components() { + match component { + Component::Normal(segment) => clean_relative.push(segment), + Component::CurDir => {} + Component::ParentDir | Component::RootDir | Component::Prefix(_) => { + return Err(PackageManagerError::ArchiveExtraction(format!( + "entry `{}` escapes extraction root", + relative_path.display() + ))); + } + } + } + + if clean_relative.as_os_str().is_empty() { + return Err(PackageManagerError::ArchiveExtraction( + "archive entry had an empty path".to_string(), + )); + } + Ok(root.join(clean_relative)) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use serde::Deserialize; + use std::collections::BTreeMap; + use std::io::Cursor; + use std::io::Write; + use tempfile::TempDir; + use wiremock::Mock; + use wiremock::MockServer; + use wiremock::ResponseTemplate; + use wiremock::matchers::method; + use wiremock::matchers::path; + use zip::ZipWriter; + use zip::write::SimpleFileOptions; + + #[derive(Clone, Debug)] + struct TestPackage { + base_url: Url, + version: String, + } + + #[derive(Clone, Debug, Deserialize)] + struct TestReleaseManifest { + package_version: String, + platforms: BTreeMap, + } + + #[derive(Clone, Debug, PartialEq, Eq)] + struct TestInstalledPackage { + version: String, + platform: PackagePlatform, + root_dir: PathBuf, + } + + impl ManagedPackage for TestPackage { + type Error = PackageManagerError; + type Installed = TestInstalledPackage; + type ReleaseManifest = TestReleaseManifest; + + fn default_cache_root_relative(&self) -> &str { + "packages/test-package" + } + + fn version(&self) -> &str { + &self.version + } + + fn manifest_url(&self) -> Result { + self.base_url + .join(&format!("test-package-v{}-manifest.json", self.version)) + .map_err(PackageManagerError::InvalidBaseUrl) + } + + fn archive_url(&self, archive: &PackageReleaseArchive) -> Result { + self.base_url + .join(&archive.archive) + .map_err(PackageManagerError::InvalidBaseUrl) + } + + fn release_version<'a>(&self, manifest: &'a Self::ReleaseManifest) -> &'a str { + &manifest.package_version + } + + fn platform_archive( + &self, + manifest: &Self::ReleaseManifest, + platform: PackagePlatform, + ) -> Result { + manifest + .platforms + .get(platform.as_str()) + .cloned() + .ok_or_else(|| PackageManagerError::MissingPlatform(platform.as_str().to_string())) + } + + fn install_dir(&self, cache_root: &Path, platform: PackagePlatform) -> PathBuf { + cache_root.join(self.version()).join(platform.as_str()) + } + + fn installed_version<'a>(&self, package: &'a Self::Installed) -> &'a str { + &package.version + } + + fn load_installed( + &self, + root_dir: PathBuf, + platform: PackagePlatform, + ) -> Result { + let version = + std::fs::read_to_string(root_dir.join("manifest.json")).map_err(|source| { + PackageManagerError::Io { + context: format!( + "failed to read {}", + root_dir.join("manifest.json").display() + ), + source, + } + })?; + Ok(TestInstalledPackage { + version: version.trim().to_string(), + platform, + root_dir, + }) + } + } + + #[tokio::test] + async fn ensure_installed_downloads_and_extracts_zip_package() { + let server = MockServer::start().await; + let version = "0.1.0"; + let platform = PackagePlatform::detect_current().unwrap_or_else(|error| panic!("{error}")); + let archive_name = format!("test-package-v{version}-{}.zip", platform.as_str()); + let archive_bytes = build_zip_archive(version); + let archive_sha = format!("{:x}", Sha256::digest(&archive_bytes)); + let manifest = serde_json::json!({ + "package_version": version, + "platforms": { + platform.as_str(): { + "archive": archive_name, + "sha256": archive_sha, + "format": "zip", + "size_bytes": archive_bytes.len(), + } + } + }); + Mock::given(method("GET")) + .and(path(format!("/test-package-v{version}-manifest.json"))) + .respond_with(ResponseTemplate::new(200).set_body_json(&manifest)) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/{archive_name}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(archive_bytes)) + .mount(&server) + .await; + + let codex_home = TempDir::new().unwrap_or_else(|error| panic!("{error}")); + let package = TestPackage { + base_url: Url::parse(&format!("{}/", server.uri())) + .unwrap_or_else(|error| panic!("{error}")), + version: version.to_string(), + }; + let manager = PackageManager::new(PackageManagerConfig::new( + codex_home.path().to_path_buf(), + package, + )); + + let installed = manager + .ensure_installed() + .await + .unwrap_or_else(|error| panic!("{error}")); + + assert_eq!( + installed, + TestInstalledPackage { + version: version.to_string(), + platform, + root_dir: codex_home + .path() + .join("packages") + .join("test-package") + .join(version) + .join(platform.as_str()), + } + ); + } + + #[test] + fn tar_gz_extraction_supports_default_package_root_detection() { + let temp = TempDir::new().unwrap_or_else(|error| panic!("{error}")); + let archive_path = temp.path().join("package.tar.gz"); + let extraction_root = temp.path().join("extract"); + std::fs::create_dir_all(&extraction_root).unwrap_or_else(|error| panic!("{error}")); + write_tar_gz_archive(&archive_path, "0.2.0"); + + extract_archive(&archive_path, &extraction_root, ArchiveFormat::TarGz) + .unwrap_or_else(|error| panic!("{error}")); + let package_root = + detect_single_package_root(&extraction_root).unwrap_or_else(|error| panic!("{error}")); + + assert!(package_root.join("manifest.json").exists()); + } + + fn build_zip_archive(version: &str) -> Vec { + let mut bytes = Cursor::new(Vec::new()); + { + let mut zip = ZipWriter::new(&mut bytes); + let options = SimpleFileOptions::default(); + zip.start_file("test-package/manifest.json", options) + .unwrap_or_else(|error| panic!("{error}")); + zip.write_all(version.as_bytes()) + .unwrap_or_else(|error| panic!("{error}")); + zip.finish().unwrap_or_else(|error| panic!("{error}")); + } + bytes.into_inner() + } + + fn write_tar_gz_archive(archive_path: &Path, version: &str) { + let file = File::create(archive_path).unwrap_or_else(|error| panic!("{error}")); + let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default()); + let mut builder = tar::Builder::new(encoder); + + append_tar_file( + &mut builder, + "test-package/manifest.json", + version.as_bytes(), + ); + builder.finish().unwrap_or_else(|error| panic!("{error}")); + } + + fn append_tar_file( + builder: &mut tar::Builder>, + path: &str, + contents: &[u8], + ) { + let mut header = tar::Header::new_gnu(); + header.set_size(contents.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + builder + .append_data(&mut header, path, contents) + .unwrap_or_else(|error| panic!("{error}")); + } +} From 8dfd654196c36b26cd12ac348f5a8a9b688f38ca Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Wed, 4 Mar 2026 13:30:09 -0800 Subject: [PATCH 382/385] feat(app-server-test-client): OTEL setup for tracing (#13493) ### Overview This PR: - Updates `app-server-test-client` to load OTEL settings from `$CODEX_HOME/config.toml` and initializes its own OTEL provider. - Add real client root spans to app-server test client traces. This updates `codex-app-server-test-client` so its Datadog traces reflect the full client-driven flow instead of a set of server spans stitched together under a synthetic parent. Before this change, the test client generated a fake `traceparent` once and reused it for every JSON-RPC request. That kept the requests in one trace, but there was no real client span at the top, so Datadog ended up showing the sequence in a slightly misleading way, where all RPCs were anchored under `initialize`. Now the test client: - loads OTEL settings from the normal Codex config path, including `$CODEX_HOME/config.toml` and existing --config overrides - initializes tracing the same way other Codex binaries do when trace export is enabled - creates a real client root span for each scripted command - creates per-request client spans for JSON-RPC methods like `initialize`, `thread/start`, and `turn/start` - injects W3C trace context from the current client span into request.trace instead of reusing a fabricated carrier This gives us a cleaner trace shape in Datadog: - one trace URL for the whole scripted flow - a visible client root span - proper client/server parent-child relationships for each app-server request --- codex-rs/Cargo.lock | 6 + .../schema/json/ClientRequest.json | 2 +- .../codex_app_server_protocol.schemas.json | 2 +- .../codex_app_server_protocol.v2.schemas.json | 2 +- .../v2/WindowsSandboxSetupStartParams.json | 2 +- codex-rs/app-server-test-client/Cargo.toml | 6 + codex-rs/app-server-test-client/src/lib.rs | 578 +++++++++++------- codex-rs/app-server-test-client/src/main.rs | 4 +- codex-rs/cli/src/main.rs | 5 +- 9 files changed, 379 insertions(+), 228 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index ba3156dadd..ab8743e843 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1490,9 +1490,15 @@ dependencies = [ "anyhow", "clap", "codex-app-server-protocol", + "codex-core", + "codex-otel", "codex-protocol", + "codex-utils-cli", "serde", "serde_json", + "tokio", + "tracing", + "tracing-subscriber", "tungstenite", "url", "uuid", diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 62495a79a1..0e3c68de39 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -3914,4 +3914,4 @@ } ], "title": "ClientRequest" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index f09f2fc553..86cbda2810 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -15391,4 +15391,4 @@ }, "title": "CodexAppServerProtocol", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 7f37aaecb9..3428205999 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -14291,4 +14291,4 @@ }, "title": "CodexAppServerProtocolV2", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json index 663d360649..00edc8b02e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/WindowsSandboxSetupStartParams.json @@ -25,4 +25,4 @@ ], "title": "WindowsSandboxSetupStartParams", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-test-client/Cargo.toml b/codex-rs/app-server-test-client/Cargo.toml index 05c8938f05..32d2588fdf 100644 --- a/codex-rs/app-server-test-client/Cargo.toml +++ b/codex-rs/app-server-test-client/Cargo.toml @@ -11,9 +11,15 @@ workspace = true anyhow = { workspace = true } clap = { workspace = true, features = ["derive", "env"] } codex-app-server-protocol = { workspace = true } +codex-core = { workspace = true } +codex-otel = { workspace = true } codex-protocol = { workspace = true } +codex-utils-cli = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } +tokio = { workspace = true, features = ["rt"] } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } tungstenite = { workspace = true } url = { workspace = true } uuid = { workspace = true, features = ["v4"] } diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index 06f677ceb7..28579c6c8f 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -62,10 +62,17 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as V2UserInput; +use codex_core::config::Config; +use codex_otel::current_span_w3c_trace_context; +use codex_otel::otel_provider::OtelProvider; use codex_protocol::protocol::W3cTraceContext; +use codex_utils_cli::CliConfigOverrides; use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::Value; +use tracing::info_span; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; use tungstenite::Message; use tungstenite::WebSocket; use tungstenite::connect; @@ -98,6 +105,10 @@ const NOTIFICATIONS_TO_OPT_OUT: &[&str] = &[ ]; const APP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5); const APP_SERVER_GRACEFUL_SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100); +const DEFAULT_ANALYTICS_ENABLED: bool = true; +const OTEL_SERVICE_NAME: &str = "codex-app-server-test-client"; +const TRACE_DISABLED_MESSAGE: &str = + "Not enabled - enable tracing in $CODEX_HOME/config.toml to get a trace URL!"; /// Minimal launcher that initializes the Codex app-server and logs the handshake. #[derive(Parser)] @@ -236,7 +247,7 @@ enum CliCommand { }, } -pub fn run() -> Result<()> { +pub async fn run() -> Result<()> { let Cli { codex_bin, url, @@ -256,7 +267,7 @@ pub fn run() -> Result<()> { CliCommand::SendMessage { user_message } => { ensure_dynamic_tools_unused(&dynamic_tools, "send-message")?; let endpoint = resolve_endpoint(codex_bin, url)?; - send_message(&endpoint, &config_overrides, user_message) + send_message(&endpoint, &config_overrides, user_message).await } CliCommand::SendMessageV2 { experimental_api, @@ -270,6 +281,7 @@ pub fn run() -> Result<()> { experimental_api, &dynamic_tools, ) + .await } CliCommand::ResumeMessageV2 { thread_id, @@ -283,28 +295,29 @@ pub fn run() -> Result<()> { user_message, &dynamic_tools, ) + .await } CliCommand::ThreadResume { thread_id } => { ensure_dynamic_tools_unused(&dynamic_tools, "thread-resume")?; let endpoint = resolve_endpoint(codex_bin, url)?; - thread_resume_follow(&endpoint, &config_overrides, thread_id) + thread_resume_follow(&endpoint, &config_overrides, thread_id).await } CliCommand::Watch => { ensure_dynamic_tools_unused(&dynamic_tools, "watch")?; let endpoint = resolve_endpoint(codex_bin, url)?; - watch(&endpoint, &config_overrides) + watch(&endpoint, &config_overrides).await } CliCommand::TriggerCmdApproval { user_message } => { let endpoint = resolve_endpoint(codex_bin, url)?; - trigger_cmd_approval(&endpoint, &config_overrides, user_message, &dynamic_tools) + trigger_cmd_approval(&endpoint, &config_overrides, user_message, &dynamic_tools).await } CliCommand::TriggerPatchApproval { user_message } => { let endpoint = resolve_endpoint(codex_bin, url)?; - trigger_patch_approval(&endpoint, &config_overrides, user_message, &dynamic_tools) + trigger_patch_approval(&endpoint, &config_overrides, user_message, &dynamic_tools).await } CliCommand::NoTriggerCmdApproval => { let endpoint = resolve_endpoint(codex_bin, url)?; - no_trigger_cmd_approval(&endpoint, &config_overrides, &dynamic_tools) + no_trigger_cmd_approval(&endpoint, &config_overrides, &dynamic_tools).await } CliCommand::SendFollowUpV2 { first_message, @@ -318,6 +331,7 @@ pub fn run() -> Result<()> { follow_up_message, &dynamic_tools, ) + .await } CliCommand::TriggerZshForkMultiCmdApproval { user_message, @@ -333,26 +347,27 @@ pub fn run() -> Result<()> { abort_on, &dynamic_tools, ) + .await } CliCommand::TestLogin => { ensure_dynamic_tools_unused(&dynamic_tools, "test-login")?; let endpoint = resolve_endpoint(codex_bin, url)?; - test_login(&endpoint, &config_overrides) + test_login(&endpoint, &config_overrides).await } CliCommand::GetAccountRateLimits => { ensure_dynamic_tools_unused(&dynamic_tools, "get-account-rate-limits")?; let endpoint = resolve_endpoint(codex_bin, url)?; - get_account_rate_limits(&endpoint, &config_overrides) + get_account_rate_limits(&endpoint, &config_overrides).await } CliCommand::ModelList => { ensure_dynamic_tools_unused(&dynamic_tools, "model-list")?; let endpoint = resolve_endpoint(codex_bin, url)?; - model_list(&endpoint, &config_overrides) + model_list(&endpoint, &config_overrides).await } CliCommand::ThreadList { limit } => { ensure_dynamic_tools_unused(&dynamic_tools, "thread-list")?; let endpoint = resolve_endpoint(codex_bin, url)?; - thread_list(&endpoint, &config_overrides, limit) + thread_list(&endpoint, &config_overrides, limit).await } } } @@ -487,7 +502,15 @@ fn shell_quote(input: &str) -> String { format!("'{}'", input.replace('\'', "'\\''")) } -fn send_message( +struct SendMessagePolicies<'a> { + command_name: &'static str, + experimental_api: bool, + approval_policy: Option, + sandbox_policy: Option, + dynamic_tools: &'a Option>, +} + +async fn send_message( endpoint: &Endpoint, config_overrides: &[String], user_message: String, @@ -497,14 +520,18 @@ fn send_message( endpoint, config_overrides, user_message, - false, - None, - None, - &dynamic_tools, + SendMessagePolicies { + command_name: "send-message", + experimental_api: false, + approval_policy: None, + sandbox_policy: None, + dynamic_tools: &dynamic_tools, + }, ) + .await } -pub fn send_message_v2( +pub async fn send_message_v2( codex_bin: &Path, config_overrides: &[String], user_message: String, @@ -518,9 +545,10 @@ pub fn send_message_v2( true, dynamic_tools, ) + .await } -fn send_message_v2_endpoint( +async fn send_message_v2_endpoint( endpoint: &Endpoint, config_overrides: &[String], user_message: String, @@ -535,14 +563,18 @@ fn send_message_v2_endpoint( endpoint, config_overrides, user_message, - experimental_api, - None, - None, - dynamic_tools, + SendMessagePolicies { + command_name: "send-message-v2", + experimental_api, + approval_policy: None, + sandbox_policy: None, + dynamic_tools, + }, ) + .await } -fn trigger_zsh_fork_multi_cmd_approval( +async fn trigger_zsh_fork_multi_cmd_approval( endpoint: &Endpoint, config_overrides: &[String], user_message: Option, @@ -559,89 +591,96 @@ fn trigger_zsh_fork_multi_cmd_approval( let default_prompt = "Run this exact command using shell command execution without rewriting or splitting it: /usr/bin/true && /usr/bin/true"; let message = user_message.unwrap_or_else(|| default_prompt.to_string()); - with_client(endpoint, config_overrides, |client| { - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + with_client( + "trigger-zsh-fork-multi-cmd-approval", + endpoint, + config_overrides, + |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let thread_response = client.thread_start(ThreadStartParams { - dynamic_tools: dynamic_tools.clone(), - ..Default::default() - })?; - println!("< thread/start response: {thread_response:?}"); + let thread_response = client.thread_start(ThreadStartParams { + dynamic_tools: dynamic_tools.clone(), + ..Default::default() + })?; + println!("< thread/start response: {thread_response:?}"); - client.command_approval_behavior = match abort_on { - Some(index) => CommandApprovalBehavior::AbortOn(index), - None => CommandApprovalBehavior::AlwaysAccept, - }; - client.command_approval_count = 0; - client.command_approval_item_ids.clear(); - client.command_execution_statuses.clear(); - client.last_turn_status = None; + client.command_approval_behavior = match abort_on { + Some(index) => CommandApprovalBehavior::AbortOn(index), + None => CommandApprovalBehavior::AlwaysAccept, + }; + client.command_approval_count = 0; + client.command_approval_item_ids.clear(); + client.command_execution_statuses.clear(); + client.last_turn_status = None; - let mut turn_params = TurnStartParams { - thread_id: thread_response.thread.id.clone(), - input: vec![V2UserInput::Text { - text: message, - text_elements: Vec::new(), - }], - ..Default::default() - }; - turn_params.approval_policy = Some(AskForApproval::OnRequest); - turn_params.sandbox_policy = Some(SandboxPolicy::ReadOnly { - access: ReadOnlyAccess::FullAccess, - network_access: false, - }); + let mut turn_params = TurnStartParams { + thread_id: thread_response.thread.id.clone(), + input: vec![V2UserInput::Text { + text: message, + text_elements: Vec::new(), + }], + ..Default::default() + }; + turn_params.approval_policy = Some(AskForApproval::OnRequest); + turn_params.sandbox_policy = Some(SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + network_access: false, + }); - let turn_response = client.turn_start(turn_params)?; - println!("< turn/start response: {turn_response:?}"); - client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; + let turn_response = client.turn_start(turn_params)?; + println!("< turn/start response: {turn_response:?}"); + client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; - if client.command_approval_count < min_approvals { - bail!( - "expected at least {min_approvals} command approvals, got {}", - client.command_approval_count - ); - } - let mut approvals_per_item = std::collections::BTreeMap::new(); - for item_id in &client.command_approval_item_ids { - *approvals_per_item.entry(item_id.clone()).or_insert(0usize) += 1; - } - let max_approvals_for_one_item = approvals_per_item.values().copied().max().unwrap_or(0); - if max_approvals_for_one_item < min_approvals { - bail!( - "expected at least {min_approvals} approvals for one command item, got max {max_approvals_for_one_item} with map {approvals_per_item:?}" - ); - } - - let last_command_status = client.command_execution_statuses.last(); - if abort_on.is_none() { - if last_command_status != Some(&CommandExecutionStatus::Completed) { - bail!("expected completed command execution, got {last_command_status:?}"); - } - if client.last_turn_status != Some(TurnStatus::Completed) { + if client.command_approval_count < min_approvals { bail!( - "expected completed turn in all-accept flow, got {:?}", - client.last_turn_status + "expected at least {min_approvals} command approvals, got {}", + client.command_approval_count ); } - } else if last_command_status == Some(&CommandExecutionStatus::Completed) { - bail!( - "expected non-completed command execution in mixed approval/decline flow, got {last_command_status:?}" + let mut approvals_per_item = std::collections::BTreeMap::new(); + for item_id in &client.command_approval_item_ids { + *approvals_per_item.entry(item_id.clone()).or_insert(0usize) += 1; + } + let max_approvals_for_one_item = + approvals_per_item.values().copied().max().unwrap_or(0); + if max_approvals_for_one_item < min_approvals { + bail!( + "expected at least {min_approvals} approvals for one command item, got max {max_approvals_for_one_item} with map {approvals_per_item:?}" + ); + } + + let last_command_status = client.command_execution_statuses.last(); + if abort_on.is_none() { + if last_command_status != Some(&CommandExecutionStatus::Completed) { + bail!("expected completed command execution, got {last_command_status:?}"); + } + if client.last_turn_status != Some(TurnStatus::Completed) { + bail!( + "expected completed turn in all-accept flow, got {:?}", + client.last_turn_status + ); + } + } else if last_command_status == Some(&CommandExecutionStatus::Completed) { + bail!( + "expected non-completed command execution in mixed approval/decline flow, got {last_command_status:?}" + ); + } + + println!( + "[zsh-fork multi-approval summary] approvals={}, approvals_per_item={approvals_per_item:?}, command_statuses={:?}, turn_status={:?}", + client.command_approval_count, + client.command_execution_statuses, + client.last_turn_status ); - } - println!( - "[zsh-fork multi-approval summary] approvals={}, approvals_per_item={approvals_per_item:?}, command_statuses={:?}, turn_status={:?}", - client.command_approval_count, - client.command_execution_statuses, - client.last_turn_status - ); - - Ok(()) - }) + Ok(()) + }, + ) + .await } -fn resume_message_v2( +async fn resume_message_v2( endpoint: &Endpoint, config_overrides: &[String], thread_id: String, @@ -650,7 +689,7 @@ fn resume_message_v2( ) -> Result<()> { ensure_dynamic_tools_unused(dynamic_tools, "resume-message-v2")?; - with_client(endpoint, config_overrides, |client| { + with_client("resume-message-v2", endpoint, config_overrides, |client| { let initialize = client.initialize()?; println!("< initialize response: {initialize:?}"); @@ -674,39 +713,42 @@ fn resume_message_v2( Ok(()) }) + .await } -fn thread_resume_follow( +async fn thread_resume_follow( endpoint: &Endpoint, config_overrides: &[String], thread_id: String, ) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; + with_client("thread-resume", endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + let resume_response = client.thread_resume(ThreadResumeParams { + thread_id, + ..Default::default() + })?; + println!("< thread/resume response: {resume_response:?}"); + println!("< streaming notifications until process is terminated"); - let resume_response = client.thread_resume(ThreadResumeParams { - thread_id, - ..Default::default() - })?; - println!("< thread/resume response: {resume_response:?}"); - println!("< streaming notifications until process is terminated"); - - client.stream_notifications_forever() + client.stream_notifications_forever() + }) + .await } -fn watch(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; +async fn watch(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { + with_client("watch", endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); + println!("< streaming inbound messages until process is terminated"); - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); - println!("< streaming inbound messages until process is terminated"); - - client.stream_notifications_forever() + client.stream_notifications_forever() + }) + .await } -fn trigger_cmd_approval( +async fn trigger_cmd_approval( endpoint: &Endpoint, config_overrides: &[String], user_message: Option, @@ -719,17 +761,21 @@ fn trigger_cmd_approval( endpoint, config_overrides, message, - true, - Some(AskForApproval::OnRequest), - Some(SandboxPolicy::ReadOnly { - access: ReadOnlyAccess::FullAccess, - network_access: false, - }), - dynamic_tools, + SendMessagePolicies { + command_name: "trigger-cmd-approval", + experimental_api: true, + approval_policy: Some(AskForApproval::OnRequest), + sandbox_policy: Some(SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + network_access: false, + }), + dynamic_tools, + }, ) + .await } -fn trigger_patch_approval( +async fn trigger_patch_approval( endpoint: &Endpoint, config_overrides: &[String], user_message: Option, @@ -742,17 +788,21 @@ fn trigger_patch_approval( endpoint, config_overrides, message, - true, - Some(AskForApproval::OnRequest), - Some(SandboxPolicy::ReadOnly { - access: ReadOnlyAccess::FullAccess, - network_access: false, - }), - dynamic_tools, + SendMessagePolicies { + command_name: "trigger-patch-approval", + experimental_api: true, + approval_policy: Some(AskForApproval::OnRequest), + sandbox_policy: Some(SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + network_access: false, + }), + dynamic_tools, + }, ) + .await } -fn no_trigger_cmd_approval( +async fn no_trigger_cmd_approval( endpoint: &Endpoint, config_overrides: &[String], dynamic_tools: &Option>, @@ -762,60 +812,67 @@ fn no_trigger_cmd_approval( endpoint, config_overrides, prompt.to_string(), - true, - None, - None, - dynamic_tools, + SendMessagePolicies { + command_name: "no-trigger-cmd-approval", + experimental_api: true, + approval_policy: None, + sandbox_policy: None, + dynamic_tools, + }, ) + .await } -fn send_message_v2_with_policies( +async fn send_message_v2_with_policies( endpoint: &Endpoint, config_overrides: &[String], user_message: String, - experimental_api: bool, - approval_policy: Option, - sandbox_policy: Option, - dynamic_tools: &Option>, + policies: SendMessagePolicies<'_>, ) -> Result<()> { - with_client(endpoint, config_overrides, |client| { - let initialize = client.initialize_with_experimental_api(experimental_api)?; - println!("< initialize response: {initialize:?}"); + with_client( + policies.command_name, + endpoint, + config_overrides, + |client| { + let initialize = client.initialize_with_experimental_api(policies.experimental_api)?; + println!("< initialize response: {initialize:?}"); - let thread_response = client.thread_start(ThreadStartParams { - dynamic_tools: dynamic_tools.clone(), - ..Default::default() - })?; - println!("< thread/start response: {thread_response:?}"); - let mut turn_params = TurnStartParams { - thread_id: thread_response.thread.id.clone(), - input: vec![V2UserInput::Text { - text: user_message, - // Test client sends plain text without UI element ranges. - text_elements: Vec::new(), - }], - ..Default::default() - }; - turn_params.approval_policy = approval_policy; - turn_params.sandbox_policy = sandbox_policy; + let thread_response = client.thread_start(ThreadStartParams { + dynamic_tools: policies.dynamic_tools.clone(), + ..Default::default() + })?; + println!("< thread/start response: {thread_response:?}"); + let mut turn_params = TurnStartParams { + thread_id: thread_response.thread.id.clone(), + input: vec![V2UserInput::Text { + text: user_message, + // Test client sends plain text without UI element ranges. + text_elements: Vec::new(), + }], + ..Default::default() + }; + turn_params.approval_policy = policies.approval_policy; + turn_params.sandbox_policy = policies.sandbox_policy; - let turn_response = client.turn_start(turn_params)?; - println!("< turn/start response: {turn_response:?}"); + let turn_response = client.turn_start(turn_params)?; + println!("< turn/start response: {turn_response:?}"); - client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; + client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; - Ok(()) - }) + Ok(()) + }, + ) + .await } -fn send_follow_up_v2( +async fn send_follow_up_v2( endpoint: &Endpoint, config_overrides: &[String], first_message: String, follow_up_message: String, dynamic_tools: &Option>, ) -> Result<()> { - with_client(endpoint, config_overrides, |client| { + with_client("send-follow-up-v2", endpoint, config_overrides, |client| { let initialize = client.initialize()?; println!("< initialize response: {initialize:?}"); @@ -853,10 +910,11 @@ fn send_follow_up_v2( Ok(()) }) + .await } -fn test_login(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { - with_client(endpoint, config_overrides, |client| { +async fn test_login(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { + with_client("test-login", endpoint, config_overrides, |client| { let initialize = client.initialize()?; println!("< initialize response: {initialize:?}"); @@ -883,22 +941,29 @@ fn test_login(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { ); } }) + .await } -fn get_account_rate_limits(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { - with_client(endpoint, config_overrides, |client| { - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); +async fn get_account_rate_limits(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { + with_client( + "get-account-rate-limits", + endpoint, + config_overrides, + |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let response = client.get_account_rate_limits()?; - println!("< account/rateLimits/read response: {response:?}"); + let response = client.get_account_rate_limits()?; + println!("< account/rateLimits/read response: {response:?}"); - Ok(()) - }) + Ok(()) + }, + ) + .await } -fn model_list(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { - with_client(endpoint, config_overrides, |client| { +async fn model_list(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { + with_client("model-list", endpoint, config_overrides, |client| { let initialize = client.initialize()?; println!("< initialize response: {initialize:?}"); @@ -907,10 +972,11 @@ fn model_list(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { Ok(()) }) + .await } -fn thread_list(endpoint: &Endpoint, config_overrides: &[String], limit: u32) -> Result<()> { - with_client(endpoint, config_overrides, |client| { +async fn thread_list(endpoint: &Endpoint, config_overrides: &[String], limit: u32) -> Result<()> { + with_client("thread-list", endpoint, config_overrides, |client| { let initialize = client.initialize()?; println!("< initialize response: {initialize:?}"); @@ -928,16 +994,28 @@ fn thread_list(endpoint: &Endpoint, config_overrides: &[String], limit: u32) -> Ok(()) }) + .await } -fn with_client( +async fn with_client( + command_name: &'static str, endpoint: &Endpoint, config_overrides: &[String], f: impl FnOnce(&mut CodexClient) -> Result, ) -> Result { - let mut client = CodexClient::connect(endpoint, config_overrides)?; - let result = f(&mut client); - client.print_trace_summary(); + let tracing = TestClientTracing::initialize(config_overrides).await?; + let command_span = info_span!( + "app_server_test_client.command", + otel.kind = "client", + otel.name = command_name, + app_server_test_client.command = command_name, + ); + let trace_summary = command_span.in_scope(|| TraceSummary::capture(tracing.traces_enabled)); + let result = command_span.in_scope(|| { + let mut client = CodexClient::connect(endpoint, config_overrides)?; + f(&mut client) + }); + print_trace_summary(&trace_summary); result } @@ -995,8 +1073,6 @@ struct CodexClient { command_approval_item_ids: Vec, command_execution_statuses: Vec, last_turn_status: Option, - trace_id: String, - trace_root_span_id: String, } #[derive(Debug, Clone, Copy)] @@ -1056,8 +1132,6 @@ impl CodexClient { command_approval_item_ids: Vec::new(), command_execution_statuses: Vec::new(), last_turn_status: None, - trace_id: generate_trace_id(), - trace_root_span_id: generate_parent_span_id(), }) } @@ -1079,8 +1153,6 @@ impl CodexClient { command_approval_item_ids: Vec::new(), command_execution_statuses: Vec::new(), last_turn_status: None, - trace_id: generate_trace_id(), - trace_root_span_id: generate_parent_span_id(), }) } @@ -1302,37 +1374,31 @@ impl CodexClient { where T: DeserializeOwned, { - self.write_request(&request)?; - self.wait_for_response(request_id, method) + let request_span = info_span!( + "app_server_test_client.request", + otel.kind = "client", + otel.name = method, + rpc.system = "jsonrpc", + rpc.method = method, + rpc.request_id = ?request_id, + ); + request_span.in_scope(|| { + self.write_request(&request)?; + self.wait_for_response(request_id, method) + }) } fn write_request(&mut self, request: &ClientRequest) -> Result<()> { - let request = self.jsonrpc_request_with_trace(request)?; + let request_value = serde_json::to_value(request)?; + let mut request: JSONRPCRequest = serde_json::from_value(request_value) + .context("client request was not a valid JSON-RPC request")?; + request.trace = current_span_w3c_trace_context(); let request_json = serde_json::to_string(&request)?; let request_pretty = serde_json::to_string_pretty(&request)?; print_multiline_with_prefix("> ", &request_pretty); self.write_payload(&request_json) } - fn jsonrpc_request_with_trace(&self, request: &ClientRequest) -> Result { - let request_value = serde_json::to_value(request)?; - let mut request: JSONRPCRequest = serde_json::from_value(request_value) - .context("client request was not a valid JSON-RPC request")?; - request.trace = Some(W3cTraceContext { - traceparent: Some(format!( - "00-{}-{}-01", - self.trace_id, self.trace_root_span_id - )), - tracestate: None, - }); - Ok(request) - } - - fn print_trace_summary(&self) { - println!("\n[Datadog trace]"); - println!("go/trace/{}\n", self.trace_id); - } - fn wait_for_response(&mut self, request_id: RequestId, method: &str) -> Result where T: DeserializeOwned, @@ -1598,21 +1664,91 @@ impl CodexClient { } } -fn generate_trace_id() -> String { - Uuid::new_v4().simple().to_string() -} - -fn generate_parent_span_id() -> String { - let uuid = Uuid::new_v4().simple().to_string(); - uuid[..16].to_string() -} - fn print_multiline_with_prefix(prefix: &str, payload: &str) { for line in payload.lines() { println!("{prefix}{line}"); } } +struct TestClientTracing { + _otel_provider: Option, + traces_enabled: bool, +} + +impl TestClientTracing { + async fn initialize(config_overrides: &[String]) -> Result { + let cli_kv_overrides = CliConfigOverrides { + raw_overrides: config_overrides.to_vec(), + } + .parse_overrides() + .map_err(|e| anyhow::anyhow!("error parsing -c overrides: {e}"))?; + let config = Config::load_with_cli_overrides(cli_kv_overrides) + .await + .context("error loading config")?; + let otel_provider = codex_core::otel_init::build_provider( + &config, + env!("CARGO_PKG_VERSION"), + Some(OTEL_SERVICE_NAME), + DEFAULT_ANALYTICS_ENABLED, + ) + .map_err(|e| anyhow::anyhow!("error loading otel config: {e}"))?; + let traces_enabled = otel_provider + .as_ref() + .and_then(|provider| provider.tracer_provider.as_ref()) + .is_some(); + if let Some(provider) = otel_provider.as_ref() + && traces_enabled + { + let _ = tracing_subscriber::registry() + .with(provider.tracing_layer()) + .try_init(); + } + Ok(Self { + traces_enabled, + _otel_provider: otel_provider, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum TraceSummary { + Enabled { url: String }, + Disabled, +} + +impl TraceSummary { + fn capture(traces_enabled: bool) -> Self { + if !traces_enabled { + return Self::Disabled; + } + current_span_w3c_trace_context() + .as_ref() + .and_then(trace_url_from_context) + .map_or(Self::Disabled, |url| Self::Enabled { url }) + } +} + +fn trace_url_from_context(trace: &W3cTraceContext) -> Option { + let traceparent = trace.traceparent.as_deref()?; + let mut parts = traceparent.split('-'); + match (parts.next(), parts.next(), parts.next(), parts.next()) { + (Some(_version), Some(trace_id), Some(_span_id), Some(_trace_flags)) + if trace_id.len() == 32 => + { + Some(format!("go/trace/{trace_id}")) + } + _ => None, + } +} + +fn print_trace_summary(trace_summary: &TraceSummary) { + println!("\n[Datadog trace]"); + match trace_summary { + TraceSummary::Enabled { url } => println!("{url}\n"), + TraceSummary::Disabled => println!("{TRACE_DISABLED_MESSAGE}\n"), + } +} + impl Drop for CodexClient { fn drop(&mut self) { let ClientTransport::Stdio { child, stdin, .. } = &mut self.transport else { diff --git a/codex-rs/app-server-test-client/src/main.rs b/codex-rs/app-server-test-client/src/main.rs index a4da2e4026..794bede1c2 100644 --- a/codex-rs/app-server-test-client/src/main.rs +++ b/codex-rs/app-server-test-client/src/main.rs @@ -1,5 +1,7 @@ use anyhow::Result; +use tokio::runtime::Builder; fn main() -> Result<()> { - codex_app_server_test_client::run() + let runtime = Builder::new_current_thread().enable_all().build()?; + runtime.block_on(codex_app_server_test_client::run()) } diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index f818b743e9..41b8361862 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -473,11 +473,12 @@ fn run_execpolicycheck(cmd: ExecPolicyCheckCommand) -> anyhow::Result<()> { cmd.run() } -fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Result<()> { +async fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Result<()> { match cmd.subcommand { DebugAppServerSubcommand::SendMessageV2(cmd) => { let codex_bin = std::env::current_exe()?; codex_app_server_test_client::send_message_v2(&codex_bin, &[], cmd.user_message, &None) + .await } } } @@ -755,7 +756,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { }, Some(Subcommand::Debug(DebugCommand { subcommand })) => match subcommand { DebugSubcommand::AppServer(cmd) => { - run_debug_app_server_command(cmd)?; + run_debug_app_server_command(cmd).await?; } DebugSubcommand::ClearMemories => { run_debug_clear_memories_command(&root_config_overrides, &interactive).await?; From ce139bb1afade875eaf8d1fb477b58062be9d896 Mon Sep 17 00:00:00 2001 From: alexsong-oai Date: Wed, 4 Mar 2026 13:59:50 -0800 Subject: [PATCH 383/385] add metrics for external config import (#13501) --- codex-rs/core/src/external_agent_config.rs | 128 ++++++++++++++++++--- 1 file changed, 115 insertions(+), 13 deletions(-) diff --git a/codex-rs/core/src/external_agent_config.rs b/codex-rs/core/src/external_agent_config.rs index d0fde766f5..24319fe064 100644 --- a/codex-rs/core/src/external_agent_config.rs +++ b/codex-rs/core/src/external_agent_config.rs @@ -7,6 +7,9 @@ use std::path::Path; use std::path::PathBuf; use toml::Value as TomlValue; +const EXTERNAL_AGENT_CONFIG_DETECT_METRIC: &str = "codex.external_agent_config.detect"; +const EXTERNAL_AGENT_CONFIG_IMPORT_METRIC: &str = "codex.external_agent_config.import"; + #[derive(Debug, Clone, PartialEq, Eq)] pub struct ExternalAgentConfigDetectOptions { pub include_home: bool, @@ -74,13 +77,28 @@ impl ExternalAgentConfigService { for migration_item in migration_items { match migration_item.item_type { ExternalAgentConfigMigrationItemType::Config => { - self.import_config(migration_item.cwd.as_deref())? + self.import_config(migration_item.cwd.as_deref())?; + emit_migration_metric( + EXTERNAL_AGENT_CONFIG_IMPORT_METRIC, + ExternalAgentConfigMigrationItemType::Config, + None, + ); } ExternalAgentConfigMigrationItemType::Skills => { - self.import_skills(migration_item.cwd.as_deref())? + let skills_count = self.import_skills(migration_item.cwd.as_deref())?; + emit_migration_metric( + EXTERNAL_AGENT_CONFIG_IMPORT_METRIC, + ExternalAgentConfigMigrationItemType::Skills, + Some(skills_count), + ); } ExternalAgentConfigMigrationItemType::AgentsMd => { - self.import_agents_md(migration_item.cwd.as_deref())? + self.import_agents_md(migration_item.cwd.as_deref())?; + emit_migration_metric( + EXTERNAL_AGENT_CONFIG_IMPORT_METRIC, + ExternalAgentConfigMigrationItemType::AgentsMd, + None, + ); } ExternalAgentConfigMigrationItemType::McpServerConfig => {} } @@ -132,6 +150,11 @@ impl ExternalAgentConfigService { ), cwd: cwd.clone(), }); + emit_migration_metric( + EXTERNAL_AGENT_CONFIG_DETECT_METRIC, + ExternalAgentConfigMigrationItemType::Config, + None, + ); } } } @@ -144,12 +167,8 @@ impl ExternalAgentConfigService { || self.home_target_skills_dir(), |repo_root| repo_root.join(".agents").join("skills"), ); - let source_skill_names = collect_subdirectory_names(&source_skills)?; - let target_skill_names = collect_subdirectory_names(&target_skills)?; - if source_skill_names - .iter() - .any(|skill_name| !target_skill_names.contains(skill_name)) - { + let skills_count = count_missing_subdirectories(&source_skills, &target_skills)?; + if skills_count > 0 { items.push(ExternalAgentConfigMigrationItem { item_type: ExternalAgentConfigMigrationItemType::Skills, description: format!( @@ -159,6 +178,11 @@ impl ExternalAgentConfigService { ), cwd: cwd.clone(), }); + emit_migration_metric( + EXTERNAL_AGENT_CONFIG_DETECT_METRIC, + ExternalAgentConfigMigrationItemType::Skills, + Some(skills_count), + ); } let source_agents_md = if let Some(repo_root) = repo_root { @@ -183,6 +207,11 @@ impl ExternalAgentConfigService { ), cwd, }); + emit_migration_metric( + EXTERNAL_AGENT_CONFIG_DETECT_METRIC, + ExternalAgentConfigMigrationItemType::AgentsMd, + None, + ); } Ok(()) @@ -247,14 +276,14 @@ impl ExternalAgentConfigService { Ok(()) } - fn import_skills(&self, cwd: Option<&Path>) -> io::Result<()> { + fn import_skills(&self, cwd: Option<&Path>) -> io::Result { let (source_skills, target_skills) = if let Some(repo_root) = find_repo_root(cwd)? { ( repo_root.join(".claude").join("skills"), repo_root.join(".agents").join("skills"), ) } else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) { - return Ok(()); + return Ok(0); } else { ( self.claude_home.join("skills"), @@ -262,10 +291,11 @@ impl ExternalAgentConfigService { ) }; if !source_skills.is_dir() { - return Ok(()); + return Ok(0); } fs::create_dir_all(&target_skills)?; + let mut copied_count = 0usize; for entry in fs::read_dir(&source_skills)? { let entry = entry?; @@ -280,9 +310,10 @@ impl ExternalAgentConfigService { } copy_dir_recursive(&entry.path(), &target)?; + copied_count += 1; } - Ok(()) + Ok(copied_count) } fn import_agents_md(&self, cwd: Option<&Path>) -> io::Result<()> { @@ -374,6 +405,15 @@ fn collect_subdirectory_names(path: &Path) -> io::Result> { Ok(names) } +fn count_missing_subdirectories(source: &Path, target: &Path) -> io::Result { + let source_names = collect_subdirectory_names(source)?; + let target_names = collect_subdirectory_names(target)?; + Ok(source_names + .iter() + .filter(|name| !target_names.contains(*name)) + .count()) +} + fn is_missing_or_empty_text_file(path: &Path) -> io::Result { if !path.exists() { return Ok(true); @@ -614,6 +654,39 @@ fn invalid_data_error(message: impl Into) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message.into()) } +fn migration_metric_tags( + item_type: ExternalAgentConfigMigrationItemType, + skills_count: Option, +) -> Vec<(&'static str, String)> { + let migration_type = match item_type { + ExternalAgentConfigMigrationItemType::Config => "config", + ExternalAgentConfigMigrationItemType::Skills => "skills", + ExternalAgentConfigMigrationItemType::AgentsMd => "agents_md", + ExternalAgentConfigMigrationItemType::McpServerConfig => "mcp_server_config", + }; + let mut tags = vec![("migration_type", migration_type.to_string())]; + if item_type == ExternalAgentConfigMigrationItemType::Skills { + tags.push(("skills_count", skills_count.unwrap_or(0).to_string())); + } + tags +} + +fn emit_migration_metric( + metric_name: &str, + item_type: ExternalAgentConfigMigrationItemType, + skills_count: Option, +) { + let Some(metrics) = codex_otel::metrics::global() else { + return; + }; + let tags = migration_metric_tags(item_type, skills_count); + let tag_refs = tags + .iter() + .map(|(key, value)| (*key, value.as_str())) + .collect::>(); + let _ = metrics.counter(metric_name, 1, &tag_refs); +} + #[cfg(test)] mod tests { use super::*; @@ -984,4 +1057,33 @@ mod tests { "Codex guidance" ); } + + #[test] + fn migration_metric_tags_for_skills_include_skills_count() { + assert_eq!( + migration_metric_tags(ExternalAgentConfigMigrationItemType::Skills, Some(3)), + vec![ + ("migration_type", "skills".to_string()), + ("skills_count", "3".to_string()), + ] + ); + } + + #[test] + fn import_skills_returns_only_new_skill_directory_count() { + let (_root, claude_home, codex_home) = fixture_paths(); + let agents_skills = codex_home + .parent() + .map(|parent| parent.join(".agents").join("skills")) + .unwrap_or_else(|| PathBuf::from(".agents").join("skills")); + fs::create_dir_all(claude_home.join("skills").join("skill-a")).expect("create source a"); + fs::create_dir_all(claude_home.join("skills").join("skill-b")).expect("create source b"); + fs::create_dir_all(agents_skills.join("skill-a")).expect("create existing target"); + + let copied_count = service_for_paths(claude_home, codex_home) + .import_skills(None) + .expect("import skills"); + + assert_eq!(copied_count, 1); + } } From f80e5d979d7a1872da11520507ae881860fa4268 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 4 Mar 2026 15:08:57 -0700 Subject: [PATCH 384/385] Notify TUI about plan mode prompts and user input requests (#13495) Addresses #13478 Summary - Add two new scopes for `tui.notifications` config: `plan-mode-prompt` and `user-input-requested`. - Add Plan Mode prompt and user-input-requested notifications to the TUI so these events surface consistently outside of plan mode - Add helpers and tests to ensure the new notification types publish the right titles, summaries, and type tags for filtering - Add prioritization mechanism to fix an existing bug where one notification event could arbitrarily overwrite others Testing - Manually tested plan mode to ensure that notification appeared --- codex-rs/tui/src/chatwidget.rs | 80 ++++++++++++++- codex-rs/tui/src/chatwidget/tests.rs | 147 +++++++++++++++++++++++++++ 2 files changed, 223 insertions(+), 4 deletions(-) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 8c4f4ef57b..120ec3d571 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1656,6 +1656,9 @@ impl ChatWidget { items, ..Default::default() }); + self.notify(Notification::PlanModePrompt { + title: PLAN_IMPLEMENTATION_TITLE.to_string(), + }); } pub(crate) fn open_multi_agent_enable_prompt(&mut self) { @@ -2872,6 +2875,10 @@ impl ChatWidget { pub(crate) fn handle_request_user_input_now(&mut self, ev: RequestUserInputEvent) { self.flush_answer_stream_with_separator(); + self.notify(Notification::UserInputRequested { + question_count: ev.questions.len(), + summary: Notification::user_input_request_summary(&ev.questions), + }); self.bottom_pane.push_user_input_request(ev); self.request_redraw(); } @@ -4976,6 +4983,11 @@ impl ChatWidget { if !notification.allowed_for(&self.config.tui_notifications) { return; } + if let Some(existing) = self.pending_notification.as_ref() + && existing.priority() > notification.priority() + { + return; + } self.pending_notification = Some(notification); self.request_redraw(); } @@ -6172,6 +6184,9 @@ impl ChatWidget { ], ..Default::default() }); + self.notify(Notification::PlanModePrompt { + title: PLAN_MODE_REASONING_SCOPE_TITLE.to_string(), + }); } /// Open a popup to choose the reasoning effort (stage 2) for the given model. @@ -8383,11 +8398,28 @@ impl Renderable for ChatWidget { } } +#[derive(Debug)] enum Notification { - AgentTurnComplete { response: String }, - ExecApprovalRequested { command: String }, - EditApprovalRequested { cwd: PathBuf, changes: Vec }, - ElicitationRequested { server_name: String }, + AgentTurnComplete { + response: String, + }, + ExecApprovalRequested { + command: String, + }, + EditApprovalRequested { + cwd: PathBuf, + changes: Vec, + }, + ElicitationRequested { + server_name: String, + }, + PlanModePrompt { + title: String, + }, + UserInputRequested { + question_count: usize, + summary: Option, + }, } impl Notification { @@ -8414,6 +8446,17 @@ impl Notification { Notification::ElicitationRequested { server_name } => { format!("Approval requested by {server_name}") } + Notification::PlanModePrompt { title } => { + format!("Plan mode prompt: {title}") + } + Notification::UserInputRequested { + question_count, + summary, + } => match (*question_count, summary.as_deref()) { + (1, Some(summary)) => format!("Question requested: {summary}"), + (1, None) => "Question requested".to_string(), + (count, _) => format!("Questions requested: {count}"), + }, } } @@ -8423,6 +8466,19 @@ impl Notification { Notification::ExecApprovalRequested { .. } | Notification::EditApprovalRequested { .. } | Notification::ElicitationRequested { .. } => "approval-requested", + Notification::PlanModePrompt { .. } => "plan-mode-prompt", + Notification::UserInputRequested { .. } => "user-input-requested", + } + } + + fn priority(&self) -> u8 { + match self { + Notification::AgentTurnComplete { .. } => 0, + Notification::ExecApprovalRequested { .. } + | Notification::EditApprovalRequested { .. } + | Notification::ElicitationRequested { .. } + | Notification::PlanModePrompt { .. } + | Notification::UserInputRequested { .. } => 1, } } @@ -8448,6 +8504,22 @@ impl Notification { Some(truncate_text(trimmed, AGENT_NOTIFICATION_PREVIEW_GRAPHEMES)) } } + + fn user_input_request_summary( + questions: &[codex_protocol::request_user_input::RequestUserInputQuestion], + ) -> Option { + let first_question = questions.first()?; + let summary = if first_question.header.trim().is_empty() { + first_question.question.trim() + } else { + first_question.header.trim() + }; + if summary.is_empty() { + None + } else { + Some(truncate_text(summary, 30)) + } + } } const AGENT_NOTIFICATION_PREVIEW_GRAPHEMES: usize = 200; diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 2ece156517..6d74473e39 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -22,6 +22,7 @@ use codex_core::config::Config; use codex_core::config::ConfigBuilder; use codex_core::config::Constrained; use codex_core::config::ConstraintError; +use codex_core::config::types::Notifications; #[cfg(target_os = "windows")] use codex_core::config::types::WindowsSandboxModeToml; use codex_core::config_loader::RequirementSource; @@ -96,6 +97,9 @@ use codex_protocol::protocol::UndoCompletedEvent; use codex_protocol::protocol::UndoStartedEvent; use codex_protocol::protocol::ViewImageToolCallEvent; use codex_protocol::protocol::WarningEvent; +use codex_protocol::request_user_input::RequestUserInputEvent; +use codex_protocol::request_user_input::RequestUserInputQuestion; +use codex_protocol::request_user_input::RequestUserInputQuestionOption; use codex_protocol::user_input::TextElement; use codex_protocol::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; @@ -2535,6 +2539,149 @@ async fn plan_reasoning_scope_popup_all_modes_persists_global_and_plan_override( ); } +#[test] +fn plan_mode_prompt_notification_uses_dedicated_type_name() { + let notification = Notification::PlanModePrompt { + title: PLAN_IMPLEMENTATION_TITLE.to_string(), + }; + + assert!(notification.allowed_for(&Notifications::Custom( + vec!["plan-mode-prompt".to_string(),] + ))); + assert!(!notification.allowed_for(&Notifications::Custom(vec![ + "approval-requested".to_string(), + ]))); + assert_eq!( + notification.display(), + format!("Plan mode prompt: {PLAN_IMPLEMENTATION_TITLE}") + ); +} + +#[test] +fn user_input_requested_notification_uses_dedicated_type_name() { + let notification = Notification::UserInputRequested { + question_count: 1, + summary: Some("Reasoning scope".to_string()), + }; + + assert!(notification.allowed_for(&Notifications::Custom(vec![ + "user-input-requested".to_string(), + ]))); + assert!(!notification.allowed_for(&Notifications::Custom(vec![ + "approval-requested".to_string(), + ]))); + assert_eq!( + notification.display(), + "Question requested: Reasoning scope" + ); +} + +#[tokio::test] +async fn open_plan_implementation_prompt_sets_pending_notification() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.config.tui_notifications = Notifications::Custom(vec!["plan-mode-prompt".to_string()]); + + chat.open_plan_implementation_prompt(); + + assert_matches!( + chat.pending_notification, + Some(Notification::PlanModePrompt { ref title }) if title == PLAN_IMPLEMENTATION_TITLE + ); +} + +#[tokio::test] +async fn open_plan_reasoning_scope_prompt_sets_pending_notification() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.config.tui_notifications = Notifications::Custom(vec!["plan-mode-prompt".to_string()]); + + chat.open_plan_reasoning_scope_prompt( + "gpt-5.1-codex-max".to_string(), + Some(ReasoningEffortConfig::High), + ); + + assert_matches!( + chat.pending_notification, + Some(Notification::PlanModePrompt { ref title }) if title == PLAN_MODE_REASONING_SCOPE_TITLE + ); +} + +#[tokio::test] +async fn agent_turn_complete_does_not_override_pending_plan_mode_prompt_notification() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + + chat.open_plan_implementation_prompt(); + chat.notify(Notification::AgentTurnComplete { + response: "done".to_string(), + }); + + assert_matches!( + chat.pending_notification, + Some(Notification::PlanModePrompt { ref title }) if title == PLAN_IMPLEMENTATION_TITLE + ); +} + +#[tokio::test] +async fn user_input_notification_overrides_pending_agent_turn_complete_notification() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + + chat.notify(Notification::AgentTurnComplete { + response: "done".to_string(), + }); + chat.handle_request_user_input_now(RequestUserInputEvent { + call_id: "call-1".to_string(), + turn_id: "turn-1".to_string(), + questions: vec![RequestUserInputQuestion { + id: "reasoning_scope".to_string(), + header: "Reasoning scope".to_string(), + question: "Which reasoning scope should I use?".to_string(), + is_other: false, + is_secret: false, + options: Some(vec![RequestUserInputQuestionOption { + label: "Plan only".to_string(), + description: "Update only Plan mode.".to_string(), + }]), + }], + }); + + assert_matches!( + chat.pending_notification, + Some(Notification::UserInputRequested { + question_count: 1, + summary: Some(ref summary), + }) if summary == "Reasoning scope" + ); +} + +#[tokio::test] +async fn handle_request_user_input_sets_pending_notification() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; + chat.config.tui_notifications = Notifications::Custom(vec!["user-input-requested".to_string()]); + + chat.handle_request_user_input_now(RequestUserInputEvent { + call_id: "call-1".to_string(), + turn_id: "turn-1".to_string(), + questions: vec![RequestUserInputQuestion { + id: "reasoning_scope".to_string(), + header: "Reasoning scope".to_string(), + question: "Which reasoning scope should I use?".to_string(), + is_other: false, + is_secret: false, + options: Some(vec![RequestUserInputQuestionOption { + label: "Plan only".to_string(), + description: "Update only Plan mode.".to_string(), + }]), + }], + }); + + assert_matches!( + chat.pending_notification, + Some(Notification::UserInputRequested { + question_count: 1, + summary: Some(ref summary), + }) if summary == "Reasoning scope" + ); +} + #[tokio::test] async fn plan_reasoning_scope_popup_mentions_selected_reasoning() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await; From 4907096d1348b398b7bd7559a6ecc399b1dd7424 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 4 Mar 2026 14:10:54 -0800 Subject: [PATCH 385/385] [release] temporarily use thin LTO for releases (#13506) --- .github/workflows/rust-release.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 5d6d3f7ca0..b88c1f2641 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -57,7 +57,9 @@ jobs: run: working-directory: codex-rs env: - CARGO_PROFILE_RELEASE_LTO: ${{ contains(github.ref_name, '-alpha') && 'thin' || 'fat' }} + # 2026-03-04: temporarily change releases to use thin LTO because + # Ubuntu ARM is timing out at 60 minutes. + CARGO_PROFILE_RELEASE_LTO: ${{ contains(github.ref_name, '-alpha') && 'thin' || 'thin' }} strategy: fail-fast: false @@ -211,6 +213,7 @@ jobs: - name: Cargo build shell: bash run: | + echo "CARGO_PROFILE_RELEASE_LTO: ${CARGO_PROFILE_RELEASE_LTO}" cargo build --target ${{ matrix.target }} --release --timings --bin codex --bin codex-responses-api-proxy - name: Upload Cargo timings