From 509ff1c643e0b45366fc5d77c78279ca29b71448 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 26 Jan 2026 22:30:24 -0800 Subject: [PATCH 001/116] Fixing main and make plan mode reasoning effort medium (#9980) It's overthinking so much on high and going over the context window. --- .../collaboration_mode_presets.rs | 2 +- .../bottom_pane/request_user_input/layout.rs | 55 +++++++++++-------- 2 files changed, 32 insertions(+), 25 deletions(-) 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 aff111b1ad..83059b912e 100644 --- a/codex-rs/core/src/models_manager/collaboration_mode_presets.rs +++ b/codex-rs/core/src/models_manager/collaboration_mode_presets.rs @@ -28,7 +28,7 @@ fn plan_preset() -> CollaborationModeMask { name: "Plan".to_string(), mode: Some(ModeKind::Plan), model: None, - reasoning_effort: Some(Some(ReasoningEffort::High)), + reasoning_effort: Some(Some(ReasoningEffort::Medium)), developer_instructions: Some(Some(COLLABORATION_MODE_PLAN.to_string())), } } diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs b/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs index bb2b06dea5..4a1817da89 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs @@ -62,12 +62,14 @@ impl RequestUserInputOverlay { notes_area, ) = self.build_layout_areas( area, - progress_height, - question_height, - answer_title_height, - options_height, - notes_title_height, - notes_height, + LayoutHeights { + progress_height, + question_height, + answer_title_height, + options_height, + notes_title_height, + notes_height, + }, ); LayoutSections { @@ -276,12 +278,7 @@ impl RequestUserInputOverlay { fn build_layout_areas( &self, area: Rect, - progress_height: u16, - question_height: u16, - answer_title_height: u16, - options_height: u16, - notes_title_height: u16, - notes_height: u16, + heights: LayoutHeights, ) -> ( Rect, // progress_area Rect, // header_area @@ -296,10 +293,10 @@ impl RequestUserInputOverlay { x: area.x, y: cursor_y, width: area.width, - height: progress_height, + height: heights.progress_height, }; - cursor_y = cursor_y.saturating_add(progress_height); - let header_height = area.height.saturating_sub(progress_height).min(1); + cursor_y = cursor_y.saturating_add(heights.progress_height); + let header_height = area.height.saturating_sub(heights.progress_height).min(1); let header_area = Rect { x: area.x, y: cursor_y, @@ -311,37 +308,37 @@ impl RequestUserInputOverlay { x: area.x, y: cursor_y, width: area.width, - height: question_height, + height: heights.question_height, }; - cursor_y = cursor_y.saturating_add(question_height); + cursor_y = cursor_y.saturating_add(heights.question_height); let answer_title_area = Rect { x: area.x, y: cursor_y, width: area.width, - height: answer_title_height, + height: heights.answer_title_height, }; - cursor_y = cursor_y.saturating_add(answer_title_height); + cursor_y = cursor_y.saturating_add(heights.answer_title_height); let options_area = Rect { x: area.x, y: cursor_y, width: area.width, - height: options_height, + height: heights.options_height, }; - cursor_y = cursor_y.saturating_add(options_height); + cursor_y = cursor_y.saturating_add(heights.options_height); let notes_title_area = Rect { x: area.x, y: cursor_y, width: area.width, - height: notes_title_height, + height: heights.notes_title_height, }; - cursor_y = cursor_y.saturating_add(notes_title_height); + cursor_y = cursor_y.saturating_add(heights.notes_title_height); let notes_area = Rect { x: area.x, y: cursor_y, width: area.width, - height: notes_height, + height: heights.notes_height, }; ( @@ -355,3 +352,13 @@ impl RequestUserInputOverlay { ) } } + +#[derive(Clone, Copy, Debug)] +struct LayoutHeights { + progress_height: u16, + question_height: u16, + answer_title_height: u16, + options_height: u16, + notes_title_height: u16, + notes_height: u16, +} From ab99df0694e484f67fcfb8b2765364854f434872 Mon Sep 17 00:00:00 2001 From: K Bediako <70529246+Kbediako@users.noreply.github.com> Date: Tue, 27 Jan 2026 20:29:12 +1100 Subject: [PATCH 002/116] Fix: cap aggregated exec output consistently (#9759) ## WHAT? - Bias aggregated output toward stderr under contention (2/3 stderr, 1/3 stdout) while keeping the 1 MiB cap. - Rebalance unused stderr share back to stdout when stderr is tiny to avoid underfilling. - Add tests for contention, small-stderr rebalance, and under-cap ordering (stdout then stderr). ## WHY? - Review feedback requested stderr priority under contention. - Avoid underfilled aggregated output when stderr is small while preserving a consistent cap across exec paths. ## HOW? - Update `aggregate_output` to compute stdout/stderr shares, then reassign unused capacity to the other stream. - Use the helper in both Windows and async exec paths. - Add regression tests for contention/rebalance and under-cap ordering. ## BEFORE ```rust // Best-effort aggregate: stdout then stderr (capped). let mut aggregated = Vec::with_capacity( stdout .text .len() .saturating_add(stderr.text.len()) .min(EXEC_OUTPUT_MAX_BYTES), ); append_capped(&mut aggregated, &stdout.text, EXEC_OUTPUT_MAX_BYTES); append_capped(&mut aggregated, &stderr.text, EXEC_OUTPUT_MAX_BYTES); let aggregated_output = StreamOutput { text: aggregated, truncated_after_lines: None, }; ``` ## AFTER ```rust fn aggregate_output( stdout: &StreamOutput>, stderr: &StreamOutput>, ) -> StreamOutput> { let total_len = stdout.text.len().saturating_add(stderr.text.len()); let max_bytes = EXEC_OUTPUT_MAX_BYTES; let mut aggregated = Vec::with_capacity(total_len.min(max_bytes)); if total_len <= max_bytes { aggregated.extend_from_slice(&stdout.text); aggregated.extend_from_slice(&stderr.text); return StreamOutput { text: aggregated, truncated_after_lines: None, }; } // Under contention, reserve 1/3 for stdout and 2/3 for stderr; rebalance unused stderr to stdout. let want_stdout = stdout.text.len().min(max_bytes / 3); let want_stderr = stderr.text.len(); let stderr_take = want_stderr.min(max_bytes.saturating_sub(want_stdout)); let remaining = max_bytes.saturating_sub(want_stdout + stderr_take); let stdout_take = want_stdout + remaining.min(stdout.text.len().saturating_sub(want_stdout)); aggregated.extend_from_slice(&stdout.text[..stdout_take]); aggregated.extend_from_slice(&stderr.text[..stderr_take]); StreamOutput { text: aggregated, truncated_after_lines: None, } } ``` ## TESTS - [x] `just fmt` - [x] `just fix -p codex-core` - [x] `cargo test -p codex-core aggregate_output_` - [x] `cargo test -p codex-core` - [x] `cargo test --all-features` ## FIXES Fixes #9758 --- codex-rs/core/src/exec.rs | 143 ++++++++++++++++++++++++++++++-------- 1 file changed, 115 insertions(+), 28 deletions(-) diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 275f2fb856..ea23cb1216 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -312,20 +312,7 @@ async fn exec_windows_sandbox( text: stderr_text, truncated_after_lines: None, }; - // Best-effort aggregate: stdout then stderr (capped). - let mut aggregated = Vec::with_capacity( - stdout - .text - .len() - .saturating_add(stderr.text.len()) - .min(EXEC_OUTPUT_MAX_BYTES), - ); - append_capped(&mut aggregated, &stdout.text, EXEC_OUTPUT_MAX_BYTES); - append_capped(&mut aggregated, &stderr.text, EXEC_OUTPUT_MAX_BYTES); - let aggregated_output = StreamOutput { - text: aggregated, - truncated_after_lines: None, - }; + let aggregated_output = aggregate_output(&stdout, &stderr); Ok(RawExecToolCallOutput { exit_status, @@ -519,6 +506,39 @@ fn append_capped(dst: &mut Vec, src: &[u8], max_bytes: usize) { dst.extend_from_slice(&src[..take]); } +fn aggregate_output( + stdout: &StreamOutput>, + stderr: &StreamOutput>, +) -> StreamOutput> { + let total_len = stdout.text.len().saturating_add(stderr.text.len()); + let max_bytes = EXEC_OUTPUT_MAX_BYTES; + let mut aggregated = Vec::with_capacity(total_len.min(max_bytes)); + + if total_len <= max_bytes { + aggregated.extend_from_slice(&stdout.text); + aggregated.extend_from_slice(&stderr.text); + return StreamOutput { + text: aggregated, + truncated_after_lines: None, + }; + } + + // Under contention, reserve 1/3 for stdout and 2/3 for stderr; rebalance unused stderr to stdout. + let want_stdout = stdout.text.len().min(max_bytes / 3); + let want_stderr = stderr.text.len(); + let stderr_take = want_stderr.min(max_bytes.saturating_sub(want_stdout)); + let remaining = max_bytes.saturating_sub(want_stdout + stderr_take); + let stdout_take = want_stdout + remaining.min(stdout.text.len().saturating_sub(want_stdout)); + + aggregated.extend_from_slice(&stdout.text[..stdout_take]); + aggregated.extend_from_slice(&stderr.text[..stderr_take]); + + StreamOutput { + text: aggregated, + truncated_after_lines: None, + } +} + #[derive(Clone, Debug)] pub struct ExecToolCallOutput { pub exit_code: i32, @@ -683,20 +703,7 @@ async fn consume_truncated_output( Duration::from_millis(IO_DRAIN_TIMEOUT_MS), ) .await?; - // Best-effort aggregate: stdout then stderr (capped). - let mut aggregated = Vec::with_capacity( - stdout - .text - .len() - .saturating_add(stderr.text.len()) - .min(EXEC_OUTPUT_MAX_BYTES), - ); - append_capped(&mut aggregated, &stdout.text, EXEC_OUTPUT_MAX_BYTES); - append_capped(&mut aggregated, &stderr.text, EXEC_OUTPUT_MAX_BYTES * 2); - let aggregated_output = StreamOutput { - text: aggregated, - truncated_after_lines: None, - }; + let aggregated_output = aggregate_output(&stdout, &stderr); Ok(RawExecToolCallOutput { exit_status, @@ -771,6 +778,7 @@ fn synthetic_exit_status(code: i32) -> ExitStatus { #[cfg(test)] mod tests { use super::*; + use pretty_assertions::assert_eq; use std::time::Duration; use tokio::io::AsyncWriteExt; @@ -846,6 +854,85 @@ mod tests { assert_eq!(out.text.len(), EXEC_OUTPUT_MAX_BYTES); } + #[test] + fn aggregate_output_prefers_stderr_on_contention() { + let stdout = StreamOutput { + text: vec![b'a'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr); + let stdout_cap = EXEC_OUTPUT_MAX_BYTES / 3; + let stderr_cap = EXEC_OUTPUT_MAX_BYTES.saturating_sub(stdout_cap); + + assert_eq!(aggregated.text.len(), EXEC_OUTPUT_MAX_BYTES); + assert_eq!(aggregated.text[..stdout_cap], vec![b'a'; stdout_cap]); + assert_eq!(aggregated.text[stdout_cap..], vec![b'b'; stderr_cap]); + } + + #[test] + fn aggregate_output_fills_remaining_capacity_with_stderr() { + let stdout_len = EXEC_OUTPUT_MAX_BYTES / 10; + let stdout = StreamOutput { + text: vec![b'a'; stdout_len], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr); + let stderr_cap = EXEC_OUTPUT_MAX_BYTES.saturating_sub(stdout_len); + + assert_eq!(aggregated.text.len(), EXEC_OUTPUT_MAX_BYTES); + assert_eq!(aggregated.text[..stdout_len], vec![b'a'; stdout_len]); + assert_eq!(aggregated.text[stdout_len..], vec![b'b'; stderr_cap]); + } + + #[test] + fn aggregate_output_rebalances_when_stderr_is_small() { + let stdout = StreamOutput { + text: vec![b'a'; EXEC_OUTPUT_MAX_BYTES], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; 1], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr); + let stdout_len = EXEC_OUTPUT_MAX_BYTES.saturating_sub(1); + + assert_eq!(aggregated.text.len(), EXEC_OUTPUT_MAX_BYTES); + assert_eq!(aggregated.text[..stdout_len], vec![b'a'; stdout_len]); + assert_eq!(aggregated.text[stdout_len..], vec![b'b'; 1]); + } + + #[test] + fn aggregate_output_keeps_stdout_then_stderr_when_under_cap() { + let stdout = StreamOutput { + text: vec![b'a'; 4], + truncated_after_lines: None, + }; + let stderr = StreamOutput { + text: vec![b'b'; 3], + truncated_after_lines: None, + }; + + let aggregated = aggregate_output(&stdout, &stderr); + let mut expected = Vec::new(); + expected.extend_from_slice(&stdout.text); + expected.extend_from_slice(&stderr.text); + + assert_eq!(aggregated.text, expected); + assert_eq!(aggregated.truncated_after_lines, None); + } + #[cfg(unix)] #[test] fn sandbox_detection_flags_sigsys_exit_code() { From 742f086ee6dfa2b365e903dbee2e6a165b3e0da7 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 27 Jan 2026 12:46:51 +0000 Subject: [PATCH 003/116] nit: better tool description (#9988) --- codex-rs/core/src/tools/spec.rs | 36 +++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 64f4053bb5..d7fd1d0187 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -444,14 +444,17 @@ fn create_spawn_agent_tool() -> ToolSpec { properties.insert( "message".to_string(), JsonSchema::String { - description: Some("Initial message to send to the new agent.".to_string()), + description: Some( + "Initial task for the new agent. Include scope, constraints, and the expected output." + .to_string(), + ), }, ); properties.insert( "agent_type".to_string(), JsonSchema::String { description: Some(format!( - "Optional agent type to spawn ({}).", + "Optional agent type ({}). Use an explicit type when delegating.", AgentRole::enum_values().join(", ") )), }, @@ -459,7 +462,9 @@ fn create_spawn_agent_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "spawn_agent".to_string(), - description: "Spawn a new agent and return its id.".to_string(), + description: + "Spawn a sub-agent for a well-scoped task. Returns the agent id to use to communicate with this agent." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -474,7 +479,7 @@ fn create_send_input_tool() -> ToolSpec { properties.insert( "id".to_string(), JsonSchema::String { - description: Some("Identifier of the agent to message.".to_string()), + description: Some("Agent id to message (from spawn_agent).".to_string()), }, ); properties.insert( @@ -487,7 +492,7 @@ fn create_send_input_tool() -> ToolSpec { "interrupt".to_string(), JsonSchema::Boolean { description: Some( - "When true, interrupt the agent's current task before sending the message. When false (default), the message will be processed when the agent is done on its current task." + "When true, stop the agent's current task and handle this immediately. When false (default), queue this message." .to_string(), ), }, @@ -495,7 +500,9 @@ fn create_send_input_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "send_input".to_string(), - description: "Send a message to an existing agent.".to_string(), + description: + "Send a message to an existing agent. Use interrupt=true to redirect work immediately." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -511,23 +518,25 @@ fn create_wait_tool() -> ToolSpec { "ids".to_string(), JsonSchema::Array { items: Box::new(JsonSchema::String { description: None }), - description: Some("Identifiers of the agents to wait on.".to_string()), + description: Some( + "Agent ids to wait on. Pass multiple ids to wait for whichever finishes first." + .to_string(), + ), }, ); properties.insert( "timeout_ms".to_string(), JsonSchema::Number { description: Some(format!( - "Optional timeout in milliseconds. Defaults to {DEFAULT_WAIT_TIMEOUT_MS}, min {MIN_WAIT_TIMEOUT_MS}, and max {MAX_WAIT_TIMEOUT_MS}. Avoid tight polling loops; prefer longer waits (seconds to minutes)." + "Optional timeout in milliseconds. Defaults to {DEFAULT_WAIT_TIMEOUT_MS}, min {MIN_WAIT_TIMEOUT_MS}, max {MAX_WAIT_TIMEOUT_MS}. Prefer longer waits (minutes) to avoid busy polling." )), }, ); ToolSpec::Function(ResponsesApiTool { name: "wait".to_string(), - description: - "Wait for agents and return their statuses. If no agent is done, no status get returned." - .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." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -634,13 +643,14 @@ fn create_close_agent_tool() -> ToolSpec { properties.insert( "id".to_string(), JsonSchema::String { - description: Some("Identifier of the agent to close.".to_string()), + description: Some("Agent id to close (from spawn_agent).".to_string()), }, ); ToolSpec::Function(ResponsesApiTool { name: "close_agent".to_string(), - description: "Close an agent and return its last known status.".to_string(), + description: "Close an agent when it is no longer needed and return its last known status." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, From 74ffbbe7c1608c31f7ca7f42f94363dc7782a6cb Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 27 Jan 2026 13:03:12 +0000 Subject: [PATCH 004/116] nit: better unused prompt (#9991) --- .../core/templates/agents/orchestrator.md | 173 ++++++++++++------ 1 file changed, 115 insertions(+), 58 deletions(-) diff --git a/codex-rs/core/templates/agents/orchestrator.md b/codex-rs/core/templates/agents/orchestrator.md index c303591d48..0d8aa47901 100644 --- a/codex-rs/core/templates/agents/orchestrator.md +++ b/codex-rs/core/templates/agents/orchestrator.md @@ -1,74 +1,131 @@ -You are Codex Orchestrator, based on GPT-5. You are running as an orchestration agent in the Codex CLI on a user's computer. +You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals. -## Role +# Personality +You are a collaborative, highly capable pair-programmer AI. You take engineering quality seriously, and collaboration is a kind of quiet joy: as real progress happens, your enthusiasm shows briefly and specifically. Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work. -* You are the interface between the user and the workers. -* Your job is to understand the task, decompose it, and delegate well-scoped work to workers. -* You coordinate execution, monitor progress, resolve conflicts, and integrate results into a single coherent outcome. -* You may perform lightweight actions (e.g. reading files, basic commands) to understand the task, but all substantive work must be delegated to workers. -* **Your job is not finished until the entire task is fully completed and verified.** -* While the task is incomplete, you must keep monitoring and coordinating workers. You must not return early. +## Tone and style +- Anything you say outside of tool use is shown to the user. Do not narrate abstractly; explain what you are doing and why, using plain language. +- Output will be rendered in a command line interface or minimal UI so keep responses tight, scannable, and low-noise. Generally avoid the use of emojis. You may format with GitHub-flavored Markdown. +- Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the `1. 2. 3.` style markers (with a period), never `1)`. +- When writing a final assistant response, state the solution first before explaining your answer. The complexity of the answer should match the task. If the task is simple, your answer should be short. When you make big or complex changes, walk the user through what you did and why. +- Headers are optional, only use them when you think they are necessary. If you do use them, use short Title Case (1-3 words) wrapped in **…**. Don't add a blank line. +- Code samples or multi-line snippets should be wrapped in fenced code blocks. Include an info string as often as possible. +- Never output the content of large files, just provide references. Use inline code to make file paths clickable; each reference should have a stand alone path, even if it's the same file. Paths may be absolute, workspace-relative, a//b/ diff-prefixed, or bare filename/suffix; locations may be :line[:column] or #Lline[Ccolumn] (1-based; column defaults to 1). Do not use file://, vscode://, or https://, and do not provide line ranges. Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5 +- The user does not see command execution outputs. When asked to show the output of a command (e.g. `git show`), relay the important details in your answer or summarize the key lines so the user understands the result. +- Never tell the user to "save/copy this file", the user is on the same machine and has access to the same files as you have. +- If you weren't able to do something, for example run tests, tell the user. +- If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps. -## Core invariants +## Responsiveness -* **Never stop monitoring workers.** -* **Do not rush workers. Be patient.** -* The orchestrator must not return unless the task is fully accomplished. -* If the user ask you a question/status while you are working, always answer him before continuing your work. +### Collaboration posture: +- If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as `date`), you should do so. +- Treat the user as an equal co-builder; preserve the user's intent and coding style rather than rewriting everything. +- When the user is in flow, stay succinct and high-signal; when the user seems blocked, get more animated with hypotheses, experiments, and offers to take the next concrete step. +- Propose options and trade-offs and invite steering, but don't block on unnecessary confirmations. +- Reference the collaboration explicitly when appropriate emphasizing shared achievement. -## Worker execution semantics +### User Updates Spec +You'll work for stretches with tool calls — it's critical to keep the user updated as you work. -* While a worker is running, you cannot observe intermediate state. -* Workers are able to run commands, update/create/delete files etc. They can be considered as fully autonomous agents -* Messages sent with `send_input` are queued and processed only after the worker finishes, unless interrupted. -* Therefore: - * Do not send messages to “check status” or “ask for progress” unless being asked. - * Monitoring happens exclusively via `wait`. - * Sending a message is a commitment for the *next* phase of work. +Tone: +- Friendly, confident, senior-engineer energy. Positive, collaborative, humble; fix mistakes quickly. -## Interrupt semantics +Frequency & Length: +- Send short updates (1–2 sentences) whenever there is a meaningful, important insight you need to share with the user to keep them informed. +- If you expect a longer heads‑down stretch, post a brief heads‑down note with why and when you'll report back; when you resume, summarize what you learned. +- Only the initial plan, plan updates, and final recap can be longer, with multiple bullets and paragraphs -* If a worker is taking longer than expected but is still working, do nothing and keep waiting unless being asked. -* Only intervene if you must change, stop, or redirect the *current* work. -* To stop a worker’s current task, you **must** use `send_input(interrupt=true)`. -* Use `interrupt=true` sparingly and deliberately. +Content: +- Before you begin, give a quick plan with goal, constraints, next steps. +- While you're exploring, call out meaningful new information and discoveries that you find that helps the user understand what's happening and how you're approaching the solution. +- If you change the plan (e.g., choose an inline tweak instead of a promised helper), say so explicitly in the next update or the recap. +- Emojis are allowed only to mark milestones/sections or real wins; never decorative; never inside code/diffs/commit messages. -## Multi-agent workflow +# Code style -1. Understand the request and determine the optimal set of workers. If the task can be divided into sub-tasks, spawn one worker per sub-task and make them work together. -2. Spawn worker(s) with precise goals, constraints, and expected deliverables. -3. Monitor workers using `wait`. -4. When a worker finishes: - * verify correctness, - * check integration with other work, - * assess whether the global task is closer to completion. -5. If issues remain, assign fixes to the appropriate worker(s) and repeat steps 3–5. Do not fix yourself unless the fixes are very small. -6. Close agents only when no further work is required from them. -7. Return to the user only when the task is fully completed and verified. +- Follow the precedence rules user instructions > system / dev / user / AGENTS.md instructions > match local file conventions > instructions below. +- Use language-appropriate best practices. +- Optimize for clarity, readability, and maintainability. +- Prefer explicit, verbose, human-readable code over clever or concise code. +- Write clear, well-punctuated comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare. +- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them. -## Collaboration rules +# Reviews -* Workers operate in a shared environment. You must tell it to them. -* Workers must not revert, overwrite, or conflict with others’ work. -* By default, workers must not spawn sub-agents unless explicitly allowed. -* When multiple workers are active, you may pass multiple IDs to `wait` to react to the first completion and keep the workflow event-driven and use a long timeout (e.g. 5 minutes). -* Do not busy-poll `wait` with very short timeouts. Prefer waits measured in seconds (or minutes) so the system is idle while workers run. +When the user asks for a review, you default to a code-review mindset. Your response prioritizes identifying bugs, risks, behavioral regressions, and missing tests. You present findings first, ordered by severity and including file or line references where possible. Open questions or assumptions follow. You state explicitly if no findings exist and call out any residual risks or test gaps. -## Collab tools +# Your environment -* `spawn_agent`: create a worker with an initial prompt (`agent_type` required). -* `send_input`: send follow-ups or fixes (queued unless interrupted). -* `send_input(interrupt=true)`: stop current work and redirect immediately. -* `wait`: wait for one or more workers; returns when at least one finishes. -* `close_agent`: close a worker when fully done. +## Using GIT -## Final response +- You may be working in a dirty git worktree. + * NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user. + * If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes. + * If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them. + * If the changes are in unrelated files, just ignore them and don't revert them. +- Do not amend a commit unless explicitly requested to do so. +- While you are working, you might notice unexpected changes that you didn't make. It's likely the user made them. If this happens, STOP IMMEDIATELY and ask the user how they would like to proceed. +- Be cautious when using git. **NEVER** use destructive commands like `git reset --hard` or `git checkout --` unless specifically requested or approved by the user. +- You struggle using the git interactive console. **ALWAYS** prefer using non-interactive git commands. -* Keep responses concise, factual, and in plain text. -* Summarize: - * what was delegated, - * key outcomes, - * verification performed, - * and any remaining risks. -* If verification failed, state issues clearly and describe what was reassigned. -* Do not dump large files inline; reference paths using backticks. +## Agents.md + +- If the directory you are in has an AGENTS.md file, it is provided to you at the top, and you don't have to search for it. +- If the user starts by chatting without a specific engineering/code related request, do NOT search for an AGENTS.md. Only do so once there is a relevant request. + +# Tool use + +- Unless you are otherwise instructed, prefer using `rg` or `rg --files` respectively when searching because `rg` is much faster than alternatives like `grep`. If the `rg` command is not found, then use alternatives. +- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase). + +- Use the plan tool to explain to the user what you are going to do + - Only use it for more complex tasks, do not use it for straightforward tasks (roughly the easiest 40%). + - Do not make single-step plans. If a single step plan makes sense to you, the task is straightforward and doesn't need a plan. + - When you made a plan, update it after having performed one of the sub-tasks that you shared on the plan. + +# Sub-agents +If `spawn_agent` is unavailable or fails, ignore this section and proceed solo. + +## Core rule +Sub-agents are their to make you go fast and time is a big constraint so leverage them smartly as much as you can. + +## General guidelines +- Prefer multiple sub-agents to parallelize your work. Time is a constraint so parallelism resolve the task faster. +- If sub-agents are running, **wait for them before yielding**, unless the user asks an explicit question. + - If the user asks a question, answer it first, then continue coordinating sub-agents. +- When you ask sub-agent to do the work for you, your only role becomes to coordinate them. Do not perform the actual work while they are working. +- When you have plan with multiple step, process them in parallel by spawning one agent per step when this is possible. + +## Sub-agent types +### `worker` sub-agents +Use for execution and production work. +Typical tasks: +- Implement part of a feature +- 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 + +### `explorer` sub-agents +Use for fast codebase understanding and information gathering. +`explorer` are extremely fast agents so use them as much as you can to speed up the resolution of the global task. +Typical tasks: +- Locate usages of a symbol or concept +- Understand how X is handled in Y +- Review a section of code for issues +- Assess impact of a potential change + Rules: +- Be explicit in what you are looking for. A good usage of `explorer` would mean that don't need to read the same code after the explorer send you the result. +- **Always** prefer asking explorers rather than exploring the codebase yourself. +- Spawn multiple explorers in parallel when useful and wait for all results. +- You can ask the `explorer` to return file name, lines, entire code snippets, ... +- Reuse the same explorer when it is relevant. If later in your process you have more questions on some code an explorer already covered, reuse this same explorer to be more efficient. + +## Flow +1. Understand the task. +2. Spawn the optimal necessary sub-agents. +3. Coordinate them via wait / send_input. +4. Iterate on this. You can use agents at different step of the process and during the whole resolution of the task. Never forget to use them. +5. Ask the user before shutting sub-agents down unless you need to because you reached the agent limit. From 3b726d95501acffacf1da2e7d0da767226d2de98 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 27 Jan 2026 16:32:05 +0000 Subject: [PATCH 005/116] chore: clean orchestrator prompt (#9994) --- .../core/templates/agents/orchestrator.md | 29 ++----------------- 1 file changed, 2 insertions(+), 27 deletions(-) diff --git a/codex-rs/core/templates/agents/orchestrator.md b/codex-rs/core/templates/agents/orchestrator.md index 0d8aa47901..e0976f52ef 100644 --- a/codex-rs/core/templates/agents/orchestrator.md +++ b/codex-rs/core/templates/agents/orchestrator.md @@ -93,35 +93,10 @@ Sub-agents are their to make you go fast and time is a big constraint so leverag ## General guidelines - Prefer multiple sub-agents to parallelize your work. Time is a constraint so parallelism resolve the task faster. - If sub-agents are running, **wait for them before yielding**, unless the user asks an explicit question. - - If the user asks a question, answer it first, then continue coordinating sub-agents. + - If the user asks a question, answer it first, then continue coordinating sub-agents. - When you ask sub-agent to do the work for you, your only role becomes to coordinate them. Do not perform the actual work while they are working. - When you have plan with multiple step, process them in parallel by spawning one agent per step when this is possible. - -## Sub-agent types -### `worker` sub-agents -Use for execution and production work. -Typical tasks: -- Implement part of a feature -- 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 - -### `explorer` sub-agents -Use for fast codebase understanding and information gathering. -`explorer` are extremely fast agents so use them as much as you can to speed up the resolution of the global task. -Typical tasks: -- Locate usages of a symbol or concept -- Understand how X is handled in Y -- Review a section of code for issues -- Assess impact of a potential change - Rules: -- Be explicit in what you are looking for. A good usage of `explorer` would mean that don't need to read the same code after the explorer send you the result. -- **Always** prefer asking explorers rather than exploring the codebase yourself. -- Spawn multiple explorers in parallel when useful and wait for all results. -- You can ask the `explorer` to return file name, lines, entire code snippets, ... -- Reuse the same explorer when it is relevant. If later in your process you have more questions on some code an explorer already covered, reuse this same explorer to be more efficient. +- Choose the correct agent type. ## Flow 1. Understand the task. From ddc704d4c632cab9aa7517a7a40a6d8283a2ee75 Mon Sep 17 00:00:00 2001 From: gt-oai Date: Tue, 27 Jan 2026 16:59:53 +0000 Subject: [PATCH 006/116] backend-client: add get_config_requirements_file (#10001) Adds getting config requirement to backend-client. I made a slash command to test it (not included in this PR): Screenshot 2026-01-27 at 15 20 41 --- codex-rs/backend-client/src/client.rs | 15 +++++++ codex-rs/backend-client/src/lib.rs | 1 + codex-rs/backend-client/src/types.rs | 1 + .../src/models/config_file_response.rs | 40 +++++++++++++++++++ .../src/models/mod.rs | 4 ++ 5 files changed, 61 insertions(+) create mode 100644 codex-rs/codex-backend-openapi-models/src/models/config_file_response.rs diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index ea3585956b..ec5fd3f61b 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -1,4 +1,5 @@ use crate::types::CodeTaskDetailsResponse; +use crate::types::ConfigFileResponse; use crate::types::CreditStatusDetails; use crate::types::PaginatedListTaskListItem; use crate::types::RateLimitStatusPayload; @@ -244,6 +245,20 @@ impl Client { self.decode_json::(&url, &ct, &body) } + /// Fetch the managed requirements file from codex-backend. + /// + /// `GET /api/codex/config/requirements` (Codex API style) or + /// `GET /wham/config/requirements` (ChatGPT backend-api style). + pub async fn get_config_requirements_file(&self) -> Result { + let url = match self.path_style { + PathStyle::CodexApi => format!("{}/api/codex/config/requirements", self.base_url), + PathStyle::ChatGptApi => format!("{}/wham/config/requirements", self.base_url), + }; + let req = self.http.get(&url).headers(self.headers()); + let (body, ct) = self.exec_request(req, "GET", &url).await?; + self.decode_json::(&url, &ct, &body) + } + /// Create a new task (user turn) by POSTing to the appropriate backend path /// based on `path_style`. Returns the created task id. pub async fn create_task(&self, request_body: serde_json::Value) -> Result { diff --git a/codex-rs/backend-client/src/lib.rs b/codex-rs/backend-client/src/lib.rs index 29fe9f3c6b..de827e9a97 100644 --- a/codex-rs/backend-client/src/lib.rs +++ b/codex-rs/backend-client/src/lib.rs @@ -4,6 +4,7 @@ pub mod types; pub use client::Client; pub use types::CodeTaskDetailsResponse; pub use types::CodeTaskDetailsResponseExt; +pub use types::ConfigFileResponse; pub use types::PaginatedListTaskListItem; pub use types::TaskListItem; pub use types::TurnAttemptsSiblingTurnsResponse; diff --git a/codex-rs/backend-client/src/types.rs b/codex-rs/backend-client/src/types.rs index afeb231a18..9deeab7903 100644 --- a/codex-rs/backend-client/src/types.rs +++ b/codex-rs/backend-client/src/types.rs @@ -1,3 +1,4 @@ +pub use codex_backend_openapi_models::models::ConfigFileResponse; pub use codex_backend_openapi_models::models::CreditStatusDetails; pub use codex_backend_openapi_models::models::PaginatedListTaskListItem; pub use codex_backend_openapi_models::models::PlanType; diff --git a/codex-rs/codex-backend-openapi-models/src/models/config_file_response.rs b/codex-rs/codex-backend-openapi-models/src/models/config_file_response.rs new file mode 100644 index 0000000000..2e22cb58fe --- /dev/null +++ b/codex-rs/codex-backend-openapi-models/src/models/config_file_response.rs @@ -0,0 +1,40 @@ +/* + * codex-backend + * + * codex-backend + * + * The version of the OpenAPI document: 0.0.1 + * + * Generated by: https://openapi-generator.tech + */ + +use serde::Deserialize; +use serde::Serialize; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConfigFileResponse { + #[serde(rename = "contents", skip_serializing_if = "Option::is_none")] + pub contents: Option, + #[serde(rename = "sha256", skip_serializing_if = "Option::is_none")] + pub sha256: Option, + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + #[serde(rename = "updated_by_user_id", skip_serializing_if = "Option::is_none")] + pub updated_by_user_id: Option, +} + +impl ConfigFileResponse { + pub fn new( + contents: Option, + sha256: Option, + updated_at: Option, + updated_by_user_id: Option, + ) -> ConfigFileResponse { + ConfigFileResponse { + contents, + sha256, + updated_at, + updated_by_user_id, + } + } +} diff --git a/codex-rs/codex-backend-openapi-models/src/models/mod.rs b/codex-rs/codex-backend-openapi-models/src/models/mod.rs index d767154925..7072dede5e 100644 --- a/codex-rs/codex-backend-openapi-models/src/models/mod.rs +++ b/codex-rs/codex-backend-openapi-models/src/models/mod.rs @@ -3,6 +3,10 @@ // Currently export only the types referenced by the workspace // The process for this will change +// Config +pub mod config_file_response; +pub use self::config_file_response::ConfigFileResponse; + // Cloud Tasks pub mod code_task_details_response; pub use self::code_task_details_response::CodeTaskDetailsResponse; From dd24ac6b26888a88aeb276ed936c2a86c5ac995b Mon Sep 17 00:00:00 2001 From: mjr-openai Date: Tue, 27 Jan 2026 12:19:43 -0500 Subject: [PATCH 007/116] update pnpm to 10.28.2 to address security issues (#9992) Updates pnpm to 10.28.2. to address security issues in prior versions of pnpm that can allow deps to execute lifecycle scripts against policy. I have read the CLA Document and I hereby sign the CLA --- PNPM.md | 6 +++--- package.json | 2 +- pnpm-workspace.yaml | 4 ++++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/PNPM.md b/PNPM.md index 860633c8e1..9f05e39cf8 100644 --- a/PNPM.md +++ b/PNPM.md @@ -15,7 +15,7 @@ This project has been migrated from npm to pnpm to improve dependency management ```bash # Global installation of pnpm -npm install -g pnpm@10.8.1 +npm install -g pnpm@10.28.2 # Or with corepack (available with Node.js 22+) corepack enable @@ -59,12 +59,12 @@ codex/ ## CI/CD -CI/CD workflows have been updated to use pnpm instead of npm. Make sure your CI environments use pnpm 10.8.1 or higher. +CI/CD workflows have been updated to use pnpm instead of npm. Make sure your CI environments use pnpm 10.28.2 or higher. ## Known issues If you encounter issues with pnpm, try the following solutions: 1. Remove the `node_modules` folder and `pnpm-lock.yaml` file, then run `pnpm install` -2. Make sure you're using pnpm 10.8.1 or higher +2. Make sure you're using pnpm 10.28.2 or higher 3. Verify that Node.js 22 or higher is installed diff --git a/package.json b/package.json index ae676d8230..9f1452a972 100644 --- a/package.json +++ b/package.json @@ -21,5 +21,5 @@ "node": ">=22", "pnpm": ">=9.0.0" }, - "packageManager": "pnpm@10.8.1" + "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264" } diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index ddd5674bf1..78899b9321 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -5,3 +5,7 @@ packages: ignoredBuiltDependencies: - esbuild + +minimumReleaseAge: 10080 + +blockExoticSubdeps: true From 067922a734f4abb11ef3db7290daed4feeeda60c Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 27 Jan 2026 17:20:07 +0000 Subject: [PATCH 008/116] description in role type (#9993) --- codex-rs/core/src/agent/role.rs | 38 ++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/agent/role.rs b/codex-rs/core/src/agent/role.rs index dd05c18470..7a9dda005b 100644 --- a/codex-rs/core/src/agent/role.rs +++ b/codex-rs/core/src/agent/role.rs @@ -44,6 +44,8 @@ pub struct AgentProfile { pub reasoning_effort: Option, /// Whether to force a read-only sandbox policy. pub read_only: bool, + /// Description to include in the tool specs. + pub description: &'static str, } impl AgentRole { @@ -51,7 +53,19 @@ impl AgentRole { pub fn enum_values() -> Vec { ALL_ROLES .iter() - .filter_map(|role| serde_json::to_string(role).ok()) + .filter_map(|role| { + let description = role.profile().description; + serde_json::to_string(role) + .map(|role| { + let description = if !description.is_empty() { + format!(r#", "description": {description}"#) + } else { + String::new() + }; + format!(r#"{{ "name": {role}{description}}}"#) + }) + .ok() + }) .collect() } @@ -66,11 +80,33 @@ impl AgentRole { AgentRole::Worker => AgentProfile { // base_instructions: Some(WORKER_PROMPT), // model: Some(WORKER_MODEL), + description: r#"Use for execution and production work. +Typical tasks: +- Implement part of a feature +- 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"#, ..Default::default() }, AgentRole::Explorer => AgentProfile { model: Some(EXPLORER_MODEL), reasoning_effort: Some(ReasoningEffort::Low), + description: r#"Use for fast codebase understanding and information gathering. +`explorer` are extremely fast agents so use them as much as you can to speed up the resolution of the global task. +Typical tasks: +- Locate usages of a symbol or concept +- Understand how X is handled in Y +- Review a section of code for issues +- Assess impact of a potential change +Rules: +- Be explicit in what you are looking for. A good usage of `explorer` would mean that don't need to read the same code after the explorer send you the result. +- **Always** prefer asking explorers rather than exploring the codebase yourself. +- Spawn multiple explorers in parallel when useful and wait for all results. +- You can ask the `explorer` to return file name, lines, entire code snippets, ... +- Reuse the same explorer when it is relevant. If later in your process you have more questions on some code an explorer already covered, reuse this same explorer to be more efficient. + "#, ..Default::default() }, } From 538e1059a3b4eaa78b16b04de8de0043b9f21ff8 Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Tue, 27 Jan 2026 09:43:09 -0800 Subject: [PATCH 009/116] TUI footer: right-align context and degrade shortcut summary + mode cleanly (#9944) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Refines the bottom footer layout to keep `% context left` right-aligned while making the left side degrade cleanly ## Behavior with empty textarea Full width: Screenshot 2026-01-26 at 2 59 59 PM Less: Screenshot 2026-01-26 at 2 59 48 PM Min width: Screenshot 2026-01-26 at 2 59 33 PM ## Behavior with message in textarea and agent running (steer enabled) Full width: Screenshot 2026-01-26 at 4 33 54 PM Less: Screenshot 2026-01-26 at 4 30 12 PM Less: Screenshot 2026-01-26 at 4 30 51 PM Less: Screenshot 2026-01-26 at 4 30 56 PM Less: Screenshot 2026-01-26 at 4 31 08 PM ## Notes / Edge Cases - In steer mode while typing, the queue hint no longer replaces the mode label; it renders as `tab to queue message · {Mode}`. - Collapse priorities differ by state: - With the queue hint active, `% context left` is hidden before shortening or dropping the queue hint. - In the empty + non-running state, `? for shortcuts` is dropped first, and `% context left` is only shown if `(shift+tab to cycle)` can also fit. - Transient instructional states (`?` overlay, Esc hint, Ctrl+C/D reminders, and flash/override hints) intentionally suppress the mode label (and context) to focus the next action. ## Implementation Notes - Renamed the base footer modes to make the state explicit: `ComposerEmpty` and `ComposerHasDraft`, and compute the base mode directly from emptiness. - Unified collapse behavior in `single_line_footer_layout` for both base modes, with: - Queue-hint behavior that prefers keeping the queue hint over context. - A cycle-hint guard that prevents context from reappearing after `(shift+tab to cycle)` is dropped. - Kept rendering responsibilities explicit: - `single_line_footer_layout` decides what fits. - `render_footer_line` renders a chosen line. - `render_footer_from_props` renders the canonical mode-to-text mapping. - Expanded snapshot coverage: - Added `footer_collapse_snapshots` in `chat_composer.rs` to lock the distinct collapse states across widths. - Consolidated the width-aware snapshot helper usage (e.g., `snapshot_composer_state_with_width`, `snapshot_footer_with_mode_indicator`). --- .codespellrc | 2 +- codex-rs/tui/src/bottom_pane/chat_composer.rs | 316 ++++++++- codex-rs/tui/src/bottom_pane/footer.rs | 610 +++++++++++++++--- ...mposer__tests__backspace_after_pastes.snap | 2 +- ...tom_pane__chat_composer__tests__empty.snap | 2 +- ...er__tests__footer_collapse_empty_full.snap | 13 + ...ollapse_empty_mode_cycle_with_context.snap | 13 + ...apse_empty_mode_cycle_without_context.snap | 13 + ...ests__footer_collapse_empty_mode_only.snap | 13 + ...er__tests__footer_collapse_queue_full.snap | 13 + ...ollapse_queue_message_without_context.snap | 13 + ...ests__footer_collapse_queue_mode_only.snap | 13 + ...ter_collapse_queue_short_with_context.snap | 13 + ..._collapse_queue_short_without_context.snap | 13 + ...ests__footer_mode_hidden_while_typing.snap | 2 +- ...er__tests__image_placeholder_multiple.snap | 3 +- ...oser__tests__image_placeholder_single.snap | 3 +- ...tom_pane__chat_composer__tests__large.snap | 2 +- ...chat_composer__tests__multiple_pastes.snap | 2 +- ...tom_pane__chat_composer__tests__small.snap | 2 +- ...omposer_has_draft_queue_hint_disabled.snap | 5 + ...composer_has_draft_queue_hint_enabled.snap | 5 + ...oter_context_only_queue_hint_disabled.snap | 5 - ...ooter_context_only_queue_hint_enabled.snap | 5 - ...er__tests__footer_context_tokens_used.snap | 2 +- ...r_mode_indicator_narrow_overlap_hides.snap | 2 +- ...ter_mode_indicator_running_hides_hint.snap | 2 +- ...er__tests__footer_mode_indicator_wide.snap | 2 +- ...sts__footer_shortcuts_context_running.snap | 2 +- ...oter__tests__footer_shortcuts_default.snap | 2 +- ...s_visible_when_status_hidden_snapshot.snap | 2 +- ...er_fill_height_without_bottom_padding.snap | 2 +- ...__status_and_queued_messages_snapshot.snap | 2 +- ...tom_pane__tests__status_only_snapshot.snap | 2 +- ..._details_and_queued_messages_snapshot.snap | 2 +- ...exec_and_status_layout_vt100_snapshot.snap | 2 +- ...i__chatwidget__tests__chatwidget_tall.snap | 2 +- ...et__tests__mcp_startup_header_booting.snap | 2 +- ..._review_queues_user_messages_snapshot.snap | 2 +- ...atwidget__tests__status_widget_active.snap | 3 +- 40 files changed, 949 insertions(+), 167 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_disabled.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_enabled.snap delete mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_disabled.snap delete mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_enabled.snap diff --git a/.codespellrc b/.codespellrc index 84b4495e31..a3f0cd501a 100644 --- a/.codespellrc +++ b/.codespellrc @@ -1,6 +1,6 @@ [codespell] # Ref: https://github.com/codespell-project/codespell#using-a-config-file -skip = .git*,vendor,*-lock.yaml,*.lock,.codespellrc,*test.ts,*.jsonl,frame*.txt +skip = .git*,vendor,*-lock.yaml,*.lock,.codespellrc,*test.ts,*.jsonl,frame*.txt,*.snap,*.snap.new check-hidden = true ignore-regex = ^\s*"image/\S+": ".*|\b(afterAll)\b ignore-words-list = ratatui,ser,iTerm,iterm2,iterm diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index c283b10ab1..909061aa68 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -96,15 +96,20 @@ use super::file_search_popup::FileSearchPopup; use super::footer::CollaborationModeIndicator; use super::footer::FooterMode; use super::footer::FooterProps; +use super::footer::SummaryLeft; +use super::footer::can_show_left_with_context; +use super::footer::context_window_line; use super::footer::esc_hint_mode; use super::footer::footer_height; use super::footer::footer_hint_items_width; use super::footer::footer_line_width; use super::footer::inset_footer_hint_area; -use super::footer::render_footer; +use super::footer::render_context_right; +use super::footer::render_footer_from_props; use super::footer::render_footer_hint_items; -use super::footer::render_mode_indicator; +use super::footer::render_footer_line; use super::footer::reset_mode_after_activity; +use super::footer::single_line_footer_layout; use super::footer::toggle_shortcut_mode; use super::paste_burst::CharDecision; use super::paste_burst::PasteBurst; @@ -341,7 +346,7 @@ impl ChatComposer { paste_burst: PasteBurst::default(), disable_paste_burst: false, custom_prompts: Vec::new(), - footer_mode: FooterMode::ShortcutSummary, + footer_mode: FooterMode::ComposerEmpty, footer_hint_override: None, footer_flash: None, context_window_percent: None, @@ -2234,7 +2239,11 @@ impl ChatComposer { return false; } - let next = toggle_shortcut_mode(self.footer_mode, self.quit_shortcut_hint_visible()); + let next = toggle_shortcut_mode( + self.footer_mode, + self.quit_shortcut_hint_visible(), + self.is_empty(), + ); let changed = next != self.footer_mode; self.footer_mode = next; changed @@ -2254,19 +2263,32 @@ impl ChatComposer { } } + /// Resolve the effective footer mode via a small priority waterfall. + /// + /// The base mode is derived solely from whether the composer is empty: + /// `ComposerEmpty` iff empty, otherwise `ComposerHasDraft`. Transient + /// modes (Esc hint, overlay, quit reminder) can override that base when + /// their conditions are active. fn footer_mode(&self) -> FooterMode { + let base_mode = if self.is_empty() { + FooterMode::ComposerEmpty + } else { + FooterMode::ComposerHasDraft + }; + match self.footer_mode { FooterMode::EscHint => FooterMode::EscHint, FooterMode::ShortcutOverlay => FooterMode::ShortcutOverlay, FooterMode::QuitShortcutReminder if self.quit_shortcut_hint_visible() => { FooterMode::QuitShortcutReminder } - FooterMode::QuitShortcutReminder => FooterMode::ShortcutSummary, - FooterMode::ShortcutSummary if self.quit_shortcut_hint_visible() => { + FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft + if self.quit_shortcut_hint_visible() => + { FooterMode::QuitShortcutReminder } - FooterMode::ShortcutSummary if !self.is_empty() => FooterMode::ContextOnly, - other => other, + FooterMode::QuitShortcutReminder => base_mode, + FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft => base_mode, } } @@ -2584,6 +2606,28 @@ impl Renderable for ChatComposer { } ActivePopup::None => { let footer_props = self.footer_props(); + let show_cycle_hint = !footer_props.is_task_running; + let show_shortcuts_hint = match footer_props.mode { + FooterMode::ComposerEmpty => !self.is_in_paste_burst(), + FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + | FooterMode::EscHint + | FooterMode::ComposerHasDraft => false, + }; + let show_queue_hint = match footer_props.mode { + FooterMode::ComposerHasDraft => { + footer_props.is_task_running && footer_props.steer_enabled + } + FooterMode::QuitShortcutReminder + | FooterMode::ComposerEmpty + | FooterMode::ShortcutOverlay + | FooterMode::EscHint => false, + }; + let context_line = context_window_line( + footer_props.context_window_percent, + footer_props.context_window_used_tokens, + ); + let context_width = context_line.width() as u16; let custom_height = self.custom_footer_height(); let footer_hint_height = custom_height.unwrap_or_else(|| footer_height(footer_props)); @@ -2598,26 +2642,102 @@ impl Renderable for ChatComposer { } else { popup_rect }; - let mut left_content_width = None; - if self.footer_flash_visible() { + let left_width = if self.footer_flash_visible() { + self.footer_flash + .as_ref() + .map(|flash| flash.line.width() as u16) + .unwrap_or(0) + } else if let Some(items) = self.footer_hint_override.as_ref() { + footer_hint_items_width(items) + } else { + footer_line_width( + footer_props, + self.collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ) + }; + let can_show_left_and_context = + can_show_left_with_context(hint_rect, left_width, context_width); + let has_override = + self.footer_flash_visible() || self.footer_hint_override.is_some(); + let single_line_layout = if has_override { + None + } else { + match footer_props.mode { + FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft => { + // Both of these modes render the single-line footer style (with + // either the shortcuts hint or the optional queue hint). We still + // want the single-line collapse rules so the mode label can win over + // the context indicator on narrow widths. + Some(single_line_footer_layout( + hint_rect, + context_width, + self.collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + )) + } + FooterMode::EscHint + | FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay => None, + } + }; + let show_context = if matches!( + footer_props.mode, + FooterMode::EscHint + | FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + ) { + false + } else { + single_line_layout + .as_ref() + .map(|(_, show_context)| *show_context) + .unwrap_or(can_show_left_and_context) + }; + + if let Some((summary_left, _)) = single_line_layout { + match summary_left { + SummaryLeft::Default => { + render_footer_from_props( + hint_rect, + buf, + footer_props, + self.collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ); + } + SummaryLeft::Custom(line) => { + render_footer_line(hint_rect, buf, line); + } + SummaryLeft::None => {} + } + } else if self.footer_flash_visible() { if let Some(flash) = self.footer_flash.as_ref() { flash.line.render(inset_footer_hint_area(hint_rect), buf); - left_content_width = Some(flash.line.width() as u16); } } else if let Some(items) = self.footer_hint_override.as_ref() { render_footer_hint_items(hint_rect, buf, items); - left_content_width = Some(footer_hint_items_width(items)); } else { - render_footer(hint_rect, buf, footer_props); - left_content_width = Some(footer_line_width(footer_props)); + render_footer_from_props( + hint_rect, + buf, + footer_props, + self.collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ); + } + + if show_context { + render_context_right(hint_rect, buf, &context_line); } - render_mode_indicator( - hint_rect, - buf, - self.collaboration_mode_indicator, - !footer_props.is_task_running, - left_content_width, - ); } } let style = user_message_style(); @@ -2647,8 +2767,11 @@ impl Renderable for ChatComposer { .unwrap_or("Input disabled.") .to_string() }; - let placeholder = Span::from(text).dim(); - Line::from(vec![placeholder]).render_ref(textarea_rect.inner(Margin::new(0, 0)), buf); + if !textarea_rect.is_empty() { + let placeholder = Span::from(text).dim(); + Line::from(vec![placeholder]) + .render_ref(textarea_rect.inner(Margin::new(0, 0)), buf); + } } } } @@ -2861,14 +2984,17 @@ mod tests { ); } - fn snapshot_composer_state(name: &str, enhanced_keys_supported: bool, setup: F) - where + fn snapshot_composer_state_with_width( + name: &str, + width: u16, + enhanced_keys_supported: bool, + setup: F, + ) where F: FnOnce(&mut ChatComposer), { use ratatui::Terminal; use ratatui::backend::TestBackend; - let width = 100; let (tx, _rx) = unbounded_channel::(); let sender = AppEventSender::new(tx); let mut composer = ChatComposer::new( @@ -2890,6 +3016,13 @@ mod tests { insta::assert_snapshot!(name, terminal.backend()); } + fn snapshot_composer_state(name: &str, enhanced_keys_supported: bool, setup: F) + where + F: FnOnce(&mut ChatComposer), + { + snapshot_composer_state_with_width(name, 100, enhanced_keys_supported, setup); + } + #[test] fn footer_mode_snapshots() { use crossterm::event::KeyCode; @@ -2942,6 +3075,100 @@ mod tests { }); } + #[test] + fn footer_collapse_snapshots() { + fn setup_collab_footer( + composer: &mut ChatComposer, + context_percent: i64, + indicator: CollaborationModeIndicator, + ) { + composer.set_collaboration_modes_enabled(true); + composer.set_collaboration_mode_indicator(Some(indicator)); + composer.set_context_window(Some(context_percent), None); + } + + // Empty textarea, agent idle: shortcuts hint can show, and cycle hint is available. + snapshot_composer_state_with_width("footer_collapse_empty_full", 120, true, |composer| { + setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + }); + snapshot_composer_state_with_width( + "footer_collapse_empty_mode_cycle_with_context", + 60, + true, + |composer| { + setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_empty_mode_cycle_without_context", + 44, + true, + |composer| { + setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_empty_mode_only", + 26, + true, + |composer| { + setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + }, + ); + + // Textarea has content, agent running, steer enabled: queue hint is shown. + snapshot_composer_state_with_width("footer_collapse_queue_full", 120, true, |composer| { + setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }); + snapshot_composer_state_with_width( + "footer_collapse_queue_short_with_context", + 50, + true, + |composer| { + setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_queue_message_without_context", + 40, + true, + |composer| { + setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_queue_short_without_context", + 30, + true, + |composer| { + setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_queue_mode_only", + 20, + true, + |composer| { + setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + } + #[test] fn esc_hint_stays_hidden_with_draft_content() { use crossterm::event::KeyCode; @@ -2962,15 +3189,40 @@ mod tests { assert!(!composer.is_empty()); assert_eq!(composer.current_text(), "d"); - assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary); + assert_eq!(composer.footer_mode, FooterMode::ComposerEmpty); assert!(matches!(composer.active_popup, ActivePopup::None)); let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary); + assert_eq!(composer.footer_mode, FooterMode::ComposerEmpty); assert!(!composer.esc_backtrack_hint); } + #[test] + fn base_footer_mode_tracks_empty_state_after_quit_hint_expires() { + use crossterm::event::KeyCode; + + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + + type_chars_humanlike(&mut composer, &['d']); + composer.show_quit_shortcut_hint(key_hint::ctrl(KeyCode::Char('c')), true); + composer.quit_shortcut_expires_at = + Some(Instant::now() - std::time::Duration::from_secs(1)); + + assert_eq!(composer.footer_mode(), FooterMode::ComposerHasDraft); + + composer.set_text_content(String::new(), Vec::new(), Vec::new()); + assert_eq!(composer.footer_mode(), FooterMode::ComposerEmpty); + } + #[test] fn clear_for_ctrl_c_records_cleared_draft() { let (tx, _rx) = unbounded_channel::(); @@ -3031,11 +3283,11 @@ mod tests { // Toggle back to prompt mode so subsequent typing captures characters. let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); - assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary); + assert_eq!(composer.footer_mode, FooterMode::ComposerEmpty); type_chars_humanlike(&mut composer, &['h']); assert_eq!(composer.textarea.text(), "h"); - assert_eq!(composer.footer_mode(), FooterMode::ContextOnly); + assert_eq!(composer.footer_mode(), FooterMode::ComposerHasDraft); let (result, needs_redraw) = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); @@ -3043,8 +3295,8 @@ mod tests { assert!(needs_redraw, "typing should still mark the view dirty"); let _ = flush_after_paste_burst(&mut composer); assert_eq!(composer.textarea.text(), "h?"); - assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary); - assert_eq!(composer.footer_mode(), FooterMode::ContextOnly); + assert_eq!(composer.footer_mode, FooterMode::ComposerEmpty); + assert_eq!(composer.footer_mode(), FooterMode::ComposerHasDraft); } /// Behavior: while a paste-like burst is being captured, `?` must not toggle the shortcut diff --git a/codex-rs/tui/src/bottom_pane/footer.rs b/codex-rs/tui/src/bottom_pane/footer.rs index 16f4f22a94..69c5e7bb00 100644 --- a/codex-rs/tui/src/bottom_pane/footer.rs +++ b/codex-rs/tui/src/bottom_pane/footer.rs @@ -8,6 +8,30 @@ //! Some footer content is time-based rather than event-based, such as the "press again to quit" //! hint. The owning widgets schedule redraws so time-based hints can expire even if the UI is //! otherwise idle. +//! +//! Single-line collapse overview: +//! 1. The composer decides the current `FooterMode` and hint flags, then calls +//! `single_line_footer_layout` for the base single-line modes. +//! 2. `single_line_footer_layout` applies the width-based fallback rules: +//! (If this description is hard to follow, just try it out by resizing +//! your terminal width; these rules were built out of trial and error.) +//! - Start with the fullest left-side hint plus the right-side context. +//! - When the queue hint is active, prefer keeping that queue hint visible, +//! even if it means dropping the right-side context earlier; the queue +//! hint may also be shortened before it is removed. +//! - When the queue hint is not active but the mode cycle hint is applicable, +//! drop "? for shortcuts" before dropping "(shift+tab to cycle)". +//! - If "(shift+tab to cycle)" cannot fit, also hide the right-side +//! context to avoid too many state transitions in quick succession. +//! - Finally, try a mode-only line (with and without context), and fall +//! back to no left-side footer if nothing can fit. +//! 3. When collapse chooses a specific line, callers render it via +//! `render_footer_line`. Otherwise, callers render the straightforward +//! mode-to-text mapping via `render_footer_from_props`. +//! +//! In short: `single_line_footer_layout` chooses *what* best fits, and the two +//! render helpers choose whether to draw the chosen line or the default +//! `FooterProps` mapping. #[cfg(target_os = "linux")] use crate::clipboard_paste::is_probably_wsl; use crate::key_hint; @@ -27,9 +51,10 @@ use ratatui::widgets::Widget; /// The rendering inputs for the footer area under the composer. /// /// Callers are expected to construct `FooterProps` from higher-level state (`ChatComposer`, -/// `BottomPane`, and `ChatWidget`) and pass it to `render_footer`. The footer treats these values as -/// authoritative and does not attempt to infer missing state (for example, it does not query -/// whether a task is running). +/// `BottomPane`, and `ChatWidget`) and pass it to the footer render helpers +/// (`render_footer_from_props` or the single-line collapse logic). The footer +/// treats these values as authoritative and does not attempt to infer missing +/// state (for example, it does not query whether a task is running). #[derive(Clone, Copy, Debug)] pub(crate) struct FooterProps { pub(crate) mode: FooterMode, @@ -77,7 +102,7 @@ impl CollaborationModeIndicator { let label = self.label(show_cycle_hint); match self { CollaborationModeIndicator::Plan => Span::from(label).magenta(), - CollaborationModeIndicator::Code => Span::from(label).cyan(), + CollaborationModeIndicator::Code => Span::from(label).dim(), CollaborationModeIndicator::PairProgramming => Span::from(label).cyan(), CollaborationModeIndicator::Execute => Span::from(label).dim(), } @@ -92,21 +117,36 @@ impl CollaborationModeIndicator { pub(crate) enum FooterMode { /// Transient "press again to quit" reminder (Ctrl+C/Ctrl+D). QuitShortcutReminder, - ShortcutSummary, + /// Multi-line shortcut overlay shown after pressing `?`. ShortcutOverlay, + /// Transient "press Esc again" hint shown after the first Esc while idle. EscHint, - ContextOnly, + /// Base single-line footer when the composer is empty. + ComposerEmpty, + /// Base single-line footer when the composer contains a draft. + /// + /// The shortcuts hint is suppressed here; when a task is running with + /// steer enabled, this mode can show the queue hint instead. + ComposerHasDraft, } -pub(crate) fn toggle_shortcut_mode(current: FooterMode, ctrl_c_hint: bool) -> FooterMode { +pub(crate) fn toggle_shortcut_mode( + current: FooterMode, + ctrl_c_hint: bool, + is_empty: bool, +) -> FooterMode { if ctrl_c_hint && matches!(current, FooterMode::QuitShortcutReminder) { return current; } + let base_mode = if is_empty { + FooterMode::ComposerEmpty + } else { + FooterMode::ComposerHasDraft + }; + match current { - FooterMode::ShortcutOverlay | FooterMode::QuitShortcutReminder => { - FooterMode::ShortcutSummary - } + FooterMode::ShortcutOverlay | FooterMode::QuitShortcutReminder => base_mode, _ => FooterMode::ShortcutOverlay, } } @@ -124,57 +164,347 @@ pub(crate) fn reset_mode_after_activity(current: FooterMode) -> FooterMode { FooterMode::EscHint | FooterMode::ShortcutOverlay | FooterMode::QuitShortcutReminder - | FooterMode::ContextOnly => FooterMode::ShortcutSummary, + | FooterMode::ComposerHasDraft => FooterMode::ComposerEmpty, other => other, } } pub(crate) fn footer_height(props: FooterProps) -> u16 { - footer_lines(props).len() as u16 + let show_shortcuts_hint = match props.mode { + FooterMode::ComposerEmpty => true, + FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + | FooterMode::EscHint + | FooterMode::ComposerHasDraft => false, + }; + let show_queue_hint = match props.mode { + FooterMode::ComposerHasDraft => props.is_task_running && props.steer_enabled, + FooterMode::QuitShortcutReminder + | FooterMode::ComposerEmpty + | FooterMode::ShortcutOverlay + | FooterMode::EscHint => false, + }; + footer_from_props_lines(props, None, false, show_shortcuts_hint, show_queue_hint).len() as u16 } -pub(crate) fn render_footer(area: Rect, buf: &mut Buffer, props: FooterProps) { +/// Render a single precomputed footer line. +pub(crate) fn render_footer_line(area: Rect, buf: &mut Buffer, line: Line<'static>) { Paragraph::new(prefix_lines( - footer_lines(props), + vec![line], " ".repeat(FOOTER_INDENT_COLS).into(), " ".repeat(FOOTER_INDENT_COLS).into(), )) .render(area, buf); } -pub(crate) fn render_mode_indicator( +/// Render footer content directly from `FooterProps`. +/// +/// This is intentionally not part of the width-based collapse/fallback logic. +/// Transient instructional states (shortcut overlay, Esc hint, quit reminder) +/// prioritize "what to do next" instructions and currently suppress the +/// collaboration mode label entirely. When collapse logic has already chosen a +/// specific single line, prefer `render_footer_line`. +pub(crate) fn render_footer_from_props( area: Rect, buf: &mut Buffer, - indicator: Option, + props: FooterProps, + collaboration_mode_indicator: Option, show_cycle_hint: bool, - left_content_width: Option, + show_shortcuts_hint: bool, + show_queue_hint: bool, ) { - let Some(indicator) = indicator else { - return; + Paragraph::new(prefix_lines( + footer_from_props_lines( + props, + collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ), + " ".repeat(FOOTER_INDENT_COLS).into(), + " ".repeat(FOOTER_INDENT_COLS).into(), + )) + .render(area, buf); +} + +pub(crate) fn left_fits(area: Rect, left_width: u16) -> bool { + let max_width = area.width.saturating_sub(FOOTER_INDENT_COLS as u16); + left_width <= max_width +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SummaryHintKind { + None, + Shortcuts, + QueueMessage, + QueueShort, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct LeftSideState { + hint: SummaryHintKind, + show_cycle_hint: bool, +} + +fn left_side_line( + collaboration_mode_indicator: Option, + state: LeftSideState, +) -> Line<'static> { + let mut line = Line::from(""); + match state.hint { + SummaryHintKind::None => {} + SummaryHintKind::Shortcuts => { + line.push_span(key_hint::plain(KeyCode::Char('?'))); + line.push_span(" for shortcuts".dim()); + } + SummaryHintKind::QueueMessage => { + line.push_span(key_hint::plain(KeyCode::Tab)); + line.push_span(" to queue message".dim()); + } + SummaryHintKind::QueueShort => { + line.push_span(key_hint::plain(KeyCode::Tab)); + line.push_span(" to queue".dim()); + } }; + + if let Some(collaboration_mode_indicator) = collaboration_mode_indicator { + if !matches!(state.hint, SummaryHintKind::None) { + line.push_span(" · ".dim()); + } + line.push_span(collaboration_mode_indicator.styled_span(state.show_cycle_hint)); + } + + line +} + +pub(crate) enum SummaryLeft { + Default, + Custom(Line<'static>), + None, +} + +/// Compute the single-line footer layout and whether the right-side context +/// indicator can be shown alongside it. +pub(crate) fn single_line_footer_layout( + area: Rect, + context_width: u16, + collaboration_mode_indicator: Option, + show_cycle_hint: bool, + show_shortcuts_hint: bool, + show_queue_hint: bool, +) -> (SummaryLeft, bool) { + let hint_kind = if show_queue_hint { + SummaryHintKind::QueueMessage + } else if show_shortcuts_hint { + SummaryHintKind::Shortcuts + } else { + SummaryHintKind::None + }; + let default_state = LeftSideState { + hint: hint_kind, + show_cycle_hint, + }; + let default_line = left_side_line(collaboration_mode_indicator, default_state); + let default_width = default_line.width() as u16; + if default_width > 0 && can_show_left_with_context(area, default_width, context_width) { + return (SummaryLeft::Default, true); + } + + let state_line = |state: LeftSideState| -> Line<'static> { + if state == default_state { + default_line.clone() + } else { + left_side_line(collaboration_mode_indicator, state) + } + }; + let state_width = |state: LeftSideState| -> u16 { state_line(state).width() as u16 }; + // When the mode cycle hint is applicable (idle, non-queue mode), only show + // the right-side context indicator if the "(shift+tab to cycle)" variant + // can also fit. + let context_requires_cycle_hint = show_cycle_hint && !show_queue_hint; + + if show_queue_hint { + // In queue mode, prefer dropping context before dropping the queue hint. + let queue_states = [ + default_state, + LeftSideState { + hint: SummaryHintKind::QueueMessage, + show_cycle_hint: false, + }, + LeftSideState { + hint: SummaryHintKind::QueueShort, + show_cycle_hint: false, + }, + ]; + + // Pass 1: keep the right-side context indicator if any queue variant + // can fit alongside it. We skip adjacent duplicates because + // `default_state` can already be the no-cycle queue variant. + let mut previous_state: Option = None; + for state in queue_states { + if previous_state == Some(state) { + continue; + } + previous_state = Some(state); + let width = state_width(state); + if width > 0 && can_show_left_with_context(area, width, context_width) { + if state == default_state { + return (SummaryLeft::Default, true); + } + return (SummaryLeft::Custom(state_line(state)), true); + } + } + + // Pass 2: if context cannot fit, drop it before dropping the queue + // hint. Reuse the same dedupe so we do not try equivalent states twice. + let mut previous_state: Option = None; + for state in queue_states { + if previous_state == Some(state) { + continue; + } + previous_state = Some(state); + let width = state_width(state); + if width > 0 && left_fits(area, width) { + if state == default_state { + return (SummaryLeft::Default, false); + } + return (SummaryLeft::Custom(state_line(state)), false); + } + } + } else if collaboration_mode_indicator.is_some() { + if show_cycle_hint { + // First fallback: drop shortcut hint but keep the cycle + // hint on the mode label if it can fit. + let cycle_state = LeftSideState { + hint: SummaryHintKind::None, + show_cycle_hint: true, + }; + let cycle_width = state_width(cycle_state); + if cycle_width > 0 && can_show_left_with_context(area, cycle_width, context_width) { + return (SummaryLeft::Custom(state_line(cycle_state)), true); + } + if cycle_width > 0 && left_fits(area, cycle_width) { + return (SummaryLeft::Custom(state_line(cycle_state)), false); + } + } + + // Next fallback: mode label only. If the cycle hint is applicable but + // cannot fit, we also suppress context so the right side does not + // outlive "(shift+tab to cycle)" on the left. + let mode_only_state = LeftSideState { + hint: SummaryHintKind::None, + show_cycle_hint: false, + }; + let mode_only_width = state_width(mode_only_state); + if !context_requires_cycle_hint + && mode_only_width > 0 + && can_show_left_with_context(area, mode_only_width, context_width) + { + return ( + SummaryLeft::Custom(state_line(mode_only_state)), + true, // show_context + ); + } + if mode_only_width > 0 && left_fits(area, mode_only_width) { + return ( + SummaryLeft::Custom(state_line(mode_only_state)), + false, // show_context + ); + } + } + + // Final fallback: if queue variants (or other earlier states) could not fit + // at all, drop every hint and try to show just the mode label. + if let Some(collaboration_mode_indicator) = collaboration_mode_indicator { + let mode_only_state = LeftSideState { + hint: SummaryHintKind::None, + show_cycle_hint: false, + }; + // Compute the width without going through `state_line` so we do not + // depend on `default_state` (which may still be a queue variant). + let mode_only_width = + left_side_line(Some(collaboration_mode_indicator), mode_only_state).width() as u16; + if !context_requires_cycle_hint + && can_show_left_with_context(area, mode_only_width, context_width) + { + return ( + SummaryLeft::Custom(left_side_line( + Some(collaboration_mode_indicator), + mode_only_state, + )), + true, // show_context + ); + } + if left_fits(area, mode_only_width) { + return ( + SummaryLeft::Custom(left_side_line( + Some(collaboration_mode_indicator), + mode_only_state, + )), + false, // show_context + ); + } + } + + (SummaryLeft::None, true) +} + +fn right_aligned_x(area: Rect, content_width: u16) -> Option { + if area.is_empty() { + return None; + } + + let right_padding = FOOTER_INDENT_COLS as u16; + let max_width = area.width.saturating_sub(right_padding); + if content_width == 0 || max_width == 0 { + return None; + } + + if content_width >= max_width { + return Some(area.x.saturating_add(right_padding)); + } + + Some( + area.x + .saturating_add(area.width) + .saturating_sub(content_width) + .saturating_sub(right_padding), + ) +} + +pub(crate) fn can_show_left_with_context(area: Rect, left_width: u16, context_width: u16) -> bool { + let Some(context_x) = right_aligned_x(area, context_width) else { + return true; + }; + let left_extent = FOOTER_INDENT_COLS as u16 + left_width; + left_extent <= context_x.saturating_sub(area.x) +} + +pub(crate) fn render_context_right(area: Rect, buf: &mut Buffer, line: &Line<'static>) { if area.is_empty() { return; } - let span = indicator.styled_span(show_cycle_hint); - let label_width = span.width() as u16; - if label_width == 0 || label_width > area.width { + let context_width = line.width() as u16; + let Some(mut x) = right_aligned_x(area, context_width) else { return; - } - - let x = area - .x - .saturating_add(area.width) - .saturating_sub(label_width) - .saturating_sub(FOOTER_INDENT_COLS as u16); + }; let y = area.y + area.height.saturating_sub(1); - if let Some(left_content_width) = left_content_width { - let left_extent = FOOTER_INDENT_COLS as u16 + left_content_width; - if left_extent >= x.saturating_sub(area.x) { - return; + let max_x = area.x.saturating_add(area.width); + + for span in &line.spans { + if x >= max_x { + break; } + let span_width = span.width() as u16; + if span_width == 0 { + continue; + } + let remaining = max_x.saturating_sub(x); + let draw_width = span_width.min(remaining); + buf.set_span(x, y, span, draw_width); + x = x.saturating_add(span_width); } - buf.set_span(x, y, &span, label_width); } pub(crate) fn inset_footer_hint_area(mut area: Rect) -> Rect { @@ -193,26 +523,35 @@ pub(crate) fn render_footer_hint_items(area: Rect, buf: &mut Buffer, items: &[(S footer_hint_items_line(items).render(inset_footer_hint_area(area), buf); } -fn footer_lines(props: FooterProps) -> Vec> { - // Show the context indicator on the left, appended after the primary hint - // (e.g., "? for shortcuts"). Keep it visible even when typing (i.e., when - // the shortcut hint is hidden). Hide it only for the multi-line - // ShortcutOverlay. +/// Map `FooterProps` to footer lines without width-based collapse. +/// +/// This is the canonical FooterMode-to-text mapping. It powers transient, +/// instructional states (shortcut overlay, Esc hint, quit reminder) and also +/// the default rendering for base states when collapse is not applied (or when +/// `single_line_footer_layout` returns `SummaryLeft::Default`). Collapse and +/// fallback decisions live in `single_line_footer_layout`; this function only +/// formats the chosen/default content. +fn footer_from_props_lines( + props: FooterProps, + collaboration_mode_indicator: Option, + show_cycle_hint: bool, + show_shortcuts_hint: bool, + show_queue_hint: bool, +) -> Vec> { match props.mode { FooterMode::QuitShortcutReminder => { vec![quit_shortcut_reminder_line(props.quit_shortcut_key)] } - FooterMode::ShortcutSummary => { - let mut line = context_window_line( - props.context_window_percent, - props.context_window_used_tokens, - ); - line.push_span(" · ".dim()); - line.extend(vec![ - key_hint::plain(KeyCode::Char('?')).into(), - " for shortcuts".dim(), - ]); - vec![line] + FooterMode::ComposerEmpty => { + let state = LeftSideState { + hint: if show_shortcuts_hint { + SummaryHintKind::Shortcuts + } else { + SummaryHintKind::None + }, + show_cycle_hint, + }; + vec![left_side_line(collaboration_mode_indicator, state)] } FooterMode::ShortcutOverlay => { #[cfg(target_os = "linux")] @@ -229,26 +568,37 @@ fn footer_lines(props: FooterProps) -> Vec> { shortcut_overlay_lines(state) } FooterMode::EscHint => vec![esc_hint_line(props.esc_backtrack_hint)], - FooterMode::ContextOnly => { - let mut line = context_window_line( - props.context_window_percent, - props.context_window_used_tokens, - ); - if props.is_task_running && props.steer_enabled { - line.push_span(" · ".dim()); - line.push_span(key_hint::plain(KeyCode::Tab)); - line.push_span(" to queue message".dim()); - } - vec![line] + FooterMode::ComposerHasDraft => { + let state = LeftSideState { + hint: if show_queue_hint { + SummaryHintKind::QueueMessage + } else { + SummaryHintKind::None + }, + show_cycle_hint, + }; + vec![left_side_line(collaboration_mode_indicator, state)] } } } -pub(crate) fn footer_line_width(props: FooterProps) -> u16 { - footer_lines(props) - .last() - .map(|line| line.width() as u16) - .unwrap_or(0) +pub(crate) fn footer_line_width( + props: FooterProps, + collaboration_mode_indicator: Option, + show_cycle_hint: bool, + show_shortcuts_hint: bool, + show_queue_hint: bool, +) -> u16 { + footer_from_props_lines( + props, + collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ) + .last() + .map(|line| line.width() as u16) + .unwrap_or(0) } pub(crate) fn footer_hint_items_width(items: &[(String, String)]) -> u16 { @@ -396,7 +746,7 @@ fn build_columns(entries: Vec>) -> Vec> { .collect() } -fn context_window_line(percent: Option, used_tokens: Option) -> Line<'static> { +pub(crate) fn context_window_line(percent: Option, used_tokens: Option) -> Line<'static> { if let Some(percent) = percent { let percent = percent.clamp(0, 100); return Line::from(vec![Span::from(format!("{percent}% context left")).dim()]); @@ -615,36 +965,102 @@ mod tests { use ratatui::backend::TestBackend; fn snapshot_footer(name: &str, props: FooterProps) { - let height = footer_height(props).max(1); - let mut terminal = Terminal::new(TestBackend::new(80, height)).unwrap(); - terminal - .draw(|f| { - let area = Rect::new(0, 0, f.area().width, height); - render_footer(area, f.buffer_mut(), props); - }) - .unwrap(); - assert_snapshot!(name, terminal.backend()); + snapshot_footer_with_mode_indicator(name, 80, props, None); } - fn snapshot_footer_with_indicator( + fn snapshot_footer_with_mode_indicator( name: &str, width: u16, props: FooterProps, - indicator: Option, + collaboration_mode_indicator: Option, ) { let height = footer_height(props).max(1); let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal .draw(|f| { let area = Rect::new(0, 0, f.area().width, height); - render_footer(area, f.buffer_mut(), props); - render_mode_indicator( - area, - f.buffer_mut(), - indicator, - !props.is_task_running, - Some(footer_line_width(props)), + let context_line = context_window_line( + props.context_window_percent, + props.context_window_used_tokens, ); + let context_width = context_line.width() as u16; + let show_cycle_hint = !props.is_task_running; + let show_shortcuts_hint = match props.mode { + FooterMode::ComposerEmpty => true, + FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + | FooterMode::EscHint + | FooterMode::ComposerHasDraft => false, + }; + let show_queue_hint = match props.mode { + FooterMode::ComposerHasDraft => props.is_task_running && props.steer_enabled, + FooterMode::QuitShortcutReminder + | FooterMode::ComposerEmpty + | FooterMode::ShortcutOverlay + | FooterMode::EscHint => false, + }; + let left_width = footer_line_width( + props, + collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ); + let can_show_left_and_context = + can_show_left_with_context(area, left_width, context_width); + if matches!( + props.mode, + FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft + ) { + let (summary_left, show_context) = single_line_footer_layout( + area, + context_width, + collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ); + match summary_left { + SummaryLeft::Default => { + render_footer_from_props( + area, + f.buffer_mut(), + props, + collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ); + } + SummaryLeft::Custom(line) => { + render_footer_line(area, f.buffer_mut(), line); + } + SummaryLeft::None => {} + } + if show_context { + render_context_right(area, f.buffer_mut(), &context_line); + } + } else { + render_footer_from_props( + area, + f.buffer_mut(), + props, + collaboration_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ); + let show_context = can_show_left_and_context + && !matches!( + props.mode, + FooterMode::EscHint + | FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + ); + if show_context { + render_context_right(area, f.buffer_mut(), &context_line); + } + } }) .unwrap(); assert_snapshot!(name, terminal.backend()); @@ -655,7 +1071,7 @@ mod tests { snapshot_footer( "footer_shortcuts_default", FooterProps { - mode: FooterMode::ShortcutSummary, + mode: FooterMode::ComposerEmpty, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, @@ -760,7 +1176,7 @@ mod tests { snapshot_footer( "footer_shortcuts_context_running", FooterProps { - mode: FooterMode::ShortcutSummary, + mode: FooterMode::ComposerEmpty, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, @@ -775,7 +1191,7 @@ mod tests { snapshot_footer( "footer_context_tokens_used", FooterProps { - mode: FooterMode::ShortcutSummary, + mode: FooterMode::ComposerEmpty, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, @@ -788,9 +1204,9 @@ mod tests { ); snapshot_footer( - "footer_context_only_queue_hint_disabled", + "footer_composer_has_draft_queue_hint_disabled", FooterProps { - mode: FooterMode::ContextOnly, + mode: FooterMode::ComposerHasDraft, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, @@ -803,9 +1219,9 @@ mod tests { ); snapshot_footer( - "footer_context_only_queue_hint_enabled", + "footer_composer_has_draft_queue_hint_enabled", FooterProps { - mode: FooterMode::ContextOnly, + mode: FooterMode::ComposerHasDraft, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, @@ -818,7 +1234,7 @@ mod tests { ); let props = FooterProps { - mode: FooterMode::ShortcutSummary, + mode: FooterMode::ComposerEmpty, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, @@ -829,14 +1245,14 @@ mod tests { context_window_used_tokens: None, }; - snapshot_footer_with_indicator( + snapshot_footer_with_mode_indicator( "footer_mode_indicator_wide", 120, props, Some(CollaborationModeIndicator::Plan), ); - snapshot_footer_with_indicator( + snapshot_footer_with_mode_indicator( "footer_mode_indicator_narrow_overlap_hides", 50, props, @@ -844,7 +1260,7 @@ mod tests { ); let props = FooterProps { - mode: FooterMode::ShortcutSummary, + mode: FooterMode::ComposerEmpty, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, @@ -855,7 +1271,7 @@ mod tests { context_window_used_tokens: None, }; - snapshot_footer_with_indicator( + snapshot_footer_with_mode_indicator( "footer_mode_indicator_running_hides_hint", 120, props, diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap index e4cc9ffefd..0b88e19a22 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" 100% context left " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap index 53e0aee4cf..47c97c74d2 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" 100% context left · ? for shortcuts " +" ? for shortcuts 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap new file mode 100644 index 0000000000..90a7b12e4a --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anything " +" " +" " +" " +" " +" " +" " +" ? for shortcuts · Code mode (shift+tab to cycle) 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap new file mode 100644 index 0000000000..cfc93be1e6 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anything " +" " +" " +" " +" " +" " +" " +" Code mode (shift+tab to cycle) 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap new file mode 100644 index 0000000000..9901a8fbbf --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anything " +" " +" " +" " +" " +" " +" " +" Code mode (shift+tab to cycle) " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap new file mode 100644 index 0000000000..98c7c33889 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anythin " +" " +" " +" " +" " +" " +" " +" Code mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap new file mode 100644 index 0000000000..cfb47fa9d7 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue message · Code mode 98% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap new file mode 100644 index 0000000000..0a91488b58 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue message · Code mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap new file mode 100644 index 0000000000..9adcc6e059 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" Code mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap new file mode 100644 index 0000000000..0910602616 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue · Code mode 98% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap new file mode 100644 index 0000000000..993dc34035 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue · Code mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap index 67e616e917..5faacfa64f 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" 100% context left " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_multiple.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_multiple.snap index 3f1adf6291..49eca416c2 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_multiple.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_multiple.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 2116 expression: terminal.backend() --- " " @@ -11,4 +10,4 @@ expression: terminal.backend() " " " " " " -" 100% context left " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_single.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_single.snap index e46fa0a740..3a5dd7a758 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_single.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__image_placeholder_single.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 2116 expression: terminal.backend() --- " " @@ -11,4 +10,4 @@ expression: terminal.backend() " " " " " " -" 100% context left " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap index 6b018021ec..d2f77dbec3 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" 100% context left " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap index 40098faee0..0d16cec0b4 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" 100% context left " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap index 498ed76936..8d3f8216db 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" 100% context left " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_disabled.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_disabled.snap new file mode 100644 index 0000000000..6fdeda07b1 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_disabled.snap @@ -0,0 +1,5 @@ +--- +source: tui/src/bottom_pane/footer.rs +expression: terminal.backend() +--- +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_enabled.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_enabled.snap new file mode 100644 index 0000000000..71370d83ba --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_enabled.snap @@ -0,0 +1,5 @@ +--- +source: tui/src/bottom_pane/footer.rs +expression: terminal.backend() +--- +" tab to queue message 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_disabled.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_disabled.snap deleted file mode 100644 index ce36b2ada8..0000000000 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_disabled.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/bottom_pane/footer.rs -expression: terminal.backend() ---- -" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_enabled.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_enabled.snap deleted file mode 100644 index b9733866d7..0000000000 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_only_queue_hint_enabled.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/bottom_pane/footer.rs -expression: terminal.backend() ---- -" 100% context left · tab to queue message " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_tokens_used.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_tokens_used.snap index a77ca5565b..b7ee60704c 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_tokens_used.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_tokens_used.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 123K used · ? for shortcuts " +" ? for shortcuts 123K used " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_narrow_overlap_hides.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_narrow_overlap_hides.snap index ed9fea7c88..6266f43d0b 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_narrow_overlap_hides.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_narrow_overlap_hides.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 100% context left · ? for shortcuts " +" Plan mode (shift+tab to cycle) " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_running_hides_hint.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_running_hides_hint.snap index fe5868b87c..9f9be080da 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_running_hides_hint.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_running_hides_hint.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 100% context left · ? for shortcuts Plan mode " +" ? for shortcuts · Plan mode 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_wide.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_wide.snap index 7212d6de51..8c32ee50dc 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_wide.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_mode_indicator_wide.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 100% context left · ? for shortcuts Plan mode (shift+tab to cycle) " +" ? for shortcuts · Plan mode (shift+tab to cycle) 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap index d05ac90a91..2a81b85576 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 72% context left · ? for shortcuts " +" ? for shortcuts 72% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap index c95a5dc0b3..02804e5735 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 100% context left · ? for shortcuts " +" ? for shortcuts 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap index 5aea415190..47581631c2 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap @@ -7,4 +7,4 @@ expression: "render_snapshot(&pane, area)" › Ask Codex to do anything - 100% context left · ? for shortcuts + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap index 86e3da4573..494883e4c3 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap @@ -7,4 +7,4 @@ expression: "render_snapshot(&pane, area)" › Ask Codex to do anything - 100% context left · ? for sh + 100% context left diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_queued_messages_snapshot.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_queued_messages_snapshot.snap index e651ec9274..a82f6512cf 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_queued_messages_snapshot.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_queued_messages_snapshot.snap @@ -9,4 +9,4 @@ expression: "render_snapshot(&pane, area)" › Ask Codex to do anything - 100% context left · ? for shortcuts + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_only_snapshot.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_only_snapshot.snap index 79e1e126eb..136c358055 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_only_snapshot.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_only_snapshot.snap @@ -7,4 +7,4 @@ expression: "render_snapshot(&pane, area)" › Ask Codex to do anything - 100% context left · ? for shortcuts + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_with_details_and_queued_messages_snapshot.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_with_details_and_queued_messages_snapshot.snap index 12090d09e9..b714c69d88 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_with_details_and_queued_messages_snapshot.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_with_details_and_queued_messages_snapshot.snap @@ -11,4 +11,4 @@ expression: "render_snapshot(&pane, area)" › Ask Codex to do anything - 100% context left · ? for shortcuts + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap index b51d759fe7..52779fd840 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap @@ -41,4 +41,4 @@ expression: term.backend().vt100().screen().contents() › Summarize recent commits - 100% context left · tab to queue message + tab to queue message 100% context left diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap index 64361e90f9..ebffeb8f53 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap @@ -25,4 +25,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - 100% context left · ? for shortcuts + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap index c6866c1b51..6074ed1f20 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__mcp_startup_header_booting.snap @@ -8,4 +8,4 @@ expression: terminal.backend() " " "› Ask Codex to do anything " " " -" 100% context left · ? for shortcuts " +" ? for shortcuts 100% context left " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap index 1c02350a6d..ce28175ea6 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__review_queues_user_messages_snapshot.snap @@ -19,4 +19,4 @@ expression: term.backend().vt100().screen().contents() › Ask Codex to do anything - 100% context left · ? for shortcuts + ? for shortcuts 100% context left diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap index 9fbebfb500..3acfd95eec 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap @@ -1,6 +1,5 @@ --- source: tui/src/chatwidget/tests.rs -assertion_line: 1577 expression: terminal.backend() --- " " @@ -9,4 +8,4 @@ expression: terminal.backend() " " "› Ask Codex to do anything " " " -" 100% context left · ? for shortcuts " +" ? for shortcuts 100% context left " From 877b76bb9d95969bac667d1facd2b37831588d15 Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Tue, 27 Jan 2026 10:09:39 -0800 Subject: [PATCH 010/116] feat(network-proxy): add a SOCKS5 proxy with policy enforcement (#9803) ### Summary - Adds an optional SOCKS5 listener via `rama-socks5` - SOCKS5 is disabled by default and gated by config - Reuses existing policy enforcement and blocked-request recording - Blocks SOCKS5 in limited mode to prevent method-policy bypass - Applies bind clamping to the SOCKS5 listener ### Config New/used fields under `network_proxy`: - `enable_socks5` - `socks_url` - `enable_socks5_udp` ### Scope - Changes limited to `codex-rs/network-proxy` (+ `codex-rs/Cargo.lock`) ### Testing ```bash cd codex-rs just fmt cargo test -p codex-network-proxy --offline --- codex-rs/Cargo.lock | 28 +++ codex-rs/network-proxy/Cargo.toml | 1 + codex-rs/network-proxy/README.md | 17 +- codex-rs/network-proxy/src/config.rs | 50 ++++- codex-rs/network-proxy/src/lib.rs | 1 + codex-rs/network-proxy/src/proxy.rs | 56 ++++- codex-rs/network-proxy/src/socks5.rs | 318 +++++++++++++++++++++++++++ 7 files changed, 452 insertions(+), 19 deletions(-) create mode 100644 codex-rs/network-proxy/src/socks5.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 75d72d360f..43916d1e14 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1683,6 +1683,7 @@ dependencies = [ "rama-http", "rama-http-backend", "rama-net", + "rama-socks5", "rama-tcp", "rama-tls-boring", "rama-unix", @@ -5959,6 +5960,21 @@ dependencies = [ "tokio", ] +[[package]] +name = "rama-socks5" +version = "0.3.0-alpha.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5468b263516daaf258de32542c1974b7cbe962363ad913dcb669f5d46db0ef3e" +dependencies = [ + "byteorder", + "rama-core", + "rama-net", + "rama-tcp", + "rama-udp", + "rama-utils", + "tokio", +] + [[package]] name = "rama-tcp" version = "0.3.0-alpha.4" @@ -5997,6 +6013,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "rama-udp" +version = "0.3.0-alpha.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36ed05e0ecac73e084e92a3a8b1fbf16fdae8958c506f0f0eada180a2d99eef4" +dependencies = [ + "rama-core", + "rama-net", + "tokio", + "tokio-util", +] + [[package]] name = "rama-unix" version = "0.3.0-alpha.4" diff --git a/codex-rs/network-proxy/Cargo.toml b/codex-rs/network-proxy/Cargo.toml index 2d303b1c95..959837d4e2 100644 --- a/codex-rs/network-proxy/Cargo.toml +++ b/codex-rs/network-proxy/Cargo.toml @@ -34,6 +34,7 @@ rama-core = { version = "=0.3.0-alpha.4" } rama-http = { version = "=0.3.0-alpha.4" } rama-http-backend = { version = "=0.3.0-alpha.4", features = ["tls"] } rama-net = { version = "=0.3.0-alpha.4", features = ["http", "tls"] } +rama-socks5 = { version = "=0.3.0-alpha.4" } rama-tcp = { version = "=0.3.0-alpha.4", features = ["http"] } rama-tls-boring = { version = "=0.3.0-alpha.4", features = ["http"] } diff --git a/codex-rs/network-proxy/README.md b/codex-rs/network-proxy/README.md index 1d19a92a68..3d8c20307d 100644 --- a/codex-rs/network-proxy/README.md +++ b/codex-rs/network-proxy/README.md @@ -3,6 +3,7 @@ `codex-network-proxy` is Codex's local network policy enforcement proxy. It runs: - an HTTP proxy (default `127.0.0.1:3128`) +- an optional SOCKS5 proxy (default `127.0.0.1:8081`, disabled by default) - an admin HTTP API (default `127.0.0.1:8080`) It enforces an allow/deny policy and a "limited" mode intended for read-only network access. @@ -20,6 +21,10 @@ Example config: enabled = true proxy_url = "http://127.0.0.1:3128" admin_url = "http://127.0.0.1:8080" +# Optional SOCKS5 listener (disabled by default). +enable_socks5 = false +socks_url = "http://127.0.0.1:8081" +enable_socks5_udp = false # When `enabled` is false, the proxy no-ops and does not bind listeners. # When true, respect HTTP(S)_PROXY/ALL_PROXY for upstream requests (HTTP(S) proxies only), # including CONNECT tunnels in full mode. @@ -28,7 +33,7 @@ allow_upstream_proxy = false # If you want to expose these listeners beyond localhost, you must opt in explicitly. dangerously_allow_non_loopback_proxy = false dangerously_allow_non_loopback_admin = false -mode = "limited" # or "full" +mode = "full" # default when unset; use "limited" for read-only mode [network_proxy.policy] # Hosts must match the allowlist (unless denied). @@ -60,6 +65,12 @@ export HTTP_PROXY="http://127.0.0.1:3128" export HTTPS_PROXY="http://127.0.0.1:3128" ``` +For SOCKS5 traffic (when `enable_socks5 = true`): + +```bash +export ALL_PROXY="socks5h://127.0.0.1:8081" +``` + ### 4) Understand blocks / debugging When a request is blocked, the proxy responds with `403` and includes: @@ -70,8 +81,8 @@ When a request is blocked, the proxy responds with `403` and includes: - `blocked-by-method-policy` - `blocked-by-policy` -In "limited" mode, only `GET`, `HEAD`, and `OPTIONS` are allowed for plain HTTP. HTTPS `CONNECT` -remains a transparent tunnel, so limited-mode method enforcement does not apply to HTTPS. +In "limited" mode, only `GET`, `HEAD`, and `OPTIONS` are allowed. HTTPS `CONNECT` and SOCKS5 are +blocked because they would bypass method enforcement. ## Library API diff --git a/codex-rs/network-proxy/src/config.rs b/codex-rs/network-proxy/src/config.rs index 7bd6957ac7..ae4a450179 100644 --- a/codex-rs/network-proxy/src/config.rs +++ b/codex-rs/network-proxy/src/config.rs @@ -23,6 +23,12 @@ pub struct NetworkProxySettings { #[serde(default = "default_admin_url")] pub admin_url: String, #[serde(default)] + pub enable_socks5: bool, + #[serde(default = "default_socks_url")] + pub socks_url: String, + #[serde(default)] + pub enable_socks5_udp: bool, + #[serde(default)] pub allow_upstream_proxy: bool, #[serde(default)] pub dangerously_allow_non_loopback_proxy: bool, @@ -40,6 +46,9 @@ impl Default for NetworkProxySettings { enabled: false, proxy_url: default_proxy_url(), admin_url: default_admin_url(), + enable_socks5: false, + socks_url: default_socks_url(), + enable_socks5_udp: false, allow_upstream_proxy: false, dangerously_allow_non_loopback_proxy: false, dangerously_allow_non_loopback_admin: false, @@ -90,6 +99,10 @@ fn default_admin_url() -> String { "http://127.0.0.1:8080".to_string() } +fn default_socks_url() -> String { + "http://127.0.0.1:8081".to_string() +} + /// Clamp non-loopback bind addresses to loopback unless explicitly allowed. fn clamp_non_loopback(addr: SocketAddr, allow_non_loopback: bool, name: &str) -> SocketAddr { if addr.ip().is_loopback() { @@ -110,21 +123,27 @@ fn clamp_non_loopback(addr: SocketAddr, allow_non_loopback: bool, name: &str) -> pub(crate) fn clamp_bind_addrs( http_addr: SocketAddr, + socks_addr: SocketAddr, admin_addr: SocketAddr, cfg: &NetworkProxySettings, -) -> (SocketAddr, SocketAddr) { +) -> (SocketAddr, SocketAddr, SocketAddr) { let http_addr = clamp_non_loopback( http_addr, cfg.dangerously_allow_non_loopback_proxy, "HTTP proxy", ); + let socks_addr = clamp_non_loopback( + socks_addr, + cfg.dangerously_allow_non_loopback_proxy, + "SOCKS5 proxy", + ); let admin_addr = clamp_non_loopback( admin_addr, cfg.dangerously_allow_non_loopback_admin, "admin API", ); if cfg.policy.allow_unix_sockets.is_empty() { - return (http_addr, admin_addr); + return (http_addr, socks_addr, admin_addr); } // `x-unix-socket` is intentionally a local escape hatch. If the proxy (or admin API) is @@ -136,6 +155,11 @@ pub(crate) fn clamp_bind_addrs( "unix socket proxying is enabled; ignoring dangerously_allow_non_loopback_proxy and clamping HTTP proxy to loopback" ); } + if cfg.dangerously_allow_non_loopback_proxy && !socks_addr.ip().is_loopback() { + warn!( + "unix socket proxying is enabled; ignoring dangerously_allow_non_loopback_proxy and clamping SOCKS5 proxy to loopback" + ); + } if cfg.dangerously_allow_non_loopback_admin && !admin_addr.ip().is_loopback() { warn!( "unix socket proxying is enabled; ignoring dangerously_allow_non_loopback_admin and clamping admin API to loopback" @@ -143,12 +167,14 @@ pub(crate) fn clamp_bind_addrs( } ( SocketAddr::from(([127, 0, 0, 1], http_addr.port())), + SocketAddr::from(([127, 0, 0, 1], socks_addr.port())), SocketAddr::from(([127, 0, 0, 1], admin_addr.port())), ) } pub struct RuntimeConfig { pub http_addr: SocketAddr, + pub socks_addr: SocketAddr, pub admin_addr: SocketAddr, } @@ -159,16 +185,24 @@ pub fn resolve_runtime(cfg: &NetworkProxyConfig) -> Result { cfg.network_proxy.proxy_url ) })?; + let socks_addr = resolve_addr(&cfg.network_proxy.socks_url, 8081).with_context(|| { + format!( + "invalid network_proxy.socks_url: {}", + cfg.network_proxy.socks_url + ) + })?; let admin_addr = resolve_addr(&cfg.network_proxy.admin_url, 8080).with_context(|| { format!( "invalid network_proxy.admin_url: {}", cfg.network_proxy.admin_url ) })?; - let (http_addr, admin_addr) = clamp_bind_addrs(http_addr, admin_addr, &cfg.network_proxy); + let (http_addr, socks_addr, admin_addr) = + clamp_bind_addrs(http_addr, socks_addr, admin_addr, &cfg.network_proxy); Ok(RuntimeConfig { http_addr, + socks_addr, admin_addr, }) } @@ -403,11 +437,14 @@ mod tests { ..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, admin_addr) = clamp_bind_addrs(http_addr, admin_addr, &cfg); + let (http_addr, socks_addr, admin_addr) = + clamp_bind_addrs(http_addr, socks_addr, admin_addr, &cfg); assert_eq!(http_addr, "0.0.0.0:3128".parse::().unwrap()); + assert_eq!(socks_addr, "0.0.0.0:8081".parse::().unwrap()); assert_eq!(admin_addr, "0.0.0.0:8080".parse::().unwrap()); } @@ -423,11 +460,14 @@ mod tests { ..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, admin_addr) = clamp_bind_addrs(http_addr, admin_addr, &cfg); + 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()); } } diff --git a/codex-rs/network-proxy/src/lib.rs b/codex-rs/network-proxy/src/lib.rs index 71e4ec7356..f4bcb8c74b 100644 --- a/codex-rs/network-proxy/src/lib.rs +++ b/codex-rs/network-proxy/src/lib.rs @@ -9,6 +9,7 @@ mod proxy; mod reasons; mod responses; mod runtime; +mod socks5; mod state; mod upstream; diff --git a/codex-rs/network-proxy/src/proxy.rs b/codex-rs/network-proxy/src/proxy.rs index 480880e946..cb09b9959d 100644 --- a/codex-rs/network-proxy/src/proxy.rs +++ b/codex-rs/network-proxy/src/proxy.rs @@ -3,6 +3,7 @@ use crate::config; use crate::http_proxy; use crate::network_policy::NetworkPolicyDecider; use crate::runtime::unix_socket_permissions_supported; +use crate::socks5; use crate::state::NetworkProxyState; use anyhow::Context; use anyhow::Result; @@ -61,8 +62,9 @@ impl NetworkProxyBuilder { let current_cfg = state.current_cfg().await?; let runtime = config::resolve_runtime(¤t_cfg)?; // Reapply bind clamping for caller overrides so unix-socket proxying stays loopback-only. - let (http_addr, admin_addr) = config::clamp_bind_addrs( + let (http_addr, socks_addr, admin_addr) = config::clamp_bind_addrs( self.http_addr.unwrap_or(runtime.http_addr), + runtime.socks_addr, self.admin_addr.unwrap_or(runtime.admin_addr), ¤t_cfg.network_proxy, ); @@ -70,6 +72,7 @@ impl NetworkProxyBuilder { Ok(NetworkProxy { state, http_addr, + socks_addr, admin_addr, policy_decider: self.policy_decider, }) @@ -80,6 +83,7 @@ impl NetworkProxyBuilder { pub struct NetworkProxy { state: Arc, http_addr: SocketAddr, + socks_addr: SocketAddr, admin_addr: SocketAddr, policy_decider: Option>, } @@ -105,10 +109,21 @@ impl NetworkProxy { self.http_addr, self.policy_decider.clone(), )); + let socks_task = if current_cfg.network_proxy.enable_socks5 { + Some(tokio::spawn(socks5::run_socks5( + self.state.clone(), + self.socks_addr, + self.policy_decider.clone(), + current_cfg.network_proxy.enable_socks5_udp, + ))) + } else { + None + }; let admin_task = tokio::spawn(admin::run_admin_api(self.state.clone(), self.admin_addr)); Ok(NetworkProxyHandle { http_task: Some(http_task), + socks_task, admin_task: Some(admin_task), completed: false, }) @@ -117,6 +132,7 @@ impl NetworkProxy { pub struct NetworkProxyHandle { http_task: Option>>, + socks_task: Option>>, admin_task: Option>>, completed: bool, } @@ -125,6 +141,7 @@ impl NetworkProxyHandle { fn noop() -> Self { Self { http_task: Some(tokio::spawn(async { Ok(()) })), + socks_task: None, admin_task: Some(tokio::spawn(async { Ok(()) })), completed: true, } @@ -133,33 +150,49 @@ impl NetworkProxyHandle { pub async fn wait(mut self) -> Result<()> { let http_task = self.http_task.take().context("missing http proxy task")?; let admin_task = self.admin_task.take().context("missing admin proxy task")?; + let socks_task = self.socks_task.take(); let http_result = http_task.await; let admin_result = admin_task.await; + let socks_result = match socks_task { + Some(task) => Some(task.await), + None => None, + }; self.completed = true; http_result??; admin_result??; + if let Some(socks_result) = socks_result { + socks_result??; + } Ok(()) } pub async fn shutdown(mut self) -> Result<()> { - abort_tasks(self.http_task.take(), self.admin_task.take()).await; + abort_tasks( + self.http_task.take(), + self.socks_task.take(), + self.admin_task.take(), + ) + .await; self.completed = true; Ok(()) } } +async fn abort_task(task: Option>>) { + if let Some(task) = task { + task.abort(); + let _ = task.await; + } +} + async fn abort_tasks( http_task: Option>>, + socks_task: Option>>, admin_task: Option>>, ) { - if let Some(http_task) = http_task { - http_task.abort(); - let _ = http_task.await; - } - if let Some(admin_task) = admin_task { - admin_task.abort(); - let _ = admin_task.await; - } + abort_task(http_task).await; + abort_task(socks_task).await; + abort_task(admin_task).await; } impl Drop for NetworkProxyHandle { @@ -168,9 +201,10 @@ impl Drop for NetworkProxyHandle { return; } let http_task = self.http_task.take(); + let socks_task = self.socks_task.take(); let admin_task = self.admin_task.take(); tokio::spawn(async move { - abort_tasks(http_task, admin_task).await; + abort_tasks(http_task, socks_task, admin_task).await; }); } } diff --git a/codex-rs/network-proxy/src/socks5.rs b/codex-rs/network-proxy/src/socks5.rs new file mode 100644 index 0000000000..9426502544 --- /dev/null +++ b/codex-rs/network-proxy/src/socks5.rs @@ -0,0 +1,318 @@ +use crate::config::NetworkMode; +use crate::network_policy::NetworkDecision; +use crate::network_policy::NetworkPolicyDecider; +use crate::network_policy::NetworkPolicyRequest; +use crate::network_policy::NetworkProtocol; +use crate::network_policy::evaluate_host_policy; +use crate::policy::normalize_host; +use crate::reasons::REASON_METHOD_NOT_ALLOWED; +use crate::reasons::REASON_PROXY_DISABLED; +use crate::state::BlockedRequest; +use crate::state::NetworkProxyState; +use anyhow::Context as _; +use anyhow::Result; +use rama_core::Layer; +use rama_core::Service; +use rama_core::error::BoxError; +use rama_core::extensions::ExtensionsRef; +use rama_core::layer::AddInputExtensionLayer; +use rama_core::service::service_fn; +use rama_net::client::EstablishedClientConnection; +use rama_net::stream::SocketInfo; +use rama_socks5::Socks5Acceptor; +use rama_socks5::server::DefaultConnector; +use rama_socks5::server::DefaultUdpRelay; +use rama_socks5::server::udp::RelayRequest; +use rama_socks5::server::udp::RelayResponse; +use rama_tcp::TcpStream; +use rama_tcp::client::Request as TcpRequest; +use rama_tcp::client::service::TcpConnector; +use rama_tcp::server::TcpListener; +use std::io; +use std::net::SocketAddr; +use std::sync::Arc; +use tracing::error; +use tracing::info; +use tracing::warn; + +pub async fn run_socks5( + state: Arc, + addr: SocketAddr, + policy_decider: Option>, + enable_socks5_udp: bool, +) -> Result<()> { + let listener = TcpListener::build() + .bind(addr) + .await + // See `http_proxy.rs` for details on why we wrap `BoxError` before converting to anyhow. + .map_err(rama_core::error::OpaqueError::from) + .map_err(anyhow::Error::from) + .with_context(|| format!("bind SOCKS5 proxy: {addr}"))?; + + info!("SOCKS5 proxy listening on {addr}"); + + match state.network_mode().await { + Ok(NetworkMode::Limited) => { + info!("SOCKS5 is blocked in limited mode; set mode=\"full\" to allow SOCKS5"); + } + Ok(NetworkMode::Full) => {} + Err(err) => { + warn!("failed to read network mode: {err}"); + } + } + + let tcp_connector = TcpConnector::default(); + let policy_tcp_connector = service_fn({ + let policy_decider = policy_decider.clone(); + move |req: TcpRequest| { + let tcp_connector = tcp_connector.clone(); + let policy_decider = policy_decider.clone(); + async move { handle_socks5_tcp(req, tcp_connector, policy_decider).await } + } + }); + + let socks_connector = DefaultConnector::default().with_connector(policy_tcp_connector); + let base = Socks5Acceptor::new().with_connector(socks_connector); + + if enable_socks5_udp { + let udp_state = state.clone(); + let udp_decider = policy_decider.clone(); + let udp_relay = DefaultUdpRelay::default().with_async_inspector(service_fn({ + move |request: RelayRequest| { + let udp_state = udp_state.clone(); + let udp_decider = udp_decider.clone(); + async move { inspect_socks5_udp(request, udp_state, udp_decider).await } + } + })); + let socks_acceptor = base.with_udp_associator(udp_relay); + listener + .serve(AddInputExtensionLayer::new(state).into_layer(socks_acceptor)) + .await; + } else { + listener + .serve(AddInputExtensionLayer::new(state).into_layer(base)) + .await; + } + Ok(()) +} + +async fn handle_socks5_tcp( + req: TcpRequest, + tcp_connector: TcpConnector, + policy_decider: Option>, +) -> Result, BoxError> { + let app_state = req + .extensions() + .get::>() + .cloned() + .ok_or_else(|| io::Error::other("missing state"))?; + + let host = normalize_host(&req.authority.host.to_string()); + let port = req.authority.port; + if host.is_empty() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid host").into()); + } + + let client = req + .extensions() + .get::() + .map(|info| info.peer_addr().to_string()); + + match app_state.enabled().await { + Ok(true) => {} + Ok(false) => { + let _ = app_state + .record_blocked(BlockedRequest::new( + host.clone(), + REASON_PROXY_DISABLED.to_string(), + client.clone(), + None, + None, + "socks5".to_string(), + )) + .await; + let client = client.as_deref().unwrap_or_default(); + warn!("SOCKS blocked; proxy disabled (client={client}, host={host})"); + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "proxy disabled").into()); + } + Err(err) => { + error!("failed to read enabled state: {err}"); + return Err(io::Error::other("proxy error").into()); + } + } + + match app_state.network_mode().await { + Ok(NetworkMode::Limited) => { + let _ = app_state + .record_blocked(BlockedRequest::new( + host.clone(), + REASON_METHOD_NOT_ALLOWED.to_string(), + client.clone(), + None, + Some(NetworkMode::Limited), + "socks5".to_string(), + )) + .await; + let client = client.as_deref().unwrap_or_default(); + warn!( + "SOCKS blocked by method policy (client={client}, host={host}, mode=limited, allowed_methods=GET, HEAD, OPTIONS)" + ); + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "blocked").into()); + } + Ok(NetworkMode::Full) => {} + Err(err) => { + error!("failed to evaluate method policy: {err}"); + return Err(io::Error::other("proxy error").into()); + } + } + + let request = NetworkPolicyRequest::new( + NetworkProtocol::Socks5Tcp, + host.clone(), + port, + client.clone(), + None, + None, + None, + ); + + match evaluate_host_policy(&app_state, policy_decider.as_ref(), &request).await { + Ok(NetworkDecision::Deny { reason }) => { + let _ = app_state + .record_blocked(BlockedRequest::new( + host.clone(), + reason.clone(), + client.clone(), + None, + None, + "socks5".to_string(), + )) + .await; + let client = client.as_deref().unwrap_or_default(); + warn!("SOCKS blocked (client={client}, host={host}, reason={reason})"); + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "blocked").into()); + } + Ok(NetworkDecision::Allow) => { + let client = client.as_deref().unwrap_or_default(); + info!("SOCKS allowed (client={client}, host={host}, port={port})"); + } + Err(err) => { + error!("failed to evaluate host: {err}"); + return Err(io::Error::other("proxy error").into()); + } + } + + tcp_connector.serve(req).await +} + +async fn inspect_socks5_udp( + request: RelayRequest, + state: Arc, + policy_decider: Option>, +) -> io::Result { + let RelayRequest { + server_address, + payload, + extensions, + .. + } = request; + + let host = normalize_host(&server_address.ip_addr.to_string()); + let port = server_address.port; + if host.is_empty() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid host")); + } + + let client = extensions + .get::() + .map(|info| info.peer_addr().to_string()); + + match state.enabled().await { + Ok(true) => {} + Ok(false) => { + let _ = state + .record_blocked(BlockedRequest::new( + host.clone(), + REASON_PROXY_DISABLED.to_string(), + client.clone(), + None, + None, + "socks5-udp".to_string(), + )) + .await; + let client = client.as_deref().unwrap_or_default(); + warn!("SOCKS UDP blocked; proxy disabled (client={client}, host={host})"); + return Ok(RelayResponse { + maybe_payload: None, + extensions, + }); + } + Err(err) => { + error!("failed to read enabled state: {err}"); + return Err(io::Error::other("proxy error")); + } + } + + match state.network_mode().await { + Ok(NetworkMode::Limited) => { + let _ = state + .record_blocked(BlockedRequest::new( + host.clone(), + REASON_METHOD_NOT_ALLOWED.to_string(), + client.clone(), + None, + Some(NetworkMode::Limited), + "socks5-udp".to_string(), + )) + .await; + return Ok(RelayResponse { + maybe_payload: None, + extensions, + }); + } + Ok(NetworkMode::Full) => {} + Err(err) => { + error!("failed to evaluate method policy: {err}"); + return Err(io::Error::other("proxy error")); + } + } + + let request = NetworkPolicyRequest::new( + NetworkProtocol::Socks5Udp, + host.clone(), + port, + client.clone(), + None, + None, + None, + ); + + match evaluate_host_policy(&state, policy_decider.as_ref(), &request).await { + Ok(NetworkDecision::Deny { reason }) => { + let _ = state + .record_blocked(BlockedRequest::new( + host.clone(), + reason.clone(), + client.clone(), + None, + None, + "socks5-udp".to_string(), + )) + .await; + let client = client.as_deref().unwrap_or_default(); + warn!("SOCKS UDP blocked (client={client}, host={host}, reason={reason})"); + Ok(RelayResponse { + maybe_payload: None, + extensions, + }) + } + Ok(NetworkDecision::Allow) => Ok(RelayResponse { + maybe_payload: Some(payload), + extensions, + }), + Err(err) => { + error!("failed to evaluate UDP host: {err}"); + Err(io::Error::other("proxy error")) + } + } +} From fc0fd85349429a90589e887095e853ace236a541 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 27 Jan 2026 10:41:54 -0800 Subject: [PATCH 011/116] fix(app-server, core): defer initial context write to rollout file until first turn (#9950) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Overview Currently calling `thread/resume` will always bump the thread's `updated_at` timestamp. This PR makes it the `updated_at` timestamp changes only if a turn is triggered. ### Additonal context What we typically do on resuming a thread is **always** writing “initial context” to the rollout file immediately. This initial context includes: - Developer instructions derived from sandbox/approval policy + cwd - Optional developer instructions (if provided) - Optional collaboration-mode instructions - Optional user instructions (if provided) - Environment context (cwd, shell, etc.) This PR defers writing the “initial context” to the rollout file until the first `turn/start`, so we don't inadvertently bump the thread's `updated_at` timestamp until a turn is actually triggered. This works even though both `thread/resume` and `turn/start` accept overrides (such as `model`, `cwd`, etc.) because the initial context is seeded from the effective `TurnContext` in memory, computed at `turn/start` time, after both sets of overrides have been applied. **NOTE**: This is a very short-lived solution until we introduce sqlite. Then we can remove this. --- .../tests/suite/v2/thread_resume.rs | 162 ++++++++++++++++++ codex-rs/core/src/codex.rs | 116 +++++++++++-- codex-rs/core/src/state/session.rs | 6 + codex-rs/core/src/tasks/mod.rs | 2 + 4 files changed, 269 insertions(+), 17 deletions(-) diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 6129c0de2f..af746b37b7 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -2,7 +2,9 @@ use anyhow::Result; use app_test_support::McpProcess; use app_test_support::create_fake_rollout_with_text_elements; use app_test_support::create_mock_responses_server_repeating_assistant; +use app_test_support::rollout_path; use app_test_support::to_response; +use chrono::Utc; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SessionSource; @@ -22,6 +24,8 @@ use codex_protocol::user_input::TextElement; use core_test_support::responses; use core_test_support::skip_if_no_network; use pretty_assertions::assert_eq; +use std::fs::FileTimes; +use std::path::Path; use std::path::PathBuf; use tempfile::TempDir; use tokio::time::timeout; @@ -147,6 +151,116 @@ async fn thread_resume_returns_rollout_history() -> Result<()> { Ok(()) } +#[tokio::test] +async fn thread_resume_without_overrides_does_not_change_updated_at_or_mtime() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + let rollout = setup_rollout_fixture(codex_home.path(), &server.uri())?; + let thread_id = rollout.conversation_id.clone(); + + 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 { thread, .. } = to_response::(resume_resp)?; + + assert_eq!(thread.updated_at, rollout.expected_updated_at); + + let after_modified = std::fs::metadata(&rollout.rollout_file_path)?.modified()?; + assert_eq!(after_modified, rollout.before_modified); + + let turn_id = mcp + .send_turn_start_request(TurnStartParams { + thread_id, + input: vec![UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_id)), + ) + .await??; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + let after_turn_modified = std::fs::metadata(&rollout.rollout_file_path)?.modified()?; + assert!(after_turn_modified > rollout.before_modified); + + Ok(()) +} + +#[tokio::test] +async fn thread_resume_with_overrides_defers_updated_at_until_turn_start() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + let rollout = setup_rollout_fixture(codex_home.path(), &server.uri())?; + + 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: rollout.conversation_id.clone(), + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let ThreadResumeResponse { thread, .. } = to_response::(resume_resp)?; + + assert_eq!(thread.updated_at, rollout.expected_updated_at); + + let after_resume_modified = std::fs::metadata(&rollout.rollout_file_path)?.modified()?; + assert_eq!(after_resume_modified, rollout.before_modified); + + let turn_id = mcp + .send_turn_start_request(TurnStartParams { + thread_id: rollout.conversation_id, + input: vec![UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_id)), + ) + .await??; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + let after_turn_modified = std::fs::metadata(&rollout.rollout_file_path)?.modified()?; + assert!(after_turn_modified > rollout.before_modified); + + Ok(()) +} + #[tokio::test] async fn thread_resume_prefers_path_over_thread_id() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; @@ -364,3 +478,51 @@ stream_max_retries = 0 ), ) } + +fn set_rollout_mtime(path: &Path, updated_at_rfc3339: &str) -> Result<()> { + let parsed = chrono::DateTime::parse_from_rfc3339(updated_at_rfc3339)?.with_timezone(&Utc); + let times = FileTimes::new().set_modified(parsed.into()); + std::fs::OpenOptions::new() + .append(true) + .open(path)? + .set_times(times)?; + Ok(()) +} + +struct RolloutFixture { + conversation_id: String, + rollout_file_path: PathBuf, + before_modified: std::time::SystemTime, + expected_updated_at: i64, +} + +fn setup_rollout_fixture(codex_home: &Path, server_uri: &str) -> Result { + create_config_toml(codex_home, server_uri)?; + + let preview = "Saved user message"; + let filename_ts = "2025-01-05T12-00-00"; + let meta_rfc3339 = "2025-01-05T12:00:00Z"; + let expected_updated_at_rfc3339 = "2025-01-07T00:00:00Z"; + let conversation_id = create_fake_rollout_with_text_elements( + codex_home, + filename_ts, + meta_rfc3339, + preview, + Vec::new(), + Some("mock_provider"), + None, + )?; + let rollout_file_path = rollout_path(codex_home, filename_ts, &conversation_id); + set_rollout_mtime(rollout_file_path.as_path(), expected_updated_at_rfc3339)?; + let before_modified = std::fs::metadata(&rollout_file_path)?.modified()?; + let expected_updated_at = chrono::DateTime::parse_from_rfc3339(expected_updated_at_rfc3339)? + .with_timezone(&Utc) + .timestamp(); + + Ok(RolloutFixture { + conversation_id, + rollout_file_path, + before_modified, + expected_updated_at, + }) +} diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 41e148e113..26cfdefea4 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -933,23 +933,28 @@ impl Session { // Build and record initial items (user instructions + environment context) let items = self.build_initial_context(&turn_context).await; self.record_conversation_items(&turn_context, &items).await; + { + let mut state = self.state.lock().await; + state.initial_context_seeded = true; + } // Ensure initial items are visible to immediate readers (e.g., tests, forks). self.flush_rollout().await; } - InitialHistory::Resumed(_) | InitialHistory::Forked(_) => { - let rollout_items = conversation_history.get_rollout_items(); - let persist = matches!(conversation_history, InitialHistory::Forked(_)); + InitialHistory::Resumed(resumed_history) => { + let rollout_items = resumed_history.history; + { + let mut state = self.state.lock().await; + state.initial_context_seeded = false; + } // If resuming, warn when the last recorded model differs from the current one. - if let InitialHistory::Resumed(_) = conversation_history - && let Some(prev) = rollout_items.iter().rev().find_map(|it| { - if let RolloutItem::TurnContext(ctx) = it { - Some(ctx.model.as_str()) - } else { - None - } - }) - { + if let Some(prev) = rollout_items.iter().rev().find_map(|it| { + if let RolloutItem::TurnContext(ctx) = it { + Some(ctx.model.as_str()) + } else { + None + } + }) { let curr = turn_context.client.get_model(); if prev != curr { warn!( @@ -984,8 +989,29 @@ impl Session { state.set_token_info(Some(info)); } + // Defer seeding the session's initial context until the first turn starts so + // turn/start overrides can be merged before we write to the rollout. + self.flush_rollout().await; + } + InitialHistory::Forked(rollout_items) => { + // Always add response items to conversation history + let reconstructed_history = self + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + if !reconstructed_history.is_empty() { + self.record_into_history(&reconstructed_history, &turn_context) + .await; + } + + // Seed usage info from the recorded rollout so UIs can show token counts + // immediately on resume/fork. + if let Some(info) = Self::last_token_info_from_rollout(&rollout_items) { + let mut state = self.state.lock().await; + state.set_token_info(Some(info)); + } + // If persisting, persist all rollout items as-is (recorder filters) - if persist && !rollout_items.is_empty() { + if !rollout_items.is_empty() { self.persist_rollout_items(&rollout_items).await; } @@ -993,6 +1019,10 @@ impl Session { let initial_context = self.build_initial_context(&turn_context).await; self.record_conversation_items(&turn_context, &initial_context) .await; + { + let mut state = self.state.lock().await; + state.initial_context_seeded = true; + } // Flush after seeding history and any persisted rollout copy. self.flush_rollout().await; } @@ -1643,6 +1673,21 @@ impl Session { 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; + } + async fn persist_rollout_response_items(&self, items: &[ResponseItem]) { let rollout_items: Vec = items .iter() @@ -2332,6 +2377,11 @@ mod handlers { return; } + let initial_context_seeded = sess.state.lock().await.initial_context_seeded; + if !initial_context_seeded { + return; + } + let current_context = sess.new_default_turn_with_sub_id(sub_id).await; let update_items = sess.build_settings_update_items( Some(&previous_context), @@ -2419,6 +2469,7 @@ mod handlers { // Attempt to inject input into current task if let Err(items) = sess.inject_input(items).await { + sess.seed_initial_context_if_needed(¤t_context).await; let update_items = sess.build_settings_update_items( previous_context.as_ref(), ¤t_context, @@ -3719,6 +3770,23 @@ mod tests { #[tokio::test] async fn record_initial_history_reconstructs_resumed_transcript() { + let (session, turn_context) = make_session_and_context().await; + let (rollout_items, expected) = sample_rollout(&session, &turn_context).await; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + let history = session.state.lock().await.clone_history(); + assert_eq!(expected, history.raw_items()); + } + + #[tokio::test] + async fn resumed_history_seeds_initial_context_on_first_turn_only() { let (session, turn_context) = make_session_and_context().await; let (rollout_items, mut expected) = sample_rollout(&session, &turn_context).await; @@ -3730,9 +3798,17 @@ mod tests { })) .await; + 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; expected.extend(session.build_initial_context(&turn_context).await); - let history = session.state.lock().await.clone_history(); - assert_eq!(expected, history.raw_items()); + 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; + let history_after_second_seed = session.clone_history().await; + assert_eq!(expected, history_after_second_seed.raw_items()); } #[tokio::test] @@ -4347,7 +4423,8 @@ mod tests { session_configuration.session_source.clone(), ); - let state = SessionState::new(session_configuration.clone()); + let mut state = SessionState::new(session_configuration.clone()); + mark_state_initial_context_seeded(&mut state); let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone())); let services = SessionServices { @@ -4456,7 +4533,8 @@ mod tests { session_configuration.session_source.clone(), ); - let state = SessionState::new(session_configuration.clone()); + let mut state = SessionState::new(session_configuration.clone()); + mark_state_initial_context_seeded(&mut state); let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone())); let services = SessionServices { @@ -4502,6 +4580,10 @@ 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; diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 746396949e..067f7b3378 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -15,6 +15,11 @@ pub(crate) struct SessionState { pub(crate) history: ContextManager, pub(crate) latest_rate_limits: Option, pub(crate) server_reasoning_included: bool, + /// 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, } impl SessionState { @@ -26,6 +31,7 @@ impl SessionState { history, latest_rate_limits: None, server_reasoning_included: false, + initial_context_seeded: false, } } diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index bbf9d9c276..08d23f7987 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -115,6 +115,8 @@ impl Session { task: T, ) { self.abort_all_tasks(TurnAbortReason::Replaced).await; + self.seed_initial_context_if_needed(turn_context.as_ref()) + .await; let task: Arc = Arc::new(task); let task_kind = task.kind(); From 894923ed5d6d659987396bbead8db1cb71f76225 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Tue, 27 Jan 2026 10:47:07 -0800 Subject: [PATCH 012/116] feat: make it possible to specify --config flags in the SDK (#10003) Updates the `CodexOptions` passed to the `Codex()` constructor in the SDK to support a `config` property that is a map of configuration data that will be transformed into `--config` flags passed to the invocation of `codex`. Therefore, something like this: ```typescript const codex = new Codex({ config: { show_raw_agent_reasoning: true, sandbox_workspace_write: { network_access: true }, }, }); ``` would result in the following args being added to the invocation of `codex`: ```shell --config show_raw_agent_reasoning=true --config sandbox_workspace_write.network_access=true ``` --- sdk/typescript/README.md | 16 +++++ sdk/typescript/src/codex.ts | 3 +- sdk/typescript/src/codexOptions.ts | 12 ++++ sdk/typescript/src/exec.ts | 110 +++++++++++++++++++++++++++-- sdk/typescript/tests/run.test.ts | 110 ++++++++++++++++++++++++++++- 5 files changed, 240 insertions(+), 11 deletions(-) diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 09e8a513d3..ae87b63fab 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -131,3 +131,19 @@ const codex = new Codex({ The SDK still injects its required variables (such as `OPENAI_BASE_URL` and `CODEX_API_KEY`) on top of the environment you provide. + +### Passing `--config` overrides + +Use the `config` option to provide additional Codex CLI configuration overrides. The SDK accepts a JSON object, flattens it +into dotted paths, and serializes values as TOML literals before passing them as repeated `--config key=value` flags. + +```typescript +const codex = new Codex({ + config: { + show_raw_agent_reasoning: true, + sandbox_workspace_write: { network_access: true }, + }, +}); +``` + +Thread options still take precedence for overlapping settings because they are emitted after these global overrides. diff --git a/sdk/typescript/src/codex.ts b/sdk/typescript/src/codex.ts index a42159232e..e3ce4aa0de 100644 --- a/sdk/typescript/src/codex.ts +++ b/sdk/typescript/src/codex.ts @@ -13,7 +13,8 @@ export class Codex { private options: CodexOptions; constructor(options: CodexOptions = {}) { - this.exec = new CodexExec(options.codexPathOverride, options.env); + const { codexPathOverride, env, config } = options; + this.exec = new CodexExec(codexPathOverride, env, config); this.options = options; } diff --git a/sdk/typescript/src/codexOptions.ts b/sdk/typescript/src/codexOptions.ts index 31fb637d4c..b6abb94b79 100644 --- a/sdk/typescript/src/codexOptions.ts +++ b/sdk/typescript/src/codexOptions.ts @@ -1,7 +1,19 @@ +export type CodexConfigValue = string | number | boolean | CodexConfigValue[] | CodexConfigObject; + +export type CodexConfigObject = { [key: string]: CodexConfigValue }; + export type CodexOptions = { codexPathOverride?: string; baseUrl?: string; apiKey?: string; + /** + * Additional `--config key=value` overrides to pass to the Codex CLI. + * + * Provide a JSON object and the SDK will flatten it into dotted paths and + * serialize values as TOML literals so they are compatible with the CLI's + * `--config` parsing. + */ + config?: CodexConfigObject; /** * Environment variables passed to the Codex CLI process. When provided, the SDK * will not inherit variables from `process.env`. diff --git a/sdk/typescript/src/exec.ts b/sdk/typescript/src/exec.ts index c8e957e1f2..d569106c84 100644 --- a/sdk/typescript/src/exec.ts +++ b/sdk/typescript/src/exec.ts @@ -3,12 +3,8 @@ import path from "node:path"; import readline from "node:readline"; import { fileURLToPath } from "node:url"; -import { - SandboxMode, - ModelReasoningEffort, - ApprovalMode, - WebSearchMode, -} from "./threadOptions"; +import type { CodexConfigObject, CodexConfigValue } from "./codexOptions"; +import { SandboxMode, ModelReasoningEffort, ApprovalMode, WebSearchMode } from "./threadOptions"; export type CodexExecArgs = { input: string; @@ -49,15 +45,27 @@ const TYPESCRIPT_SDK_ORIGINATOR = "codex_sdk_ts"; export class CodexExec { private executablePath: string; private envOverride?: Record; + private configOverrides?: CodexConfigObject; - constructor(executablePath: string | null = null, env?: Record) { + constructor( + executablePath: string | null = null, + env?: Record, + configOverrides?: CodexConfigObject, + ) { this.executablePath = executablePath || findCodexPath(); this.envOverride = env; + this.configOverrides = configOverrides; } async *run(args: CodexExecArgs): AsyncGenerator { const commandArgs: string[] = ["exec", "--experimental-json"]; + if (this.configOverrides) { + for (const override of serializeConfigOverrides(this.configOverrides)) { + commandArgs.push("--config", override); + } + } + if (args.model) { commandArgs.push("--model", args.model); } @@ -202,6 +210,94 @@ export class CodexExec { } } +function serializeConfigOverrides(configOverrides: CodexConfigObject): string[] { + const overrides: string[] = []; + flattenConfigOverrides(configOverrides, "", overrides); + return overrides; +} + +function flattenConfigOverrides( + value: CodexConfigValue, + prefix: string, + overrides: string[], +): void { + if (!isPlainObject(value)) { + if (prefix) { + overrides.push(`${prefix}=${toTomlValue(value, prefix)}`); + return; + } else { + throw new Error("Codex config overrides must be a plain object"); + } + } + + const entries = Object.entries(value); + if (!prefix && entries.length === 0) { + return; + } + + if (prefix && entries.length === 0) { + overrides.push(`${prefix}={}`); + return; + } + + for (const [key, child] of entries) { + if (!key) { + throw new Error("Codex config override keys must be non-empty strings"); + } + if (child === undefined) { + continue; + } + const path = prefix ? `${prefix}.${key}` : key; + if (isPlainObject(child)) { + flattenConfigOverrides(child, path, overrides); + } else { + overrides.push(`${path}=${toTomlValue(child, path)}`); + } + } +} + +function toTomlValue(value: CodexConfigValue, path: string): string { + if (typeof value === "string") { + return JSON.stringify(value); + } else if (typeof value === "number") { + if (!Number.isFinite(value)) { + throw new Error(`Codex config override at ${path} must be a finite number`); + } + return `${value}`; + } else if (typeof value === "boolean") { + return value ? "true" : "false"; + } else if (Array.isArray(value)) { + const rendered = value.map((item, index) => toTomlValue(item, `${path}[${index}]`)); + return `[${rendered.join(", ")}]`; + } else if (isPlainObject(value)) { + const parts: string[] = []; + for (const [key, child] of Object.entries(value)) { + if (!key) { + throw new Error("Codex config override keys must be non-empty strings"); + } + if (child === undefined) { + continue; + } + parts.push(`${formatTomlKey(key)} = ${toTomlValue(child, `${path}.${key}`)}`); + } + return `{${parts.join(", ")}}`; + } else if (value === null) { + throw new Error(`Codex config override at ${path} cannot be null`); + } else { + const typeName = typeof value; + throw new Error(`Unsupported Codex config override value at ${path}: ${typeName}`); + } +} + +const TOML_BARE_KEY = /^[A-Za-z0-9_-]+$/; +function formatTomlKey(key: string): string { + return TOML_BARE_KEY.test(key) ? key : JSON.stringify(key); +} + +function isPlainObject(value: unknown): value is CodexConfigObject { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + const scriptFileName = fileURLToPath(import.meta.url); const scriptDirName = path.dirname(scriptFileName); diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index 993b2304d5..410bf50267 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -410,6 +410,86 @@ describe("Codex", () => { } }); + it("passes CodexOptions config overrides as TOML --config flags", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: [ + sse( + responseStarted("response_1"), + assistantMessage("Config overrides applied", "item_1"), + responseCompleted("response_1"), + ), + ], + }); + + const { args: spawnArgs, restore } = codexExecSpy(); + + try { + const client = new Codex({ + codexPathOverride: codexExecPath, + baseUrl: url, + apiKey: "test", + config: { + approval_policy: "never", + sandbox_workspace_write: { network_access: true }, + retry_budget: 3, + tool_rules: { allow: ["git status", "git diff"] }, + }, + }); + + const thread = client.startThread(); + await thread.run("apply config overrides"); + + const commandArgs = spawnArgs[0]; + expect(commandArgs).toBeDefined(); + expectPair(commandArgs, ["--config", 'approval_policy="never"']); + expectPair(commandArgs, ["--config", "sandbox_workspace_write.network_access=true"]); + expectPair(commandArgs, ["--config", "retry_budget=3"]); + expectPair(commandArgs, ["--config", 'tool_rules.allow=["git status", "git diff"]']); + } finally { + restore(); + await close(); + } + }); + + it("lets thread options override CodexOptions config overrides", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: [ + sse( + responseStarted("response_1"), + assistantMessage("Thread overrides applied", "item_1"), + responseCompleted("response_1"), + ), + ], + }); + + const { args: spawnArgs, restore } = codexExecSpy(); + + try { + const client = new Codex({ + codexPathOverride: codexExecPath, + baseUrl: url, + apiKey: "test", + config: { approval_policy: "never" }, + }); + + const thread = client.startThread({ approvalPolicy: "on-request" }); + await thread.run("override approval policy"); + + const commandArgs = spawnArgs[0]; + const approvalPolicyOverrides = collectConfigValues(commandArgs, "approval_policy"); + expect(approvalPolicyOverrides).toEqual([ + 'approval_policy="never"', + 'approval_policy="on-request"', + ]); + expect(approvalPolicyOverrides.at(-1)).toBe('approval_policy="on-request"'); + } finally { + restore(); + await close(); + } + }); + it("allows overriding the env passed to the Codex CLI", async () => { const { url, close } = await startResponsesTestProxy({ statusCode: 200, @@ -737,13 +817,37 @@ describe("Codex", () => { } }, 10000); // TODO(pakrym): remove timeout }); + +/** + * Given a list of args to `codex` and a `key`, collects all `--config` + * overrides for that key. + */ +function collectConfigValues(args: string[] | undefined, key: string): string[] { + if (!args) { + throw new Error("args is undefined"); + } + + const values: string[] = []; + for (let i = 0; i < args.length; i += 1) { + if (args[i] !== "--config") { + continue; + } + + const override = args[i + 1]; + if (override?.startsWith(`${key}=`)) { + values.push(override); + } + } + return values; +} + function expectPair(args: string[] | undefined, pair: [string, string]) { if (!args) { - throw new Error("Args is undefined"); + throw new Error("args is undefined"); } - const index = args.indexOf(pair[0]); + const index = args.findIndex((arg, i) => arg === pair[0] && args[i + 1] === pair[1]); if (index === -1) { - throw new Error(`Pair ${pair[0]} not found in args`); + throw new Error(`Pair ${pair[0]} ${pair[1]} not found in args`); } expect(args[index + 1]).toBe(pair[1]); } From c40ad65bd8a6d5c67b220fdf158b79be8226e5a5 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Tue, 27 Jan 2026 11:04:23 -0800 Subject: [PATCH 013/116] remove sandbox globals. (#9797) Threads sandbox updates through OverrideTurnContext for active turn Passes computed sandbox type into safety/exec --- .../app-server/src/codex_message_processor.rs | 5 ++ codex-rs/core/src/apply_patch.rs | 1 + codex-rs/core/src/codex.rs | 20 ++++++ codex-rs/core/src/config/mod.rs | 36 ++++++----- codex-rs/core/src/exec.rs | 19 +++++- codex-rs/core/src/lib.rs | 3 - codex-rs/core/src/safety.rs | 63 +++++-------------- codex-rs/core/src/sandboxing/mod.rs | 15 ++++- codex-rs/core/src/tasks/user_shell.rs | 1 + codex-rs/core/src/tools/handlers/shell.rs | 2 + codex-rs/core/src/tools/orchestrator.rs | 12 ++-- codex-rs/core/src/tools/sandboxing.rs | 2 + codex-rs/core/src/windows_sandbox.rs | 34 ++++++++++ .../tests/suite/collaboration_instructions.rs | 9 +++ codex-rs/core/tests/suite/exec.rs | 4 +- codex-rs/core/tests/suite/model_overrides.rs | 2 + codex-rs/core/tests/suite/override_updates.rs | 3 + .../core/tests/suite/permissions_messages.rs | 3 + codex-rs/core/tests/suite/personality.rs | 2 + codex-rs/core/tests/suite/prompt_caching.rs | 2 + codex-rs/core/tests/suite/remote_models.rs | 2 + codex-rs/core/tests/suite/review.rs | 1 + .../exec-server/src/posix/escalate_server.rs | 2 + .../linux-sandbox/tests/suite/landlock.rs | 3 + codex-rs/protocol/src/config_types.rs | 12 ++++ codex-rs/protocol/src/protocol.rs | 5 ++ codex-rs/tui/src/app.rs | 54 ++++++++++++++-- codex-rs/tui/src/app_event.rs | 3 + codex-rs/tui/src/bottom_pane/chat_composer.rs | 11 ++++ codex-rs/tui/src/bottom_pane/command_popup.rs | 5 ++ codex-rs/tui/src/bottom_pane/mod.rs | 6 ++ .../tui/src/bottom_pane/slash_commands.rs | 34 +++++----- codex-rs/tui/src/chatwidget.rs | 58 ++++++++++++++--- codex-rs/tui/src/chatwidget/tests.rs | 30 ++------- codex-rs/tui/src/lib.rs | 7 ++- 35 files changed, 339 insertions(+), 132 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index fec9b2abdb..589b88d9a2 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -169,6 +169,7 @@ use codex_core::read_head_for_summary; use codex_core::read_session_meta_line; use codex_core::rollout_date_parts; use codex_core::sandboxing::SandboxPermissions; +use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_feedback::CodexFeedback; use codex_login::ServerOptions as LoginServerOptions; use codex_login::ShutdownHandle; @@ -176,6 +177,7 @@ use codex_login::run_login_server; use codex_protocol::ThreadId; use codex_protocol::config_types::ForcedLoginMethod; use codex_protocol::config_types::Personality; +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::dynamic_tools::DynamicToolSpec as CoreDynamicToolSpec; use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; @@ -1259,12 +1261,14 @@ impl CodexMessageProcessor { let timeout_ms = params .timeout_ms .and_then(|timeout_ms| u64::try_from(timeout_ms).ok()); + let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); let exec_params = ExecParams { command: params.command, cwd, expiration: timeout_ms.into(), env, sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level, justification: None, arg0: None, }; @@ -3887,6 +3891,7 @@ impl CodexMessageProcessor { cwd: params.cwd, approval_policy: params.approval_policy.map(AskForApproval::to_core), sandbox_policy: params.sandbox_policy.map(|p| p.to_core()), + windows_sandbox_level: None, model: params.model, effort: params.effort.map(Some), summary: params.summary, diff --git a/codex-rs/core/src/apply_patch.rs b/codex-rs/core/src/apply_patch.rs index 1a47ca60b7..f87e07300d 100644 --- a/codex-rs/core/src/apply_patch.rs +++ b/codex-rs/core/src/apply_patch.rs @@ -42,6 +42,7 @@ pub(crate) async fn apply_patch( turn_context.approval_policy, &turn_context.sandbox_policy, &turn_context.cwd, + turn_context.windows_sandbox_level, ) { SafetyCheck::AutoApprove { user_explicitly_approved, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 26cfdefea4..4dcc5d4455 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -174,11 +174,13 @@ use crate::turn_diff_tracker::TurnDiffTracker; use crate::unified_exec::UnifiedExecProcessManager; use crate::user_notification::UserNotification; use crate::util::backoff; +use crate::windows_sandbox::WindowsSandboxLevelExt; use codex_async_utils::OrCancelExt; use codex_otel::OtelManager; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::ContentItem; use codex_protocol::models::DeveloperInstructions; use codex_protocol::models::ResponseInputItem; @@ -325,6 +327,7 @@ impl Codex { compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy.clone(), sandbox_policy: config.sandbox_policy.clone(), + windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), session_source, @@ -445,6 +448,7 @@ pub(crate) struct TurnContext { pub(crate) personality: Option, pub(crate) approval_policy: AskForApproval, pub(crate) sandbox_policy: SandboxPolicy, + pub(crate) windows_sandbox_level: WindowsSandboxLevel, pub(crate) shell_environment_policy: ShellEnvironmentPolicy, pub(crate) tools_config: ToolsConfig, pub(crate) ghost_snapshot: GhostSnapshotConfig, @@ -496,6 +500,7 @@ pub(crate) struct SessionConfiguration { approval_policy: Constrained, /// How to sandbox commands executed in the system sandbox_policy: Constrained, + windows_sandbox_level: WindowsSandboxLevel, /// Working directory that should be treated as the *root* of the /// session. All relative paths supplied by the model as well as the @@ -544,6 +549,9 @@ impl SessionConfiguration { if let Some(sandbox_policy) = updates.sandbox_policy.clone() { next_configuration.sandbox_policy.set(sandbox_policy)?; } + if let Some(windows_sandbox_level) = updates.windows_sandbox_level { + next_configuration.windows_sandbox_level = windows_sandbox_level; + } if let Some(cwd) = updates.cwd.clone() { next_configuration.cwd = cwd; } @@ -556,6 +564,7 @@ pub(crate) struct SessionSettingsUpdate { pub(crate) cwd: Option, pub(crate) approval_policy: Option, pub(crate) sandbox_policy: Option, + pub(crate) windows_sandbox_level: Option, pub(crate) collaboration_mode: Option, pub(crate) reasoning_summary: Option, pub(crate) final_output_json_schema: Option>, @@ -620,6 +629,7 @@ impl Session { personality: session_configuration.personality, approval_policy: session_configuration.approval_policy.value(), sandbox_policy: session_configuration.sandbox_policy.get().clone(), + windows_sandbox_level: session_configuration.windows_sandbox_level, shell_environment_policy: per_turn_config.shell_environment_policy.clone(), tools_config, ghost_snapshot: per_turn_config.ghost_snapshot.clone(), @@ -2191,6 +2201,7 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv cwd, approval_policy, sandbox_policy, + windows_sandbox_level, model, effort, summary, @@ -2214,6 +2225,7 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv cwd, approval_policy, sandbox_policy, + windows_sandbox_level, collaboration_mode: Some(collaboration_mode), reasoning_summary: summary, personality, @@ -2430,6 +2442,7 @@ mod handlers { cwd: Some(cwd), approval_policy: Some(approval_policy), sandbox_policy: Some(sandbox_policy), + windows_sandbox_level: None, collaboration_mode, reasoning_summary: Some(summary), final_output_json_schema: Some(final_output_json_schema), @@ -2918,6 +2931,7 @@ async fn spawn_review_thread( personality: parent_turn_context.personality, approval_policy: parent_turn_context.approval_policy, sandbox_policy: parent_turn_context.sandbox_policy.clone(), + windows_sandbox_level: parent_turn_context.windows_sandbox_level, shell_environment_policy: parent_turn_context.shell_environment_policy.clone(), cwd: parent_turn_context.cwd.clone(), final_output_json_schema: None, @@ -4062,6 +4076,7 @@ mod tests { compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy.clone(), sandbox_policy: config.sandbox_policy.clone(), + windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, @@ -4142,6 +4157,7 @@ mod tests { compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy.clone(), sandbox_policy: config.sandbox_policy.clone(), + windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, @@ -4406,6 +4422,7 @@ mod tests { compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy.clone(), sandbox_policy: config.sandbox_policy.clone(), + windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, @@ -4516,6 +4533,7 @@ mod tests { compact_prompt: config.compact_prompt.clone(), approval_policy: config.approval_policy.clone(), sandbox_policy: config.sandbox_policy.clone(), + windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, @@ -5023,6 +5041,7 @@ mod tests { expiration: timeout_ms.into(), env: HashMap::new(), sandbox_permissions, + windows_sandbox_level: turn_context.windows_sandbox_level, justification: Some("test".to_string()), arg0: None, }; @@ -5033,6 +5052,7 @@ mod tests { cwd: params.cwd.clone(), expiration: timeout_ms.into(), env: HashMap::new(), + windows_sandbox_level: turn_context.windows_sandbox_level, justification: params.justification.clone(), arg0: None, }; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 8744b756bf..2778c03a7b 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -38,6 +38,7 @@ use crate::project_doc::DEFAULT_PROJECT_DOC_FILENAME; use crate::project_doc::LOCAL_PROJECT_DOC_FILENAME; use crate::protocol::AskForApproval; use crate::protocol::SandboxPolicy; +use crate::windows_sandbox::WindowsSandboxLevelExt; use codex_app_server_protocol::Tools; use codex_app_server_protocol::UserSavedConfig; use codex_protocol::config_types::AltScreenMode; @@ -49,6 +50,7 @@ use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::TrustLevel; use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchMode; +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::openai_models::ReasoningEffort; use codex_rmcp_client::OAuthCredentialsStoreMode; use codex_utils_absolute_path::AbsolutePathBuf; @@ -1056,6 +1058,7 @@ impl ConfigToml { &self, sandbox_mode_override: Option, profile_sandbox_mode: Option, + windows_sandbox_level: WindowsSandboxLevel, resolved_cwd: &Path, ) -> SandboxPolicyResolution { let resolved_sandbox_mode = sandbox_mode_override @@ -1094,7 +1097,7 @@ impl ConfigToml { if cfg!(target_os = "windows") && matches!(resolved_sandbox_mode, SandboxMode::WorkspaceWrite) // If the experimental Windows sandbox is enabled, do not force a downgrade. - && crate::safety::get_platform_sandbox().is_none() + && windows_sandbox_level == codex_protocol::config_types::WindowsSandboxLevel::Disabled { sandbox_policy = SandboxPolicy::new_read_only_policy(); forced_auto_mode_downgraded_on_windows = true; @@ -1285,16 +1288,6 @@ impl Config { let features = Features::from_config(&cfg, &config_profile, feature_overrides); let web_search_mode = resolve_web_search_mode(&cfg, &config_profile, &features); - #[cfg(target_os = "windows")] - { - // Base flag controls sandbox on/off; elevated only applies when base is enabled. - let sandbox_enabled = features.enabled(Feature::WindowsSandbox); - crate::safety::set_windows_sandbox_enabled(sandbox_enabled); - let elevated_enabled = - sandbox_enabled && features.enabled(Feature::WindowsSandboxElevated); - crate::safety::set_windows_elevated_sandbox_enabled(elevated_enabled); - } - let resolved_cwd = { use std::env; @@ -1321,10 +1314,16 @@ impl Config { .get_active_project(&resolved_cwd) .unwrap_or(ProjectConfig { trust_level: None }); + let windows_sandbox_level = WindowsSandboxLevel::from_features(&features); let SandboxPolicyResolution { policy: mut sandbox_policy, forced_auto_mode_downgraded_on_windows, - } = cfg.derive_sandbox_policy(sandbox_mode, config_profile.sandbox_mode, &resolved_cwd); + } = cfg.derive_sandbox_policy( + sandbox_mode, + config_profile.sandbox_mode, + windows_sandbox_level, + &resolved_cwd, + ); if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = &mut sandbox_policy { for path in additional_writable_roots { if !writable_roots.iter().any(|existing| existing == &path) { @@ -1667,7 +1666,6 @@ impl Config { } pub fn set_windows_sandbox_globally(&mut self, value: bool) { - crate::safety::set_windows_sandbox_enabled(value); if value { self.features.enable(Feature::WindowsSandbox); } else { @@ -1677,7 +1675,6 @@ impl Config { } pub fn set_windows_elevated_sandbox_globally(&mut self, value: bool) { - crate::safety::set_windows_elevated_sandbox_enabled(value); if value { self.features.enable(Feature::WindowsSandboxElevated); } else { @@ -1871,6 +1868,7 @@ network_access = false # This should be ignored. let resolution = sandbox_full_access_cfg.derive_sandbox_policy( sandbox_mode_override, None, + WindowsSandboxLevel::Disabled, &PathBuf::from("/tmp/test"), ); assert_eq!( @@ -1894,6 +1892,7 @@ network_access = true # This should be ignored. let resolution = sandbox_read_only_cfg.derive_sandbox_policy( sandbox_mode_override, None, + WindowsSandboxLevel::Disabled, &PathBuf::from("/tmp/test"), ); assert_eq!( @@ -1925,6 +1924,7 @@ exclude_slash_tmp = true let resolution = sandbox_workspace_write_cfg.derive_sandbox_policy( sandbox_mode_override, None, + WindowsSandboxLevel::Disabled, &PathBuf::from("/tmp/test"), ); if cfg!(target_os = "windows") { @@ -1973,6 +1973,7 @@ trust_level = "trusted" let resolution = sandbox_workspace_write_cfg.derive_sandbox_policy( sandbox_mode_override, None, + WindowsSandboxLevel::Disabled, &PathBuf::from("/tmp/test"), ); if cfg!(target_os = "windows") { @@ -4190,7 +4191,12 @@ trust_level = "untrusted" let cfg = toml::from_str::(config_with_untrusted) .expect("TOML deserialization should succeed"); - let resolution = cfg.derive_sandbox_policy(None, None, &PathBuf::from("/tmp/test")); + let resolution = cfg.derive_sandbox_policy( + None, + None, + WindowsSandboxLevel::Disabled, + &PathBuf::from("/tmp/test"), + ); // Verify that untrusted projects get WorkspaceWrite (or ReadOnly on Windows due to downgrade) if cfg!(target_os = "windows") { diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index ea23cb1216..37f6c2de96 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -64,6 +64,7 @@ pub struct ExecParams { pub expiration: ExecExpiration, pub env: HashMap, pub sandbox_permissions: SandboxPermissions, + pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, pub justification: Option, pub arg0: Option, } @@ -141,11 +142,15 @@ pub async fn process_exec_tool_call( codex_linux_sandbox_exe: &Option, stdout_stream: Option, ) -> Result { + let windows_sandbox_level = params.windows_sandbox_level; let sandbox_type = match &sandbox_policy { SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } => { SandboxType::None } - _ => get_platform_sandbox().unwrap_or(SandboxType::None), + _ => get_platform_sandbox( + windows_sandbox_level != codex_protocol::config_types::WindowsSandboxLevel::Disabled, + ) + .unwrap_or(SandboxType::None), }; tracing::debug!("Sandbox type: {sandbox_type:?}"); @@ -155,6 +160,7 @@ pub async fn process_exec_tool_call( expiration, env, sandbox_permissions, + windows_sandbox_level, justification, arg0: _, } = params; @@ -184,6 +190,7 @@ pub async fn process_exec_tool_call( sandbox_type, sandbox_cwd, codex_linux_sandbox_exe.as_ref(), + windows_sandbox_level, ) .map_err(CodexErr::from)?; @@ -202,6 +209,7 @@ pub(crate) async fn execute_exec_env( env, expiration, sandbox, + windows_sandbox_level, sandbox_permissions, justification, arg0, @@ -213,6 +221,7 @@ pub(crate) async fn execute_exec_env( expiration, env, sandbox_permissions, + windows_sandbox_level, justification, arg0, }; @@ -229,7 +238,7 @@ async fn exec_windows_sandbox( sandbox_policy: &SandboxPolicy, ) -> Result { use crate::config::find_codex_home; - use crate::safety::is_windows_elevated_sandbox_enabled; + use codex_protocol::config_types::WindowsSandboxLevel; use codex_windows_sandbox::run_windows_sandbox_capture; use codex_windows_sandbox::run_windows_sandbox_capture_elevated; @@ -238,6 +247,7 @@ async fn exec_windows_sandbox( cwd, env, expiration, + windows_sandbox_level, .. } = params; // TODO(iceweasel-oai): run_windows_sandbox_capture should support all @@ -255,7 +265,7 @@ async fn exec_windows_sandbox( "windows sandbox: failed to resolve codex_home: {err}" ))) })?; - let use_elevated = is_windows_elevated_sandbox_enabled(); + let use_elevated = matches!(windows_sandbox_level, WindowsSandboxLevel::Elevated); let spawn_res = tokio::task::spawn_blocking(move || { if use_elevated { run_windows_sandbox_capture_elevated( @@ -584,6 +594,7 @@ async fn exec( env, arg0, expiration, + windows_sandbox_level: _, .. } = params; @@ -965,6 +976,7 @@ mod tests { expiration: 500.into(), env, sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled, justification: None, arg0: None, }; @@ -1010,6 +1022,7 @@ mod tests { expiration: ExecExpiration::Cancellation(cancel_token), env, sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled, justification: None, arg0: None, }; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 010ba3874a..27fa255c85 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -126,9 +126,6 @@ pub use exec_policy::ExecPolicyError; pub use exec_policy::check_execpolicy_for_warnings; pub use exec_policy::load_exec_policy; pub use safety::get_platform_sandbox; -pub use safety::is_windows_elevated_sandbox_enabled; -pub use safety::set_windows_elevated_sandbox_enabled; -pub use safety::set_windows_sandbox_enabled; pub use tools::spec::parse_tool_input_schema; // Re-export the protocol types from the standalone `codex-protocol` crate so existing // `codex_core::protocol::...` references continue to work across the workspace. diff --git a/codex-rs/core/src/safety.rs b/codex-rs/core/src/safety.rs index 601a5a8b81..47a12e029e 100644 --- a/codex-rs/core/src/safety.rs +++ b/codex-rs/core/src/safety.rs @@ -10,45 +10,7 @@ use crate::util::resolve_path; use crate::protocol::AskForApproval; use crate::protocol::SandboxPolicy; - -#[cfg(target_os = "windows")] -use std::sync::atomic::AtomicBool; -#[cfg(target_os = "windows")] -use std::sync::atomic::Ordering; - -#[cfg(target_os = "windows")] -static WINDOWS_SANDBOX_ENABLED: AtomicBool = AtomicBool::new(false); -#[cfg(target_os = "windows")] -static WINDOWS_ELEVATED_SANDBOX_ENABLED: AtomicBool = AtomicBool::new(false); - -#[cfg(target_os = "windows")] -pub fn set_windows_sandbox_enabled(enabled: bool) { - WINDOWS_SANDBOX_ENABLED.store(enabled, Ordering::Relaxed); -} - -#[cfg(not(target_os = "windows"))] -#[allow(dead_code)] -pub fn set_windows_sandbox_enabled(_enabled: bool) {} - -#[cfg(target_os = "windows")] -pub fn set_windows_elevated_sandbox_enabled(enabled: bool) { - WINDOWS_ELEVATED_SANDBOX_ENABLED.store(enabled, Ordering::Relaxed); -} - -#[cfg(not(target_os = "windows"))] -#[allow(dead_code)] -pub fn set_windows_elevated_sandbox_enabled(_enabled: bool) {} - -#[cfg(target_os = "windows")] -pub fn is_windows_elevated_sandbox_enabled() -> bool { - WINDOWS_ELEVATED_SANDBOX_ENABLED.load(Ordering::Relaxed) -} - -#[cfg(not(target_os = "windows"))] -#[allow(dead_code)] -pub fn is_windows_elevated_sandbox_enabled() -> bool { - false -} +use codex_protocol::config_types::WindowsSandboxLevel; #[derive(Debug, PartialEq)] pub enum SafetyCheck { @@ -67,6 +29,7 @@ pub fn assess_patch_safety( policy: AskForApproval, sandbox_policy: &SandboxPolicy, cwd: &Path, + windows_sandbox_level: WindowsSandboxLevel, ) -> SafetyCheck { if action.is_empty() { return SafetyCheck::Reject { @@ -104,7 +67,7 @@ pub fn assess_patch_safety( // Only auto‑approve when we can actually enforce a sandbox. Otherwise // fall back to asking the user because the patch may touch arbitrary // paths outside the project. - match get_platform_sandbox() { + match get_platform_sandbox(windows_sandbox_level != WindowsSandboxLevel::Disabled) { Some(sandbox_type) => SafetyCheck::AutoApprove { sandbox_type, user_explicitly_approved: false, @@ -122,19 +85,17 @@ pub fn assess_patch_safety( } } -pub fn get_platform_sandbox() -> Option { +pub fn get_platform_sandbox(windows_sandbox_enabled: bool) -> Option { if cfg!(target_os = "macos") { Some(SandboxType::MacosSeatbelt) } else if cfg!(target_os = "linux") { Some(SandboxType::LinuxSeccomp) } else if cfg!(target_os = "windows") { - #[cfg(target_os = "windows")] - { - if WINDOWS_SANDBOX_ENABLED.load(Ordering::Relaxed) { - return Some(SandboxType::WindowsRestrictedToken); - } + if windows_sandbox_enabled { + Some(SandboxType::WindowsRestrictedToken) + } else { + None } - None } else { None } @@ -277,7 +238,13 @@ mod tests { }; assert_eq!( - assess_patch_safety(&add_inside, AskForApproval::OnRequest, &policy, &cwd), + assess_patch_safety( + &add_inside, + AskForApproval::OnRequest, + &policy, + &cwd, + WindowsSandboxLevel::Disabled + ), SafetyCheck::AutoApprove { sandbox_type: SandboxType::None, user_explicitly_approved: false, diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index a2c8ad1e31..fca7adda29 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -21,6 +21,7 @@ use crate::seatbelt::create_seatbelt_command_args; use crate::spawn::CODEX_SANDBOX_ENV_VAR; use crate::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use crate::tools::sandboxing::SandboxablePreference; +use codex_protocol::config_types::WindowsSandboxLevel; pub use codex_protocol::models::SandboxPermissions; use std::collections::HashMap; use std::path::Path; @@ -44,6 +45,7 @@ pub struct ExecEnv { pub env: HashMap, pub expiration: ExecExpiration, pub sandbox: SandboxType, + pub windows_sandbox_level: WindowsSandboxLevel, pub sandbox_permissions: SandboxPermissions, pub justification: Option, pub arg0: Option, @@ -76,19 +78,26 @@ impl SandboxManager { &self, policy: &SandboxPolicy, pref: SandboxablePreference, + windows_sandbox_level: WindowsSandboxLevel, ) -> SandboxType { match pref { SandboxablePreference::Forbid => SandboxType::None, SandboxablePreference::Require => { // Require a platform sandbox when available; on Windows this // respects the experimental_windows_sandbox feature. - crate::safety::get_platform_sandbox().unwrap_or(SandboxType::None) + crate::safety::get_platform_sandbox( + windows_sandbox_level != WindowsSandboxLevel::Disabled, + ) + .unwrap_or(SandboxType::None) } SandboxablePreference::Auto => match policy { SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } => { SandboxType::None } - _ => crate::safety::get_platform_sandbox().unwrap_or(SandboxType::None), + _ => crate::safety::get_platform_sandbox( + windows_sandbox_level != WindowsSandboxLevel::Disabled, + ) + .unwrap_or(SandboxType::None), }, } } @@ -100,6 +109,7 @@ impl SandboxManager { sandbox: SandboxType, sandbox_policy_cwd: &Path, codex_linux_sandbox_exe: Option<&PathBuf>, + windows_sandbox_level: WindowsSandboxLevel, ) -> Result { let mut env = spec.env; if !policy.has_full_network_access() { @@ -160,6 +170,7 @@ impl SandboxManager { env, expiration: spec.expiration, sandbox, + windows_sandbox_level, sandbox_permissions: spec.sandbox_permissions, justification: spec.justification, arg0: arg0_override, diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 1f1f1eb59e..4305417a35 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -109,6 +109,7 @@ impl SessionTask for UserShellCommandTask { // should use that instead of an "arbitrarily large" timeout here. expiration: USER_SHELL_TIMEOUT_MS.into(), sandbox: SandboxType::None, + windows_sandbox_level: turn_context.windows_sandbox_level, sandbox_permissions: SandboxPermissions::UseDefault, justification: None, arg0: None, diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index dc9f198cc0..c3628e8c34 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -36,6 +36,7 @@ impl ShellHandler { expiration: params.timeout_ms.into(), env: create_env(&turn_context.shell_environment_policy), sandbox_permissions: params.sandbox_permissions.unwrap_or_default(), + windows_sandbox_level: turn_context.windows_sandbox_level, justification: params.justification, arg0: None, } @@ -62,6 +63,7 @@ impl ShellCommandHandler { expiration: params.timeout_ms.into(), env: create_env(&turn_context.shell_environment_policy), sandbox_permissions: params.sandbox_permissions.unwrap_or_default(), + windows_sandbox_level: turn_context.windows_sandbox_level, justification: params.justification, arg0: None, } diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index f0810916a5..e9fdd6208b 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -88,19 +88,22 @@ impl ToolOrchestrator { // 2) First attempt under the selected sandbox. let initial_sandbox = match tool.sandbox_mode_for_first_attempt(req) { SandboxOverride::BypassSandboxFirstAttempt => crate::exec::SandboxType::None, - SandboxOverride::NoOverride => self - .sandbox - .select_initial(&turn_ctx.sandbox_policy, tool.sandbox_preference()), + SandboxOverride::NoOverride => self.sandbox.select_initial( + &turn_ctx.sandbox_policy, + tool.sandbox_preference(), + turn_ctx.windows_sandbox_level, + ), }; // Platform-specific flag gating is handled by SandboxManager::select_initial - // via crate::safety::get_platform_sandbox(). + // via crate::safety::get_platform_sandbox(..). let initial_attempt = SandboxAttempt { sandbox: initial_sandbox, policy: &turn_ctx.sandbox_policy, manager: &self.sandbox, sandbox_cwd: &turn_ctx.cwd, codex_linux_sandbox_exe: turn_ctx.codex_linux_sandbox_exe.as_ref(), + windows_sandbox_level: turn_ctx.windows_sandbox_level, }; match tool.run(req, &initial_attempt, tool_ctx).await { @@ -151,6 +154,7 @@ impl ToolOrchestrator { manager: &self.sandbox, sandbox_cwd: &turn_ctx.cwd, codex_linux_sandbox_exe: None, + windows_sandbox_level: turn_ctx.windows_sandbox_level, }; // Second attempt. diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index eefce38bc6..a7d2bca62a 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -274,6 +274,7 @@ pub(crate) struct SandboxAttempt<'a> { pub(crate) manager: &'a SandboxManager, pub(crate) sandbox_cwd: &'a Path, pub codex_linux_sandbox_exe: Option<&'a std::path::PathBuf>, + pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, } impl<'a> SandboxAttempt<'a> { @@ -287,6 +288,7 @@ impl<'a> SandboxAttempt<'a> { self.sandbox, self.sandbox_cwd, self.codex_linux_sandbox_exe, + self.windows_sandbox_level, ) } } diff --git a/codex-rs/core/src/windows_sandbox.rs b/codex-rs/core/src/windows_sandbox.rs index b355bad280..45212e1d48 100644 --- a/codex-rs/core/src/windows_sandbox.rs +++ b/codex-rs/core/src/windows_sandbox.rs @@ -1,4 +1,8 @@ +use crate::config::Config; +use crate::features::Feature; +use crate::features::Features; use crate::protocol::SandboxPolicy; +use codex_protocol::config_types::WindowsSandboxLevel; use std::collections::HashMap; use std::path::Path; @@ -8,6 +12,36 @@ use std::path::Path; /// prompts users to enable the legacy sandbox feature. pub const ELEVATED_SANDBOX_NUX_ENABLED: bool = true; +pub trait WindowsSandboxLevelExt { + fn from_config(config: &Config) -> WindowsSandboxLevel; + fn from_features(features: &Features) -> WindowsSandboxLevel; +} + +impl WindowsSandboxLevelExt for WindowsSandboxLevel { + fn from_config(config: &Config) -> WindowsSandboxLevel { + Self::from_features(&config.features) + } + + fn from_features(features: &Features) -> WindowsSandboxLevel { + if !features.enabled(Feature::WindowsSandbox) { + return WindowsSandboxLevel::Disabled; + } + if features.enabled(Feature::WindowsSandboxElevated) { + WindowsSandboxLevel::Elevated + } else { + WindowsSandboxLevel::RestrictedToken + } + } +} + +pub fn windows_sandbox_level_from_config(config: &Config) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_config(config) +} + +pub fn windows_sandbox_level_from_features(features: &Features) -> WindowsSandboxLevel { + WindowsSandboxLevel::from_features(features) +} + #[cfg(target_os = "windows")] pub fn sandbox_setup_is_complete(codex_home: &Path) -> bool { codex_windows_sandbox::sandbox_setup_is_complete(codex_home) diff --git a/codex-rs/core/tests/suite/collaboration_instructions.rs b/codex-rs/core/tests/suite/collaboration_instructions.rs index f7183b817e..0f492d78c9 100644 --- a/codex-rs/core/tests/suite/collaboration_instructions.rs +++ b/codex-rs/core/tests/suite/collaboration_instructions.rs @@ -104,6 +104,7 @@ async fn user_input_includes_collaboration_instructions_after_override() -> Resu cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -185,6 +186,7 @@ async fn override_then_user_turn_uses_updated_collaboration_instructions() -> Re cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -238,6 +240,7 @@ async fn user_turn_overrides_collaboration_instructions_after_override() -> Resu cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -292,6 +295,7 @@ async fn collaboration_mode_update_emits_new_instruction_message() -> Result<()> cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -316,6 +320,7 @@ async fn collaboration_mode_update_emits_new_instruction_message() -> Result<()> cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -361,6 +366,7 @@ async fn collaboration_mode_update_noop_does_not_append() -> Result<()> { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -385,6 +391,7 @@ async fn collaboration_mode_update_noop_does_not_append() -> Result<()> { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -436,6 +443,7 @@ async fn resume_replays_collaboration_instructions() -> Result<()> { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -491,6 +499,7 @@ async fn empty_collaboration_instructions_are_ignored() -> Result<()> { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index c093482157..cdf597a4e9 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -10,6 +10,7 @@ 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 tempfile::TempDir; use codex_core::error::Result; @@ -27,7 +28,7 @@ fn skip_test() -> bool { #[expect(clippy::expect_used)] async fn run_test_cmd(tmp: TempDir, cmd: Vec<&str>) -> Result { - let sandbox_type = get_platform_sandbox().expect("should be able to get sandbox type"); + let sandbox_type = get_platform_sandbox(false).expect("should be able to get sandbox type"); assert_eq!(sandbox_type, SandboxType::MacosSeatbelt); let params = ExecParams { @@ -36,6 +37,7 @@ async fn run_test_cmd(tmp: TempDir, cmd: Vec<&str>) -> Result Result<()> { cwd: None, approval_policy: Some(AskForApproval::Never), sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -161,6 +162,7 @@ async fn override_turn_context_records_environment_update() -> Result<()> { cwd: Some(new_cwd.path().to_path_buf()), approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -198,6 +200,7 @@ async fn override_turn_context_records_collaboration_update() -> Result<()> { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, diff --git a/codex-rs/core/tests/suite/permissions_messages.rs b/codex-rs/core/tests/suite/permissions_messages.rs index f3d9e8d47b..679c0c1f6c 100644 --- a/codex-rs/core/tests/suite/permissions_messages.rs +++ b/codex-rs/core/tests/suite/permissions_messages.rs @@ -106,6 +106,7 @@ async fn permissions_message_added_on_override_change() -> Result<()> { cwd: None, approval_policy: Some(AskForApproval::Never), sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -227,6 +228,7 @@ async fn resume_replays_permissions_messages() -> Result<()> { cwd: None, approval_policy: Some(AskForApproval::Never), sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -309,6 +311,7 @@ async fn resume_and_fork_append_permissions_messages() -> Result<()> { cwd: None, approval_policy: Some(AskForApproval::Never), sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index 410ca08e4e..7a27866569 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -210,6 +210,7 @@ async fn user_turn_personality_some_adds_update_message() -> anyhow::Result<()> cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -362,6 +363,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: Some(remote_slug.to_string()), effort: None, summary: None, diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 32969bcf5a..5831c62357 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -350,6 +350,7 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> an cwd: None, approval_policy: Some(AskForApproval::Never), sandbox_policy: Some(new_policy.clone()), + windows_sandbox_level: None, model: Some("o3".to_string()), effort: Some(Some(ReasoningEffort::High)), summary: Some(ReasoningSummary::Detailed), @@ -427,6 +428,7 @@ async fn override_before_first_turn_emits_environment_context() -> anyhow::Resul cwd: None, approval_policy: Some(AskForApproval::Never), sandbox_policy: None, + windows_sandbox_level: None, model: Some("gpt-5.1-codex".to_string()), effort: Some(Some(ReasoningEffort::Low)), summary: None, diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index 7e5fab9871..71374cb84f 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -138,6 +138,7 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: Some(REMOTE_MODEL_SLUG.to_string()), effort: None, summary: None, @@ -367,6 +368,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: Some(model.to_string()), effort: None, summary: None, diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index de62bf462d..cfc4a80488 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -819,6 +819,7 @@ async fn review_uses_overridden_cwd_for_base_branch_merge_base() { cwd: Some(repo_path.to_path_buf()), approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: None, effort: None, summary: None, diff --git a/codex-rs/exec-server/src/posix/escalate_server.rs b/codex-rs/exec-server/src/posix/escalate_server.rs index d99f300704..ef991ce8cd 100644 --- a/codex-rs/exec-server/src/posix/escalate_server.rs +++ b/codex-rs/exec-server/src/posix/escalate_server.rs @@ -10,6 +10,7 @@ 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 tokio::process::Command; use tokio_util::sync::CancellationToken; @@ -87,6 +88,7 @@ impl EscalateServer { expiration: ExecExpiration::Cancellation(cancel_rx), env, sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, justification: None, arg0: None, }, diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index 663f3cbe21..84f89a1678 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -7,6 +7,7 @@ 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_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; @@ -60,6 +61,7 @@ async fn run_cmd_output( expiration: timeout_ms.into(), env: create_env_from_core_vars(), sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, justification: None, arg0: None, }; @@ -177,6 +179,7 @@ async fn assert_network_blocked(cmd: &[&str]) { expiration: NETWORK_TIMEOUT_MS.into(), env: create_env_from_core_vars(), sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, justification: None, arg0: None, }; diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs index 00b9bc0e80..86d39d6d4a 100644 --- a/codex-rs/protocol/src/config_types.rs +++ b/codex-rs/protocol/src/config_types.rs @@ -66,6 +66,18 @@ pub enum SandboxMode { DangerFullAccess, } +#[derive( + Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Display, JsonSchema, TS, +)] +#[serde(rename_all = "kebab-case")] +#[strum(serialize_all = "kebab-case")] +pub enum WindowsSandboxLevel { + #[default] + Disabled, + RestrictedToken, + Elevated, +} + #[derive( Debug, Serialize, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index c60b13d72f..c2d282e995 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -16,6 +16,7 @@ use crate::approvals::ElicitationRequestEvent; use crate::config_types::CollaborationMode; use crate::config_types::Personality; use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; +use crate::config_types::WindowsSandboxLevel; use crate::custom_prompts::CustomPrompt; use crate::dynamic_tools::DynamicToolCallRequest; use crate::dynamic_tools::DynamicToolResponse; @@ -158,6 +159,10 @@ pub enum Op { #[serde(skip_serializing_if = "Option::is_none")] sandbox_policy: Option, + /// Updated Windows sandbox mode for tool execution. + #[serde(skip_serializing_if = "Option::is_none")] + windows_sandbox_level: Option, + /// Updated model slug. When set, the model info is derived /// automatically. #[serde(skip_serializing_if = "Option::is_none")] diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 5413fb1496..4e41a2a0d6 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -42,7 +42,6 @@ use codex_core::config::ConfigOverrides; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config_loader::ConfigLayerStackOrdering; -#[cfg(target_os = "windows")] 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; @@ -58,9 +57,13 @@ 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; use codex_protocol::ThreadId; use codex_protocol::config_types::Personality; +#[cfg(target_os = "windows")] +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::items::TurnItem; use codex_protocol::openai_models::ModelPreset; use codex_protocol::openai_models::ModelUpgrade; @@ -1088,7 +1091,8 @@ impl App { // On startup, if Agent mode (workspace-write) or ReadOnly is active, warn about world-writable dirs on Windows. #[cfg(target_os = "windows")] { - let should_check = codex_core::get_platform_sandbox().is_some() + let should_check = WindowsSandboxLevel::from_config(&app.config) + != WindowsSandboxLevel::Disabled && matches!( app.config.sandbox_policy.get(), codex_core::protocol::SandboxPolicy::WorkspaceWrite { .. } @@ -1684,9 +1688,24 @@ impl App { elevated_enabled, ); self.chat_widget.clear_forced_auto_mode_downgrade(); + let windows_sandbox_level = + WindowsSandboxLevel::from_config(&self.config); if let Some((sample_paths, extra_count, failed_scan)) = self.chat_widget.world_writable_warning_details() { + self.app_event_tx.send(AppEvent::CodexOp( + Op::OverrideTurnContext { + cwd: None, + approval_policy: None, + sandbox_policy: None, + windows_sandbox_level: Some(windows_sandbox_level), + model: None, + effort: None, + summary: None, + collaboration_mode: None, + personality: None, + }, + )); self.app_event_tx.send( AppEvent::OpenWorldWritableWarningConfirmation { preset: Some(preset.clone()), @@ -1701,6 +1720,7 @@ impl App { cwd: None, approval_policy: Some(preset.approval), sandbox_policy: Some(preset.sandbox.clone()), + windows_sandbox_level: Some(windows_sandbox_level), model: None, effort: None, summary: None, @@ -1839,7 +1859,8 @@ impl App { } #[cfg(target_os = "windows")] if !matches!(&policy, codex_core::protocol::SandboxPolicy::ReadOnly) - || codex_core::get_platform_sandbox().is_some() + || WindowsSandboxLevel::from_config(&self.config) + != WindowsSandboxLevel::Disabled { self.config.forced_auto_mode_downgraded_on_windows = false; } @@ -1861,7 +1882,8 @@ impl App { return Ok(AppRunControl::Continue); } - let should_check = codex_core::get_platform_sandbox().is_some() + let should_check = WindowsSandboxLevel::from_config(&self.config) + != WindowsSandboxLevel::Disabled && policy_is_workspace_write_or_ro && !self.chat_widget.world_writable_warning_hidden(); if should_check { @@ -1885,6 +1907,12 @@ impl App { if updates.is_empty() { return Ok(AppRunControl::Continue); } + let windows_sandbox_changed = updates.iter().any(|(feature, _)| { + matches!( + feature, + Feature::WindowsSandbox | Feature::WindowsSandboxElevated + ) + }); let mut builder = ConfigEditsBuilder::new(&self.config.codex_home) .with_profile(self.active_profile.as_deref()); for (feature, enabled) in &updates { @@ -1910,6 +1938,24 @@ impl App { } } } + if windows_sandbox_changed { + #[cfg(target_os = "windows")] + { + let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + self.app_event_tx + .send(AppEvent::CodexOp(Op::OverrideTurnContext { + cwd: None, + approval_policy: None, + sandbox_policy: None, + windows_sandbox_level: Some(windows_sandbox_level), + model: None, + effort: None, + summary: None, + collaboration_mode: None, + personality: None, + })); + } + } if let Err(err) = builder.apply().await { tracing::error!(error = %err, "failed to persist feature flags"); self.chat_widget.add_error_message(format!( diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index f1ec28f3f1..b65d1efb62 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -178,6 +178,9 @@ pub(crate) enum AppEvent { mode: WindowsSandboxEnableMode, }, + /// Update the Windows sandbox feature mode without changing approval presets. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + /// Update the current approval policy in the running app and widget. UpdateAskForApprovalPolicy(AskForApproval), diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 909061aa68..e6a3266d6a 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -273,6 +273,7 @@ pub(crate) struct ChatComposer { config: ChatComposerConfig, collaboration_mode_indicator: Option, personality_command_enabled: bool, + windows_degraded_sandbox_active: bool, } #[derive(Clone, Debug)] @@ -358,6 +359,7 @@ impl ChatComposer { config, collaboration_mode_indicator: None, personality_command_enabled: false, + windows_degraded_sandbox_active: false, }; // Apply configuration via the setter to keep side-effects centralized. this.set_disable_paste_burst(disable_paste_burst); @@ -405,6 +407,10 @@ impl ChatComposer { fn image_paste_enabled(&self) -> bool { self.config.image_paste_enabled } + #[cfg(target_os = "windows")] + pub fn set_windows_degraded_sandbox_active(&mut self, enabled: bool) { + self.windows_degraded_sandbox_active = enabled; + } fn layout_areas(&self, area: Rect) -> [Rect; 3] { let footer_props = self.footer_props(); let footer_hint_height = self @@ -1728,6 +1734,7 @@ impl ChatComposer { name, self.collaboration_modes_enabled, self.personality_command_enabled, + self.windows_degraded_sandbox_active, ) .is_some(); let prompt_prefix = format!("{PROMPTS_CMD_PREFIX}:"); @@ -1904,6 +1911,7 @@ impl ChatComposer { name, self.collaboration_modes_enabled, self.personality_command_enabled, + self.windows_degraded_sandbox_active, ) { self.textarea.set_text_clearing_elements(""); @@ -1931,6 +1939,7 @@ impl ChatComposer { name, self.collaboration_modes_enabled, self.personality_command_enabled, + self.windows_degraded_sandbox_active, ) && cmd == SlashCommand::Review { @@ -2391,6 +2400,7 @@ impl ChatComposer { name, self.collaboration_modes_enabled, self.personality_command_enabled, + self.windows_degraded_sandbox_active, ) { return true; } @@ -2447,6 +2457,7 @@ impl ChatComposer { CommandPopupFlags { collaboration_modes_enabled, personality_command_enabled, + windows_degraded_sandbox_active: self.windows_degraded_sandbox_active, }, ); command_popup.on_composer_text_change(first_line.to_string()); diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 3c54dff0fe..e879e880cc 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -33,6 +33,7 @@ pub(crate) struct CommandPopup { pub(crate) struct CommandPopupFlags { pub(crate) collaboration_modes_enabled: bool, pub(crate) personality_command_enabled: bool, + pub(crate) windows_degraded_sandbox_active: bool, } impl CommandPopup { @@ -41,6 +42,7 @@ impl CommandPopup { let builtins = slash_commands::builtins_for_input( flags.collaboration_modes_enabled, flags.personality_command_enabled, + flags.windows_degraded_sandbox_active, ); // Exclude prompts that collide with builtin command names and sort by name. let exclude: HashSet = builtins.iter().map(|(n, _)| (*n).to_string()).collect(); @@ -461,6 +463,7 @@ mod tests { CommandPopupFlags { collaboration_modes_enabled: true, personality_command_enabled: true, + windows_degraded_sandbox_active: false, }, ); popup.on_composer_text_change("/collab".to_string()); @@ -478,6 +481,7 @@ mod tests { CommandPopupFlags { collaboration_modes_enabled: true, personality_command_enabled: false, + windows_degraded_sandbox_active: false, }, ); popup.on_composer_text_change("/pers".to_string()); @@ -503,6 +507,7 @@ mod tests { CommandPopupFlags { collaboration_modes_enabled: true, personality_command_enabled: true, + windows_degraded_sandbox_active: false, }, ); popup.on_composer_text_change("/personality".to_string()); diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index d0236062f6..bbd59c58bd 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -213,6 +213,12 @@ impl BottomPane { self.request_redraw(); } + #[cfg(target_os = "windows")] + pub fn set_windows_degraded_sandbox_active(&mut self, enabled: bool) { + self.composer.set_windows_degraded_sandbox_active(enabled); + self.request_redraw(); + } + pub fn set_collaboration_mode_indicator( &mut self, indicator: Option, diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index 55765a00da..e0707a4228 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -8,20 +8,12 @@ use codex_common::fuzzy_match::fuzzy_match; use crate::slash_command::SlashCommand; use crate::slash_command::built_in_slash_commands; -/// Whether the Windows degraded-sandbox elevation flow is currently allowed. -pub(crate) fn windows_degraded_sandbox_active() -> bool { - cfg!(target_os = "windows") - && codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED - && codex_core::get_platform_sandbox().is_some() - && !codex_core::is_windows_elevated_sandbox_enabled() -} - /// Return the built-ins that should be visible/usable for the current input. pub(crate) fn builtins_for_input( collaboration_modes_enabled: bool, personality_command_enabled: bool, + allow_elevate_sandbox: bool, ) -> Vec<(&'static str, SlashCommand)> { - let allow_elevate_sandbox = windows_degraded_sandbox_active(); built_in_slash_commands() .into_iter() .filter(|(_, cmd)| allow_elevate_sandbox || *cmd != SlashCommand::ElevateSandbox) @@ -35,11 +27,16 @@ pub(crate) fn find_builtin_command( name: &str, collaboration_modes_enabled: bool, personality_command_enabled: bool, + allow_elevate_sandbox: bool, ) -> Option { - builtins_for_input(collaboration_modes_enabled, personality_command_enabled) - .into_iter() - .find(|(command_name, _)| *command_name == name) - .map(|(_, cmd)| cmd) + builtins_for_input( + collaboration_modes_enabled, + personality_command_enabled, + allow_elevate_sandbox, + ) + .into_iter() + .find(|(command_name, _)| *command_name == name) + .map(|(_, cmd)| cmd) } /// Whether any visible built-in fuzzily matches the provided prefix. @@ -47,8 +44,13 @@ pub(crate) fn has_builtin_prefix( name: &str, collaboration_modes_enabled: bool, personality_command_enabled: bool, + allow_elevate_sandbox: bool, ) -> bool { - builtins_for_input(collaboration_modes_enabled, personality_command_enabled) - .into_iter() - .any(|(command_name, _)| fuzzy_match(command_name, name).is_some()) + builtins_for_input( + collaboration_modes_enabled, + personality_command_enabled, + allow_elevate_sandbox, + ) + .into_iter() + .any(|(command_name, _)| fuzzy_match(command_name, name).is_some()) } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 9dc1bc4bfe..bd1014b2f4 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -88,6 +88,8 @@ use codex_core::protocol::WarningEvent; use codex_core::protocol::WebSearchBeginEvent; use codex_core::protocol::WebSearchEndEvent; use codex_core::skills::model::SkillMetadata; +#[cfg(target_os = "windows")] +use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_otel::OtelManager; use codex_protocol::ThreadId; use codex_protocol::account::PlanType; @@ -97,6 +99,8 @@ use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Personality; use codex_protocol::config_types::Settings; +#[cfg(target_os = "windows")] +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::local_image_label_text; use codex_protocol::parse_command::ParsedCommand; use codex_protocol::request_user_input::RequestUserInputEvent; @@ -2057,6 +2061,14 @@ impl ChatWidget { widget.config.features.enabled(Feature::CollaborationModes), ); widget.sync_personality_command_enabled(); + #[cfg(target_os = "windows")] + widget.bottom_pane.set_windows_degraded_sandbox_active( + codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + && matches!( + WindowsSandboxLevel::from_config(&widget.config), + WindowsSandboxLevel::RestrictedToken + ), + ); widget.update_collaboration_mode_indicator(); widget @@ -2308,6 +2320,14 @@ impl ChatWidget { widget.config.features.enabled(Feature::CollaborationModes), ); widget.sync_personality_command_enabled(); + #[cfg(target_os = "windows")] + widget.bottom_pane.set_windows_degraded_sandbox_active( + codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + && matches!( + WindowsSandboxLevel::from_config(&widget.config), + WindowsSandboxLevel::RestrictedToken + ), + ); widget.update_collaboration_mode_indicator(); widget @@ -2563,9 +2583,9 @@ impl ChatWidget { SlashCommand::ElevateSandbox => { #[cfg(target_os = "windows")] { - let windows_degraded_sandbox_enabled = codex_core::get_platform_sandbox() - .is_some() - && !codex_core::is_windows_elevated_sandbox_enabled(); + let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + let windows_degraded_sandbox_enabled = + matches!(windows_sandbox_level, WindowsSandboxLevel::RestrictedToken); if !windows_degraded_sandbox_enabled || !codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED { @@ -3340,6 +3360,7 @@ impl ChatWidget { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: Some(switch_model.clone()), effort: Some(Some(default_effort)), summary: None, @@ -3462,6 +3483,7 @@ impl ChatWidget { effort: None, summary: None, collaboration_mode: None, + windows_sandbox_level: None, personality: Some(personality), })); tx.send(AppEvent::UpdatePersonality(personality)); @@ -3731,6 +3753,7 @@ impl ChatWidget { 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, @@ -3904,6 +3927,7 @@ impl ChatWidget { cwd: None, approval_policy: None, sandbox_policy: None, + windows_sandbox_level: None, model: Some(model.clone()), effort: Some(effort), summary: None, @@ -3944,8 +3968,10 @@ impl ChatWidget { let presets: Vec = builtin_approval_presets(); #[cfg(target_os = "windows")] - let windows_degraded_sandbox_enabled = codex_core::get_platform_sandbox().is_some() - && !codex_core::is_windows_elevated_sandbox_enabled(); + let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); + #[cfg(target_os = "windows")] + let windows_degraded_sandbox_enabled = + matches!(windows_sandbox_level, WindowsSandboxLevel::RestrictedToken); #[cfg(not(target_os = "windows"))] let windows_degraded_sandbox_enabled = false; @@ -3986,7 +4012,9 @@ impl ChatWidget { } else if preset.id == "auto" { #[cfg(target_os = "windows")] { - if codex_core::get_platform_sandbox().is_none() { + if WindowsSandboxLevel::from_config(&self.config) + == WindowsSandboxLevel::Disabled + { let preset_clone = preset.clone(); if codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED && codex_core::windows_sandbox::sandbox_setup_is_complete( @@ -4088,6 +4116,7 @@ impl ChatWidget { cwd: None, approval_policy: Some(approval), sandbox_policy: Some(sandbox_clone.clone()), + windows_sandbox_level: None, model: None, effort: None, summary: None, @@ -4591,7 +4620,7 @@ impl ChatWidget { #[cfg(target_os = "windows")] pub(crate) fn maybe_prompt_windows_sandbox_enable(&mut self) { if self.config.forced_auto_mode_downgraded_on_windows - && codex_core::get_platform_sandbox().is_none() + && WindowsSandboxLevel::from_config(&self.config) == WindowsSandboxLevel::Disabled && let Some(preset) = builtin_approval_presets() .into_iter() .find(|preset| preset.id == "auto") @@ -4651,7 +4680,7 @@ impl ChatWidget { pub(crate) fn set_sandbox_policy(&mut self, policy: SandboxPolicy) -> ConstraintResult<()> { #[cfg(target_os = "windows")] let should_clear_downgrade = !matches!(&policy, SandboxPolicy::ReadOnly) - || codex_core::get_platform_sandbox().is_some(); + || WindowsSandboxLevel::from_config(&self.config) != WindowsSandboxLevel::Disabled; self.config.sandbox_policy.set(policy)?; @@ -4685,6 +4714,19 @@ impl ChatWidget { self.refresh_model_display(); self.request_redraw(); } + #[cfg(target_os = "windows")] + if matches!( + feature, + Feature::WindowsSandbox | Feature::WindowsSandboxElevated + ) { + self.bottom_pane.set_windows_degraded_sandbox_active( + codex_core::windows_sandbox::ELEVATED_SANDBOX_NUX_ENABLED + && matches!( + WindowsSandboxLevel::from_config(&self.config), + WindowsSandboxLevel::RestrictedToken + ), + ); + } } 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 44aa0340cb..76d5600010 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -92,16 +92,6 @@ use tokio::sync::mpsc::error::TryRecvError; use tokio::sync::mpsc::unbounded_channel; use toml::Value as TomlValue; -#[cfg(target_os = "windows")] -fn set_windows_sandbox_enabled(enabled: bool) { - codex_core::set_windows_sandbox_enabled(enabled); -} - -#[cfg(target_os = "windows")] -fn set_windows_elevated_sandbox_enabled(enabled: bool) { - codex_core::set_windows_elevated_sandbox_enabled(enabled); -} - async fn test_config() -> Config { // Use base defaults to avoid depending on host state. let codex_home = std::env::temp_dir(); @@ -3050,16 +3040,9 @@ async fn approvals_selection_popup_snapshot() { async fn approvals_selection_popup_snapshot_windows_degraded_sandbox() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - let was_sandbox_enabled = codex_core::get_platform_sandbox().is_some(); - let was_elevated_enabled = codex_core::is_windows_elevated_sandbox_enabled(); - chat.config.notices.hide_full_access_warning = None; - chat.config.features.enable(Feature::WindowsSandbox); - chat.config - .features - .disable(Feature::WindowsSandboxElevated); - set_windows_sandbox_enabled(true); - set_windows_elevated_sandbox_enabled(false); + chat.set_feature_enabled(Feature::WindowsSandbox, true); + chat.set_feature_enabled(Feature::WindowsSandboxElevated, false); chat.open_approvals_popup(); @@ -3067,10 +3050,6 @@ async fn approvals_selection_popup_snapshot_windows_degraded_sandbox() { insta::with_settings!({ snapshot_suffix => "windows_degraded" }, { assert_snapshot!("approvals_selection_popup", popup); }); - - // Avoid leaking sandbox global state into other tests. - set_windows_sandbox_enabled(was_sandbox_enabled); - set_windows_elevated_sandbox_enabled(was_elevated_enabled); } #[tokio::test] @@ -3133,7 +3112,8 @@ async fn windows_auto_mode_prompt_requests_enabling_sandbox_feature() { async fn startup_prompts_for_windows_sandbox_when_agent_requested() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; - set_windows_sandbox_enabled(false); + chat.set_feature_enabled(Feature::WindowsSandbox, false); + chat.set_feature_enabled(Feature::WindowsSandboxElevated, false); chat.config.forced_auto_mode_downgraded_on_windows = true; chat.maybe_prompt_windows_sandbox_enable(); @@ -3151,8 +3131,6 @@ async fn startup_prompts_for_windows_sandbox_when_agent_requested() { popup.contains("Stay in"), "expected startup prompt to offer staying in current mode: {popup}" ); - - set_windows_sandbox_enabled(true); } #[tokio::test] diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 0fac506d32..17b839f7a8 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -26,13 +26,14 @@ use codex_core::config::resolve_oss_provider; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::format_config_error_with_source; use codex_core::find_thread_path_by_id_str; -use codex_core::get_platform_sandbox; 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::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_utils_absolute_path::AbsolutePathBuf; @@ -816,7 +817,9 @@ async fn load_config_or_exit_with_fallback_cwd( /// or if the current cwd project is already trusted. If not, we need to /// show the trust screen. fn should_show_trust_screen(config: &Config) -> bool { - if cfg!(target_os = "windows") && get_platform_sandbox().is_none() { + if cfg!(target_os = "windows") + && WindowsSandboxLevel::from_config(config) == WindowsSandboxLevel::Disabled + { // If the experimental sandbox is not enabled, Native Windows cannot enforce sandboxed write access; skip the trust prompt entirely. return false; } From 700a29e15780c16cd54dc5c895ef4cafb65232c9 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Tue, 27 Jan 2026 11:15:38 -0800 Subject: [PATCH 014/116] chore: introduce *Args types for new() methods (#10009) Constructors with long param lists can be hard to reason about when a number of the args are `None`, in practice. Introducing a struct to use as the args type helps make things more self-documenting. --- codex-rs/network-proxy/src/http_proxy.rs | 110 ++++++++-------- codex-rs/network-proxy/src/lib.rs | 1 + codex-rs/network-proxy/src/network_policy.rs | 83 +++++++----- codex-rs/network-proxy/src/runtime.rs | 26 ++-- codex-rs/network-proxy/src/socks5.rs | 130 ++++++++++--------- codex-rs/network-proxy/src/state.rs | 1 + 6 files changed, 189 insertions(+), 162 deletions(-) diff --git a/codex-rs/network-proxy/src/http_proxy.rs b/codex-rs/network-proxy/src/http_proxy.rs index abe6b30144..b2856ac601 100644 --- a/codex-rs/network-proxy/src/http_proxy.rs +++ b/codex-rs/network-proxy/src/http_proxy.rs @@ -2,6 +2,7 @@ use crate::config::NetworkMode; use crate::network_policy::NetworkDecision; use crate::network_policy::NetworkPolicyDecider; use crate::network_policy::NetworkPolicyRequest; +use crate::network_policy::NetworkPolicyRequestArgs; use crate::network_policy::NetworkProtocol; use crate::network_policy::evaluate_host_policy; use crate::policy::normalize_host; @@ -12,6 +13,7 @@ use crate::responses::blocked_header_value; use crate::responses::json_response; use crate::runtime::unix_socket_permissions_supported; use crate::state::BlockedRequest; +use crate::state::BlockedRequestArgs; use crate::state::NetworkProxyState; use crate::upstream::UpstreamClient; use crate::upstream::proxy_for_connect; @@ -146,27 +148,27 @@ async fn http_connect_accept( .await); } - let request = NetworkPolicyRequest::new( - NetworkProtocol::HttpsConnect, - host.clone(), - authority.port, - client.clone(), - Some("CONNECT".to_string()), - None, - None, - ); + let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs { + protocol: NetworkProtocol::HttpsConnect, + host: host.clone(), + port: authority.port, + client_addr: client.clone(), + method: Some("CONNECT".to_string()), + command: None, + exec_policy_hint: None, + }); match evaluate_host_policy(&app_state, policy_decider.as_ref(), &request).await { Ok(NetworkDecision::Deny { reason }) => { let _ = app_state - .record_blocked(BlockedRequest::new( - host.clone(), - reason.clone(), - client.clone(), - Some("CONNECT".to_string()), - None, - "http-connect".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: reason.clone(), + client: client.clone(), + method: Some("CONNECT".to_string()), + mode: None, + protocol: "http-connect".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!("CONNECT blocked (client={client}, host={host}, reason={reason})"); @@ -189,14 +191,14 @@ async fn http_connect_accept( if mode == NetworkMode::Limited { let _ = app_state - .record_blocked(BlockedRequest::new( - host.clone(), - REASON_METHOD_NOT_ALLOWED.to_string(), - client.clone(), - Some("CONNECT".to_string()), - Some(NetworkMode::Limited), - "http-connect".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: REASON_METHOD_NOT_ALLOWED.to_string(), + client: client.clone(), + method: Some("CONNECT".to_string()), + mode: Some(NetworkMode::Limited), + protocol: "http-connect".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!("CONNECT blocked by method policy (client={client}, host={host}, mode=limited)"); @@ -425,27 +427,27 @@ async fn http_plain_proxy( .await); } - let request = NetworkPolicyRequest::new( - NetworkProtocol::Http, - host.clone(), + let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs { + protocol: NetworkProtocol::Http, + host: host.clone(), port, - client.clone(), - Some(req.method().as_str().to_string()), - None, - None, - ); + client_addr: client.clone(), + method: Some(req.method().as_str().to_string()), + command: None, + exec_policy_hint: None, + }); match evaluate_host_policy(&app_state, policy_decider.as_ref(), &request).await { Ok(NetworkDecision::Deny { reason }) => { let _ = app_state - .record_blocked(BlockedRequest::new( - host.clone(), - reason.clone(), - client.clone(), - Some(req.method().as_str().to_string()), - None, - "http".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: reason.clone(), + client: client.clone(), + method: Some(req.method().as_str().to_string()), + mode: None, + protocol: "http".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!("request blocked (client={client}, host={host}, reason={reason})"); @@ -460,14 +462,14 @@ async fn http_plain_proxy( if !method_allowed { let _ = app_state - .record_blocked(BlockedRequest::new( - host.clone(), - REASON_METHOD_NOT_ALLOWED.to_string(), - client.clone(), - Some(req.method().as_str().to_string()), - Some(NetworkMode::Limited), - "http".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: REASON_METHOD_NOT_ALLOWED.to_string(), + client: client.clone(), + method: Some(req.method().as_str().to_string()), + mode: Some(NetworkMode::Limited), + protocol: "http".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); let method = req.method(); @@ -565,14 +567,14 @@ async fn proxy_disabled_response( protocol: &str, ) -> Response { let _ = app_state - .record_blocked(BlockedRequest::new( + .record_blocked(BlockedRequest::new(BlockedRequestArgs { host, - REASON_PROXY_DISABLED.to_string(), + reason: REASON_PROXY_DISABLED.to_string(), client, method, - None, - protocol.to_string(), - )) + mode: None, + protocol: protocol.to_string(), + })) .await; text_response(StatusCode::SERVICE_UNAVAILABLE, "proxy disabled") } diff --git a/codex-rs/network-proxy/src/lib.rs b/codex-rs/network-proxy/src/lib.rs index f4bcb8c74b..e636273128 100644 --- a/codex-rs/network-proxy/src/lib.rs +++ b/codex-rs/network-proxy/src/lib.rs @@ -17,6 +17,7 @@ use anyhow::Result; pub use network_policy::NetworkDecision; pub use network_policy::NetworkPolicyDecider; pub use network_policy::NetworkPolicyRequest; +pub use network_policy::NetworkPolicyRequestArgs; pub use network_policy::NetworkProtocol; pub use proxy::Args; pub use proxy::NetworkProxy; diff --git a/codex-rs/network-proxy/src/network_policy.rs b/codex-rs/network-proxy/src/network_policy.rs index 6f410b3e4b..f14202510c 100644 --- a/codex-rs/network-proxy/src/network_policy.rs +++ b/codex-rs/network-proxy/src/network_policy.rs @@ -26,16 +26,27 @@ pub struct NetworkPolicyRequest { pub exec_policy_hint: Option, } +pub struct NetworkPolicyRequestArgs { + pub protocol: NetworkProtocol, + pub host: String, + pub port: u16, + pub client_addr: Option, + pub method: Option, + pub command: Option, + pub exec_policy_hint: Option, +} + impl NetworkPolicyRequest { - pub fn new( - protocol: NetworkProtocol, - host: String, - port: u16, - client_addr: Option, - method: Option, - command: Option, - exec_policy_hint: Option, - ) -> Self { + pub fn new(args: NetworkPolicyRequestArgs) -> Self { + let NetworkPolicyRequestArgs { + protocol, + host, + port, + client_addr, + method, + command, + exec_policy_hint, + } = args; Self { protocol, host, @@ -139,15 +150,15 @@ mod tests { } }); - let request = NetworkPolicyRequest::new( - NetworkProtocol::Http, - "example.com".to_string(), - 80, - None, - Some("GET".to_string()), - None, - None, - ); + let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs { + protocol: NetworkProtocol::Http, + host: "example.com".to_string(), + port: 80, + client_addr: None, + method: Some("GET".to_string()), + command: None, + exec_policy_hint: None, + }); let decision = evaluate_host_policy(&state, Some(&decider), &request) .await @@ -172,15 +183,15 @@ mod tests { } }); - let request = NetworkPolicyRequest::new( - NetworkProtocol::Http, - "blocked.com".to_string(), - 80, - None, - Some("GET".to_string()), - None, - None, - ); + let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs { + protocol: NetworkProtocol::Http, + host: "blocked.com".to_string(), + port: 80, + client_addr: None, + method: Some("GET".to_string()), + command: None, + exec_policy_hint: None, + }); let decision = evaluate_host_policy(&state, Some(&decider), &request) .await @@ -210,15 +221,15 @@ mod tests { } }); - let request = NetworkPolicyRequest::new( - NetworkProtocol::Http, - "127.0.0.1".to_string(), - 80, - None, - Some("GET".to_string()), - None, - None, - ); + let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs { + protocol: NetworkProtocol::Http, + host: "127.0.0.1".to_string(), + port: 80, + client_addr: None, + method: Some("GET".to_string()), + command: None, + exec_policy_hint: None, + }); let decision = evaluate_host_policy(&state, Some(&decider), &request) .await diff --git a/codex-rs/network-proxy/src/runtime.rs b/codex-rs/network-proxy/src/runtime.rs index 49e34d5c0a..1c29672cfa 100644 --- a/codex-rs/network-proxy/src/runtime.rs +++ b/codex-rs/network-proxy/src/runtime.rs @@ -73,15 +73,25 @@ pub struct BlockedRequest { pub timestamp: i64, } +pub struct BlockedRequestArgs { + pub host: String, + pub reason: String, + pub client: Option, + pub method: Option, + pub mode: Option, + pub protocol: String, +} + impl BlockedRequest { - pub fn new( - host: String, - reason: String, - client: Option, - method: Option, - mode: Option, - protocol: String, - ) -> Self { + pub fn new(args: BlockedRequestArgs) -> Self { + let BlockedRequestArgs { + host, + reason, + client, + method, + mode, + protocol, + } = args; Self { host, reason, diff --git a/codex-rs/network-proxy/src/socks5.rs b/codex-rs/network-proxy/src/socks5.rs index 9426502544..44be9060be 100644 --- a/codex-rs/network-proxy/src/socks5.rs +++ b/codex-rs/network-proxy/src/socks5.rs @@ -2,12 +2,14 @@ use crate::config::NetworkMode; use crate::network_policy::NetworkDecision; use crate::network_policy::NetworkPolicyDecider; use crate::network_policy::NetworkPolicyRequest; +use crate::network_policy::NetworkPolicyRequestArgs; use crate::network_policy::NetworkProtocol; use crate::network_policy::evaluate_host_policy; use crate::policy::normalize_host; use crate::reasons::REASON_METHOD_NOT_ALLOWED; use crate::reasons::REASON_PROXY_DISABLED; use crate::state::BlockedRequest; +use crate::state::BlockedRequestArgs; use crate::state::NetworkProxyState; use anyhow::Context as _; use anyhow::Result; @@ -122,14 +124,14 @@ async fn handle_socks5_tcp( Ok(true) => {} Ok(false) => { let _ = app_state - .record_blocked(BlockedRequest::new( - host.clone(), - REASON_PROXY_DISABLED.to_string(), - client.clone(), - None, - None, - "socks5".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: REASON_PROXY_DISABLED.to_string(), + client: client.clone(), + method: None, + mode: None, + protocol: "socks5".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!("SOCKS blocked; proxy disabled (client={client}, host={host})"); @@ -144,14 +146,14 @@ async fn handle_socks5_tcp( match app_state.network_mode().await { Ok(NetworkMode::Limited) => { let _ = app_state - .record_blocked(BlockedRequest::new( - host.clone(), - REASON_METHOD_NOT_ALLOWED.to_string(), - client.clone(), - None, - Some(NetworkMode::Limited), - "socks5".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: REASON_METHOD_NOT_ALLOWED.to_string(), + client: client.clone(), + method: None, + mode: Some(NetworkMode::Limited), + protocol: "socks5".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!( @@ -166,27 +168,27 @@ async fn handle_socks5_tcp( } } - let request = NetworkPolicyRequest::new( - NetworkProtocol::Socks5Tcp, - host.clone(), + let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs { + protocol: NetworkProtocol::Socks5Tcp, + host: host.clone(), port, - client.clone(), - None, - None, - None, - ); + client_addr: client.clone(), + method: None, + command: None, + exec_policy_hint: None, + }); match evaluate_host_policy(&app_state, policy_decider.as_ref(), &request).await { Ok(NetworkDecision::Deny { reason }) => { let _ = app_state - .record_blocked(BlockedRequest::new( - host.clone(), - reason.clone(), - client.clone(), - None, - None, - "socks5".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: reason.clone(), + client: client.clone(), + method: None, + mode: None, + protocol: "socks5".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!("SOCKS blocked (client={client}, host={host}, reason={reason})"); @@ -231,14 +233,14 @@ async fn inspect_socks5_udp( Ok(true) => {} Ok(false) => { let _ = state - .record_blocked(BlockedRequest::new( - host.clone(), - REASON_PROXY_DISABLED.to_string(), - client.clone(), - None, - None, - "socks5-udp".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: REASON_PROXY_DISABLED.to_string(), + client: client.clone(), + method: None, + mode: None, + protocol: "socks5-udp".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!("SOCKS UDP blocked; proxy disabled (client={client}, host={host})"); @@ -256,14 +258,14 @@ async fn inspect_socks5_udp( match state.network_mode().await { Ok(NetworkMode::Limited) => { let _ = state - .record_blocked(BlockedRequest::new( - host.clone(), - REASON_METHOD_NOT_ALLOWED.to_string(), - client.clone(), - None, - Some(NetworkMode::Limited), - "socks5-udp".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: REASON_METHOD_NOT_ALLOWED.to_string(), + client: client.clone(), + method: None, + mode: Some(NetworkMode::Limited), + protocol: "socks5-udp".to_string(), + })) .await; return Ok(RelayResponse { maybe_payload: None, @@ -277,27 +279,27 @@ async fn inspect_socks5_udp( } } - let request = NetworkPolicyRequest::new( - NetworkProtocol::Socks5Udp, - host.clone(), + let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs { + protocol: NetworkProtocol::Socks5Udp, + host: host.clone(), port, - client.clone(), - None, - None, - None, - ); + client_addr: client.clone(), + method: None, + command: None, + exec_policy_hint: None, + }); match evaluate_host_policy(&state, policy_decider.as_ref(), &request).await { Ok(NetworkDecision::Deny { reason }) => { let _ = state - .record_blocked(BlockedRequest::new( - host.clone(), - reason.clone(), - client.clone(), - None, - None, - "socks5-udp".to_string(), - )) + .record_blocked(BlockedRequest::new(BlockedRequestArgs { + host: host.clone(), + reason: reason.clone(), + client: client.clone(), + method: None, + mode: None, + protocol: "socks5-udp".to_string(), + })) .await; let client = client.as_deref().unwrap_or_default(); warn!("SOCKS UDP blocked (client={client}, host={host}, reason={reason})"); diff --git a/codex-rs/network-proxy/src/state.rs b/codex-rs/network-proxy/src/state.rs index e1e8a1e4e6..552455f510 100644 --- a/codex-rs/network-proxy/src/state.rs +++ b/codex-rs/network-proxy/src/state.rs @@ -20,6 +20,7 @@ use serde::Deserialize; use std::collections::HashSet; pub use crate::runtime::BlockedRequest; +pub use crate::runtime::BlockedRequestArgs; pub use crate::runtime::NetworkProxyState; #[cfg(test)] pub(crate) use crate::runtime::network_proxy_state_for_policy; From 30eb655ad18827bf2386aef6df7c24927748c78b Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Tue, 27 Jan 2026 11:29:28 -0800 Subject: [PATCH 015/116] really fix pwd for windows codex zip (#10011) Co-authored-by: Michael Bolin --- .github/workflows/rust-release.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 35b91e25d5..e2f952ed06 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -252,6 +252,7 @@ jobs: # Path that contains the uncompressed binaries for the current # ${{ matrix.target }} dest="dist/${{ matrix.target }}" + repo_root=$PWD # We want to ship the raw Windows executables in the GitHub Release # in addition to the compressed archives. Keep the originals for @@ -305,7 +306,7 @@ jobs: cp "$setup_src" "$bundle_dir/codex-windows-sandbox-setup.exe" # Use an absolute path so bundle zips land in the real dist # dir even when 7z runs from a temp directory. - (cd "$bundle_dir" && 7z a "$(pwd)/$dest/${base}.zip" .) + (cd "$bundle_dir" && 7z a "$repo_root/$dest/${base}.zip" .) else echo "warning: missing sandbox binaries; falling back to single-binary zip" echo "warning: expected $runner_src and $setup_src" From 2f8a44baea790a8bb2ebb2bc5f31a0cd9543c484 Mon Sep 17 00:00:00 2001 From: alexsong-oai Date: Tue, 27 Jan 2026 12:06:40 -0800 Subject: [PATCH 016/116] Remove load from SKILL.toml fallback (#10007) --- codex-rs/core/src/skills/loader.rs | 243 ++++++++++------------------- 1 file changed, 84 insertions(+), 159 deletions(-) diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index 2216390857..a411dd8bc3 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -52,7 +52,6 @@ struct Interface { const SKILLS_FILENAME: &str = "SKILL.md"; const SKILLS_JSON_FILENAME: &str = "SKILL.json"; -const SKILLS_TOML_FILENAME: &str = "SKILL.toml"; const SKILLS_DIR_NAME: &str = "skills"; const MAX_NAME_LEN: usize = 64; const MAX_DESCRIPTION_LEN: usize = 1024; @@ -373,92 +372,60 @@ fn parse_skill_file(path: &Path, scope: SkillScope) -> Result Option { // Fail open: optional interface metadata should not block loading SKILL.md. let skill_dir = skill_path.parent()?; - let interface_paths = [ - (skill_dir.join(SKILLS_JSON_FILENAME), InterfaceFormat::Json), - (skill_dir.join(SKILLS_TOML_FILENAME), InterfaceFormat::Toml), - ]; - - for (interface_path, format) in interface_paths { - if !interface_path.exists() { - continue; - } - - let contents = match fs::read_to_string(&interface_path) { - Ok(contents) => contents, - Err(error) => { - tracing::warn!( - "ignoring {path}: failed to read {label}: {error}", - path = interface_path.display(), - label = format.label() - ); - continue; - } - }; - let parsed: SkillMetadataFile = match format.parse(&contents) { - Ok(parsed) => parsed, - Err(error) => { - tracing::warn!( - "ignoring {path}: invalid {label}: {error}", - path = interface_path.display(), - label = format.label() - ); - continue; - } - }; - let interface = parsed.interface?; - - let interface = SkillInterface { - display_name: resolve_str( - interface.display_name, - MAX_NAME_LEN, - "interface.display_name", - ), - short_description: resolve_str( - interface.short_description, - MAX_SHORT_DESCRIPTION_LEN, - "interface.short_description", - ), - icon_small: resolve_asset_path(skill_dir, "interface.icon_small", interface.icon_small), - icon_large: resolve_asset_path(skill_dir, "interface.icon_large", interface.icon_large), - brand_color: resolve_color_str(interface.brand_color, "interface.brand_color"), - default_prompt: resolve_str( - interface.default_prompt, - MAX_DEFAULT_PROMPT_LEN, - "interface.default_prompt", - ), - }; - let has_fields = interface.display_name.is_some() - || interface.short_description.is_some() - || interface.icon_small.is_some() - || interface.icon_large.is_some() - || interface.brand_color.is_some() - || interface.default_prompt.is_some(); - return if has_fields { Some(interface) } else { None }; + let interface_path = skill_dir.join(SKILLS_JSON_FILENAME); + if !interface_path.exists() { + return None; } - None -} - -#[derive(Clone, Copy)] -enum InterfaceFormat { - Json, - Toml, -} - -impl InterfaceFormat { - fn label(self) -> &'static str { - match self { - InterfaceFormat::Json => "SKILL.json", - InterfaceFormat::Toml => "SKILL.toml", + let contents = match fs::read_to_string(&interface_path) { + Ok(contents) => contents, + Err(error) => { + tracing::warn!( + "ignoring {path}: failed to read SKILL.json: {error}", + path = interface_path.display() + ); + return None; } - } - - fn parse(self, contents: &str) -> Result { - match self { - InterfaceFormat::Json => serde_json::from_str(contents).map_err(|err| err.to_string()), - InterfaceFormat::Toml => toml::from_str(contents).map_err(|err| err.to_string()), + }; + let parsed: SkillMetadataFile = match serde_json::from_str(&contents) { + Ok(parsed) => parsed, + Err(error) => { + tracing::warn!( + "ignoring {path}: invalid JSON: {error}", + path = interface_path.display() + ); + return None; } - } + }; + let interface = parsed.interface?; + + let interface = SkillInterface { + display_name: resolve_str( + interface.display_name, + MAX_NAME_LEN, + "interface.display_name", + ), + short_description: resolve_str( + interface.short_description, + MAX_SHORT_DESCRIPTION_LEN, + "interface.short_description", + ), + icon_small: resolve_asset_path(skill_dir, "interface.icon_small", interface.icon_small), + icon_large: resolve_asset_path(skill_dir, "interface.icon_large", interface.icon_large), + brand_color: resolve_color_str(interface.brand_color, "interface.brand_color"), + default_prompt: resolve_str( + interface.default_prompt, + MAX_DEFAULT_PROMPT_LEN, + "interface.default_prompt", + ), + }; + let has_fields = interface.display_name.is_some() + || interface.short_description.is_some() + || interface.icon_small.is_some() + || interface.icon_large.is_some() + || interface.brand_color.is_some() + || interface.default_prompt.is_some(); + if has_fields { Some(interface) } else { None } } fn resolve_asset_path( @@ -789,12 +756,6 @@ mod tests { } fn write_skill_interface_at(skill_dir: &Path, contents: &str) -> PathBuf { - let path = skill_dir.join(SKILLS_TOML_FILENAME); - fs::write(&path, contents).unwrap(); - path - } - - fn write_skill_interface_json_at(skill_dir: &Path, contents: &str) -> PathBuf { let path = skill_dir.join(SKILLS_JSON_FILENAME); fs::write(&path, contents).unwrap(); path @@ -802,60 +763,12 @@ mod tests { #[tokio::test] async fn loads_skill_interface_metadata_happy_path() { - let codex_home = tempfile::tempdir().expect("tempdir"); - let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from toml"); - let skill_dir = skill_path.parent().expect("skill dir"); - let normalized_skill_dir = normalized(skill_dir); - - write_skill_interface_at( - skill_dir, - r##" -[interface] -display_name = "UI Skill" -short_description = " short desc " -icon_small = "./assets/small-400px.png" -icon_large = "./assets/large-logo.svg" -brand_color = "#3B82F6" -default_prompt = " default prompt " -"##, - ); - - let cfg = make_config(&codex_home).await; - let outcome = load_skills(&cfg); - - assert!( - outcome.errors.is_empty(), - "unexpected errors: {:?}", - outcome.errors - ); - assert_eq!( - outcome.skills, - vec![SkillMetadata { - name: "ui-skill".to_string(), - description: "from toml".to_string(), - short_description: None, - interface: Some(SkillInterface { - display_name: Some("UI Skill".to_string()), - short_description: Some("short desc".to_string()), - icon_small: Some(normalized_skill_dir.join("assets/small-400px.png")), - icon_large: Some(normalized_skill_dir.join("assets/large-logo.svg")), - brand_color: Some("#3B82F6".to_string()), - default_prompt: Some("default prompt".to_string()), - }), - path: normalized(&skill_path), - scope: SkillScope::User, - }] - ); - } - - #[tokio::test] - async fn loads_skill_interface_metadata_from_json() { let codex_home = tempfile::tempdir().expect("tempdir"); let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); let normalized_skill_dir = normalized(skill_dir); - write_skill_interface_json_at( + write_skill_interface_at( skill_dir, r##" { @@ -902,17 +815,20 @@ default_prompt = " default prompt " #[tokio::test] async fn accepts_icon_paths_under_assets_dir() { let codex_home = tempfile::tempdir().expect("tempdir"); - let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from toml"); + let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); let normalized_skill_dir = normalized(skill_dir); write_skill_interface_at( skill_dir, r#" -[interface] -display_name = "UI Skill" -icon_small = "assets/icon.png" -icon_large = "./assets/logo.svg" +{ + "interface": { + "display_name": "UI Skill", + "icon_small": "assets/icon.png", + "icon_large": "./assets/logo.svg" + } +} "#, ); @@ -928,7 +844,7 @@ icon_large = "./assets/logo.svg" outcome.skills, vec![SkillMetadata { name: "ui-skill".to_string(), - description: "from toml".to_string(), + description: "from json".to_string(), short_description: None, interface: Some(SkillInterface { display_name: Some("UI Skill".to_string()), @@ -947,14 +863,17 @@ icon_large = "./assets/logo.svg" #[tokio::test] async fn ignores_invalid_brand_color() { let codex_home = tempfile::tempdir().expect("tempdir"); - let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from toml"); + let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); write_skill_interface_at( skill_dir, r#" -[interface] -brand_color = "blue" +{ + "interface": { + "brand_color": "blue" + } +} "#, ); @@ -970,7 +889,7 @@ brand_color = "blue" outcome.skills, vec![SkillMetadata { name: "ui-skill".to_string(), - description: "from toml".to_string(), + description: "from json".to_string(), short_description: None, interface: None, path: normalized(&skill_path), @@ -982,7 +901,7 @@ brand_color = "blue" #[tokio::test] async fn ignores_default_prompt_over_max_length() { let codex_home = tempfile::tempdir().expect("tempdir"); - let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from toml"); + let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); let normalized_skill_dir = normalized(skill_dir); let too_long = "x".repeat(MAX_DEFAULT_PROMPT_LEN + 1); @@ -991,10 +910,13 @@ brand_color = "blue" skill_dir, &format!( r##" -[interface] -display_name = "UI Skill" -icon_small = "./assets/small-400px.png" -default_prompt = "{too_long}" +{{ + "interface": {{ + "display_name": "UI Skill", + "icon_small": "./assets/small-400px.png", + "default_prompt": "{too_long}" + }} +}} "## ), ); @@ -1011,7 +933,7 @@ default_prompt = "{too_long}" outcome.skills, vec![SkillMetadata { name: "ui-skill".to_string(), - description: "from toml".to_string(), + description: "from json".to_string(), short_description: None, interface: Some(SkillInterface { display_name: Some("UI Skill".to_string()), @@ -1030,15 +952,18 @@ default_prompt = "{too_long}" #[tokio::test] async fn drops_interface_when_icons_are_invalid() { let codex_home = tempfile::tempdir().expect("tempdir"); - let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from toml"); + let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); write_skill_interface_at( skill_dir, r#" -[interface] -icon_small = "icon.png" -icon_large = "./assets/../logo.svg" +{ + "interface": { + "icon_small": "icon.png", + "icon_large": "./assets/../logo.svg" + } +} "#, ); @@ -1054,7 +979,7 @@ icon_large = "./assets/../logo.svg" outcome.skills, vec![SkillMetadata { name: "ui-skill".to_string(), - description: "from toml".to_string(), + description: "from json".to_string(), short_description: None, interface: None, path: normalized(&skill_path), From 28051d18c6877108a8982fdcb7ae16f37b45e1a6 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Tue, 27 Jan 2026 12:09:05 -0800 Subject: [PATCH 017/116] enable live web search for DangerFullAccess sandbox policy (#10008) Auto-enable live `web_search` tool when sandbox policy is `DangerFullAccess`. Explicitly setting `web_search` (canonical setting), or enabling `web_search_cached` or `web_search_request` still takes precedence over this sandbox-policy-driven enablement. --- codex-rs/core/src/config/mod.rs | 55 ++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 2778c03a7b..4e49efabda 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1203,11 +1203,13 @@ pub fn resolve_oss_provider( } } -/// Resolve the web search mode from explicit config and feature flags. +/// Resolve the web search mode from explicit config, feature flags, and sandbox policy. +/// Live search is auto-enabled when sandbox policy is `DangerFullAccess` fn resolve_web_search_mode( config_toml: &ConfigToml, config_profile: &ConfigProfile, features: &Features, + sandbox_policy: &SandboxPolicy, ) -> WebSearchMode { if let Some(mode) = config_profile.web_search.or(config_toml.web_search) { return mode; @@ -1218,6 +1220,9 @@ fn resolve_web_search_mode( if features.enabled(Feature::WebSearchRequest) { return WebSearchMode::Live; } + if matches!(sandbox_policy, SandboxPolicy::DangerFullAccess) { + return WebSearchMode::Live; + } WebSearchMode::Cached } @@ -1287,7 +1292,6 @@ impl Config { }; let features = Features::from_config(&cfg, &config_profile, feature_overrides); - let web_search_mode = resolve_web_search_mode(&cfg, &config_profile, &features); let resolved_cwd = { use std::env; @@ -1343,6 +1347,8 @@ impl Config { AskForApproval::default() } }); + let web_search_mode = + resolve_web_search_mode(&cfg, &config_profile, &features, &sandbox_policy); // TODO(dylan): We should be able to leverage ConfigLayerStack so that // we can reliably check this at every config level. let did_user_set_custom_approval_policy_or_sandbox_mode = approval_policy_override @@ -2271,7 +2277,7 @@ trust_level = "trusted" let features = Features::with_defaults(); assert_eq!( - resolve_web_search_mode(&cfg, &profile, &features), + resolve_web_search_mode(&cfg, &profile, &features, &SandboxPolicy::ReadOnly), WebSearchMode::Cached ); } @@ -2287,7 +2293,7 @@ trust_level = "trusted" features.enable(Feature::WebSearchCached); assert_eq!( - resolve_web_search_mode(&cfg, &profile, &features), + resolve_web_search_mode(&cfg, &profile, &features, &SandboxPolicy::ReadOnly), WebSearchMode::Live ); } @@ -2303,11 +2309,50 @@ trust_level = "trusted" features.enable(Feature::WebSearchRequest); assert_eq!( - resolve_web_search_mode(&cfg, &profile, &features), + resolve_web_search_mode(&cfg, &profile, &features, &SandboxPolicy::ReadOnly), WebSearchMode::Disabled ); } + #[test] + fn danger_full_access_defaults_web_search_live_when_unset() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg = ConfigToml { + sandbox_mode: Some(SandboxMode::DangerFullAccess), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!(config.web_search_mode, WebSearchMode::Live); + + Ok(()) + } + + #[test] + fn explicit_web_search_mode_wins_in_danger_full_access() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg = ConfigToml { + sandbox_mode: Some(SandboxMode::DangerFullAccess), + web_search: Some(WebSearchMode::Cached), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!(config.web_search_mode, WebSearchMode::Cached); + + Ok(()) + } + #[test] fn profile_legacy_toggles_override_base() -> std::io::Result<()> { let codex_home = TempDir::new()?; From 337643b00a385b6980112dd7dcfcc172765e77be Mon Sep 17 00:00:00 2001 From: K Bediako <70529246+Kbediako@users.noreply.github.com> Date: Wed, 28 Jan 2026 08:14:08 +1100 Subject: [PATCH 018/116] Fix: Render MCP image outputs regardless of ordering (#9815) ## What? - Render an MCP image output cell whenever a decodable image block exists in `CallToolResult.content` (including text-before-image or malformed image before valid image). ## Why? - Tool results that include caption text before the image currently drop the image output cell. - A malformed image block can also suppress later valid image output. ## How? - Iterate `content` and return the first successfully decoded image instead of only checking the first block. - Add unit tests that cover text-before-image ordering and invalid-image-before-valid. ## Before ```rust let image = match result { Ok(mcp_types::CallToolResult { content, .. }) => { if let Some(mcp_types::ContentBlock::ImageContent(image)) = content.first() { // decode image (fails -> None) } else { None } } _ => None, }?; ``` ## After ```rust let image = result .as_ref() .ok()? .content .iter() .find_map(decode_mcp_image)?; ``` ## Risk / Impact - Low: only affects image cell creation for MCP tool results; no change for non-image outputs. ## Tests - [x] `just fmt` - [x] `cargo test -p codex-tui` - [x] Rerun after branch update (2026-01-27): `just fmt`, `cargo test -p codex-tui` Manual testing # Manual testing: MCP image tool result rendering (Codex TUI) # Build the rmcp stdio test server binary: cd codex-rs cargo build -p codex-rmcp-client --bin test_stdio_server # Register the server as an MCP server (absolute path to the built binary): codex mcp add mcpimg -- /Users/joshka/code/codex-pr-review/codex-rs/target/debug/test_stdio_server # Then in Codex TUI, ask it to call: - mcpimg.image_scenario({"scenario":"image_only"}) - mcpimg.image_scenario({"scenario":"text_then_image","caption":"Here is the image:"}) - mcpimg.image_scenario({"scenario":"invalid_base64_then_image"}) - mcpimg.image_scenario({"scenario":"invalid_image_bytes_then_image"}) - mcpimg.image_scenario({"scenario":"multiple_valid_images"}) - mcpimg.image_scenario({"scenario":"image_then_text","caption":"Here is the image:"}) - mcpimg.image_scenario({"scenario":"text_only","caption":"Here is the image:"}) # Expected: # - You should see an extra history cell: "tool result (image output)" when the # tool result contains at least one decodable image block (even if earlier # blocks are text or invalid images). Fixes #9814 --------- Co-authored-by: Josh McKinney --- .../rmcp-client/src/bin/test_stdio_server.rs | 185 +++++++++++++++++- codex-rs/tui/src/history_cell.rs | 153 +++++++++++---- 2 files changed, 296 insertions(+), 42 deletions(-) diff --git a/codex-rs/rmcp-client/src/bin/test_stdio_server.rs b/codex-rs/rmcp-client/src/bin/test_stdio_server.rs index 7805a7de9a..3719766acb 100644 --- a/codex-rs/rmcp-client/src/bin/test_stdio_server.rs +++ b/codex-rs/rmcp-client/src/bin/test_stdio_server.rs @@ -35,12 +35,19 @@ struct TestToolServer { const MEMO_URI: &str = "memo://codex/example-note"; const MEMO_CONTENT: &str = "This is a sample MCP resource served by the rmcp test server."; +const SMALL_PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; + pub fn stdio() -> (tokio::io::Stdin, tokio::io::Stdout) { (tokio::io::stdin(), tokio::io::stdout()) } + impl TestToolServer { fn new() -> Self { - let tools = vec![Self::echo_tool(), Self::image_tool()]; + let tools = vec![ + Self::echo_tool(), + Self::image_tool(), + Self::image_scenario_tool(), + ]; let resources = vec![Self::memo_resource()]; let resource_templates = vec![Self::memo_template()]; Self { @@ -86,6 +93,61 @@ impl TestToolServer { ) } + /// Tool intended for manual testing of Codex TUI rendering for MCP image tool results. + /// + /// This exists to exercise edge cases where a `CallToolResult.content` includes image blocks + /// that aren't the first item (or includes invalid image blocks before a valid image). + /// + /// Manual testing approach (Codex TUI): + /// - Build this binary: `cargo build -p codex-rmcp-client --bin test_stdio_server` + /// - Register it: + /// - `codex mcp add mcpimg -- /abs/path/to/test_stdio_server` + /// - Then in Codex TUI, ask it to call: + /// - `mcpimg.image_scenario({"scenario":"image_only"})` + /// - `mcpimg.image_scenario({"scenario":"text_then_image","caption":"Here is the image:"})` + /// - `mcpimg.image_scenario({"scenario":"invalid_base64_then_image"})` + /// - `mcpimg.image_scenario({"scenario":"invalid_image_bytes_then_image"})` + /// - `mcpimg.image_scenario({"scenario":"multiple_valid_images"})` + /// - `mcpimg.image_scenario({"scenario":"image_then_text","caption":"Here is the image:"})` + /// - `mcpimg.image_scenario({"scenario":"text_only","caption":"Here is the image:"})` + /// - You should see an extra history cell: `tool result (image output)`. + fn image_scenario_tool() -> Tool { + #[expect(clippy::expect_used)] + let schema: JsonObject = serde_json::from_value(serde_json::json!({ + "type": "object", + "properties": { + "scenario": { + "type": "string", + "enum": [ + "image_only", + "text_then_image", + "invalid_base64_then_image", + "invalid_image_bytes_then_image", + "multiple_valid_images", + "image_then_text", + "text_only" + ] + }, + "caption": { "type": "string" }, + "data_url": { + "type": "string", + "description": "Optional data URL like data:image/png;base64,AAAA...; if omitted, uses a built-in tiny PNG." + } + }, + "required": ["scenario"], + "additionalProperties": false + })) + .expect("image_scenario tool schema should deserialize"); + + Tool::new( + Cow::Borrowed("image_scenario"), + Cow::Borrowed( + "Return content blocks for manual testing of MCP image rendering scenarios.", + ), + Arc::new(schema), + ) + } + fn memo_resource() -> Resource { let raw = RawResource { uri: MEMO_URI.to_string(), @@ -125,6 +187,32 @@ struct EchoArgs { env_var: Option, } +#[derive(Deserialize, Debug)] +#[serde(rename_all = "snake_case")] +/// Scenarios for `image_scenario`, intended to exercise Codex TUI handling of MCP image outputs. +/// +/// The key behavior under test is that the TUI should render an image output cell if *any* +/// decodable image block exists in the tool result content, even if the first block is text or an +/// invalid image. +enum ImageScenario { + ImageOnly, + TextThenImage, + InvalidBase64ThenImage, + InvalidImageBytesThenImage, + MultipleValidImages, + ImageThenText, + TextOnly, +} + +#[derive(Deserialize, Debug)] +struct ImageScenarioArgs { + scenario: ImageScenario, + #[serde(default)] + caption: Option, + #[serde(default)] + data_url: Option, +} + impl ServerHandler for TestToolServer { fn get_info(&self) -> ServerInfo { ServerInfo { @@ -244,14 +332,6 @@ impl ServerHandler for TestToolServer { ) })?; - fn parse_data_url(url: &str) -> Option<(String, String)> { - let rest = url.strip_prefix("data:")?; - let (mime_and_opts, data) = rest.split_once(',')?; - let (mime, _opts) = - mime_and_opts.split_once(';').unwrap_or((mime_and_opts, "")); - Some((mime.to_string(), data.to_string())) - } - let (mime_type, data_b64) = parse_data_url(&data_url).ok_or_else(|| { McpError::invalid_params( format!("invalid data URL for image tool: {data_url}"), @@ -263,6 +343,10 @@ impl ServerHandler for TestToolServer { data_b64, mime_type, )])) } + "image_scenario" => { + let args = Self::parse_call_args::(&request, "image_scenario")?; + Self::image_scenario_result(args) + } other => Err(McpError::invalid_params( format!("unknown tool: {other}"), None, @@ -271,6 +355,89 @@ impl ServerHandler for TestToolServer { } } +impl TestToolServer { + fn parse_call_args Deserialize<'de>>( + request: &CallToolRequestParam, + tool_name: &'static str, + ) -> Result { + match request.arguments.as_ref() { + Some(arguments) => serde_json::from_value(serde_json::Value::Object( + arguments.clone().into_iter().collect(), + )) + .map_err(|err| McpError::invalid_params(err.to_string(), None)), + None => Err(McpError::invalid_params( + format!("missing arguments for {tool_name} tool"), + None, + )), + } + } + + fn image_scenario_result(args: ImageScenarioArgs) -> Result { + let (mime_type, valid_data_b64) = if let Some(data_url) = &args.data_url { + parse_data_url(data_url).ok_or_else(|| { + McpError::invalid_params( + format!("invalid data_url for image_scenario tool: {data_url}"), + None, + ) + })? + } else { + ("image/png".to_string(), SMALL_PNG_BASE64.to_string()) + }; + + let caption = args + .caption + .unwrap_or_else(|| "Here is the image:".to_string()); + + let mut content = Vec::new(); + match args.scenario { + ImageScenario::ImageOnly => { + content.push(rmcp::model::Content::image(valid_data_b64, mime_type)); + } + ImageScenario::TextThenImage => { + content.push(rmcp::model::Content::text(caption)); + content.push(rmcp::model::Content::image(valid_data_b64, mime_type)); + } + ImageScenario::InvalidBase64ThenImage => { + content.push(rmcp::model::Content::image( + "not-base64".to_string(), + "image/png".to_string(), + )); + content.push(rmcp::model::Content::image(valid_data_b64, mime_type)); + } + ImageScenario::InvalidImageBytesThenImage => { + content.push(rmcp::model::Content::image( + "bm90IGFuIGltYWdl".to_string(), + "image/png".to_string(), + )); + content.push(rmcp::model::Content::image(valid_data_b64, mime_type)); + } + ImageScenario::MultipleValidImages => { + content.push(rmcp::model::Content::image( + valid_data_b64.clone(), + mime_type.clone(), + )); + content.push(rmcp::model::Content::image(valid_data_b64, mime_type)); + } + ImageScenario::ImageThenText => { + content.push(rmcp::model::Content::image(valid_data_b64, mime_type)); + content.push(rmcp::model::Content::text(caption)); + } + ImageScenario::TextOnly => { + content.push(rmcp::model::Content::text(caption)); + } + } + + Ok(CallToolResult::success(content)) + } +} + +fn parse_data_url(url: &str) -> Option<(String, String)> { + let rest = url.strip_prefix("data:")?; + let (mime_and_opts, data) = rest.split_once(',')?; + let (mime, _opts) = mime_and_opts.split_once(';').unwrap_or((mime_and_opts, "")); + Some((mime.to_string(), data.to_string())) +} + #[tokio::main] async fn main() -> Result<(), Box> { eprintln!("starting rmcp test server"); diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 02a148df4c..687d18fa6a 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -1429,44 +1429,62 @@ pub(crate) fn new_web_search_call( cell } -/// If the first content is an image, return a new cell with the image. -/// TODO(rgwood-dd): Handle images properly even if they're not the first result. +/// Returns an additional history cell if an MCP tool result includes a decodable image. +/// +/// This intentionally returns at most one cell: the first image in `CallToolResult.content` that +/// successfully base64-decodes and parses as an image. This is used as a lightweight “image output +/// exists” affordance separate from the main MCP tool call cell. +/// +/// Manual testing tip: +/// - Run the rmcp stdio test server (`codex-rs/rmcp-client/src/bin/test_stdio_server.rs`) and +/// register it as an MCP server via `codex mcp add`. +/// - Use its `image_scenario` tool with cases like `text_then_image`, +/// `invalid_base64_then_image`, or `invalid_image_bytes_then_image` to ensure this path triggers +/// even when the first block is not a valid image. fn try_new_completed_mcp_tool_call_with_image_output( result: &Result, ) -> Option { - match result { - Ok(mcp_types::CallToolResult { content, .. }) => { - if let Some(mcp_types::ContentBlock::ImageContent(image)) = content.first() { - let raw_data = match base64::engine::general_purpose::STANDARD.decode(&image.data) { - Ok(data) => data, - Err(e) => { - error!("Failed to decode image data: {e}"); - return None; - } - }; - let reader = match ImageReader::new(Cursor::new(raw_data)).with_guessed_format() { - Ok(reader) => reader, - Err(e) => { - error!("Failed to guess image format: {e}"); - return None; - } - }; + let image = result + .as_ref() + .ok()? + .content + .iter() + .find_map(decode_mcp_image)?; - let image = match reader.decode() { - Ok(image) => image, - Err(e) => { - error!("Image decoding failed: {e}"); - return None; - } - }; + Some(CompletedMcpToolCallWithImageOutput { _image: image }) +} - Some(CompletedMcpToolCallWithImageOutput { _image: image }) - } else { - None - } - } - _ => None, - } +/// Decodes an MCP `ImageContent` block into an in-memory image. +/// +/// Returns `None` when the block is not an image, when base64 decoding fails, when the format +/// cannot be inferred, or when the image decoder rejects the bytes. +fn decode_mcp_image(block: &mcp_types::ContentBlock) -> Option { + let image = match block { + mcp_types::ContentBlock::ImageContent(image) => image, + _ => return None, + }; + let raw_data = base64::engine::general_purpose::STANDARD + .decode(&image.data) + .map_err(|e| { + error!("Failed to decode image data: {e}"); + e + }) + .ok()?; + let reader = ImageReader::new(Cursor::new(raw_data)) + .with_guessed_format() + .map_err(|e| { + error!("Failed to guess image format: {e}"); + e + }) + .ok()?; + + reader + .decode() + .map_err(|e| { + error!("Image decoding failed: {e}"); + e + }) + .ok() } #[allow(clippy::disallowed_methods)] @@ -1929,9 +1947,12 @@ mod tests { use codex_core::protocol::ExecCommandSource; use mcp_types::CallToolResult; use mcp_types::ContentBlock; + use mcp_types::ImageContent; use mcp_types::TextContent; use mcp_types::Tool; use mcp_types::ToolInputSchema; + + const SMALL_PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; async fn test_config() -> Config { let codex_home = std::env::temp_dir(); ConfigBuilder::default() @@ -1957,6 +1978,15 @@ mod tests { render_lines(&cell.transcript_lines(u16::MAX)) } + fn image_block(data: &str) -> ContentBlock { + ContentBlock::ImageContent(ImageContent { + annotations: None, + data: data.to_string(), + mime_type: "image/png".into(), + r#type: "image".into(), + }) + } + #[test] fn unified_exec_interaction_cell_renders_input() { let cell = @@ -2251,6 +2281,63 @@ mod tests { insta::assert_snapshot!(rendered); } + #[test] + fn completed_mcp_tool_call_image_after_text_returns_extra_cell() { + let invocation = McpInvocation { + server: "image".into(), + tool: "generate".into(), + arguments: Some(json!({ + "prompt": "tiny image", + })), + }; + + let result = CallToolResult { + content: vec![ + ContentBlock::TextContent(TextContent { + annotations: None, + text: "Here is the image:".into(), + r#type: "text".into(), + }), + image_block(SMALL_PNG_BASE64), + ], + is_error: None, + structured_content: None, + }; + + let mut cell = new_active_mcp_tool_call("call-image".into(), invocation, true); + let extra_cell = cell + .complete(Duration::from_millis(25), Ok(result)) + .expect("expected image cell"); + + let rendered = render_lines(&extra_cell.display_lines(80)); + assert_eq!(rendered, vec!["tool result (image output)"]); + } + + #[test] + fn completed_mcp_tool_call_skips_invalid_image_blocks() { + let invocation = McpInvocation { + server: "image".into(), + tool: "generate".into(), + arguments: Some(json!({ + "prompt": "tiny image", + })), + }; + + let result = CallToolResult { + content: vec![image_block("not-base64"), image_block(SMALL_PNG_BASE64)], + is_error: None, + structured_content: None, + }; + + let mut cell = new_active_mcp_tool_call("call-image-2".into(), invocation, true); + let extra_cell = cell + .complete(Duration::from_millis(25), Ok(result)) + .expect("expected image cell"); + + let rendered = render_lines(&extra_cell.display_lines(80)); + assert_eq!(rendered, vec!["tool result (image output)"]); + } + #[test] fn completed_mcp_tool_call_error_snapshot() { let invocation = McpInvocation { From c7c2b3cf8d1b09128b4aface2895aa69363818d5 Mon Sep 17 00:00:00 2001 From: blevy-oai Date: Tue, 27 Jan 2026 13:22:54 -0800 Subject: [PATCH 019/116] Show OAuth error descriptions in callback responses (#9654) ### Motivation - The local OAuth callback server returned a generic "Invalid OAuth callback" on failures even when the query contained an `error_description`, making it hard to debug OAuth failures. ### Description - Update `codex-rs/rmcp-client/src/perform_oauth_login.rs` to surface `error_description` values from the callback query in the HTTP response. - Introduce a `CallbackOutcome` enum and change `parse_oauth_callback` to return it, parsing `code`, `state`, and `error_description` from the query string. - Change `spawn_callback_server` to match on `CallbackOutcome` and return `OAuth error: ` with a 400 status when `error_description` is present, while preserving the existing success and invalid flows. - Use inline formatting for the error response string. ### Testing - Ran `just fmt` in the `codex-rs` workspace to format changes successfully. - Ran `cargo test -p codex-rmcp-client` and all tests passed. ------ [Codex Task](https://chatgpt.com/codex/tasks/task_i_6971aadc68d0832e93159efea8cd48a9) --- .../rmcp-client/src/perform_oauth_login.rs | 75 +++++++++++++------ 1 file changed, 53 insertions(+), 22 deletions(-) diff --git a/codex-rs/rmcp-client/src/perform_oauth_login.rs b/codex-rs/rmcp-client/src/perform_oauth_login.rs index 64cf979ec7..09b746837e 100644 --- a/codex-rs/rmcp-client/src/perform_oauth_login.rs +++ b/codex-rs/rmcp-client/src/perform_oauth_login.rs @@ -103,21 +103,32 @@ fn spawn_callback_server(server: Arc, tx: oneshot::Sender<(String, Strin tokio::task::spawn_blocking(move || { while let Ok(request) = server.recv() { let path = request.url().to_string(); - if let Some(OauthCallbackResult { code, state }) = parse_oauth_callback(&path) { - let response = - Response::from_string("Authentication complete. You may close this window."); - if let Err(err) = request.respond(response) { - eprintln!("Failed to respond to OAuth callback: {err}"); + match parse_oauth_callback(&path) { + CallbackOutcome::Success(OauthCallbackResult { code, state }) => { + let response = Response::from_string( + "Authentication complete. You may close this window.", + ); + if let Err(err) = request.respond(response) { + eprintln!("Failed to respond to OAuth callback: {err}"); + } + if let Err(err) = tx.send((code, state)) { + eprintln!("Failed to send OAuth callback: {err:?}"); + } + break; } - if let Err(err) = tx.send((code, state)) { - eprintln!("Failed to send OAuth callback: {err:?}"); + CallbackOutcome::Error(description) => { + let response = Response::from_string(format!("OAuth error: {description}")) + .with_status_code(400); + if let Err(err) = request.respond(response) { + eprintln!("Failed to respond to OAuth callback: {err}"); + } } - break; - } else { - let response = - Response::from_string("Invalid OAuth callback").with_status_code(400); - if let Err(err) = request.respond(response) { - eprintln!("Failed to respond to OAuth callback: {err}"); + CallbackOutcome::Invalid => { + let response = + Response::from_string("Invalid OAuth callback").with_status_code(400); + if let Err(err) = request.respond(response) { + eprintln!("Failed to respond to OAuth callback: {err}"); + } } } } @@ -129,29 +140,49 @@ struct OauthCallbackResult { state: String, } -fn parse_oauth_callback(path: &str) -> Option { - let (route, query) = path.split_once('?')?; +enum CallbackOutcome { + Success(OauthCallbackResult), + Error(String), + Invalid, +} + +fn parse_oauth_callback(path: &str) -> CallbackOutcome { + let Some((route, query)) = path.split_once('?') else { + return CallbackOutcome::Invalid; + }; if route != "/callback" { - return None; + return CallbackOutcome::Invalid; } let mut code = None; let mut state = None; + let mut error_description = None; for pair in query.split('&') { - let (key, value) = pair.split_once('=')?; - let decoded = decode(value).ok()?.into_owned(); + let Some((key, value)) = pair.split_once('=') else { + continue; + }; + let Ok(decoded) = decode(value) else { + continue; + }; + let decoded = decoded.into_owned(); match key { "code" => code = Some(decoded), "state" => state = Some(decoded), + "error_description" => error_description = Some(decoded), _ => {} } } - Some(OauthCallbackResult { - code: code?, - state: state?, - }) + if let (Some(code), Some(state)) = (code, state) { + return CallbackOutcome::Success(OauthCallbackResult { code, state }); + } + + if let Some(description) = error_description { + return CallbackOutcome::Error(description); + } + + CallbackOutcome::Invalid } pub struct OauthLoginHandle { From 3ae966edd8fdc194a0f7395c8cfcfc54b94c260b Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Tue, 27 Jan 2026 13:29:55 -0800 Subject: [PATCH 020/116] Clarify external editor env var message (#10030) ### Motivation - Improve UX by making it explicit that `VISUAL`/`EDITOR` must be set before launching Codex, not during a running session. ### Description - Update the external editor error text in `codex-rs/tui/src/app.rs` to: `"Cannot open external editor: set $VISUAL or $EDITOR before starting Codex."` and run `just fmt` to apply formatting. ### Testing - Ran `just fmt` successfully; attempted `cargo test -p codex-tui` but it failed due to network errors when fetching git dependencies (tests did not complete). ------ [Codex Task](https://chatgpt.com/codex/tasks/task_i_6972c2c984948329b1a37d5c5839aff3) --- codex-rs/tui/src/app.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 4e41a2a0d6..87f232ed2b 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -2268,8 +2268,9 @@ impl App { Err(external_editor::EditorError::MissingEditor) => { self.chat_widget .add_to_history(history_cell::new_error_event( - "Cannot open external editor: set $VISUAL or $EDITOR".to_string(), - )); + "Cannot open external editor: set $VISUAL or $EDITOR before starting Codex." + .to_string(), + )); self.reset_external_editor_state(tui); return; } From 19d8f71a98f382857deb08f70710f4086b93ef6b Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Tue, 27 Jan 2026 14:57:07 -0800 Subject: [PATCH 021/116] Ask user question UI footer improvements (#9949) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Polishes the `request_user_input` TUI overlay Question 1 (unanswered) Screenshot 2026-01-27 at 1 30 09 PM Tab to add notes Screenshot 2026-01-27 at 1 30 25 PM Question 2 (unanswered) Screenshot 2026-01-27 at 1 30 55 PM Ctrl+p or h to go back to q1 (answered) Screenshot 2026-01-27 at 1 31 27 PM Unanswered freeform Screenshot 2026-01-27 at 1 31 42 PM ## Key changes - Footer tips wrap at tip boundaries (no truncation mid‑tip); footer height scales to wrapped tips. - Keep tooltip text as Esc: interrupt in all states. - Make the full Tab: add notes tip cyan/bold when applicable; hide notes UI by default. - Notes toggling/backspace: - Tab opens notes when an option is selected; Tab again clears notes and hides the notes UI. - Backspace in options clears the current selection. - Backspace in empty notes closes notes and returns to options. - Selection/answering behavior: - Option questions highlight a default option but are not answered until Enter. - Enter no longer auto‑selects when there’s no selection (prevents accidental answers). - Notes submission can commit the selected option when present. - Freeform questions require Enter with non‑empty text to mark answered; drafts are not submitted unless committed. - Unanswered cues: - Skipped option questions count as unanswered. - Unanswered question titles are highlighted for visibility. - Typing/navigation in options: - Typing no longer opens notes; notes are Tab‑only. - j/k move option selection; h/l switch questions (Ctrl+n/Ctrl+p still work). ## Tests - Added unit coverage for: - tip‑level wrapping - focus reset when switching questions with existing drafts - backspace clearing selection - backspace closing empty notes - typing in options does not open notes - freeform draft submission gating - h/l question navigation in options - Updated snapshots, including narrow footer wrap. ## Why These changes make the ask‑user‑question overlay: - safer (no silent auto‑selection or accidental freeform submission), - clearer (tips wrap cleanly and unanswered states stand out), - more ergonomic (Tab explicitly controls notes; backspace acts like undo/close). ## Codex author `codex fork 019bfc3c-2c42-7982-9119-fee8b9315c2f` --------- Co-authored-by: Ahmed Ibrahim --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 2 - .../bottom_pane/request_user_input/layout.rs | 254 ++-- .../src/bottom_pane/request_user_input/mod.rs | 1190 +++++++++++++++-- .../bottom_pane/request_user_input/render.rs | 304 +++-- ...tests__request_user_input_footer_wrap.snap | 16 + ...t__tests__request_user_input_freeform.snap | 18 +- ...quest_user_input_multi_question_first.snap | 14 + ...equest_user_input_multi_question_last.snap | 15 + ...ut__tests__request_user_input_options.snap | 25 +- ...uest_user_input_options_notes_visible.snap | 19 + ..._request_user_input_scrolling_options.snap | 21 +- ...ests__request_user_input_tight_height.snap | 17 +- ...s__request_user_input_wrapped_options.snap | 27 +- 13 files changed, 1578 insertions(+), 344 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap create mode 100644 codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap create mode 100644 codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap create mode 100644 codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index e6a3266d6a..d101e042e3 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -232,7 +232,6 @@ impl ChatComposerConfig { } } } - pub(crate) struct ChatComposer { textarea: TextArea, textarea_state: RefCell, @@ -394,7 +393,6 @@ impl ChatComposer { pub fn set_personality_command_enabled(&mut self, enabled: bool) { self.personality_command_enabled = enabled; } - /// Centralized feature gating keeps config checks out of call sites. fn popups_enabled(&self) -> bool { self.config.popups_enabled diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs b/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs index 4a1817da89..11856bd1df 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs @@ -1,12 +1,12 @@ use ratatui::layout::Rect; +use super::DESIRED_SPACERS_WHEN_NOTES_HIDDEN; use super::RequestUserInputOverlay; pub(super) struct LayoutSections { pub(super) progress_area: Rect, pub(super) header_area: Rect, pub(super) question_area: Rect, - pub(super) answer_title_area: Rect, // Wrapped question text lines to render in the question area. pub(super) question_lines: Vec, pub(super) options_area: Rect, @@ -20,7 +20,8 @@ impl RequestUserInputOverlay { /// Compute layout sections, collapsing notes and hints as space shrinks. pub(super) fn layout_sections(&self, area: Rect) -> LayoutSections { let has_options = self.has_options(); - let footer_pref = if self.unanswered_count() > 0 { 2 } else { 1 }; + let notes_visible = !has_options || self.notes_ui_visible(); + let footer_pref = self.footer_required_height(area.width); let notes_pref_height = self.notes_input_height(area.width); let mut question_lines = self.wrapped_question_lines(area.width); let question_height = question_lines.len() as u16; @@ -28,18 +29,22 @@ impl RequestUserInputOverlay { let ( question_height, progress_height, - answer_title_height, + spacer_after_question, + options_height, + spacer_after_options, notes_title_height, notes_height, - options_height, footer_lines, ) = if has_options { self.layout_with_options( - area.height, - area.width, - question_height, - notes_pref_height, - footer_pref, + OptionsLayoutArgs { + available_height: area.height, + width: area.width, + question_height, + notes_pref_height, + footer_pref, + notes_visible, + }, &mut question_lines, ) } else { @@ -52,31 +57,24 @@ impl RequestUserInputOverlay { ) }; - let ( - progress_area, - header_area, - question_area, - answer_title_area, - options_area, - notes_title_area, - notes_area, - ) = self.build_layout_areas( - area, - LayoutHeights { - progress_height, - question_height, - answer_title_height, - options_height, - notes_title_height, - notes_height, - }, - ); + let (progress_area, header_area, question_area, options_area, notes_title_area, notes_area) = + self.build_layout_areas( + area, + LayoutHeights { + progress_height, + question_height, + spacer_after_question, + options_height, + spacer_after_options, + notes_title_height, + notes_height, + }, + ); LayoutSections { progress_area, header_area, question_area, - answer_title_area, question_lines, options_area, notes_title_area, @@ -90,21 +88,28 @@ impl RequestUserInputOverlay { /// Handles both tight layout (when space is constrained) and normal layout /// (when there's sufficient space for all elements). /// - /// Returns: (question_height, progress_height, answer_title_height, notes_title_height, notes_height, options_height, footer_lines) + /// Returns: (question_height, progress_height, spacer_after_question, options_height, spacer_after_options, notes_title_height, notes_height, footer_lines) fn layout_with_options( &self, - available_height: u16, - width: u16, - question_height: u16, - notes_pref_height: u16, - footer_pref: u16, + args: OptionsLayoutArgs, question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16) { - let options_required_height = self.options_required_height(width); + ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { + let OptionsLayoutArgs { + available_height, + width, + question_height, + notes_pref_height, + footer_pref, + notes_visible, + } = args; + let options_heights = OptionsHeights { + preferred: self.options_preferred_height(width), + full: self.options_required_height(width), + }; let min_options_height = 1u16; let required = 1u16 .saturating_add(question_height) - .saturating_add(options_required_height); + .saturating_add(options_heights.preferred); if required > available_height { self.layout_with_options_tight( @@ -115,11 +120,14 @@ impl RequestUserInputOverlay { ) } else { self.layout_with_options_normal( - available_height, - question_height, - options_required_height, - notes_pref_height, - footer_pref, + OptionsNormalArgs { + available_height, + question_height, + notes_pref_height, + footer_pref, + notes_visible, + }, + options_heights, ) } } @@ -132,7 +140,7 @@ impl RequestUserInputOverlay { question_height: u16, min_options_height: u16, question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16) { + ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { let max_question_height = available_height.saturating_sub(1u16.saturating_add(min_options_height)); let adjusted_question_height = question_height.min(max_question_height); @@ -140,42 +148,46 @@ impl RequestUserInputOverlay { let options_height = available_height.saturating_sub(1u16.saturating_add(adjusted_question_height)); - (adjusted_question_height, 0, 0, 0, 0, options_height, 0) + (adjusted_question_height, 0, 0, options_height, 0, 0, 0, 0) } - /// Normal layout for options case: allocate space for all elements with - /// preference order: notes, footer, labels, then progress. + /// Normal layout for options case: allocate footer + progress first, and + /// only allocate notes (and its label) when explicitly visible. fn layout_with_options_normal( &self, - available_height: u16, - question_height: u16, - options_required_height: u16, - notes_pref_height: u16, - footer_pref: u16, - ) -> (u16, u16, u16, u16, u16, u16, u16) { - let options_height = options_required_height; + args: OptionsNormalArgs, + options: OptionsHeights, + ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { + let OptionsNormalArgs { + available_height, + question_height, + notes_pref_height, + footer_pref, + notes_visible, + } = args; + let min_options_height = 1u16; + let mut options_height = options.preferred.max(min_options_height); let used = 1u16 .saturating_add(question_height) .saturating_add(options_height); let mut remaining = available_height.saturating_sub(used); - // Prefer notes next, then footer, then labels, with progress last. - let mut notes_height = notes_pref_height.min(remaining); - remaining = remaining.saturating_sub(notes_height); - - let footer_lines = footer_pref.min(remaining); - remaining = remaining.saturating_sub(footer_lines); - - let mut answer_title_height = 0; - if remaining > 0 { - answer_title_height = 1; - remaining = remaining.saturating_sub(1); - } - - let mut notes_title_height = 0; - if remaining > 0 { - notes_title_height = 1; - remaining = remaining.saturating_sub(1); + // When notes are hidden, prefer to reserve room for progress, footer, + // and spacers by shrinking the options window if needed. + let desired_spacers = if notes_visible { + 0 + } else { + DESIRED_SPACERS_WHEN_NOTES_HIDDEN + }; + let required_extra = footer_pref + .saturating_add(1) // progress line + .saturating_add(desired_spacers); + if remaining < required_extra { + let deficit = required_extra.saturating_sub(remaining); + let reducible = options_height.saturating_sub(min_options_height); + let reduce_by = deficit.min(reducible); + options_height = options_height.saturating_sub(reduce_by); + remaining = remaining.saturating_add(reduce_by); } let mut progress_height = 0; @@ -184,16 +196,58 @@ impl RequestUserInputOverlay { remaining = remaining.saturating_sub(1); } - // Expand the notes composer with any leftover rows. + if !notes_visible { + let mut spacer_after_options = 0; + if remaining > footer_pref { + spacer_after_options = 1; + remaining = remaining.saturating_sub(1); + } + let footer_lines = footer_pref.min(remaining); + remaining = remaining.saturating_sub(footer_lines); + let mut spacer_after_question = 0; + if remaining > 0 { + spacer_after_question = 1; + remaining = remaining.saturating_sub(1); + } + let grow_by = remaining.min(options.full.saturating_sub(options_height)); + options_height = options_height.saturating_add(grow_by); + return ( + question_height, + progress_height, + spacer_after_question, + options_height, + spacer_after_options, + 0, + 0, + footer_lines, + ); + } + + let footer_lines = footer_pref.min(remaining); + remaining = remaining.saturating_sub(footer_lines); + + // Prefer notes next, then labels, with any leftover rows expanding notes. + let spacer_after_question = 0; + let spacer_after_options = 0; + let mut notes_height = notes_pref_height.min(remaining); + remaining = remaining.saturating_sub(notes_height); + + let mut notes_title_height = 0; + if remaining > 0 { + notes_title_height = 1; + remaining = remaining.saturating_sub(1); + } + notes_height = notes_height.saturating_add(remaining); ( question_height, progress_height, - answer_title_height, + spacer_after_question, + options_height, + spacer_after_options, notes_title_height, notes_height, - options_height, footer_lines, ) } @@ -203,7 +257,7 @@ impl RequestUserInputOverlay { /// Handles both tight layout (when space is constrained) and normal layout /// (when there's sufficient space for all elements). /// - /// Returns: (question_height, progress_height, answer_title_height, notes_title_height, notes_height, options_height, footer_lines) + /// Returns: (question_height, progress_height, spacer_after_question, options_height, spacer_after_options, notes_title_height, notes_height, footer_lines) fn layout_without_options( &self, available_height: u16, @@ -211,7 +265,7 @@ impl RequestUserInputOverlay { notes_pref_height: u16, footer_pref: u16, question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16) { + ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { let required = 1u16.saturating_add(question_height); if required > available_height { self.layout_without_options_tight(available_height, question_height, question_lines) @@ -231,12 +285,12 @@ impl RequestUserInputOverlay { available_height: u16, question_height: u16, question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16) { + ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { let max_question_height = available_height.saturating_sub(1); let adjusted_question_height = question_height.min(max_question_height); question_lines.truncate(adjusted_question_height as usize); - (adjusted_question_height, 0, 0, 0, 0, 0, 0) + (adjusted_question_height, 0, 0, 0, 0, 0, 0, 0) } /// Normal layout for no-options case: allocate space for notes, footer, and progress. @@ -246,7 +300,7 @@ impl RequestUserInputOverlay { question_height: u16, notes_pref_height: u16, footer_pref: u16, - ) -> (u16, u16, u16, u16, u16, u16, u16) { + ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { let required = 1u16.saturating_add(question_height); let mut remaining = available_height.saturating_sub(required); let mut notes_height = notes_pref_height.min(remaining); @@ -268,8 +322,9 @@ impl RequestUserInputOverlay { progress_height, 0, 0, - notes_height, 0, + 0, + notes_height, footer_lines, ) } @@ -283,7 +338,6 @@ impl RequestUserInputOverlay { Rect, // progress_area Rect, // header_area Rect, // question_area - Rect, // answer_title_area Rect, // options_area Rect, // notes_title_area Rect, // notes_area @@ -311,14 +365,8 @@ impl RequestUserInputOverlay { height: heights.question_height, }; cursor_y = cursor_y.saturating_add(heights.question_height); + cursor_y = cursor_y.saturating_add(heights.spacer_after_question); - let answer_title_area = Rect { - x: area.x, - y: cursor_y, - width: area.width, - height: heights.answer_title_height, - }; - cursor_y = cursor_y.saturating_add(heights.answer_title_height); let options_area = Rect { x: area.x, y: cursor_y, @@ -326,6 +374,7 @@ impl RequestUserInputOverlay { height: heights.options_height, }; cursor_y = cursor_y.saturating_add(heights.options_height); + cursor_y = cursor_y.saturating_add(heights.spacer_after_options); let notes_title_area = Rect { x: area.x, @@ -345,7 +394,6 @@ impl RequestUserInputOverlay { progress_area, header_area, question_area, - answer_title_area, options_area, notes_title_area, notes_area, @@ -357,8 +405,34 @@ impl RequestUserInputOverlay { struct LayoutHeights { progress_height: u16, question_height: u16, - answer_title_height: u16, + spacer_after_question: u16, options_height: u16, + spacer_after_options: u16, notes_title_height: u16, notes_height: u16, } + +#[derive(Clone, Copy, Debug)] +struct OptionsLayoutArgs { + available_height: u16, + width: u16, + question_height: u16, + notes_pref_height: u16, + footer_pref: u16, + notes_visible: bool, +} + +#[derive(Clone, Copy, Debug)] +struct OptionsNormalArgs { + available_height: u16, + question_height: u16, + notes_pref_height: u16, + footer_pref: u16, + notes_visible: bool, +} + +#[derive(Clone, Copy, Debug)] +struct OptionsHeights { + preferred: u16, + full: u16, +} 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 1da955ec3b..3fe16c4314 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 @@ -13,6 +13,7 @@ use std::path::PathBuf; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; +use crossterm::event::KeyModifiers; mod layout; mod render; @@ -33,12 +34,16 @@ use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputEvent; use codex_protocol::request_user_input::RequestUserInputResponse; use codex_protocol::user_input::TextElement; +use unicode_width::UnicodeWidthStr; -const NOTES_PLACEHOLDER: &str = "Add notes (optional)"; +const NOTES_PLACEHOLDER: &str = "Add notes"; const ANSWER_PLACEHOLDER: &str = "Type your answer (optional)"; // Keep in sync with ChatComposer's minimum composer height. const MIN_COMPOSER_HEIGHT: u16 = 3; -const SELECT_OPTION_PLACEHOLDER: &str = "Select an option to add notes (optional)"; +const SELECT_OPTION_PLACEHOLDER: &str = "Select an option to add notes"; +pub(super) const TIP_SEPARATOR: &str = " | "; +pub(super) const MAX_VISIBLE_OPTION_ROWS: usize = 4; +pub(super) const DESIRED_SPACERS_WHEN_NOTES_HIDDEN: u16 = 2; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Focus { @@ -54,12 +59,38 @@ struct ComposerDraft { } struct AnswerState { - // Final selection for the question (always set for option questions). - selected: Option, + // Committed selection for the question (may be None when unanswered). + committed_option_idx: Option, // Scrollable cursor state for option navigation/highlight. - option_state: ScrollState, + options_ui_state: ScrollState, // Per-question notes draft. draft: ComposerDraft, + // Whether a freeform answer has been explicitly submitted. + freeform_committed: bool, + // Whether the notes UI has been explicitly opened for this question. + notes_visible: bool, +} + +#[derive(Clone, Debug)] +pub(super) struct FooterTip { + pub(super) text: String, + pub(super) highlight: bool, +} + +impl FooterTip { + fn new(text: impl Into) -> Self { + Self { + text: text.into(), + highlight: false, + } + } + + fn highlighted(text: impl Into) -> Self { + Self { + text: text.into(), + highlight: true, + } + } } pub(crate) struct RequestUserInputOverlay { @@ -154,8 +185,11 @@ impl RequestUserInputOverlay { if !self.has_options() { return None; } - self.current_answer() - .and_then(|answer| answer.selected.or(answer.option_state.selected_idx)) + self.current_answer().and_then(|answer| { + answer + .committed_option_idx + .or(answer.options_ui_state.selected_idx) + }) } fn current_option_label(&self) -> Option<&str> { @@ -166,6 +200,23 @@ impl RequestUserInputOverlay { .map(|option| option.label.as_str()) } + fn notes_has_content(&self, idx: usize) -> bool { + if idx == self.current_index() { + !self.composer.current_text_with_pending().trim().is_empty() + } else { + !self.answers[idx].draft.text.trim().is_empty() + } + } + + pub(super) fn notes_ui_visible(&self) -> bool { + if !self.has_options() { + return true; + } + let idx = self.current_index(); + self.current_answer() + .is_some_and(|answer| answer.notes_visible || self.notes_has_content(idx)) + } + pub(super) fn wrapped_question_lines(&self, width: u16) -> Vec { self.current_question() .map(|q| { @@ -177,6 +228,10 @@ impl RequestUserInputOverlay { .unwrap_or_default() } + fn focus_is_notes(&self) -> bool { + matches!(self.focus, Focus::Notes) + } + pub(super) fn option_rows(&self) -> Vec { self.current_question() .and_then(|question| question.options.as_ref()) @@ -187,7 +242,7 @@ impl RequestUserInputOverlay { .map(|(idx, opt)| { let selected = self .current_answer() - .and_then(|answer| answer.selected) + .and_then(|answer| answer.committed_option_idx) .is_some_and(|sel| sel == idx); let prefix = if selected { "(x)" } else { "( )" }; GenericDisplayRow { @@ -213,7 +268,7 @@ impl RequestUserInputOverlay { let mut state = self .current_answer() - .map(|answer| answer.option_state) + .map(|answer| answer.options_ui_state) .unwrap_or_default(); if state.selected_idx.is_none() { state.selected_idx = Some(0); @@ -222,6 +277,28 @@ impl RequestUserInputOverlay { measure_rows_height(&rows, &state, rows.len(), width.max(1)) } + pub(super) fn options_preferred_height(&self, width: u16) -> u16 { + if !self.has_options() { + return 0; + } + + let rows = self.option_rows(); + if rows.is_empty() { + return 1; + } + + let mut state = self + .current_answer() + .map(|answer| answer.options_ui_state) + .unwrap_or_default(); + if state.selected_idx.is_none() { + state.selected_idx = Some(0); + } + + let visible_items = rows.len().min(MAX_VISIBLE_OPTION_ROWS); + measure_rows_height(&rows, &state, visible_items, width.max(1)) + } + fn capture_composer_draft(&self) -> ComposerDraft { ComposerDraft { text: self.composer.current_text_with_pending(), @@ -237,8 +314,12 @@ impl RequestUserInputOverlay { fn save_current_draft(&mut self) { let draft = self.capture_composer_draft(); + let notes_empty = draft.text.trim().is_empty(); if let Some(answer) = self.current_answer_mut() { answer.draft = draft; + if !notes_empty { + answer.notes_visible = true; + } } } @@ -259,11 +340,7 @@ impl RequestUserInputOverlay { } fn notes_placeholder(&self) -> &'static str { - if self.has_options() - && self - .current_answer() - .is_some_and(|answer| answer.selected.is_none()) - { + if self.has_options() && self.selected_option_index().is_none() { SELECT_OPTION_PLACEHOLDER } else if self.has_options() { NOTES_PLACEHOLDER @@ -272,6 +349,94 @@ impl RequestUserInputOverlay { } } + fn sync_composer_placeholder(&mut self) { + self.composer + .set_placeholder_text(self.notes_placeholder().to_string()); + } + + fn footer_tips(&self) -> Vec { + let mut tips = Vec::new(); + let notes_visible = self.notes_ui_visible(); + if self.has_options() { + let options_len = self.options_len(); + if let Some(selected_idx) = self.selected_option_index() { + let option_index = selected_idx + 1; + tips.push(FooterTip::new(format!( + "Option {option_index} of {options_len}" + ))); + } else { + tips.push(FooterTip::new("No option selected")); + } + tips.push(FooterTip::new("\u{2191}/\u{2193} scroll")); + if self.selected_option_index().is_some() && !notes_visible { + tips.push(FooterTip::highlighted("Tab: add notes")); + } + if self.selected_option_index().is_some() && notes_visible && self.focus_is_notes() { + tips.push(FooterTip::new("Tab: clear notes")); + } + } + + let question_count = self.question_count(); + let is_last_question = question_count > 0 && self.current_index() + 1 >= question_count; + let enter_tip = if question_count > 1 && is_last_question { + "Enter: submit all answers" + } else { + "Enter: submit answer" + }; + tips.push(FooterTip::new(enter_tip)); + if question_count > 1 { + tips.push(FooterTip::new("Ctrl+n next")); + } + tips.push(FooterTip::new("Esc: interrupt")); + tips + } + + pub(super) fn footer_tip_lines(&self, width: u16) -> Vec> { + let max_width = width.max(1) as usize; + let separator_width = UnicodeWidthStr::width(TIP_SEPARATOR); + let tips = self.footer_tips(); + if tips.is_empty() { + return vec![Vec::new()]; + } + + let mut lines: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + let mut used = 0usize; + + for tip in tips { + let tip_width = UnicodeWidthStr::width(tip.text.as_str()).min(max_width); + let extra = if current.is_empty() { + tip_width + } else { + separator_width.saturating_add(tip_width) + }; + if !current.is_empty() && used.saturating_add(extra) > max_width { + lines.push(current); + current = Vec::new(); + used = 0; + } + if current.is_empty() { + used = tip_width; + } else { + used = used + .saturating_add(separator_width) + .saturating_add(tip_width); + } + current.push(tip); + } + + if current.is_empty() { + lines.push(Vec::new()); + } else { + lines.push(current); + } + lines + } + + pub(super) fn footer_required_height(&self, width: u16) -> u16 { + self.footer_tip_lines(width).len() as u16 + } + /// Ensure the focus mode is valid for the current question. fn ensure_focus_available(&mut self) { if self.question_count() == 0 { @@ -279,6 +444,14 @@ impl RequestUserInputOverlay { } if !self.has_options() { self.focus = Focus::Notes; + if let Some(answer) = self.current_answer_mut() { + answer.notes_visible = true; + } + return; + } + if matches!(self.focus, Focus::Notes) && !self.notes_ui_visible() { + self.focus = Focus::Options; + self.sync_composer_placeholder(); } } @@ -289,16 +462,20 @@ impl RequestUserInputOverlay { .questions .iter() .map(|question| { - let mut option_state = ScrollState::new(); - if let Some(options) = question.options.as_ref() - && !options.is_empty() - { - option_state.selected_idx = Some(0); + let has_options = question + .options + .as_ref() + .is_some_and(|options| !options.is_empty()); + let mut options_ui_state = ScrollState::new(); + if has_options { + options_ui_state.selected_idx = Some(0); } AnswerState { - selected: option_state.selected_idx, - option_state, + committed_option_idx: None, + options_ui_state, draft: ComposerDraft::default(), + freeform_committed: false, + notes_visible: !has_options, } }) .collect(); @@ -318,8 +495,8 @@ impl RequestUserInputOverlay { self.save_current_draft(); let offset = if next { 1 } else { len.saturating_sub(1) }; self.current_idx = (self.current_idx + offset) % len; - self.ensure_focus_available(); self.restore_current_draft(); + self.ensure_focus_available(); } /// Synchronize selection state to the currently focused option. @@ -328,22 +505,41 @@ impl RequestUserInputOverlay { return; } let options_len = self.options_len(); - let Some(answer) = self.current_answer_mut() else { - return; + let updated = if let Some(answer) = self.current_answer_mut() { + answer.options_ui_state.clamp_selection(options_len); + answer.committed_option_idx = answer.options_ui_state.selected_idx; + true + } else { + false }; - answer.option_state.clamp_selection(options_len); - answer.selected = answer.option_state.selected_idx; + if updated { + self.sync_composer_placeholder(); + } + } + + /// Clear the current option selection and hide notes when empty. + fn clear_selection(&mut self) { + if !self.has_options() { + return; + } + self.save_current_draft(); + let notes_empty = self.composer.current_text_with_pending().trim().is_empty(); + if let Some(answer) = self.current_answer_mut() { + answer.committed_option_idx = None; + answer.options_ui_state.reset(); + if notes_empty { + answer.notes_visible = false; + } + } + self.sync_composer_placeholder(); } /// Ensure there is a selection before allowing notes entry. fn ensure_selected_for_notes(&mut self) { - if self.has_options() - && self - .current_answer() - .is_some_and(|answer| answer.selected.is_none()) - { - self.select_current_option(); + if let Some(answer) = self.current_answer_mut() { + answer.notes_visible = true; } + self.sync_composer_placeholder(); } /// Advance to next question, or submit when on the last one. @@ -362,16 +558,21 @@ impl RequestUserInputOverlay { for (idx, question) in self.request.questions.iter().enumerate() { let answer_state = &self.answers[idx]; let options = question.options.as_ref(); - // For option questions we always produce a selection. + // For option questions we may still produce no selection. let selected_idx = if options.is_some_and(|opts| !opts.is_empty()) { - answer_state - .selected - .or(answer_state.option_state.selected_idx) + answer_state.committed_option_idx } else { - answer_state.selected + None + }; + // Notes are appended as extra answers. For freeform questions, only submit when + // the user explicitly committed the draft. + let notes = if options.is_some_and(|opts| !opts.is_empty()) + || answer_state.freeform_committed + { + answer_state.draft.text.trim().to_string() + } else { + String::new() }; - // Notes are appended as extra answers. - let notes = answer_state.draft.text.trim().to_string(); let selected_label = selected_idx.and_then(|selected_idx| { question .options @@ -405,27 +606,37 @@ impl RequestUserInputOverlay { } } - /// Count freeform-only questions that have no notes. + fn is_question_answered(&self, idx: usize, _current_text: &str) -> bool { + let Some(question) = self.request.questions.get(idx) else { + return false; + }; + let Some(answer) = self.answers.get(idx) else { + return false; + }; + let has_options = question + .options + .as_ref() + .is_some_and(|options| !options.is_empty()); + if has_options { + answer.committed_option_idx.is_some() + } else { + answer.freeform_committed + } + } + + fn current_question_answered(&self) -> bool { + let current_text = self.composer.current_text(); + self.is_question_answered(self.current_index(), ¤t_text) + } + + /// Count questions that would submit an empty answer list. fn unanswered_count(&self) -> usize { let current_text = self.composer.current_text(); self.request .questions .iter() .enumerate() - .filter(|(idx, question)| { - let answer = &self.answers[*idx]; - let options = question.options.as_ref(); - if options.is_some_and(|opts| !opts.is_empty()) { - false - } else { - let notes = if *idx == self.current_index() { - current_text.as_str() - } else { - answer.draft.text.as_str() - }; - notes.trim().is_empty() - } - }) + .filter(|(idx, _question)| !self.is_question_answered(*idx, ¤t_text)) .count() } @@ -467,6 +678,21 @@ impl RequestUserInputOverlay { text, text_elements, } => { + if self.has_options() + && matches!(self.focus, Focus::Notes) + && !text.trim().is_empty() + { + let options_len = self.options_len(); + if let Some(answer) = self.current_answer_mut() { + answer.options_ui_state.clamp_selection(options_len); + answer.committed_option_idx = answer.options_ui_state.selected_idx; + } + } + if !self.has_options() + && let Some(answer) = self.current_answer_mut() + { + answer.freeform_committed = !text.trim().is_empty(); + } self.apply_submission_to_draft(text, text_elements); self.go_next_or_submit(); true @@ -489,12 +715,36 @@ impl BottomPaneView for RequestUserInputOverlay { } // Question navigation is always available. - match key_event.code { - KeyCode::PageUp => { + match key_event { + KeyEvent { + code: KeyCode::Char('p'), + modifiers: KeyModifiers::CONTROL, + .. + } => { self.move_question(false); return; } - KeyCode::PageDown => { + KeyEvent { + code: KeyCode::Char('n'), + modifiers: KeyModifiers::CONTROL, + .. + } => { + self.move_question(true); + return; + } + KeyEvent { + code: KeyCode::Char('h'), + modifiers: KeyModifiers::NONE, + .. + } if self.has_options() && matches!(self.focus, Focus::Options) => { + self.move_question(false); + return; + } + KeyEvent { + code: KeyCode::Char('l'), + modifiers: KeyModifiers::NONE, + .. + } if self.has_options() && matches!(self.focus, Focus::Options) => { self.move_question(true); return; } @@ -506,36 +756,74 @@ impl BottomPaneView for RequestUserInputOverlay { let options_len = self.options_len(); // Keep selection synchronized as the user moves. match key_event.code { - KeyCode::Up => { - if let Some(answer) = self.current_answer_mut() { - answer.option_state.move_up_wrap(options_len); - answer.selected = answer.option_state.selected_idx; + KeyCode::Up | KeyCode::Char('k') => { + let moved = if let Some(answer) = self.current_answer_mut() { + answer.options_ui_state.move_up_wrap(options_len); + true + } else { + false + }; + if moved { + self.sync_composer_placeholder(); } } - KeyCode::Down => { - if let Some(answer) = self.current_answer_mut() { - answer.option_state.move_down_wrap(options_len); - answer.selected = answer.option_state.selected_idx; + KeyCode::Down | KeyCode::Char('j') => { + let moved = if let Some(answer) = self.current_answer_mut() { + answer.options_ui_state.move_down_wrap(options_len); + true + } else { + false + }; + if moved { + self.sync_composer_placeholder(); } } KeyCode::Char(' ') => { self.select_current_option(); } - KeyCode::Enter => { - self.select_current_option(); - self.go_next_or_submit(); + KeyCode::Backspace => { + self.clear_selection(); } - KeyCode::Char(_) | KeyCode::Backspace | KeyCode::Delete => { - // Any typing while in options switches to notes for fast freeform input. - self.focus = Focus::Notes; - self.ensure_selected_for_notes(); - let (result, _) = self.composer.handle_key_event(key_event); - self.handle_composer_input_result(result); + KeyCode::Tab => { + if self.selected_option_index().is_some() { + self.focus = Focus::Notes; + self.ensure_selected_for_notes(); + } + } + KeyCode::Enter => { + let has_selection = self.selected_option_index().is_some(); + if has_selection { + self.select_current_option(); + } + self.go_next_or_submit(); } _ => {} } } Focus::Notes => { + let notes_empty = self.composer.current_text_with_pending().trim().is_empty(); + if self.has_options() && matches!(key_event.code, KeyCode::Tab) { + if let Some(answer) = self.current_answer_mut() { + answer.draft = ComposerDraft::default(); + answer.notes_visible = false; + } + self.composer + .set_text_content(String::new(), Vec::new(), Vec::new()); + self.composer.move_cursor_to_end(); + self.focus = Focus::Options; + self.sync_composer_placeholder(); + return; + } + if self.has_options() && matches!(key_event.code, KeyCode::Backspace) && notes_empty + { + self.save_current_draft(); + if let Some(answer) = self.current_answer_mut() { + answer.notes_visible = false; + } + self.focus = Focus::Options; + self.sync_composer_placeholder(); + return; + } if matches!(key_event.code, KeyCode::Enter) { self.ensure_selected_for_notes(); let (result, _) = self.composer.handle_key_event(key_event); @@ -548,15 +836,25 @@ impl BottomPaneView for RequestUserInputOverlay { let options_len = self.options_len(); match key_event.code { KeyCode::Up => { - if let Some(answer) = self.current_answer_mut() { - answer.option_state.move_up_wrap(options_len); - answer.selected = answer.option_state.selected_idx; + let moved = if let Some(answer) = self.current_answer_mut() { + answer.options_ui_state.move_up_wrap(options_len); + true + } else { + false + }; + if moved { + self.sync_composer_placeholder(); } } KeyCode::Down => { - if let Some(answer) = self.current_answer_mut() { - answer.option_state.move_down_wrap(options_len); - answer.selected = answer.option_state.selected_idx; + let moved = if let Some(answer) = self.current_answer_mut() { + answer.options_ui_state.move_down_wrap(options_len); + true + } else { + false + }; + if moved { + self.sync_composer_placeholder(); } } _ => {} @@ -613,6 +911,7 @@ impl BottomPaneView for RequestUserInputOverlay { mod tests { use super::*; use crate::app_event::AppEvent; + use crate::bottom_pane::selection_popup_common::menu_surface_inset; use crate::render::renderable::Renderable; use codex_protocol::request_user_input::RequestUserInputQuestion; use codex_protocol::request_user_input::RequestUserInputQuestionOption; @@ -620,6 +919,7 @@ mod tests { use ratatui::buffer::Buffer; use ratatui::layout::Rect; use tokio::sync::mpsc::unbounded_channel; + use unicode_width::UnicodeWidthStr; fn test_sender() -> ( AppEventSender, @@ -747,7 +1047,7 @@ mod tests { } #[test] - fn options_always_return_a_selection() { + fn options_can_submit_empty_when_unanswered() { let (tx, mut rx) = test_sender(); let mut overlay = RequestUserInputOverlay::new( request_event("turn-1", vec![question_with_options("q1", "Pick one")]), @@ -765,9 +1065,475 @@ mod tests { }; assert_eq!(id, "turn-1"); let answer = response.answers.get("q1").expect("answer missing"); + assert_eq!(answer.answers, Vec::::new()); + } + + #[test] + fn enter_commits_default_selection_on_last_option_question() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { + panic!("expected UserInputAnswer"); + }; + let answer = response.answers.get("q1").expect("answer missing"); assert_eq!(answer.answers, vec!["Option 1".to_string()]); } + #[test] + fn enter_commits_default_selection_on_non_last_option_question() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Pick one"), + question_with_options("q2", "Pick two"), + ], + ), + tx, + true, + false, + false, + ); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + assert_eq!(overlay.current_index(), 1); + let first_answer = &overlay.answers[0]; + assert_eq!(first_answer.committed_option_idx, Some(0)); + assert_eq!(first_answer.options_ui_state.selected_idx, Some(0)); + assert!(rx.try_recv().is_err()); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { + panic!("expected UserInputAnswer"); + }; + let answer = response.answers.get("q1").expect("answer missing"); + assert_eq!(answer.answers, vec!["Option 1".to_string()]); + } + + #[test] + fn vim_keys_move_option_selection() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer().expect("answer missing"); + assert_eq!(answer.options_ui_state.selected_idx, Some(0)); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('j'))); + let answer = overlay.current_answer().expect("answer missing"); + assert_eq!(answer.options_ui_state.selected_idx, Some(1)); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('k'))); + let answer = overlay.current_answer().expect("answer missing"); + assert_eq!(answer.options_ui_state.selected_idx, Some(0)); + } + + #[test] + fn typing_in_options_does_not_open_notes() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Pick one"), + question_with_options("q2", "Pick two"), + ], + ), + tx, + true, + false, + false, + ); + + assert_eq!(overlay.current_index(), 0); + assert_eq!(overlay.notes_ui_visible(), false); + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('x'))); + assert_eq!(overlay.current_index(), 0); + assert_eq!(overlay.notes_ui_visible(), false); + assert!(matches!(overlay.focus, Focus::Options)); + assert_eq!(overlay.composer.current_text_with_pending(), ""); + } + + #[test] + fn h_l_move_between_questions_in_options() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Pick one"), + question_with_options("q2", "Pick two"), + ], + ), + tx, + true, + false, + false, + ); + + assert_eq!(overlay.current_index(), 0); + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('l'))); + assert_eq!(overlay.current_index(), 1); + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('h'))); + assert_eq!(overlay.current_index(), 0); + } + + #[test] + fn tab_opens_notes_when_option_selected() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(1); + answer.committed_option_idx = Some(1); + + assert_eq!(overlay.notes_ui_visible(), false); + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + assert_eq!(overlay.notes_ui_visible(), true); + assert!(matches!(overlay.focus, Focus::Notes)); + } + + #[test] + fn switching_to_options_resets_notes_focus_when_notes_hidden() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_without_options("q1", "Notes"), + question_with_options("q2", "Pick one"), + ], + ), + tx, + true, + false, + false, + ); + + assert!(matches!(overlay.focus, Focus::Notes)); + overlay.move_question(true); + + let answer = overlay.current_answer().expect("answer missing"); + assert!(matches!(overlay.focus, Focus::Options)); + assert_eq!(answer.committed_option_idx, None); + assert_eq!(overlay.notes_ui_visible(), false); + } + + #[test] + fn switching_from_freeform_with_text_resets_focus_and_keeps_last_option_empty() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_without_options("q1", "Notes"), + question_with_options("q2", "Pick one"), + ], + ), + tx, + true, + false, + false, + ); + + overlay + .composer + .set_text_content("freeform notes".to_string(), Vec::new(), Vec::new()); + overlay.composer.move_cursor_to_end(); + + overlay.move_question(true); + + let answer = overlay.current_answer().expect("answer missing"); + assert!(matches!(overlay.focus, Focus::Options)); + assert_eq!(overlay.notes_ui_visible(), false); + assert_eq!(answer.committed_option_idx, None); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { + panic!("expected UserInputAnswer"); + }; + let answer = response.answers.get("q2").expect("answer missing"); + assert_eq!(answer.answers, vec!["Option 1".to_string()]); + } + + #[test] + fn esc_in_notes_mode_without_options_interrupts() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_without_options("q1", "Notes")]), + tx, + true, + false, + false, + ); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Esc)); + + assert_eq!(overlay.done, true); + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(op) = event else { + panic!("expected CodexOp"); + }; + assert_eq!(op, Op::Interrupt); + } + + #[test] + fn esc_in_options_mode_interrupts() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Esc)); + + assert_eq!(overlay.done, true); + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(op) = event else { + panic!("expected CodexOp"); + }; + assert_eq!(op, Op::Interrupt); + } + + #[test] + fn esc_in_notes_mode_interrupts() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + answer.committed_option_idx = Some(0); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + overlay.handle_key_event(KeyEvent::from(KeyCode::Esc)); + + assert_eq!(overlay.done, true); + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(op) = event else { + panic!("expected CodexOp"); + }; + assert_eq!(op, Op::Interrupt); + } + + #[test] + fn esc_in_notes_mode_interrupts_with_notes_visible() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + answer.committed_option_idx = Some(0); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('a'))); + overlay.handle_key_event(KeyEvent::from(KeyCode::Esc)); + + assert_eq!(overlay.done, true); + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(op) = event else { + panic!("expected CodexOp"); + }; + assert_eq!(op, Op::Interrupt); + } + + #[test] + fn backspace_in_options_clears_selection() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(1); + answer.committed_option_idx = Some(1); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Backspace)); + + let answer = overlay.current_answer().expect("answer missing"); + assert_eq!(answer.committed_option_idx, None); + assert_eq!(answer.options_ui_state.selected_idx, None); + assert_eq!(overlay.notes_ui_visible(), false); + assert!(rx.try_recv().is_err()); + } + + #[test] + fn backspace_on_empty_notes_closes_notes_ui() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + answer.committed_option_idx = Some(0); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + assert!(matches!(overlay.focus, Focus::Notes)); + assert_eq!(overlay.notes_ui_visible(), true); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Backspace)); + + let answer = overlay.current_answer().expect("answer missing"); + assert!(matches!(overlay.focus, Focus::Options)); + assert_eq!(overlay.notes_ui_visible(), false); + assert_eq!(answer.committed_option_idx, Some(0)); + assert!(rx.try_recv().is_err()); + } + + #[test] + fn tab_in_notes_clears_notes_and_hides_ui() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + answer.committed_option_idx = Some(0); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + overlay + .composer + .set_text_content("Some notes".to_string(), Vec::new(), Vec::new()); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + + let answer = overlay.current_answer().expect("answer missing"); + assert!(matches!(overlay.focus, Focus::Options)); + assert_eq!(overlay.notes_ui_visible(), false); + assert_eq!(overlay.composer.current_text_with_pending(), ""); + assert_eq!(answer.draft.text, ""); + assert_eq!(answer.committed_option_idx, Some(0)); + assert!(rx.try_recv().is_err()); + } + + #[test] + fn skipped_option_questions_count_as_unanswered() { + let (tx, _rx) = test_sender(); + let overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + + assert_eq!(overlay.unanswered_count(), 1); + } + + #[test] + fn highlighted_option_questions_are_unanswered() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + + assert_eq!(overlay.unanswered_count(), 1); + } + + #[test] + fn freeform_requires_enter_with_text_to_mark_answered() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_without_options("q1", "Notes"), + question_without_options("q2", "More"), + ], + ), + tx, + true, + false, + false, + ); + + overlay + .composer + .set_text_content("Draft".to_string(), Vec::new(), Vec::new()); + overlay.composer.move_cursor_to_end(); + assert_eq!(overlay.unanswered_count(), 2); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + assert_eq!(overlay.answers[0].freeform_committed, true); + assert_eq!(overlay.unanswered_count(), 1); + } + + #[test] + fn freeform_enter_with_empty_text_is_unanswered() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_without_options("q1", "Notes"), + question_without_options("q2", "More"), + ], + ), + tx, + true, + false, + false, + ); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + assert_eq!(overlay.answers[0].freeform_committed, false); + assert_eq!(overlay.unanswered_count(), 2); + } + #[test] fn freeform_questions_submit_empty_when_empty() { let (tx, mut rx) = test_sender(); @@ -789,6 +1555,31 @@ mod tests { assert_eq!(answer.answers, Vec::::new()); } + #[test] + fn freeform_draft_is_not_submitted_without_enter() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_without_options("q1", "Notes")]), + tx, + true, + false, + false, + ); + overlay + .composer + .set_text_content("Draft text".to_string(), Vec::new(), Vec::new()); + overlay.composer.move_cursor_to_end(); + + overlay.submit_answers(); + + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { + panic!("expected UserInputAnswer"); + }; + let answer = response.answers.get("q1").expect("answer missing"); + assert_eq!(answer.answers, Vec::::new()); + } + #[test] fn notes_are_captured_for_selected_option() { let (tx, mut rx) = test_sender(); @@ -802,7 +1593,7 @@ mod tests { { let answer = overlay.current_answer_mut().expect("answer missing"); - answer.option_state.selected_idx = Some(1); + answer.options_ui_state.selected_idx = Some(1); } overlay.select_current_option(); overlay @@ -826,6 +1617,37 @@ mod tests { ); } + #[test] + fn notes_submission_commits_selected_option() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Pick one"), + question_with_options("q2", "Pick two"), + ], + ), + tx, + true, + false, + false, + ); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Down)); + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + overlay + .composer + .set_text_content("Notes".to_string(), Vec::new(), Vec::new()); + overlay.composer.move_cursor_to_end(); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + assert_eq!(overlay.current_index(), 1); + let answer = overlay.answers.first().expect("answer missing"); + assert_eq!(answer.committed_option_idx, Some(1)); + } + #[test] fn large_paste_is_preserved_when_switching_questions() { let (tx, _rx) = test_sender(); @@ -860,13 +1682,37 @@ mod tests { false, false, ); - let area = Rect::new(0, 0, 64, 16); + let area = Rect::new(0, 0, 120, 16); insta::assert_snapshot!( "request_user_input_options", render_snapshot(&overlay, area) ); } + #[test] + fn request_user_input_options_notes_visible_snapshot() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Area")]), + tx, + true, + false, + false, + ); + { + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + answer.committed_option_idx = Some(0); + } + overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); + + let area = Rect::new(0, 0, 120, 16); + insta::assert_snapshot!( + "request_user_input_options_notes_visible", + render_snapshot(&overlay, area) + ); + } + #[test] fn request_user_input_tight_height_snapshot() { let (tx, _rx) = test_sender(); @@ -877,7 +1723,7 @@ mod tests { false, false, ); - let area = Rect::new(0, 0, 60, 8); + let area = Rect::new(0, 0, 120, 10); insta::assert_snapshot!( "request_user_input_tight_height", render_snapshot(&overlay, area) @@ -901,17 +1747,20 @@ mod tests { let width = 48u16; let question_height = overlay.wrapped_question_lines(width).len() as u16; let options_height = overlay.options_required_height(width); - let height = 1u16 - .saturating_add(question_height) + let extras = 1u16 // header + .saturating_add(1) // progress + .saturating_add(DESIRED_SPACERS_WHEN_NOTES_HIDDEN) + .saturating_add(overlay.footer_required_height(width)); + let height = question_height .saturating_add(options_height) - .saturating_add(4); + .saturating_add(extras); let sections = overlay.layout_sections(Rect::new(0, 0, width, height)); assert_eq!(sections.options_area.height, options_height); } #[test] - fn request_user_input_wrapped_options_snapshot() { + fn desired_height_keeps_spacers_and_preferred_options_visible() { let (tx, _rx) = test_sender(); let overlay = RequestUserInputOverlay::new( request_event( @@ -924,13 +1773,86 @@ mod tests { false, ); - let width = 52u16; + let width = 110u16; + let height = overlay.desired_height(width); + let content_area = menu_surface_inset(Rect::new(0, 0, width, height)); + let sections = overlay.layout_sections(content_area); + let preferred = overlay.options_preferred_height(content_area.width); + + assert_eq!(sections.options_area.height, preferred); + let question_bottom = sections.question_area.y + sections.question_area.height; + let options_bottom = sections.options_area.y + sections.options_area.height; + let spacer_after_question = sections.options_area.y.saturating_sub(question_bottom); + let spacer_after_options = sections.notes_title_area.y.saturating_sub(options_bottom); + assert_eq!(spacer_after_question, 1); + assert_eq!(spacer_after_options, 1); + } + + #[test] + fn footer_wraps_tips_without_splitting_individual_tips() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Pick one"), + question_with_options("q2", "Pick two"), + ], + ), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + answer.committed_option_idx = Some(0); + + let width = 36u16; + let lines = overlay.footer_tip_lines(width); + assert!(lines.len() > 1); + let separator_width = UnicodeWidthStr::width(TIP_SEPARATOR); + for tips in lines { + let used = tips.iter().enumerate().fold(0usize, |acc, (idx, tip)| { + let tip_width = UnicodeWidthStr::width(tip.text.as_str()).min(width as usize); + let extra = if idx == 0 { + tip_width + } else { + separator_width.saturating_add(tip_width) + }; + acc.saturating_add(extra) + }); + assert!(used <= width as usize); + } + } + + #[test] + fn request_user_input_wrapped_options_snapshot() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![question_with_wrapped_options("q1", "Next Step")], + ), + tx, + true, + false, + false, + ); + + { + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(0); + answer.committed_option_idx = Some(0); + } + + let width = 110u16; let question_height = overlay.wrapped_question_lines(width).len() as u16; let options_height = overlay.options_required_height(width); let height = 1u16 .saturating_add(question_height) .saturating_add(options_height) - .saturating_add(4); + .saturating_add(8); let area = Rect::new(0, 0, width, height); insta::assert_snapshot!( "request_user_input_wrapped_options", @@ -938,6 +1860,35 @@ mod tests { ); } + #[test] + fn request_user_input_footer_wrap_snapshot() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Pick one"), + question_with_options("q2", "Pick two"), + ], + ), + tx, + true, + false, + false, + ); + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_ui_state.selected_idx = Some(1); + answer.committed_option_idx = Some(1); + + let width = 52u16; + let height = overlay.desired_height(width); + let area = Rect::new(0, 0, width, height); + insta::assert_snapshot!( + "request_user_input_footer_wrap", + render_snapshot(&overlay, area) + ); + } + #[test] fn request_user_input_scroll_options_snapshot() { let (tx, _rx) = test_sender(); @@ -980,10 +1931,10 @@ mod tests { ); { let answer = overlay.current_answer_mut().expect("answer missing"); - answer.option_state.selected_idx = Some(3); - answer.selected = Some(3); + answer.options_ui_state.selected_idx = Some(3); + answer.committed_option_idx = Some(3); } - let area = Rect::new(0, 0, 68, 10); + let area = Rect::new(0, 0, 120, 12); insta::assert_snapshot!( "request_user_input_scrolling_options", render_snapshot(&overlay, area) @@ -1000,13 +1951,60 @@ mod tests { false, false, ); - let area = Rect::new(0, 0, 64, 10); + let area = Rect::new(0, 0, 120, 10); insta::assert_snapshot!( "request_user_input_freeform", render_snapshot(&overlay, area) ); } + #[test] + fn request_user_input_multi_question_first_snapshot() { + let (tx, _rx) = test_sender(); + let overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Area"), + question_without_options("q2", "Goal"), + ], + ), + tx, + true, + false, + false, + ); + let area = Rect::new(0, 0, 120, 15); + insta::assert_snapshot!( + "request_user_input_multi_question_first", + render_snapshot(&overlay, area) + ); + } + + #[test] + fn request_user_input_multi_question_last_snapshot() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Area"), + question_without_options("q2", "Goal"), + ], + ), + tx, + true, + false, + false, + ); + overlay.move_question(true); + let area = Rect::new(0, 0, 120, 12); + insta::assert_snapshot!( + "request_user_input_multi_question_last", + render_snapshot(&overlay, area) + ); + } + #[test] fn options_scroll_while_editing_notes() { let (tx, _rx) = test_sender(); @@ -1017,6 +2015,7 @@ mod tests { false, false, ); + overlay.select_current_option(); overlay.focus = Focus::Notes; overlay .composer @@ -1026,6 +2025,7 @@ mod tests { overlay.handle_key_event(KeyEvent::from(KeyCode::Down)); let answer = overlay.current_answer().expect("answer missing"); - assert_eq!(answer.selected, Some(1)); + assert_eq!(answer.committed_option_idx, Some(0)); + assert_eq!(answer.options_ui_state.selected_idx, Some(1)); } } diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/render.rs b/codex-rs/tui/src/bottom_pane/request_user_input/render.rs index b64f704340..0ab53fb841 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/render.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/render.rs @@ -1,41 +1,58 @@ -use crossterm::event::KeyCode; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::style::Stylize; use ratatui::text::Line; +use ratatui::text::Span; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; +use unicode_width::UnicodeWidthChar; +use unicode_width::UnicodeWidthStr; use crate::bottom_pane::selection_popup_common::menu_surface_inset; use crate::bottom_pane::selection_popup_common::menu_surface_padding_height; use crate::bottom_pane::selection_popup_common::render_menu_surface; use crate::bottom_pane::selection_popup_common::render_rows; -use crate::key_hint; use crate::render::renderable::Renderable; +use super::DESIRED_SPACERS_WHEN_NOTES_HIDDEN; use super::RequestUserInputOverlay; +use super::TIP_SEPARATOR; impl Renderable for RequestUserInputOverlay { fn desired_height(&self, width: u16) -> u16 { let outer = Rect::new(0, 0, width, u16::MAX); let inner = menu_surface_inset(outer); let inner_width = inner.width.max(1); + let has_options = self.has_options(); let question_height = self.wrapped_question_lines(inner_width).len(); - let options_height = self.options_required_height(inner_width) as usize; - let notes_height = self.notes_input_height(inner_width) as usize; - let footer_height = if self.unanswered_count() > 0 { 2 } else { 1 }; + let options_height = if has_options { + self.options_preferred_height(inner_width) as usize + } else { + 0 + }; + let notes_visible = !has_options || self.notes_ui_visible(); + let notes_height = if notes_visible { + self.notes_input_height(inner_width) as usize + } else { + 0 + }; + let spacer_rows = if has_options && !notes_visible { + DESIRED_SPACERS_WHEN_NOTES_HIDDEN as usize + } else { + 0 + }; + let footer_height = self.footer_required_height(inner_width) as usize; // Tight minimum height: progress + header + question + (optional) titles/options // + notes composer + footer + menu padding. let mut height = question_height .saturating_add(options_height) + .saturating_add(spacer_rows) .saturating_add(notes_height) .saturating_add(footer_height) .saturating_add(2); // progress + header - if self.has_options() { - height = height - .saturating_add(1) // answer title - .saturating_add(1); // notes title + if has_options && notes_visible { + height = height.saturating_add(1); // notes title } height = height.saturating_add(menu_surface_padding_height() as usize); height.max(8) as u16 @@ -63,12 +80,19 @@ impl RequestUserInputOverlay { return; } let sections = self.layout_sections(content_area); + let notes_visible = self.notes_ui_visible(); + let unanswered = self.unanswered_count(); // Progress header keeps the user oriented across multiple questions. let progress_line = if self.question_count() > 0 { let idx = self.current_index() + 1; let total = self.question_count(); - Line::from(format!("Question {idx}/{total}").dim()) + let base = format!("Question {idx}/{total}"); + if unanswered > 0 { + Line::from(format!("{base} ({unanswered} unanswered)").dim()) + } else { + Line::from(base.dim()) + } } else { Line::from("No questions".dim()) }; @@ -76,8 +100,13 @@ impl RequestUserInputOverlay { // Question title and wrapped prompt text. let question_header = self.current_question().map(|q| q.header.clone()); + let answered = self.current_question_answered(); let header_line = if let Some(header) = question_header { - Line::from(header.bold()) + if answered { + Line::from(header.bold()) + } else { + Line::from(header.cyan().bold()) + } } else { Line::from("No questions".dim()) }; @@ -101,54 +130,45 @@ impl RequestUserInputOverlay { ); } - if sections.answer_title_area.height > 0 { - let answer_label = "Answer"; - let answer_title = if self.focus_is_options() || self.focus_is_notes_without_options() { - answer_label.cyan().bold() - } else { - answer_label.dim() - }; - Paragraph::new(Line::from(answer_title)).render(sections.answer_title_area, buf); - } - // Build rows with selection markers for the shared selection renderer. let option_rows = self.option_rows(); if self.has_options() { - let mut option_state = self + let mut options_ui_state = self .current_answer() - .map(|answer| answer.option_state) + .map(|answer| answer.options_ui_state) .unwrap_or_default(); if sections.options_area.height > 0 { // Ensure the selected option is visible in the scroll window. - option_state + options_ui_state .ensure_visible(option_rows.len(), sections.options_area.height as usize); render_rows( sections.options_area, buf, &option_rows, - &option_state, + &options_ui_state, option_rows.len().max(1), "No options", ); } } - if sections.notes_title_area.height > 0 { + if notes_visible && sections.notes_title_area.height > 0 { let notes_label = if self.has_options() && self .current_answer() - .is_some_and(|answer| answer.selected.is_some()) + .is_some_and(|answer| answer.committed_option_idx.is_some()) { if let Some(label) = self.current_option_label() { - format!("Notes for {label} (optional)") + format!("Notes for {label}") } else { - "Notes (optional)".to_string() + "Notes".to_string() } } else { - "Notes (optional)".to_string() + "Notes".to_string() }; - let notes_title = if self.focus_is_notes() { + let notes_active = self.focus_is_notes(); + let notes_title = if notes_active { notes_label.as_str().cyan().bold() } else { notes_label.as_str().dim() @@ -156,7 +176,7 @@ impl RequestUserInputOverlay { Paragraph::new(Line::from(notes_title)).render(sections.notes_title_area, buf); } - if sections.notes_area.height > 0 { + if notes_visible && sections.notes_area.height > 0 { self.render_notes_input(sections.notes_area, buf); } @@ -164,69 +184,55 @@ impl RequestUserInputOverlay { .notes_area .y .saturating_add(sections.notes_area.height); - if sections.footer_lines == 2 { - // Status line for unanswered count when any question is empty. - let warning = format!( - "Unanswered: {} | Will submit as skipped", - self.unanswered_count() - ); - Paragraph::new(Line::from(warning.dim())).render( - Rect { - x: content_area.x, - y: footer_y, - width: content_area.width, - height: 1, - }, - buf, - ); + let footer_area = Rect { + x: content_area.x, + y: footer_y, + width: content_area.width, + height: sections.footer_lines, + }; + if footer_area.height == 0 { + return; } - let hint_y = footer_y.saturating_add(sections.footer_lines.saturating_sub(1)); - // Footer hints (selection index + navigation keys). - let mut hint_spans = Vec::new(); - if self.has_options() { - let options_len = self.options_len(); - let option_index = self.selected_option_index().map_or(0, |idx| idx + 1); - hint_spans.extend(vec![ - format!("Option {option_index} of {options_len}").into(), - " | ".into(), - ]); - } - hint_spans.extend(vec![ - key_hint::plain(KeyCode::Up).into(), - "/".into(), - key_hint::plain(KeyCode::Down).into(), - " scroll | ".into(), - key_hint::plain(KeyCode::Enter).into(), - " next question | ".into(), - ]); - if self.question_count() > 1 { - hint_spans.extend(vec![ - key_hint::plain(KeyCode::PageUp).into(), - " prev | ".into(), - key_hint::plain(KeyCode::PageDown).into(), - " next | ".into(), - ]); - } - hint_spans.extend(vec![ - key_hint::plain(KeyCode::Esc).into(), - " interrupt".into(), - ]); - Paragraph::new(Line::from(hint_spans).dim()).render( - Rect { - x: content_area.x, - y: hint_y, - width: content_area.width, + let tip_lines = self.footer_tip_lines(footer_area.width); + for (row_idx, tips) in tip_lines + .into_iter() + .take(footer_area.height as usize) + .enumerate() + { + let mut spans = Vec::new(); + for (tip_idx, tip) in tips.into_iter().enumerate() { + if tip_idx > 0 { + spans.push(TIP_SEPARATOR.into()); + } + if tip.highlight { + spans.push(tip.text.cyan().bold().not_dim()); + } else { + spans.push(tip.text.into()); + } + } + let line = Line::from(spans).dim(); + let line = truncate_line_word_boundary_with_ellipsis(line, footer_area.width as usize); + let row_area = Rect { + x: footer_area.x, + y: footer_area.y.saturating_add(row_idx as u16), + width: footer_area.width, height: 1, - }, - buf, - ); + }; + Paragraph::new(line).render(row_area, buf); + } } /// Return the cursor position when editing notes, if visible. pub(super) fn cursor_pos_impl(&self, area: Rect) -> Option<(u16, u16)> { + let has_options = self.has_options(); + let notes_visible = self.notes_ui_visible(); + if !self.focus_is_notes() { return None; } + if has_options && !notes_visible { + return None; + } let content_area = menu_surface_inset(area); if content_area.width == 0 || content_area.height == 0 { return None; @@ -246,16 +252,118 @@ impl RequestUserInputOverlay { } self.composer.render(area, buf); } - - fn focus_is_options(&self) -> bool { - matches!(self.focus, super::Focus::Options) - } - - fn focus_is_notes(&self) -> bool { - matches!(self.focus, super::Focus::Notes) - } - - fn focus_is_notes_without_options(&self) -> bool { - !self.has_options() && self.focus_is_notes() - } +} + +fn line_width(line: &Line<'_>) -> usize { + line.iter() + .map(|span| UnicodeWidthStr::width(span.content.as_ref())) + .sum() +} + +/// Truncate a styled line to `max_width`, preferring a word boundary, and append an ellipsis. +/// +/// This walks spans character-by-character, tracking the last width-safe position and the last +/// whitespace boundary within the available width (excluding the ellipsis width). If the line +/// overflows, it truncates at the last word boundary when possible (falling back to the last +/// fitting character), trims trailing whitespace, then appends an ellipsis styled to match the +/// last visible span (or the line style if nothing was kept). +fn truncate_line_word_boundary_with_ellipsis( + line: Line<'static>, + max_width: usize, +) -> Line<'static> { + if max_width == 0 { + return Line::from(Vec::>::new()); + } + + if line_width(&line) <= max_width { + return line; + } + + let ellipsis = "…"; + let ellipsis_width = UnicodeWidthStr::width(ellipsis); + if ellipsis_width >= max_width { + return Line::from(ellipsis); + } + let limit = max_width.saturating_sub(ellipsis_width); + + #[derive(Clone, Copy)] + struct BreakPoint { + span_idx: usize, + byte_end: usize, + } + + // Track display width as we scan, along with the best "cut here" positions. + let mut used = 0usize; + let mut last_fit: Option = None; + let mut last_word_break: Option = None; + let mut overflowed = false; + + 'outer: for (span_idx, span) in line.spans.iter().enumerate() { + let text = span.content.as_ref(); + for (byte_idx, ch) in text.char_indices() { + let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0); + if used.saturating_add(ch_width) > limit { + overflowed = true; + break 'outer; + } + used = used.saturating_add(ch_width); + let bp = BreakPoint { + span_idx, + byte_end: byte_idx + ch.len_utf8(), + }; + last_fit = Some(bp); + if ch.is_whitespace() { + last_word_break = Some(bp); + } + } + } + + // If we never overflowed, the original line already fits. + if !overflowed { + return line; + } + + // Prefer breaking on whitespace; otherwise fall back to the last fitting character. + let chosen_break = last_word_break.or(last_fit); + let Some(chosen_break) = chosen_break else { + return Line::from(ellipsis); + }; + + let line_style = line.style; + let mut spans_out: Vec> = Vec::new(); + for (idx, span) in line.spans.into_iter().enumerate() { + if idx < chosen_break.span_idx { + spans_out.push(span); + continue; + } + if idx == chosen_break.span_idx { + let text = span.content.into_owned(); + let truncated = text[..chosen_break.byte_end].to_string(); + if !truncated.is_empty() { + spans_out.push(Span::styled(truncated, span.style)); + } + } + break; + } + + while let Some(last) = spans_out.last_mut() { + let trimmed = last + .content + .trim_end_matches(char::is_whitespace) + .to_string(); + if trimmed.is_empty() { + spans_out.pop(); + } else { + last.content = trimmed.into(); + break; + } + } + + let ellipsis_style = spans_out + .last() + .map(|span| span.style) + .unwrap_or(line_style); + spans_out.push(Span::styled(ellipsis, ellipsis_style)); + + Line::from(spans_out).style(line_style) } diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap new file mode 100644 index 0000000000..02f91a7b47 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap @@ -0,0 +1,16 @@ +--- +source: tui/src/bottom_pane/request_user_input/mod.rs +expression: "render_snapshot(&overlay, area)" +--- + + Question 1/2 (1 unanswered) + Pick one + Choose an option. + + ( ) Option 1 First choice. + (x) Option 2 Second choice. + ( ) Option 3 Third choice. + + Option 2 of 3 | ↑/↓ scroll | Tab: add notes + Enter: submit answer | Ctrl+n next + Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap index dd5ced6fca..3e947c015b 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap @@ -2,12 +2,12 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - - Question 1/1 - Goal - Share details. - - › Type your answer (optional) - - Unanswered: 1 | Will submit as skipped - ↑/↓ scroll | enter next question | esc interrupt + + Question 1/1 (1 unanswered) + Goal + Share details. + + › Type your answer (optional) + + + Enter: submit answer | Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap new file mode 100644 index 0000000000..cdae6785d9 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap @@ -0,0 +1,14 @@ +--- +source: tui/src/bottom_pane/request_user_input/mod.rs +expression: "render_snapshot(&overlay, area)" +--- + + Question 1/2 (2 unanswered) + Area + Choose an option. + + ( ) Option 1 First choice. + ( ) Option 2 Second choice. + ( ) Option 3 Third choice. + + Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Ctrl+n next | Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap new file mode 100644 index 0000000000..d007b6b43c --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap @@ -0,0 +1,15 @@ +--- +source: tui/src/bottom_pane/request_user_input/mod.rs +expression: "render_snapshot(&overlay, area)" +--- + + Question 2/2 (2 unanswered) + Goal + Share details. + + › Type your answer (optional) + + + + + Enter: submit all answers | Ctrl+n next | Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap index 37ed036478..67eb6dc712 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap @@ -2,18 +2,13 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - - Question 1/1 - Area - Choose an option. - Answer - (x) Option 1 First choice. - ( ) Option 2 Second choice. - ( ) Option 3 Third choice. - Notes for Option 1 (optional) - - › Add notes (optional) - - - - Option 1 of 3 | ↑/↓ scroll | enter next question | esc inter + + Question 1/1 (1 unanswered) + Area + Choose an option. + + ( ) Option 1 First choice. + ( ) Option 2 Second choice. + ( ) Option 3 Third choice. + + Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap new file mode 100644 index 0000000000..24799ed636 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap @@ -0,0 +1,19 @@ +--- +source: tui/src/bottom_pane/request_user_input/mod.rs +expression: "render_snapshot(&overlay, area)" +--- + + Question 1/1 + Area + Choose an option. + (x) Option 1 First choice. + ( ) Option 2 Second choice. + ( ) Option 3 Third choice. + Notes for Option 1 + + › Add notes + + + + + Option 1 of 3 | ↑/↓ scroll | Tab: clear notes | Enter: submit answer | Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap index ace8eb4537..95813336b2 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap @@ -2,13 +2,14 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - - Next Step - What would you like to do next? - ( ) Discuss a code change (Recommended) Walk through a plan and - edit code together. - ( ) Run tests Pick a crate and run - its tests. - ( ) Review a diff Summarize or review - current changes. - Option 4 of 5 | ↑/↓ scroll | enter next question | esc interrupt + + Question 1/1 + Next Step + What would you like to do next? + + ( ) Discuss a code change (Recommended) Walk through a plan and edit code together. + ( ) Run tests Pick a crate and run its tests. + ( ) Review a diff Summarize or review current changes. + (x) Refactor Tighten structure and remove dead code. + + Option 4 of 5 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap index e8cd2bd22e..a963370be9 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap @@ -2,11 +2,12 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - - Area - Choose an option. - (x) Option 1 First choice. - ( ) Option 2 Second choice. - ( ) Option 3 Third choice. - - Option 1 of 3 | ↑/↓ scroll | enter next question | esc i + + Question 1/1 (1 unanswered) + Area + Choose an option. + + ( ) Option 1 First choice. + ( ) Option 2 Second choice. + + Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap index 4ae9dd048f..0d1e727422 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap @@ -2,20 +2,13 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - - Next Step - Choose the next step for this task. - (x) Discuss a code change Walk through a plan, - then implement it - together with careful - checks. - ( ) Run targeted tests Pick the most - relevant crate and - validate the current - behavior first. - ( ) Review the diff Summarize the changes - and highlight the - most important risks - and gaps. - - Option 1 of 3 | ↑/↓ scroll | enter next question + + Question 1/1 + Next Step + Choose the next step for this task. + + (x) Discuss a code change Walk through a plan, then implement it together with careful checks. + ( ) Run targeted tests Pick the most relevant crate and validate the current behavior first. + ( ) Review the diff Summarize the changes and highlight the most important risks and gaps. + + Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt From 3f3916e5950bdb2c3096cc681dd8d672c9023086 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?SlKz=E1=B5=8D=E1=B5=90?= <105301169+slkzgm@users.noreply.github.com> Date: Wed, 28 Jan 2026 02:10:16 +0100 Subject: [PATCH 022/116] tui: stabilize shortcut overlay snapshots on WSL (#9359) Fixes #9361 ## Context Split out from #9059 per review: https://github.com/openai/codex/pull/9059#issuecomment-3757859033 ## Summary The shortcut overlay renders different paste-image bindings on WSL (Ctrl+Alt+V) vs non-WSL (Ctrl+V), which makes snapshot tests non-deterministic when run under WSL. ## Changes - Gate WSL detection behind `cfg(not(test))` so snapshot tests are deterministic across environments. - Add a focused unit test that still asserts the WSL-specific paste-image binding. ## Testing - `just fmt` - `just fix -p codex-tui` - `just fix -p codex-tui2` - `cargo test -p codex-tui` - `cargo test -p codex-tui2` --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 15 ++++- codex-rs/tui/src/bottom_pane/footer.rs | 61 ++++++++++++++++--- 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index d101e042e3..af45054792 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -2257,14 +2257,27 @@ impl ChatComposer { } fn footer_props(&self) -> FooterProps { + let mode = self.footer_mode(); + let is_wsl = { + #[cfg(target_os = "linux")] + { + mode == FooterMode::ShortcutOverlay && crate::clipboard_paste::is_probably_wsl() + } + #[cfg(not(target_os = "linux"))] + { + false + } + }; + FooterProps { - mode: self.footer_mode(), + mode, esc_backtrack_hint: self.esc_backtrack_hint, use_shift_enter_hint: self.use_shift_enter_hint, is_task_running: self.is_task_running, quit_shortcut_key: self.quit_shortcut_key, steer_enabled: self.steer_enabled, collaboration_modes_enabled: self.collaboration_modes_enabled, + is_wsl, context_window_percent: self.context_window_percent, context_window_used_tokens: self.context_window_used_tokens, } diff --git a/codex-rs/tui/src/bottom_pane/footer.rs b/codex-rs/tui/src/bottom_pane/footer.rs index 69c5e7bb00..1ded8ce319 100644 --- a/codex-rs/tui/src/bottom_pane/footer.rs +++ b/codex-rs/tui/src/bottom_pane/footer.rs @@ -32,8 +32,6 @@ //! In short: `single_line_footer_layout` chooses *what* best fits, and the two //! render helpers choose whether to draw the chosen line or the default //! `FooterProps` mapping. -#[cfg(target_os = "linux")] -use crate::clipboard_paste::is_probably_wsl; use crate::key_hint; use crate::key_hint::KeyBinding; use crate::render::line_utils::prefix_lines; @@ -63,6 +61,7 @@ pub(crate) struct FooterProps { pub(crate) is_task_running: bool, pub(crate) steer_enabled: bool, pub(crate) collaboration_modes_enabled: bool, + pub(crate) is_wsl: bool, /// Which key the user must press again to quit. /// /// This is rendered when `mode` is `FooterMode::QuitShortcutReminder`. @@ -554,15 +553,10 @@ fn footer_from_props_lines( vec![left_side_line(collaboration_mode_indicator, state)] } FooterMode::ShortcutOverlay => { - #[cfg(target_os = "linux")] - let is_wsl = is_probably_wsl(); - #[cfg(not(target_os = "linux"))] - let is_wsl = false; - let state = ShortcutsState { use_shift_enter_hint: props.use_shift_enter_hint, esc_backtrack_hint: props.esc_backtrack_hint, - is_wsl, + is_wsl: props.is_wsl, collaboration_modes_enabled: props.collaboration_modes_enabled, }; shortcut_overlay_lines(state) @@ -961,6 +955,7 @@ const SHORTCUTS: &[ShortcutDescriptor] = &[ mod tests { use super::*; use insta::assert_snapshot; + use pretty_assertions::assert_eq; use ratatui::Terminal; use ratatui::backend::TestBackend; @@ -1077,6 +1072,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1092,6 +1088,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1107,6 +1104,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: true, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1122,6 +1120,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1137,6 +1136,7 @@ mod tests { is_task_running: true, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1152,6 +1152,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1167,6 +1168,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1182,6 +1184,7 @@ mod tests { is_task_running: true, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: Some(72), context_window_used_tokens: None, @@ -1197,6 +1200,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: Some(123_456), @@ -1212,6 +1216,7 @@ mod tests { is_task_running: true, steer_enabled: false, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1227,6 +1232,7 @@ mod tests { is_task_running: true, steer_enabled: true, collaboration_modes_enabled: false, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1240,6 +1246,7 @@ mod tests { is_task_running: false, steer_enabled: false, collaboration_modes_enabled: true, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1266,6 +1273,7 @@ mod tests { is_task_running: true, steer_enabled: false, collaboration_modes_enabled: true, + is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), context_window_percent: None, context_window_used_tokens: None, @@ -1278,4 +1286,41 @@ mod tests { Some(CollaborationModeIndicator::Plan), ); } + + #[test] + fn paste_image_shortcut_prefers_ctrl_alt_v_under_wsl() { + let descriptor = SHORTCUTS + .iter() + .find(|descriptor| descriptor.id == ShortcutId::PasteImage) + .expect("paste image shortcut"); + + let is_wsl = { + #[cfg(target_os = "linux")] + { + crate::clipboard_paste::is_probably_wsl() + } + #[cfg(not(target_os = "linux"))] + { + false + } + }; + + let expected_key = if is_wsl { + key_hint::ctrl_alt(KeyCode::Char('v')) + } else { + key_hint::ctrl(KeyCode::Char('v')) + }; + + let actual_key = descriptor + .binding_for(ShortcutsState { + use_shift_enter_hint: false, + esc_backtrack_hint: false, + is_wsl, + collaboration_modes_enabled: false, + }) + .expect("shortcut binding") + .key; + + assert_eq!(actual_key, expected_key); + } } From a90ab789c2ea1d4177141d8aef454655accf57b3 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Tue, 27 Jan 2026 18:09:29 -0800 Subject: [PATCH 023/116] fix: enable per-turn updates to web search mode (#10040) web_search can now be updated per-turn, for things like changes to sandbox policy. `SandboxPolicy::DangerFullAccess` now sets web_search to `live`, and the default is still `cached`. Added integration tests. --- codex-rs/core/src/client.rs | 12 ++- codex-rs/core/src/codex.rs | 9 +- codex-rs/core/src/config/mod.rs | 100 ++++++++---------- codex-rs/core/src/tasks/review.rs | 2 +- codex-rs/core/src/tools/spec.rs | 64 +++++------ codex-rs/core/tests/responses_headers.rs | 2 +- codex-rs/core/tests/suite/model_tools.rs | 2 +- codex-rs/core/tests/suite/prompt_caching.rs | 2 +- .../core/tests/suite/web_search_cached.rs | 96 ++++++++++++++++- 9 files changed, 187 insertions(+), 102 deletions(-) diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 6392b3e70c..f415c3604a 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -655,11 +655,13 @@ fn build_responses_headers( let mut headers = experimental_feature_headers(config); headers.insert( WEB_SEARCH_ELIGIBLE_HEADER, - HeaderValue::from_static(if config.web_search_mode == WebSearchMode::Disabled { - "false" - } else { - "true" - }), + HeaderValue::from_static( + if matches!(config.web_search_mode, Some(WebSearchMode::Disabled)) { + "false" + } else { + "true" + }, + ), ); if let Some(turn_state) = turn_state && let Some(state) = turn_state.get() diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 4dcc5d4455..c2c25967d2 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -100,6 +100,7 @@ use crate::config::Config; use crate::config::Constrained; use crate::config::ConstraintResult; use crate::config::GhostSnapshotConfig; +use crate::config::resolve_web_search_mode_for_turn; use crate::config::types::McpServerConfig; use crate::config::types::ShellEnvironmentPolicy; use crate::context_manager::ContextManager; @@ -581,6 +582,10 @@ impl Session { session_configuration.collaboration_mode.reasoning_effort(); per_turn_config.model_reasoning_summary = session_configuration.model_reasoning_summary; per_turn_config.model_personality = session_configuration.personality; + per_turn_config.web_search_mode = Some(resolve_web_search_mode_for_turn( + per_turn_config.web_search_mode, + session_configuration.sandbox_policy.get(), + )); per_turn_config.features = config.features.clone(); per_turn_config } @@ -2888,7 +2893,7 @@ async fn spawn_review_thread( let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &review_model_info, features: &review_features, - web_search_mode: review_web_search_mode, + web_search_mode: Some(review_web_search_mode), }); let review_prompt = resolved.prompt.clone(); @@ -2900,7 +2905,7 @@ async fn spawn_review_thread( let mut per_turn_config = (*config).clone(); per_turn_config.model = Some(model.clone()); per_turn_config.features = review_features.clone(); - per_turn_config.web_search_mode = review_web_search_mode; + per_turn_config.web_search_mode = Some(review_web_search_mode); let otel_manager = parent_turn_context .client diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 4e49efabda..5d84d577eb 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -306,8 +306,8 @@ pub struct Config { /// model info's default preference. pub include_apply_patch_tool: bool, - /// Explicit or feature-derived web search mode. Defaults to cached. - pub web_search_mode: WebSearchMode, + /// Explicit or feature-derived web search mode. + pub web_search_mode: Option, /// If set to `true`, used only the experimental unified exec tool. pub use_experimental_unified_exec_tool: bool, @@ -1203,27 +1203,36 @@ pub fn resolve_oss_provider( } } -/// Resolve the web search mode from explicit config, feature flags, and sandbox policy. -/// Live search is auto-enabled when sandbox policy is `DangerFullAccess` +/// Resolve the web search mode from explicit config and feature flags. fn resolve_web_search_mode( config_toml: &ConfigToml, config_profile: &ConfigProfile, features: &Features, - sandbox_policy: &SandboxPolicy, -) -> WebSearchMode { +) -> Option { if let Some(mode) = config_profile.web_search.or(config_toml.web_search) { - return mode; + return Some(mode); } if features.enabled(Feature::WebSearchCached) { - return WebSearchMode::Cached; + return Some(WebSearchMode::Cached); } if features.enabled(Feature::WebSearchRequest) { - return WebSearchMode::Live; + return Some(WebSearchMode::Live); + } + None +} + +pub(crate) fn resolve_web_search_mode_for_turn( + explicit_mode: Option, + sandbox_policy: &SandboxPolicy, +) -> WebSearchMode { + if let Some(mode) = explicit_mode { + return mode; } if matches!(sandbox_policy, SandboxPolicy::DangerFullAccess) { - return WebSearchMode::Live; + WebSearchMode::Live + } else { + WebSearchMode::Cached } - WebSearchMode::Cached } impl Config { @@ -1347,8 +1356,7 @@ impl Config { AskForApproval::default() } }); - let web_search_mode = - resolve_web_search_mode(&cfg, &config_profile, &features, &sandbox_policy); + let web_search_mode = resolve_web_search_mode(&cfg, &config_profile, &features); // TODO(dylan): We should be able to leverage ConfigLayerStack so that // we can reliably check this at every config level. let did_user_set_custom_approval_policy_or_sandbox_mode = approval_policy_override @@ -2271,15 +2279,12 @@ trust_level = "trusted" } #[test] - fn web_search_mode_defaults_to_cached_if_unset() { + fn web_search_mode_defaults_to_none_if_unset() { let cfg = ConfigToml::default(); let profile = ConfigProfile::default(); let features = Features::with_defaults(); - assert_eq!( - resolve_web_search_mode(&cfg, &profile, &features, &SandboxPolicy::ReadOnly), - WebSearchMode::Cached - ); + assert_eq!(resolve_web_search_mode(&cfg, &profile, &features), None); } #[test] @@ -2293,8 +2298,8 @@ trust_level = "trusted" features.enable(Feature::WebSearchCached); assert_eq!( - resolve_web_search_mode(&cfg, &profile, &features, &SandboxPolicy::ReadOnly), - WebSearchMode::Live + resolve_web_search_mode(&cfg, &profile, &features), + Some(WebSearchMode::Live) ); } @@ -2309,48 +2314,33 @@ trust_level = "trusted" features.enable(Feature::WebSearchRequest); assert_eq!( - resolve_web_search_mode(&cfg, &profile, &features, &SandboxPolicy::ReadOnly), - WebSearchMode::Disabled + resolve_web_search_mode(&cfg, &profile, &features), + Some(WebSearchMode::Disabled) ); } #[test] - fn danger_full_access_defaults_web_search_live_when_unset() -> std::io::Result<()> { - let codex_home = TempDir::new()?; - let cfg = ConfigToml { - sandbox_mode: Some(SandboxMode::DangerFullAccess), - ..Default::default() - }; + fn web_search_mode_for_turn_defaults_to_cached_when_unset() { + let mode = resolve_web_search_mode_for_turn(None, &SandboxPolicy::ReadOnly); - let config = Config::load_from_base_config_with_overrides( - cfg, - ConfigOverrides::default(), - codex_home.path().to_path_buf(), - )?; - - assert_eq!(config.web_search_mode, WebSearchMode::Live); - - Ok(()) + assert_eq!(mode, WebSearchMode::Cached); } #[test] - fn explicit_web_search_mode_wins_in_danger_full_access() -> std::io::Result<()> { - let codex_home = TempDir::new()?; - let cfg = ConfigToml { - sandbox_mode: Some(SandboxMode::DangerFullAccess), - web_search: Some(WebSearchMode::Cached), - ..Default::default() - }; + fn web_search_mode_for_turn_defaults_to_live_for_danger_full_access() { + let mode = resolve_web_search_mode_for_turn(None, &SandboxPolicy::DangerFullAccess); - let config = Config::load_from_base_config_with_overrides( - cfg, - ConfigOverrides::default(), - codex_home.path().to_path_buf(), - )?; + assert_eq!(mode, WebSearchMode::Live); + } - assert_eq!(config.web_search_mode, WebSearchMode::Cached); + #[test] + fn web_search_mode_for_turn_prefers_explicit_value() { + let mode = resolve_web_search_mode_for_turn( + Some(WebSearchMode::Cached), + &SandboxPolicy::DangerFullAccess, + ); - Ok(()) + assert_eq!(mode, WebSearchMode::Cached); } #[test] @@ -3786,7 +3776,7 @@ model_verbosity = "high" forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, - web_search_mode: WebSearchMode::Cached, + web_search_mode: None, use_experimental_unified_exec_tool: false, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), @@ -3869,7 +3859,7 @@ model_verbosity = "high" forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, - web_search_mode: WebSearchMode::Cached, + web_search_mode: None, use_experimental_unified_exec_tool: false, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), @@ -3967,7 +3957,7 @@ model_verbosity = "high" forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, - web_search_mode: WebSearchMode::Cached, + web_search_mode: None, use_experimental_unified_exec_tool: false, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), @@ -4051,7 +4041,7 @@ model_verbosity = "high" forced_chatgpt_workspace_id: None, forced_login_method: None, include_apply_patch_tool: false, - web_search_mode: WebSearchMode::Cached, + web_search_mode: None, use_experimental_unified_exec_tool: false, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index 89dbaf90fe..d156d3e0d5 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -86,7 +86,7 @@ async fn start_review_conversation( let mut sub_agent_config = config.as_ref().clone(); // Carry over review-only feature restrictions so the delegate cannot // re-enable blocked tools (web search, view image). - sub_agent_config.web_search_mode = WebSearchMode::Disabled; + sub_agent_config.web_search_mode = Some(WebSearchMode::Disabled); // 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/spec.rs b/codex-rs/core/src/tools/spec.rs index d7fd1d0187..a128ceeaf6 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -27,7 +27,7 @@ use std::collections::HashMap; pub(crate) struct ToolsConfig { pub shell_type: ConfigShellToolType, pub apply_patch_tool_type: Option, - pub web_search_mode: WebSearchMode, + pub web_search_mode: Option, pub collab_tools: bool, pub collaboration_modes_tools: bool, pub experimental_supported_tools: Vec, @@ -36,7 +36,7 @@ pub(crate) struct ToolsConfig { pub(crate) struct ToolsConfigParams<'a> { pub(crate) model_info: &'a ModelInfo, pub(crate) features: &'a Features, - pub(crate) web_search_mode: WebSearchMode, + pub(crate) web_search_mode: Option, } impl ToolsConfig { @@ -1384,17 +1384,17 @@ pub(crate) fn build_specs( } match config.web_search_mode { - WebSearchMode::Cached => { + Some(WebSearchMode::Cached) => { builder.push_spec(ToolSpec::WebSearch { external_web_access: Some(false), }); } - WebSearchMode::Live => { + Some(WebSearchMode::Live) => { builder.push_spec(ToolSpec::WebSearch { external_web_access: Some(true), }); } - WebSearchMode::Disabled => {} + Some(WebSearchMode::Disabled) | None => {} } builder.push_spec_with_parallel_support(create_view_image_tool(), true); @@ -1556,7 +1556,7 @@ mod tests { let config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Live, + web_search_mode: Some(WebSearchMode::Live), }); let (tools, _) = build_specs(&config, None, &[]).build(); @@ -1620,7 +1620,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs(&tools_config, None, &[]).build(); assert_contains_tool_names( @@ -1638,7 +1638,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs(&tools_config, None, &[]).build(); assert!( @@ -1650,7 +1650,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs(&tools_config, None, &[]).build(); assert_contains_tool_names(&tools, &["request_user_input"]); @@ -1659,7 +1659,7 @@ mod tests { fn assert_model_tools( model_slug: &str, features: &Features, - web_search_mode: WebSearchMode, + web_search_mode: Option, expected_tools: &[&str], ) { let config = test_config(); @@ -1683,7 +1683,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs(&tools_config, None, &[]).build(); @@ -1705,7 +1705,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Live, + web_search_mode: Some(WebSearchMode::Live), }); let (tools, _) = build_specs(&tools_config, None, &[]).build(); @@ -1725,7 +1725,7 @@ mod tests { assert_model_tools( "gpt-5-codex", &features, - WebSearchMode::Cached, + Some(WebSearchMode::Cached), &[ "shell_command", "list_mcp_resources", @@ -1747,7 +1747,7 @@ mod tests { assert_model_tools( "gpt-5.1-codex", &features, - WebSearchMode::Cached, + Some(WebSearchMode::Cached), &[ "shell_command", "list_mcp_resources", @@ -1770,7 +1770,7 @@ mod tests { assert_model_tools( "gpt-5-codex", &features, - WebSearchMode::Live, + Some(WebSearchMode::Live), &[ "exec_command", "write_stdin", @@ -1794,7 +1794,7 @@ mod tests { assert_model_tools( "gpt-5.1-codex", &features, - WebSearchMode::Live, + Some(WebSearchMode::Live), &[ "exec_command", "write_stdin", @@ -1817,7 +1817,7 @@ mod tests { assert_model_tools( "codex-mini-latest", &features, - WebSearchMode::Cached, + Some(WebSearchMode::Cached), &[ "local_shell", "list_mcp_resources", @@ -1838,7 +1838,7 @@ mod tests { assert_model_tools( "gpt-5.1-codex-mini", &features, - WebSearchMode::Cached, + Some(WebSearchMode::Cached), &[ "shell_command", "list_mcp_resources", @@ -1860,7 +1860,7 @@ mod tests { assert_model_tools( "gpt-5", &features, - WebSearchMode::Cached, + Some(WebSearchMode::Cached), &[ "shell", "list_mcp_resources", @@ -1881,7 +1881,7 @@ mod tests { assert_model_tools( "gpt-5.1", &features, - WebSearchMode::Cached, + Some(WebSearchMode::Cached), &[ "shell_command", "list_mcp_resources", @@ -1903,7 +1903,7 @@ mod tests { assert_model_tools( "exp-5.1", &features, - WebSearchMode::Cached, + Some(WebSearchMode::Cached), &[ "exec_command", "write_stdin", @@ -1927,7 +1927,7 @@ mod tests { assert_model_tools( "codex-mini-latest", &features, - WebSearchMode::Live, + Some(WebSearchMode::Live), &[ "exec_command", "write_stdin", @@ -1951,7 +1951,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Live, + web_search_mode: Some(WebSearchMode::Live), }); let (tools, _) = build_specs(&tools_config, Some(HashMap::new()), &[]).build(); @@ -1973,7 +1973,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs(&tools_config, None, &[]).build(); @@ -1992,7 +1992,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs(&tools_config, None, &[]).build(); @@ -2023,7 +2023,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Live, + web_search_mode: Some(WebSearchMode::Live), }); let (tools, _) = build_specs( &tools_config, @@ -2119,7 +2119,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); // Intentionally construct a map with keys that would sort alphabetically. @@ -2196,7 +2196,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs( @@ -2254,7 +2254,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs( @@ -2309,7 +2309,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs( @@ -2366,7 +2366,7 @@ mod tests { let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs( @@ -2479,7 +2479,7 @@ Examples of valid command strings: let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, - web_search_mode: WebSearchMode::Cached, + web_search_mode: Some(WebSearchMode::Cached), }); let (tools, _) = build_specs( &tools_config, diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 9e268a2c50..22d9fa8b79 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -264,7 +264,7 @@ async fn responses_stream_includes_web_search_eligible_header_false_when_disable let test = test_codex() .with_config(|config| { - config.web_search_mode = WebSearchMode::Disabled; + config.web_search_mode = Some(WebSearchMode::Disabled); }) .build(&server) .await diff --git a/codex-rs/core/tests/suite/model_tools.rs b/codex-rs/core/tests/suite/model_tools.rs index 0c8277e915..b08b5281c8 100644 --- a/codex-rs/core/tests/suite/model_tools.rs +++ b/codex-rs/core/tests/suite/model_tools.rs @@ -38,7 +38,7 @@ async fn collect_tool_identifiers_for_model(model: &str) -> Vec { .with_model(model) // Keep tool expectations stable when the default web_search mode changes. .with_config(|config| { - config.web_search_mode = WebSearchMode::Cached; + config.web_search_mode = Some(WebSearchMode::Cached); config.features.enable(Feature::CollaborationModes); }); let test = builder diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 5831c62357..579a1856d4 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -92,7 +92,7 @@ async fn prompt_tools_are_consistent_across_requests() -> anyhow::Result<()> { config.user_instructions = Some("be consistent and helpful".to_string()); config.model = Some("gpt-5.1-codex-max".to_string()); // Keep tool expectations stable when the default web_search mode changes. - config.web_search_mode = WebSearchMode::Cached; + config.web_search_mode = Some(WebSearchMode::Cached); config.features.enable(Feature::CollaborationModes); }) .build(&server) diff --git a/codex-rs/core/tests/suite/web_search_cached.rs b/codex-rs/core/tests/suite/web_search_cached.rs index 261efaf942..df8b7dbb5b 100644 --- a/codex-rs/core/tests/suite/web_search_cached.rs +++ b/codex-rs/core/tests/suite/web_search_cached.rs @@ -1,6 +1,7 @@ #![allow(clippy::unwrap_used)] use codex_core::features::Feature; +use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::WebSearchMode; use core_test_support::load_sse_fixture_with_id; use core_test_support::responses; @@ -25,7 +26,7 @@ fn find_web_search_tool(body: &Value) -> &Value { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn web_search_mode_cached_sets_external_web_access_false_in_request_body() { +async fn web_search_mode_cached_sets_external_web_access_false() { skip_if_no_network!(); let server = start_mock_server().await; @@ -35,7 +36,7 @@ async fn web_search_mode_cached_sets_external_web_access_false_in_request_body() let mut builder = test_codex() .with_model("gpt-5-codex") .with_config(|config| { - config.web_search_mode = WebSearchMode::Cached; + config.web_search_mode = Some(WebSearchMode::Cached); }); let test = builder .build(&server) @@ -56,7 +57,7 @@ async fn web_search_mode_cached_sets_external_web_access_false_in_request_body() } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn web_search_mode_takes_precedence_over_legacy_flags_in_request_body() { +async fn web_search_mode_takes_precedence_over_legacy_flags() { skip_if_no_network!(); let server = start_mock_server().await; @@ -67,7 +68,7 @@ async fn web_search_mode_takes_precedence_over_legacy_flags_in_request_body() { .with_model("gpt-5-codex") .with_config(|config| { config.features.enable(Feature::WebSearchRequest); - config.web_search_mode = WebSearchMode::Cached; + config.web_search_mode = Some(WebSearchMode::Cached); }); let test = builder .build(&server) @@ -86,3 +87,90 @@ async fn web_search_mode_takes_precedence_over_legacy_flags_in_request_body() { "web_search mode should win over legacy web_search_request" ); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn web_search_mode_defaults_to_cached_when_unset() { + skip_if_no_network!(); + + let server = start_mock_server().await; + let sse = sse_completed("resp-1"); + let resp_mock = responses::mount_sse_once(&server, sse).await; + + let mut builder = test_codex() + .with_model("gpt-5-codex") + .with_config(|config| { + config.web_search_mode = None; + config.features.disable(Feature::WebSearchCached); + config.features.disable(Feature::WebSearchRequest); + }); + let test = builder + .build(&server) + .await + .expect("create test Codex conversation"); + + test.submit_turn_with_policy("hello default cached web search", SandboxPolicy::ReadOnly) + .await + .expect("submit turn"); + + let body = resp_mock.single_request().body_json(); + let tool = find_web_search_tool(&body); + assert_eq!( + tool.get("external_web_access").and_then(Value::as_bool), + Some(false), + "default web_search should be cached when unset" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn web_search_mode_updates_between_turns_with_sandbox_policy() { + skip_if_no_network!(); + + let server = start_mock_server().await; + let resp_mock = responses::mount_sse_sequence( + &server, + vec![sse_completed("resp-1"), sse_completed("resp-2")], + ) + .await; + + let mut builder = test_codex() + .with_model("gpt-5-codex") + .with_config(|config| { + config.web_search_mode = None; + config.features.disable(Feature::WebSearchCached); + config.features.disable(Feature::WebSearchRequest); + }); + let test = builder + .build(&server) + .await + .expect("create test Codex conversation"); + + test.submit_turn_with_policy("hello cached", SandboxPolicy::ReadOnly) + .await + .expect("submit first turn"); + test.submit_turn_with_policy("hello live", SandboxPolicy::DangerFullAccess) + .await + .expect("submit second turn"); + + let requests = resp_mock.requests(); + assert_eq!(requests.len(), 2, "expected two response requests"); + + let first_body = requests[0].body_json(); + let first_tool = find_web_search_tool(&first_body); + assert_eq!( + first_tool + .get("external_web_access") + .and_then(Value::as_bool), + Some(false), + "read-only policy should default web_search to cached" + ); + + let second_body = requests[1].body_json(); + let second_tool = find_web_search_tool(&second_body); + assert_eq!( + second_tool + .get("external_web_access") + .and_then(Value::as_bool), + Some(true), + "danger-full-access policy should default web_search to live" + ); +} From 1609f6aa815fe74942d7bd9410b5951894b53170 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Tue, 27 Jan 2026 18:24:24 -0800 Subject: [PATCH 024/116] fix: allow unknown fields on Notice in schema (#10041) the `notice` field didn't allow unknown fields in the schema, leading to issues where they shouldn't be. Now we allow unknown fields. image --- codex-rs/core/config.schema.json | 1 - codex-rs/core/src/config/types.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 6b48dcb4a9..1e164b24cb 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -441,7 +441,6 @@ "type": "object" }, "Notice": { - "additionalProperties": false, "description": "Settings for notices we display to users via the tui and app-server clients (primarily the Codex IDE extension). NOTE: these are different from notifications - notices are warnings, NUX screens, acknowledgements, etc.", "properties": { "hide_full_access_warning": { diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index 96379dfa03..a1d126c114 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -472,7 +472,6 @@ const fn default_true() -> bool { /// (primarily the Codex IDE extension). NOTE: these are different from /// notifications - notices are warnings, NUX screens, acknowledgements, etc. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] pub struct Notice { /// Tracks whether the user has acknowledged the full access warning prompt. pub hide_full_access_warning: Option, From add648df825563bca7611a005365858270c0041f Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Tue, 27 Jan 2026 18:39:59 -0800 Subject: [PATCH 025/116] Restore image attachments/text elements when recalling input history (Up/Down) (#9628) **Summary** - Up/Down input history now restores image attachments and text elements for local entries. - Composer history stores rich local entries (text + text elements + local image paths) while persistent history remains text-only. - Added tests to verify history recall rehydrates image placeholders and attachments in both `tui` and `tui2`. **Changes** - `tui/src/bottom_pane/chat_composer_history.rs`: store `HistoryEntry` (text + elements + image paths) for local history; adapt navigation + tests. - `tui2/src/bottom_pane/chat_composer_history.rs`: same as above. - `tui/src/bottom_pane/chat_composer.rs`: record rich history entries and restore them on Up/Down; update Ctrl+C history and tests. - `tui2/src/bottom_pane/chat_composer.rs`: same as above. --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 86 +++++++++++-- .../src/bottom_pane/chat_composer_history.rs | 114 +++++++++++++----- codex-rs/tui/src/chatwidget/tests.rs | 5 +- docs/tui-chat-composer.md | 13 ++ 4 files changed, 171 insertions(+), 47 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index af45054792..e59f820821 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -15,6 +15,16 @@ //! [`ChatComposer::handle_key_event_without_popup`]. After every handled key, we call //! [`ChatComposer::sync_popups`] so UI state follows the latest buffer/cursor. //! +//! # History Navigation (↑/↓) +//! +//! The Up/Down history path is managed by [`ChatComposerHistory`]. It merges: +//! +//! - Persistent cross-session history (text-only; no element ranges or attachments). +//! - Local in-session history (full text + text elements + local image paths). +//! +//! When recalling a local entry, the composer rehydrates text elements and image attachments. +//! When recalling a persistent entry, only the text is restored. +//! //! # Submission and Prompt Expansion //! //! On submit/queue paths, the composer: @@ -89,6 +99,7 @@ use ratatui::widgets::StatefulWidgetRef; use ratatui::widgets::WidgetRef; use super::chat_composer_history::ChatComposerHistory; +use super::chat_composer_history::HistoryEntry; use super::command_popup::CommandItem; use super::command_popup::CommandPopup; use super::command_popup::CommandPopupFlags; @@ -460,11 +471,12 @@ impl ChatComposer { offset: usize, entry: Option, ) -> bool { - let Some(text) = self.history.on_entry_response(log_id, offset, entry) else { + let Some(entry) = self.history.on_entry_response(log_id, offset, entry) else { return false; }; - // Composer history (↑/↓) stores plain text only; no UI element ranges/attachments to restore here. - self.set_text_content(text, Vec::new(), Vec::new()); + // Persistent ↑/↓ history is text-only (backwards-compatible and avoids persisting + // attachments), but local in-session ↑/↓ history can rehydrate elements and image paths. + self.set_text_content(entry.text, entry.text_elements, entry.local_image_paths); true } @@ -707,9 +719,19 @@ impl ChatComposer { return None; } let previous = self.current_text(); + let text_elements = self.textarea.text_elements(); + let local_image_paths = self + .attached_images + .iter() + .map(|img| img.path.clone()) + .collect(); self.set_text_content(String::new(), Vec::new(), Vec::new()); self.history.reset_navigation(); - self.history.record_local_submission(&previous); + self.history.record_local_submission(HistoryEntry { + text: previous.clone(), + text_elements, + local_image_paths, + }); Some(previous) } @@ -1792,8 +1814,17 @@ impl ChatComposer { if text.is_empty() && self.attached_images.is_empty() { return None; } - if !text.is_empty() { - self.history.record_local_submission(&text); + if !text.is_empty() || !self.attached_images.is_empty() { + let local_image_paths = self + .attached_images + .iter() + .map(|img| img.path.clone()) + .collect(); + self.history.record_local_submission(HistoryEntry { + text: text.clone(), + text_elements: text_elements.clone(), + local_image_paths, + }); } self.pending_pastes.clear(); Some((text, text_elements)) @@ -1989,15 +2020,19 @@ impl ChatComposer { .history .should_handle_navigation(self.textarea.text(), self.textarea.cursor()) { - let replace_text = match key_event.code { + let replace_entry = match key_event.code { KeyCode::Up => self.history.navigate_up(&self.app_event_tx), KeyCode::Down => self.history.navigate_down(&self.app_event_tx), KeyCode::Char('p') => self.history.navigate_up(&self.app_event_tx), KeyCode::Char('n') => self.history.navigate_down(&self.app_event_tx), _ => unreachable!(), }; - if let Some(text) = replace_text { - self.set_text_content(text, Vec::new(), Vec::new()); + if let Some(entry) = replace_entry { + self.set_text_content( + entry.text, + entry.text_elements, + entry.local_image_paths, + ); return (InputResult::None, true); } } @@ -3268,7 +3303,7 @@ mod tests { assert_eq!( composer.history.navigate_up(&composer.app_event_tx), - Some("draft text".to_string()) + Some(HistoryEntry::from_text("draft text".to_string())) ); } @@ -4721,6 +4756,37 @@ mod tests { assert_eq!(vec![path], imgs); } + #[test] + fn history_navigation_restores_image_attachments() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.set_steer_enabled(true); + let path = PathBuf::from("/tmp/image1.png"); + composer.attach_image(path.clone()); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(matches!(result, InputResult::Submitted { .. })); + + composer.set_text_content(String::new(), Vec::new(), Vec::new()); + + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + + let text = composer.current_text(); + assert_eq!(text, "[Image #1]"); + let text_elements = composer.text_elements(); + assert_eq!(text_elements.len(), 1); + assert_eq!(text_elements[0].placeholder(&text), Some("[Image #1]")); + assert_eq!(composer.local_image_paths(), vec![path]); + } + #[test] fn set_text_content_reattaches_images_without_placeholder_metadata() { let (tx, _rx) = unbounded_channel::(); 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 991283a566..da9f46ae4b 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer_history.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer_history.rs @@ -1,8 +1,35 @@ use std::collections::HashMap; +use std::path::PathBuf; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use codex_core::protocol::Op; +use codex_protocol::user_input::TextElement; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct HistoryEntry { + pub(crate) text: String, + pub(crate) text_elements: Vec, + pub(crate) local_image_paths: Vec, +} + +impl HistoryEntry { + fn empty() -> Self { + Self { + text: String::new(), + text_elements: Vec::new(), + local_image_paths: Vec::new(), + } + } + + pub(crate) fn from_text(text: String) -> Self { + Self { + text, + text_elements: Vec::new(), + local_image_paths: Vec::new(), + } + } +} /// State machine that manages shell-style history navigation (Up/Down) inside /// the chat composer. This struct is intentionally decoupled from the @@ -15,10 +42,10 @@ pub(crate) struct ChatComposerHistory { history_entry_count: usize, /// Messages submitted by the user *during this UI session* (newest at END). - local_history: Vec, + local_history: Vec, /// Cache of persistent history entries fetched on-demand. - fetched_history: HashMap, + fetched_history: HashMap, /// Current cursor within the combined (persistent + local) history. `None` /// indicates the user is *not* currently browsing history. @@ -54,8 +81,8 @@ impl ChatComposerHistory { /// Record a message submitted by the user in the current session so it can /// be recalled later. - pub fn record_local_submission(&mut self, text: &str) { - if text.is_empty() { + pub fn record_local_submission(&mut self, entry: HistoryEntry) { + if entry.text.is_empty() && entry.local_image_paths.is_empty() { return; } @@ -63,11 +90,11 @@ impl ChatComposerHistory { self.last_history_text = None; // Avoid inserting a duplicate if identical to the previous entry. - if self.local_history.last().is_some_and(|prev| prev == text) { + if self.local_history.last().is_some_and(|prev| prev == &entry) { return; } - self.local_history.push(text.to_string()); + self.local_history.push(entry); } /// Reset navigation tracking so the next Up key resumes from the latest entry. @@ -99,7 +126,7 @@ impl ChatComposerHistory { /// Handle . Returns true when the key was consumed and the caller /// should request a redraw. - pub fn navigate_up(&mut self, app_event_tx: &AppEventSender) -> Option { + pub fn navigate_up(&mut self, app_event_tx: &AppEventSender) -> Option { let total_entries = self.history_entry_count + self.local_history.len(); if total_entries == 0 { return None; @@ -116,7 +143,7 @@ impl ChatComposerHistory { } /// Handle . - pub fn navigate_down(&mut self, app_event_tx: &AppEventSender) -> Option { + pub fn navigate_down(&mut self, app_event_tx: &AppEventSender) -> Option { let total_entries = self.history_entry_count + self.local_history.len(); if total_entries == 0 { return None; @@ -137,7 +164,7 @@ impl ChatComposerHistory { // Past newest – clear and exit browsing mode. self.history_cursor = None; self.last_history_text = None; - Some(String::new()) + Some(HistoryEntry::empty()) } } } @@ -148,16 +175,17 @@ impl ChatComposerHistory { log_id: u64, offset: usize, entry: Option, - ) -> Option { + ) -> Option { if self.history_log_id != Some(log_id) { return None; } let text = entry?; - self.fetched_history.insert(offset, text.clone()); + let entry = HistoryEntry::from_text(text); + self.fetched_history.insert(offset, entry.clone()); if self.history_cursor == Some(offset as isize) { - self.last_history_text = Some(text.clone()); - return Some(text); + self.last_history_text = Some(entry.text.clone()); + return Some(entry); } None } @@ -170,19 +198,20 @@ impl ChatComposerHistory { &mut self, global_idx: usize, app_event_tx: &AppEventSender, - ) -> Option { + ) -> Option { if global_idx >= self.history_entry_count { // Local entry. - if let Some(text) = self + if let Some(entry) = self .local_history .get(global_idx - self.history_entry_count) + .cloned() { - self.last_history_text = Some(text.clone()); - return Some(text.clone()); + self.last_history_text = Some(entry.text.clone()); + return Some(entry); } - } else if let Some(text) = self.fetched_history.get(&global_idx) { - self.last_history_text = Some(text.clone()); - return Some(text.clone()); + } else if let Some(entry) = self.fetched_history.get(&global_idx).cloned() { + self.last_history_text = Some(entry.text.clone()); + return Some(entry); } else if let Some(log_id) = self.history_log_id { let op = Op::GetHistoryEntryRequest { offset: global_idx, @@ -206,22 +235,28 @@ mod tests { let mut history = ChatComposerHistory::new(); // Empty submissions are ignored. - history.record_local_submission(""); + history.record_local_submission(HistoryEntry::from_text(String::new())); assert_eq!(history.local_history.len(), 0); // First entry is recorded. - history.record_local_submission("hello"); + history.record_local_submission(HistoryEntry::from_text("hello".to_string())); assert_eq!(history.local_history.len(), 1); - assert_eq!(history.local_history.last().unwrap(), "hello"); + assert_eq!( + history.local_history.last().unwrap(), + &HistoryEntry::from_text("hello".to_string()) + ); // Identical consecutive entry is skipped. - history.record_local_submission("hello"); + history.record_local_submission(HistoryEntry::from_text("hello".to_string())); assert_eq!(history.local_history.len(), 1); // Different entry is recorded. - history.record_local_submission("world"); + history.record_local_submission(HistoryEntry::from_text("world".to_string())); assert_eq!(history.local_history.len(), 2); - assert_eq!(history.local_history.last().unwrap(), "world"); + assert_eq!( + history.local_history.last().unwrap(), + &HistoryEntry::from_text("world".to_string()) + ); } #[test] @@ -252,7 +287,7 @@ mod tests { // Inject the async response. assert_eq!( - Some("latest".into()), + Some(HistoryEntry::from_text("latest".to_string())), history.on_entry_response(1, 2, Some("latest".into())) ); @@ -273,7 +308,7 @@ mod tests { ); assert_eq!( - Some("older".into()), + Some(HistoryEntry::from_text("older".to_string())), history.on_entry_response(1, 1, Some("older".into())) ); } @@ -285,16 +320,29 @@ mod tests { let mut history = ChatComposerHistory::new(); history.set_metadata(1, 3); - history.fetched_history.insert(1, "command2".into()); - history.fetched_history.insert(2, "command3".into()); + history + .fetched_history + .insert(1, HistoryEntry::from_text("command2".to_string())); + history + .fetched_history + .insert(2, HistoryEntry::from_text("command3".to_string())); - assert_eq!(Some("command3".into()), history.navigate_up(&tx)); - assert_eq!(Some("command2".into()), history.navigate_up(&tx)); + assert_eq!( + Some(HistoryEntry::from_text("command3".to_string())), + history.navigate_up(&tx) + ); + assert_eq!( + Some(HistoryEntry::from_text("command2".to_string())), + history.navigate_up(&tx) + ); history.reset_navigation(); assert!(history.history_cursor.is_none()); assert!(history.last_history_text.is_none()); - assert_eq!(Some("command3".into()), history.navigate_up(&tx)); + assert_eq!( + Some(HistoryEntry::from_text("command3".to_string())), + history.navigate_up(&tx) + ); } } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 76d5600010..64060aece8 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -1749,10 +1749,7 @@ async fn ctrl_c_cleared_prompt_is_recoverable_via_history() { assert!(!chat.bottom_pane.quit_shortcut_hint_visible()); let images = chat.bottom_pane.take_recent_submission_images(); - assert!( - images.is_empty(), - "attachments are not preserved in history recall" - ); + assert_eq!(vec![PathBuf::from("/tmp/preview.png")], images); } #[tokio::test] diff --git a/docs/tui-chat-composer.md b/docs/tui-chat-composer.md index baab4ce0ed..01b5334d94 100644 --- a/docs/tui-chat-composer.md +++ b/docs/tui-chat-composer.md @@ -49,6 +49,19 @@ The solution is to detect paste-like _bursts_ and buffer them into a single expl - After handling the key, `sync_popups()` runs so popup visibility/filters stay consistent with the latest text + cursor. +### History navigation (↑/↓) + +Up/Down recall is handled by `ChatComposerHistory` and merges two sources: + +- **Persistent history** (cross-session, fetched from `~/.codex/history.jsonl`): text-only. It + does **not** carry text element ranges or local image attachments, so recalling one of these + entries only restores the text. +- **Local history** (current session): stores the full submission payload, including text + elements and local image paths. Recalling a local entry rehydrates placeholders and attachments. + +This distinction keeps the on-disk history backward compatible and avoids persisting attachments, +while still providing a richer recall experience for in-session edits. + ## Config gating for reuse `ChatComposer` now supports feature gating via `ChatComposerConfig` From 3bb8e69dd33fee1022825154cacc81fb40278750 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Tue, 27 Jan 2026 19:02:45 -0800 Subject: [PATCH 026/116] [skills] Auto install MCP dependencies when running skils with dependency specs. (#9982) Auto install MCP dependencies when running skils with dependency specs. --- .../app-server-protocol/src/protocol/v2.rs | 62 ++- .../app-server/src/codex_message_processor.rs | 16 + codex-rs/cli/src/mcp_cmd.rs | 47 +- codex-rs/core/config.schema.json | 6 + codex-rs/core/src/codex.rs | 125 ++++- codex-rs/core/src/default_client.rs | 16 + codex-rs/core/src/features.rs | 8 + codex-rs/core/src/mcp/auth.rs | 41 ++ codex-rs/core/src/mcp/mod.rs | 4 + codex-rs/core/src/mcp/skill_dependencies.rs | 518 ++++++++++++++++++ codex-rs/core/src/skills/injection.rs | 501 ++++++++++++++++- codex-rs/core/src/skills/loader.rs | 267 ++++++++- codex-rs/core/src/skills/mod.rs | 1 + codex-rs/core/src/skills/model.rs | 16 + codex-rs/core/src/state/session.rs | 14 + codex-rs/protocol/src/protocol.rs | 30 +- codex-rs/tui/src/bottom_pane/mod.rs | 1 + codex-rs/tui/src/chatwidget/skills.rs | 19 + 18 files changed, 1591 insertions(+), 101 deletions(-) create mode 100644 codex-rs/core/src/mcp/skill_dependencies.rs diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index e4b3b90589..0116bd21e9 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -27,10 +27,12 @@ use codex_protocol::protocol::NetworkAccess as CoreNetworkAccess; use codex_protocol::protocol::RateLimitSnapshot as CoreRateLimitSnapshot; use codex_protocol::protocol::RateLimitWindow as CoreRateLimitWindow; use codex_protocol::protocol::SessionSource as CoreSessionSource; +use codex_protocol::protocol::SkillDependencies as CoreSkillDependencies; use codex_protocol::protocol::SkillErrorInfo as CoreSkillErrorInfo; use codex_protocol::protocol::SkillInterface as CoreSkillInterface; use codex_protocol::protocol::SkillMetadata as CoreSkillMetadata; use codex_protocol::protocol::SkillScope as CoreSkillScope; +use codex_protocol::protocol::SkillToolDependency as CoreSkillToolDependency; use codex_protocol::protocol::SubAgentSource as CoreSubAgentSource; use codex_protocol::protocol::TokenUsage as CoreTokenUsage; use codex_protocol::protocol::TokenUsageInfo as CoreTokenUsageInfo; @@ -1395,11 +1397,14 @@ pub struct SkillMetadata { pub description: String, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] - /// Legacy short_description from SKILL.md. Prefer SKILL.toml interface.short_description. + /// Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description. pub short_description: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub interface: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub dependencies: Option, pub path: PathBuf, pub scope: SkillScope, pub enabled: bool, @@ -1423,6 +1428,35 @@ pub struct SkillInterface { pub default_prompt: Option, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct SkillDependencies { + pub tools: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct SkillToolDependency { + #[serde(rename = "type")] + #[ts(rename = "type")] + pub r#type: String, + pub value: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub transport: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub command: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub url: Option, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -1462,6 +1496,7 @@ impl From for SkillMetadata { description: value.description, short_description: value.short_description, interface: value.interface.map(SkillInterface::from), + dependencies: value.dependencies.map(SkillDependencies::from), path: value.path, scope: value.scope.into(), enabled: true, @@ -1482,6 +1517,31 @@ impl From for SkillInterface { } } +impl From for SkillDependencies { + fn from(value: CoreSkillDependencies) -> Self { + Self { + tools: value + .tools + .into_iter() + .map(SkillToolDependency::from) + .collect(), + } + } +} + +impl From for SkillToolDependency { + fn from(value: CoreSkillToolDependency) -> Self { + Self { + r#type: value.r#type, + value: value.value, + description: value.description, + transport: value.transport, + command: value.command, + url: value.url, + } + } +} + impl From for SkillScope { fn from(value: CoreSkillScope) -> Self { match value { diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 589b88d9a2..e7acf3d290 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -4522,6 +4522,22 @@ fn skills_to_info( default_prompt: interface.default_prompt, } }), + dependencies: skill.dependencies.clone().map(|dependencies| { + codex_app_server_protocol::SkillDependencies { + tools: dependencies + .tools + .into_iter() + .map(|tool| codex_app_server_protocol::SkillToolDependency { + r#type: tool.r#type, + value: tool.value, + description: tool.description, + transport: tool.transport, + command: tool.command, + url: tool.url, + }) + .collect(), + } + }), path: skill.path.clone(), scope: skill.scope.into(), enabled, diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 7cc42c4c49..83de37e027 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -13,11 +13,12 @@ use codex_core::config::find_codex_home; use codex_core::config::load_global_mcp_servers; use codex_core::config::types::McpServerConfig; 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_rmcp_client::delete_oauth_tokens; use codex_rmcp_client::perform_oauth_login; -use codex_rmcp_client::supports_oauth_login; /// Subcommands: /// - `list` — list configured servers (with `--json`) @@ -260,33 +261,25 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re println!("Added global MCP server '{name}'."); - if let McpServerTransportConfig::StreamableHttp { - url, - bearer_token_env_var: None, - http_headers, - env_http_headers, - } = transport - { - match supports_oauth_login(&url).await { - Ok(true) => { - println!("Detected OAuth support. Starting OAuth flow…"); - perform_oauth_login( - &name, - &url, - config.mcp_oauth_credentials_store_mode, - http_headers.clone(), - env_http_headers.clone(), - &Vec::new(), - config.mcp_oauth_callback_port, - ) - .await?; - println!("Successfully logged in."); - } - Ok(false) => {} - Err(_) => println!( - "MCP server may or may not require login. Run `codex mcp login {name}` to login." - ), + match oauth_login_support(&transport).await { + McpOAuthLoginSupport::Supported(oauth_config) => { + println!("Detected OAuth support. Starting OAuth flow…"); + perform_oauth_login( + &name, + &oauth_config.url, + config.mcp_oauth_credentials_store_mode, + oauth_config.http_headers, + oauth_config.env_http_headers, + &Vec::new(), + config.mcp_oauth_callback_port, + ) + .await?; + println!("Successfully logged in."); } + McpOAuthLoginSupport::Unsupported => {} + McpOAuthLoginSupport::Unknown(_) => println!( + "MCP server may or may not require login. Run `codex mcp login {name}` to login." + ), } Ok(()) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 1e164b24cb..1fe5f9e75d 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -198,6 +198,9 @@ "shell_tool": { "type": "boolean" }, + "skill_mcp_dependency_install": { + "type": "boolean" + }, "steer": { "type": "boolean" }, @@ -1190,6 +1193,9 @@ "shell_tool": { "type": "boolean" }, + "skill_mcp_dependency_install": { + "type": "boolean" + }, "steer": { "type": "boolean" }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index c2c25967d2..d4f2822a73 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -115,6 +115,7 @@ use crate::instructions::UserInstructions; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::auth::compute_auth_statuses; 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::model_provider_info::CHAT_WIRE_API_DEPRECATION_SUMMARY; @@ -138,9 +139,11 @@ use crate::protocol::RequestUserInputEvent; use crate::protocol::ReviewDecision; use crate::protocol::SandboxPolicy; use crate::protocol::SessionConfiguredEvent; +use crate::protocol::SkillDependencies as ProtocolSkillDependencies; use crate::protocol::SkillErrorInfo; use crate::protocol::SkillInterface as ProtocolSkillInterface; use crate::protocol::SkillMetadata as ProtocolSkillMetadata; +use crate::protocol::SkillToolDependency as ProtocolSkillToolDependency; use crate::protocol::StreamErrorEvent; use crate::protocol::Submission; use crate::protocol::TokenCountEvent; @@ -158,6 +161,7 @@ use crate::skills::SkillInjections; use crate::skills::SkillMetadata; use crate::skills::SkillsManager; use crate::skills::build_skill_injections; +use crate::skills::collect_explicit_skill_mentions; use crate::state::ActiveTurn; use crate::state::SessionServices; use crate::state::SessionState; @@ -1857,6 +1861,19 @@ impl Session { self.send_token_count_event(turn_context).await; } + pub(crate) async fn mcp_dependency_prompted(&self) -> HashSet { + let state = self.state.lock().await; + state.mcp_dependency_prompted() + } + + pub(crate) async fn record_mcp_dependency_prompted(&self, names: I) + where + I: IntoIterator, + { + let mut state = self.state.lock().await; + state.record_mcp_dependency_prompted(names); + } + pub(crate) async fn set_server_reasoning_included(&self, included: bool) { let mut state = self.state.lock().await; state.set_server_reasoning_included(included); @@ -2101,35 +2118,12 @@ impl Session { Arc::clone(&self.services.user_shell) } - async fn refresh_mcp_servers_if_requested(&self, turn_context: &TurnContext) { - let refresh_config = { self.pending_mcp_server_refresh_config.lock().await.take() }; - let Some(refresh_config) = refresh_config else { - return; - }; - - let McpServerRefreshConfig { - mcp_servers, - mcp_oauth_credentials_store_mode, - } = refresh_config; - - let mcp_servers = - match serde_json::from_value::>(mcp_servers) { - Ok(servers) => servers, - Err(err) => { - warn!("failed to parse MCP server refresh config: {err}"); - return; - } - }; - let store_mode = match serde_json::from_value::( - mcp_oauth_credentials_store_mode, - ) { - Ok(mode) => mode, - Err(err) => { - warn!("failed to parse MCP OAuth refresh config: {err}"); - return; - } - }; - + async fn refresh_mcp_servers_inner( + &self, + turn_context: &TurnContext, + mcp_servers: HashMap, + store_mode: OAuthCredentialsStoreMode, + ) { let auth = self.services.auth_manager.auth().await; let config = self.get_config().await; let mcp_servers = with_codex_apps_mcp( @@ -2162,6 +2156,49 @@ impl Session { *manager = refreshed_manager; } + async fn refresh_mcp_servers_if_requested(&self, turn_context: &TurnContext) { + let refresh_config = { self.pending_mcp_server_refresh_config.lock().await.take() }; + let Some(refresh_config) = refresh_config else { + return; + }; + + let McpServerRefreshConfig { + mcp_servers, + mcp_oauth_credentials_store_mode, + } = refresh_config; + + let mcp_servers = + match serde_json::from_value::>(mcp_servers) { + Ok(servers) => servers, + Err(err) => { + warn!("failed to parse MCP server refresh config: {err}"); + return; + } + }; + let store_mode = match serde_json::from_value::( + mcp_oauth_credentials_store_mode, + ) { + Ok(mode) => mode, + Err(err) => { + warn!("failed to parse MCP OAuth refresh config: {err}"); + return; + } + }; + + self.refresh_mcp_servers_inner(turn_context, mcp_servers, store_mode) + .await; + } + + pub(crate) async fn refresh_mcp_servers_now( + &self, + turn_context: &TurnContext, + mcp_servers: HashMap, + store_mode: OAuthCredentialsStoreMode, + ) { + self.refresh_mcp_servers_inner(turn_context, mcp_servers, store_mode) + .await; + } + async fn mcp_startup_cancellation_token(&self) -> CancellationToken { self.services .mcp_startup_cancellation_token @@ -2985,6 +3022,22 @@ fn skills_to_info( brand_color: interface.brand_color, default_prompt: interface.default_prompt, }), + dependencies: skill.dependencies.clone().map(|dependencies| { + ProtocolSkillDependencies { + tools: dependencies + .tools + .into_iter() + .map(|tool| ProtocolSkillToolDependency { + r#type: tool.r#type, + value: tool.value, + description: tool.description, + transport: tool.transport, + command: tool.command, + url: tool.url, + }) + .collect(), + } + }), path: skill.path.clone(), scope: skill.scope, enabled: !disabled_paths.contains(&skill.path), @@ -3044,11 +3097,23 @@ pub(crate) async fn run_turn( .await, ); + let mentioned_skills = skills_outcome.as_ref().map_or_else(Vec::new, |outcome| { + collect_explicit_skill_mentions(&input, &outcome.skills, &outcome.disabled_paths) + }); + + maybe_prompt_and_install_mcp_dependencies( + sess.as_ref(), + turn_context.as_ref(), + &cancellation_token, + &mentioned_skills, + ) + .await; + let otel_manager = turn_context.client.get_otel_manager(); let SkillInjections { items: skill_items, warnings: skill_warnings, - } = build_skill_injections(&input, skills_outcome.as_ref(), Some(&otel_manager)).await; + } = build_skill_injections(&mentioned_skills, Some(&otel_manager)).await; for message in skill_warnings { sess.send_event(&turn_context, EventMsg::Warning(WarningEvent { message })) diff --git a/codex-rs/core/src/default_client.rs b/codex-rs/core/src/default_client.rs index 4ded10a3d9..67a5daf1b1 100644 --- a/codex-rs/core/src/default_client.rs +++ b/codex-rs/core/src/default_client.rs @@ -95,6 +95,12 @@ pub fn originator() -> Originator { get_originator_value(None) } +pub fn is_first_party_originator(originator_value: &str) -> bool { + originator_value == DEFAULT_ORIGINATOR + || originator_value == "codex_vscode" + || originator_value.starts_with("Codex ") +} + pub fn get_codex_user_agent() -> String { let build_version = env!("CARGO_PKG_VERSION"); let os_info = os_info::get(); @@ -185,6 +191,7 @@ fn is_sandboxed() -> bool { mod tests { use super::*; use core_test_support::skip_if_no_network; + use pretty_assertions::assert_eq; #[test] fn test_get_codex_user_agent() { @@ -194,6 +201,15 @@ mod tests { assert!(user_agent.starts_with(&prefix)); } + #[test] + fn is_first_party_originator_matches_known_values() { + assert_eq!(is_first_party_originator(DEFAULT_ORIGINATOR), true); + assert_eq!(is_first_party_originator("codex_vscode"), true); + assert_eq!(is_first_party_originator("Codex Something Else"), true); + assert_eq!(is_first_party_originator("codex_cli"), false); + assert_eq!(is_first_party_originator("Other"), false); + } + #[tokio::test] async fn test_create_client_sets_default_headers() { skip_if_no_network!(); diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 7fde52687c..cc56970276 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -109,6 +109,8 @@ pub enum Feature { Collab, /// Enable connectors (apps). Connectors, + /// Allow prompting and installing missing MCP dependencies. + SkillMcpDependencyInstall, /// Steer feature flag - when enabled, Enter submits immediately instead of queuing. Steer, /// Enable collaboration modes (Plan, Code, Pair Programming, Execute). @@ -449,6 +451,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::SkillMcpDependencyInstall, + key: "skill_mcp_dependency_install", + stage: Stage::Stable, + default_enabled: true, + }, FeatureSpec { id: Feature::Steer, key: "steer", diff --git a/codex-rs/core/src/mcp/auth.rs b/codex-rs/core/src/mcp/auth.rs index e321a857bb..f095c930dc 100644 --- a/codex-rs/core/src/mcp/auth.rs +++ b/codex-rs/core/src/mcp/auth.rs @@ -4,12 +4,53 @@ use anyhow::Result; use codex_protocol::protocol::McpAuthStatus; use codex_rmcp_client::OAuthCredentialsStoreMode; use codex_rmcp_client::determine_streamable_http_auth_status; +use codex_rmcp_client::supports_oauth_login; use futures::future::join_all; use tracing::warn; use crate::config::types::McpServerConfig; use crate::config::types::McpServerTransportConfig; +#[derive(Debug, Clone)] +pub struct McpOAuthLoginConfig { + pub url: String, + pub http_headers: Option>, + pub env_http_headers: Option>, +} + +#[derive(Debug)] +pub enum McpOAuthLoginSupport { + Supported(McpOAuthLoginConfig), + Unsupported, + Unknown(anyhow::Error), +} + +pub async fn oauth_login_support(transport: &McpServerTransportConfig) -> McpOAuthLoginSupport { + let McpServerTransportConfig::StreamableHttp { + url, + bearer_token_env_var, + http_headers, + env_http_headers, + } = transport + else { + return McpOAuthLoginSupport::Unsupported; + }; + + if bearer_token_env_var.is_some() { + return McpOAuthLoginSupport::Unsupported; + } + + match supports_oauth_login(url).await { + Ok(true) => McpOAuthLoginSupport::Supported(McpOAuthLoginConfig { + url: url.clone(), + http_headers: http_headers.clone(), + env_http_headers: env_http_headers.clone(), + }), + Ok(false) => McpOAuthLoginSupport::Unsupported, + Err(err) => McpOAuthLoginSupport::Unknown(err), + } +} + #[derive(Debug, Clone)] pub struct McpAuthStatusEntry { pub config: McpServerConfig, diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index 1bb08a75be..fa1de0f045 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -1,4 +1,8 @@ pub mod auth; +mod skill_dependencies; + +pub(crate) use skill_dependencies::maybe_prompt_and_install_mcp_dependencies; + use std::collections::HashMap; use std::env; use std::path::PathBuf; diff --git a/codex-rs/core/src/mcp/skill_dependencies.rs b/codex-rs/core/src/mcp/skill_dependencies.rs new file mode 100644 index 0000000000..c295a96863 --- /dev/null +++ b/codex-rs/core/src/mcp/skill_dependencies.rs @@ -0,0 +1,518 @@ +use std::collections::HashMap; +use std::collections::HashSet; + +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::request_user_input::RequestUserInputArgs; +use codex_protocol::request_user_input::RequestUserInputQuestion; +use codex_protocol::request_user_input::RequestUserInputQuestionOption; +use codex_protocol::request_user_input::RequestUserInputResponse; +use codex_rmcp_client::perform_oauth_login; +use tokio_util::sync::CancellationToken; +use tracing::warn; + +use super::auth::McpOAuthLoginSupport; +use super::auth::oauth_login_support; +use super::effective_mcp_servers; +use crate::codex::Session; +use crate::codex::TurnContext; +use crate::config::Config; +use crate::config::edit::ConfigEditsBuilder; +use crate::config::load_global_mcp_servers; +use crate::config::types::McpServerConfig; +use crate::config::types::McpServerTransportConfig; +use crate::default_client::is_first_party_originator; +use crate::default_client::originator; +use crate::features::Feature; +use crate::skills::SkillMetadata; +use crate::skills::model::SkillToolDependency; + +const SKILL_MCP_DEPENDENCY_PROMPT_ID: &str = "skill_mcp_dependency_install"; +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.sandbox_policy, + SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } + ) +} + +fn format_missing_mcp_dependencies(missing: &HashMap) -> String { + let mut names = missing.keys().cloned().collect::>(); + names.sort(); + names.join(", ") +} + +async fn filter_prompted_mcp_dependencies( + sess: &Session, + missing: &HashMap, +) -> HashMap { + let prompted = sess.mcp_dependency_prompted().await; + if prompted.is_empty() { + return missing.clone(); + } + + missing + .iter() + .filter(|(name, config)| !prompted.contains(&canonical_mcp_server_key(name, config))) + .map(|(name, config)| (name.clone(), config.clone())) + .collect() +} + +async fn should_install_mcp_dependencies( + sess: &Session, + turn_context: &TurnContext, + missing: &HashMap, + cancellation_token: &CancellationToken, +) -> bool { + if is_full_access_mode(turn_context) { + return true; + } + + let server_list = format_missing_mcp_dependencies(missing); + let question = RequestUserInputQuestion { + id: SKILL_MCP_DEPENDENCY_PROMPT_ID.to_string(), + header: "Install MCP servers?".to_string(), + question: format!( + "The following MCP servers are required by the selected skills but are not installed yet: {server_list}. Install them now?" + ), + is_other: false, + options: Some(vec![ + RequestUserInputQuestionOption { + label: MCP_DEPENDENCY_OPTION_INSTALL.to_string(), + description: + "Install and enable the missing MCP servers in your global config." + .to_string(), + }, + RequestUserInputQuestionOption { + label: MCP_DEPENDENCY_OPTION_SKIP.to_string(), + description: "Skip installation for now and do not show again for these MCP servers in this session." + .to_string(), + }, + ]), + }; + let args = RequestUserInputArgs { + questions: vec![question], + }; + let sub_id = &turn_context.sub_id; + let call_id = format!("mcp-deps-{sub_id}"); + let response_fut = sess.request_user_input(turn_context, call_id, args); + let response = tokio::select! { + biased; + _ = cancellation_token.cancelled() => { + let empty = RequestUserInputResponse { + answers: HashMap::new(), + }; + sess.notify_user_input_response(sub_id, empty.clone()).await; + empty + } + response = response_fut => response.unwrap_or_else(|| RequestUserInputResponse { + answers: HashMap::new(), + }), + }; + + let install = response + .answers + .get(SKILL_MCP_DEPENDENCY_PROMPT_ID) + .is_some_and(|answer| { + answer + .answers + .iter() + .any(|entry| entry == MCP_DEPENDENCY_OPTION_INSTALL) + }); + + let prompted_keys = missing + .iter() + .map(|(name, config)| canonical_mcp_server_key(name, config)); + sess.record_mcp_dependency_prompted(prompted_keys).await; + + install +} + +pub(crate) async fn maybe_prompt_and_install_mcp_dependencies( + sess: &Session, + turn_context: &TurnContext, + cancellation_token: &CancellationToken, + mentioned_skills: &[SkillMetadata], +) { + let originator_value = originator().value; + if !is_first_party_originator(originator_value.as_str()) { + // Only support first-party clients for now. + return; + } + + let config = turn_context.client.config(); + if mentioned_skills.is_empty() || !config.features.enabled(Feature::SkillMcpDependencyInstall) { + return; + } + + let installed = config.mcp_servers.get().clone(); + let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed); + if missing.is_empty() { + return; + } + + let unprompted_missing = filter_prompted_mcp_dependencies(sess, &missing).await; + if unprompted_missing.is_empty() { + return; + } + + if should_install_mcp_dependencies(sess, turn_context, &unprompted_missing, cancellation_token) + .await + { + maybe_install_mcp_dependencies(sess, turn_context, config.as_ref(), mentioned_skills).await; + } +} + +pub(crate) async fn maybe_install_mcp_dependencies( + sess: &Session, + turn_context: &TurnContext, + config: &Config, + mentioned_skills: &[SkillMetadata], +) { + if mentioned_skills.is_empty() || !config.features.enabled(Feature::SkillMcpDependencyInstall) { + return; + } + + let codex_home = config.codex_home.clone(); + let installed = config.mcp_servers.get().clone(); + let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed); + if missing.is_empty() { + return; + } + + let mut servers = match load_global_mcp_servers(&codex_home).await { + Ok(servers) => servers, + Err(err) => { + warn!("failed to load MCP servers while installing skill dependencies: {err}"); + return; + } + }; + + let mut updated = false; + let mut added = Vec::new(); + for (name, config) in missing { + if servers.contains_key(&name) { + continue; + } + servers.insert(name.clone(), config.clone()); + added.push((name, config)); + updated = true; + } + + if !updated { + return; + } + + if let Err(err) = ConfigEditsBuilder::new(&codex_home) + .replace_mcp_servers(&servers) + .apply() + .await + { + warn!("failed to persist MCP dependencies for mentioned skills: {err}"); + return; + } + + for (name, server_config) in added { + let oauth_config = match oauth_login_support(&server_config.transport).await { + McpOAuthLoginSupport::Supported(config) => config, + McpOAuthLoginSupport::Unsupported => continue, + McpOAuthLoginSupport::Unknown(err) => { + warn!("MCP server may or may not require login for dependency {name}: {err}"); + continue; + } + }; + + sess.notify_background_event( + turn_context, + format!( + "Authenticating MCP {name}... Follow instructions in your browser if prompted." + ), + ) + .await; + + if let Err(err) = perform_oauth_login( + &name, + &oauth_config.url, + config.mcp_oauth_credentials_store_mode, + oauth_config.http_headers, + oauth_config.env_http_headers, + &[], + config.mcp_oauth_callback_port, + ) + .await + { + warn!("failed to login to MCP dependency {name}: {err}"); + } + } + + // Refresh from the effective merged MCP map (global + repo + managed) and + // overlay the updated global servers so we don't drop repo-scoped servers. + let auth = sess.services.auth_manager.auth().await; + let mut refresh_servers = effective_mcp_servers(config, auth.as_ref()); + for (name, server_config) in &servers { + refresh_servers + .entry(name.clone()) + .or_insert_with(|| server_config.clone()); + } + sess.refresh_mcp_servers_now( + turn_context, + refresh_servers, + config.mcp_oauth_credentials_store_mode, + ) + .await; +} + +fn canonical_mcp_key(transport: &str, identifier: &str, fallback: &str) -> String { + let identifier = identifier.trim(); + if identifier.is_empty() { + fallback.to_string() + } else { + format!("mcp__{transport}__{identifier}") + } +} + +fn canonical_mcp_server_key(name: &str, config: &McpServerConfig) -> String { + match &config.transport { + McpServerTransportConfig::Stdio { command, .. } => { + canonical_mcp_key("stdio", command, name) + } + McpServerTransportConfig::StreamableHttp { url, .. } => { + canonical_mcp_key("streamable_http", url, name) + } + } +} + +fn canonical_mcp_dependency_key(dependency: &SkillToolDependency) -> Result { + let transport = dependency.transport.as_deref().unwrap_or("streamable_http"); + if transport.eq_ignore_ascii_case("streamable_http") { + let url = dependency + .url + .as_ref() + .ok_or_else(|| "missing url for streamable_http dependency".to_string())?; + return Ok(canonical_mcp_key("streamable_http", url, &dependency.value)); + } + if transport.eq_ignore_ascii_case("stdio") { + let command = dependency + .command + .as_ref() + .ok_or_else(|| "missing command for stdio dependency".to_string())?; + return Ok(canonical_mcp_key("stdio", command, &dependency.value)); + } + Err(format!("unsupported transport {transport}")) +} + +pub(crate) fn collect_missing_mcp_dependencies( + mentioned_skills: &[SkillMetadata], + installed: &HashMap, +) -> HashMap { + let mut missing = HashMap::new(); + let installed_keys: HashSet = installed + .iter() + .map(|(name, config)| canonical_mcp_server_key(name, config)) + .collect(); + let mut seen_canonical_keys = HashSet::new(); + + for skill in mentioned_skills { + let Some(dependencies) = skill.dependencies.as_ref() else { + continue; + }; + + for tool in &dependencies.tools { + if !tool.r#type.eq_ignore_ascii_case("mcp") { + continue; + } + let dependency_key = match canonical_mcp_dependency_key(tool) { + Ok(key) => key, + Err(err) => { + let dependency = tool.value.as_str(); + let skill_name = skill.name.as_str(); + warn!( + "unable to auto-install MCP dependency {dependency} for skill {skill_name}: {err}", + ); + continue; + } + }; + if installed_keys.contains(&dependency_key) + || seen_canonical_keys.contains(&dependency_key) + { + continue; + } + + let config = match mcp_dependency_to_server_config(tool) { + Ok(config) => config, + Err(err) => { + let dependency = dependency_key.as_str(); + let skill_name = skill.name.as_str(); + warn!( + "unable to auto-install MCP dependency {dependency} for skill {skill_name}: {err}", + ); + continue; + } + }; + + missing.insert(tool.value.clone(), config); + seen_canonical_keys.insert(dependency_key); + } + } + + missing +} + +fn mcp_dependency_to_server_config( + dependency: &SkillToolDependency, +) -> Result { + let transport = dependency.transport.as_deref().unwrap_or("streamable_http"); + if transport.eq_ignore_ascii_case("streamable_http") { + let url = dependency + .url + .as_ref() + .ok_or_else(|| "missing url for streamable_http dependency".to_string())?; + return Ok(McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url: url.clone(), + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + }, + enabled: true, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + }); + } + + if transport.eq_ignore_ascii_case("stdio") { + let command = dependency + .command + .as_ref() + .ok_or_else(|| "missing command for stdio dependency".to_string())?; + return Ok(McpServerConfig { + transport: McpServerTransportConfig::Stdio { + command: command.clone(), + args: Vec::new(), + env: None, + env_vars: Vec::new(), + cwd: None, + }, + enabled: true, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + }); + } + + Err(format!("unsupported transport {transport}")) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::skills::model::SkillDependencies; + use codex_protocol::protocol::SkillScope; + use pretty_assertions::assert_eq; + use std::path::PathBuf; + + fn skill_with_tools(tools: Vec) -> SkillMetadata { + SkillMetadata { + name: "skill".to_string(), + description: "skill".to_string(), + short_description: None, + interface: None, + dependencies: Some(SkillDependencies { tools }), + path: PathBuf::from("skill"), + scope: SkillScope::User, + } + } + + #[test] + fn collect_missing_respects_canonical_installed_key() { + let url = "https://example.com/mcp".to_string(); + let skills = vec![skill_with_tools(vec![SkillToolDependency { + r#type: "mcp".to_string(), + value: "github".to_string(), + description: None, + transport: Some("streamable_http".to_string()), + command: None, + url: Some(url.clone()), + }])]; + let installed = HashMap::from([( + "alias".to_string(), + McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url, + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + }, + enabled: true, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + }, + )]); + + assert_eq!( + collect_missing_mcp_dependencies(&skills, &installed), + HashMap::new() + ); + } + + #[test] + fn collect_missing_dedupes_by_canonical_key_but_preserves_original_name() { + let url = "https://example.com/one".to_string(); + let skills = vec![skill_with_tools(vec![ + SkillToolDependency { + r#type: "mcp".to_string(), + value: "alias-one".to_string(), + description: None, + transport: Some("streamable_http".to_string()), + command: None, + url: Some(url.clone()), + }, + SkillToolDependency { + r#type: "mcp".to_string(), + value: "alias-two".to_string(), + description: None, + transport: Some("streamable_http".to_string()), + command: None, + url: Some(url.clone()), + }, + ])]; + + let expected = HashMap::from([( + "alias-one".to_string(), + McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url, + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + }, + enabled: true, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + }, + )]); + + assert_eq!( + collect_missing_mcp_dependencies(&skills, &HashMap::new()), + expected + ); + } +} diff --git a/codex-rs/core/src/skills/injection.rs b/codex-rs/core/src/skills/injection.rs index 9aa12d775c..65ec4dd510 100644 --- a/codex-rs/core/src/skills/injection.rs +++ b/codex-rs/core/src/skills/injection.rs @@ -2,7 +2,6 @@ use std::collections::HashSet; use std::path::PathBuf; use crate::instructions::SkillInstructions; -use crate::skills::SkillLoadOutcome; use crate::skills::SkillMetadata; use codex_otel::OtelManager; use codex_protocol::models::ResponseItem; @@ -16,20 +15,9 @@ pub(crate) struct SkillInjections { } pub(crate) async fn build_skill_injections( - inputs: &[UserInput], - skills: Option<&SkillLoadOutcome>, + mentioned_skills: &[SkillMetadata], otel: Option<&OtelManager>, ) -> SkillInjections { - if inputs.is_empty() { - return SkillInjections::default(); - } - - let Some(outcome) = skills else { - return SkillInjections::default(); - }; - - let mentioned_skills = - collect_explicit_skill_mentions(inputs, &outcome.skills, &outcome.disabled_paths); if mentioned_skills.is_empty() { return SkillInjections::default(); } @@ -42,15 +30,15 @@ pub(crate) async fn build_skill_injections( for skill in mentioned_skills { match fs::read_to_string(&skill.path).await { Ok(contents) => { - emit_skill_injected_metric(otel, &skill, "ok"); + emit_skill_injected_metric(otel, skill, "ok"); result.items.push(ResponseItem::from(SkillInstructions { - name: skill.name, + name: skill.name.clone(), path: skill.path.to_string_lossy().into_owned(), contents, })); } Err(err) => { - emit_skill_injected_metric(otel, &skill, "error"); + emit_skill_injected_metric(otel, skill, "error"); let message = format!( "Failed to load skill {name} at {path}: {err:#}", name = skill.name, @@ -76,23 +64,488 @@ fn emit_skill_injected_metric(otel: Option<&OtelManager>, skill: &SkillMetadata, ); } -fn collect_explicit_skill_mentions( +/// Collect explicitly mentioned skills from `$name` text mentions. +/// +/// Text inputs are scanned once to extract `$skill-name` tokens, then we iterate `skills` +/// in their existing order to preserve prior ordering semantics. +/// +/// Complexity: `O(S + T + N_t * S)` time, `O(S)` space, where: +/// `S` = number of skills, `T` = total text length, `N_t` = number of text inputs. +pub(crate) fn collect_explicit_skill_mentions( inputs: &[UserInput], skills: &[SkillMetadata], disabled_paths: &HashSet, ) -> Vec { let mut selected: Vec = Vec::new(); - let mut seen: HashSet = HashSet::new(); + let mut seen_names: HashSet = HashSet::new(); + let mut seen_paths: HashSet = HashSet::new(); for input in inputs { - if let UserInput::Skill { name, path } = input - && seen.insert(name.clone()) - && let Some(skill) = skills.iter().find(|s| s.name == *name && s.path == *path) - && !disabled_paths.contains(&skill.path) - { - selected.push(skill.clone()); + if let UserInput::Text { text, .. } = input { + let mentioned_names = extract_skill_mentions(text); + select_skills_from_mentions( + skills, + disabled_paths, + &mentioned_names, + &mut seen_names, + &mut seen_paths, + &mut selected, + ); } } selected } + +struct SkillMentions<'a> { + names: HashSet<&'a str>, + paths: HashSet<&'a str>, +} + +impl<'a> SkillMentions<'a> { + fn is_empty(&self) -> bool { + self.names.is_empty() && self.paths.is_empty() + } +} + +/// Extract `$skill-name` mentions from a single text input. +/// +/// Supports explicit resource links in the form `[$skill-name](resource path)`. When a +/// resource path is present, it is captured for exact path matching while also tracking +/// the name for fallback matching. +fn extract_skill_mentions(text: &str) -> SkillMentions<'_> { + let text_bytes = text.as_bytes(); + let mut mentioned_names: HashSet<&str> = HashSet::new(); + let mut mentioned_paths: HashSet<&str> = HashSet::new(); + + let mut index = 0; + while index < text_bytes.len() { + let byte = text_bytes[index]; + if byte == b'[' + && let Some((name, path, end_index)) = + parse_linked_skill_mention(text, text_bytes, index) + { + if !is_common_env_var(name) { + mentioned_names.insert(name); + mentioned_paths.insert(path); + } + index = end_index; + continue; + } + + if byte != b'$' { + index += 1; + continue; + } + + let name_start = index + 1; + let Some(first_name_byte) = text_bytes.get(name_start) else { + index += 1; + continue; + }; + if !is_skill_name_char(*first_name_byte) { + index += 1; + continue; + } + + let mut name_end = name_start + 1; + while let Some(next_byte) = text_bytes.get(name_end) + && is_skill_name_char(*next_byte) + { + name_end += 1; + } + + let name = &text[name_start..name_end]; + if !is_common_env_var(name) { + mentioned_names.insert(name); + } + index = name_end; + } + + SkillMentions { + names: mentioned_names, + paths: mentioned_paths, + } +} + +/// Select mentioned skills while preserving the order of `skills`. +fn select_skills_from_mentions( + skills: &[SkillMetadata], + disabled_paths: &HashSet, + mentions: &SkillMentions<'_>, + seen_names: &mut HashSet, + seen_paths: &mut HashSet, + selected: &mut Vec, +) { + if mentions.is_empty() { + return; + } + + for skill in skills { + if disabled_paths.contains(&skill.path) || seen_paths.contains(&skill.path) { + continue; + } + + let path_str = skill.path.to_string_lossy(); + if mentions.paths.contains(path_str.as_ref()) { + seen_paths.insert(skill.path.clone()); + seen_names.insert(skill.name.clone()); + selected.push(skill.clone()); + } + } + + for skill in skills { + if disabled_paths.contains(&skill.path) || seen_paths.contains(&skill.path) { + continue; + } + + if mentions.names.contains(skill.name.as_str()) && seen_names.insert(skill.name.clone()) { + seen_paths.insert(skill.path.clone()); + selected.push(skill.clone()); + } + } +} + +fn parse_linked_skill_mention<'a>( + text: &'a str, + text_bytes: &[u8], + start: usize, +) -> Option<(&'a str, &'a str, usize)> { + let dollar_index = start + 1; + if text_bytes.get(dollar_index) != Some(&b'$') { + return None; + } + + let name_start = dollar_index + 1; + let first_name_byte = text_bytes.get(name_start)?; + if !is_skill_name_char(*first_name_byte) { + return None; + } + + let mut name_end = name_start + 1; + while let Some(next_byte) = text_bytes.get(name_end) + && is_skill_name_char(*next_byte) + { + name_end += 1; + } + + if text_bytes.get(name_end) != Some(&b']') { + return None; + } + + let mut path_start = name_end + 1; + while let Some(next_byte) = text_bytes.get(path_start) + && next_byte.is_ascii_whitespace() + { + path_start += 1; + } + if text_bytes.get(path_start) != Some(&b'(') { + return None; + } + + let mut path_end = path_start + 1; + while let Some(next_byte) = text_bytes.get(path_end) + && *next_byte != b')' + { + path_end += 1; + } + if text_bytes.get(path_end) != Some(&b')') { + return None; + } + + let path = text[path_start + 1..path_end].trim(); + if path.is_empty() { + return None; + } + + let name = &text[name_start..name_end]; + Some((name, path, path_end + 1)) +} + +fn is_common_env_var(name: &str) -> bool { + let upper = name.to_ascii_uppercase(); + matches!( + upper.as_str(), + "PATH" + | "HOME" + | "USER" + | "SHELL" + | "PWD" + | "TMPDIR" + | "TEMP" + | "TMP" + | "LANG" + | "TERM" + | "XDG_CONFIG_HOME" + ) +} + +#[cfg(test)] +fn text_mentions_skill(text: &str, skill_name: &str) -> bool { + if skill_name.is_empty() { + return false; + } + + let text_bytes = text.as_bytes(); + let skill_bytes = skill_name.as_bytes(); + + for (index, byte) in text_bytes.iter().copied().enumerate() { + if byte != b'$' { + continue; + } + + let name_start = index + 1; + let Some(rest) = text_bytes.get(name_start..) else { + continue; + }; + if !rest.starts_with(skill_bytes) { + continue; + } + + let after_index = name_start + skill_bytes.len(); + let after = text_bytes.get(after_index).copied(); + if after.is_none_or(|b| !is_skill_name_char(b)) { + return true; + } + } + + false +} + +fn is_skill_name_char(byte: u8) -> bool { + matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use std::collections::HashSet; + + fn make_skill(name: &str, path: &str) -> SkillMetadata { + SkillMetadata { + name: name.to_string(), + description: format!("{name} skill"), + short_description: None, + interface: None, + dependencies: None, + path: PathBuf::from(path), + scope: codex_protocol::protocol::SkillScope::User, + } + } + + fn set<'a>(items: &'a [&'a str]) -> HashSet<&'a str> { + items.iter().copied().collect() + } + + fn assert_mentions(text: &str, expected_names: &[&str], expected_paths: &[&str]) { + let mentions = extract_skill_mentions(text); + assert_eq!(mentions.names, set(expected_names)); + assert_eq!(mentions.paths, set(expected_paths)); + } + + #[test] + fn text_mentions_skill_requires_exact_boundary() { + assert_eq!( + true, + text_mentions_skill("use $notion-research-doc please", "notion-research-doc") + ); + assert_eq!( + true, + text_mentions_skill("($notion-research-doc)", "notion-research-doc") + ); + assert_eq!( + true, + text_mentions_skill("$notion-research-doc.", "notion-research-doc") + ); + assert_eq!( + false, + text_mentions_skill("$notion-research-docs", "notion-research-doc") + ); + assert_eq!( + false, + text_mentions_skill("$notion-research-doc_extra", "notion-research-doc") + ); + } + + #[test] + fn text_mentions_skill_handles_end_boundary_and_near_misses() { + assert_eq!(true, text_mentions_skill("$alpha-skill", "alpha-skill")); + assert_eq!(false, text_mentions_skill("$alpha-skillx", "alpha-skill")); + assert_eq!( + true, + text_mentions_skill("$alpha-skillx and later $alpha-skill ", "alpha-skill") + ); + } + + #[test] + fn text_mentions_skill_handles_many_dollars_without_looping() { + let prefix = "$".repeat(256); + let text = format!("{prefix} not-a-mention"); + assert_eq!(false, text_mentions_skill(&text, "alpha-skill")); + } + + #[test] + fn extract_skill_mentions_handles_plain_and_linked_mentions() { + assert_mentions( + "use $alpha and [$beta](/tmp/beta)", + &["alpha", "beta"], + &["/tmp/beta"], + ); + } + + #[test] + fn extract_skill_mentions_skips_common_env_vars() { + assert_mentions("use $PATH and $alpha", &["alpha"], &[]); + assert_mentions("use [$HOME](/tmp/skill)", &[], &[]); + assert_mentions("use $XDG_CONFIG_HOME and $beta", &["beta"], &[]); + } + + #[test] + fn extract_skill_mentions_requires_link_syntax() { + assert_mentions("[beta](/tmp/beta)", &[], &[]); + assert_mentions("[$beta] /tmp/beta", &["beta"], &[]); + assert_mentions("[$beta]()", &["beta"], &[]); + } + + #[test] + fn extract_skill_mentions_trims_linked_paths_and_allows_spacing() { + assert_mentions("use [$beta] ( /tmp/beta )", &["beta"], &["/tmp/beta"]); + } + + #[test] + fn extract_skill_mentions_stops_at_non_name_chars() { + assert_mentions( + "use $alpha.skill and $beta_extra", + &["alpha", "beta_extra"], + &[], + ); + } + + #[test] + fn collect_explicit_skill_mentions_text_respects_skill_order() { + let alpha = make_skill("alpha-skill", "/tmp/alpha"); + let beta = make_skill("beta-skill", "/tmp/beta"); + let skills = vec![beta.clone(), alpha.clone()]; + let inputs = vec![UserInput::Text { + text: "first $alpha-skill then $beta-skill".to_string(), + text_elements: Vec::new(), + }]; + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + + // Text scanning should not change the previous selection ordering semantics. + assert_eq!(selected, vec![beta, alpha]); + } + + #[test] + fn collect_explicit_skill_mentions_ignores_structured_inputs() { + let alpha = make_skill("alpha-skill", "/tmp/alpha"); + let beta = make_skill("beta-skill", "/tmp/beta"); + let skills = vec![alpha.clone(), beta]; + let inputs = vec![ + UserInput::Text { + text: "please run $alpha-skill".to_string(), + text_elements: Vec::new(), + }, + UserInput::Skill { + name: "beta-skill".to_string(), + path: PathBuf::from("/tmp/beta"), + }, + ]; + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + + assert_eq!(selected, vec![alpha]); + } + + #[test] + fn collect_explicit_skill_mentions_dedupes_by_path() { + let alpha = make_skill("alpha-skill", "/tmp/alpha"); + let skills = vec![alpha.clone()]; + let inputs = vec![UserInput::Text { + text: "use [$alpha-skill](/tmp/alpha) and [$alpha-skill](/tmp/alpha)".to_string(), + text_elements: Vec::new(), + }]; + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + + assert_eq!(selected, vec![alpha]); + } + + #[test] + fn collect_explicit_skill_mentions_dedupes_by_name() { + let alpha = make_skill("demo-skill", "/tmp/alpha"); + let beta = make_skill("demo-skill", "/tmp/beta"); + let skills = vec![alpha.clone(), beta]; + let inputs = vec![UserInput::Text { + text: "use $demo-skill and again $demo-skill".to_string(), + text_elements: Vec::new(), + }]; + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + + assert_eq!(selected, vec![alpha]); + } + + #[test] + fn collect_explicit_skill_mentions_prefers_linked_path_over_name() { + let alpha = make_skill("demo-skill", "/tmp/alpha"); + let beta = make_skill("demo-skill", "/tmp/beta"); + let skills = vec![alpha, beta.clone()]; + let inputs = vec![UserInput::Text { + text: "use $demo-skill and [$demo-skill](/tmp/beta)".to_string(), + text_elements: Vec::new(), + }]; + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + + assert_eq!(selected, vec![beta]); + } + + #[test] + fn collect_explicit_skill_mentions_falls_back_when_linked_path_disabled() { + let alpha = make_skill("demo-skill", "/tmp/alpha"); + let beta = make_skill("demo-skill", "/tmp/beta"); + let skills = vec![alpha, beta.clone()]; + let inputs = vec![UserInput::Text { + text: "use [$demo-skill](/tmp/alpha)".to_string(), + text_elements: Vec::new(), + }]; + let disabled = HashSet::from([PathBuf::from("/tmp/alpha")]); + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &disabled); + + assert_eq!(selected, vec![beta]); + } + + #[test] + fn collect_explicit_skill_mentions_prefers_resource_path() { + let alpha = make_skill("demo-skill", "/tmp/alpha"); + let beta = make_skill("demo-skill", "/tmp/beta"); + let skills = vec![alpha, beta.clone()]; + let inputs = vec![UserInput::Text { + text: "use [$demo-skill](/tmp/beta)".to_string(), + text_elements: Vec::new(), + }]; + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + + assert_eq!(selected, vec![beta]); + } + + #[test] + fn collect_explicit_skill_mentions_falls_back_to_name_when_path_missing() { + let alpha = make_skill("demo-skill", "/tmp/alpha"); + let beta = make_skill("demo-skill", "/tmp/beta"); + let skills = vec![alpha.clone(), beta]; + let inputs = vec![UserInput::Text { + text: "use [$demo-skill](/tmp/missing)".to_string(), + text_elements: Vec::new(), + }]; + + let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + + assert_eq!(selected, vec![alpha]); + } +} diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index a411dd8bc3..581f7d0c1f 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -1,10 +1,12 @@ use crate::config::Config; use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigLayerStackOrdering; +use crate::skills::model::SkillDependencies; use crate::skills::model::SkillError; use crate::skills::model::SkillInterface; use crate::skills::model::SkillLoadOutcome; use crate::skills::model::SkillMetadata; +use crate::skills::model::SkillToolDependency; use crate::skills::system::system_cache_root_dir; use codex_app_server_protocol::ConfigLayerSource; use codex_protocol::protocol::SkillScope; @@ -38,6 +40,8 @@ struct SkillFrontmatterMetadata { struct SkillMetadataFile { #[serde(default)] interface: Option, + #[serde(default)] + dependencies: Option, } #[derive(Debug, Default, Deserialize)] @@ -50,6 +54,23 @@ struct Interface { default_prompt: Option, } +#[derive(Debug, Default, Deserialize)] +struct Dependencies { + #[serde(default)] + tools: Vec, +} + +#[derive(Debug, Default, Deserialize)] +struct DependencyTool { + #[serde(rename = "type")] + kind: Option, + value: Option, + description: Option, + transport: Option, + command: Option, + url: Option, +} + const SKILLS_FILENAME: &str = "SKILL.md"; const SKILLS_JSON_FILENAME: &str = "SKILL.json"; const SKILLS_DIR_NAME: &str = "skills"; @@ -57,6 +78,12 @@ const MAX_NAME_LEN: usize = 64; const MAX_DESCRIPTION_LEN: usize = 1024; const MAX_SHORT_DESCRIPTION_LEN: usize = MAX_DESCRIPTION_LEN; const MAX_DEFAULT_PROMPT_LEN: usize = MAX_DESCRIPTION_LEN; +const MAX_DEPENDENCY_TYPE_LEN: usize = MAX_NAME_LEN; +const MAX_DEPENDENCY_TRANSPORT_LEN: usize = MAX_NAME_LEN; +const MAX_DEPENDENCY_VALUE_LEN: usize = MAX_DESCRIPTION_LEN; +const MAX_DEPENDENCY_DESCRIPTION_LEN: usize = MAX_DESCRIPTION_LEN; +const MAX_DEPENDENCY_COMMAND_LEN: usize = MAX_DESCRIPTION_LEN; +const MAX_DEPENDENCY_URL_LEN: usize = MAX_DESCRIPTION_LEN; // Traversal depth from the skills root. const MAX_SCAN_DEPTH: usize = 6; const MAX_SKILLS_DIRS_PER_ROOT: usize = 2000; @@ -345,7 +372,7 @@ fn parse_skill_file(path: &Path, scope: SkillScope) -> Result Result Option { - // Fail open: optional interface metadata should not block loading SKILL.md. - let skill_dir = skill_path.parent()?; - let interface_path = skill_dir.join(SKILLS_JSON_FILENAME); - if !interface_path.exists() { - return None; +fn load_skill_metadata(skill_path: &Path) -> (Option, Option) { + // Fail open: optional metadata should not block loading SKILL.md. + let Some(skill_dir) = skill_path.parent() else { + return (None, None); + }; + let metadata_path = skill_dir.join(SKILLS_JSON_FILENAME); + if !metadata_path.exists() { + return (None, None); } - let contents = match fs::read_to_string(&interface_path) { + let contents = match fs::read_to_string(&metadata_path) { Ok(contents) => contents, Err(error) => { tracing::warn!( - "ignoring {path}: failed to read SKILL.json: {error}", - path = interface_path.display() + "ignoring {path}: failed to read {label}: {error}", + path = metadata_path.display(), + label = SKILLS_JSON_FILENAME ); - return None; + return (None, None); } }; + let parsed: SkillMetadataFile = match serde_json::from_str(&contents) { Ok(parsed) => parsed, Err(error) => { tracing::warn!( - "ignoring {path}: invalid JSON: {error}", - path = interface_path.display() + "ignoring {path}: invalid {label}: {error}", + path = metadata_path.display(), + label = SKILLS_JSON_FILENAME ); - return None; + return (None, None); } }; - let interface = parsed.interface?; + ( + resolve_interface(parsed.interface, skill_dir), + resolve_dependencies(parsed.dependencies), + ) +} + +fn resolve_interface(interface: Option, skill_dir: &Path) -> Option { + let interface = interface?; let interface = SkillInterface { display_name: resolve_str( interface.display_name, @@ -428,6 +468,58 @@ fn load_skill_interface(skill_path: &Path) -> Option { if has_fields { Some(interface) } else { None } } +fn resolve_dependencies(dependencies: Option) -> Option { + let dependencies = dependencies?; + let tools: Vec = dependencies + .tools + .into_iter() + .filter_map(resolve_dependency_tool) + .collect(); + if tools.is_empty() { + None + } else { + Some(SkillDependencies { tools }) + } +} + +fn resolve_dependency_tool(tool: DependencyTool) -> Option { + let r#type = resolve_required_str( + tool.kind, + MAX_DEPENDENCY_TYPE_LEN, + "dependencies.tools.type", + )?; + let value = resolve_required_str( + tool.value, + MAX_DEPENDENCY_VALUE_LEN, + "dependencies.tools.value", + )?; + let description = resolve_str( + tool.description, + MAX_DEPENDENCY_DESCRIPTION_LEN, + "dependencies.tools.description", + ); + let transport = resolve_str( + tool.transport, + MAX_DEPENDENCY_TRANSPORT_LEN, + "dependencies.tools.transport", + ); + let command = resolve_str( + tool.command, + MAX_DEPENDENCY_COMMAND_LEN, + "dependencies.tools.command", + ); + let url = resolve_str(tool.url, MAX_DEPENDENCY_URL_LEN, "dependencies.tools.url"); + + Some(SkillToolDependency { + r#type, + value, + description, + transport, + command, + url, + }) +} + fn resolve_asset_path( skill_dir: &Path, field: &'static str, @@ -511,6 +603,18 @@ fn resolve_str(value: Option, max_len: usize, field: &'static str) -> Op Some(value) } +fn resolve_required_str( + value: Option, + max_len: usize, + field: &'static str, +) -> Option { + let Some(value) = value else { + tracing::warn!("ignoring {field}: value is missing"); + return None; + }; + resolve_str(Some(value), max_len, field) +} + fn resolve_color_str(value: Option, field: &'static str) -> Option { let value = value?; let value = value.trim(); @@ -755,14 +859,118 @@ mod tests { path } - fn write_skill_interface_at(skill_dir: &Path, contents: &str) -> PathBuf { - let path = skill_dir.join(SKILLS_JSON_FILENAME); + fn write_skill_metadata_at(skill_dir: &Path, filename: &str, contents: &str) -> PathBuf { + let path = skill_dir.join(filename); fs::write(&path, contents).unwrap(); path } + fn write_skill_interface_at(skill_dir: &Path, contents: &str) -> PathBuf { + write_skill_metadata_at(skill_dir, SKILLS_JSON_FILENAME, contents) + } + #[tokio::test] - async fn loads_skill_interface_metadata_happy_path() { + async fn loads_skill_dependencies_metadata_from_json() { + let codex_home = tempfile::tempdir().expect("tempdir"); + let skill_path = write_skill(&codex_home, "demo", "dep-skill", "from json"); + let skill_dir = skill_path.parent().expect("skill dir"); + + write_skill_metadata_at( + skill_dir, + SKILLS_JSON_FILENAME, + r#" +{ + "dependencies": { + "tools": [ + { + "type": "env_var", + "value": "GITHUB_TOKEN", + "description": "GitHub API token with repo scopes" + }, + { + "type": "mcp", + "value": "github", + "description": "GitHub MCP server", + "transport": "streamable_http", + "url": "https://example.com/mcp" + }, + { + "type": "cli", + "value": "gh", + "description": "GitHub CLI" + }, + { + "type": "mcp", + "value": "local-gh", + "description": "Local GH MCP server", + "transport": "stdio", + "command": "gh-mcp" + } + ] + } +} +"#, + ); + + let cfg = make_config(&codex_home).await; + let outcome = load_skills(&cfg); + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![SkillMetadata { + name: "dep-skill".to_string(), + description: "from json".to_string(), + short_description: None, + interface: None, + dependencies: Some(SkillDependencies { + tools: vec![ + SkillToolDependency { + r#type: "env_var".to_string(), + value: "GITHUB_TOKEN".to_string(), + description: Some("GitHub API token with repo scopes".to_string()), + transport: None, + command: None, + url: None, + }, + SkillToolDependency { + r#type: "mcp".to_string(), + value: "github".to_string(), + description: Some("GitHub MCP server".to_string()), + transport: Some("streamable_http".to_string()), + command: None, + url: Some("https://example.com/mcp".to_string()), + }, + SkillToolDependency { + r#type: "cli".to_string(), + value: "gh".to_string(), + description: Some("GitHub CLI".to_string()), + transport: None, + command: None, + url: None, + }, + SkillToolDependency { + r#type: "mcp".to_string(), + value: "local-gh".to_string(), + description: Some("Local GH MCP server".to_string()), + transport: Some("stdio".to_string()), + command: Some("gh-mcp".to_string()), + url: None, + }, + ], + }), + path: normalized(&skill_path), + scope: SkillScope::User, + }] + ); + } + + #[tokio::test] + async fn loads_skill_interface_metadata_from_json() { let codex_home = tempfile::tempdir().expect("tempdir"); let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); @@ -806,6 +1014,7 @@ mod tests { brand_color: Some("#3B82F6".to_string()), default_prompt: Some("default prompt".to_string()), }), + dependencies: None, path: normalized(skill_path.as_path()), scope: SkillScope::User, }] @@ -854,6 +1063,7 @@ mod tests { brand_color: None, default_prompt: None, }), + dependencies: None, path: normalized(&skill_path), scope: SkillScope::User, }] @@ -892,6 +1102,7 @@ mod tests { description: "from json".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::User, }] @@ -943,6 +1154,7 @@ mod tests { brand_color: None, default_prompt: None, }), + dependencies: None, path: normalized(&skill_path), scope: SkillScope::User, }] @@ -982,6 +1194,7 @@ mod tests { description: "from json".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::User, }] @@ -1024,6 +1237,7 @@ mod tests { description: "from link".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&shared_skill_path), scope: SkillScope::User, }] @@ -1082,6 +1296,7 @@ mod tests { description: "still loads".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::User, }] @@ -1116,6 +1331,7 @@ mod tests { description: "from link".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&shared_skill_path), scope: SkillScope::Admin, }] @@ -1154,6 +1370,7 @@ mod tests { description: "from link".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&linked_skill_path), scope: SkillScope::Repo, }] @@ -1215,6 +1432,7 @@ mod tests { description: "loads".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&within_depth_path), scope: SkillScope::User, }] @@ -1240,6 +1458,7 @@ mod tests { description: "does things carefully".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::User, }] @@ -1269,6 +1488,7 @@ mod tests { description: "long description".to_string(), short_description: Some("short summary".to_string()), interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::User, }] @@ -1379,6 +1599,7 @@ mod tests { description: "from repo".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -1430,6 +1651,7 @@ mod tests { description: "from nested".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&nested_skill_path), scope: SkillScope::Repo, }, @@ -1438,6 +1660,7 @@ mod tests { description: "from root".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&root_skill_path), scope: SkillScope::Repo, }, @@ -1475,6 +1698,7 @@ mod tests { description: "from cwd".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -1510,6 +1734,7 @@ mod tests { description: "from repo".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -1549,6 +1774,7 @@ mod tests { description: "from repo".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&repo_skill_path), scope: SkillScope::Repo, }, @@ -1557,6 +1783,7 @@ mod tests { description: "from user".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&user_skill_path), scope: SkillScope::User, }, @@ -1619,6 +1846,7 @@ mod tests { description: first_description.to_string(), short_description: None, interface: None, + dependencies: None, path: first_path, scope: SkillScope::Repo, }, @@ -1627,6 +1855,7 @@ mod tests { description: second_description.to_string(), short_description: None, interface: None, + dependencies: None, path: second_path, scope: SkillScope::Repo, }, @@ -1696,6 +1925,7 @@ mod tests { description: "from repo".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -1752,6 +1982,7 @@ mod tests { description: "from system".to_string(), short_description: None, interface: None, + dependencies: None, path: normalized(&skill_path), scope: SkillScope::System, }] diff --git a/codex-rs/core/src/skills/mod.rs b/codex-rs/core/src/skills/mod.rs index cf7c180502..ae4ffa2920 100644 --- a/codex-rs/core/src/skills/mod.rs +++ b/codex-rs/core/src/skills/mod.rs @@ -7,6 +7,7 @@ pub mod system; pub(crate) use injection::SkillInjections; pub(crate) use injection::build_skill_injections; +pub(crate) use injection::collect_explicit_skill_mentions; pub use loader::load_skills; pub use manager::SkillsManager; pub use model::SkillError; diff --git a/codex-rs/core/src/skills/model.rs b/codex-rs/core/src/skills/model.rs index fe3357f9d9..92ecbd84b9 100644 --- a/codex-rs/core/src/skills/model.rs +++ b/codex-rs/core/src/skills/model.rs @@ -9,6 +9,7 @@ pub struct SkillMetadata { pub description: String, pub short_description: Option, pub interface: Option, + pub dependencies: Option, pub path: PathBuf, pub scope: SkillScope, } @@ -23,6 +24,21 @@ pub struct SkillInterface { pub default_prompt: Option, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SkillDependencies { + pub tools: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SkillToolDependency { + pub r#type: String, + pub value: String, + pub description: Option, + pub transport: Option, + pub command: Option, + pub url: Option, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct SkillError { pub path: PathBuf, diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 067f7b3378..9d3d96db99 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_protocol::models::ResponseItem; +use std::collections::HashSet; use crate::codex::SessionConfiguration; use crate::context_manager::ContextManager; @@ -15,6 +16,7 @@ pub(crate) struct SessionState { pub(crate) history: ContextManager, pub(crate) latest_rate_limits: Option, pub(crate) server_reasoning_included: bool, + 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 @@ -31,6 +33,7 @@ impl SessionState { history, latest_rate_limits: None, server_reasoning_included: false, + mcp_dependency_prompted: HashSet::new(), initial_context_seeded: false, } } @@ -98,6 +101,17 @@ impl SessionState { pub(crate) fn server_reasoning_included(&self) -> bool { self.server_reasoning_included } + + pub(crate) fn record_mcp_dependency_prompted(&mut self, names: I) + where + I: IntoIterator, + { + self.mcp_dependency_prompted.extend(names); + } + + pub(crate) fn mcp_dependency_prompted(&self) -> HashSet { + self.mcp_dependency_prompted.clone() + } } // Sometimes new snapshots don't include credits or plan information. diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index c2d282e995..b9a4f2120b 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -2093,11 +2093,14 @@ pub struct SkillMetadata { pub description: String, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] - /// Legacy short_description from SKILL.md. Prefer SKILL.toml interface.short_description. + /// Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description. pub short_description: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub interface: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub dependencies: Option, pub path: PathBuf, pub scope: SkillScope, pub enabled: bool, @@ -2119,6 +2122,31 @@ pub struct SkillInterface { pub default_prompt: Option, } +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS, PartialEq, Eq)] +pub struct SkillDependencies { + pub tools: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS, PartialEq, Eq)] +pub struct SkillToolDependency { + #[serde(rename = "type")] + #[ts(rename = "type")] + pub r#type: String, + pub value: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub transport: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub command: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub url: Option, +} + #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct SkillErrorInfo { pub path: PathBuf, diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index bbd59c58bd..e0a7319a42 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -1154,6 +1154,7 @@ mod tests { description: "test skill".to_string(), short_description: None, interface: None, + dependencies: None, path: PathBuf::from("test-skill"), scope: SkillScope::User, }]), diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index d72ca60455..d6893a9e3c 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -15,8 +15,10 @@ use crate::skills_helpers::skill_display_name; 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; impl ChatWidget { pub(crate) fn open_skills_list(&mut self) { @@ -168,6 +170,23 @@ fn protocol_skill_to_core(skill: &ProtocolSkillMetadata) -> SkillMetadata { brand_color: interface.brand_color, default_prompt: interface.default_prompt, }), + dependencies: skill + .dependencies + .clone() + .map(|dependencies| SkillDependencies { + tools: dependencies + .tools + .into_iter() + .map(|tool| SkillToolDependency { + r#type: tool.r#type, + value: tool.value, + description: tool.description, + transport: tool.transport, + command: tool.command, + url: tool.url, + }) + .collect(), + }), path: skill.path.clone(), scope: skill.scope, } From fef3e36f67b831793283b5165b4cfd9b43acb94f Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Tue, 27 Jan 2026 21:15:15 -0700 Subject: [PATCH 027/116] fix(core) info cleanup (#9986) ## Summary Simplify this logic a bit. --- codex-rs/core/src/models_manager/model_info.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/codex-rs/core/src/models_manager/model_info.rs b/codex-rs/core/src/models_manager/model_info.rs index c07c144c11..5d8d0d2937 100644 --- a/codex-rs/core/src/models_manager/model_info.rs +++ b/codex-rs/core/src/models_manager/model_info.rs @@ -259,9 +259,7 @@ pub(crate) fn find_model_info_for_slug(slug: &str) -> ModelInfo { truncation_policy: TruncationPolicyConfig::tokens(10_000), context_window: Some(CONTEXT_WINDOW_272K), ) - } else if (slug.starts_with("gpt-5.2") || slug.starts_with("boomslang")) - && !slug.contains("codex") - { + } else if slug.starts_with("gpt-5.2") || slug.starts_with("boomslang") { model_info!( slug, apply_patch_tool_type: Some(ApplyPatchToolType::Freeform), @@ -276,7 +274,7 @@ pub(crate) fn find_model_info_for_slug(slug: &str) -> ModelInfo { context_window: Some(CONTEXT_WINDOW_272K), supported_reasoning_levels: supported_reasoning_level_low_medium_high_xhigh_non_codex(), ) - } else if slug.starts_with("gpt-5.1") && !slug.contains("codex") { + } else if slug.starts_with("gpt-5.1") { model_info!( slug, apply_patch_tool_type: Some(ApplyPatchToolType::Freeform), From 9f793656910c66f5c7e77e3be87d8cafb8fadaf0 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Tue, 27 Jan 2026 23:06:10 -0800 Subject: [PATCH 028/116] error code/msg details for failed elevated setup (#9941) --- codex-rs/core/src/windows_sandbox.rs | 13 + codex-rs/tui/src/app.rs | 19 +- codex-rs/windows-sandbox-rs/src/firewall.rs | 128 ++++++-- codex-rs/windows-sandbox-rs/src/lib.rs | 17 + .../windows-sandbox-rs/src/sandbox_users.rs | 80 ++++- .../windows-sandbox-rs/src/setup_error.rs | 296 ++++++++++++++++++ .../windows-sandbox-rs/src/setup_main_win.rs | 176 +++++++++-- .../src/setup_orchestrator.rs | 106 ++++++- 8 files changed, 759 insertions(+), 76 deletions(-) create mode 100644 codex-rs/windows-sandbox-rs/src/setup_error.rs diff --git a/codex-rs/core/src/windows_sandbox.rs b/codex-rs/core/src/windows_sandbox.rs index 45212e1d48..22825752b2 100644 --- a/codex-rs/core/src/windows_sandbox.rs +++ b/codex-rs/core/src/windows_sandbox.rs @@ -52,6 +52,19 @@ pub fn sandbox_setup_is_complete(_codex_home: &Path) -> bool { false } +#[cfg(target_os = "windows")] +pub fn elevated_setup_failure_details(err: &anyhow::Error) -> Option<(String, String)> { + let failure = codex_windows_sandbox::extract_setup_failure(err)?; + let code = failure.code.as_str().to_string(); + let message = codex_windows_sandbox::sanitize_setup_metric_tag_value(&failure.message); + Some((code, message)) +} + +#[cfg(not(target_os = "windows"))] +pub fn elevated_setup_failure_details(_err: &anyhow::Error) -> Option<(String, String)> { + None +} + #[cfg(target_os = "windows")] pub fn run_elevated_setup( policy: &SandboxPolicy, diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 87f232ed2b..4e9cfb3fcd 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1632,10 +1632,27 @@ impl App { } } Err(err) => { + let mut code_tag: Option = None; + let mut message_tag: Option = None; + if let Some((code, message)) = + codex_core::windows_sandbox::elevated_setup_failure_details( + &err, + ) + { + code_tag = Some(code); + message_tag = Some(message); + } + let mut tags: Vec<(&str, &str)> = Vec::new(); + if let Some(code) = code_tag.as_deref() { + tags.push(("code", code)); + } + if let Some(message) = message_tag.as_deref() { + tags.push(("message", message)); + } otel_manager.counter( "codex.windows_sandbox.elevated_setup_failure", 1, - &[], + &tags, ); tracing::error!( error = %err, diff --git a/codex-rs/windows-sandbox-rs/src/firewall.rs b/codex-rs/windows-sandbox-rs/src/firewall.rs index c75214bb36..b4939fd42b 100644 --- a/codex-rs/windows-sandbox-rs/src/firewall.rs +++ b/codex-rs/windows-sandbox-rs/src/firewall.rs @@ -21,6 +21,9 @@ use windows::Win32::System::Com::CoUninitialize; use windows::Win32::System::Com::CLSCTX_INPROC_SERVER; use windows::Win32::System::Com::COINIT_APARTMENTTHREADED; +use codex_windows_sandbox::SetupErrorCode; +use codex_windows_sandbox::SetupFailure; + // This is the stable identifier we use to find/update the rule idempotently. // It intentionally does not change between installs. const OFFLINE_BLOCK_RULE_NAME: &str = "codex_sandbox_offline_block_outbound"; @@ -33,16 +36,27 @@ pub fn ensure_offline_outbound_block(offline_sid: &str, log: &mut File) -> Resul let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; if hr.is_err() { - return Err(anyhow::anyhow!("CoInitializeEx failed: {hr:?}")); + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallComInitFailed, + format!("CoInitializeEx failed: {hr:?}"), + ))); } let result = unsafe { (|| -> Result<()> { let policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER) - .map_err(|e| anyhow::anyhow!("CoCreateInstance NetFwPolicy2: {e:?}"))?; - let rules = policy - .Rules() - .map_err(|e| anyhow::anyhow!("INetFwPolicy2::Rules: {e:?}"))?; + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallPolicyAccessFailed, + format!("CoCreateInstance NetFwPolicy2 failed: {err:?}"), + )) + })?; + let rules = policy.Rules().map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallPolicyAccessFailed, + format!("INetFwPolicy2::Rules failed: {err:?}"), + )) + })?; // Block all outbound IP protocols for this user. ensure_block_rule( @@ -75,14 +89,28 @@ fn ensure_block_rule( ) -> Result<()> { let name = BSTR::from(internal_name); let rule: INetFwRule3 = match unsafe { rules.Item(&name) } { - Ok(existing) => existing - .cast() - .map_err(|e| anyhow::anyhow!("cast existing firewall rule to INetFwRule3: {e:?}"))?, + Ok(existing) => existing.cast().map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("cast existing firewall rule to INetFwRule3 failed: {err:?}"), + )) + })?, Err(_) => { let new_rule: INetFwRule3 = - unsafe { CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER) } - .map_err(|e| anyhow::anyhow!("CoCreateInstance NetFwRule: {e:?}"))?; - unsafe { new_rule.SetName(&name) }.map_err(|e| anyhow::anyhow!("SetName: {e:?}"))?; + unsafe { CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER) }.map_err( + |err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("CoCreateInstance NetFwRule failed: {err:?}"), + )) + }, + )?; + unsafe { new_rule.SetName(&name) }.map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetName failed: {err:?}"), + )) + })?; // Set all properties before adding the rule so we don't leave half-configured rules. configure_rule( &new_rule, @@ -91,7 +119,12 @@ fn ensure_block_rule( local_user_spec, offline_sid, )?; - unsafe { rules.Add(&new_rule) }.map_err(|e| anyhow::anyhow!("Rules::Add: {e:?}"))?; + unsafe { rules.Add(&new_rule) }.map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("Rules::Add failed: {err:?}"), + )) + })?; new_rule } }; @@ -117,29 +150,66 @@ fn configure_rule( ) -> Result<()> { unsafe { rule.SetDescription(&BSTR::from(friendly_desc)) - .map_err(|e| anyhow::anyhow!("SetDescription: {e:?}"))?; - rule.SetDirection(NET_FW_RULE_DIR_OUT) - .map_err(|e| anyhow::anyhow!("SetDirection: {e:?}"))?; - rule.SetAction(NET_FW_ACTION_BLOCK) - .map_err(|e| anyhow::anyhow!("SetAction: {e:?}"))?; - rule.SetEnabled(VARIANT_TRUE) - .map_err(|e| anyhow::anyhow!("SetEnabled: {e:?}"))?; - rule.SetProfiles(NET_FW_PROFILE2_ALL.0) - .map_err(|e| anyhow::anyhow!("SetProfiles: {e:?}"))?; - rule.SetProtocol(protocol) - .map_err(|e| anyhow::anyhow!("SetProtocol: {e:?}"))?; + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetDescription failed: {err:?}"), + )) + })?; + rule.SetDirection(NET_FW_RULE_DIR_OUT).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetDirection failed: {err:?}"), + )) + })?; + rule.SetAction(NET_FW_ACTION_BLOCK).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetAction failed: {err:?}"), + )) + })?; + rule.SetEnabled(VARIANT_TRUE).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetEnabled failed: {err:?}"), + )) + })?; + rule.SetProfiles(NET_FW_PROFILE2_ALL.0).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetProfiles failed: {err:?}"), + )) + })?; + rule.SetProtocol(protocol).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetProtocol failed: {err:?}"), + )) + })?; rule.SetLocalUserAuthorizedList(&BSTR::from(local_user_spec)) - .map_err(|e| anyhow::anyhow!("SetLocalUserAuthorizedList: {e:?}"))?; + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("SetLocalUserAuthorizedList failed: {err:?}"), + )) + })?; } // Read-back verification: ensure we actually wrote the expected SID scope. - let actual = unsafe { rule.LocalUserAuthorizedList() } - .map_err(|e| anyhow::anyhow!("LocalUserAuthorizedList (read-back): {e:?}"))?; + let actual = unsafe { rule.LocalUserAuthorizedList() }.map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleVerifyFailed, + format!("LocalUserAuthorizedList (read-back) failed: {err:?}"), + )) + })?; let actual_str = actual.to_string(); if !actual_str.contains(offline_sid) { - anyhow::bail!( - "offline firewall rule user scope mismatch: expected SID {offline_sid}, got {actual_str}" - ); + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleVerifyFailed, + format!( + "offline firewall rule user scope mismatch: expected SID {offline_sid}, got {actual_str}" + ), + ))); } Ok(()) } diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index 62fda67655..fc062d6fd5 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -16,6 +16,9 @@ mod setup; #[cfg(target_os = "windows")] mod elevated_impl; +#[cfg(target_os = "windows")] +mod setup_error; + #[cfg(target_os = "windows")] pub use acl::allow_null_device; #[cfg(target_os = "windows")] @@ -67,6 +70,20 @@ pub use setup::sandbox_secrets_dir; #[cfg(target_os = "windows")] pub use setup::SETUP_VERSION; #[cfg(target_os = "windows")] +pub use setup_error::extract_failure as extract_setup_failure; +#[cfg(target_os = "windows")] +pub use setup_error::sanitize_tag_value as sanitize_setup_metric_tag_value; +#[cfg(target_os = "windows")] +pub use setup_error::setup_error_path; +#[cfg(target_os = "windows")] +pub use setup_error::write_setup_error_report; +#[cfg(target_os = "windows")] +pub use setup_error::SetupErrorCode; +#[cfg(target_os = "windows")] +pub use setup_error::SetupErrorReport; +#[cfg(target_os = "windows")] +pub use setup_error::SetupFailure; +#[cfg(target_os = "windows")] pub use token::convert_string_sid_to_sid; #[cfg(target_os = "windows")] pub use token::create_readonly_token_with_cap_from; diff --git a/codex-rs/windows-sandbox-rs/src/sandbox_users.rs b/codex-rs/windows-sandbox-rs/src/sandbox_users.rs index 5847363efb..5ab39c3cec 100644 --- a/codex-rs/windows-sandbox-rs/src/sandbox_users.rs +++ b/codex-rs/windows-sandbox-rs/src/sandbox_users.rs @@ -39,6 +39,8 @@ use codex_windows_sandbox::sandbox_dir; use codex_windows_sandbox::sandbox_secrets_dir; use codex_windows_sandbox::string_from_sid_bytes; use codex_windows_sandbox::to_wide; +use codex_windows_sandbox::SetupErrorCode; +use codex_windows_sandbox::SetupFailure; use codex_windows_sandbox::SETUP_VERSION; pub const SANDBOX_USERS_GROUP: &str = "CodexSandboxUsers"; @@ -122,9 +124,10 @@ pub fn ensure_local_user(name: &str, password: &str, log: &mut File) -> Result<( ); if upd != NERR_Success { super::log_line(log, &format!("NetUserSetInfo failed for {name} code {upd}"))?; - return Err(anyhow::anyhow!( - "failed to create/update user {name}, code {status}/{upd}" - )); + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUserCreateOrUpdateFailed, + format!("failed to create/update user {name}, code {status}/{upd}"), + ))); } } @@ -174,7 +177,10 @@ pub fn ensure_local_group(name: &str, comment: &str, log: &mut File) -> Result<( log, &format!("NetLocalGroupAdd failed for {name} code {status} parm_err={parm_err}"), )?; - anyhow::bail!("failed to create local group {name}, code {status}"); + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUsersGroupCreateFailed, + format!("failed to create local group {name}, code {status}"), + ))); } } Ok(()) @@ -394,11 +400,37 @@ fn write_secrets( online_pwd: &str, ) -> Result<()> { let sandbox_dir = sandbox_dir(codex_home); - std::fs::create_dir_all(&sandbox_dir)?; + std::fs::create_dir_all(&sandbox_dir).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUsersFileWriteFailed, + format!( + "failed to create sandbox dir {}: {err}", + sandbox_dir.display() + ), + )) + })?; let secrets_dir = sandbox_secrets_dir(codex_home); - std::fs::create_dir_all(&secrets_dir)?; - let offline_blob = dpapi_protect(offline_pwd.as_bytes())?; - let online_blob = dpapi_protect(online_pwd.as_bytes())?; + std::fs::create_dir_all(&secrets_dir).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUsersFileWriteFailed, + format!( + "failed to create secrets dir {}: {err}", + secrets_dir.display() + ), + )) + })?; + let offline_blob = dpapi_protect(offline_pwd.as_bytes()).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperDpapiProtectFailed, + format!("dpapi protect failed for offline user: {err}"), + )) + })?; + let online_blob = dpapi_protect(online_pwd.as_bytes()).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperDpapiProtectFailed, + format!("dpapi protect failed for online user: {err}"), + )) + })?; let users = SandboxUsersFile { version: SETUP_VERSION, offline: SandboxUserRecord { @@ -420,7 +452,35 @@ fn write_secrets( }; let users_path = secrets_dir.join("sandbox_users.json"); let marker_path = sandbox_dir.join("setup_marker.json"); - std::fs::write(users_path, serde_json::to_vec_pretty(&users)?)?; - std::fs::write(marker_path, serde_json::to_vec_pretty(&marker)?)?; + let users_json = serde_json::to_vec_pretty(&users).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUsersFileWriteFailed, + format!("serialize sandbox users failed: {err}"), + )) + })?; + std::fs::write(&users_path, users_json).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUsersFileWriteFailed, + format!( + "write sandbox users file {} failed: {err}", + users_path.display() + ), + )) + })?; + let marker_json = serde_json::to_vec_pretty(&marker).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSetupMarkerWriteFailed, + format!("serialize setup marker failed: {err}"), + )) + })?; + std::fs::write(&marker_path, marker_json).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSetupMarkerWriteFailed, + format!( + "write setup marker file {} failed: {err}", + marker_path.display() + ), + )) + })?; Ok(()) } diff --git a/codex-rs/windows-sandbox-rs/src/setup_error.rs b/codex-rs/windows-sandbox-rs/src/setup_error.rs new file mode 100644 index 0000000000..21d260b4d4 --- /dev/null +++ b/codex-rs/windows-sandbox-rs/src/setup_error.rs @@ -0,0 +1,296 @@ +use anyhow::Context; +use anyhow::Result; +use serde::Deserialize; +use serde::Serialize; +use std::fs; +use std::io::ErrorKind; +use std::path::Path; +use std::path::PathBuf; + +/// These represent the most common failures for the elevated sandbox setup. +/// +/// Codes are used as metric tags. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SetupErrorCode { + // Orchestrator (run in CLI) failures. + /// Failed to create `codex_home/.sandbox` in the orchestrator. + OrchestratorSandboxDirCreateFailed, + /// Failed to determine whether the current process is elevated. + OrchestratorElevationCheckFailed, + /// Failed to serialize the elevation payload before launching the helper. + OrchestratorPayloadSerializeFailed, + /// Failed to launch the setup helper process (spawn or ShellExecuteExW). + OrchestratorHelperLaunchFailed, + /// Helper exited non-zero and no structured report was available. + OrchestratorHelperExitNonzero, + /// Helper exited non-zero and reading `setup_error.json` failed. + OrchestratorHelperReportReadFailed, + // Helper (elevated process) failures. + /// Helper failed while validating or decoding the request payload. + HelperRequestArgsFailed, + /// Helper failed to create `codex_home/.sandbox`. + HelperSandboxDirCreateFailed, + /// Helper failed to open or write the setup log. + HelperLogFailed, + /// Helper failed in the provisioning phase (fallback bucket). + HelperUserProvisionFailed, + /// Helper failed to create the sandbox users local group. + HelperUsersGroupCreateFailed, + /// Helper failed to create or update a sandbox user account. + HelperUserCreateOrUpdateFailed, + /// Helper failed to protect user passwords with DPAPI. + HelperDpapiProtectFailed, + /// Helper failed to write the sandbox users secrets file. + HelperUsersFileWriteFailed, + /// Helper failed to write the setup marker file. + HelperSetupMarkerWriteFailed, + /// Helper failed to resolve a SID or convert it to a PSID. + HelperSidResolveFailed, + /// Helper failed to load or convert capability SIDs. + HelperCapabilitySidFailed, + /// Helper failed to initialize COM for firewall configuration. + HelperFirewallComInitFailed, + /// Helper failed to access firewall policy or rule collections. + HelperFirewallPolicyAccessFailed, + /// Helper failed to create, update, or add the firewall rule. + HelperFirewallRuleCreateOrAddFailed, + /// Helper failed to verify the configured firewall rule scope. + HelperFirewallRuleVerifyFailed, + /// Helper failed to spawn the read-ACL helper process. + HelperReadAclHelperSpawnFailed, + /// Helper failed to lock down sandbox directories via ACLs. + HelperSandboxLockFailed, + /// Helper failed for an unmapped or unexpected reason. + HelperUnknownError, +} + +impl SetupErrorCode { + pub fn as_str(self) -> &'static str { + match self { + Self::OrchestratorSandboxDirCreateFailed => "orchestrator_sandbox_dir_create_failed", + Self::OrchestratorElevationCheckFailed => "orchestrator_elevation_check_failed", + Self::OrchestratorPayloadSerializeFailed => "orchestrator_payload_serialize_failed", + Self::OrchestratorHelperLaunchFailed => "orchestrator_helper_launch_failed", + Self::OrchestratorHelperExitNonzero => "orchestrator_helper_exit_nonzero", + Self::OrchestratorHelperReportReadFailed => "orchestrator_helper_report_read_failed", + Self::HelperRequestArgsFailed => "helper_request_args_failed", + Self::HelperSandboxDirCreateFailed => "helper_sandbox_dir_create_failed", + Self::HelperLogFailed => "helper_log_failed", + Self::HelperUserProvisionFailed => "helper_user_provision_failed", + Self::HelperUsersGroupCreateFailed => "helper_users_group_create_failed", + Self::HelperUserCreateOrUpdateFailed => "helper_user_create_or_update_failed", + Self::HelperDpapiProtectFailed => "helper_dpapi_protect_failed", + Self::HelperUsersFileWriteFailed => "helper_users_file_write_failed", + Self::HelperSetupMarkerWriteFailed => "helper_setup_marker_write_failed", + Self::HelperSidResolveFailed => "helper_sid_resolve_failed", + Self::HelperCapabilitySidFailed => "helper_capability_sid_failed", + Self::HelperFirewallComInitFailed => "helper_firewall_com_init_failed", + Self::HelperFirewallPolicyAccessFailed => "helper_firewall_policy_access_failed", + Self::HelperFirewallRuleCreateOrAddFailed => { + "helper_firewall_rule_create_or_add_failed" + } + Self::HelperFirewallRuleVerifyFailed => "helper_firewall_rule_verify_failed", + Self::HelperReadAclHelperSpawnFailed => "helper_read_acl_helper_spawn_failed", + Self::HelperSandboxLockFailed => "helper_sandbox_lock_failed", + Self::HelperUnknownError => "helper_unknown_error", + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SetupErrorReport { + pub code: SetupErrorCode, + pub message: String, +} + +#[derive(Debug)] +pub struct SetupFailure { + pub code: SetupErrorCode, + pub message: String, +} + +impl SetupFailure { + pub fn new(code: SetupErrorCode, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } + + pub fn from_report(report: SetupErrorReport) -> Self { + Self::new(report.code, report.message) + } + + pub fn metric_message(&self) -> String { + sanitize_tag_value(&self.message) + } +} + +impl std::fmt::Display for SetupFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.code.as_str(), self.message) + } +} + +impl std::error::Error for SetupFailure {} + +pub fn failure(code: SetupErrorCode, message: impl Into) -> anyhow::Error { + anyhow::Error::new(SetupFailure::new(code, message)) +} + +pub fn extract_failure(err: &anyhow::Error) -> Option<&SetupFailure> { + err.downcast_ref::() +} + +pub fn setup_error_path(codex_home: &Path) -> PathBuf { + codex_home.join(".sandbox").join("setup_error.json") +} + +pub fn clear_setup_error_report(codex_home: &Path) -> Result<()> { + let path = setup_error_path(codex_home); + match fs::remove_file(&path) { + Ok(()) => Ok(()), + Err(err) if err.kind() == ErrorKind::NotFound => Ok(()), + Err(err) => Err(err).with_context(|| format!("remove {}", path.display())), + } +} + +pub fn write_setup_error_report(codex_home: &Path, report: &SetupErrorReport) -> Result<()> { + let sandbox_dir = codex_home.join(".sandbox"); + fs::create_dir_all(&sandbox_dir) + .with_context(|| format!("create sandbox dir {}", sandbox_dir.display()))?; + let path = setup_error_path(codex_home); + let json = serde_json::to_vec_pretty(report)?; + fs::write(&path, json).with_context(|| format!("write {}", path.display()))?; + Ok(()) +} + +pub fn read_setup_error_report(codex_home: &Path) -> Result> { + let path = setup_error_path(codex_home); + let bytes = match fs::read(&path) { + Ok(bytes) => bytes, + Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None), + Err(err) => return Err(err).with_context(|| format!("read {}", path.display())), + }; + let report = serde_json::from_slice::(&bytes) + .with_context(|| format!("parse {}", path.display()))?; + Ok(Some(report)) +} + +/// Sanitize a tag value to comply with metric tag validation rules: +/// only ASCII alphanumeric, '.', '_', '-', and '/' are allowed. +pub fn sanitize_tag_value(value: &str) -> String { + const MAX_LEN: usize = 256; + let redacted = redact_home_paths(value); + let sanitized: String = redacted + .chars() + .map(|ch| { + if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-' | '/') { + ch + } else { + '_' + } + }) + .collect(); + let trimmed = sanitized.trim_matches('_'); + if trimmed.is_empty() { + return "unspecified".to_string(); + } + if trimmed.len() <= MAX_LEN { + trimmed.to_string() + } else { + trimmed[..MAX_LEN].to_string() + } +} + +fn redact_home_paths(value: &str) -> String { + let mut usernames: Vec = Vec::new(); + if let Ok(username) = std::env::var("USERNAME") { + if !username.trim().is_empty() { + usernames.push(username); + } + } + if let Ok(user) = std::env::var("USER") { + if !user.trim().is_empty() && !usernames.iter().any(|v| v.eq_ignore_ascii_case(&user)) { + usernames.push(user); + } + } + + redact_username_segments(value, &usernames) +} + +fn redact_username_segments(value: &str, usernames: &[String]) -> String { + if usernames.is_empty() { + return value.to_string(); + } + + let mut segments: Vec = Vec::new(); + let mut separators: Vec = Vec::new(); + let mut current = String::new(); + + for ch in value.chars() { + if ch == '\\' || ch == '/' { + segments.push(std::mem::take(&mut current)); + separators.push(ch); + } else { + current.push(ch); + } + } + segments.push(current); + + for segment in &mut segments { + let matches = if cfg!(windows) { + usernames + .iter() + .any(|name| segment.eq_ignore_ascii_case(name)) + } else { + usernames.iter().any(|name| segment == name) + }; + if matches { + *segment = "".to_string(); + } + } + + let mut out = String::new(); + for (idx, segment) in segments.iter().enumerate() { + out.push_str(segment); + if let Some(sep) = separators.get(idx) { + out.push(*sep); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn sanitize_tag_value_redacts_username_segments() { + let usernames = vec!["Alice".to_string(), "Bob".to_string()]; + let msg = "failed to write C:\\Users\\Alice\\file.txt; fallback D:\\Profiles\\Bob\\x"; + let redacted = redact_username_segments(msg, &usernames); + assert_eq!( + redacted, + "failed to write C:\\Users\\\\file.txt; fallback D:\\Profiles\\\\x" + ); + } + + #[test] + fn sanitize_tag_value_leaves_unknown_segments() { + let usernames = vec!["Alice".to_string()]; + let msg = "failed to write E:\\data\\file.txt"; + let redacted = redact_username_segments(msg, &usernames); + assert_eq!(redacted, msg); + } + + #[test] + fn sanitize_tag_value_redacts_multiple_occurrences() { + let usernames = vec!["Alice".to_string()]; + let msg = "C:\\Users\\Alice\\a and C:\\Users\\Alice\\b"; + let redacted = redact_username_segments(msg, &usernames); + assert_eq!(redacted, "C:\\Users\\\\a and C:\\Users\\\\b"); + } +} 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 39c8a95d4c..6868028782 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_main_win.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_main_win.rs @@ -9,6 +9,7 @@ use base64::Engine; use codex_windows_sandbox::convert_string_sid_to_sid; use codex_windows_sandbox::ensure_allow_mask_aces_with_inheritance; use codex_windows_sandbox::ensure_allow_write_aces; +use codex_windows_sandbox::extract_setup_failure; use codex_windows_sandbox::hide_newly_created_users; use codex_windows_sandbox::load_or_create_cap_sids; use codex_windows_sandbox::log_note; @@ -17,6 +18,10 @@ use codex_windows_sandbox::sandbox_dir; use codex_windows_sandbox::sandbox_secrets_dir; use codex_windows_sandbox::string_from_sid_bytes; use codex_windows_sandbox::to_wide; +use codex_windows_sandbox::write_setup_error_report; +use codex_windows_sandbox::SetupErrorCode; +use codex_windows_sandbox::SetupErrorReport; +use codex_windows_sandbox::SetupFailure; use codex_windows_sandbox::LOG_FILE_NAME; use codex_windows_sandbox::SETUP_VERSION; use serde::Deserialize; @@ -89,7 +94,12 @@ enum SetupMode { fn log_line(log: &mut File, msg: &str) -> Result<()> { let ts = chrono::Utc::now().to_rfc3339(); - writeln!(log, "[{ts}] {msg}")?; + writeln!(log, "[{ts}] {msg}").map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperLogFailed, + format!("failed to write setup log line: {err}"), + )) + })?; Ok(()) } @@ -349,29 +359,74 @@ pub fn main() -> Result<()> { fn real_main() -> Result<()> { let mut args = std::env::args().collect::>(); if args.len() != 2 { - anyhow::bail!("expected payload argument"); + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperRequestArgsFailed, + "expected payload argument", + ))); } let payload_b64 = args.remove(1); - let payload_json = BASE64 - .decode(payload_b64) - .context("failed to decode payload b64")?; - let payload: Payload = - serde_json::from_slice(&payload_json).context("failed to parse payload json")?; + let payload_json = BASE64.decode(payload_b64).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperRequestArgsFailed, + format!("failed to decode payload b64: {err}"), + )) + })?; + let payload: Payload = serde_json::from_slice(&payload_json).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperRequestArgsFailed, + format!("failed to parse payload json: {err}"), + )) + })?; if payload.version != SETUP_VERSION { - anyhow::bail!("setup version mismatch"); + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperRequestArgsFailed, + format!( + "setup version mismatch: expected {SETUP_VERSION}, got {}", + payload.version + ), + ))); } let sbx_dir = sandbox_dir(&payload.codex_home); - std::fs::create_dir_all(&sbx_dir)?; + std::fs::create_dir_all(&sbx_dir).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSandboxDirCreateFailed, + format!("failed to create sandbox dir {}: {err}", sbx_dir.display()), + )) + })?; let log_path = sbx_dir.join(LOG_FILE_NAME); let mut log = File::options() .create(true) .append(true) .open(&log_path) - .context("open log")?; + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperLogFailed, + format!("open log {} failed: {err}", log_path.display()), + )) + })?; let result = run_setup(&payload, &mut log, &sbx_dir); if let Err(err) = &result { let _ = log_line(&mut log, &format!("setup error: {err:?}")); log_note(&format!("setup error: {err:?}"), Some(sbx_dir.as_path())); + let failure = extract_setup_failure(err) + .map(|f| SetupFailure::new(f.code, f.message.clone())) + .unwrap_or_else(|| { + SetupFailure::new(SetupErrorCode::HelperUnknownError, err.to_string()) + }); + let report = SetupErrorReport { + code: failure.code, + message: failure.message.clone(), + }; + if let Err(write_err) = write_setup_error_report(&payload.codex_home, &report) { + let _ = log_line( + &mut log, + &format!("setup error report write failed: {write_err}"), + ); + log_note( + &format!("setup error report write failed: {write_err}"), + Some(sbx_dir.as_path()), + ); + } } result } @@ -446,32 +501,77 @@ fn run_setup_full(payload: &Payload, log: &mut File, sbx_dir: &Path) -> Result<( let refresh_only = payload.refresh_only; if refresh_only { } else { - provision_sandbox_users( + let provision_result = provision_sandbox_users( &payload.codex_home, &payload.offline_username, &payload.online_username, log, - )?; + ); + if let Err(err) = provision_result { + if extract_setup_failure(&err).is_some() { + return Err(err); + } + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUserProvisionFailed, + format!("provision sandbox users failed: {err}"), + ))); + } let users = vec![ payload.offline_username.clone(), payload.online_username.clone(), ]; hide_newly_created_users(&users, sbx_dir); } - let offline_sid = resolve_sid(&payload.offline_username)?; + let offline_sid = resolve_sid(&payload.offline_username).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSidResolveFailed, + format!( + "resolve SID for offline user {} failed: {err}", + payload.offline_username + ), + )) + })?; let offline_sid_str = string_from_sid_bytes(&offline_sid).map_err(anyhow::Error::msg)?; - let sandbox_group_sid = resolve_sandbox_users_group_sid()?; - let sandbox_group_psid = sid_bytes_to_psid(&sandbox_group_sid)?; + let sandbox_group_sid = resolve_sandbox_users_group_sid().map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSidResolveFailed, + format!("resolve sandbox users group SID failed: {err}"), + )) + })?; + let sandbox_group_psid = sid_bytes_to_psid(&sandbox_group_sid).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSidResolveFailed, + format!("convert sandbox users group SID to PSID failed: {err}"), + )) + })?; - let caps = load_or_create_cap_sids(&payload.codex_home)?; + let caps = load_or_create_cap_sids(&payload.codex_home).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperCapabilitySidFailed, + format!("load or create capability SIDs failed: {err}"), + )) + })?; let cap_psid = unsafe { - convert_string_sid_to_sid(&caps.workspace) - .ok_or_else(|| anyhow::anyhow!("convert capability SID failed"))? + convert_string_sid_to_sid(&caps.workspace).ok_or_else(|| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperCapabilitySidFailed, + format!("convert capability SID {} failed", caps.workspace), + )) + })? }; let mut refresh_errors: Vec = Vec::new(); if !refresh_only { - firewall::ensure_offline_outbound_block(&offline_sid_str, log)?; + let firewall_result = firewall::ensure_offline_outbound_block(&offline_sid_str, log); + if let Err(err) = firewall_result { + if extract_setup_failure(&err).is_some() { + return Err(err); + } + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("ensure offline outbound block failed: {err}"), + ))); + } } if payload.read_roots.is_empty() { @@ -482,14 +582,26 @@ fn run_setup_full(payload: &Payload, log: &mut File, sbx_dir: &Path) -> Result<( log_line(log, "read ACL helper already running; skipping spawn")?; } Ok(false) => { - spawn_read_acl_helper(payload, log)?; + spawn_read_acl_helper(payload, log).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperReadAclHelperSpawnFailed, + format!("spawn read ACL helper failed: {err}"), + )) + })?; } Err(err) => { log_line( log, &format!("read ACL mutex check failed: {err}; spawning anyway"), )?; - spawn_read_acl_helper(payload, log)?; + spawn_read_acl_helper(payload, log).map_err(|spawn_err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperReadAclHelperSpawnFailed, + format!( + "spawn read ACL helper failed after mutex error {err}: {spawn_err}" + ), + )) + })?; } } } @@ -615,14 +727,32 @@ fn run_setup_full(payload: &Payload, log: &mut File, sbx_dir: &Path) -> Result<( &sandbox_group_sid, GRANT_ACCESS, log, - )?; + ) + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSandboxLockFailed, + format!( + "lock sandbox dir {} failed: {err}", + sandbox_dir(&payload.codex_home).display() + ), + )) + })?; lock_sandbox_dir( &sandbox_secrets_dir(&payload.codex_home), &payload.real_user, &sandbox_group_sid, DENY_ACCESS, log, - )?; + ) + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSandboxLockFailed, + format!( + "lock sandbox secrets dir {} failed: {err}", + sandbox_secrets_dir(&payload.codex_home).display() + ), + )) + })?; let legacy_users = sandbox_dir(&payload.codex_home).join("sandbox_users.json"); if legacy_users.exists() { let _ = std::fs::remove_file(&legacy_users); diff --git a/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs b/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs index 19e20fc9d0..74137379ec 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs @@ -13,6 +13,11 @@ use crate::allow::compute_allow_paths; use crate::allow::AllowDenyPaths; use crate::logging::log_note; use crate::policy::SandboxPolicy; +use crate::setup_error::clear_setup_error_report; +use crate::setup_error::failure; +use crate::setup_error::read_setup_error_report; +use crate::setup_error::SetupErrorCode; +use crate::setup_error::SetupFailure; use anyhow::anyhow; use anyhow::Context; use anyhow::Result; @@ -308,7 +313,30 @@ fn find_setup_exe() -> PathBuf { PathBuf::from("codex-windows-sandbox-setup.exe") } -fn run_setup_exe(payload: &ElevationPayload, needs_elevation: bool) -> Result<()> { +fn report_helper_failure( + codex_home: &Path, + cleared_report: bool, + exit_code: Option, +) -> anyhow::Error { + let exit_detail = format!("setup helper exited with status {exit_code:?}"); + if !cleared_report { + return failure(SetupErrorCode::OrchestratorHelperExitNonzero, exit_detail); + } + match read_setup_error_report(codex_home) { + Ok(Some(report)) => anyhow::Error::new(SetupFailure::from_report(report)), + Ok(None) => failure(SetupErrorCode::OrchestratorHelperExitNonzero, exit_detail), + Err(err) => failure( + SetupErrorCode::OrchestratorHelperReportReadFailed, + format!("{exit_detail}; failed to read setup_error.json: {err}"), + ), + } +} + +fn run_setup_exe( + payload: &ElevationPayload, + needs_elevation: bool, + codex_home: &Path, +) -> Result<()> { use windows_sys::Win32::System::Threading::GetExitCodeProcess; use windows_sys::Win32::System::Threading::WaitForSingleObject; use windows_sys::Win32::System::Threading::INFINITE; @@ -316,8 +344,25 @@ fn run_setup_exe(payload: &ElevationPayload, needs_elevation: bool) -> Result<() use windows_sys::Win32::UI::Shell::SEE_MASK_NOCLOSEPROCESS; use windows_sys::Win32::UI::Shell::SHELLEXECUTEINFOW; let exe = find_setup_exe(); - let payload_json = serde_json::to_string(payload)?; + let payload_json = serde_json::to_string(payload).map_err(|err| { + failure( + SetupErrorCode::OrchestratorPayloadSerializeFailed, + format!("failed to serialize elevation payload: {err}"), + ) + })?; let payload_b64 = BASE64_STANDARD.encode(payload_json.as_bytes()); + let cleared_report = match clear_setup_error_report(codex_home) { + Ok(()) => true, + Err(err) => { + log_note( + &format!( + "setup orchestrator: failed to clear setup_error.json before launch: {err}" + ), + Some(&sandbox_dir(codex_home)), + ); + false + } + }; if !needs_elevation { let status = Command::new(&exe) @@ -327,13 +372,27 @@ fn run_setup_exe(payload: &ElevationPayload, needs_elevation: bool) -> Result<() .stdout(Stdio::null()) .stderr(Stdio::null()) .status() - .context("failed to launch setup helper")?; + .map_err(|err| { + failure( + SetupErrorCode::OrchestratorHelperLaunchFailed, + format!("failed to launch setup helper (non-elevated): {err}"), + ) + })?; if !status.success() { - return Err(anyhow!( - "setup helper exited with status {:?}", - status.code() + return Err(report_helper_failure( + codex_home, + cleared_report, + status.code(), )); } + if let Err(err) = clear_setup_error_report(codex_home) { + log_note( + &format!( + "setup orchestrator: failed to clear setup_error.json after success: {err}" + ), + Some(&sandbox_dir(codex_home)), + ); + } return Ok(()); } @@ -351,9 +410,10 @@ fn run_setup_exe(payload: &ElevationPayload, needs_elevation: bool) -> Result<() sei.nShow = 0; // SW_HIDE let ok = unsafe { ShellExecuteExW(&mut sei) }; if ok == 0 || sei.hProcess == 0 { - return Err(anyhow!( - "ShellExecuteExW failed to launch setup helper: {}", - unsafe { GetLastError() } + let last_error = unsafe { GetLastError() }; + return Err(failure( + SetupErrorCode::OrchestratorHelperLaunchFailed, + format!("ShellExecuteExW failed to launch setup helper: {last_error}"), )); } unsafe { @@ -362,9 +422,19 @@ fn run_setup_exe(payload: &ElevationPayload, needs_elevation: bool) -> Result<() GetExitCodeProcess(sei.hProcess, &mut code); CloseHandle(sei.hProcess); if code != 0 { - return Err(anyhow!("setup helper exited with status {}", code)); + return Err(report_helper_failure( + codex_home, + cleared_report, + Some(code as i32), + )); } } + if let Err(err) = clear_setup_error_report(codex_home) { + log_note( + &format!("setup orchestrator: failed to clear setup_error.json after success: {err}"), + Some(&sandbox_dir(codex_home)), + ); + } Ok(()) } @@ -379,7 +449,12 @@ pub fn run_elevated_setup( ) -> Result<()> { // Ensure the shared sandbox directory exists before we send it to the elevated helper. let sbx_dir = sandbox_dir(codex_home); - std::fs::create_dir_all(&sbx_dir)?; + std::fs::create_dir_all(&sbx_dir).map_err(|err| { + failure( + SetupErrorCode::OrchestratorSandboxDirCreateFailed, + format!("failed to create sandbox dir {}: {err}", sbx_dir.display()), + ) + })?; let (read_roots, write_roots) = build_payload_roots( policy, policy_cwd, @@ -399,8 +474,13 @@ pub fn run_elevated_setup( real_user: std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string()), refresh_only: false, }; - let needs_elevation = !is_elevated()?; - run_setup_exe(&payload, needs_elevation) + let needs_elevation = !is_elevated().map_err(|err| { + failure( + SetupErrorCode::OrchestratorElevationCheckFailed, + format!("failed to determine elevation state: {err}"), + ) + })?; + run_setup_exe(&payload, needs_elevation, codex_home) } fn build_payload_roots( From 996e09ca24c057403a891eb6fc859b495edd82ee Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 01:43:17 -0700 Subject: [PATCH 029/116] feat(core) RequestRule (#9489) ## Summary Instead of trying to derive the prefix_rule for a command mechanically, let's let the model decide for us. ## Testing - [x] tested locally --- codex-rs/Cargo.lock | 2 + codex-rs/app-server/Cargo.toml | 1 + .../app-server/tests/suite/send_message.rs | 3 + codex-rs/core/config.schema.json | 6 + codex-rs/core/src/codex.rs | 71 +++- codex-rs/core/src/exec_policy.rs | 335 +++++++++++------- codex-rs/core/src/features.rs | 8 + codex-rs/core/src/tools/handlers/shell.rs | 113 +++--- .../core/src/tools/handlers/unified_exec.rs | 16 +- codex-rs/core/src/tools/router.rs | 1 + codex-rs/core/src/tools/spec.rs | 114 +++--- codex-rs/core/src/unified_exec/mod.rs | 2 + .../core/src/unified_exec/process_manager.rs | 39 +- codex-rs/core/tests/suite/approvals.rs | 10 + .../core/tests/suite/permissions_messages.rs | 46 +-- codex-rs/execpolicy/src/policy.rs | 31 ++ codex-rs/execpolicy/src/rule.rs | 6 + codex-rs/protocol/Cargo.toml | 1 + codex-rs/protocol/src/models.rs | 132 ++++++- .../approval_policy/on_request_rule.md | 61 ++++ 20 files changed, 696 insertions(+), 302 deletions(-) create mode 100644 codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 43916d1e14..383a9cf48e 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1077,6 +1077,7 @@ dependencies = [ "codex-chatgpt", "codex-common", "codex-core", + "codex-execpolicy", "codex-feedback", "codex-file-search", "codex-login", @@ -1756,6 +1757,7 @@ name = "codex-protocol" version = "0.0.0" dependencies = [ "anyhow", + "codex-execpolicy", "codex-git", "codex-utils-absolute-path", "codex-utils-image", diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 9fa2044058..af2f30c49c 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -56,6 +56,7 @@ axum = { workspace = true, default-features = false, features = [ "tokio", ] } base64 = { workspace = true } +codex-execpolicy = { workspace = true } core_test_support = { workspace = true } mcp-types = { workspace = true } os_info = { workspace = true } diff --git a/codex-rs/app-server/tests/suite/send_message.rs b/codex-rs/app-server/tests/suite/send_message.rs index 0c713de87c..814352a007 100644 --- a/codex-rs/app-server/tests/suite/send_message.rs +++ b/codex-rs/app-server/tests/suite/send_message.rs @@ -11,6 +11,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_execpolicy::Policy; use codex_protocol::ThreadId; use codex_protocol::models::ContentItem; use codex_protocol::models::DeveloperInstructions; @@ -358,6 +359,8 @@ fn assert_permissions_message(item: &ResponseItem) { let expected = DeveloperInstructions::from_policy( &SandboxPolicy::DangerFullAccess, AskForApproval::Never, + &Policy::empty(), + false, &PathBuf::from("/tmp"), ) .into_text(); diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 1fe5f9e75d..c11256c70d 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -189,6 +189,9 @@ "remote_models": { "type": "boolean" }, + "request_rule": { + "type": "boolean" + }, "responses_websockets": { "type": "boolean" }, @@ -1184,6 +1187,9 @@ "remote_models": { "type": "boolean" }, + "request_rule": { + "type": "boolean" + }, "responses_websockets": { "type": "boolean" }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index d4f2822a73..e9fbecfa90 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -190,6 +190,7 @@ use codex_protocol::models::ContentItem; use codex_protocol::models::DeveloperInstructions; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; +use codex_protocol::models::render_command_prefix_list; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::InitialHistory; use codex_protocol::user_input::UserInput; @@ -1226,6 +1227,8 @@ impl Session { DeveloperInstructions::from_policy( &next.sandbox_policy, next.approval_policy, + self.services.exec_policy.current().as_ref(), + self.features.enabled(Feature::RequestRule), &next.cwd, ) .into(), @@ -1416,6 +1419,44 @@ impl Session { Ok(()) } + async fn turn_context_for_sub_id(&self, sub_id: &str) -> Option> { + let active = self.active_turn.lock().await; + active + .as_ref() + .and_then(|turn| turn.tasks.get(sub_id)) + .map(|task| Arc::clone(&task.turn_context)) + } + + pub(crate) async fn record_execpolicy_amendment_message( + &self, + sub_id: &str, + amendment: &ExecPolicyAmendment, + ) { + let Some(prefixes) = render_command_prefix_list([amendment.command.as_slice()]) else { + warn!("execpolicy amendment for {sub_id} had no command prefix"); + return; + }; + let text = format!("Approved command prefix saved:\n{prefixes}"); + let message: ResponseItem = DeveloperInstructions::new(text.clone()).into(); + + if let Some(turn_context) = self.turn_context_for_sub_id(sub_id).await { + self.record_conversation_items(&turn_context, std::slice::from_ref(&message)) + .await; + return; + } + + if self + .inject_response_items(vec![ResponseInputItem::Message { + role: "developer".to_string(), + content: vec![ContentItem::InputText { text }], + }]) + .await + .is_err() + { + warn!("no active turn found to record execpolicy amendment message for {sub_id}"); + } + } + /// Emit an exec approval request event and await the user's decision. /// /// The request is keyed by `sub_id`/`call_id` so matching responses are delivered @@ -1749,6 +1790,8 @@ impl Session { DeveloperInstructions::from_policy( &turn_context.sandbox_policy, turn_context.approval_policy, + self.services.exec_policy.current().as_ref(), + self.features.enabled(Feature::RequestRule), &turn_context.cwd, ) .into(), @@ -2595,18 +2638,26 @@ mod handlers { if let ReviewDecision::ApprovedExecpolicyAmendment { proposed_execpolicy_amendment, } = &decision - && let Err(err) = sess + { + match sess .persist_execpolicy_amendment(proposed_execpolicy_amendment) .await - { - let message = format!("Failed to apply execpolicy amendment: {err}"); - tracing::warn!("{message}"); - let warning = EventMsg::Warning(WarningEvent { message }); - sess.send_event_raw(Event { - id: id.clone(), - msg: warning, - }) - .await; + { + Ok(()) => { + sess.record_execpolicy_amendment_message(&id, proposed_execpolicy_amendment) + .await; + } + Err(err) => { + let message = format!("Failed to apply execpolicy amendment: {err}"); + tracing::warn!("{message}"); + let warning = EventMsg::Warning(WarningEvent { message }); + sess.send_event_raw(Event { + id: id.clone(), + msg: warning, + }) + .await; + } + } } match decision { ReviewDecision::Abort => { diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index 61c0070239..07a9ebceba 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -87,6 +87,15 @@ pub(crate) struct ExecPolicyManager { policy: ArcSwap, } +pub(crate) struct ExecApprovalRequest<'a> { + pub(crate) features: &'a Features, + pub(crate) command: &'a [String], + pub(crate) approval_policy: AskForApproval, + pub(crate) sandbox_policy: &'a SandboxPolicy, + pub(crate) sandbox_permissions: SandboxPermissions, + pub(crate) prefix_rule: Option>, +} + impl ExecPolicyManager { pub(crate) fn new(policy: Arc) -> Self { Self { @@ -112,12 +121,16 @@ impl ExecPolicyManager { pub(crate) async fn create_exec_approval_requirement_for_command( &self, - features: &Features, - command: &[String], - approval_policy: AskForApproval, - sandbox_policy: &SandboxPolicy, - sandbox_permissions: SandboxPermissions, + req: ExecApprovalRequest<'_>, ) -> ExecApprovalRequirement { + let ExecApprovalRequest { + features, + command, + approval_policy, + sandbox_policy, + sandbox_permissions, + prefix_rule, + } = req; let exec_policy = self.current(); let commands = parse_shell_lc_plain_commands(command).unwrap_or_else(|| vec![command.to_vec()]); @@ -131,6 +144,12 @@ impl ExecPolicyManager { }; let evaluation = exec_policy.check_multiple(commands.iter(), &exec_policy_fallback); + let requested_amendment = derive_requested_execpolicy_amendment( + features, + prefix_rule.as_ref(), + &evaluation.matched_rules, + ); + match evaluation.decision { Decision::Forbidden => ExecApprovalRequirement::Forbidden { reason: derive_forbidden_reason(command, &evaluation), @@ -144,9 +163,11 @@ impl ExecPolicyManager { ExecApprovalRequirement::NeedsApproval { reason: derive_prompt_reason(command, &evaluation), proposed_execpolicy_amendment: if features.enabled(Feature::ExecPolicy) { - try_derive_execpolicy_amendment_for_prompt_rules( - &evaluation.matched_rules, - ) + requested_amendment.or_else(|| { + try_derive_execpolicy_amendment_for_prompt_rules( + &evaluation.matched_rules, + ) + }) } else { None }, @@ -382,6 +403,30 @@ fn try_derive_execpolicy_amendment_for_allow_rules( }) } +fn derive_requested_execpolicy_amendment( + features: &Features, + prefix_rule: Option<&Vec>, + matched_rules: &[RuleMatch], +) -> Option { + if !features.enabled(Feature::ExecPolicy) { + return None; + } + + let prefix_rule = prefix_rule?; + if prefix_rule.is_empty() { + return None; + } + + if matched_rules + .iter() + .any(|rule_match| is_policy_match(rule_match) && rule_match.decision() == Decision::Prompt) + { + return None; + } + + Some(ExecPolicyAmendment::new(prefix_rule.clone())) +} + /// Only return a reason when a policy rule drove the prompt decision. fn derive_prompt_reason(command_args: &[String], evaluation: &Evaluation) -> Option { let command = render_shlex_command(command_args); @@ -756,13 +801,14 @@ prefix_rule(pattern=["rm"], decision="forbidden") let manager = ExecPolicyManager::new(policy); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &forbidden_script, - AskForApproval::OnRequest, - &SandboxPolicy::DangerFullAccess, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &forbidden_script, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -790,17 +836,18 @@ prefix_rule( let manager = ExecPolicyManager::new(policy); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &[ + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &[ "rm".to_string(), "-rf".to_string(), "/some/important/folder".to_string(), ], - AskForApproval::OnRequest, - &SandboxPolicy::DangerFullAccess, - SandboxPermissions::UseDefault, - ) + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -823,13 +870,14 @@ prefix_rule( let manager = ExecPolicyManager::new(policy); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::OnRequest, - &SandboxPolicy::DangerFullAccess, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -853,13 +901,14 @@ prefix_rule( let manager = ExecPolicyManager::new(policy); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::Never, - &SandboxPolicy::DangerFullAccess, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::Never, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -876,13 +925,14 @@ prefix_rule( let manager = ExecPolicyManager::default(); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::UnlessTrusted, - &SandboxPolicy::ReadOnly, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -894,6 +944,40 @@ prefix_rule( ); } + #[tokio::test] + async fn request_rule_uses_prefix_rule() { + let command = vec![ + "cargo".to_string(), + "install".to_string(), + "cargo-insta".to_string(), + ]; + let manager = ExecPolicyManager::default(); + let mut features = Features::with_defaults(); + features.enable(Feature::RequestRule); + + let requirement = manager + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &features, + command: &command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::ReadOnly, + 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![ + "cargo".to_string(), + "install".to_string(), + ])), + } + ); + } + #[tokio::test] async fn heuristics_apply_when_other_commands_match_policy() { let policy_src = r#"prefix_rule(pattern=["apple"], decision="allow")"#; @@ -910,13 +994,14 @@ prefix_rule( assert_eq!( ExecPolicyManager::new(policy) - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::UnlessTrusted, - &SandboxPolicy::DangerFullAccess, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await, ExecApprovalRequirement::NeedsApproval { reason: None, @@ -984,13 +1069,14 @@ prefix_rule( let manager = ExecPolicyManager::default(); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::UnlessTrusted, - &SandboxPolicy::ReadOnly, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -1011,13 +1097,14 @@ prefix_rule( let manager = ExecPolicyManager::default(); let requirement = manager - .create_exec_approval_requirement_for_command( - &features, - &command, - AskForApproval::UnlessTrusted, - &SandboxPolicy::ReadOnly, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &features, + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -1041,13 +1128,14 @@ prefix_rule( let manager = ExecPolicyManager::new(policy); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::OnRequest, - &SandboxPolicy::DangerFullAccess, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -1068,13 +1156,14 @@ prefix_rule( ]; let manager = ExecPolicyManager::default(); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::UnlessTrusted, - &SandboxPolicy::ReadOnly, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -1106,13 +1195,14 @@ prefix_rule( assert_eq!( ExecPolicyManager::new(policy) - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::UnlessTrusted, - &SandboxPolicy::ReadOnly, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await, ExecApprovalRequirement::NeedsApproval { reason: None, @@ -1129,13 +1219,14 @@ prefix_rule( let manager = ExecPolicyManager::default(); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::OnRequest, - &SandboxPolicy::ReadOnly, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -1159,13 +1250,14 @@ prefix_rule( let manager = ExecPolicyManager::new(policy); let requirement = manager - .create_exec_approval_requirement_for_command( - &Features::with_defaults(), - &command, - AskForApproval::OnRequest, - &SandboxPolicy::ReadOnly, - SandboxPermissions::UseDefault, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &Features::with_defaults(), + command: &command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) .await; assert_eq!( @@ -1226,13 +1318,14 @@ prefix_rule( assert_eq!( expected_req, policy - .create_exec_approval_requirement_for_command( - &features, - &sneaky_command, - AskForApproval::OnRequest, - &SandboxPolicy::ReadOnly, - permissions, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &features, + command: &sneaky_command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: permissions, + prefix_rule: None, + }) .await, "{pwsh_approval_reason}" ); @@ -1249,13 +1342,14 @@ prefix_rule( ]))), }, policy - .create_exec_approval_requirement_for_command( - &features, - &dangerous_command, - AskForApproval::OnRequest, - &SandboxPolicy::ReadOnly, - permissions, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &features, + command: &dangerous_command, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: permissions, + prefix_rule: None, + }) .await, r#"On all platforms, a forbidden command should require approval (unless AskForApproval::Never is specified)."# @@ -1268,13 +1362,14 @@ prefix_rule( reason: "`rm -rf /important/data` rejected: blocked by policy".to_string(), }, policy - .create_exec_approval_requirement_for_command( - &features, - &dangerous_command, - AskForApproval::Never, - &SandboxPolicy::ReadOnly, - permissions, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &features, + command: &dangerous_command, + approval_policy: AskForApproval::Never, + sandbox_policy: &SandboxPolicy::ReadOnly, + sandbox_permissions: permissions, + prefix_rule: None, + }) .await, r#"On all platforms, a forbidden command should require approval (unless AskForApproval::Never is specified)."# diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index cc56970276..bd739e5a75 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -89,6 +89,8 @@ pub enum Feature { WebSearchCached, /// Gate the execpolicy enforcement for shell/unified exec. ExecPolicy, + /// Allow the model to request approval and propose exec rules. + RequestRule, /// Enable Windows sandbox (restricted token) on Windows. WindowsSandbox, /// Use the elevated Windows sandbox pipeline (setup + runner). @@ -393,6 +395,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: true, }, + FeatureSpec { + id: Feature::RequestRule, + key: "request_rule", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::WindowsSandbox, key: "experimental_windows_sandbox", diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index c3628e8c34..dbfb0364bf 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use crate::codex::TurnContext; use crate::exec::ExecParams; use crate::exec_env::create_env; +use crate::exec_policy::ExecApprovalRequest; use crate::function_tool::FunctionCallError; use crate::is_safe_command::is_known_safe_command; use crate::protocol::ExecCommandSource; @@ -28,16 +29,27 @@ pub struct ShellHandler; pub struct ShellCommandHandler; +struct RunExecLikeArgs { + tool_name: String, + exec_params: ExecParams, + prefix_rule: Option>, + session: Arc, + turn: Arc, + tracker: crate::tools::context::SharedTurnDiffTracker, + call_id: String, + freeform: bool, +} + impl ShellHandler { - fn to_exec_params(params: ShellToolCallParams, turn_context: &TurnContext) -> ExecParams { + fn to_exec_params(params: &ShellToolCallParams, turn_context: &TurnContext) -> ExecParams { ExecParams { - command: params.command, + command: params.command.clone(), cwd: turn_context.resolve_path(params.workdir.clone()), expiration: params.timeout_ms.into(), env: create_env(&turn_context.shell_environment_policy), sandbox_permissions: params.sandbox_permissions.unwrap_or_default(), windows_sandbox_level: turn_context.windows_sandbox_level, - justification: params.justification, + justification: params.justification.clone(), arg0: None, } } @@ -50,7 +62,7 @@ impl ShellCommandHandler { } fn to_exec_params( - params: ShellCommandToolCallParams, + params: &ShellCommandToolCallParams, session: &crate::codex::Session, turn_context: &TurnContext, ) -> ExecParams { @@ -64,7 +76,7 @@ impl ShellCommandHandler { env: create_env(&turn_context.shell_environment_policy), sandbox_permissions: params.sandbox_permissions.unwrap_or_default(), windows_sandbox_level: turn_context.windows_sandbox_level, - justification: params.justification, + justification: params.justification.clone(), arg0: None, } } @@ -108,29 +120,32 @@ impl ToolHandler for ShellHandler { match payload { ToolPayload::Function { arguments } => { let params: ShellToolCallParams = parse_arguments(&arguments)?; - let exec_params = Self::to_exec_params(params, turn.as_ref()); - Self::run_exec_like( - tool_name.as_str(), + let prefix_rule = params.prefix_rule.clone(); + let exec_params = Self::to_exec_params(¶ms, turn.as_ref()); + Self::run_exec_like(RunExecLikeArgs { + tool_name: tool_name.clone(), exec_params, + prefix_rule, session, turn, tracker, call_id, - false, - ) + freeform: false, + }) .await } ToolPayload::LocalShell { params } => { - let exec_params = Self::to_exec_params(params, turn.as_ref()); - Self::run_exec_like( - tool_name.as_str(), + let exec_params = Self::to_exec_params(¶ms, turn.as_ref()); + Self::run_exec_like(RunExecLikeArgs { + tool_name: tool_name.clone(), exec_params, + prefix_rule: None, session, turn, tracker, call_id, - false, - ) + freeform: false, + }) .await } _ => Err(FunctionCallError::RespondToModel(format!( @@ -181,30 +196,43 @@ impl ToolHandler for ShellCommandHandler { }; let params: ShellCommandToolCallParams = parse_arguments(&arguments)?; - let exec_params = Self::to_exec_params(params, session.as_ref(), turn.as_ref()); - ShellHandler::run_exec_like( - tool_name.as_str(), + let prefix_rule = params.prefix_rule.clone(); + let exec_params = Self::to_exec_params(¶ms, session.as_ref(), turn.as_ref()); + ShellHandler::run_exec_like(RunExecLikeArgs { + tool_name, exec_params, + prefix_rule, session, turn, tracker, call_id, - true, - ) + freeform: true, + }) .await } } impl ShellHandler { - async fn run_exec_like( - tool_name: &str, - exec_params: ExecParams, - session: Arc, - turn: Arc, - tracker: crate::tools::context::SharedTurnDiffTracker, - call_id: String, - freeform: bool, - ) -> Result { + async fn run_exec_like(args: RunExecLikeArgs) -> Result { + let RunExecLikeArgs { + tool_name, + exec_params, + prefix_rule, + session, + turn, + tracker, + call_id, + freeform, + } = args; + + let features = session.features(); + let request_rule_enabled = features.enabled(crate::features::Feature::RequestRule); + let prefix_rule = if request_rule_enabled { + prefix_rule + } else { + None + }; + // Approval policy guard for explicit escalation in non-OnRequest modes. if exec_params .sandbox_permissions @@ -214,9 +242,9 @@ impl ShellHandler { codex_protocol::protocol::AskForApproval::OnRequest ) { + let approval_policy = turn.approval_policy; return Err(FunctionCallError::RespondToModel(format!( - "approval policy is {policy:?}; reject command — you should not ask for escalated permissions if the approval policy is {policy:?}", - policy = turn.approval_policy + "approval policy is {approval_policy:?}; reject command — you should not ask for escalated permissions if the approval policy is {approval_policy:?}" ))); } @@ -229,7 +257,7 @@ impl ShellHandler { turn.as_ref(), Some(&tracker), &call_id, - tool_name, + tool_name.as_str(), ) .await? { @@ -246,17 +274,17 @@ impl ShellHandler { let event_ctx = ToolEventCtx::new(session.as_ref(), turn.as_ref(), &call_id, None); emitter.begin(event_ctx).await; - let features = session.features(); let exec_approval_requirement = session .services .exec_policy - .create_exec_approval_requirement_for_command( - &features, - &exec_params.command, - turn.approval_policy, - &turn.sandbox_policy, - exec_params.sandbox_permissions, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &features, + command: &exec_params.command, + approval_policy: turn.approval_policy, + sandbox_policy: &turn.sandbox_policy, + sandbox_permissions: exec_params.sandbox_permissions, + prefix_rule, + }) .await; let req = ShellRequest { @@ -274,7 +302,7 @@ impl ShellHandler { session: session.as_ref(), turn: turn.as_ref(), call_id: call_id.clone(), - tool_name: tool_name.to_string(), + tool_name, }; let out = orchestrator .run(&mut runtime, &req, &tool_ctx, &turn, turn.approval_policy) @@ -377,10 +405,11 @@ mod tests { login, timeout_ms, sandbox_permissions: Some(sandbox_permissions), + prefix_rule: None, justification: justification.clone(), }; - let exec_params = ShellCommandHandler::to_exec_params(params, &session, &turn_context); + let exec_params = ShellCommandHandler::to_exec_params(¶ms, &session, &turn_context); // ExecParams cannot derive Eq due to the CancellationToken field, so we manually compare the fields. assert_eq!(exec_params.command, expected_command); diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index c9c5a3a71d..2e331bae59 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -43,6 +43,8 @@ struct ExecCommandArgs { sandbox_permissions: SandboxPermissions, #[serde(default)] justification: Option, + #[serde(default)] + prefix_rule: Option>, } #[derive(Debug, Deserialize)] @@ -135,19 +137,28 @@ impl ToolHandler for UnifiedExecHandler { max_output_tokens, sandbox_permissions, justification, + prefix_rule, .. } = args; + let features = session.features(); + let request_rule_enabled = features.enabled(crate::features::Feature::RequestRule); + let prefix_rule = if request_rule_enabled { + prefix_rule + } else { + None + }; + if sandbox_permissions.requires_escalated_permissions() && !matches!( context.turn.approval_policy, codex_protocol::protocol::AskForApproval::OnRequest ) { + let approval_policy = context.turn.approval_policy; manager.release_process_id(&process_id).await; return Err(FunctionCallError::RespondToModel(format!( - "approval policy is {policy:?}; reject command — you cannot ask for escalated permissions if the approval policy is {policy:?}", - policy = context.turn.approval_policy + "approval policy is {approval_policy:?}; reject command — you cannot ask for escalated permissions if the approval policy is {approval_policy:?}" ))); } @@ -183,6 +194,7 @@ impl ToolHandler for UnifiedExecHandler { tty, sandbox_permissions, justification, + prefix_rule, }, &context, ) diff --git a/codex-rs/core/src/tools/router.rs b/codex-rs/core/src/tools/router.rs index b1f41923bc..d3ff84a2b0 100644 --- a/codex-rs/core/src/tools/router.rs +++ b/codex-rs/core/src/tools/router.rs @@ -114,6 +114,7 @@ impl ToolRouter { workdir: exec.working_directory, timeout_ms: exec.timeout_ms, sandbox_permissions: Some(SandboxPermissions::UseDefault), + prefix_rule: None, justification: None, }; Ok(Some(ToolCall { diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index a128ceeaf6..df65a94d8a 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -30,6 +30,7 @@ pub(crate) struct ToolsConfig { pub web_search_mode: Option, pub collab_tools: bool, pub collaboration_modes_tools: bool, + pub request_rule_enabled: bool, pub experimental_supported_tools: Vec, } @@ -49,6 +50,7 @@ impl ToolsConfig { let include_apply_patch_tool = features.enabled(Feature::ApplyPatchFreeform); let include_collab_tools = features.enabled(Feature::Collab); let include_collaboration_modes_tools = features.enabled(Feature::CollaborationModes); + let request_rule_enabled = features.enabled(Feature::RequestRule); let shell_type = if !features.enabled(Feature::ShellTool) { ConfigShellToolType::Disabled @@ -81,6 +83,7 @@ impl ToolsConfig { web_search_mode: *web_search_mode, collab_tools: include_collab_tools, collaboration_modes_tools: include_collaboration_modes_tools, + request_rule_enabled, experimental_supported_tools: model_info.experimental_supported_tools.clone(), } } @@ -142,8 +145,50 @@ impl From for AdditionalProperties { } } -fn create_exec_command_tool() -> ToolSpec { - let properties = BTreeMap::from([ +fn create_approval_parameters(include_prefix_rule: bool) -> BTreeMap { + let mut properties = BTreeMap::from([ + ( + "sandbox_permissions".to_string(), + JsonSchema::String { + description: Some( + "Sandbox permissions for the command. Set to \"require_escalated\" to request running without sandbox restrictions; defaults to \"use_default\"." + .to_string(), + ), + }, + ), + ( + "justification".to_string(), + JsonSchema::String { + description: Some( + r#"Only set if sandbox_permissions is \"require_escalated\". + Request approval from the user to run this command outside the sandbox. + Phrased as a simple question that summarizes the purpose of the + command as it relates to the task at hand - e.g. 'Do you want to + fetch and pull the latest version of this git branch?'"# + .to_string(), + ), + }, + ), + ]); + + if include_prefix_rule { + properties.insert( + "prefix_rule".to_string(), + JsonSchema::Array { + items: Box::new(JsonSchema::String { description: None }), + description: Some( + r#"Only specify when sandbox_permissions is `require_escalated`. + Suggest a prefix command pattern that will allow you to fulfill similar requests from the user in the future. + Should be a short but reasonable prefix, e.g. [\"git\", \"pull\"] or [\"uv\", \"run\"] or [\"pytest\"]."#.to_string(), + ), + }); + } + + properties +} + +fn create_exec_command_tool(include_prefix_rule: bool) -> ToolSpec { + let mut properties = BTreeMap::from([ ( "cmd".to_string(), JsonSchema::String { @@ -199,25 +244,8 @@ fn create_exec_command_tool() -> ToolSpec { ), }, ), - ( - "sandbox_permissions".to_string(), - JsonSchema::String { - description: Some( - "Sandbox permissions for the command. Set to \"require_escalated\" to request running without sandbox restrictions; defaults to \"use_default\"." - .to_string(), - ), - }, - ), - ( - "justification".to_string(), - JsonSchema::String { - description: Some( - "Only set if sandbox_permissions is \"require_escalated\". 1-sentence explanation of why we want to run this command." - .to_string(), - ), - }, - ), ]); + properties.extend(create_approval_parameters(include_prefix_rule)); ToolSpec::Function(ResponsesApiTool { name: "exec_command".to_string(), @@ -280,8 +308,8 @@ fn create_write_stdin_tool() -> ToolSpec { }) } -fn create_shell_tool() -> ToolSpec { - let properties = BTreeMap::from([ +fn create_shell_tool(include_prefix_rule: bool) -> ToolSpec { + let mut properties = BTreeMap::from([ ( "command".to_string(), JsonSchema::Array { @@ -301,19 +329,8 @@ fn create_shell_tool() -> ToolSpec { description: Some("The timeout for the command in milliseconds".to_string()), }, ), - ( - "sandbox_permissions".to_string(), - JsonSchema::String { - description: Some("Sandbox permissions for the command. Set to \"require_escalated\" to request running without sandbox restrictions; defaults to \"use_default\".".to_string()), - }, - ), - ( - "justification".to_string(), - JsonSchema::String { - description: Some("Only set if sandbox_permissions is \"require_escalated\". 1-sentence explanation of why we want to run this command.".to_string()), - }, - ), ]); + properties.extend(create_approval_parameters(include_prefix_rule)); let description = if cfg!(windows) { r#"Runs a Powershell command (Windows) and returns its output. Arguments to `shell` will be passed to CreateProcessW(). Most commands should be prefixed with ["powershell.exe", "-Command"]. @@ -344,8 +361,8 @@ Examples of valid command strings: }) } -fn create_shell_command_tool() -> ToolSpec { - let properties = BTreeMap::from([ +fn create_shell_command_tool(include_prefix_rule: bool) -> ToolSpec { + let mut properties = BTreeMap::from([ ( "command".to_string(), JsonSchema::String { @@ -375,19 +392,8 @@ fn create_shell_command_tool() -> ToolSpec { description: Some("The timeout for the command in milliseconds".to_string()), }, ), - ( - "sandbox_permissions".to_string(), - JsonSchema::String { - description: Some("Sandbox permissions for the command. Set to \"require_escalated\" to request running without sandbox restrictions; defaults to \"use_default\".".to_string()), - }, - ), - ( - "justification".to_string(), - JsonSchema::String { - description: Some("Only set if sandbox_permissions is \"require_escalated\". 1-sentence explanation of why we want to run this command.".to_string()), - }, - ), ]); + properties.extend(create_approval_parameters(include_prefix_rule)); let description = if cfg!(windows) { r#"Runs a Powershell command (Windows) and returns its output. @@ -1292,13 +1298,13 @@ pub(crate) fn build_specs( match &config.shell_type { ConfigShellToolType::Default => { - builder.push_spec(create_shell_tool()); + builder.push_spec(create_shell_tool(config.request_rule_enabled)); } ConfigShellToolType::Local => { builder.push_spec(ToolSpec::LocalShell {}); } ConfigShellToolType::UnifiedExec => { - builder.push_spec(create_exec_command_tool()); + builder.push_spec(create_exec_command_tool(config.request_rule_enabled)); builder.push_spec(create_write_stdin_tool()); builder.register_handler("exec_command", unified_exec_handler.clone()); builder.register_handler("write_stdin", unified_exec_handler); @@ -1307,7 +1313,7 @@ pub(crate) fn build_specs( // Do nothing. } ConfigShellToolType::ShellCommand => { - builder.push_spec(create_shell_command_tool()); + builder.push_spec(create_shell_command_tool(config.request_rule_enabled)); } } @@ -1579,7 +1585,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(false), create_write_stdin_tool(), create_list_mcp_resources_tool(), create_list_mcp_resource_templates_tool(), @@ -2413,7 +2419,7 @@ mod tests { #[test] fn test_shell_tool() { - let tool = super::create_shell_tool(); + let tool = super::create_shell_tool(false); let ToolSpec::Function(ResponsesApiTool { description, name, .. }) = &tool @@ -2443,7 +2449,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(false); let ToolSpec::Function(ResponsesApiTool { description, name, .. }) = &tool diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 3f359c3866..4c45f1cf42 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -82,6 +82,7 @@ pub(crate) struct ExecCommandRequest { pub tty: bool, pub sandbox_permissions: SandboxPermissions, pub justification: Option, + pub prefix_rule: Option>, } #[derive(Debug)] @@ -205,6 +206,7 @@ mod tests { tty: true, sandbox_permissions: SandboxPermissions::UseDefault, justification: None, + prefix_rule: None, }, &context, ) diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 3230e75b15..5b3e83a5dc 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -11,9 +11,9 @@ use tokio::time::Instant; use tokio_util::sync::CancellationToken; use crate::exec_env::create_env; +use crate::exec_policy::ExecApprovalRequest; use crate::protocol::ExecCommandSource; use crate::sandboxing::ExecEnv; -use crate::sandboxing::SandboxPermissions; use crate::tools::events::ToolEmitter; use crate::tools::events::ToolEventCtx; use crate::tools::events::ToolEventStage; @@ -123,14 +123,7 @@ impl UnifiedExecProcessManager { .unwrap_or_else(|| context.turn.cwd.clone()); let process = self - .open_session_with_sandbox( - &request.command, - cwd.clone(), - request.sandbox_permissions, - request.justification, - request.tty, - context, - ) + .open_session_with_sandbox(&request, cwd.clone(), context) .await; let process = match process { @@ -486,11 +479,8 @@ impl UnifiedExecProcessManager { pub(super) async fn open_session_with_sandbox( &self, - command: &[String], + request: &ExecCommandRequest, cwd: PathBuf, - sandbox_permissions: SandboxPermissions, - justification: Option, - tty: bool, context: &UnifiedExecContext, ) -> Result { let env = apply_unified_exec_env(create_env(&context.turn.shell_environment_policy)); @@ -501,21 +491,22 @@ impl UnifiedExecProcessManager { .session .services .exec_policy - .create_exec_approval_requirement_for_command( - &features, - command, - context.turn.approval_policy, - &context.turn.sandbox_policy, - sandbox_permissions, - ) + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + features: &features, + command: &request.command, + approval_policy: context.turn.approval_policy, + sandbox_policy: &context.turn.sandbox_policy, + sandbox_permissions: request.sandbox_permissions, + prefix_rule: request.prefix_rule.clone(), + }) .await; let req = UnifiedExecToolRequest::new( - command.to_vec(), + request.command.clone(), cwd, env, - tty, - sandbox_permissions, - justification, + request.tty, + request.sandbox_permissions, + request.justification.clone(), exec_approval_requirement, ); let tool_ctx = ToolCtx { diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index ad1881f945..1b295964e8 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -1754,6 +1754,16 @@ async fn approving_execpolicy_amendment_persists_policy_and_skips_future_prompts .await?; wait_for_completion(&test).await; + let developer_messages = first_results + .single_request() + .message_input_texts("developer"); + assert!( + developer_messages + .iter() + .any(|message| message.contains(r#"["touch", "allow-prefix.txt"]"#)), + "expected developer message documenting saved rule, got: {developer_messages:?}" + ); + let policy_path = test.home.path().join("rules").join("default.rules"); let policy_contents = fs::read_to_string(&policy_path)?; assert!( diff --git a/codex-rs/core/tests/suite/permissions_messages.rs b/codex-rs/core/tests/suite/permissions_messages.rs index 679c0c1f6c..e4eded15ff 100644 --- a/codex-rs/core/tests/suite/permissions_messages.rs +++ b/codex-rs/core/tests/suite/permissions_messages.rs @@ -4,6 +4,8 @@ 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::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::responses::ev_completed; @@ -411,10 +413,11 @@ async fn permissions_message_includes_writable_roots() -> Result<()> { exclude_tmpdir_env_var: false, exclude_slash_tmp: false, }; + let sandbox_policy_for_config = sandbox_policy.clone(); let mut builder = test_codex().with_config(move |config| { config.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); - config.sandbox_policy = Constrained::allow_any(sandbox_policy); + config.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); }); let test = builder.build(&server).await?; @@ -432,39 +435,14 @@ async fn permissions_message_includes_writable_roots() -> Result<()> { let body = req.single_request().body_json(); let input = body["input"].as_array().expect("input array"); let permissions = permissions_texts(input); - let sandbox_text = "Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `workspace-write`: The sandbox permits reading files, and editing files in `cwd` and `writable_roots`. Editing files in other directories requires approval. Network access is restricted."; - let approval_text = " Approvals are your mechanism to get user consent to run shell commands without the sandbox. `approval_policy` is `on-request`: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. If the completing the task requires escalated permissions, Do not let these settings or the sandbox deter you from attempting to accomplish the user's task.\n\nHere are scenarios where you'll need to request approval:\n- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /var)\n- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.\n- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)\n- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval. ALWAYS proceed to use the `sandbox_permissions` and `justification` parameters - do not message the user before requesting approval for the command.\n- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for.\n\nWhen requesting approval to execute a command that will require escalated privileges:\n - Provide the `sandbox_permissions` parameter with the value `\"require_escalated\"`\n - Include a short, 1 sentence explanation for why you need escalated permissions in the justification parameter"; - // Normalize paths by removing trailing slashes to match AbsolutePathBuf behavior - let normalize_path = - |p: &std::path::Path| -> String { p.to_string_lossy().trim_end_matches('/').to_string() }; - let mut roots = vec![ - normalize_path(writable.path()), - normalize_path(test.config.cwd.as_path()), - ]; - if cfg!(unix) && std::path::Path::new("/tmp").is_dir() { - roots.push("/tmp".to_string()); - } - if let Some(tmpdir) = std::env::var_os("TMPDIR") { - let tmpdir_path = std::path::PathBuf::from(&tmpdir); - if tmpdir_path.is_absolute() && !tmpdir.is_empty() { - roots.push(normalize_path(&tmpdir_path)); - } - } - let roots_text = if roots.len() == 1 { - format!(" The writable root is `{}`.", roots[0]) - } else { - format!( - " The writable roots are {}.", - roots - .iter() - .map(|root| format!("`{root}`")) - .collect::>() - .join(", ") - ) - }; - let expected = format!( - "{sandbox_text}{approval_text}{roots_text}" - ); + let expected = DeveloperInstructions::from_policy( + &sandbox_policy, + AskForApproval::OnRequest, + &Policy::empty(), + false, + test.config.cwd.as_path(), + ) + .into_text(); // Normalize line endings to handle Windows vs Unix differences let normalize_line_endings = |s: &str| s.replace("\r\n", "\n"); let expected_normalized = normalize_line_endings(&expected); diff --git a/codex-rs/execpolicy/src/policy.rs b/codex-rs/execpolicy/src/policy.rs index 1e758277b8..0da0332d0b 100644 --- a/codex-rs/execpolicy/src/policy.rs +++ b/codex-rs/execpolicy/src/policy.rs @@ -31,6 +31,30 @@ impl Policy { &self.rules_by_program } + pub fn get_allowed_prefixes(&self) -> Vec> { + let mut prefixes = Vec::new(); + + for (_program, rules) in self.rules_by_program.iter_all() { + for rule in rules { + let Some(prefix_rule) = rule.as_any().downcast_ref::() else { + continue; + }; + if prefix_rule.decision != Decision::Allow { + continue; + } + + let mut prefix = Vec::with_capacity(prefix_rule.pattern.rest.len() + 1); + prefix.push(prefix_rule.pattern.first.as_ref().to_string()); + prefix.extend(prefix_rule.pattern.rest.iter().map(render_pattern_token)); + prefixes.push(prefix); + } + } + + prefixes.sort(); + prefixes.dedup(); + prefixes + } + pub fn add_prefix_rule(&mut self, prefix: &[String], decision: Decision) -> Result<()> { let (first_token, rest) = prefix .split_first() @@ -116,6 +140,13 @@ impl Policy { } } +fn render_pattern_token(token: &PatternToken) -> String { + match token { + PatternToken::Single(value) => value.clone(), + PatternToken::Alts(alternatives) => format!("[{}]", alternatives.join("|")), + } +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Evaluation { diff --git a/codex-rs/execpolicy/src/rule.rs b/codex-rs/execpolicy/src/rule.rs index de78a5fda9..b7c1a7cfde 100644 --- a/codex-rs/execpolicy/src/rule.rs +++ b/codex-rs/execpolicy/src/rule.rs @@ -96,6 +96,8 @@ pub trait Rule: Any + Debug + Send + Sync { fn program(&self) -> &str; fn matches(&self, cmd: &[String]) -> Option; + + fn as_any(&self) -> &dyn Any; } pub type RuleRef = Arc; @@ -114,6 +116,10 @@ impl Rule for PrefixRule { justification: self.justification.clone(), }) } + + fn as_any(&self) -> &dyn Any { + self + } } /// Count how many rules match each provided example and error if any example is unmatched. diff --git a/codex-rs/protocol/Cargo.toml b/codex-rs/protocol/Cargo.toml index 19ec1fcc36..c3d9d30915 100644 --- a/codex-rs/protocol/Cargo.toml +++ b/codex-rs/protocol/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [dependencies] codex-git = { workspace = true } +codex-execpolicy = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-image = { workspace = true } icu_decimal = { workspace = true } diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index b0b8156916..50e8ee342f 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -19,6 +19,7 @@ use crate::protocol::NetworkAccess; use crate::protocol::SandboxPolicy; use crate::protocol::WritableRoot; use crate::user_input::UserInput; +use codex_execpolicy::Policy; use codex_git::GhostCommit; use codex_utils_image::error::ImageProcessingError; use schemars::JsonSchema; @@ -205,6 +206,8 @@ const APPROVAL_POLICY_ON_FAILURE: &str = include_str!("prompts/permissions/approval_policy/on_failure.md"); const APPROVAL_POLICY_ON_REQUEST: &str = include_str!("prompts/permissions/approval_policy/on_request.md"); +const APPROVAL_POLICY_ON_REQUEST_RULE: &str = + include_str!("prompts/permissions/approval_policy/on_request_rule.md"); const SANDBOX_MODE_DANGER_FULL_ACCESS: &str = include_str!("prompts/permissions/sandbox_mode/danger_full_access.md"); @@ -217,12 +220,42 @@ impl DeveloperInstructions { Self { text: text.into() } } + pub fn from( + approval_policy: AskForApproval, + exec_policy: &Policy, + request_rule_enabled: bool, + ) -> DeveloperInstructions { + let text = match approval_policy { + AskForApproval::Never => APPROVAL_POLICY_NEVER.to_string(), + AskForApproval::UnlessTrusted => APPROVAL_POLICY_UNLESS_TRUSTED.to_string(), + AskForApproval::OnFailure => APPROVAL_POLICY_ON_FAILURE.to_string(), + AskForApproval::OnRequest => { + if !request_rule_enabled { + APPROVAL_POLICY_ON_REQUEST.to_string() + } else { + let command_prefixes = format_allow_prefixes(exec_policy); + match command_prefixes { + Some(prefixes) => { + format!("{APPROVAL_POLICY_ON_REQUEST_RULE}\n{prefixes}") + } + None => APPROVAL_POLICY_ON_REQUEST_RULE.to_string(), + } + } + } + }; + + DeveloperInstructions::new(text) + } + pub fn into_text(self) -> String { self.text } pub fn concat(self, other: impl Into) -> Self { let mut text = self.text; + if !text.ends_with('\n') { + text.push('\n'); + } text.push_str(&other.into().text); Self { text } } @@ -237,6 +270,8 @@ impl DeveloperInstructions { pub fn from_policy( sandbox_policy: &SandboxPolicy, approval_policy: AskForApproval, + exec_policy: &Policy, + request_rule_enabled: bool, cwd: &Path, ) -> Self { let network_access = if sandbox_policy.has_full_network_access() { @@ -259,6 +294,8 @@ impl DeveloperInstructions { sandbox_mode, network_access, approval_policy, + exec_policy, + request_rule_enabled, writable_roots, ) } @@ -281,6 +318,8 @@ impl DeveloperInstructions { sandbox_mode: SandboxMode, network_access: NetworkAccess, approval_policy: AskForApproval, + exec_policy: &Policy, + request_rule_enabled: bool, writable_roots: Option>, ) -> Self { let start_tag = DeveloperInstructions::new(""); @@ -290,7 +329,11 @@ impl DeveloperInstructions { sandbox_mode, network_access, )) - .concat(DeveloperInstructions::from(approval_policy)) + .concat(DeveloperInstructions::from( + approval_policy, + exec_policy, + request_rule_enabled, + )) .concat(DeveloperInstructions::from_writable_roots(writable_roots)) .concat(end_tag) } @@ -328,6 +371,37 @@ impl DeveloperInstructions { } } +pub fn render_command_prefix_list(prefixes: I) -> Option +where + I: IntoIterator, + P: AsRef<[String]>, +{ + let lines = prefixes + .into_iter() + .map(|prefix| format!("- {}", render_command_prefix(prefix.as_ref()))) + .collect::>(); + if lines.is_empty() { + return None; + } + + Some(lines.join("\n")) +} + +fn render_command_prefix(prefix: &[String]) -> String { + let tokens = prefix + .iter() + .map(|token| serde_json::to_string(token).unwrap_or_else(|_| format!("{token:?}"))) + .collect::>() + .join(", "); + format!("[{tokens}]") +} + +fn format_allow_prefixes(exec_policy: &Policy) -> Option { + let prefixes = exec_policy.get_allowed_prefixes(); + let lines = render_command_prefix_list(prefixes)?; + Some(format!("Approved command prefixes:\n{lines}")) +} + impl From for ResponseItem { fn from(di: DeveloperInstructions) -> Self { ResponseItem::Message { @@ -352,19 +426,6 @@ impl From for DeveloperInstructions { } } -impl From for DeveloperInstructions { - fn from(mode: AskForApproval) -> Self { - let text = match mode { - AskForApproval::Never => APPROVAL_POLICY_NEVER.trim_end(), - AskForApproval::UnlessTrusted => APPROVAL_POLICY_UNLESS_TRUSTED.trim_end(), - AskForApproval::OnFailure => APPROVAL_POLICY_ON_FAILURE.trim_end(), - AskForApproval::OnRequest => APPROVAL_POLICY_ON_REQUEST.trim_end(), - }; - - DeveloperInstructions::new(text) - } -} - fn should_serialize_reasoning_content(content: &Option>) -> bool { match content { Some(content) => !content @@ -633,6 +694,10 @@ pub struct ShellToolCallParams { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub sandbox_permissions: Option, + /// Suggests a command prefix to persist for future sessions + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub prefix_rule: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub justification: Option, } @@ -653,6 +718,9 @@ pub struct ShellCommandToolCallParams { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub sandbox_permissions: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub prefix_rule: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub justification: Option, } @@ -836,6 +904,7 @@ mod tests { use crate::config_types::SandboxMode; use crate::protocol::AskForApproval; use anyhow::Result; + use codex_execpolicy::Policy; use mcp_types::ImageContent; use mcp_types::TextContent; use pretty_assertions::assert_eq; @@ -844,15 +913,17 @@ mod tests { #[test] fn converts_sandbox_mode_into_developer_instructions() { + let workspace_write: DeveloperInstructions = SandboxMode::WorkspaceWrite.into(); assert_eq!( - DeveloperInstructions::from(SandboxMode::WorkspaceWrite), + workspace_write, DeveloperInstructions::new( "Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `workspace-write`: The sandbox permits reading files, and editing files in `cwd` and `writable_roots`. Editing files in other directories requires approval. Network access is restricted." ) ); + let read_only: DeveloperInstructions = SandboxMode::ReadOnly.into(); assert_eq!( - DeveloperInstructions::from(SandboxMode::ReadOnly), + read_only, DeveloperInstructions::new( "Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `read-only`: The sandbox only permits reading files. Network access is restricted." ) @@ -865,6 +936,8 @@ mod tests { SandboxMode::WorkspaceWrite, NetworkAccess::Enabled, AskForApproval::OnRequest, + &Policy::empty(), + false, None, ); @@ -891,6 +964,8 @@ mod tests { let instructions = DeveloperInstructions::from_policy( &policy, AskForApproval::UnlessTrusted, + &Policy::empty(), + false, &PathBuf::from("/tmp"), ); let text = instructions.into_text(); @@ -898,6 +973,30 @@ mod tests { assert!(text.contains("`approval_policy` is `unless-trusted`")); } + #[test] + fn includes_request_rule_instructions_when_enabled() { + let mut exec_policy = Policy::empty(); + exec_policy + .add_prefix_rule( + &["git".to_string(), "pull".to_string()], + codex_execpolicy::Decision::Allow, + ) + .expect("add rule"); + let instructions = DeveloperInstructions::from_permissions_with_network( + SandboxMode::WorkspaceWrite, + NetworkAccess::Enabled, + AskForApproval::OnRequest, + &exec_policy, + true, + None, + ); + + let text = instructions.into_text(); + assert!(text.contains("prefix_rule")); + assert!(text.contains("Approved command prefixes")); + assert!(text.contains(r#"["git", "pull"]"#)); + } + #[test] fn serializes_success_as_plain_string() -> Result<()> { let item = ResponseInputItem::FunctionCallOutput { @@ -1126,6 +1225,7 @@ mod tests { workdir: Some("/tmp".to_string()), timeout_ms: Some(1000), sandbox_permissions: None, + prefix_rule: None, justification: None, }, params diff --git a/codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md b/codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md new file mode 100644 index 0000000000..336f1fb748 --- /dev/null +++ b/codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md @@ -0,0 +1,61 @@ +# Escalation Requests + +Commands are run outside the sandbox if they are approved by the user, or match an existing rule that allows it to run unrestricted. The command string is split into independent command segments at shell control operators, including but not limited to: + +- Pipes: | +- Logical operators: &&, || +- Command separators: ; +- Subshell boundaries: (...), $(...) + +Each resulting segment is evaluated independently for sandbox restrictions and approval requirements. + +Example: + +git pull | tee output.txt + +This is treated as two command segments: + +["git", "pull"] + +["tee", "output.txt"] + +## How to request escalation + +IMPORTANT: To request approval to execute a command that will require escalated privileges: + +- Provide the `sandbox_permissions` parameter with the value `"require_escalated"` +- Include a short question asking the user if they want to allow the action in `justification` parameter. e.g. "Do you want to download and install dependencies for this project?" +- Suggest a `prefix_rule` - this will be shown to the user with an option to persist the rule approval for future sessions. + +If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with "require_escalated". ALWAYS proceed to use the `justification` and `prefix_rule` parameters - do not message the user before requesting approval for the command. + +## When to request escalation + +While commands are running inside the sandbox, here are some scenarios that will require escalation outside the sandbox: + +- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /var) +- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files. +- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with `require_escalated`. ALWAYS proceed to use the `sandbox_permissions` and `justification` parameters. do not message the user before requesting approval for the command. +- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for. + +Only run commands that require approval if it is absolutely necessary to solve the user's query, don't try and circumvent approvals by using other tools. + +## prefix_rule guidance + +When choosing a `prefix_rule`, request one that will allow you to fulfill similar requests from the user in the future without re-requesting escalation. It should be categorical and reasonably scoped to similar capabilities. You MUST NOT pass the entire command into `prefix_rule`. + + +["npm", "run", "dev"] + + +["gh", "pr", "checks"] + + +["pytest"] + + +["cargo", "test", "-p", "codex-app-server"] + +["cargo", "test"] + + From 71b8d937edae488129c59f1a2bc6221e9be7b07a Mon Sep 17 00:00:00 2001 From: gt-oai Date: Wed, 28 Jan 2026 12:00:10 +0000 Subject: [PATCH 030/116] Add exec policy TOML representation (#10026) We'd like to represent these in `requirements.toml`. This just adds the representation and the tests, doesn't wire it up anywhere yet. --- codex-rs/Cargo.lock | 1 + codex-rs/core/Cargo.toml | 1 + codex-rs/core/src/config_loader/mod.rs | 2 + .../config_loader/requirements_exec_policy.rs | 188 ++++++++++++++++++ codex-rs/core/src/config_loader/tests.rs | 162 +++++++++++++++ 5 files changed, 354 insertions(+) create mode 100644 codex-rs/core/src/config_loader/requirements_exec_policy.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 383a9cf48e..e4fe78a3dc 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1389,6 +1389,7 @@ dependencies = [ "libc", "maplit", "mcp-types", + "multimap", "once_cell", "openssl-sys", "os_info", diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index c151356e3d..c186758cb4 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -55,6 +55,7 @@ indoc = { workspace = true } keyring = { workspace = true, features = ["crypto-rust"] } libc = { workspace = true } mcp-types = { workspace = true } +multimap = { workspace = true } once_cell = { workspace = true } os_info = { workspace = true } rand = { workspace = true } diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index ae56c384e4..5db10f2808 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -6,6 +6,8 @@ mod layer_io; mod macos; mod merge; mod overrides; +#[cfg(test)] +mod requirements_exec_policy; mod state; #[cfg(test)] diff --git a/codex-rs/core/src/config_loader/requirements_exec_policy.rs b/codex-rs/core/src/config_loader/requirements_exec_policy.rs new file mode 100644 index 0000000000..cbc1d7531e --- /dev/null +++ b/codex-rs/core/src/config_loader/requirements_exec_policy.rs @@ -0,0 +1,188 @@ +use codex_execpolicy::Decision; +use codex_execpolicy::Policy; +use codex_execpolicy::rule::PatternToken; +use codex_execpolicy::rule::PrefixPattern; +use codex_execpolicy::rule::PrefixRule; +use codex_execpolicy::rule::RuleRef; +use multimap::MultiMap; +use serde::Deserialize; +use std::sync::Arc; +use thiserror::Error; + +/// TOML types for expressing exec policy requirements. +/// +/// These types are kept separate from `ConfigRequirementsToml` and are +/// converted into `codex-execpolicy` rules. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct RequirementsExecPolicyTomlRoot { + pub exec_policy: RequirementsExecPolicyToml, +} + +/// TOML representation of `[exec_policy]` within `requirements.toml`. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct RequirementsExecPolicyToml { + pub prefix_rules: Vec, +} + +/// A TOML representation of the `prefix_rule(...)` Starlark builtin. +/// +/// This mirrors the builtin defined in `execpolicy/src/parser.rs`. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct RequirementsExecPolicyPrefixRuleToml { + pub pattern: Vec, + pub decision: Option, + pub justification: Option, +} + +/// TOML-friendly representation of a pattern token. +/// +/// Starlark supports either a string token or a list of alternative tokens at +/// each position, but TOML arrays cannot mix strings and arrays. Using an +/// array of tables sidesteps that restriction. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct RequirementsExecPolicyPatternTokenToml { + pub token: Option, + pub any_of: Option>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum RequirementsExecPolicyDecisionToml { + Allow, + Prompt, + Forbidden, +} + +impl RequirementsExecPolicyDecisionToml { + fn as_decision(self) -> Decision { + match self { + Self::Allow => Decision::Allow, + Self::Prompt => Decision::Prompt, + Self::Forbidden => Decision::Forbidden, + } + } +} + +#[derive(Debug, Error)] +pub enum RequirementsExecPolicyParseError { + #[error("exec policy prefix_rules cannot be empty")] + EmptyPrefixRules, + + #[error("exec policy prefix_rule at index {rule_index} has an empty pattern")] + EmptyPattern { rule_index: usize }, + + #[error( + "exec policy prefix_rule at index {rule_index} has an invalid pattern token at index {token_index}: {reason}" + )] + InvalidPatternToken { + rule_index: usize, + token_index: usize, + reason: String, + }, + + #[error("exec policy prefix_rule at index {rule_index} has an empty justification")] + EmptyJustification { rule_index: usize }, +} + +impl RequirementsExecPolicyToml { + /// Convert requirements TOML exec policy rules into the internal `.rules` + /// representation used by `codex-execpolicy`. + pub fn to_policy(&self) -> Result { + if self.prefix_rules.is_empty() { + return Err(RequirementsExecPolicyParseError::EmptyPrefixRules); + } + + let mut rules_by_program: MultiMap = MultiMap::new(); + + for (rule_index, rule) in self.prefix_rules.iter().enumerate() { + if let Some(justification) = &rule.justification + && justification.trim().is_empty() + { + return Err(RequirementsExecPolicyParseError::EmptyJustification { rule_index }); + } + + if rule.pattern.is_empty() { + return Err(RequirementsExecPolicyParseError::EmptyPattern { rule_index }); + } + + let pattern_tokens = rule + .pattern + .iter() + .enumerate() + .map(|(token_index, token)| parse_pattern_token(token, rule_index, token_index)) + .collect::, _>>()?; + + let decision = rule + .decision + .map(RequirementsExecPolicyDecisionToml::as_decision) + .unwrap_or(Decision::Allow); + let justification = rule.justification.clone(); + + let (first_token, remaining_tokens) = pattern_tokens + .split_first() + .ok_or(RequirementsExecPolicyParseError::EmptyPattern { rule_index })?; + + let rest: Arc<[PatternToken]> = remaining_tokens.to_vec().into(); + + for head in first_token.alternatives() { + let rule: RuleRef = Arc::new(PrefixRule { + pattern: PrefixPattern { + first: Arc::from(head.as_str()), + rest: rest.clone(), + }, + decision, + justification: justification.clone(), + }); + rules_by_program.insert(head.clone(), rule); + } + } + + Ok(Policy::new(rules_by_program)) + } +} + +fn parse_pattern_token( + token: &RequirementsExecPolicyPatternTokenToml, + rule_index: usize, + token_index: usize, +) -> Result { + match (&token.token, &token.any_of) { + (Some(single), None) => { + if single.trim().is_empty() { + return Err(RequirementsExecPolicyParseError::InvalidPatternToken { + rule_index, + token_index, + reason: "token cannot be empty".to_string(), + }); + } + Ok(PatternToken::Single(single.clone())) + } + (None, Some(alternatives)) => { + if alternatives.is_empty() { + return Err(RequirementsExecPolicyParseError::InvalidPatternToken { + rule_index, + token_index, + reason: "any_of cannot be empty".to_string(), + }); + } + if alternatives.iter().any(|alt| alt.trim().is_empty()) { + return Err(RequirementsExecPolicyParseError::InvalidPatternToken { + rule_index, + token_index, + reason: "any_of cannot include empty tokens".to_string(), + }); + } + Ok(PatternToken::Alts(alternatives.clone())) + } + (Some(_), Some(_)) => Err(RequirementsExecPolicyParseError::InvalidPatternToken { + rule_index, + token_index, + reason: "set either token or any_of, not both".to_string(), + }), + (None, None) => Err(RequirementsExecPolicyParseError::InvalidPatternToken { + rule_index, + token_index, + reason: "set either token or any_of".to_string(), + }), + } +} diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index 03b0706c84..4b512c150f 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -911,3 +911,165 @@ async fn project_root_markers_supports_alternate_markers() -> std::io::Result<() Ok(()) } + +mod requirements_exec_policy_tests { + use super::super::requirements_exec_policy::RequirementsExecPolicyDecisionToml; + use super::super::requirements_exec_policy::RequirementsExecPolicyPatternTokenToml; + use super::super::requirements_exec_policy::RequirementsExecPolicyPrefixRuleToml; + use super::super::requirements_exec_policy::RequirementsExecPolicyToml; + use super::super::requirements_exec_policy::RequirementsExecPolicyTomlRoot; + use codex_execpolicy::Decision; + use codex_execpolicy::Evaluation; + use codex_execpolicy::RuleMatch; + use pretty_assertions::assert_eq; + use toml::from_str; + + fn tokens(cmd: &[&str]) -> Vec { + cmd.iter().map(std::string::ToString::to_string).collect() + } + + fn allow_all(_: &[String]) -> Decision { + Decision::Allow + } + + #[test] + fn parses_single_prefix_rule_from_raw_toml() -> anyhow::Result<()> { + let toml_str = r#" +[exec_policy] +prefix_rules = [ + { pattern = [{ token = "rm" }], decision = "forbidden" }, +] +"#; + + let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; + + assert_eq!( + parsed, + RequirementsExecPolicyTomlRoot { + exec_policy: RequirementsExecPolicyToml { + prefix_rules: vec![RequirementsExecPolicyPrefixRuleToml { + pattern: vec![RequirementsExecPolicyPatternTokenToml { + token: Some("rm".to_string()), + any_of: None, + }], + decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), + justification: None, + }], + }, + } + ); + + Ok(()) + } + + #[test] + fn parses_multiple_prefix_rules_from_raw_toml() -> anyhow::Result<()> { + let toml_str = r#" +[exec_policy] +prefix_rules = [ + { pattern = [{ token = "rm" }], decision = "forbidden" }, + { pattern = [{ token = "git" }, { any_of = ["push", "commit"] }], decision = "prompt", justification = "review changes before push or commit" }, +] +"#; + + let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; + + assert_eq!( + parsed, + RequirementsExecPolicyTomlRoot { + exec_policy: RequirementsExecPolicyToml { + prefix_rules: vec![ + RequirementsExecPolicyPrefixRuleToml { + pattern: vec![RequirementsExecPolicyPatternTokenToml { + token: Some("rm".to_string()), + any_of: None, + }], + decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), + justification: None, + }, + RequirementsExecPolicyPrefixRuleToml { + pattern: vec![ + RequirementsExecPolicyPatternTokenToml { + token: Some("git".to_string()), + any_of: None, + }, + RequirementsExecPolicyPatternTokenToml { + token: None, + any_of: Some(vec!["push".to_string(), "commit".to_string()]), + }, + ], + decision: Some(RequirementsExecPolicyDecisionToml::Prompt), + justification: Some("review changes before push or commit".to_string()), + }, + ], + }, + } + ); + + Ok(()) + } + + #[test] + fn converts_rules_toml_into_internal_policy_representation() -> anyhow::Result<()> { + let toml_str = r#" +[exec_policy] +prefix_rules = [ + { pattern = [{ token = "rm" }], decision = "forbidden" }, +] +"#; + + let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; + let policy = parsed.exec_policy.to_policy()?; + + assert_eq!( + policy.check(&tokens(&["rm", "-rf", "/tmp"]), &allow_all), + Evaluation { + decision: Decision::Forbidden, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: tokens(&["rm"]), + decision: Decision::Forbidden, + justification: None, + }], + } + ); + + Ok(()) + } + + #[test] + fn head_any_of_expands_into_multiple_program_rules() -> anyhow::Result<()> { + let toml_str = r#" +[exec_policy] +prefix_rules = [ + { pattern = [{ any_of = ["git", "hg"] }, { token = "status" }], decision = "prompt" }, +] +"#; + let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; + let policy = parsed.exec_policy.to_policy()?; + + assert_eq!( + policy.check(&tokens(&["git", "status"]), &allow_all), + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: tokens(&["git", "status"]), + decision: Decision::Prompt, + justification: None, + }], + } + ); + assert_eq!( + policy.check(&tokens(&["hg", "status"]), &allow_all), + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: tokens(&["hg", "status"]), + decision: Decision::Prompt, + justification: None, + }], + } + ); + + Ok(()) + } +} From dabafe204a28adce00e70ec5388d7f23b051569d Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 28 Jan 2026 13:03:20 +0000 Subject: [PATCH 031/116] feat: codex exec auto-subscribe to new threads (#9821) --- codex-rs/exec/src/cli.rs | 34 +++++ .../src/event_processor_with_jsonl_output.rs | 19 +-- codex-rs/exec/src/lib.rs | 132 +++++++++++++----- codex-rs/exec/src/main.rs | 41 ++++++ 4 files changed, 183 insertions(+), 43 deletions(-) diff --git a/codex-rs/exec/src/cli.rs b/codex-rs/exec/src/cli.rs index 56ff805fa0..4c10bb0d72 100644 --- a/codex-rs/exec/src/cli.rs +++ b/codex-rs/exec/src/cli.rs @@ -244,3 +244,37 @@ pub enum Color { #[default] Auto, } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn resume_parses_prompt_after_global_flags() { + const PROMPT: &str = "echo resume-with-global-flags-after-subcommand"; + let cli = Cli::parse_from([ + "codex-exec", + "resume", + "--last", + "--json", + "--model", + "gpt-5.2-codex", + "--dangerously-bypass-approvals-and-sandbox", + "--skip-git-repo-check", + PROMPT, + ]); + + let Some(Command::Resume(args)) = cli.command else { + panic!("expected resume command"); + }; + let effective_prompt = args.prompt.clone().or_else(|| { + if args.last { + args.session_id.clone() + } else { + None + } + }); + assert_eq!(effective_prompt.as_deref(), Some(PROMPT)); + } +} 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 0dfce33cb6..d43ce4387c 100644 --- a/codex-rs/exec/src/event_processor_with_jsonl_output.rs +++ b/codex-rs/exec/src/event_processor_with_jsonl_output.rs @@ -849,16 +849,17 @@ impl EventProcessor for EventProcessorWithJsonOutput { let protocol::Event { msg, .. } = event; - if let protocol::EventMsg::TurnComplete(protocol::TurnCompleteEvent { - last_agent_message, - }) = msg - { - if let Some(output_file) = self.last_message_path.as_deref() { - handle_last_message(last_agent_message.as_deref(), output_file); + match msg { + protocol::EventMsg::TurnComplete(protocol::TurnCompleteEvent { + last_agent_message, + }) => { + if let Some(output_file) = self.last_message_path.as_deref() { + handle_last_message(last_agent_message.as_deref(), output_file); + } + CodexStatus::InitiateShutdown } - CodexStatus::InitiateShutdown - } else { - CodexStatus::Running + protocol::EventMsg::ShutdownComplete => CodexStatus::Shutdown, + _ => CodexStatus::Running, } } } diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 441041aa68..f2c212d895 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -46,13 +46,17 @@ use codex_utils_absolute_path::AbsolutePathBuf; use event_processor_with_human_output::EventProcessorWithHumanOutput; use event_processor_with_jsonl_output::EventProcessorWithJsonOutput; use serde_json::Value; +use std::collections::HashSet; use std::io::IsTerminal; use std::io::Read; use std::path::PathBuf; +use std::sync::Arc; use supports_color::Stream; +use tokio::sync::Mutex; use tracing::debug; use tracing::error; use tracing::info; +use tracing::warn; use tracing_subscriber::EnvFilter; use tracing_subscriber::prelude::*; @@ -72,6 +76,13 @@ enum InitialOperation { }, } +#[derive(Clone)] +struct ThreadEventEnvelope { + thread_id: codex_protocol::ThreadId, + thread: Arc, + event: Event, +} + pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> anyhow::Result<()> { if let Err(err) = set_default_originator("codex_exec".to_string()) { tracing::warn!(?err, "Failed to set codex exec originator override {err:?}"); @@ -326,11 +337,11 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any true, config.cli_auth_credentials_store_mode, ); - let thread_manager = ThreadManager::new( + let thread_manager = Arc::new(ThreadManager::new( config.codex_home.clone(), auth_manager.clone(), SessionSource::Exec, - ); + )); let default_model = thread_manager .get_models_manager() .get_default_model(&config.model, &config, RefreshStrategy::OnlineIfUncached) @@ -338,7 +349,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any // Handle resume subcommand by resolving a rollout path and using explicit resume API. let NewThread { - thread_id: _, + thread_id: primary_thread_id, thread, session_configured, } = if let Some(ExecCommand::Resume(args)) = command.as_ref() { @@ -420,40 +431,47 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any info!("Codex initialized with event: {session_configured:?}"); - let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); + let attached_threads = Arc::new(Mutex::new(HashSet::from([primary_thread_id]))); + spawn_thread_listener(primary_thread_id, thread.clone(), tx.clone()); + { let thread = thread.clone(); + tokio::spawn(async move { + if tokio::signal::ctrl_c().await.is_ok() { + tracing::debug!("Keyboard interrupt"); + // Immediately notify Codex to abort any in-flight task. + thread.submit(Op::Interrupt).await.ok(); + } + }); + } + + { + let thread_manager = Arc::clone(&thread_manager); + let attached_threads = Arc::clone(&attached_threads); + let tx = tx.clone(); + let mut thread_created_rx = thread_manager.subscribe_thread_created(); tokio::spawn(async move { loop { - tokio::select! { - _ = tokio::signal::ctrl_c() => { - tracing::debug!("Keyboard interrupt"); - // Immediately notify Codex to abort any in‑flight task. - thread.submit(Op::Interrupt).await.ok(); - - // Exit the inner loop and return to the main input prompt. The codex - // will emit a `TurnInterrupted` (Error) event which is drained later. - break; - } - res = thread.next_event() => match res { - Ok(event) => { - debug!("Received event: {event:?}"); - - let is_shutdown_complete = matches!(event.msg, EventMsg::ShutdownComplete); - if let Err(e) = tx.send(event) { - error!("Error sending event: {e:?}"); - break; + match thread_created_rx.recv().await { + Ok(thread_id) => { + if attached_threads.lock().await.contains(&thread_id) { + continue; + } + match thread_manager.get_thread(thread_id).await { + Ok(thread) => { + attached_threads.lock().await.insert(thread_id); + spawn_thread_listener(thread_id, thread, tx.clone()); } - if is_shutdown_complete { - info!("Received shutdown event, exiting event loop."); - break; + Err(err) => { + warn!("failed to attach listener for thread {thread_id}: {err}") } - }, - Err(e) => { - error!("Error receiving event: {e:?}"); - break; } } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { + warn!("thread_created receiver lagged; skipping resync"); + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, } } }); @@ -492,7 +510,12 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any // Track whether a fatal error was reported by the server so we can // exit with a non-zero status for automation-friendly signaling. let mut error_seen = false; - while let Some(event) = rx.recv().await { + while let Some(envelope) = rx.recv().await { + let ThreadEventEnvelope { + thread_id, + thread, + event, + } = envelope; if let EventMsg::ElicitationRequest(ev) = &event.msg { // Automatically cancel elicitation requests in exec mode. thread @@ -506,15 +529,20 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any if matches!(event.msg, EventMsg::Error(_)) { error_seen = true; } - let shutdown: CodexStatus = event_processor.process_event(event); + if thread_id != primary_thread_id && matches!(&event.msg, EventMsg::TurnComplete(_)) { + continue; + } + let shutdown = event_processor.process_event(event); + if thread_id != primary_thread_id && matches!(shutdown, CodexStatus::InitiateShutdown) { + continue; + } match shutdown { CodexStatus::Running => continue, CodexStatus::InitiateShutdown => { thread.submit(Op::Shutdown).await?; } - CodexStatus::Shutdown => { - break; - } + CodexStatus::Shutdown if thread_id == primary_thread_id => break, + CodexStatus::Shutdown => continue, } } event_processor.print_final_output(); @@ -525,6 +553,42 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any Ok(()) } +fn spawn_thread_listener( + thread_id: codex_protocol::ThreadId, + thread: Arc, + tx: tokio::sync::mpsc::UnboundedSender, +) { + tokio::spawn(async move { + loop { + match thread.next_event().await { + Ok(event) => { + debug!("Received event: {event:?}"); + + let is_shutdown_complete = matches!(event.msg, EventMsg::ShutdownComplete); + if let Err(err) = tx.send(ThreadEventEnvelope { + thread_id, + thread: Arc::clone(&thread), + event, + }) { + error!("Error sending event: {err:?}"); + break; + } + if is_shutdown_complete { + info!( + "Received shutdown event for thread {thread_id}, exiting event loop." + ); + break; + } + } + Err(err) => { + error!("Error receiving event: {err:?}"); + break; + } + } + } + }); +} + async fn resolve_resume_path( config: &Config, args: &crate::cli::ResumeArgs, diff --git a/codex-rs/exec/src/main.rs b/codex-rs/exec/src/main.rs index 03ee533ea9..2d3db1f42e 100644 --- a/codex-rs/exec/src/main.rs +++ b/codex-rs/exec/src/main.rs @@ -38,3 +38,44 @@ fn main() -> anyhow::Result<()> { Ok(()) }) } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn top_cli_parses_resume_prompt_after_config_flag() { + const PROMPT: &str = "echo resume-with-global-flags-after-subcommand"; + let cli = TopCli::parse_from([ + "codex-exec", + "resume", + "--last", + "--json", + "--model", + "gpt-5.2-codex", + "--config", + "reasoning_level=xhigh", + "--dangerously-bypass-approvals-and-sandbox", + "--skip-git-repo-check", + PROMPT, + ]); + + let Some(codex_exec::Command::Resume(args)) = cli.inner.command else { + panic!("expected resume command"); + }; + let effective_prompt = args.prompt.clone().or_else(|| { + if args.last { + args.session_id.clone() + } else { + None + } + }); + assert_eq!(effective_prompt.as_deref(), Some(PROMPT)); + assert_eq!(cli.config_overrides.raw_overrides.len(), 1); + assert_eq!( + cli.config_overrides.raw_overrides[0], + "reasoning_level=xhigh" + ); + } +} From 3878c3dc7c88f356e3ec983dae30a01902a3ec53 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 28 Jan 2026 15:29:14 +0100 Subject: [PATCH 032/116] feat: sqlite 1 (#10004) Add a `.sqlite` database to be used to store rollout metatdata (and later logs) This PR is phase 1: * Add the database and the required infrastructure * Add a backfill of the database * Persist the newly created rollout both in files and in the DB * When we need to get metadata or a rollout, consider the `JSONL` as the source of truth but compare the results with the DB and show any errors --- .github/workflows/rust-ci.yml | 88 +++ .github/workflows/rust-release.yml | 77 ++- codex-rs/Cargo.lock | 503 +++++++++++++++++- codex-rs/Cargo.toml | 3 + .../app-server/src/codex_message_processor.rs | 29 +- codex-rs/core/Cargo.toml | 1 + codex-rs/core/config.schema.json | 6 + codex-rs/core/src/codex.rs | 40 +- codex-rs/core/src/codex_thread.rs | 6 + codex-rs/core/src/features.rs | 8 + codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/rollout/list.rs | 36 +- codex-rs/core/src/rollout/metadata.rs | 333 ++++++++++++ codex-rs/core/src/rollout/mod.rs | 1 + codex-rs/core/src/rollout/recorder.rs | 169 +++++- codex-rs/core/src/state/service.rs | 2 + codex-rs/core/src/state_db.rs | 303 +++++++++++ codex-rs/core/tests/suite/mod.rs | 1 + codex-rs/core/tests/suite/sqlite_state.rs | 199 +++++++ codex-rs/otel/src/metrics/mod.rs | 2 +- codex-rs/protocol/src/thread_id.rs | 24 +- codex-rs/state/BUILD.bazel | 7 + codex-rs/state/Cargo.toml | 23 + codex-rs/state/migrations/0001_threads.sql | 25 + codex-rs/state/src/extract.rs | 182 +++++++ codex-rs/state/src/lib.rs | 34 ++ codex-rs/state/src/migrations.rs | 3 + codex-rs/state/src/model.rs | 352 ++++++++++++ codex-rs/state/src/paths.rs | 10 + codex-rs/state/src/runtime.rs | 458 ++++++++++++++++ 30 files changed, 2882 insertions(+), 44 deletions(-) create mode 100644 codex-rs/core/src/rollout/metadata.rs create mode 100644 codex-rs/core/src/state_db.rs create mode 100644 codex-rs/core/tests/suite/sqlite_state.rs create mode 100644 codex-rs/state/BUILD.bazel create mode 100644 codex-rs/state/Cargo.toml create mode 100644 codex-rs/state/migrations/0001_threads.sql create mode 100644 codex-rs/state/src/extract.rs create mode 100644 codex-rs/state/src/lib.rs create mode 100644 codex-rs/state/src/migrations.rs create mode 100644 codex-rs/state/src/model.rs create mode 100644 codex-rs/state/src/paths.rs create mode 100644 codex-rs/state/src/runtime.rs diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index a8efec1089..fc2ab5a043 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -177,11 +177,31 @@ jobs: steps: - uses: actions/checkout@v6 + - name: Install UBSan runtime (musl) + if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl' }} + shell: bash + run: | + set -euo pipefail + if command -v apt-get >/dev/null 2>&1; then + sudo apt-get update -y + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y libubsan1 + fi - uses: dtolnay/rust-toolchain@1.92 with: targets: ${{ matrix.target }} components: clippy + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + name: Use hermetic Cargo home (musl) + shell: bash + run: | + set -euo pipefail + cargo_home="${GITHUB_WORKSPACE}/.cargo-home" + mkdir -p "${cargo_home}/bin" + echo "CARGO_HOME=${cargo_home}" >> "$GITHUB_ENV" + echo "${cargo_home}/bin" >> "$GITHUB_PATH" + : > "${cargo_home}/config.toml" + - name: Compute lockfile hash id: lockhash working-directory: codex-rs @@ -202,6 +222,10 @@ jobs: ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ + ${{ github.workspace }}/.cargo-home/bin/ + ${{ github.workspace }}/.cargo-home/registry/index/ + ${{ github.workspace }}/.cargo-home/registry/cache/ + ${{ github.workspace }}/.cargo-home/git/db/ key: cargo-home-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ steps.lockhash.outputs.hash }}-${{ steps.lockhash.outputs.toolchain_hash }} restore-keys: | cargo-home-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}- @@ -244,6 +268,14 @@ jobs: sccache-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ steps.lockhash.outputs.hash }}- sccache-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}- + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + name: Disable sccache wrapper (musl) + shell: bash + run: | + set -euo pipefail + echo "RUSTC_WRAPPER=" >> "$GITHUB_ENV" + echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV" + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} name: Prepare APT cache directories (musl) shell: bash @@ -277,6 +309,58 @@ jobs: shell: bash run: bash "${GITHUB_WORKSPACE}/.github/scripts/install-musl-build-tools.sh" + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + name: Configure rustc UBSan wrapper (musl host) + shell: bash + run: | + set -euo pipefail + ubsan="" + if command -v ldconfig >/dev/null 2>&1; then + ubsan="$(ldconfig -p | grep -m1 'libubsan\.so\.1' | sed -E 's/.*=> (.*)$/\1/')" + fi + wrapper_root="${RUNNER_TEMP:-/tmp}" + wrapper="${wrapper_root}/rustc-ubsan-wrapper" + cat > "${wrapper}" <> "$GITHUB_ENV" + echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV" + + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + name: Clear sanitizer flags (musl) + shell: bash + run: | + set -euo pipefail + # Clear global Rust flags so host/proc-macro builds don't pull in UBSan. + echo "RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_ENCODED_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "RUSTDOCFLAGS=" >> "$GITHUB_ENV" + # Override any runner-level Cargo config rustflags as well. + echo "CARGO_BUILD_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" + + sanitize_flags() { + local input="$1" + input="${input//-fsanitize=undefined/}" + input="${input//-fno-sanitize-recover=undefined/}" + input="${input//-fno-sanitize-trap=undefined/}" + echo "$input" + } + + cflags="$(sanitize_flags "${CFLAGS-}")" + cxxflags="$(sanitize_flags "${CXXFLAGS-}")" + echo "CFLAGS=${cflags}" >> "$GITHUB_ENV" + echo "CXXFLAGS=${cxxflags}" >> "$GITHUB_ENV" + - name: Install cargo-chef if: ${{ matrix.profile == 'release' }} uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2 @@ -322,6 +406,10 @@ jobs: ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ + ${{ github.workspace }}/.cargo-home/bin/ + ${{ github.workspace }}/.cargo-home/registry/index/ + ${{ github.workspace }}/.cargo-home/registry/cache/ + ${{ github.workspace }}/.cargo-home/git/db/ key: cargo-home-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ steps.lockhash.outputs.hash }}-${{ steps.lockhash.outputs.toolchain_hash }} - name: Save sccache cache (fallback) diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index e2f952ed06..7b8a4fe8a1 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -21,7 +21,6 @@ jobs: steps: - uses: actions/checkout@v6 - uses: dtolnay/rust-toolchain@1.92 - - name: Validate tag matches Cargo.toml version shell: bash run: | @@ -90,10 +89,30 @@ jobs: steps: - uses: actions/checkout@v6 + - name: Install UBSan runtime (musl) + if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl' }} + shell: bash + run: | + set -euo pipefail + if command -v apt-get >/dev/null 2>&1; then + sudo apt-get update -y + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y libubsan1 + fi - uses: dtolnay/rust-toolchain@1.92 with: targets: ${{ matrix.target }} + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + name: Use hermetic Cargo home (musl) + shell: bash + run: | + set -euo pipefail + cargo_home="${GITHUB_WORKSPACE}/.cargo-home" + mkdir -p "${cargo_home}/bin" + echo "CARGO_HOME=${cargo_home}" >> "$GITHUB_ENV" + echo "${cargo_home}/bin" >> "$GITHUB_PATH" + : > "${cargo_home}/config.toml" + - uses: actions/cache@v5 with: path: | @@ -101,6 +120,10 @@ jobs: ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ + ${{ github.workspace }}/.cargo-home/bin/ + ${{ github.workspace }}/.cargo-home/registry/index/ + ${{ github.workspace }}/.cargo-home/registry/cache/ + ${{ github.workspace }}/.cargo-home/git/db/ ${{ github.workspace }}/codex-rs/target/ key: cargo-${{ matrix.runner }}-${{ matrix.target }}-release-${{ hashFiles('**/Cargo.lock') }} @@ -116,6 +139,58 @@ jobs: TARGET: ${{ matrix.target }} run: bash "${GITHUB_WORKSPACE}/.github/scripts/install-musl-build-tools.sh" + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + name: Configure rustc UBSan wrapper (musl host) + shell: bash + run: | + set -euo pipefail + ubsan="" + if command -v ldconfig >/dev/null 2>&1; then + ubsan="$(ldconfig -p | grep -m1 'libubsan\.so\.1' | sed -E 's/.*=> (.*)$/\1/')" + fi + wrapper_root="${RUNNER_TEMP:-/tmp}" + wrapper="${wrapper_root}/rustc-ubsan-wrapper" + cat > "${wrapper}" <> "$GITHUB_ENV" + echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV" + + - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} + name: Clear sanitizer flags (musl) + shell: bash + run: | + set -euo pipefail + # Clear global Rust flags so host/proc-macro builds don't pull in UBSan. + echo "RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_ENCODED_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "RUSTDOCFLAGS=" >> "$GITHUB_ENV" + # Override any runner-level Cargo config rustflags as well. + echo "CARGO_BUILD_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" + + sanitize_flags() { + local input="$1" + input="${input//-fsanitize=undefined/}" + input="${input//-fno-sanitize-recover=undefined/}" + input="${input//-fno-sanitize-trap=undefined/}" + echo "$input" + } + + cflags="$(sanitize_flags "${CFLAGS-}")" + cxxflags="$(sanitize_flags "${CXXFLAGS-}")" + echo "CFLAGS=${cflags}" >> "$GITHUB_ENV" + echo "CXXFLAGS=${cxxflags}" >> "$GITHUB_ENV" + - name: Cargo build shell: bash run: | diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index e4fe78a3dc..38a86f1540 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -361,7 +361,7 @@ dependencies = [ "objc2-foundation", "parking_lot", "percent-encoding", - "windows-sys 0.52.0", + "windows-sys 0.60.2", "wl-clipboard-rs", "x11rb", ] @@ -602,6 +602,15 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -739,6 +748,9 @@ name = "bitflags" version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +dependencies = [ + "serde_core", +] [[package]] name = "block-buffer" @@ -1364,6 +1376,7 @@ dependencies = [ "codex-otel", "codex-protocol", "codex-rmcp-client", + "codex-state", "codex-utils-absolute-path", "codex-utils-cargo-bin", "codex-utils-pty", @@ -1828,6 +1841,23 @@ dependencies = [ "which", ] +[[package]] +name = "codex-state" +version = "0.0.0" +dependencies = [ + "anyhow", + "chrono", + "codex-otel", + "codex-protocol", + "pretty_assertions", + "serde", + "serde_json", + "sqlx", + "tokio", + "tracing", + "uuid", +] + [[package]] name = "codex-stdio-to-uds" version = "0.0.0" @@ -2111,6 +2141,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const_format" version = "0.2.35" @@ -2209,6 +2245,21 @@ dependencies = [ "libc", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" + [[package]] name = "crc32fast" version = "1.5.0" @@ -2252,6 +2303,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.21" @@ -2530,6 +2590,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ + "const-oid", "pem-rfc7468", "zeroize", ] @@ -2628,6 +2689,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", + "const-oid", "crypto-common", "subtle", ] @@ -2775,6 +2837,9 @@ name = "either" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +dependencies = [ + "serde", +] [[package]] name = "ena" @@ -2908,7 +2973,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -2917,6 +2982,17 @@ version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + [[package]] name = "event-listener" version = "5.4.0" @@ -3008,7 +3084,7 @@ checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" dependencies = [ "cfg-if", "rustix 1.0.8", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3085,6 +3161,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + [[package]] name = "flume" version = "0.12.0" @@ -3233,6 +3320,17 @@ dependencies = [ "futures-util", ] +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + [[package]] name = "futures-io" version = "0.3.31" @@ -3313,7 +3411,7 @@ dependencies = [ "libc", "log", "rustversion", - "windows-link 0.1.3", + "windows-link 0.2.0", "windows-result 0.3.4", ] @@ -3465,6 +3563,15 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.4", +] + [[package]] name = "heck" version = "0.5.0" @@ -3668,7 +3775,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots", + "webpki-roots 1.0.2", ] [[package]] @@ -4095,7 +4202,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -4300,6 +4407,9 @@ name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -4326,6 +4436,12 @@ dependencies = [ "windows-link 0.2.0", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.6" @@ -4334,6 +4450,18 @@ checksum = "4488594b9328dee448adb906d8b126d9b7deb7cf5c22161ee591610bb1be83c0" dependencies = [ "bitflags 2.10.0", "libc", + "redox_syscall", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", ] [[package]] @@ -4518,6 +4646,16 @@ dependencies = [ "wiremock", ] +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "md5" version = "0.8.0" @@ -4795,6 +4933,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.5", + "smallvec", + "zeroize", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -4848,6 +5002,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -5330,6 +5485,27 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.32" @@ -5673,7 +5849,7 @@ dependencies = [ "once_cell", "socket2 0.6.1", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -5943,7 +6119,7 @@ checksum = "b28ee9e1e5d39264414b71f5c33e7fbb66b382c3fac456fe0daad39cf5509933" dependencies = [ "ahash", "const_format", - "flume", + "flume 0.12.0", "hex", "ipnet", "itertools 0.14.0", @@ -6001,7 +6177,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "def3d5d06d3ca3a2d2e4376cf93de0555cd9c7960f085bf77be9562f5c9ace8f" dependencies = [ "ahash", - "flume", + "flume 0.12.0", "itertools 0.14.0", "moka", "parking_lot", @@ -6293,7 +6469,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", - "webpki-roots", + "webpki-roots 1.0.2", ] [[package]] @@ -6364,6 +6540,26 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-demangle" version = "0.1.25" @@ -6395,7 +6591,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6408,7 +6604,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.9.4", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -7113,6 +7309,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.7" @@ -7197,6 +7403,218 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.4", + "hashlink", + "indexmap 2.12.0", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror 2.0.17", + "time", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.104", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.104", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags 2.10.0", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand 0.8.5", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror 2.0.17", + "time", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags 2.10.0", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand 0.8.5", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror 2.0.17", + "time", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "chrono", + "flume 0.11.1", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror 2.0.17", + "time", + "tracing", + "url", + "uuid", +] + [[package]] name = "sse-stream" version = "0.2.1" @@ -7330,6 +7748,17 @@ dependencies = [ "precomputed-hash", ] +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strsim" version = "0.10.0" @@ -7495,7 +7924,7 @@ dependencies = [ "getrandom 0.3.3", "once_cell", "rustix 1.0.8", - "windows-sys 0.52.0", + "windows-sys 0.61.1", ] [[package]] @@ -8290,6 +8719,12 @@ version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.18" @@ -8302,6 +8737,21 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + [[package]] name = "unicode-segmentation" version = "1.12.0" @@ -8509,6 +8959,12 @@ dependencies = [ "wit-bindgen-rt", ] +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + [[package]] name = "wasm-bindgen" version = "0.2.100" @@ -8708,6 +9164,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.2", +] + [[package]] name = "webpki-roots" version = "1.0.2" @@ -8734,6 +9199,16 @@ dependencies = [ "winsafe", ] +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + [[package]] name = "widestring" version = "1.2.1" @@ -8777,7 +9252,7 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index a8ebb9be89..ae4eb768bc 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -47,6 +47,7 @@ members = [ "utils/string", "codex-client", "codex-api", + "state", ] resolver = "2" @@ -91,6 +92,7 @@ codex-process-hardening = { path = "process-hardening" } codex-protocol = { path = "protocol" } codex-responses-api-proxy = { path = "responses-api-proxy" } codex-rmcp-client = { path = "rmcp-client" } +codex-state = { path = "state" } codex-stdio-to-uds = { path = "stdio-to-uds" } codex-tui = { path = "tui" } codex-utils-absolute-path = { path = "utils/absolute-path" } @@ -198,6 +200,7 @@ semver = "1.0" shlex = "1.3.0" similar = "2.7.0" socket2 = "0.6.1" +sqlx = { version = "0.8.6", default-features = false, features = ["chrono", "json", "macros", "migrate", "runtime-tokio-rustls", "sqlite", "time", "uuid"] } starlark = "0.13.0" strum = "0.27.2" strum_macros = "0.27.2" diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index e7acf3d290..c70f705a96 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -169,6 +169,7 @@ use codex_core::read_head_for_summary; use codex_core::read_session_meta_line; use codex_core::rollout_date_parts; use codex_core::sandboxing::SandboxPermissions; +use codex_core::state_db::{self}; use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_feedback::CodexFeedback; use codex_login::ServerOptions as LoginServerOptions; @@ -1609,6 +1610,7 @@ impl CodexMessageProcessor { } async fn thread_archive(&mut self, request_id: RequestId, params: ThreadArchiveParams) { + // TODO(jif) mostly rewrite this using sqlite after phase 1 let thread_id = match ThreadId::from_string(¶ms.thread_id) { Ok(id) => id, Err(err) => { @@ -1658,6 +1660,7 @@ impl CodexMessageProcessor { } async fn thread_unarchive(&mut self, request_id: RequestId, params: ThreadUnarchiveParams) { + // TODO(jif) mostly rewrite this using sqlite after phase 1 let thread_id = match ThreadId::from_string(¶ms.thread_id) { Ok(id) => id, Err(err) => { @@ -1700,6 +1703,7 @@ impl CodexMessageProcessor { let rollout_path_display = archived_path.display().to_string(); let fallback_provider = self.config.model_provider_id.clone(); + let state_db_ctx = state_db::init_if_enabled(&self.config, None).await; let archived_folder = self .config .codex_home @@ -1778,6 +1782,11 @@ impl CodexMessageProcessor { message: format!("failed to unarchive thread: {err}"), data: None, })?; + if let Some(ctx) = state_db_ctx { + let _ = ctx + .mark_unarchived(thread_id, restored_path.as_path()) + .await; + } let summary = read_summary_from_rollout(restored_path.as_path(), fallback_provider.as_str()) .await @@ -2507,7 +2516,6 @@ impl CodexMessageProcessor { }; let fallback_provider = self.config.model_provider_id.as_str(); - match read_summary_from_rollout(&path, fallback_provider).await { Ok(summary) => { let response = GetConversationSummaryResponse { summary }; @@ -3530,8 +3538,13 @@ impl CodexMessageProcessor { }); } + let mut state_db_ctx = None; + // If the thread is active, request shutdown and wait briefly. if let Some(conversation) = self.thread_manager.remove_thread(&thread_id).await { + if let Some(ctx) = conversation.state_db() { + state_db_ctx = Some(ctx); + } info!("thread {thread_id} was active; shutting down"); // Request shutdown. match conversation.submit(Op::Shutdown).await { @@ -3558,14 +3571,24 @@ impl CodexMessageProcessor { } } + if state_db_ctx.is_none() { + state_db_ctx = state_db::init_if_enabled(&self.config, None).await; + } + // Move the rollout file to archived. - let result: std::io::Result<()> = async { + let result: std::io::Result<()> = async move { let archive_folder = self .config .codex_home .join(codex_core::ARCHIVED_SESSIONS_SUBDIR); tokio::fs::create_dir_all(&archive_folder).await?; - tokio::fs::rename(&canonical_rollout_path, &archive_folder.join(&file_name)).await?; + let archived_path = archive_folder.join(&file_name); + tokio::fs::rename(&canonical_rollout_path, &archived_path).await?; + if let Some(ctx) = state_db_ctx { + let _ = ctx + .mark_archived(thread_id, archived_path.as_path(), Utc::now()) + .await; + } Ok(()) } .await; diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index c186758cb4..b336b296c6 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -37,6 +37,7 @@ codex-keyring-store = { workspace = true } codex-otel = { workspace = true } codex-protocol = { workspace = true } codex-rmcp-client = { workspace = true } +codex-state = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-pty = { workspace = true } codex-utils-readiness = { workspace = true } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index c11256c70d..a756352da0 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -204,6 +204,9 @@ "skill_mcp_dependency_install": { "type": "boolean" }, + "sqlite": { + "type": "boolean" + }, "steer": { "type": "boolean" }, @@ -1202,6 +1205,9 @@ "skill_mcp_dependency_install": { "type": "boolean" }, + "sqlite": { + "type": "boolean" + }, "steer": { "type": "boolean" }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index e9fbecfa90..e21eff9749 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -154,6 +154,7 @@ use crate::protocol::WarningEvent; use crate::rollout::RolloutRecorder; use crate::rollout::RolloutRecorderParams; use crate::rollout::map_session_init_error; +use crate::rollout::metadata; use crate::shell; use crate::shell_snapshot::ShellSnapshot; use crate::skills::SkillError; @@ -165,6 +166,7 @@ use crate::skills::collect_explicit_skill_mentions; use crate::state::ActiveTurn; use crate::state::SessionServices; use crate::state::SessionState; +use crate::state_db; use crate::tasks::GhostSnapshotTask; use crate::tasks::ReviewTask; use crate::tasks::SessionTask; @@ -420,6 +422,10 @@ impl Codex { let state = self.session.state.lock().await; state.session_configuration.thread_config_snapshot() } + + pub(crate) fn state_db(&self) -> Option { + self.session.state_db() + } } /// Context for an initialized model agent @@ -699,6 +705,13 @@ impl Session { RolloutRecorderParams::resume(resumed_history.rollout_path.clone()), ), }; + let state_builder = match &initial_history { + InitialHistory::Resumed(resumed) => metadata::builder_from_items( + resumed.history.as_slice(), + resumed.rollout_path.as_path(), + ), + InitialHistory::New | InitialHistory::Forked(_) => None, + }; // Kick off independent async setup tasks in parallel to reduce startup latency. // @@ -707,11 +720,17 @@ impl Session { // - load history metadata let rollout_fut = async { if config.ephemeral { - Ok(None) + Ok::<_, anyhow::Error>((None, None)) } else { - RolloutRecorder::new(&config, rollout_params) - .await - .map(Some) + let state_db_ctx = state_db::init_if_enabled(&config, None).await; + let rollout_recorder = RolloutRecorder::new( + &config, + rollout_params, + state_db_ctx.clone(), + state_builder.clone(), + ) + .await?; + Ok((Some(rollout_recorder), state_db_ctx)) } }; @@ -731,14 +750,14 @@ impl Session { // Join all independent futures. let ( - rollout_recorder, + rollout_recorder_and_state_db, (history_log_id, history_entry_count), (auth, mcp_servers, auth_statuses), ) = tokio::join!(rollout_fut, history_meta_fut, auth_and_mcp_fut); - let rollout_recorder = rollout_recorder.map_err(|e| { + let (rollout_recorder, state_db_ctx) = rollout_recorder_and_state_db.map_err(|e| { error!("failed to initialize rollout recorder: {e:#}"); - anyhow::Error::from(e) + e })?; let rollout_path = rollout_recorder .as_ref() @@ -842,6 +861,7 @@ impl Session { tool_approvals: Mutex::new(ApprovalStore::default()), skills_manager, agent_control, + state_db: state_db_ctx.clone(), }; let sess = Arc::new(Session { @@ -914,6 +934,10 @@ impl Session { self.tx_event.clone() } + pub(crate) fn state_db(&self) -> Option { + self.services.state_db.clone() + } + /// Ensure all rollout writes are durably flushed. pub(crate) async fn flush_rollout(&self) { let recorder = { @@ -4580,6 +4604,7 @@ mod tests { tool_approvals: Mutex::new(ApprovalStore::default()), skills_manager, agent_control, + state_db: None, }; let turn_context = Session::make_turn_context( @@ -4691,6 +4716,7 @@ mod tests { tool_approvals: Mutex::new(ApprovalStore::default()), skills_manager, agent_control, + state_db: None, }; let turn_context = Arc::new(Session::make_turn_context( diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 152679d146..fb8e466d71 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -12,6 +12,8 @@ use codex_protocol::protocol::SessionSource; use std::path::PathBuf; use tokio::sync::watch; +use crate::state_db::StateDbHandle; + #[derive(Clone, Debug)] pub struct ThreadConfigSnapshot { pub model: String, @@ -64,6 +66,10 @@ impl CodexThread { self.rollout_path.clone() } + pub fn state_db(&self) -> Option { + self.codex.state_db() + } + pub async fn config_snapshot(&self) -> ThreadConfigSnapshot { self.codex.thread_config_snapshot().await } diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index bd739e5a75..22371babd6 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -101,6 +101,8 @@ pub enum Feature { RemoteModels, /// Experimental shell snapshotting. ShellSnapshot, + /// Persist rollout metadata to a local SQLite database. + Sqlite, /// Append additional AGENTS.md guidance to user instructions. ChildAgentsMd, /// Enforce UTF8 output in Powershell. @@ -377,6 +379,12 @@ pub const FEATURES: &[FeatureSpec] = &[ }, default_enabled: false, }, + FeatureSpec { + id: Feature::Sqlite, + key: "sqlite", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::ChildAgentsMd, key: "child_agents_md", diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 27fa255c85..eaf25d14e8 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -91,6 +91,7 @@ pub mod shell; pub mod shell_snapshot; pub mod skills; pub mod spawn; +pub mod state_db; pub mod terminal; mod tools; pub mod turn_diff_tracker; diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index 9609f366b2..7469bbeb08 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -19,7 +19,9 @@ use uuid::Uuid; use super::ARCHIVED_SESSIONS_SUBDIR; use super::SESSIONS_SUBDIR; use crate::protocol::EventMsg; +use crate::state_db; use codex_file_search as file_search; +use codex_protocol::ThreadId; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionMetaLine; @@ -794,7 +796,7 @@ async fn collect_rollout_day_files( Ok(day_files) } -fn parse_timestamp_uuid_from_filename(name: &str) -> Option<(OffsetDateTime, Uuid)> { +pub(crate) fn parse_timestamp_uuid_from_filename(name: &str) -> Option<(OffsetDateTime, Uuid)> { // Expected: rollout-YYYY-MM-DDThh-mm-ss-.jsonl let core = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?; @@ -1093,11 +1095,39 @@ async fn find_thread_path_by_id_str_in_subdir( ) .map_err(|e| io::Error::other(format!("file search failed: {e}")))?; - Ok(results + let found = results .matches .into_iter() .next() - .map(|m| root.join(m.path))) + .map(|m| root.join(m.path)); + + // Checking if DB is at parity. + // TODO(jif): sqlite migration phase 1 + let archived_only = match subdir { + SESSIONS_SUBDIR => Some(false), + ARCHIVED_SESSIONS_SUBDIR => Some(true), + _ => None, + }; + let state_db_ctx = state_db::open_if_present(codex_home, "").await; + if let Some(state_db_ctx) = state_db_ctx.as_deref() + && let Ok(thread_id) = ThreadId::from_string(id_str) + { + let db_path = state_db::find_rollout_path_by_id( + Some(state_db_ctx), + thread_id, + archived_only, + "find_path_query", + ) + .await; + let canonical_path = found.as_deref(); + if db_path.as_deref() != canonical_path { + tracing::warn!( + "state db path mismatch for thread {thread_id:?}: canonical={canonical_path:?} db={db_path:?}" + ); + state_db::record_discrepancy("find_thread_path_by_id_str_in_subdir", "path_mismatch"); + } + } + Ok(found) } /// Locate a recorded thread rollout file by its UUID string using the existing diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs new file mode 100644 index 0000000000..0d6fedc272 --- /dev/null +++ b/codex-rs/core/src/rollout/metadata.rs @@ -0,0 +1,333 @@ +use crate::config::Config; +use crate::rollout; +use crate::rollout::list::parse_timestamp_uuid_from_filename; +use crate::rollout::recorder::RolloutRecorder; +use chrono::DateTime; +use chrono::NaiveDateTime; +use chrono::Timelike; +use chrono::Utc; +use codex_otel::OtelManager; +use codex_protocol::ThreadId; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::SessionSource; +use codex_state::BackfillStats; +use codex_state::DB_ERROR_METRIC; +use codex_state::ExtractionOutcome; +use codex_state::ThreadMetadataBuilder; +use codex_state::apply_rollout_item; +use std::path::Path; +use std::path::PathBuf; +use tracing::warn; + +const ROLLOUT_PREFIX: &str = "rollout-"; +const ROLLOUT_SUFFIX: &str = ".jsonl"; + +pub(crate) fn builder_from_session_meta( + session_meta: &SessionMetaLine, + rollout_path: &Path, +) -> Option { + let created_at = parse_timestamp_to_utc(session_meta.meta.timestamp.as_str())?; + let mut builder = ThreadMetadataBuilder::new( + session_meta.meta.id, + rollout_path.to_path_buf(), + created_at, + session_meta.meta.source.clone(), + ); + builder.model_provider = session_meta.meta.model_provider.clone(); + builder.cwd = session_meta.meta.cwd.clone(); + builder.sandbox_policy = SandboxPolicy::ReadOnly; + builder.approval_mode = AskForApproval::OnRequest; + if let Some(git) = session_meta.git.as_ref() { + builder.git_sha = git.commit_hash.clone(); + builder.git_branch = git.branch.clone(); + builder.git_origin_url = git.repository_url.clone(); + } + Some(builder) +} + +pub(crate) fn builder_from_items( + items: &[RolloutItem], + rollout_path: &Path, +) -> Option { + if let Some(session_meta) = items.iter().find_map(|item| match item { + RolloutItem::SessionMeta(meta_line) => Some(meta_line), + RolloutItem::ResponseItem(_) + | RolloutItem::Compacted(_) + | RolloutItem::TurnContext(_) + | RolloutItem::EventMsg(_) => None, + }) && let Some(builder) = builder_from_session_meta(session_meta, rollout_path) + { + return Some(builder); + } + + let file_name = rollout_path.file_name()?.to_str()?; + if !file_name.starts_with(ROLLOUT_PREFIX) || !file_name.ends_with(ROLLOUT_SUFFIX) { + return None; + } + let (created_ts, uuid) = parse_timestamp_uuid_from_filename(file_name)?; + let created_at = + DateTime::::from_timestamp(created_ts.unix_timestamp(), 0)?.with_nanosecond(0)?; + let id = ThreadId::from_string(&uuid.to_string()).ok()?; + Some(ThreadMetadataBuilder::new( + id, + rollout_path.to_path_buf(), + created_at, + SessionSource::default(), + )) +} + +pub(crate) async fn extract_metadata_from_rollout( + rollout_path: &Path, + default_provider: &str, + otel: Option<&OtelManager>, +) -> anyhow::Result { + let (items, _thread_id, parse_errors) = + RolloutRecorder::load_rollout_items(rollout_path).await?; + if items.is_empty() { + return Err(anyhow::anyhow!( + "empty session file: {}", + rollout_path.display() + )); + } + let builder = builder_from_items(items.as_slice(), rollout_path).ok_or_else(|| { + anyhow::anyhow!( + "rollout missing metadata builder: {}", + rollout_path.display() + ) + })?; + let mut metadata = builder.build(default_provider); + for item in &items { + apply_rollout_item(&mut metadata, item, default_provider); + } + if let Some(updated_at) = file_modified_time_utc(rollout_path).await { + metadata.updated_at = updated_at; + } + if parse_errors > 0 + && let Some(otel) = otel + { + otel.counter( + DB_ERROR_METRIC, + parse_errors as i64, + &[("stage", "extract_metadata_from_rollout")], + ); + } + Ok(ExtractionOutcome { + metadata, + parse_errors, + }) +} + +pub(crate) async fn backfill_sessions( + runtime: &codex_state::StateRuntime, + config: &Config, + otel: Option<&OtelManager>, +) -> BackfillStats { + let sessions_root = config.codex_home.join(rollout::SESSIONS_SUBDIR); + let archived_root = config.codex_home.join(rollout::ARCHIVED_SESSIONS_SUBDIR); + let mut rollout_paths: Vec<(PathBuf, bool)> = Vec::new(); + for (root, archived) in [(sessions_root, false), (archived_root, true)] { + if !tokio::fs::try_exists(&root).await.unwrap_or(false) { + continue; + } + match collect_rollout_paths(&root).await { + Ok(paths) => { + rollout_paths.extend(paths.into_iter().map(|path| (path, archived))); + } + Err(err) => { + warn!( + "failed to collect rollout paths under {}: {err}", + root.display() + ); + } + } + } + let mut stats = BackfillStats { + scanned: 0, + upserted: 0, + failed: 0, + }; + for (path, archived) in rollout_paths { + stats.scanned = stats.scanned.saturating_add(1); + match extract_metadata_from_rollout(&path, config.model_provider_id.as_str(), otel).await { + Ok(outcome) => { + if outcome.parse_errors > 0 + && let Some(otel) = otel + { + otel.counter( + DB_ERROR_METRIC, + outcome.parse_errors as i64, + &[("stage", "backfill_sessions")], + ); + } + let mut metadata = outcome.metadata; + if archived && metadata.archived_at.is_none() { + let fallback_archived_at = metadata.updated_at; + metadata.archived_at = file_modified_time_utc(&path) + .await + .or(Some(fallback_archived_at)); + } + if let Err(err) = runtime.upsert_thread(&metadata).await { + stats.failed = stats.failed.saturating_add(1); + warn!("failed to upsert rollout {}: {err}", path.display()); + } else { + stats.upserted = stats.upserted.saturating_add(1); + } + } + Err(err) => { + stats.failed = stats.failed.saturating_add(1); + warn!("failed to extract rollout {}: {err}", path.display()); + } + } + } + stats +} + +async fn file_modified_time_utc(path: &Path) -> Option> { + let modified = tokio::fs::metadata(path).await.ok()?.modified().ok()?; + let updated_at: DateTime = modified.into(); + updated_at.with_nanosecond(0) +} + +fn parse_timestamp_to_utc(ts: &str) -> Option> { + const FILENAME_TS_FORMAT: &str = "%Y-%m-%dT%H-%M-%S"; + if let Ok(naive) = NaiveDateTime::parse_from_str(ts, FILENAME_TS_FORMAT) { + let dt = DateTime::::from_naive_utc_and_offset(naive, Utc); + return dt.with_nanosecond(0); + } + if let Ok(dt) = DateTime::parse_from_rfc3339(ts) { + return dt.with_timezone(&Utc).with_nanosecond(0); + } + None +} + +async fn collect_rollout_paths(root: &Path) -> std::io::Result> { + let mut stack = vec![root.to_path_buf()]; + let mut paths = Vec::new(); + while let Some(dir) = stack.pop() { + let mut read_dir = match tokio::fs::read_dir(&dir).await { + Ok(read_dir) => read_dir, + Err(err) => { + warn!("failed to read directory {}: {err}", dir.display()); + continue; + } + }; + while let Some(entry) = read_dir.next_entry().await? { + let path = entry.path(); + let file_type = entry.file_type().await?; + if file_type.is_dir() { + stack.push(path); + continue; + } + if !file_type.is_file() { + continue; + } + let file_name = entry.file_name(); + let Some(name) = file_name.to_str() else { + continue; + }; + if name.starts_with(ROLLOUT_PREFIX) && name.ends_with(ROLLOUT_SUFFIX) { + paths.push(path); + } + } + } + Ok(paths) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::DateTime; + use chrono::NaiveDateTime; + use chrono::Timelike; + use chrono::Utc; + use codex_protocol::ThreadId; + use codex_protocol::protocol::CompactedItem; + use codex_protocol::protocol::RolloutItem; + use codex_protocol::protocol::RolloutLine; + use codex_protocol::protocol::SessionMeta; + use codex_protocol::protocol::SessionMetaLine; + use codex_protocol::protocol::SessionSource; + use codex_state::ThreadMetadataBuilder; + use pretty_assertions::assert_eq; + use std::fs::File; + use std::io::Write; + use tempfile::tempdir; + use uuid::Uuid; + + #[tokio::test] + async fn extract_metadata_from_rollout_uses_session_meta() { + let dir = tempdir().expect("tempdir"); + let uuid = Uuid::new_v4(); + let id = ThreadId::from_string(&uuid.to_string()).expect("thread id"); + let path = dir + .path() + .join(format!("rollout-2026-01-27T12-34-56-{uuid}.jsonl")); + + let session_meta = SessionMeta { + id, + forked_from_id: None, + timestamp: "2026-01-27T12:34:56Z".to_string(), + cwd: dir.path().to_path_buf(), + originator: "cli".to_string(), + cli_version: "0.0.0".to_string(), + source: SessionSource::default(), + model_provider: Some("openai".to_string()), + base_instructions: None, + }; + let session_meta_line = SessionMetaLine { + meta: session_meta, + git: None, + }; + let rollout_line = RolloutLine { + timestamp: "2026-01-27T12:34:56Z".to_string(), + item: RolloutItem::SessionMeta(session_meta_line.clone()), + }; + let json = serde_json::to_string(&rollout_line).expect("rollout json"); + let mut file = File::create(&path).expect("create rollout"); + writeln!(file, "{json}").expect("write rollout"); + + let outcome = extract_metadata_from_rollout(&path, "openai", None) + .await + .expect("extract"); + + let builder = + builder_from_session_meta(&session_meta_line, path.as_path()).expect("builder"); + let mut expected = builder.build("openai"); + apply_rollout_item(&mut expected, &rollout_line.item, "openai"); + expected.updated_at = file_modified_time_utc(&path).await.expect("mtime"); + + assert_eq!(outcome.metadata, expected); + assert_eq!(outcome.parse_errors, 0); + } + + #[test] + fn builder_from_items_falls_back_to_filename() { + let dir = tempdir().expect("tempdir"); + let uuid = Uuid::new_v4(); + let path = dir + .path() + .join(format!("rollout-2026-01-27T12-34-56-{uuid}.jsonl")); + let items = vec![RolloutItem::Compacted(CompactedItem { + message: "noop".to_string(), + replacement_history: None, + })]; + + let builder = builder_from_items(items.as_slice(), path.as_path()).expect("builder"); + let naive = NaiveDateTime::parse_from_str("2026-01-27T12-34-56", "%Y-%m-%dT%H-%M-%S") + .expect("timestamp"); + let created_at = DateTime::::from_naive_utc_and_offset(naive, Utc) + .with_nanosecond(0) + .expect("nanosecond"); + let expected = ThreadMetadataBuilder::new( + ThreadId::from_string(&uuid.to_string()).expect("thread id"), + path, + created_at, + SessionSource::default(), + ); + + assert_eq!(builder, expected); + } +} diff --git a/codex-rs/core/src/rollout/mod.rs b/codex-rs/core/src/rollout/mod.rs index fbddfecf35..cfc2d82d8d 100644 --- a/codex-rs/core/src/rollout/mod.rs +++ b/codex-rs/core/src/rollout/mod.rs @@ -9,6 +9,7 @@ pub const INTERACTIVE_SESSION_SOURCES: &[SessionSource] = pub(crate) mod error; pub mod list; +pub(crate) mod metadata; pub(crate) mod policy; pub mod recorder; pub(crate) mod truncation; diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index 53425051cf..cc35850544 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -28,11 +28,14 @@ use super::list::ThreadSortKey; use super::list::ThreadsPage; use super::list::get_threads; use super::list::get_threads_in_root; +use super::metadata; use super::policy::is_persisted_response_item; use crate::config::Config; use crate::default_client::originator; use crate::git_info::collect_git_info; use crate::path_utils; +use crate::state_db; +use crate::state_db::StateDbHandle; use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::ResumedHistory; use codex_protocol::protocol::RolloutItem; @@ -40,6 +43,7 @@ use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; +use codex_state::ThreadMetadataBuilder; /// Records all [`ResponseItem`]s for a session and flushes them to disk after /// every update. @@ -54,6 +58,7 @@ use codex_protocol::protocol::SessionSource; pub struct RolloutRecorder { tx: Sender, pub(crate) rollout_path: PathBuf, + state_db: Option, } #[derive(Clone)] @@ -111,7 +116,8 @@ impl RolloutRecorder { model_providers: Option<&[String]>, default_provider: &str, ) -> std::io::Result { - get_threads( + let stage = "list_threads"; + let page = get_threads( codex_home, page_size, cursor, @@ -120,7 +126,34 @@ impl RolloutRecorder { model_providers, default_provider, ) + .await?; + + // TODO(jif): drop after sqlite migration phase 1 + let state_db_ctx = state_db::open_if_present(codex_home, default_provider).await; + if let Some(db_ids) = state_db::list_thread_ids_db( + state_db_ctx.as_deref(), + codex_home, + page_size, + cursor, + sort_key, + allowed_sources, + model_providers, + false, + stage, + ) .await + { + if page.items.len() != db_ids.len() { + state_db::record_discrepancy(stage, "bad_len"); + return Ok(page); + } + for (id, item) in db_ids.iter().zip(page.items.iter()) { + if !item.path.display().to_string().contains(&id.to_string()) { + state_db::record_discrepancy(stage, "bad_id"); + } + } + } + Ok(page) } /// List archived threads (rollout files) under the archived sessions directory. @@ -133,8 +166,9 @@ impl RolloutRecorder { model_providers: Option<&[String]>, default_provider: &str, ) -> std::io::Result { + let stage = "list_archived_threads"; let root = codex_home.join(ARCHIVED_SESSIONS_SUBDIR); - get_threads_in_root( + let page = get_threads_in_root( root, page_size, cursor, @@ -146,7 +180,34 @@ impl RolloutRecorder { layout: ThreadListLayout::Flat, }, ) + .await?; + + // TODO(jif): drop after sqlite migration phase 1 + let state_db_ctx = state_db::open_if_present(codex_home, default_provider).await; + if let Some(db_ids) = state_db::list_thread_ids_db( + state_db_ctx.as_deref(), + codex_home, + page_size, + cursor, + sort_key, + allowed_sources, + model_providers, + true, + stage, + ) .await + { + if page.items.len() != db_ids.len() { + state_db::record_discrepancy(stage, "bad_len"); + return Ok(page); + } + for (id, item) in db_ids.iter().zip(page.items.iter()) { + if !item.path.display().to_string().contains(&id.to_string()) { + state_db::record_discrepancy(stage, "bad_id"); + } + } + } + Ok(page) } /// Find the newest recorded thread path, optionally filtering to a matching cwd. @@ -186,7 +247,12 @@ impl RolloutRecorder { /// Attempt to create a new [`RolloutRecorder`]. If the sessions directory /// cannot be created or the rollout file cannot be opened we return the /// error so the caller can decide whether to disable persistence. - pub async fn new(config: &Config, params: RolloutRecorderParams) -> std::io::Result { + pub async fn new( + config: &Config, + params: RolloutRecorderParams, + state_db_ctx: Option, + state_builder: Option, + ) -> std::io::Result { let (file, rollout_path, meta) = match params { RolloutRecorderParams::Create { conversation_id, @@ -246,9 +312,30 @@ impl RolloutRecorder { // Spawn a Tokio task that owns the file handle and performs async // writes. Using `tokio::fs::File` keeps everything on the async I/O // driver instead of blocking the runtime. - tokio::task::spawn(rollout_writer(file, rx, meta, cwd)); + tokio::task::spawn(rollout_writer( + file, + rx, + meta, + cwd, + rollout_path.clone(), + state_db_ctx.clone(), + state_builder, + config.model_provider_id.clone(), + )); - Ok(Self { tx, rollout_path }) + Ok(Self { + tx, + rollout_path, + state_db: state_db_ctx, + }) + } + + pub fn rollout_path(&self) -> &Path { + self.rollout_path.as_path() + } + + pub fn state_db(&self) -> Option { + self.state_db.clone() } pub(crate) async fn record_items(&self, items: &[RolloutItem]) -> std::io::Result<()> { @@ -281,7 +368,9 @@ impl RolloutRecorder { .map_err(|e| IoError::other(format!("failed waiting for rollout flush: {e}"))) } - pub async fn get_rollout_history(path: &Path) -> std::io::Result { + pub(crate) async fn load_rollout_items( + path: &Path, + ) -> std::io::Result<(Vec, Option, usize)> { info!("Resuming rollout from {path:?}"); let text = tokio::fs::read_to_string(path).await?; if text.trim().is_empty() { @@ -290,6 +379,7 @@ impl RolloutRecorder { let mut items: Vec = Vec::new(); let mut thread_id: Option = None; + let mut parse_errors = 0usize; for line in text.lines() { if line.trim().is_empty() { continue; @@ -298,6 +388,7 @@ impl RolloutRecorder { Ok(v) => v, Err(e) => { warn!("failed to parse line as JSON: {line:?}, error: {e}"); + parse_errors = parse_errors.saturating_add(1); continue; } }; @@ -328,15 +419,22 @@ impl RolloutRecorder { }, Err(e) => { warn!("failed to parse rollout line: {v:?}, error: {e}"); + parse_errors = parse_errors.saturating_add(1); } } } info!( - "Resumed rollout with {} items, thread ID: {:?}", + "Resumed rollout with {} items, thread ID: {:?}, parse errors: {}", items.len(), - thread_id + thread_id, + parse_errors, ); + Ok((items, thread_id, parse_errors)) + } + + pub async fn get_rollout_history(path: &Path) -> std::io::Result { + let (items, thread_id, _parse_errors) = Self::load_rollout_items(path).await?; let conversation_id = thread_id .ok_or_else(|| IoError::other("failed to parse thread ID from rollout file"))?; @@ -417,13 +515,21 @@ fn create_log_file(config: &Config, conversation_id: ThreadId) -> std::io::Resul }) } +#[allow(clippy::too_many_arguments)] async fn rollout_writer( file: tokio::fs::File, mut rx: mpsc::Receiver, mut meta: Option, cwd: std::path::PathBuf, + rollout_path: PathBuf, + state_db_ctx: Option, + mut state_builder: Option, + default_provider: String, ) -> std::io::Result<()> { let mut writer = JsonlWriter { file }; + if let Some(builder) = state_builder.as_mut() { + builder.rollout_path = rollout_path.clone(); + } // If we have a meta, collect git info asynchronously and write meta first if let Some(session_meta) = meta.take() { @@ -432,22 +538,50 @@ async fn rollout_writer( meta: session_meta, git: git_info, }; + if state_db_ctx.is_some() { + state_builder = + metadata::builder_from_session_meta(&session_meta_line, rollout_path.as_path()); + } // Write the SessionMeta as the first item in the file, wrapped in a rollout line - writer - .write_rollout_item(RolloutItem::SessionMeta(session_meta_line)) - .await?; + let rollout_item = RolloutItem::SessionMeta(session_meta_line); + writer.write_rollout_item(&rollout_item).await?; + state_db::reconcile_rollout( + state_db_ctx.as_deref(), + rollout_path.as_path(), + default_provider.as_str(), + state_builder.as_ref(), + std::slice::from_ref(&rollout_item), + ) + .await; } // Process rollout commands while let Some(cmd) = rx.recv().await { match cmd { RolloutCmd::AddItems(items) => { + let mut persisted_items = Vec::new(); for item in items { if is_persisted_response_item(&item) { - writer.write_rollout_item(item).await?; + writer.write_rollout_item(&item).await?; + persisted_items.push(item); } } + if persisted_items.is_empty() { + continue; + } + if let Some(builder) = state_builder.as_mut() { + builder.rollout_path = rollout_path.clone(); + } + state_db::apply_rollout_items( + state_db_ctx.as_deref(), + rollout_path.as_path(), + default_provider.as_str(), + state_builder.as_ref(), + persisted_items.as_slice(), + "rollout_writer", + ) + .await; } RolloutCmd::Flush { ack } => { // Ensure underlying file is flushed and then ack. @@ -470,8 +604,15 @@ struct JsonlWriter { file: tokio::fs::File, } +#[derive(serde::Serialize)] +struct RolloutLineRef<'a> { + timestamp: String, + #[serde(flatten)] + item: &'a RolloutItem, +} + impl JsonlWriter { - async fn write_rollout_item(&mut self, rollout_item: RolloutItem) -> std::io::Result<()> { + async fn write_rollout_item(&mut self, rollout_item: &RolloutItem) -> std::io::Result<()> { let timestamp_format: &[FormatItem] = format_description!( "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z" ); @@ -479,7 +620,7 @@ impl JsonlWriter { .format(timestamp_format) .map_err(|e| IoError::other(format!("failed to format timestamp: {e}")))?; - let line = RolloutLine { + let line = RolloutLineRef { timestamp, item: rollout_item, }; diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index cd1f1c0498..6559ec2e18 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -7,6 +7,7 @@ use crate::exec_policy::ExecPolicyManager; use crate::mcp_connection_manager::McpConnectionManager; use crate::models_manager::manager::ModelsManager; use crate::skills::SkillsManager; +use crate::state_db::StateDbHandle; use crate::tools::sandboxing::ApprovalStore; use crate::unified_exec::UnifiedExecProcessManager; use crate::user_notification::UserNotifier; @@ -30,4 +31,5 @@ pub(crate) struct SessionServices { pub(crate) tool_approvals: Mutex, pub(crate) skills_manager: Arc, pub(crate) agent_control: AgentControl, + pub(crate) state_db: Option, } diff --git a/codex-rs/core/src/state_db.rs b/codex-rs/core/src/state_db.rs new file mode 100644 index 0000000000..d859328e1c --- /dev/null +++ b/codex-rs/core/src/state_db.rs @@ -0,0 +1,303 @@ +use crate::config::Config; +use crate::features::Feature; +use crate::rollout::list::Cursor; +use crate::rollout::list::ThreadSortKey; +use crate::rollout::metadata; +use chrono::DateTime; +use chrono::NaiveDateTime; +use chrono::Timelike; +use chrono::Utc; +use codex_otel::OtelManager; +use codex_protocol::ThreadId; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SessionSource; +use codex_state::DB_METRIC_BACKFILL; +use codex_state::STATE_DB_FILENAME; +use codex_state::ThreadMetadataBuilder; +use serde_json::Value; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use tracing::info; +use tracing::warn; +use uuid::Uuid; + +/// Core-facing handle to the optional SQLite-backed state runtime. +pub type StateDbHandle = Arc; + +/// Initialize the state runtime when the `sqlite` feature flag is enabled. +pub async fn init_if_enabled(config: &Config, otel: Option<&OtelManager>) -> Option { + let state_path = config.codex_home.join(STATE_DB_FILENAME); + if !config.features.enabled(Feature::Sqlite) { + // We delete the file on best effort basis to maintain retro-compatibility in the future. + let wal_path = state_path.with_extension("sqlite-wal"); + let shm_path = state_path.with_extension("sqlite-shm"); + for path in [state_path.as_path(), wal_path.as_path(), shm_path.as_path()] { + tokio::fs::remove_file(path).await.ok(); + } + return None; + } + let existed = tokio::fs::try_exists(&state_path).await.unwrap_or(false); + let runtime = match codex_state::StateRuntime::init( + config.codex_home.clone(), + config.model_provider_id.clone(), + otel.cloned(), + ) + .await + { + Ok(runtime) => runtime, + Err(err) => { + warn!( + "failed to initialize state runtime at {}: {err}", + config.codex_home.display() + ); + if let Some(otel) = otel { + otel.counter("codex.db.init", 1, &[("status", "init_error")]); + } + return None; + } + }; + if !existed { + let stats = metadata::backfill_sessions(runtime.as_ref(), config, otel).await; + info!( + "state db backfill scanned={}, upserted={}, failed={}", + stats.scanned, stats.upserted, stats.failed + ); + if let Some(otel) = otel { + otel.counter( + DB_METRIC_BACKFILL, + stats.upserted as i64, + &[("status", "upserted")], + ); + otel.counter( + DB_METRIC_BACKFILL, + stats.failed as i64, + &[("status", "failed")], + ); + } + } + Some(runtime) +} + +/// Open the state runtime when the SQLite file exists, without feature gating. +/// +/// This is used for parity checks during the SQLite migration phase. +pub async fn open_if_present(codex_home: &Path, default_provider: &str) -> Option { + let db_path = codex_home.join(STATE_DB_FILENAME); + if !tokio::fs::try_exists(&db_path).await.unwrap_or(false) { + return None; + } + let runtime = codex_state::StateRuntime::init( + codex_home.to_path_buf(), + default_provider.to_string(), + None, + ) + .await + .ok()?; + Some(runtime) +} + +fn cursor_to_anchor(cursor: Option<&Cursor>) -> Option { + let cursor = cursor?; + let value = serde_json::to_value(cursor).ok()?; + let cursor_str = value.as_str()?; + let (ts_str, id_str) = cursor_str.split_once('|')?; + if id_str.contains('|') { + return None; + } + let id = Uuid::parse_str(id_str).ok()?; + let ts = if let Ok(naive) = NaiveDateTime::parse_from_str(ts_str, "%Y-%m-%dT%H-%M-%S") { + DateTime::::from_naive_utc_and_offset(naive, Utc) + } else if let Ok(dt) = DateTime::parse_from_rfc3339(ts_str) { + dt.with_timezone(&Utc) + } else { + return None; + } + .with_nanosecond(0)?; + Some(codex_state::Anchor { ts, id }) +} + +/// List thread ids from SQLite for parity checks without rollout scanning. +#[allow(clippy::too_many_arguments)] +pub async fn list_thread_ids_db( + context: Option<&codex_state::StateRuntime>, + codex_home: &Path, + page_size: usize, + cursor: Option<&Cursor>, + sort_key: ThreadSortKey, + allowed_sources: &[SessionSource], + model_providers: Option<&[String]>, + archived_only: bool, + stage: &str, +) -> Option> { + let ctx = context?; + if ctx.codex_home() != codex_home { + warn!( + "state db codex_home mismatch: expected {}, got {}", + ctx.codex_home().display(), + codex_home.display() + ); + } + + let anchor = cursor_to_anchor(cursor); + let allowed_sources: Vec = allowed_sources + .iter() + .map(|value| match serde_json::to_value(value) { + Ok(Value::String(s)) => s, + Ok(other) => other.to_string(), + Err(_) => String::new(), + }) + .collect(); + let model_providers = model_providers.map(<[String]>::to_vec); + match ctx + .list_thread_ids( + page_size, + anchor.as_ref(), + match sort_key { + ThreadSortKey::CreatedAt => codex_state::SortKey::CreatedAt, + ThreadSortKey::UpdatedAt => codex_state::SortKey::UpdatedAt, + }, + allowed_sources.as_slice(), + model_providers.as_deref(), + archived_only, + ) + .await + { + Ok(ids) => Some(ids), + Err(err) => { + warn!("state db list_thread_ids failed during {stage}: {err}"); + None + } + } +} + +/// Look up the rollout path for a thread id using SQLite. +pub async fn find_rollout_path_by_id( + context: Option<&codex_state::StateRuntime>, + thread_id: ThreadId, + archived_only: Option, + stage: &str, +) -> Option { + let ctx = context?; + ctx.find_rollout_path_by_id(thread_id, archived_only) + .await + .unwrap_or_else(|err| { + warn!("state db find_rollout_path_by_id failed during {stage}: {err}"); + None + }) +} + +/// Reconcile rollout items into SQLite, falling back to scanning the rollout file. +pub async fn reconcile_rollout( + context: Option<&codex_state::StateRuntime>, + rollout_path: &Path, + default_provider: &str, + builder: Option<&ThreadMetadataBuilder>, + items: &[RolloutItem], +) { + let Some(ctx) = context else { + return; + }; + if builder.is_some() || !items.is_empty() { + apply_rollout_items( + Some(ctx), + rollout_path, + default_provider, + builder, + items, + "reconcile_rollout", + ) + .await; + return; + } + let outcome = + match metadata::extract_metadata_from_rollout(rollout_path, default_provider, None).await { + Ok(outcome) => outcome, + Err(err) => { + warn!( + "state db reconcile_rollout extraction failed {}: {err}", + rollout_path.display() + ); + return; + } + }; + if let Err(err) = ctx.upsert_thread(&outcome.metadata).await { + warn!( + "state db reconcile_rollout upsert failed {}: {err}", + rollout_path.display() + ); + } +} + +/// Apply rollout items incrementally to SQLite. +pub async fn apply_rollout_items( + context: Option<&codex_state::StateRuntime>, + rollout_path: &Path, + _default_provider: &str, + builder: Option<&ThreadMetadataBuilder>, + items: &[RolloutItem], + stage: &str, +) { + let Some(ctx) = context else { + return; + }; + let mut builder = match builder { + Some(builder) => builder.clone(), + None => match metadata::builder_from_items(items, rollout_path) { + Some(builder) => builder, + None => { + warn!( + "state db apply_rollout_items missing builder during {stage}: {}", + rollout_path.display() + ); + record_discrepancy(stage, "missing_builder"); + return; + } + }, + }; + builder.rollout_path = rollout_path.to_path_buf(); + if let Err(err) = ctx.apply_rollout_items(&builder, items, None).await { + warn!( + "state db apply_rollout_items failed during {stage} for {}: {err}", + rollout_path.display() + ); + } +} + +/// Record a state discrepancy metric with a stage and reason tag. +pub fn record_discrepancy(stage: &str, reason: &str) { + // We access the global metric because the call sites might not have access to the broader + // OtelManager. + if let Some(metric) = codex_otel::metrics::global() { + let _ = metric.counter( + "codex.db.discrepancy", + 1, + &[("stage", stage), ("reason", reason)], + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::rollout::list::parse_cursor; + use pretty_assertions::assert_eq; + + #[test] + fn cursor_to_anchor_normalizes_timestamp_format() { + let uuid = Uuid::new_v4(); + let ts_str = "2026-01-27T12-34-56"; + let token = format!("{ts_str}|{uuid}"); + let cursor = parse_cursor(token.as_str()).expect("cursor should parse"); + let anchor = cursor_to_anchor(Some(&cursor)).expect("anchor should parse"); + + let naive = + NaiveDateTime::parse_from_str(ts_str, "%Y-%m-%dT%H-%M-%S").expect("ts should parse"); + let expected_ts = DateTime::::from_naive_utc_and_offset(naive, Utc) + .with_nanosecond(0) + .expect("nanosecond"); + + assert_eq!(anchor.id, uuid); + assert_eq!(anchor.ts, expected_ts); + } +} diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index 9bf4ef8ef2..e054070b34 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -65,6 +65,7 @@ mod shell_command; mod shell_serialization; mod shell_snapshot; mod skills; +mod sqlite_state; mod stream_error_allows_next_turn; mod stream_no_completed; mod text_encoding_fix; diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs new file mode 100644 index 0000000000..df6fa2ef72 --- /dev/null +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -0,0 +1,199 @@ +use anyhow::Result; +use codex_core::features::Feature; +use codex_protocol::ThreadId; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::SessionMeta; +use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::UserMessageEvent; +use codex_state::STATE_DB_FILENAME; +use core_test_support::load_sse_fixture_with_id; +use core_test_support::responses::mount_sse_sequence; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex::test_codex; +use pretty_assertions::assert_eq; +use std::fs; +use tokio::time::Duration; +use uuid::Uuid; + +fn sse_completed(id: &str) -> String { + load_sse_fixture_with_id("../fixtures/completed_template.json", id) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +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); + }); + let test = builder.build(&server).await?; + + let thread_id = test.session_configured.session_id; + let rollout_path = test.codex.rollout_path().expect("rollout path"); + let db_path = test.config.codex_home.join(STATE_DB_FILENAME); + + for _ in 0..100 { + if tokio::fs::try_exists(&db_path).await.unwrap_or(false) { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + let db = test.codex.state_db().expect("state db enabled"); + + let mut metadata = None; + for _ in 0..100 { + metadata = db.get_thread(thread_id).await?; + if metadata.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + let metadata = metadata.expect("thread should exist in state db"); + assert_eq!(metadata.id, thread_id); + assert_eq!(metadata.rollout_path, rollout_path); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn backfill_scans_existing_rollouts() -> Result<()> { + let server = start_mock_server().await; + + let uuid = Uuid::now_v7(); + let thread_id = ThreadId::from_string(&uuid.to_string())?; + let rollout_rel_path = format!("sessions/2026/01/27/rollout-2026-01-27T12-00-00-{uuid}.jsonl"); + let rollout_rel_path_for_hook = rollout_rel_path.clone(); + + let mut builder = test_codex() + .with_pre_build_hook(move |codex_home| { + let rollout_path = codex_home.join(&rollout_rel_path_for_hook); + let parent = rollout_path + .parent() + .expect("rollout path should have parent"); + fs::create_dir_all(parent).expect("should create rollout directory"); + + let session_meta_line = SessionMetaLine { + meta: SessionMeta { + id: thread_id, + forked_from_id: None, + timestamp: "2026-01-27T12:00:00Z".to_string(), + cwd: codex_home.to_path_buf(), + originator: "test".to_string(), + cli_version: "test".to_string(), + source: SessionSource::default(), + model_provider: None, + base_instructions: None, + }, + git: None, + }; + + let lines = [ + RolloutLine { + timestamp: "2026-01-27T12:00:00Z".to_string(), + item: RolloutItem::SessionMeta(session_meta_line), + }, + RolloutLine { + timestamp: "2026-01-27T12:00:01Z".to_string(), + item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + message: "hello from backfill".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + })), + }, + ]; + + let jsonl = lines + .iter() + .map(|line| serde_json::to_string(line).expect("rollout line should serialize")) + .collect::>() + .join("\n"); + fs::write(&rollout_path, format!("{jsonl}\n")).expect("should write rollout file"); + }) + .with_config(|config| { + config.features.enable(Feature::Sqlite); + }); + + let test = builder.build(&server).await?; + + let db_path = test.config.codex_home.join(STATE_DB_FILENAME); + let rollout_path = test.config.codex_home.join(&rollout_rel_path); + let default_provider = test.config.model_provider_id.clone(); + + for _ in 0..20 { + if tokio::fs::try_exists(&db_path).await.unwrap_or(false) { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + let db = test.codex.state_db().expect("state db enabled"); + + let mut metadata = None; + for _ in 0..40 { + metadata = db.get_thread(thread_id).await?; + if metadata.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + let metadata = metadata.expect("backfilled thread should exist in state db"); + assert_eq!(metadata.id, thread_id); + assert_eq!(metadata.rollout_path, rollout_path); + assert_eq!(metadata.model_provider, default_provider); + assert!(metadata.has_user_event); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn user_messages_persist_in_state_db() -> Result<()> { + let server = start_mock_server().await; + mount_sse_sequence( + &server, + vec![sse_completed("resp-1"), sse_completed("resp-2")], + ) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::Sqlite); + }); + let test = builder.build(&server).await?; + + let db_path = test.config.codex_home.join(STATE_DB_FILENAME); + for _ in 0..100 { + if tokio::fs::try_exists(&db_path).await.unwrap_or(false) { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + test.submit_turn("hello from sqlite").await?; + test.submit_turn("another message").await?; + + let db = test.codex.state_db().expect("state db enabled"); + let thread_id = test.session_configured.session_id; + + let mut metadata = None; + for _ in 0..100 { + metadata = db.get_thread(thread_id).await?; + if metadata + .as_ref() + .map(|entry| entry.has_user_event) + .unwrap_or(false) + { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + let metadata = metadata.expect("thread should exist in state db"); + assert!(metadata.has_user_event); + + Ok(()) +} diff --git a/codex-rs/otel/src/metrics/mod.rs b/codex-rs/otel/src/metrics/mod.rs index b13d5f917e..30a7aa1cf6 100644 --- a/codex-rs/otel/src/metrics/mod.rs +++ b/codex-rs/otel/src/metrics/mod.rs @@ -17,6 +17,6 @@ pub(crate) fn install_global(metrics: MetricsClient) { let _ = GLOBAL_METRICS.set(metrics); } -pub(crate) fn global() -> Option { +pub fn global() -> Option { GLOBAL_METRICS.get().cloned() } diff --git a/codex-rs/protocol/src/thread_id.rs b/codex-rs/protocol/src/thread_id.rs index 7b27db8364..8d6d96eff8 100644 --- a/codex-rs/protocol/src/thread_id.rs +++ b/codex-rs/protocol/src/thread_id.rs @@ -28,6 +28,28 @@ impl ThreadId { } } +impl TryFrom<&str> for ThreadId { + type Error = uuid::Error; + + fn try_from(value: &str) -> Result { + Self::from_string(value) + } +} + +impl TryFrom for ThreadId { + type Error = uuid::Error; + + fn try_from(value: String) -> Result { + Self::from_string(value.as_str()) + } +} + +impl From for String { + fn from(value: ThreadId) -> Self { + value.to_string() + } +} + impl Default for ThreadId { fn default() -> Self { Self::new() @@ -36,7 +58,7 @@ impl Default for ThreadId { impl Display for ThreadId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.uuid) + Display::fmt(&self.uuid, f) } } diff --git a/codex-rs/state/BUILD.bazel b/codex-rs/state/BUILD.bazel new file mode 100644 index 0000000000..b1f7932168 --- /dev/null +++ b/codex-rs/state/BUILD.bazel @@ -0,0 +1,7 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "state", + crate_name = "codex_state", + compile_data = glob(["migrations/**"]), +) diff --git a/codex-rs/state/Cargo.toml b/codex-rs/state/Cargo.toml new file mode 100644 index 0000000000..810e250ca7 --- /dev/null +++ b/codex-rs/state/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "codex-state" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow = { workspace = true } +chrono = { workspace = true } +codex-otel = { workspace = true } +codex-protocol = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +sqlx = { workspace = true } +tokio = { workspace = true, features = ["fs", "io-util", "macros", "rt-multi-thread", "sync", "time"] } +tracing = { workspace = true } +uuid = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } + +[lints] +workspace = true diff --git a/codex-rs/state/migrations/0001_threads.sql b/codex-rs/state/migrations/0001_threads.sql new file mode 100644 index 0000000000..7063ce11a4 --- /dev/null +++ b/codex-rs/state/migrations/0001_threads.sql @@ -0,0 +1,25 @@ +CREATE TABLE threads ( + id TEXT PRIMARY KEY, + rollout_path TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + source TEXT NOT NULL, + model_provider TEXT NOT NULL, + cwd TEXT NOT NULL, + title TEXT NOT NULL, + sandbox_policy TEXT NOT NULL, + approval_mode TEXT NOT NULL, + tokens_used INTEGER NOT NULL DEFAULT 0, + has_user_event INTEGER NOT NULL DEFAULT 0, + archived INTEGER NOT NULL DEFAULT 0, + archived_at INTEGER, + git_sha TEXT, + git_branch TEXT, + git_origin_url TEXT +); + +CREATE INDEX idx_threads_created_at ON threads(created_at DESC, id DESC); +CREATE INDEX idx_threads_updated_at ON threads(updated_at DESC, id DESC); +CREATE INDEX idx_threads_archived ON threads(archived); +CREATE INDEX idx_threads_source ON threads(source); +CREATE INDEX idx_threads_provider ON threads(model_provider); diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs new file mode 100644 index 0000000000..9c8ce21556 --- /dev/null +++ b/codex-rs/state/src/extract.rs @@ -0,0 +1,182 @@ +use crate::model::ThreadMetadata; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::models::is_local_image_close_tag_text; +use codex_protocol::models::is_local_image_open_tag_text; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::TurnContextItem; +use codex_protocol::protocol::USER_MESSAGE_BEGIN; +use serde::Serialize; +use serde_json::Value; + +/// Apply a rollout item to the metadata structure. +pub fn apply_rollout_item( + metadata: &mut ThreadMetadata, + item: &RolloutItem, + default_provider: &str, +) { + match item { + RolloutItem::SessionMeta(meta_line) => apply_session_meta_from_item(metadata, meta_line), + RolloutItem::TurnContext(turn_ctx) => apply_turn_context(metadata, turn_ctx), + RolloutItem::EventMsg(event) => apply_event_msg(metadata, event), + RolloutItem::ResponseItem(item) => apply_response_item(metadata, item), + RolloutItem::Compacted(_) => {} + } + if metadata.model_provider.is_empty() { + metadata.model_provider = default_provider.to_string(); + } +} + +fn apply_session_meta_from_item(metadata: &mut ThreadMetadata, meta_line: &SessionMetaLine) { + metadata.id = meta_line.meta.id; + metadata.source = enum_to_string(&meta_line.meta.source); + if let Some(provider) = meta_line.meta.model_provider.as_deref() { + metadata.model_provider = provider.to_string(); + } + if !meta_line.meta.cwd.as_os_str().is_empty() { + metadata.cwd = meta_line.meta.cwd.clone(); + } + if let Some(git) = meta_line.git.as_ref() { + metadata.git_sha = git.commit_hash.clone(); + metadata.git_branch = git.branch.clone(); + metadata.git_origin_url = git.repository_url.clone(); + } +} + +fn apply_turn_context(metadata: &mut ThreadMetadata, turn_ctx: &TurnContextItem) { + metadata.cwd = turn_ctx.cwd.clone(); + metadata.sandbox_policy = enum_to_string(&turn_ctx.sandbox_policy); + metadata.approval_mode = enum_to_string(&turn_ctx.approval_policy); +} + +fn apply_event_msg(metadata: &mut ThreadMetadata, event: &EventMsg) { + match event { + EventMsg::TokenCount(token_count) => { + if let Some(info) = token_count.info.as_ref() { + metadata.tokens_used = info.total_token_usage.total_tokens.max(0); + } + } + EventMsg::UserMessage(user) => { + metadata.has_user_event = true; + if metadata.title.is_empty() { + metadata.title = strip_user_message_prefix(user.message.as_str()).to_string(); + } + } + _ => {} + } +} + +fn apply_response_item(metadata: &mut ThreadMetadata, item: &ResponseItem) { + if let Some(text) = extract_user_message_text(item) { + metadata.has_user_event = true; + if metadata.title.is_empty() { + metadata.title = text; + } + } +} + +fn extract_user_message_text(item: &ResponseItem) -> Option { + let ResponseItem::Message { role, content, .. } = item else { + return None; + }; + if role != "user" { + return None; + } + let texts: Vec<&str> = content + .iter() + .filter_map(|content_item| match content_item { + ContentItem::InputText { text } => Some(text.as_str()), + ContentItem::InputImage { .. } | ContentItem::OutputText { .. } => None, + }) + .filter(|text| !is_local_image_open_tag_text(text) && !is_local_image_close_tag_text(text)) + .collect(); + if texts.is_empty() { + return None; + } + let joined = texts.join("\n"); + Some( + strip_user_message_prefix(joined.as_str()) + .trim() + .to_string(), + ) +} + +fn strip_user_message_prefix(text: &str) -> &str { + match text.find(USER_MESSAGE_BEGIN) { + Some(idx) => text[idx + USER_MESSAGE_BEGIN.len()..].trim(), + None => text.trim(), + } +} + +pub(crate) fn enum_to_string(value: &T) -> String { + match serde_json::to_value(value) { + Ok(Value::String(s)) => s, + Ok(other) => other.to_string(), + Err(_) => String::new(), + } +} + +#[cfg(test)] +mod tests { + use super::extract_user_message_text; + use crate::model::ThreadMetadata; + use chrono::DateTime; + use chrono::Utc; + use codex_protocol::ThreadId; + use codex_protocol::models::ContentItem; + use codex_protocol::models::ResponseItem; + use codex_protocol::protocol::USER_MESSAGE_BEGIN; + use pretty_assertions::assert_eq; + use std::path::PathBuf; + use uuid::Uuid; + + #[test] + fn extracts_user_message_text() { + let item = ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ + ContentItem::InputText { + text: format!(" {USER_MESSAGE_BEGIN}actual question"), + }, + ContentItem::InputImage { + image_url: "https://example.com/image.png".to_string(), + }, + ], + end_turn: None, + }; + let actual = extract_user_message_text(&item); + assert_eq!(actual.as_deref(), Some("actual question")); + } + + #[test] + fn diff_fields_detects_changes() { + let id = ThreadId::from_string(&Uuid::now_v7().to_string()).expect("thread id"); + let created_at = DateTime::::from_timestamp(1_735_689_600, 0).expect("timestamp"); + let base = ThreadMetadata { + id, + rollout_path: PathBuf::from("/tmp/a.jsonl"), + created_at, + updated_at: created_at, + source: "cli".to_string(), + model_provider: "openai".to_string(), + cwd: PathBuf::from("/tmp"), + title: "hello".to_string(), + sandbox_policy: "read-only".to_string(), + approval_mode: "on-request".to_string(), + tokens_used: 1, + has_user_event: false, + archived_at: None, + git_sha: None, + git_branch: None, + git_origin_url: None, + }; + let mut other = base.clone(); + other.tokens_used = 2; + other.title = "world".to_string(); + let diffs = base.diff_fields(&other); + assert_eq!(diffs, vec!["title", "tokens_used"]); + } +} diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs new file mode 100644 index 0000000000..67533a3791 --- /dev/null +++ b/codex-rs/state/src/lib.rs @@ -0,0 +1,34 @@ +//! SQLite-backed state for rollout metadata. +//! +//! This crate is intentionally small and focused: it extracts rollout metadata +//! from JSONL rollouts and mirrors it into a local SQLite database. Backfill +//! orchestration and rollout scanning live in `codex-core`. + +mod extract; +mod migrations; +mod model; +mod paths; +mod runtime; + +/// Preferred entrypoint: owns configuration and metrics. +pub use runtime::StateRuntime; + +/// Low-level storage engine: useful for focused tests. +/// +/// Most consumers should prefer [`StateRuntime`]. +pub use extract::apply_rollout_item; +pub use model::Anchor; +pub use model::BackfillStats; +pub use model::ExtractionOutcome; +pub use model::SortKey; +pub use model::ThreadMetadata; +pub use model::ThreadMetadataBuilder; +pub use model::ThreadsPage; +pub use runtime::STATE_DB_FILENAME; + +/// Errors encountered during DB operations. Tags: [stage] +pub const DB_ERROR_METRIC: &str = "codex.db.error"; +/// Metrics on backfill process during first init of the db. Tags: [status] +pub const DB_METRIC_BACKFILL: &str = "codex.db.backfill"; +/// Metrics on errors during comparison between DB and rollout file. Tags: [stage] +pub const DB_METRIC_COMPARE_ERROR: &str = "codex.db.compare_error"; diff --git a/codex-rs/state/src/migrations.rs b/codex-rs/state/src/migrations.rs new file mode 100644 index 0000000000..24b310224b --- /dev/null +++ b/codex-rs/state/src/migrations.rs @@ -0,0 +1,3 @@ +use sqlx::migrate::Migrator; + +pub(crate) static MIGRATOR: Migrator = sqlx::migrate!("./migrations"); diff --git a/codex-rs/state/src/model.rs b/codex-rs/state/src/model.rs new file mode 100644 index 0000000000..7d475efffc --- /dev/null +++ b/codex-rs/state/src/model.rs @@ -0,0 +1,352 @@ +use anyhow::Result; +use chrono::DateTime; +use chrono::Timelike; +use chrono::Utc; +use codex_protocol::ThreadId; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::SessionSource; +use sqlx::Row; +use sqlx::sqlite::SqliteRow; +use std::path::PathBuf; +use uuid::Uuid; + +/// The sort key to use when listing threads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SortKey { + /// Sort by the thread's creation timestamp. + CreatedAt, + /// Sort by the thread's last update timestamp. + UpdatedAt, +} + +/// A pagination anchor used for keyset pagination. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Anchor { + /// The timestamp component of the anchor. + pub ts: DateTime, + /// The UUID component of the anchor. + pub id: Uuid, +} + +/// A single page of thread metadata results. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ThreadsPage { + /// The thread metadata items in this page. + pub items: Vec, + /// The next anchor to use for pagination, if any. + pub next_anchor: Option, + /// The number of rows scanned to produce this page. + pub num_scanned_rows: usize, +} + +/// The outcome of extracting metadata from a rollout. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExtractionOutcome { + /// The extracted thread metadata. + pub metadata: ThreadMetadata, + /// The number of rollout lines that failed to parse. + pub parse_errors: usize, +} + +/// Canonical thread metadata derived from rollout files. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ThreadMetadata { + /// The thread identifier. + pub id: ThreadId, + /// The absolute rollout path on disk. + pub rollout_path: PathBuf, + /// The creation timestamp. + pub created_at: DateTime, + /// The last update timestamp. + pub updated_at: DateTime, + /// The session source (stringified enum). + pub source: String, + /// The model provider identifier. + pub model_provider: String, + /// The working directory for the thread. + pub cwd: PathBuf, + /// A best-effort thread title. + pub title: String, + /// The sandbox policy (stringified enum). + pub sandbox_policy: String, + /// The approval mode (stringified enum). + pub approval_mode: String, + /// The last observed token usage. + pub tokens_used: i64, + /// Whether the thread has observed a user message. + pub has_user_event: bool, + /// The archive timestamp, if the thread is archived. + pub archived_at: Option>, + /// The git commit SHA, if known. + pub git_sha: Option, + /// The git branch name, if known. + pub git_branch: Option, + /// The git origin URL, if known. + pub git_origin_url: Option, +} + +/// Builder data required to construct [`ThreadMetadata`] without parsing filenames. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ThreadMetadataBuilder { + /// The thread identifier. + pub id: ThreadId, + /// The absolute rollout path on disk. + pub rollout_path: PathBuf, + /// The creation timestamp. + pub created_at: DateTime, + /// The last update timestamp, if known. + pub updated_at: Option>, + /// The session source. + pub source: SessionSource, + /// The model provider identifier, if known. + pub model_provider: Option, + /// The working directory for the thread. + pub cwd: PathBuf, + /// The sandbox policy. + pub sandbox_policy: SandboxPolicy, + /// The approval mode. + pub approval_mode: AskForApproval, + /// The archive timestamp, if the thread is archived. + pub archived_at: Option>, + /// The git commit SHA, if known. + pub git_sha: Option, + /// The git branch name, if known. + pub git_branch: Option, + /// The git origin URL, if known. + pub git_origin_url: Option, +} + +impl ThreadMetadataBuilder { + /// Create a new builder with required fields and sensible defaults. + pub fn new( + id: ThreadId, + rollout_path: PathBuf, + created_at: DateTime, + source: SessionSource, + ) -> Self { + Self { + id, + rollout_path, + created_at, + updated_at: None, + source, + model_provider: None, + cwd: PathBuf::new(), + sandbox_policy: SandboxPolicy::ReadOnly, + approval_mode: AskForApproval::OnRequest, + archived_at: None, + git_sha: None, + git_branch: None, + git_origin_url: None, + } + } + + /// Build canonical thread metadata, filling missing values from defaults. + pub fn build(&self, default_provider: &str) -> ThreadMetadata { + let source = crate::extract::enum_to_string(&self.source); + let sandbox_policy = crate::extract::enum_to_string(&self.sandbox_policy); + let approval_mode = crate::extract::enum_to_string(&self.approval_mode); + let created_at = canonicalize_datetime(self.created_at); + let updated_at = self + .updated_at + .map(canonicalize_datetime) + .unwrap_or(created_at); + ThreadMetadata { + id: self.id, + rollout_path: self.rollout_path.clone(), + created_at, + updated_at, + source, + model_provider: self + .model_provider + .clone() + .unwrap_or_else(|| default_provider.to_string()), + cwd: self.cwd.clone(), + title: String::new(), + sandbox_policy, + approval_mode, + tokens_used: 0, + has_user_event: false, + archived_at: self.archived_at.map(canonicalize_datetime), + git_sha: self.git_sha.clone(), + git_branch: self.git_branch.clone(), + git_origin_url: self.git_origin_url.clone(), + } + } +} + +impl ThreadMetadata { + /// 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(); + if self.id != other.id { + diffs.push("id"); + } + if self.rollout_path != other.rollout_path { + diffs.push("rollout_path"); + } + if self.created_at != other.created_at { + diffs.push("created_at"); + } + if self.updated_at != other.updated_at { + diffs.push("updated_at"); + } + if self.source != other.source { + diffs.push("source"); + } + if self.model_provider != other.model_provider { + diffs.push("model_provider"); + } + if self.cwd != other.cwd { + diffs.push("cwd"); + } + if self.title != other.title { + diffs.push("title"); + } + if self.sandbox_policy != other.sandbox_policy { + diffs.push("sandbox_policy"); + } + if self.approval_mode != other.approval_mode { + diffs.push("approval_mode"); + } + if self.tokens_used != other.tokens_used { + diffs.push("tokens_used"); + } + if self.has_user_event != other.has_user_event { + diffs.push("has_user_event"); + } + if self.archived_at != other.archived_at { + diffs.push("archived_at"); + } + if self.git_sha != other.git_sha { + diffs.push("git_sha"); + } + if self.git_branch != other.git_branch { + diffs.push("git_branch"); + } + if self.git_origin_url != other.git_origin_url { + diffs.push("git_origin_url"); + } + diffs + } +} + +fn canonicalize_datetime(dt: DateTime) -> DateTime { + dt.with_nanosecond(0).unwrap_or(dt) +} + +#[derive(Debug)] +pub(crate) struct ThreadRow { + id: String, + rollout_path: String, + created_at: i64, + updated_at: i64, + source: String, + model_provider: String, + cwd: String, + title: String, + sandbox_policy: String, + approval_mode: String, + tokens_used: i64, + has_user_event: bool, + archived_at: Option, + git_sha: Option, + git_branch: Option, + git_origin_url: Option, +} + +impl ThreadRow { + pub(crate) fn try_from_row(row: &SqliteRow) -> Result { + Ok(Self { + id: row.try_get("id")?, + rollout_path: row.try_get("rollout_path")?, + created_at: row.try_get("created_at")?, + updated_at: row.try_get("updated_at")?, + source: row.try_get("source")?, + model_provider: row.try_get("model_provider")?, + cwd: row.try_get("cwd")?, + title: row.try_get("title")?, + sandbox_policy: row.try_get("sandbox_policy")?, + approval_mode: row.try_get("approval_mode")?, + tokens_used: row.try_get("tokens_used")?, + has_user_event: row.try_get("has_user_event")?, + archived_at: row.try_get("archived_at")?, + git_sha: row.try_get("git_sha")?, + git_branch: row.try_get("git_branch")?, + git_origin_url: row.try_get("git_origin_url")?, + }) + } +} + +impl TryFrom for ThreadMetadata { + type Error = anyhow::Error; + + fn try_from(row: ThreadRow) -> std::result::Result { + let ThreadRow { + id, + rollout_path, + created_at, + updated_at, + source, + model_provider, + cwd, + title, + sandbox_policy, + approval_mode, + tokens_used, + has_user_event, + archived_at, + git_sha, + git_branch, + git_origin_url, + } = row; + Ok(Self { + id: ThreadId::try_from(id)?, + rollout_path: PathBuf::from(rollout_path), + created_at: epoch_seconds_to_datetime(created_at)?, + updated_at: epoch_seconds_to_datetime(updated_at)?, + source, + model_provider, + cwd: PathBuf::from(cwd), + title, + sandbox_policy, + approval_mode, + tokens_used, + has_user_event, + archived_at: archived_at.map(epoch_seconds_to_datetime).transpose()?, + git_sha, + git_branch, + git_origin_url, + }) + } +} + +pub(crate) fn anchor_from_item(item: &ThreadMetadata, sort_key: SortKey) -> Option { + let id = Uuid::parse_str(&item.id.to_string()).ok()?; + let ts = match sort_key { + SortKey::CreatedAt => item.created_at, + SortKey::UpdatedAt => item.updated_at, + }; + Some(Anchor { ts, id }) +} + +pub(crate) fn datetime_to_epoch_seconds(dt: DateTime) -> i64 { + dt.timestamp() +} + +pub(crate) fn epoch_seconds_to_datetime(secs: i64) -> Result> { + DateTime::::from_timestamp(secs, 0) + .ok_or_else(|| anyhow::anyhow!("invalid unix timestamp: {secs}")) +} + +/// Statistics about a backfill operation. +#[derive(Debug, Clone)] +pub struct BackfillStats { + /// The number of rollout files scanned. + pub scanned: usize, + /// The number of rows upserted successfully. + pub upserted: usize, + /// The number of rows that failed to upsert. + pub failed: usize, +} diff --git a/codex-rs/state/src/paths.rs b/codex-rs/state/src/paths.rs new file mode 100644 index 0000000000..8123743821 --- /dev/null +++ b/codex-rs/state/src/paths.rs @@ -0,0 +1,10 @@ +use chrono::DateTime; +use chrono::Timelike; +use chrono::Utc; +use std::path::Path; + +pub(crate) async fn file_modified_time_utc(path: &Path) -> Option> { + let modified = tokio::fs::metadata(path).await.ok()?.modified().ok()?; + let updated_at: DateTime = modified.into(); + Some(updated_at.with_nanosecond(0).unwrap_or(updated_at)) +} diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs new file mode 100644 index 0000000000..f341ee3bb6 --- /dev/null +++ b/codex-rs/state/src/runtime.rs @@ -0,0 +1,458 @@ +use crate::DB_ERROR_METRIC; +use crate::SortKey; +use crate::ThreadMetadata; +use crate::ThreadMetadataBuilder; +use crate::ThreadsPage; +use crate::apply_rollout_item; +use crate::migrations::MIGRATOR; +use crate::model::ThreadRow; +use crate::model::anchor_from_item; +use crate::model::datetime_to_epoch_seconds; +use crate::paths::file_modified_time_utc; +use chrono::DateTime; +use chrono::Utc; +use codex_otel::OtelManager; +use codex_protocol::ThreadId; +use codex_protocol::protocol::RolloutItem; +use sqlx::QueryBuilder; +use sqlx::Row; +use sqlx::Sqlite; +use sqlx::SqlitePool; +use sqlx::sqlite::SqliteConnectOptions; +use sqlx::sqlite::SqliteJournalMode; +use sqlx::sqlite::SqlitePoolOptions; +use sqlx::sqlite::SqliteSynchronous; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; +use tracing::warn; + +pub const STATE_DB_FILENAME: &str = "state.sqlite"; + +const METRIC_DB_INIT: &str = "codex.db.init"; + +#[derive(Clone)] +pub struct StateRuntime { + codex_home: PathBuf, + default_provider: String, + pool: Arc, +} + +impl StateRuntime { + /// Initialize the state runtime using the provided Codex home and default provider. + /// + /// This opens (and migrates) the SQLite database at `codex_home/state.sqlite`. + pub async fn init( + codex_home: PathBuf, + default_provider: String, + otel: Option, + ) -> anyhow::Result> { + tokio::fs::create_dir_all(&codex_home).await?; + let state_path = codex_home.join(STATE_DB_FILENAME); + let existed = tokio::fs::try_exists(&state_path).await.unwrap_or(false); + let pool = match open_sqlite(&state_path).await { + Ok(db) => Arc::new(db), + Err(err) => { + warn!("failed to open state db at {}: {err}", state_path.display()); + if let Some(otel) = otel.as_ref() { + otel.counter(METRIC_DB_INIT, 1, &[("status", "open_error")]); + } + return Err(err); + } + }; + if let Some(otel) = otel.as_ref() { + otel.counter(METRIC_DB_INIT, 1, &[("status", "opened")]); + } + let runtime = Arc::new(Self { + pool, + codex_home, + default_provider, + }); + if !existed && let Some(otel) = otel.as_ref() { + otel.counter(METRIC_DB_INIT, 1, &[("status", "created")]); + } + Ok(runtime) + } + + /// Return the configured Codex home directory for this runtime. + pub fn codex_home(&self) -> &Path { + self.codex_home.as_path() + } + + /// Load thread metadata by id using the underlying database. + pub async fn get_thread(&self, id: ThreadId) -> anyhow::Result> { + let row = sqlx::query( + r#" +SELECT + id, + rollout_path, + created_at, + updated_at, + source, + model_provider, + cwd, + title, + sandbox_policy, + approval_mode, + tokens_used, + has_user_event, + archived_at, + git_sha, + git_branch, + git_origin_url +FROM threads +WHERE id = ? + "#, + ) + .bind(id.to_string()) + .fetch_optional(self.pool.as_ref()) + .await?; + row.map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) + .transpose() + } + + /// Find a rollout path by thread id using the underlying database. + pub async fn find_rollout_path_by_id( + &self, + id: ThreadId, + archived_only: Option, + ) -> anyhow::Result> { + let mut builder = + QueryBuilder::::new("SELECT rollout_path FROM threads WHERE id = "); + builder.push_bind(id.to_string()); + match archived_only { + Some(true) => { + builder.push(" AND archived = 1"); + } + Some(false) => { + builder.push(" AND archived = 0"); + } + None => {} + } + let row = builder.build().fetch_optional(self.pool.as_ref()).await?; + Ok(row + .and_then(|r| r.try_get::("rollout_path").ok()) + .map(PathBuf::from)) + } + + /// List threads using the underlying database. + pub async fn list_threads( + &self, + page_size: usize, + anchor: Option<&crate::Anchor>, + sort_key: crate::SortKey, + allowed_sources: &[String], + model_providers: Option<&[String]>, + archived_only: bool, + ) -> anyhow::Result { + let limit = page_size.saturating_add(1); + + let mut builder = QueryBuilder::::new( + r#" +SELECT + id, + rollout_path, + created_at, + updated_at, + source, + model_provider, + cwd, + title, + sandbox_policy, + approval_mode, + tokens_used, + has_user_event, + archived_at, + git_sha, + git_branch, + git_origin_url +FROM threads + "#, + ); + push_thread_filters( + &mut builder, + archived_only, + allowed_sources, + model_providers, + anchor, + sort_key, + ); + push_thread_order_and_limit(&mut builder, sort_key, limit); + + let rows = builder.build().fetch_all(self.pool.as_ref()).await?; + let mut items = rows + .into_iter() + .map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) + .collect::, _>>()?; + let num_scanned_rows = items.len(); + let next_anchor = if items.len() > page_size { + items.pop(); + items + .last() + .and_then(|item| anchor_from_item(item, sort_key)) + } else { + None + }; + Ok(ThreadsPage { + items, + next_anchor, + num_scanned_rows, + }) + } + + /// List thread ids using the underlying database (no rollout scanning). + pub async fn list_thread_ids( + &self, + limit: usize, + anchor: Option<&crate::Anchor>, + sort_key: crate::SortKey, + allowed_sources: &[String], + model_providers: Option<&[String]>, + archived_only: bool, + ) -> anyhow::Result> { + let mut builder = QueryBuilder::::new("SELECT id FROM threads"); + push_thread_filters( + &mut builder, + archived_only, + allowed_sources, + model_providers, + anchor, + sort_key, + ); + push_thread_order_and_limit(&mut builder, sort_key, limit); + + let rows = builder.build().fetch_all(self.pool.as_ref()).await?; + rows.into_iter() + .map(|row| { + let id: String = row.try_get("id")?; + Ok(ThreadId::try_from(id)?) + }) + .collect() + } + + /// Insert or replace thread metadata directly. + pub async fn upsert_thread(&self, metadata: &crate::ThreadMetadata) -> anyhow::Result<()> { + sqlx::query( + r#" +INSERT INTO threads ( + id, + rollout_path, + created_at, + updated_at, + source, + model_provider, + cwd, + title, + sandbox_policy, + approval_mode, + tokens_used, + has_user_event, + archived, + archived_at, + git_sha, + git_branch, + git_origin_url +) 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, + model_provider = excluded.model_provider, + cwd = excluded.cwd, + title = excluded.title, + sandbox_policy = excluded.sandbox_policy, + approval_mode = excluded.approval_mode, + tokens_used = excluded.tokens_used, + has_user_event = excluded.has_user_event, + archived = excluded.archived, + archived_at = excluded.archived_at, + git_sha = excluded.git_sha, + git_branch = excluded.git_branch, + git_origin_url = excluded.git_origin_url + "#, + ) + .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.model_provider.as_str()) + .bind(metadata.cwd.display().to_string()) + .bind(metadata.title.as_str()) + .bind(metadata.sandbox_policy.as_str()) + .bind(metadata.approval_mode.as_str()) + .bind(metadata.tokens_used) + .bind(metadata.has_user_event) + .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()) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } + + /// Apply rollout items incrementally using the underlying database. + pub async fn apply_rollout_items( + &self, + builder: &ThreadMetadataBuilder, + items: &[RolloutItem], + otel: Option<&OtelManager>, + ) -> anyhow::Result<()> { + if items.is_empty() { + return Ok(()); + } + let mut metadata = self + .get_thread(builder.id) + .await? + .unwrap_or_else(|| builder.build(&self.default_provider)); + metadata.rollout_path = builder.rollout_path.clone(); + for item in items { + apply_rollout_item(&mut metadata, item, &self.default_provider); + } + if let Some(updated_at) = file_modified_time_utc(builder.rollout_path.as_path()).await { + metadata.updated_at = updated_at; + } + if let Err(err) = self.upsert_thread(&metadata).await { + if let Some(otel) = otel { + otel.counter(DB_ERROR_METRIC, 1, &[("stage", "apply_rollout_items")]); + } + return Err(err); + } + Ok(()) + } + + /// Mark a thread as archived using the underlying database. + pub async fn mark_archived( + &self, + thread_id: ThreadId, + rollout_path: &Path, + archived_at: DateTime, + ) -> anyhow::Result<()> { + let Some(mut metadata) = self.get_thread(thread_id).await? else { + return Ok(()); + }; + metadata.archived_at = Some(archived_at); + metadata.rollout_path = rollout_path.to_path_buf(); + if let Some(updated_at) = file_modified_time_utc(rollout_path).await { + metadata.updated_at = updated_at; + } + if metadata.id != thread_id { + warn!( + "thread id mismatch during archive: expected {thread_id}, got {}", + metadata.id + ); + } + self.upsert_thread(&metadata).await + } + + /// Mark a thread as unarchived using the underlying database. + pub async fn mark_unarchived( + &self, + thread_id: ThreadId, + rollout_path: &Path, + ) -> anyhow::Result<()> { + let Some(mut metadata) = self.get_thread(thread_id).await? else { + return Ok(()); + }; + metadata.archived_at = None; + metadata.rollout_path = rollout_path.to_path_buf(); + if let Some(updated_at) = file_modified_time_utc(rollout_path).await { + metadata.updated_at = updated_at; + } + if metadata.id != thread_id { + warn!( + "thread id mismatch during unarchive: expected {thread_id}, got {}", + metadata.id + ); + } + self.upsert_thread(&metadata).await + } +} + +async fn open_sqlite(path: &Path) -> anyhow::Result { + let options = SqliteConnectOptions::new() + .filename(path) + .create_if_missing(true) + .journal_mode(SqliteJournalMode::Wal) + .synchronous(SqliteSynchronous::Normal) + .busy_timeout(Duration::from_secs(5)); + let pool = SqlitePoolOptions::new() + .max_connections(5) + .connect_with(options) + .await?; + MIGRATOR.run(&pool).await?; + Ok(pool) +} + +fn push_thread_filters<'a>( + builder: &mut QueryBuilder<'a, Sqlite>, + archived_only: bool, + allowed_sources: &'a [String], + model_providers: Option<&'a [String]>, + anchor: Option<&crate::Anchor>, + sort_key: SortKey, +) { + builder.push(" WHERE 1 = 1"); + if archived_only { + builder.push(" AND archived = 1"); + } else { + builder.push(" AND archived = 0"); + } + builder.push(" AND has_user_event = 1"); + if !allowed_sources.is_empty() { + builder.push(" AND source IN ("); + let mut separated = builder.separated(", "); + for source in allowed_sources { + separated.push_bind(source); + } + separated.push_unseparated(")"); + } + if let Some(model_providers) = model_providers + && !model_providers.is_empty() + { + builder.push(" AND model_provider IN ("); + let mut separated = builder.separated(", "); + for provider in model_providers { + separated.push_bind(provider); + } + separated.push_unseparated(")"); + } + if let Some(anchor) = anchor { + let anchor_ts = datetime_to_epoch_seconds(anchor.ts); + let column = match sort_key { + SortKey::CreatedAt => "created_at", + SortKey::UpdatedAt => "updated_at", + }; + builder.push(" AND ("); + builder.push(column); + builder.push(" < "); + builder.push_bind(anchor_ts); + builder.push(" OR ("); + builder.push(column); + builder.push(" = "); + builder.push_bind(anchor_ts); + builder.push(" AND id < "); + builder.push_bind(anchor.id.to_string()); + builder.push("))"); + } +} + +fn push_thread_order_and_limit( + builder: &mut QueryBuilder<'_, Sqlite>, + sort_key: SortKey, + limit: usize, +) { + let order_column = match sort_key { + SortKey::CreatedAt => "created_at", + SortKey::UpdatedAt => "updated_at", + }; + builder.push(" ORDER BY "); + builder.push(order_column); + builder.push(" DESC, id DESC"); + builder.push(" LIMIT "); + builder.push_bind(limit as i64); +} From 231406bd048e2910543394de4b07065c623df5d9 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 28 Jan 2026 16:19:08 +0100 Subject: [PATCH 033/116] feat: sort metadata by date (#10083) --- codex-rs/core/src/rollout/metadata.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs index 0d6fedc272..32d13ebde2 100644 --- a/codex-rs/core/src/rollout/metadata.rs +++ b/codex-rs/core/src/rollout/metadata.rs @@ -18,6 +18,7 @@ use codex_state::DB_ERROR_METRIC; use codex_state::ExtractionOutcome; use codex_state::ThreadMetadataBuilder; use codex_state::apply_rollout_item; +use std::cmp::Reverse; use std::path::Path; use std::path::PathBuf; use tracing::warn; @@ -144,6 +145,14 @@ pub(crate) async fn backfill_sessions( } } } + rollout_paths.sort_by_key(|(path, _archived)| { + let parsed = path + .file_name() + .and_then(|name| name.to_str()) + .and_then(parse_timestamp_uuid_from_filename) + .unwrap_or((time::OffsetDateTime::UNIX_EPOCH, uuid::Uuid::nil())); + (Reverse(parsed.0), Reverse(parsed.1)) + }); let mut stats = BackfillStats { scanned: 0, upserted: 0, From 2a624661efbc08f7cb008ed81da3cfc9007fa6e1 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 10:03:47 -0700 Subject: [PATCH 034/116] Update shell-tool-mcp.yml (#10092) ## Summary Remove pnpm version so we rely on package.json instead, and fix the mismatch due to https://github.com/openai/codex/pull/9992 --- .github/workflows/shell-tool-mcp.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index a8a01b5f6a..1f7bce1ccf 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -282,7 +282,6 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: - version: 10.8.1 run_install: false - name: Setup Node.js @@ -378,7 +377,6 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: - version: 10.8.1 run_install: false - name: Setup Node.js From 74bd6d7178a8c56e5ab1496feaf6d8bf092c3df1 Mon Sep 17 00:00:00 2001 From: zbarsky-openai Date: Wed, 28 Jan 2026 12:26:57 -0500 Subject: [PATCH 035/116] [bazel] Enable remote cache compression (#10079) BB already stores the blobs compressed so we may as well keep them compressed in transfer --- .bazelrc | 1 + 1 file changed, 1 insertion(+) diff --git a/.bazelrc b/.bazelrc index 2e3d53b620..764754c216 100644 --- a/.bazelrc +++ b/.bazelrc @@ -4,6 +4,7 @@ common --repo_env=BAZEL_NO_APPLE_CPP_TOOLCHAIN=1 common --disk_cache=~/.cache/bazel-disk-cache common --repo_contents_cache=~/.cache/bazel-repo-contents-cache common --repository_cache=~/.cache/bazel-repo-cache +common --remote_cache_compression startup --experimental_remote_repo_contents_cache common --experimental_platform_in_output_dir From 96386755b6d8a92c33bdef336fc985cf3fb1285a Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Wed, 28 Jan 2026 09:41:59 -0800 Subject: [PATCH 036/116] Refine request_user_input TUI interactions and option UX (#10025) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Overhaul the ask‑user‑questions TUI to support “Other/None” answers, better notes handling, improved option selection UX, and a safer submission flow with confirmation for unanswered questions. Multiple choice (number keys for quick selection, up/down or jk for cycling through options): Screenshot 2026-01-27 at 7 22 29 PM Tab to add notes: Screenshot 2026-01-27 at 7 22 45 PM Freeform (also note enter tooltip is highlighted on last question to indicate questions UI will be exited upon submission): Screenshot 2026-01-27 at 7 23 13 PM Confirmation dialogue (submitting with unanswered questions): Screenshot 2026-01-27 at 7 23 29 PM ## Key Changes - **Options UI refresh** - Render options as numbered entries; allow number keys to select & submit. - Remove “Option X/Y” header and allow the question UI height to expand naturally. - Keep spacing between question, options, and notes even when notes are visible. - Hide the title line and render the question prompt in cyan **only when uncommitted**. - **“Other / None of the above” support** - Wire `isOther` to add “None of the above”. - Add guidance text: “Optionally, add details in notes (tab).” - **Notes composer UX** - Remove “Notes” heading; place composer directly under the selected option. - Preserve pending paste placeholders across question navigation and after submission. - Ctrl+C clears notes **only when the notes composer has focus**. - Ctrl+C now triggers an immediate redraw so the clear is visible. - **Committed vs uncommitted state** - Introduce a unified `answer_committed` flag per question. - Editing notes (including adding text or pastes) marks the answer uncommitted. - Changing the option highlight (j/k, up/down) marks the answer uncommitted. - Clearing options (Backspace/Delete) also clears pending notes. - Question prompt turns cyan only when the answer is uncommitted. - **Submission safety & confirmation** - Only submit notes/freeform text once explicitly committed. - Last-question submit with unanswered questions shows a confirmation dialog. - Confirmation options: 1. **Proceed** (default) 2. **Go back** - Description reflects count: “Submit with N unanswered question(s).” - Esc/Backspace in confirmation returns to first unanswered question. - Ctrl+C in confirmation interrupts and exits the overlay. - **Footer hints** - Cyan highlight restored for “enter to submit answer” / “enter to submit all”. ## Codex author `codex fork 019c00ed-323a-7000-bdb5-9f9c5a635bd9` --- .../tui/src/bottom_pane/bottom_pane_view.rs | 6 + codex-rs/tui/src/bottom_pane/chat_composer.rs | 14 +- codex-rs/tui/src/bottom_pane/mod.rs | 66 ++ .../bottom_pane/request_user_input/layout.rs | 217 ++--- .../src/bottom_pane/request_user_input/mod.rs | 883 ++++++++++++++---- .../bottom_pane/request_user_input/render.rs | 270 ++++-- ...tests__request_user_input_footer_wrap.snap | 14 +- ...t__tests__request_user_input_freeform.snap | 4 +- ...uest_user_input_hidden_options_footer.snap | 13 + ...quest_user_input_multi_question_first.snap | 9 +- ...equest_user_input_multi_question_last.snap | 4 +- ...ut__tests__request_user_input_options.snap | 9 +- ...uest_user_input_options_notes_visible.snap | 14 +- ..._request_user_input_scrolling_options.snap | 14 +- ...ests__request_user_input_tight_height.snap | 8 +- ...st_user_input_unanswered_confirmation.snap | 15 + ...s__request_user_input_wrapped_options.snap | 11 +- 17 files changed, 1164 insertions(+), 407 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_hidden_options_footer.snap create mode 100644 codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_unanswered_confirmation.snap diff --git a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs index d143449226..039a9ca051 100644 --- a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs +++ b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs @@ -21,6 +21,12 @@ pub(crate) trait BottomPaneView: Renderable { CancellationEvent::NotHandled } + /// Return true if Esc should be routed through `handle_key_event` instead + /// of the `on_ctrl_c` cancellation path. + fn prefer_esc_to_handle_key_event(&self) -> bool { + false + } + /// Optional paste handler. Return true if the view modified its state and /// needs a redraw. fn handle_paste(&mut self, _pasted: String) -> bool { diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index e59f820821..4c1228cb3c 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -653,6 +653,18 @@ impl ChatComposer { text } + pub(crate) fn pending_pastes(&self) -> Vec<(String, String)> { + self.pending_pastes.clone() + } + + pub(crate) fn set_pending_pastes(&mut self, pending_pastes: Vec<(String, String)>) { + let text = self.textarea.text().to_string(); + self.pending_pastes = pending_pastes + .into_iter() + .filter(|(placeholder, _)| text.contains(placeholder)) + .collect(); + } + /// Override the footer hint items displayed beneath the composer. Passing /// `None` restores the default shortcut footer. pub(crate) fn set_footer_hint_override(&mut self, items: Option>) { @@ -1431,7 +1443,7 @@ impl ChatComposer { } /// Expand large-paste placeholders using element ranges and rebuild other element spans. - fn expand_pending_pastes( + pub(crate) fn expand_pending_pastes( text: &str, mut elements: Vec, pending_pastes: &[(String, String)], diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index e0a7319a42..701e0762cb 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -269,7 +269,10 @@ impl BottomPane { let (ctrl_c_completed, view_complete, view_in_paste_burst) = { let last_index = self.view_stack.len() - 1; let view = &mut self.view_stack[last_index]; + let prefer_esc = + key_event.code == KeyCode::Esc && view.prefer_esc_to_handle_key_event(); let ctrl_c_completed = key_event.code == KeyCode::Esc + && !prefer_esc && matches!(view.on_ctrl_c(), CancellationEvent::Handled) && view.is_complete(); if ctrl_c_completed { @@ -338,6 +341,7 @@ impl BottomPane { self.on_active_view_complete(); } self.show_quit_shortcut_hint(key_hint::ctrl(KeyCode::Char('c'))); + self.request_redraw(); } event } else if self.composer_is_empty() { @@ -346,6 +350,7 @@ impl BottomPane { self.view_stack.pop(); self.clear_composer_for_ctrl_c(); self.show_quit_shortcut_hint(key_hint::ctrl(KeyCode::Char('c'))); + self.request_redraw(); CancellationEvent::Handled } } @@ -815,7 +820,9 @@ mod tests { use insta::assert_snapshot; use ratatui::buffer::Buffer; use ratatui::layout::Rect; + use std::cell::Cell; use std::path::PathBuf; + use std::rc::Rc; use tokio::sync::mpsc::unbounded_channel; fn snapshot_buffer(buf: &Buffer) -> String { @@ -1242,4 +1249,63 @@ mod tests { "expected Esc to send Op::Interrupt while a task is running" ); } + + #[test] + fn esc_routes_to_handle_key_event_when_requested() { + #[derive(Default)] + struct EscRoutingView { + on_ctrl_c_calls: Rc>, + handle_calls: Rc>, + } + + impl Renderable for EscRoutingView { + fn render(&self, _area: Rect, _buf: &mut Buffer) {} + + fn desired_height(&self, _width: u16) -> u16 { + 0 + } + } + + impl BottomPaneView for EscRoutingView { + fn handle_key_event(&mut self, _key_event: KeyEvent) { + self.handle_calls + .set(self.handle_calls.get().saturating_add(1)); + } + + fn on_ctrl_c(&mut self) -> CancellationEvent { + self.on_ctrl_c_calls + .set(self.on_ctrl_c_calls.get().saturating_add(1)); + CancellationEvent::Handled + } + + fn prefer_esc_to_handle_key_event(&self) -> bool { + true + } + } + + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut pane = BottomPane::new(BottomPaneParams { + app_event_tx: tx, + frame_requester: FrameRequester::test_dummy(), + has_input_focus: true, + enhanced_keys_supported: false, + placeholder_text: "Ask Codex to do anything".to_string(), + disable_paste_burst: false, + animations_enabled: true, + skills: Some(Vec::new()), + }); + + let on_ctrl_c_calls = Rc::new(Cell::new(0)); + let handle_calls = Rc::new(Cell::new(0)); + pane.push_view(Box::new(EscRoutingView { + on_ctrl_c_calls: Rc::clone(&on_ctrl_c_calls), + handle_calls: Rc::clone(&handle_calls), + })); + + pane.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + + assert_eq!(on_ctrl_c_calls.get(), 0); + assert_eq!(handle_calls.get(), 1); + } } diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs b/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs index 11856bd1df..27d53229b6 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/layout.rs @@ -1,16 +1,14 @@ use ratatui::layout::Rect; -use super::DESIRED_SPACERS_WHEN_NOTES_HIDDEN; +use super::DESIRED_SPACERS_BETWEEN_SECTIONS; use super::RequestUserInputOverlay; pub(super) struct LayoutSections { pub(super) progress_area: Rect, - pub(super) header_area: Rect, pub(super) question_area: Rect, // Wrapped question text lines to render in the question area. pub(super) question_lines: Vec, pub(super) options_area: Rect, - pub(super) notes_title_area: Rect, pub(super) notes_area: Rect, // Number of footer rows (status + hints). pub(super) footer_lines: u16, @@ -26,16 +24,7 @@ impl RequestUserInputOverlay { let mut question_lines = self.wrapped_question_lines(area.width); let question_height = question_lines.len() as u16; - let ( - question_height, - progress_height, - spacer_after_question, - options_height, - spacer_after_options, - notes_title_height, - notes_height, - footer_lines, - ) = if has_options { + let layout = if has_options { self.layout_with_options( OptionsLayoutArgs { available_height: area.height, @@ -57,98 +46,52 @@ impl RequestUserInputOverlay { ) }; - let (progress_area, header_area, question_area, options_area, notes_title_area, notes_area) = - self.build_layout_areas( - area, - LayoutHeights { - progress_height, - question_height, - spacer_after_question, - options_height, - spacer_after_options, - notes_title_height, - notes_height, - }, - ); + let (progress_area, question_area, options_area, notes_area) = + self.build_layout_areas(area, layout); LayoutSections { progress_area, - header_area, question_area, question_lines, options_area, - notes_title_area, notes_area, - footer_lines, + footer_lines: layout.footer_lines, } } /// Layout calculation when options are present. - /// - /// Handles both tight layout (when space is constrained) and normal layout - /// (when there's sufficient space for all elements). - /// - /// Returns: (question_height, progress_height, spacer_after_question, options_height, spacer_after_options, notes_title_height, notes_height, footer_lines) fn layout_with_options( &self, args: OptionsLayoutArgs, question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { + ) -> LayoutPlan { let OptionsLayoutArgs { available_height, width, - question_height, + mut question_height, notes_pref_height, footer_pref, notes_visible, } = args; - let options_heights = OptionsHeights { - preferred: self.options_preferred_height(width), - full: self.options_required_height(width), - }; - let min_options_height = 1u16; - let required = 1u16 - .saturating_add(question_height) - .saturating_add(options_heights.preferred); - - if required > available_height { - self.layout_with_options_tight( + let min_options_height = available_height.min(1); + let max_question_height = available_height.saturating_sub(min_options_height); + if question_height > max_question_height { + question_height = max_question_height; + question_lines.truncate(question_height as usize); + } + self.layout_with_options_normal( + OptionsNormalArgs { available_height, question_height, - min_options_height, - question_lines, - ) - } else { - self.layout_with_options_normal( - OptionsNormalArgs { - available_height, - question_height, - notes_pref_height, - footer_pref, - notes_visible, - }, - options_heights, - ) - } - } - - /// Tight layout for options case: allocate header + question + options first - /// and drop everything else when space is constrained. - fn layout_with_options_tight( - &self, - available_height: u16, - question_height: u16, - min_options_height: u16, - question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { - let max_question_height = - available_height.saturating_sub(1u16.saturating_add(min_options_height)); - let adjusted_question_height = question_height.min(max_question_height); - question_lines.truncate(adjusted_question_height as usize); - let options_height = - available_height.saturating_sub(1u16.saturating_add(adjusted_question_height)); - - (adjusted_question_height, 0, 0, options_height, 0, 0, 0, 0) + notes_pref_height, + footer_pref, + notes_visible, + }, + OptionsHeights { + preferred: self.options_preferred_height(width), + full: self.options_required_height(width), + }, + ) } /// Normal layout for options case: allocate footer + progress first, and @@ -157,7 +100,7 @@ impl RequestUserInputOverlay { &self, args: OptionsNormalArgs, options: OptionsHeights, - ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { + ) -> LayoutPlan { let OptionsNormalArgs { available_height, question_height, @@ -165,19 +108,23 @@ impl RequestUserInputOverlay { footer_pref, notes_visible, } = args; - let min_options_height = 1u16; - let mut options_height = options.preferred.max(min_options_height); - let used = 1u16 - .saturating_add(question_height) - .saturating_add(options_height); + let max_options_height = available_height.saturating_sub(question_height); + let min_options_height = max_options_height.min(1); + let mut options_height = options + .preferred + .min(max_options_height) + .max(min_options_height); + let used = question_height.saturating_add(options_height); let mut remaining = available_height.saturating_sub(used); // When notes are hidden, prefer to reserve room for progress, footer, // and spacers by shrinking the options window if needed. let desired_spacers = if notes_visible { - 0 + // Notes already separate options from the footer, so only keep a + // single spacer between the question and options. + 1 } else { - DESIRED_SPACERS_WHEN_NOTES_HIDDEN + DESIRED_SPACERS_BETWEEN_SECTIONS }; let required_extra = footer_pref .saturating_add(1) // progress line @@ -211,45 +158,41 @@ impl RequestUserInputOverlay { } let grow_by = remaining.min(options.full.saturating_sub(options_height)); options_height = options_height.saturating_add(grow_by); - return ( + return LayoutPlan { question_height, progress_height, spacer_after_question, options_height, spacer_after_options, - 0, - 0, + notes_height: 0, footer_lines, - ); + }; } let footer_lines = footer_pref.min(remaining); remaining = remaining.saturating_sub(footer_lines); - // Prefer notes next, then labels, with any leftover rows expanding notes. - let spacer_after_question = 0; + // Prefer spacers before notes, then notes. + let mut spacer_after_question = 0; + if remaining > 0 { + spacer_after_question = 1; + remaining = remaining.saturating_sub(1); + } let spacer_after_options = 0; let mut notes_height = notes_pref_height.min(remaining); remaining = remaining.saturating_sub(notes_height); - let mut notes_title_height = 0; - if remaining > 0 { - notes_title_height = 1; - remaining = remaining.saturating_sub(1); - } - notes_height = notes_height.saturating_add(remaining); - ( + LayoutPlan { question_height, progress_height, spacer_after_question, options_height, spacer_after_options, - notes_title_height, notes_height, footer_lines, - ) + } } /// Layout calculation when no options are present. @@ -257,7 +200,6 @@ impl RequestUserInputOverlay { /// Handles both tight layout (when space is constrained) and normal layout /// (when there's sufficient space for all elements). /// - /// Returns: (question_height, progress_height, spacer_after_question, options_height, spacer_after_options, notes_title_height, notes_height, footer_lines) fn layout_without_options( &self, available_height: u16, @@ -265,8 +207,8 @@ impl RequestUserInputOverlay { notes_pref_height: u16, footer_pref: u16, question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { - let required = 1u16.saturating_add(question_height); + ) -> LayoutPlan { + let required = question_height; if required > available_height { self.layout_without_options_tight(available_height, question_height, question_lines) } else { @@ -285,12 +227,20 @@ impl RequestUserInputOverlay { available_height: u16, question_height: u16, question_lines: &mut Vec, - ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { - let max_question_height = available_height.saturating_sub(1); + ) -> LayoutPlan { + let max_question_height = available_height; let adjusted_question_height = question_height.min(max_question_height); question_lines.truncate(adjusted_question_height as usize); - (adjusted_question_height, 0, 0, 0, 0, 0, 0, 0) + LayoutPlan { + question_height: adjusted_question_height, + progress_height: 0, + spacer_after_question: 0, + options_height: 0, + spacer_after_options: 0, + notes_height: 0, + footer_lines: 0, + } } /// Normal layout for no-options case: allocate space for notes, footer, and progress. @@ -300,8 +250,8 @@ impl RequestUserInputOverlay { question_height: u16, notes_pref_height: u16, footer_pref: u16, - ) -> (u16, u16, u16, u16, u16, u16, u16, u16) { - let required = 1u16.saturating_add(question_height); + ) -> LayoutPlan { + let required = question_height; let mut remaining = available_height.saturating_sub(required); let mut notes_height = notes_pref_height.min(remaining); remaining = remaining.saturating_sub(notes_height); @@ -317,29 +267,26 @@ impl RequestUserInputOverlay { notes_height = notes_height.saturating_add(remaining); - ( + LayoutPlan { question_height, progress_height, - 0, - 0, - 0, - 0, + spacer_after_question: 0, + options_height: 0, + spacer_after_options: 0, notes_height, footer_lines, - ) + } } /// Build the final layout areas from computed heights. fn build_layout_areas( &self, area: Rect, - heights: LayoutHeights, + heights: LayoutPlan, ) -> ( Rect, // progress_area - Rect, // header_area Rect, // question_area Rect, // options_area - Rect, // notes_title_area Rect, // notes_area ) { let mut cursor_y = area.y; @@ -350,14 +297,6 @@ impl RequestUserInputOverlay { height: heights.progress_height, }; cursor_y = cursor_y.saturating_add(heights.progress_height); - let header_height = area.height.saturating_sub(heights.progress_height).min(1); - let header_area = Rect { - x: area.x, - y: cursor_y, - width: area.width, - height: header_height, - }; - cursor_y = cursor_y.saturating_add(header_height); let question_area = Rect { x: area.x, y: cursor_y, @@ -376,13 +315,6 @@ impl RequestUserInputOverlay { cursor_y = cursor_y.saturating_add(heights.options_height); cursor_y = cursor_y.saturating_add(heights.spacer_after_options); - let notes_title_area = Rect { - x: area.x, - y: cursor_y, - width: area.width, - height: heights.notes_title_height, - }; - cursor_y = cursor_y.saturating_add(heights.notes_title_height); let notes_area = Rect { x: area.x, y: cursor_y, @@ -390,26 +322,19 @@ impl RequestUserInputOverlay { height: heights.notes_height, }; - ( - progress_area, - header_area, - question_area, - options_area, - notes_title_area, - notes_area, - ) + (progress_area, question_area, options_area, notes_area) } } #[derive(Clone, Copy, Debug)] -struct LayoutHeights { +struct LayoutPlan { progress_height: u16, question_height: u16, spacer_after_question: u16, options_height: u16, spacer_after_options: u16, - notes_title_height: u16, notes_height: u16, + footer_lines: u16, } #[derive(Clone, Copy, Debug)] 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 3fe16c4314..979499835d 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 @@ -42,8 +42,15 @@ const ANSWER_PLACEHOLDER: &str = "Type your answer (optional)"; const MIN_COMPOSER_HEIGHT: u16 = 3; const SELECT_OPTION_PLACEHOLDER: &str = "Select an option to add notes"; pub(super) const TIP_SEPARATOR: &str = " | "; -pub(super) const MAX_VISIBLE_OPTION_ROWS: usize = 4; -pub(super) const DESIRED_SPACERS_WHEN_NOTES_HIDDEN: u16 = 2; +pub(super) const DESIRED_SPACERS_BETWEEN_SECTIONS: u16 = 2; +const OTHER_OPTION_LABEL: &str = "None of the above"; +const OTHER_OPTION_DESCRIPTION: &str = "Optionally, add details in notes (tab)."; +const UNANSWERED_CONFIRM_TITLE: &str = "Submit with unanswered questions?"; +const UNANSWERED_CONFIRM_GO_BACK: &str = "Go back"; +const UNANSWERED_CONFIRM_GO_BACK_DESC: &str = "Return to the first unanswered question."; +const UNANSWERED_CONFIRM_SUBMIT: &str = "Proceed"; +const UNANSWERED_CONFIRM_SUBMIT_DESC_SINGULAR: &str = "question"; +const UNANSWERED_CONFIRM_SUBMIT_DESC_PLURAL: &str = "questions"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Focus { @@ -51,22 +58,39 @@ enum Focus { Notes, } -#[derive(Default, Clone)] +#[derive(Default, Clone, PartialEq)] struct ComposerDraft { text: String, text_elements: Vec, local_image_paths: Vec, + pending_pastes: Vec<(String, String)>, +} + +impl ComposerDraft { + fn text_with_pending(&self) -> String { + if self.pending_pastes.is_empty() { + return self.text.clone(); + } + debug_assert!( + !self.text_elements.is_empty(), + "pending pastes should always have matching text elements" + ); + let (expanded, _) = ChatComposer::expand_pending_pastes( + &self.text, + self.text_elements.clone(), + &self.pending_pastes, + ); + expanded + } } struct AnswerState { - // Committed selection for the question (may be None when unanswered). - committed_option_idx: Option, // Scrollable cursor state for option navigation/highlight. - options_ui_state: ScrollState, + options_state: ScrollState, // Per-question notes draft. draft: ComposerDraft, - // Whether a freeform answer has been explicitly submitted. - freeform_committed: bool, + // Whether the answer for this question has been explicitly submitted. + answer_committed: bool, // Whether the notes UI has been explicitly opened for this question. notes_visible: bool, } @@ -106,6 +130,8 @@ pub(crate) struct RequestUserInputOverlay { current_idx: usize, focus: Focus, done: bool, + pending_submission_draft: Option, + confirm_unanswered: Option, } impl RequestUserInputOverlay { @@ -137,6 +163,8 @@ impl RequestUserInputOverlay { current_idx: 0, focus: Focus::Options, done: false, + pending_submission_draft: None, + confirm_unanswered: None, }; overlay.reset_for_request(); overlay.ensure_focus_available(); @@ -176,28 +204,28 @@ impl RequestUserInputOverlay { fn options_len(&self) -> usize { self.current_question() - .and_then(|question| question.options.as_ref()) - .map(std::vec::Vec::len) + .map(Self::options_len_for_question) .unwrap_or(0) } + fn option_index_for_digit(&self, ch: char) -> Option { + if !self.has_options() { + return None; + } + let digit = ch.to_digit(10)?; + if digit == 0 { + return None; + } + let idx = (digit - 1) as usize; + (idx < self.options_len()).then_some(idx) + } + fn selected_option_index(&self) -> Option { if !self.has_options() { return None; } - self.current_answer().and_then(|answer| { - answer - .committed_option_idx - .or(answer.options_ui_state.selected_idx) - }) - } - - fn current_option_label(&self) -> Option<&str> { - let idx = self.selected_option_index()?; - self.current_question() - .and_then(|question| question.options.as_ref()) - .and_then(|options| options.get(idx)) - .map(|option| option.label.as_str()) + self.current_answer() + .and_then(|answer| answer.options_state.selected_idx) } fn notes_has_content(&self, idx: usize) -> bool { @@ -232,26 +260,46 @@ impl RequestUserInputOverlay { matches!(self.focus, Focus::Notes) } + fn confirm_unanswered_active(&self) -> bool { + self.confirm_unanswered.is_some() + } + pub(super) fn option_rows(&self) -> Vec { self.current_question() - .and_then(|question| question.options.as_ref()) - .map(|options| { - options + .and_then(|question| question.options.as_ref().map(|options| (question, options))) + .map(|(question, options)| { + let selected_idx = self + .current_answer() + .and_then(|answer| answer.options_state.selected_idx); + let mut rows = options .iter() .enumerate() .map(|(idx, opt)| { - let selected = self - .current_answer() - .and_then(|answer| answer.committed_option_idx) - .is_some_and(|sel| sel == idx); - let prefix = if selected { "(x)" } else { "( )" }; + let selected = selected_idx.is_some_and(|sel| sel == idx); + let prefix = if selected { '›' } else { ' ' }; + let label = opt.label.as_str(); + let number = idx + 1; GenericDisplayRow { - name: format!("{prefix} {}", opt.label), + name: format!("{prefix} {number}. {label}"), description: Some(opt.description.clone()), ..Default::default() } }) - .collect::>() + .collect::>(); + + if Self::other_option_enabled_for_question(question) { + let idx = options.len(); + let selected = selected_idx.is_some_and(|sel| sel == idx); + let prefix = if selected { '›' } else { ' ' }; + let number = idx + 1; + rows.push(GenericDisplayRow { + name: format!("{prefix} {number}. {OTHER_OPTION_LABEL}"), + description: Some(OTHER_OPTION_DESCRIPTION.to_string()), + ..Default::default() + }); + } + + rows }) .unwrap_or_default() } @@ -268,7 +316,7 @@ impl RequestUserInputOverlay { let mut state = self .current_answer() - .map(|answer| answer.options_ui_state) + .map(|answer| answer.options_state) .unwrap_or_default(); if state.selected_idx.is_none() { state.selected_idx = Some(0); @@ -289,19 +337,18 @@ impl RequestUserInputOverlay { let mut state = self .current_answer() - .map(|answer| answer.options_ui_state) + .map(|answer| answer.options_state) .unwrap_or_default(); if state.selected_idx.is_none() { state.selected_idx = Some(0); } - let visible_items = rows.len().min(MAX_VISIBLE_OPTION_ROWS); - measure_rows_height(&rows, &state, visible_items, width.max(1)) + measure_rows_height(&rows, &state, rows.len(), width.max(1)) } fn capture_composer_draft(&self) -> ComposerDraft { ComposerDraft { - text: self.composer.current_text_with_pending(), + text: self.composer.current_text(), text_elements: self.composer.text_elements(), local_image_paths: self .composer @@ -309,6 +356,7 @@ impl RequestUserInputOverlay { .into_iter() .map(|img| img.path) .collect(), + pending_pastes: self.composer.pending_pastes(), } } @@ -316,6 +364,9 @@ impl RequestUserInputOverlay { let draft = self.capture_composer_draft(); let notes_empty = draft.text.trim().is_empty(); if let Some(answer) = self.current_answer_mut() { + if answer.answer_committed && answer.draft != draft { + answer.answer_committed = false; + } answer.draft = draft; if !notes_empty { answer.notes_visible = true; @@ -336,6 +387,7 @@ impl RequestUserInputOverlay { let draft = answer.draft.clone(); self.composer .set_text_content(draft.text, draft.text_elements, draft.local_image_paths); + self.composer.set_pending_pastes(draft.pending_pastes); self.composer.move_cursor_to_end(); } @@ -354,47 +406,72 @@ impl RequestUserInputOverlay { .set_placeholder_text(self.notes_placeholder().to_string()); } + fn clear_notes_draft(&mut self) { + if let Some(answer) = self.current_answer_mut() { + answer.draft = ComposerDraft::default(); + answer.answer_committed = false; + answer.notes_visible = true; + } + self.pending_submission_draft = None; + self.composer + .set_text_content(String::new(), Vec::new(), Vec::new()); + self.composer.move_cursor_to_end(); + self.sync_composer_placeholder(); + } + fn footer_tips(&self) -> Vec { let mut tips = Vec::new(); let notes_visible = self.notes_ui_visible(); if self.has_options() { - let options_len = self.options_len(); - if let Some(selected_idx) = self.selected_option_index() { - let option_index = selected_idx + 1; - tips.push(FooterTip::new(format!( - "Option {option_index} of {options_len}" - ))); - } else { - tips.push(FooterTip::new("No option selected")); - } - tips.push(FooterTip::new("\u{2191}/\u{2193} scroll")); if self.selected_option_index().is_some() && !notes_visible { - tips.push(FooterTip::highlighted("Tab: add notes")); + tips.push(FooterTip::highlighted("tab to add notes")); } if self.selected_option_index().is_some() && notes_visible && self.focus_is_notes() { - tips.push(FooterTip::new("Tab: clear notes")); + tips.push(FooterTip::new("tab to clear notes")); } } let question_count = self.question_count(); - let is_last_question = question_count > 0 && self.current_index() + 1 >= question_count; - let enter_tip = if question_count > 1 && is_last_question { - "Enter: submit all answers" + let is_last_question = self.current_index().saturating_add(1) >= question_count; + let enter_tip = if question_count == 1 { + FooterTip::highlighted("enter to submit answer") + } else if is_last_question { + FooterTip::highlighted("enter to submit all") } else { - "Enter: submit answer" + FooterTip::new("enter to submit answer") }; - tips.push(FooterTip::new(enter_tip)); + tips.push(enter_tip); if question_count > 1 { - tips.push(FooterTip::new("Ctrl+n next")); + if is_last_question { + tips.push(FooterTip::new("ctrl + n first question")); + } else { + tips.push(FooterTip::new("ctrl + n next question")); + } } - tips.push(FooterTip::new("Esc: interrupt")); + tips.push(FooterTip::new("esc to interrupt")); tips } pub(super) fn footer_tip_lines(&self, width: u16) -> Vec> { + self.wrap_footer_tips(width, self.footer_tips()) + } + + pub(super) fn footer_tip_lines_with_prefix( + &self, + width: u16, + prefix: Option, + ) -> Vec> { + let mut tips = Vec::new(); + if let Some(prefix) = prefix { + tips.push(prefix); + } + tips.extend(self.footer_tips()); + self.wrap_footer_tips(width, tips) + } + + fn wrap_footer_tips(&self, width: u16, tips: Vec) -> Vec> { let max_width = width.max(1) as usize; let separator_width = UnicodeWidthStr::width(TIP_SEPARATOR); - let tips = self.footer_tips(); if tips.is_empty() { return vec![Vec::new()]; } @@ -466,15 +543,14 @@ impl RequestUserInputOverlay { .options .as_ref() .is_some_and(|options| !options.is_empty()); - let mut options_ui_state = ScrollState::new(); + let mut options_state = ScrollState::new(); if has_options { - options_ui_state.selected_idx = Some(0); + options_state.selected_idx = Some(0); } AnswerState { - committed_option_idx: None, - options_ui_state, + options_state, draft: ComposerDraft::default(), - freeform_committed: false, + answer_committed: false, notes_visible: !has_options, } }) @@ -484,6 +560,47 @@ impl RequestUserInputOverlay { self.focus = Focus::Options; self.composer .set_text_content(String::new(), Vec::new(), Vec::new()); + self.confirm_unanswered = None; + self.pending_submission_draft = None; + } + + fn options_len_for_question( + question: &codex_protocol::request_user_input::RequestUserInputQuestion, + ) -> usize { + let options_len = question + .options + .as_ref() + .map(std::vec::Vec::len) + .unwrap_or(0); + if Self::other_option_enabled_for_question(question) { + options_len + 1 + } else { + options_len + } + } + + fn other_option_enabled_for_question( + question: &codex_protocol::request_user_input::RequestUserInputQuestion, + ) -> bool { + question.is_other + && question + .options + .as_ref() + .is_some_and(|options| !options.is_empty()) + } + + fn option_label_for_index( + question: &codex_protocol::request_user_input::RequestUserInputQuestion, + idx: usize, + ) -> Option { + let options = question.options.as_ref()?; + if idx < options.len() { + return options.get(idx).map(|opt| opt.label.clone()); + } + if idx == options.len() && Self::other_option_enabled_for_question(question) { + return Some(OTHER_OPTION_LABEL.to_string()); + } + None } /// Move to the next/previous question, wrapping in either direction. @@ -499,15 +616,25 @@ impl RequestUserInputOverlay { self.ensure_focus_available(); } + fn jump_to_question(&mut self, idx: usize) { + if idx >= self.question_count() { + return; + } + self.save_current_draft(); + self.current_idx = idx; + self.restore_current_draft(); + self.ensure_focus_available(); + } + /// Synchronize selection state to the currently focused option. - fn select_current_option(&mut self) { + fn select_current_option(&mut self, committed: bool) { if !self.has_options() { return; } let options_len = self.options_len(); let updated = if let Some(answer) = self.current_answer_mut() { - answer.options_ui_state.clamp_selection(options_len); - answer.committed_option_idx = answer.options_ui_state.selected_idx; + answer.options_state.clamp_selection(options_len); + answer.answer_committed = committed; true } else { false @@ -522,15 +649,16 @@ impl RequestUserInputOverlay { if !self.has_options() { return; } - self.save_current_draft(); - let notes_empty = self.composer.current_text_with_pending().trim().is_empty(); if let Some(answer) = self.current_answer_mut() { - answer.committed_option_idx = None; - answer.options_ui_state.reset(); - if notes_empty { - answer.notes_visible = false; - } + answer.options_state.reset(); + answer.draft = ComposerDraft::default(); + answer.answer_committed = false; + answer.notes_visible = false; } + self.pending_submission_draft = None; + self.composer + .set_text_content(String::new(), Vec::new(), Vec::new()); + self.composer.move_cursor_to_end(); self.sync_composer_placeholder(); } @@ -545,7 +673,12 @@ impl RequestUserInputOverlay { /// Advance to next question, or submit when on the last one. fn go_next_or_submit(&mut self) { if self.current_index() + 1 >= self.question_count() { - self.submit_answers(); + self.save_current_draft(); + if self.unanswered_count() > 0 { + self.open_unanswered_confirmation(); + } else { + self.submit_answers(); + } } else { self.move_question(true); } @@ -553,33 +686,28 @@ impl RequestUserInputOverlay { /// Build the response payload and dispatch it to the app. fn submit_answers(&mut self) { + self.confirm_unanswered = None; self.save_current_draft(); let mut answers = HashMap::new(); for (idx, question) in self.request.questions.iter().enumerate() { let answer_state = &self.answers[idx]; let options = question.options.as_ref(); // For option questions we may still produce no selection. - let selected_idx = if options.is_some_and(|opts| !opts.is_empty()) { - answer_state.committed_option_idx - } else { - None - }; + let selected_idx = + if options.is_some_and(|opts| !opts.is_empty()) && answer_state.answer_committed { + answer_state.options_state.selected_idx + } else { + None + }; // Notes are appended as extra answers. For freeform questions, only submit when // the user explicitly committed the draft. - let notes = if options.is_some_and(|opts| !opts.is_empty()) - || answer_state.freeform_committed - { - answer_state.draft.text.trim().to_string() + let notes = if answer_state.answer_committed { + answer_state.draft.text_with_pending().trim().to_string() } else { String::new() }; - let selected_label = selected_idx.and_then(|selected_idx| { - question - .options - .as_ref() - .and_then(|opts| opts.get(selected_idx)) - .map(|opt| opt.label.clone()) - }); + let selected_label = selected_idx + .and_then(|selected_idx| Self::option_label_for_index(question, selected_idx)); let mut answer_list = selected_label.into_iter().collect::>(); if !notes.is_empty() { answer_list.push(format!("user_note: {notes}")); @@ -606,6 +734,71 @@ impl RequestUserInputOverlay { } } + fn open_unanswered_confirmation(&mut self) { + let mut state = ScrollState::new(); + state.selected_idx = Some(0); + self.confirm_unanswered = Some(state); + } + + fn close_unanswered_confirmation(&mut self) { + self.confirm_unanswered = None; + } + + fn unanswered_question_count(&self) -> usize { + self.unanswered_count() + } + + fn unanswered_submit_description(&self) -> String { + let count = self.unanswered_question_count(); + let suffix = if count == 1 { + UNANSWERED_CONFIRM_SUBMIT_DESC_SINGULAR + } else { + UNANSWERED_CONFIRM_SUBMIT_DESC_PLURAL + }; + format!("Submit with {count} unanswered {suffix}.") + } + + fn first_unanswered_index(&self) -> Option { + let current_text = self.composer.current_text(); + self.request + .questions + .iter() + .enumerate() + .find(|(idx, _)| !self.is_question_answered(*idx, ¤t_text)) + .map(|(idx, _)| idx) + } + + fn unanswered_confirmation_rows(&self) -> Vec { + let selected = self + .confirm_unanswered + .as_ref() + .and_then(|state| state.selected_idx) + .unwrap_or(0); + let entries = [ + ( + UNANSWERED_CONFIRM_SUBMIT, + self.unanswered_submit_description(), + ), + ( + UNANSWERED_CONFIRM_GO_BACK, + UNANSWERED_CONFIRM_GO_BACK_DESC.to_string(), + ), + ]; + entries + .iter() + .enumerate() + .map(|(idx, (label, description))| { + let prefix = if idx == selected { '›' } else { ' ' }; + let number = idx + 1; + GenericDisplayRow { + name: format!("{prefix} {number}. {label}"), + description: Some(description.clone()), + ..Default::default() + } + }) + .collect() + } + fn is_question_answered(&self, idx: usize, _current_text: &str) -> bool { let Some(question) = self.request.questions.get(idx) else { return false; @@ -618,17 +811,12 @@ impl RequestUserInputOverlay { .as_ref() .is_some_and(|options| !options.is_empty()); if has_options { - answer.committed_option_idx.is_some() + answer.options_state.selected_idx.is_some() && answer.answer_committed } else { - answer.freeform_committed + answer.answer_committed } } - fn current_question_answered(&self) -> bool { - let current_text = self.composer.current_text(); - self.is_question_answered(self.current_index(), ¤t_text) - } - /// Count questions that would submit an empty answer list. fn unanswered_count(&self) -> usize { let current_text = self.composer.current_text(); @@ -660,6 +848,7 @@ impl RequestUserInputOverlay { text: text.clone(), text_elements: text_elements.clone(), local_image_paths: local_image_paths.clone(), + pending_pastes: Vec::new(), }; } self.composer @@ -668,6 +857,17 @@ impl RequestUserInputOverlay { self.composer.set_footer_hint_override(Some(Vec::new())); } + fn apply_submission_draft(&mut self, draft: ComposerDraft) { + if let Some(answer) = self.current_answer_mut() { + answer.draft = draft.clone(); + } + self.composer + .set_text_content(draft.text, draft.text_elements, draft.local_image_paths); + self.composer.set_pending_pastes(draft.pending_pastes); + self.composer.move_cursor_to_end(); + self.composer.set_footer_hint_override(Some(Vec::new())); + } + fn handle_composer_input_result(&mut self, result: InputResult) -> bool { match result { InputResult::Submitted { @@ -684,30 +884,87 @@ impl RequestUserInputOverlay { { let options_len = self.options_len(); if let Some(answer) = self.current_answer_mut() { - answer.options_ui_state.clamp_selection(options_len); - answer.committed_option_idx = answer.options_ui_state.selected_idx; + answer.options_state.clamp_selection(options_len); } } - if !self.has_options() - && let Some(answer) = self.current_answer_mut() - { - answer.freeform_committed = !text.trim().is_empty(); + if self.has_options() { + if let Some(answer) = self.current_answer_mut() { + answer.answer_committed = true; + } + } else if let Some(answer) = self.current_answer_mut() { + answer.answer_committed = !text.trim().is_empty(); + } + let draft_override = self.pending_submission_draft.take(); + if let Some(draft) = draft_override { + self.apply_submission_draft(draft); + } else { + self.apply_submission_to_draft(text, text_elements); } - self.apply_submission_to_draft(text, text_elements); self.go_next_or_submit(); true } _ => false, } } + + fn handle_confirm_unanswered_key_event(&mut self, key_event: KeyEvent) { + if key_event.kind == KeyEventKind::Release { + return; + } + let Some(state) = self.confirm_unanswered.as_mut() else { + return; + }; + + match key_event.code { + KeyCode::Esc | KeyCode::Backspace => { + self.close_unanswered_confirmation(); + if let Some(idx) = self.first_unanswered_index() { + self.jump_to_question(idx); + } + } + KeyCode::Up | KeyCode::Char('k') => { + state.move_up_wrap(2); + } + KeyCode::Down | KeyCode::Char('j') => { + state.move_down_wrap(2); + } + KeyCode::Enter => { + let selected = state.selected_idx.unwrap_or(0); + self.close_unanswered_confirmation(); + if selected == 0 { + self.submit_answers(); + } else if let Some(idx) = self.first_unanswered_index() { + self.jump_to_question(idx); + } + } + KeyCode::Char('1') | KeyCode::Char('2') => { + let idx = if matches!(key_event.code, KeyCode::Char('1')) { + 0 + } else { + 1 + }; + state.selected_idx = Some(idx); + } + _ => {} + } + } } impl BottomPaneView for RequestUserInputOverlay { + fn prefer_esc_to_handle_key_event(&self) -> bool { + true + } + fn handle_key_event(&mut self, key_event: KeyEvent) { if key_event.kind == KeyEventKind::Release { return; } + if self.confirm_unanswered_active() { + self.handle_confirm_unanswered_key_event(key_event); + return; + } + if matches!(key_event.code, KeyCode::Esc) { self.app_event_tx.send(AppEvent::CodexOp(Op::Interrupt)); self.done = true; @@ -720,11 +977,21 @@ impl BottomPaneView for RequestUserInputOverlay { code: KeyCode::Char('p'), modifiers: KeyModifiers::CONTROL, .. + } + | KeyEvent { + code: KeyCode::PageUp, + modifiers: KeyModifiers::NONE, + .. } => { self.move_question(false); return; } KeyEvent { + code: KeyCode::PageDown, + modifiers: KeyModifiers::NONE, + .. + } + | KeyEvent { code: KeyCode::Char('n'), modifiers: KeyModifiers::CONTROL, .. @@ -758,7 +1025,8 @@ impl BottomPaneView for RequestUserInputOverlay { match key_event.code { KeyCode::Up | KeyCode::Char('k') => { let moved = if let Some(answer) = self.current_answer_mut() { - answer.options_ui_state.move_up_wrap(options_len); + answer.options_state.move_up_wrap(options_len); + answer.answer_committed = false; true } else { false @@ -769,7 +1037,8 @@ impl BottomPaneView for RequestUserInputOverlay { } KeyCode::Down | KeyCode::Char('j') => { let moved = if let Some(answer) = self.current_answer_mut() { - answer.options_ui_state.move_down_wrap(options_len); + answer.options_state.move_down_wrap(options_len); + answer.answer_committed = false; true } else { false @@ -779,9 +1048,9 @@ impl BottomPaneView for RequestUserInputOverlay { } } KeyCode::Char(' ') => { - self.select_current_option(); + self.select_current_option(true); } - KeyCode::Backspace => { + KeyCode::Backspace | KeyCode::Delete => { self.clear_selection(); } KeyCode::Tab => { @@ -793,10 +1062,19 @@ impl BottomPaneView for RequestUserInputOverlay { KeyCode::Enter => { let has_selection = self.selected_option_index().is_some(); if has_selection { - self.select_current_option(); + self.select_current_option(true); } self.go_next_or_submit(); } + KeyCode::Char(ch) => { + if let Some(option_idx) = self.option_index_for_digit(ch) { + if let Some(answer) = self.current_answer_mut() { + answer.options_state.selected_idx = Some(option_idx); + } + self.select_current_option(true); + self.go_next_or_submit(); + } + } _ => {} } } @@ -805,6 +1083,7 @@ impl BottomPaneView for RequestUserInputOverlay { if self.has_options() && matches!(key_event.code, KeyCode::Tab) { if let Some(answer) = self.current_answer_mut() { answer.draft = ComposerDraft::default(); + answer.answer_committed = false; answer.notes_visible = false; } self.composer @@ -826,8 +1105,13 @@ impl BottomPaneView for RequestUserInputOverlay { } if matches!(key_event.code, KeyCode::Enter) { self.ensure_selected_for_notes(); + self.pending_submission_draft = Some(self.capture_composer_draft()); let (result, _) = self.composer.handle_key_event(key_event); if !self.handle_composer_input_result(result) { + self.pending_submission_draft = None; + if self.has_options() { + self.select_current_option(true); + } self.go_next_or_submit(); } return; @@ -837,7 +1121,8 @@ impl BottomPaneView for RequestUserInputOverlay { match key_event.code { KeyCode::Up => { let moved = if let Some(answer) = self.current_answer_mut() { - answer.options_ui_state.move_up_wrap(options_len); + answer.options_state.move_up_wrap(options_len); + answer.answer_committed = false; true } else { false @@ -848,7 +1133,8 @@ impl BottomPaneView for RequestUserInputOverlay { } KeyCode::Down => { let moved = if let Some(answer) = self.current_answer_mut() { - answer.options_ui_state.move_down_wrap(options_len); + answer.options_state.move_down_wrap(options_len); + answer.answer_committed = false; true } else { false @@ -862,13 +1148,40 @@ impl BottomPaneView for RequestUserInputOverlay { return; } self.ensure_selected_for_notes(); + if matches!( + key_event.code, + KeyCode::Char(_) | KeyCode::Backspace | KeyCode::Delete + ) && let Some(answer) = self.current_answer_mut() + { + answer.answer_committed = false; + } + let before = self.capture_composer_draft(); let (result, _) = self.composer.handle_key_event(key_event); - self.handle_composer_input_result(result); + let submitted = self.handle_composer_input_result(result); + if !submitted { + let after = self.capture_composer_draft(); + if before != after + && let Some(answer) = self.current_answer_mut() + { + answer.answer_committed = false; + } + } } } } fn on_ctrl_c(&mut self) -> CancellationEvent { + if self.confirm_unanswered_active() { + self.close_unanswered_confirmation(); + self.app_event_tx.send(AppEvent::CodexOp(Op::Interrupt)); + self.done = true; + return CancellationEvent::Handled; + } + if self.focus_is_notes() && !self.composer.current_text_with_pending().is_empty() { + self.clear_notes_draft(); + return CancellationEvent::Handled; + } + self.app_event_tx.send(AppEvent::CodexOp(Op::Interrupt)); self.done = true; CancellationEvent::Handled @@ -887,6 +1200,9 @@ impl BottomPaneView for RequestUserInputOverlay { self.focus = Focus::Notes; } self.ensure_selected_for_notes(); + if let Some(answer) = self.current_answer_mut() { + answer.answer_committed = false; + } self.composer.handle_paste(pasted) } @@ -952,6 +1268,29 @@ mod tests { } } + fn question_with_options_and_other(id: &str, header: &str) -> RequestUserInputQuestion { + RequestUserInputQuestion { + id: id.to_string(), + header: header.to_string(), + question: "Choose an option.".to_string(), + is_other: true, + options: Some(vec![ + RequestUserInputQuestionOption { + label: "Option 1".to_string(), + description: "First choice.".to_string(), + }, + RequestUserInputQuestionOption { + label: "Option 2".to_string(), + description: "Second choice.".to_string(), + }, + RequestUserInputQuestionOption { + label: "Option 3".to_string(), + description: "Third choice.".to_string(), + }, + ]), + } + } + fn question_with_wrapped_options(id: &str, header: &str) -> RequestUserInputQuestion { RequestUserInputQuestion { id: id.to_string(), @@ -1109,8 +1448,8 @@ mod tests { overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); assert_eq!(overlay.current_index(), 1); let first_answer = &overlay.answers[0]; - assert_eq!(first_answer.committed_option_idx, Some(0)); - assert_eq!(first_answer.options_ui_state.selected_idx, Some(0)); + assert!(first_answer.answer_committed); + assert_eq!(first_answer.options_state.selected_idx, Some(0)); assert!(rx.try_recv().is_err()); overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); @@ -1122,6 +1461,27 @@ mod tests { assert_eq!(answer.answers, vec!["Option 1".to_string()]); } + #[test] + fn number_keys_select_and_submit_options() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event("turn-1", vec![question_with_options("q1", "Pick one")]), + tx, + true, + false, + false, + ); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('2'))); + + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { + panic!("expected UserInputAnswer"); + }; + let answer = response.answers.get("q1").expect("answer missing"); + assert_eq!(answer.answers, vec!["Option 2".to_string()]); + } + #[test] fn vim_keys_move_option_selection() { let (tx, _rx) = test_sender(); @@ -1133,15 +1493,15 @@ mod tests { false, ); let answer = overlay.current_answer().expect("answer missing"); - assert_eq!(answer.options_ui_state.selected_idx, Some(0)); + assert_eq!(answer.options_state.selected_idx, Some(0)); overlay.handle_key_event(KeyEvent::from(KeyCode::Char('j'))); let answer = overlay.current_answer().expect("answer missing"); - assert_eq!(answer.options_ui_state.selected_idx, Some(1)); + assert_eq!(answer.options_state.selected_idx, Some(1)); overlay.handle_key_event(KeyEvent::from(KeyCode::Char('k'))); let answer = overlay.current_answer().expect("answer missing"); - assert_eq!(answer.options_ui_state.selected_idx, Some(0)); + assert_eq!(answer.options_state.selected_idx, Some(0)); } #[test] @@ -1205,8 +1565,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(1); - answer.committed_option_idx = Some(1); + answer.options_state.selected_idx = Some(1); assert_eq!(overlay.notes_ui_visible(), false); overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); @@ -1234,9 +1593,7 @@ mod tests { assert!(matches!(overlay.focus, Focus::Notes)); overlay.move_question(true); - let answer = overlay.current_answer().expect("answer missing"); assert!(matches!(overlay.focus, Focus::Options)); - assert_eq!(answer.committed_option_idx, None); assert_eq!(overlay.notes_ui_visible(), false); } @@ -1264,17 +1621,20 @@ mod tests { overlay.move_question(true); - let answer = overlay.current_answer().expect("answer missing"); assert!(matches!(overlay.focus, Focus::Options)); assert_eq!(overlay.notes_ui_visible(), false); - assert_eq!(answer.committed_option_idx, None); + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + assert!(overlay.confirm_unanswered_active()); + overlay.handle_key_event(KeyEvent::from(KeyCode::Char('1'))); overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); let event = rx.try_recv().expect("expected AppEvent"); let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { panic!("expected UserInputAnswer"); }; + let answer = response.answers.get("q1").expect("answer missing"); + assert_eq!(answer.answers, Vec::::new()); let answer = response.answers.get("q2").expect("answer missing"); assert_eq!(answer.answers, vec!["Option 1".to_string()]); } @@ -1332,8 +1692,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); - answer.committed_option_idx = Some(0); + answer.options_state.selected_idx = Some(0); overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); overlay.handle_key_event(KeyEvent::from(KeyCode::Esc)); @@ -1357,8 +1716,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); - answer.committed_option_idx = Some(0); + answer.options_state.selected_idx = Some(0); overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); overlay.handle_key_event(KeyEvent::from(KeyCode::Char('a'))); @@ -1383,14 +1741,12 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(1); - answer.committed_option_idx = Some(1); + answer.options_state.selected_idx = Some(1); overlay.handle_key_event(KeyEvent::from(KeyCode::Backspace)); let answer = overlay.current_answer().expect("answer missing"); - assert_eq!(answer.committed_option_idx, None); - assert_eq!(answer.options_ui_state.selected_idx, None); + assert_eq!(answer.options_state.selected_idx, None); assert_eq!(overlay.notes_ui_visible(), false); assert!(rx.try_recv().is_err()); } @@ -1406,8 +1762,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); - answer.committed_option_idx = Some(0); + answer.options_state.selected_idx = Some(0); overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); assert!(matches!(overlay.focus, Focus::Notes)); @@ -1418,7 +1773,7 @@ mod tests { let answer = overlay.current_answer().expect("answer missing"); assert!(matches!(overlay.focus, Focus::Options)); assert_eq!(overlay.notes_ui_visible(), false); - assert_eq!(answer.committed_option_idx, Some(0)); + assert_eq!(answer.options_state.selected_idx, Some(0)); assert!(rx.try_recv().is_err()); } @@ -1433,8 +1788,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); - answer.committed_option_idx = Some(0); + answer.options_state.selected_idx = Some(0); overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); overlay @@ -1448,7 +1802,7 @@ mod tests { assert_eq!(overlay.notes_ui_visible(), false); assert_eq!(overlay.composer.current_text_with_pending(), ""); assert_eq!(answer.draft.text, ""); - assert_eq!(answer.committed_option_idx, Some(0)); + assert_eq!(answer.options_state.selected_idx, Some(0)); assert!(rx.try_recv().is_err()); } @@ -1477,7 +1831,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); + answer.options_state.selected_idx = Some(0); assert_eq!(overlay.unanswered_count(), 1); } @@ -1507,7 +1861,7 @@ mod tests { overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); - assert_eq!(overlay.answers[0].freeform_committed, true); + assert_eq!(overlay.answers[0].answer_committed, true); assert_eq!(overlay.unanswered_count(), 1); } @@ -1530,7 +1884,7 @@ mod tests { overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); - assert_eq!(overlay.answers[0].freeform_committed, false); + assert_eq!(overlay.answers[0].answer_committed, false); assert_eq!(overlay.unanswered_count(), 2); } @@ -1580,6 +1934,48 @@ mod tests { assert_eq!(answer.answers, Vec::::new()); } + #[test] + fn freeform_commit_resets_when_draft_changes() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_without_options("q1", "Notes"), + question_without_options("q2", "More"), + ], + ), + tx, + true, + false, + false, + ); + + overlay + .composer + .set_text_content("Committed".to_string(), Vec::new(), Vec::new()); + overlay.composer.move_cursor_to_end(); + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + assert_eq!(overlay.answers[0].answer_committed, true); + + overlay.move_question(false); + overlay + .composer + .set_text_content("Edited".to_string(), Vec::new(), Vec::new()); + overlay.composer.move_cursor_to_end(); + overlay.move_question(true); + assert_eq!(overlay.answers[0].answer_committed, false); + + overlay.submit_answers(); + + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { + panic!("expected UserInputAnswer"); + }; + let answer = response.answers.get("q1").expect("answer missing"); + assert_eq!(answer.answers, Vec::::new()); + } + #[test] fn notes_are_captured_for_selected_option() { let (tx, mut rx) = test_sender(); @@ -1593,13 +1989,18 @@ mod tests { { let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(1); + answer.options_state.selected_idx = Some(1); } - overlay.select_current_option(); + overlay.select_current_option(false); overlay .composer .set_text_content("Notes for option 2".to_string(), Vec::new(), Vec::new()); overlay.composer.move_cursor_to_end(); + let draft = overlay.capture_composer_draft(); + if let Some(answer) = overlay.current_answer_mut() { + answer.draft = draft; + answer.answer_committed = true; + } overlay.submit_answers(); @@ -1645,7 +2046,61 @@ mod tests { assert_eq!(overlay.current_index(), 1); let answer = overlay.answers.first().expect("answer missing"); - assert_eq!(answer.committed_option_idx, Some(1)); + assert_eq!(answer.options_state.selected_idx, Some(1)); + assert!(answer.answer_committed); + } + + #[test] + fn is_other_adds_none_of_the_above_and_submits_it() { + let (tx, mut rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![question_with_options_and_other("q1", "Pick one")], + ), + tx, + true, + false, + false, + ); + + let rows = overlay.option_rows(); + let other_row = rows.last().expect("expected none-of-the-above row"); + assert_eq!(other_row.name, " 4. None of the above"); + assert_eq!( + other_row.description.as_deref(), + Some(OTHER_OPTION_DESCRIPTION) + ); + + let other_idx = overlay.options_len().saturating_sub(1); + { + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_state.selected_idx = Some(other_idx); + } + overlay + .composer + .set_text_content("Custom answer".to_string(), Vec::new(), Vec::new()); + overlay.composer.move_cursor_to_end(); + let draft = overlay.capture_composer_draft(); + if let Some(answer) = overlay.current_answer_mut() { + answer.draft = draft; + answer.answer_committed = true; + } + + overlay.submit_answers(); + + let event = rx.try_recv().expect("expected AppEvent"); + let AppEvent::CodexOp(Op::UserInputAnswer { response, .. }) = event else { + panic!("expected UserInputAnswer"); + }; + let answer = response.answers.get("q1").expect("answer missing"); + assert_eq!( + answer.answers, + vec![ + OTHER_OPTION_LABEL.to_string(), + "user_note: Custom answer".to_string(), + ] + ); } #[test] @@ -1669,7 +2124,42 @@ mod tests { overlay.composer.handle_paste(large.clone()); overlay.move_question(true); - assert_eq!(overlay.answers[0].draft.text, large); + let draft = &overlay.answers[0].draft; + assert_eq!(draft.pending_pastes.len(), 1); + assert_eq!(draft.pending_pastes[0].1, large); + assert!(draft.text.contains(&draft.pending_pastes[0].0)); + assert_eq!(draft.text_with_pending(), large); + } + + #[test] + fn pending_paste_placeholder_survives_submission_and_back_navigation() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "First"), + question_with_options("q2", "Second"), + ], + ), + tx, + true, + false, + false, + ); + + let large = "x".repeat(1_200); + overlay.focus = Focus::Notes; + overlay.ensure_selected_for_notes(); + overlay.composer.handle_paste(large.clone()); + + overlay.handle_key_event(KeyEvent::from(KeyCode::Enter)); + overlay.handle_key_event(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL)); + + let draft = &overlay.answers[0].draft; + assert_eq!(draft.pending_pastes.len(), 1); + assert!(draft.text.contains(&draft.pending_pastes[0].0)); + assert_eq!(draft.text_with_pending(), large); } #[test] @@ -1701,8 +2191,7 @@ mod tests { ); { let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); - answer.committed_option_idx = Some(0); + answer.options_state.selected_idx = Some(0); } overlay.handle_key_event(KeyEvent::from(KeyCode::Tab)); @@ -1747,9 +2236,8 @@ mod tests { let width = 48u16; let question_height = overlay.wrapped_question_lines(width).len() as u16; let options_height = overlay.options_required_height(width); - let extras = 1u16 // header - .saturating_add(1) // progress - .saturating_add(DESIRED_SPACERS_WHEN_NOTES_HIDDEN) + let extras = 1u16 // progress + .saturating_add(DESIRED_SPACERS_BETWEEN_SECTIONS) .saturating_add(overlay.footer_required_height(width)); let height = question_height .saturating_add(options_height) @@ -1783,7 +2271,7 @@ mod tests { let question_bottom = sections.question_area.y + sections.question_area.height; let options_bottom = sections.options_area.y + sections.options_area.height; let spacer_after_question = sections.options_area.y.saturating_sub(question_bottom); - let spacer_after_options = sections.notes_title_area.y.saturating_sub(options_bottom); + let spacer_after_options = sections.notes_area.y.saturating_sub(options_bottom); assert_eq!(spacer_after_question, 1); assert_eq!(spacer_after_options, 1); } @@ -1805,8 +2293,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); - answer.committed_option_idx = Some(0); + answer.options_state.selected_idx = Some(0); let width = 36u16; let lines = overlay.footer_tip_lines(width); @@ -1842,8 +2329,7 @@ mod tests { { let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(0); - answer.committed_option_idx = Some(0); + answer.options_state.selected_idx = Some(0); } let width = 110u16; @@ -1877,8 +2363,7 @@ mod tests { false, ); let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(1); - answer.committed_option_idx = Some(1); + answer.options_state.selected_idx = Some(1); let width = 52u16; let height = overlay.desired_height(width); @@ -1931,8 +2416,7 @@ mod tests { ); { let answer = overlay.current_answer_mut().expect("answer missing"); - answer.options_ui_state.selected_idx = Some(3); - answer.committed_option_idx = Some(3); + answer.options_state.selected_idx = Some(3); } let area = Rect::new(0, 0, 120, 12); insta::assert_snapshot!( @@ -1941,6 +2425,57 @@ mod tests { ); } + #[test] + fn request_user_input_hidden_options_footer_snapshot() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![RequestUserInputQuestion { + id: "q1".to_string(), + header: "Next Step".to_string(), + question: "What would you like to do next?".to_string(), + is_other: false, + options: Some(vec![ + RequestUserInputQuestionOption { + label: "Discuss a code change (Recommended)".to_string(), + description: "Walk through a plan and edit code together.".to_string(), + }, + RequestUserInputQuestionOption { + label: "Run tests".to_string(), + description: "Pick a crate and run its tests.".to_string(), + }, + RequestUserInputQuestionOption { + label: "Review a diff".to_string(), + description: "Summarize or review current changes.".to_string(), + }, + RequestUserInputQuestionOption { + label: "Refactor".to_string(), + description: "Tighten structure and remove dead code.".to_string(), + }, + RequestUserInputQuestionOption { + label: "Ship it".to_string(), + description: "Finalize and open a PR.".to_string(), + }, + ]), + }], + ), + tx, + true, + false, + false, + ); + { + let answer = overlay.current_answer_mut().expect("answer missing"); + answer.options_state.selected_idx = Some(3); + } + let area = Rect::new(0, 0, 80, 10); + insta::assert_snapshot!( + "request_user_input_hidden_options_footer", + render_snapshot(&overlay, area) + ); + } + #[test] fn request_user_input_freeform_snapshot() { let (tx, _rx) = test_sender(); @@ -2005,6 +2540,32 @@ mod tests { ); } + #[test] + fn request_user_input_unanswered_confirmation_snapshot() { + let (tx, _rx) = test_sender(); + let mut overlay = RequestUserInputOverlay::new( + request_event( + "turn-1", + vec![ + question_with_options("q1", "Area"), + question_without_options("q2", "Goal"), + ], + ), + tx, + true, + false, + false, + ); + + overlay.open_unanswered_confirmation(); + + let area = Rect::new(0, 0, 80, 12); + insta::assert_snapshot!( + "request_user_input_unanswered_confirmation", + render_snapshot(&overlay, area) + ); + } + #[test] fn options_scroll_while_editing_notes() { let (tx, _rx) = test_sender(); @@ -2015,7 +2576,7 @@ mod tests { false, false, ); - overlay.select_current_option(); + overlay.select_current_option(false); overlay.focus = Focus::Notes; overlay .composer @@ -2025,7 +2586,7 @@ mod tests { overlay.handle_key_event(KeyEvent::from(KeyCode::Down)); let answer = overlay.current_answer().expect("answer missing"); - assert_eq!(answer.committed_option_idx, Some(0)); - assert_eq!(answer.options_ui_state.selected_idx, Some(1)); + assert_eq!(answer.options_state.selected_idx, Some(1)); + assert!(!answer.answer_committed); } } diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/render.rs b/codex-rs/tui/src/bottom_pane/request_user_input/render.rs index 0ab53fb841..b7433f8a6d 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/render.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/render.rs @@ -5,21 +5,64 @@ use ratatui::text::Line; use ratatui::text::Span; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; +use std::borrow::Cow; use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthStr; +use crate::bottom_pane::popup_consts::standard_popup_hint_line; +use crate::bottom_pane::scroll_state::ScrollState; +use crate::bottom_pane::selection_popup_common::measure_rows_height; use crate::bottom_pane::selection_popup_common::menu_surface_inset; use crate::bottom_pane::selection_popup_common::menu_surface_padding_height; use crate::bottom_pane::selection_popup_common::render_menu_surface; use crate::bottom_pane::selection_popup_common::render_rows; +use crate::bottom_pane::selection_popup_common::wrap_styled_line; use crate::render::renderable::Renderable; -use super::DESIRED_SPACERS_WHEN_NOTES_HIDDEN; +use super::DESIRED_SPACERS_BETWEEN_SECTIONS; use super::RequestUserInputOverlay; use super::TIP_SEPARATOR; +const MIN_OVERLAY_HEIGHT: usize = 8; +const PROGRESS_ROW_HEIGHT: usize = 1; +const SPACER_ROWS_WITH_NOTES: usize = 1; +const SPACER_ROWS_NO_OPTIONS: usize = 0; + +struct UnansweredConfirmationData { + title_line: Line<'static>, + subtitle_line: Line<'static>, + hint_line: Line<'static>, + rows: Vec, + state: ScrollState, +} + +struct UnansweredConfirmationLayout { + header_lines: Vec>, + hint_lines: Vec>, + rows: Vec, + state: ScrollState, +} + +fn line_to_owned(line: Line<'_>) -> Line<'static> { + Line { + style: line.style, + alignment: line.alignment, + spans: line + .spans + .into_iter() + .map(|span| Span { + style: span.style, + content: Cow::Owned(span.content.into_owned()), + }) + .collect(), + } +} + impl Renderable for RequestUserInputOverlay { fn desired_height(&self, width: u16) -> u16 { + if self.confirm_unanswered_active() { + return self.unanswered_confirmation_height(width); + } let outer = Rect::new(0, 0, width, u16::MAX); let inner = menu_surface_inset(outer); let inner_width = inner.width.max(1); @@ -36,26 +79,29 @@ impl Renderable for RequestUserInputOverlay { } else { 0 }; - let spacer_rows = if has_options && !notes_visible { - DESIRED_SPACERS_WHEN_NOTES_HIDDEN as usize + // When notes are visible, the composer already separates options from the footer. + // Without notes, we keep extra spacing so the footer hints don't crowd the options. + let spacer_rows = if has_options { + if notes_visible { + SPACER_ROWS_WITH_NOTES + } else { + DESIRED_SPACERS_BETWEEN_SECTIONS as usize + } } else { - 0 + SPACER_ROWS_NO_OPTIONS }; let footer_height = self.footer_required_height(inner_width) as usize; - // Tight minimum height: progress + header + question + (optional) titles/options + // Tight minimum height: progress + question + (optional) titles/options // + notes composer + footer + menu padding. let mut height = question_height .saturating_add(options_height) .saturating_add(spacer_rows) .saturating_add(notes_height) .saturating_add(footer_height) - .saturating_add(2); // progress + header - if has_options && notes_visible { - height = height.saturating_add(1); // notes title - } + .saturating_add(PROGRESS_ROW_HEIGHT); // progress height = height.saturating_add(menu_surface_padding_height() as usize); - height.max(8) as u16 + height.max(MIN_OVERLAY_HEIGHT) as u16 } fn render(&self, area: Rect, buf: &mut Buffer) { @@ -68,11 +114,145 @@ impl Renderable for RequestUserInputOverlay { } impl RequestUserInputOverlay { + fn unanswered_confirmation_data(&self) -> UnansweredConfirmationData { + let unanswered = self.unanswered_question_count(); + let subtitle = format!( + "{unanswered} unanswered question{}", + if unanswered == 1 { "" } else { "s" } + ); + UnansweredConfirmationData { + title_line: Line::from(super::UNANSWERED_CONFIRM_TITLE.bold()), + subtitle_line: Line::from(subtitle.dim()), + hint_line: standard_popup_hint_line(), + rows: self.unanswered_confirmation_rows(), + state: self.confirm_unanswered.unwrap_or_default(), + } + } + + fn unanswered_confirmation_layout(&self, width: u16) -> UnansweredConfirmationLayout { + let data = self.unanswered_confirmation_data(); + let content_width = width.max(1); + let mut header_lines = wrap_styled_line(&data.title_line, content_width); + let mut subtitle_lines = wrap_styled_line(&data.subtitle_line, content_width); + header_lines.append(&mut subtitle_lines); + let header_lines = header_lines.into_iter().map(line_to_owned).collect(); + let hint_lines = wrap_styled_line(&data.hint_line, content_width) + .into_iter() + .map(line_to_owned) + .collect(); + UnansweredConfirmationLayout { + header_lines, + hint_lines, + rows: data.rows, + state: data.state, + } + } + + fn unanswered_confirmation_height(&self, width: u16) -> u16 { + let outer = Rect::new(0, 0, width, u16::MAX); + let inner = menu_surface_inset(outer); + let inner_width = inner.width.max(1); + let layout = self.unanswered_confirmation_layout(inner_width); + let rows_height = measure_rows_height( + &layout.rows, + &layout.state, + layout.rows.len().max(1), + inner_width.max(1), + ); + let height = layout.header_lines.len() as u16 + + 1 + + rows_height + + 1 + + layout.hint_lines.len() as u16 + + menu_surface_padding_height(); + height.max(MIN_OVERLAY_HEIGHT as u16) + } + + fn render_unanswered_confirmation(&self, area: Rect, buf: &mut Buffer) { + let content_area = render_menu_surface(area, buf); + if content_area.width == 0 || content_area.height == 0 { + return; + } + let width = content_area.width.max(1); + let layout = self.unanswered_confirmation_layout(width); + + let mut cursor_y = content_area.y; + for line in layout.header_lines { + if cursor_y >= content_area.y + content_area.height { + return; + } + Paragraph::new(line).render( + Rect { + x: content_area.x, + y: cursor_y, + width: content_area.width, + height: 1, + }, + buf, + ); + cursor_y = cursor_y.saturating_add(1); + } + + if cursor_y < content_area.y + content_area.height { + cursor_y = cursor_y.saturating_add(1); + } + + let remaining = content_area + .height + .saturating_sub(cursor_y.saturating_sub(content_area.y)); + if remaining == 0 { + return; + } + + let hint_height = layout.hint_lines.len() as u16; + let spacer_before_hint = u16::from(remaining > hint_height); + let rows_height = remaining.saturating_sub(hint_height + spacer_before_hint); + + let rows_area = Rect { + x: content_area.x, + y: cursor_y, + width: content_area.width, + height: rows_height, + }; + render_rows( + rows_area, + buf, + &layout.rows, + &layout.state, + layout.rows.len().max(1), + "No choices", + ); + + cursor_y = cursor_y.saturating_add(rows_height); + if spacer_before_hint > 0 { + cursor_y = cursor_y.saturating_add(1); + } + for (offset, line) in layout.hint_lines.into_iter().enumerate() { + let y = cursor_y.saturating_add(offset as u16); + if y >= content_area.y + content_area.height { + break; + } + Paragraph::new(line).render( + Rect { + x: content_area.x, + y, + width: content_area.width, + height: 1, + }, + buf, + ); + } + } + /// Render the full request-user-input overlay. pub(super) fn render_ui(&self, area: Rect, buf: &mut Buffer) { if area.width == 0 || area.height == 0 { return; } + if self.confirm_unanswered_active() { + self.render_unanswered_confirmation(area, buf); + return; + } // Paint the same menu surface used by other bottom-pane overlays and // then render the overlay content inside its inset area. let content_area = render_menu_surface(area, buf); @@ -98,28 +278,22 @@ impl RequestUserInputOverlay { }; Paragraph::new(progress_line).render(sections.progress_area, buf); - // Question title and wrapped prompt text. - let question_header = self.current_question().map(|q| q.header.clone()); - let answered = self.current_question_answered(); - let header_line = if let Some(header) = question_header { - if answered { - Line::from(header.bold()) - } else { - Line::from(header.cyan().bold()) - } - } else { - Line::from("No questions".dim()) - }; - Paragraph::new(header_line).render(sections.header_area, buf); - + // Question prompt text. let question_y = sections.question_area.y; + let answered = + self.is_question_answered(self.current_index(), &self.composer.current_text()); for (offset, line) in sections.question_lines.iter().enumerate() { if question_y.saturating_add(offset as u16) >= sections.question_area.y + sections.question_area.height { break; } - Paragraph::new(Line::from(line.clone())).render( + let question_line = if answered { + Line::from(line.clone()) + } else { + Line::from(line.clone()).cyan() + }; + Paragraph::new(question_line).render( Rect { x: sections.question_area.x, y: question_y.saturating_add(offset as u16), @@ -134,48 +308,25 @@ impl RequestUserInputOverlay { let option_rows = self.option_rows(); if self.has_options() { - let mut options_ui_state = self + let mut options_state = self .current_answer() - .map(|answer| answer.options_ui_state) + .map(|answer| answer.options_state) .unwrap_or_default(); if sections.options_area.height > 0 { // Ensure the selected option is visible in the scroll window. - options_ui_state + options_state .ensure_visible(option_rows.len(), sections.options_area.height as usize); render_rows( sections.options_area, buf, &option_rows, - &options_ui_state, + &options_state, option_rows.len().max(1), "No options", ); } } - if notes_visible && sections.notes_title_area.height > 0 { - let notes_label = if self.has_options() - && self - .current_answer() - .is_some_and(|answer| answer.committed_option_idx.is_some()) - { - if let Some(label) = self.current_option_label() { - format!("Notes for {label}") - } else { - "Notes".to_string() - } - } else { - "Notes".to_string() - }; - let notes_active = self.focus_is_notes(); - let notes_title = if notes_active { - notes_label.as_str().cyan().bold() - } else { - notes_label.as_str().dim() - }; - Paragraph::new(Line::from(notes_title)).render(sections.notes_title_area, buf); - } - if notes_visible && sections.notes_area.height > 0 { self.render_notes_input(sections.notes_area, buf); } @@ -193,7 +344,17 @@ impl RequestUserInputOverlay { if footer_area.height == 0 { return; } - let tip_lines = self.footer_tip_lines(footer_area.width); + let options_hidden = self.has_options() + && sections.options_area.height > 0 + && self.options_required_height(content_area.width) > sections.options_area.height; + let option_tip = if options_hidden { + let selected = self.selected_option_index().unwrap_or(0).saturating_add(1); + let total = self.options_len(); + Some(super::FooterTip::new(format!("option {selected}/{total}"))) + } else { + None + }; + let tip_lines = self.footer_tip_lines_with_prefix(footer_area.width, option_tip); for (row_idx, tips) in tip_lines .into_iter() .take(footer_area.height as usize) @@ -224,6 +385,9 @@ impl RequestUserInputOverlay { /// Return the cursor position when editing notes, if visible. pub(super) fn cursor_pos_impl(&self, area: Rect) -> Option<(u16, u16)> { + if self.confirm_unanswered_active() { + return None; + } let has_options = self.has_options(); let notes_visible = self.notes_ui_visible(); diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap index 02f91a7b47..3fd7194648 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_footer_wrap.snap @@ -3,14 +3,12 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - Question 1/2 (1 unanswered) - Pick one + Question 1/2 (2 unanswered) Choose an option. - ( ) Option 1 First choice. - (x) Option 2 Second choice. - ( ) Option 3 Third choice. + 1. Option 1 First choice. + › 2. Option 2 Second choice. + 3. Option 3 Third choice. - Option 2 of 3 | ↑/↓ scroll | Tab: add notes - Enter: submit answer | Ctrl+n next - Esc: interrupt + tab to add notes | enter to submit answer + ctrl + n next question | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap index 3e947c015b..3ae7b9d624 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_freeform.snap @@ -4,10 +4,10 @@ expression: "render_snapshot(&overlay, area)" --- Question 1/1 (1 unanswered) - Goal Share details. › Type your answer (optional) - Enter: submit answer | Esc: interrupt + + enter to submit answer | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_hidden_options_footer.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_hidden_options_footer.snap new file mode 100644 index 0000000000..d643647f79 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_hidden_options_footer.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/request_user_input/mod.rs +expression: "render_snapshot(&overlay, area)" +--- + + Question 1/1 (1 unanswered) + What would you like to do next? + + 2. Run tests Pick a crate and run its tests. + 3. Review a diff Summarize or review current changes. + › 4. Refactor Tighten structure and remove dead code. + + option 4/5 | tab to add notes | enter to submit answer | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap index cdae6785d9..536e34dbba 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_first.snap @@ -4,11 +4,10 @@ expression: "render_snapshot(&overlay, area)" --- Question 1/2 (2 unanswered) - Area Choose an option. - ( ) Option 1 First choice. - ( ) Option 2 Second choice. - ( ) Option 3 Third choice. + › 1. Option 1 First choice. + 2. Option 2 Second choice. + 3. Option 3 Third choice. - Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Ctrl+n next | Esc: interrupt + tab to add notes | enter to submit answer | ctrl + n next question | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap index d007b6b43c..95507c3358 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_multi_question_last.snap @@ -4,7 +4,6 @@ expression: "render_snapshot(&overlay, area)" --- Question 2/2 (2 unanswered) - Goal Share details. › Type your answer (optional) @@ -12,4 +11,5 @@ expression: "render_snapshot(&overlay, area)" - Enter: submit all answers | Ctrl+n next | Esc: interrupt + + enter to submit all | ctrl + n first question | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap index 67eb6dc712..c93576246d 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options.snap @@ -4,11 +4,10 @@ expression: "render_snapshot(&overlay, area)" --- Question 1/1 (1 unanswered) - Area Choose an option. - ( ) Option 1 First choice. - ( ) Option 2 Second choice. - ( ) Option 3 Third choice. + › 1. Option 1 First choice. + 2. Option 2 Second choice. + 3. Option 3 Third choice. - Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt + tab to add notes | enter to submit answer | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap index 24799ed636..d9d219b627 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_options_notes_visible.snap @@ -3,17 +3,17 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - Question 1/1 - Area + Question 1/1 (1 unanswered) Choose an option. - (x) Option 1 First choice. - ( ) Option 2 Second choice. - ( ) Option 3 Third choice. - Notes for Option 1 + + › 1. Option 1 First choice. + 2. Option 2 Second choice. + 3. Option 3 Third choice. › Add notes - Option 1 of 3 | ↑/↓ scroll | Tab: clear notes | Enter: submit answer | Esc: interrupt + + tab to clear notes | enter to submit answer | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap index 95813336b2..2e8d120e44 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_scrolling_options.snap @@ -3,13 +3,13 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - Question 1/1 - Next Step + Question 1/1 (1 unanswered) What would you like to do next? - ( ) Discuss a code change (Recommended) Walk through a plan and edit code together. - ( ) Run tests Pick a crate and run its tests. - ( ) Review a diff Summarize or review current changes. - (x) Refactor Tighten structure and remove dead code. + 1. Discuss a code change (Recommended) Walk through a plan and edit code together. + 2. Run tests Pick a crate and run its tests. + 3. Review a diff Summarize or review current changes. + › 4. Refactor Tighten structure and remove dead code. + 5. Ship it Finalize and open a PR. - Option 4 of 5 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt + tab to add notes | enter to submit answer | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap index a963370be9..c93576246d 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_tight_height.snap @@ -4,10 +4,10 @@ expression: "render_snapshot(&overlay, area)" --- Question 1/1 (1 unanswered) - Area Choose an option. - ( ) Option 1 First choice. - ( ) Option 2 Second choice. + › 1. Option 1 First choice. + 2. Option 2 Second choice. + 3. Option 3 Third choice. - Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt + tab to add notes | enter to submit answer | esc to interrupt diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_unanswered_confirmation.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_unanswered_confirmation.snap new file mode 100644 index 0000000000..dd689c7267 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_unanswered_confirmation.snap @@ -0,0 +1,15 @@ +--- +source: tui/src/bottom_pane/request_user_input/mod.rs +expression: "render_snapshot(&overlay, area)" +--- + + Submit with unanswered questions? + 2 unanswered questions + + › 1. Proceed Submit with 2 unanswered questions. + 2. Go back Return to the first unanswered question. + + + + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap index 0d1e727422..71d32c5abf 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap +++ b/codex-rs/tui/src/bottom_pane/request_user_input/snapshots/codex_tui__bottom_pane__request_user_input__tests__request_user_input_wrapped_options.snap @@ -3,12 +3,11 @@ source: tui/src/bottom_pane/request_user_input/mod.rs expression: "render_snapshot(&overlay, area)" --- - Question 1/1 - Next Step + Question 1/1 (1 unanswered) Choose the next step for this task. - (x) Discuss a code change Walk through a plan, then implement it together with careful checks. - ( ) Run targeted tests Pick the most relevant crate and validate the current behavior first. - ( ) Review the diff Summarize the changes and highlight the most important risks and gaps. + › 1. Discuss a code change Walk through a plan, then implement it together with careful checks. + 2. Run targeted tests Pick the most relevant crate and validate the current behavior first. + 3. Review the diff Summarize the changes and highlight the most important risks and gaps. - Option 1 of 3 | ↑/↓ scroll | Tab: add notes | Enter: submit answer | Esc: interrupt + tab to add notes | enter to submit answer | esc to interrupt From ad5f9e7370311a281985e4f8d827eaaff0abd2fd Mon Sep 17 00:00:00 2001 From: zbarsky-openai Date: Wed, 28 Jan 2026 12:46:18 -0500 Subject: [PATCH 037/116] Upgrade to rust 1.93 (#10080) I needed to upgrade bazel one to get gnullvm artifacts and then noticed monorepo had drifted forward. They should move in lockstep. Also 1.93 already shipped so we can try that instead. --- .github/workflows/rust-ci.yml | 8 ++++---- .github/workflows/rust-release.yml | 2 +- .github/workflows/sdk.yml | 2 +- .github/workflows/shell-tool-mcp.yml | 2 +- MODULE.bazel | 2 +- codex-rs/rust-toolchain.toml | 2 +- codex-rs/scripts/setup-windows.ps1 | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index fc2ab5a043..7a2ef1f2df 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -59,7 +59,7 @@ jobs: working-directory: codex-rs steps: - uses: actions/checkout@v6 - - uses: dtolnay/rust-toolchain@1.92 + - uses: dtolnay/rust-toolchain@1.93 with: components: rustfmt - name: cargo fmt @@ -77,7 +77,7 @@ jobs: working-directory: codex-rs steps: - uses: actions/checkout@v6 - - uses: dtolnay/rust-toolchain@1.92 + - uses: dtolnay/rust-toolchain@1.93 - uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2 with: tool: cargo-shear @@ -186,7 +186,7 @@ jobs: sudo apt-get update -y sudo DEBIAN_FRONTEND=noninteractive apt-get install -y libubsan1 fi - - uses: dtolnay/rust-toolchain@1.92 + - uses: dtolnay/rust-toolchain@1.93 with: targets: ${{ matrix.target }} components: clippy @@ -510,7 +510,7 @@ jobs: - name: Install DotSlash uses: facebook/install-dotslash@v2 - - uses: dtolnay/rust-toolchain@1.92 + - uses: dtolnay/rust-toolchain@1.93 with: targets: ${{ matrix.target }} diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 7b8a4fe8a1..2f764df680 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -98,7 +98,7 @@ jobs: sudo apt-get update -y sudo DEBIAN_FRONTEND=noninteractive apt-get install -y libubsan1 fi - - uses: dtolnay/rust-toolchain@1.92 + - uses: dtolnay/rust-toolchain@1.93 with: targets: ${{ matrix.target }} diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml index f506dce6ba..60c14561ab 100644 --- a/.github/workflows/sdk.yml +++ b/.github/workflows/sdk.yml @@ -24,7 +24,7 @@ jobs: node-version: 22 cache: pnpm - - uses: dtolnay/rust-toolchain@1.92 + - uses: dtolnay/rust-toolchain@1.93 - name: build codex run: cargo build --bin codex diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 1f7bce1ccf..2ae60b3e15 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -93,7 +93,7 @@ jobs: - name: Checkout repository uses: actions/checkout@v6 - - uses: dtolnay/rust-toolchain@1.92 + - uses: dtolnay/rust-toolchain@1.93 with: targets: ${{ matrix.target }} diff --git a/MODULE.bazel b/MODULE.bazel index 87db7d1522..a6a7e2eab6 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -53,7 +53,7 @@ rust = use_extension("@rules_rust//rust:extensions.bzl", "rust") rust.toolchain( edition = "2024", extra_target_triples = RUST_TRIPLES, - versions = ["1.90.0"], + versions = ["1.93.0"], ) use_repo(rust, "rust_toolchains") diff --git a/codex-rs/rust-toolchain.toml b/codex-rs/rust-toolchain.toml index 05eeaac960..954b684895 100644 --- a/codex-rs/rust-toolchain.toml +++ b/codex-rs/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "1.92.0" +channel = "1.93.0" components = ["clippy", "rustfmt", "rust-src"] diff --git a/codex-rs/scripts/setup-windows.ps1 b/codex-rs/scripts/setup-windows.ps1 index 33b6b0c352..df87731380 100644 --- a/codex-rs/scripts/setup-windows.ps1 +++ b/codex-rs/scripts/setup-windows.ps1 @@ -179,7 +179,7 @@ if (-not (Ensure-Command 'cargo')) { Write-Host "==> Configuring Rust toolchain per rust-toolchain.toml" -ForegroundColor Cyan # Pin to the workspace toolchain and install components -$toolchain = '1.92.0' +$toolchain = '1.93.0' & rustup toolchain install $toolchain --profile minimal | Out-Host & rustup default $toolchain | Out-Host & rustup component add clippy rustfmt rust-src --toolchain $toolchain | Out-Host From 35e03a07166302f623fbf3b44be0ae79df9eab69 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 11:17:17 -0700 Subject: [PATCH 038/116] Update shell-tool-mcp.yml (#10095) ## Summary #10004 broke the builds for shell-tool-mcp.yml - we need to copy over the build configuration from there. ## Testing - [x] builds --- .github/workflows/shell-tool-mcp.yml | 64 ++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 2ae60b3e15..a0eae56b59 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -93,6 +93,16 @@ jobs: - name: Checkout repository uses: actions/checkout@v6 + - name: Install UBSan runtime (musl) + if: ${{ matrix.install_musl }} + shell: bash + run: | + set -euo pipefail + if command -v apt-get >/dev/null 2>&1; then + sudo apt-get update -y + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y libubsan1 + fi + - uses: dtolnay/rust-toolchain@1.93 with: targets: ${{ matrix.target }} @@ -109,6 +119,58 @@ jobs: TARGET: ${{ matrix.target }} run: bash "${GITHUB_WORKSPACE}/.github/scripts/install-musl-build-tools.sh" + - if: ${{ matrix.install_musl }} + name: Configure rustc UBSan wrapper (musl host) + shell: bash + run: | + set -euo pipefail + ubsan="" + if command -v ldconfig >/dev/null 2>&1; then + ubsan="$(ldconfig -p | grep -m1 'libubsan\.so\.1' | sed -E 's/.*=> (.*)$/\1/')" + fi + wrapper_root="${RUNNER_TEMP:-/tmp}" + wrapper="${wrapper_root}/rustc-ubsan-wrapper" + cat > "${wrapper}" <> "$GITHUB_ENV" + echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV" + + - if: ${{ matrix.install_musl }} + name: Clear sanitizer flags (musl) + shell: bash + run: | + set -euo pipefail + # Clear global Rust flags so host/proc-macro builds don't pull in UBSan. + echo "RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_ENCODED_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "RUSTDOCFLAGS=" >> "$GITHUB_ENV" + # Override any runner-level Cargo config rustflags as well. + echo "CARGO_BUILD_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" + echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" + + sanitize_flags() { + local input="$1" + input="${input//-fsanitize=undefined/}" + input="${input//-fno-sanitize-recover=undefined/}" + input="${input//-fno-sanitize-trap=undefined/}" + echo "$input" + } + + cflags="$(sanitize_flags "${CFLAGS-}")" + cxxflags="$(sanitize_flags "${CXXFLAGS-}")" + echo "CFLAGS=${cflags}" >> "$GITHUB_ENV" + echo "CXXFLAGS=${cxxflags}" >> "$GITHUB_ENV" + - name: Build exec server binaries run: cargo build --release --target ${{ matrix.target }} --bin codex-exec-mcp-server --bin codex-execve-wrapper @@ -282,6 +344,7 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: + version: 10.8.1 run_install: false - name: Setup Node.js @@ -377,6 +440,7 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: + version: 10.8.1 run_install: false - name: Setup Node.js From b8156706e65a1bce600dcb07d7eca0f8df9b1955 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Wed, 28 Jan 2026 10:54:43 -0800 Subject: [PATCH 039/116] file-search: improve file query perf (#9939) switch nucleo-matcher for nucleo and use a "file search session" w/ live updating query instead of a single hermetic run per query. --- codex-rs/Cargo.lock | 37 +- codex-rs/Cargo.toml | 3 +- .../tests/suite/fuzzy_file_search.rs | 19 +- codex-rs/core/src/rollout/list.rs | 3 +- codex-rs/file-search/Cargo.toml | 4 +- codex-rs/file-search/src/lib.rs | 945 +++++++++++++----- codex-rs/tui/src/app.rs | 4 +- codex-rs/tui/src/bottom_pane/chat_composer.rs | 31 +- .../tui/src/bottom_pane/file_search_popup.rs | 8 - codex-rs/tui/src/file_search.rs | 233 ++--- 10 files changed, 865 insertions(+), 422 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 38a86f1540..5d17acab98 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1572,11 +1572,13 @@ version = "0.0.0" dependencies = [ "anyhow", "clap", + "crossbeam-channel", "ignore", - "nucleo-matcher", + "nucleo", "pretty_assertions", "serde", "serde_json", + "tempfile", "tokio", ] @@ -4899,11 +4901,20 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "nucleo" +version = "0.5.0" +source = "git+https://github.com/helix-editor/nucleo.git?rev=4253de9faabb4e5c6d81d946a5e35a90f87347ee#4253de9faabb4e5c6d81d946a5e35a90f87347ee" +dependencies = [ + "nucleo-matcher", + "parking_lot", + "rayon", +] + [[package]] name = "nucleo-matcher" version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf33f538733d1a5a3494b836ba913207f14d9d4a1d3cd67030c5061bdd2cac85" +source = "git+https://github.com/helix-editor/nucleo.git?rev=4253de9faabb4e5c6d81d946a5e35a90f87347ee#4253de9faabb4e5c6d81d946a5e35a90f87347ee" dependencies = [ "memchr", "unicode-segmentation", @@ -6331,6 +6342,26 @@ dependencies = [ "ratatui", ] +[[package]] +name = "rayon" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "redox_syscall" version = "0.5.15" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index ae4eb768bc..9b0ce2e16d 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -128,6 +128,7 @@ clap = "4" clap_complete = "4" color-eyre = "0.6.3" crossterm = "0.28.1" +crossbeam-channel = "0.5.15" ctor = "0.6.3" derive_more = "2" diffy = "0.4.2" @@ -161,7 +162,7 @@ maplit = "1.0.2" mime_guess = "2.0.5" multimap = "0.10.0" notify = "8.2.0" -nucleo-matcher = "0.3.1" +nucleo = { git = "https://github.com/helix-editor/nucleo.git", rev = "4253de9faabb4e5c6d81d946a5e35a90f87347ee" } once_cell = "1.20.2" openssl-sys = "*" opentelemetry = "0.31.0" 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 9c95e3de34..87fdf39117 100644 --- a/codex-rs/app-server/tests/suite/fuzzy_file_search.rs +++ b/codex-rs/app-server/tests/suite/fuzzy_file_search.rs @@ -48,8 +48,7 @@ async fn test_fuzzy_file_search_sorts_and_includes_indices() -> Result<()> { .await??; let value = resp.result; - // The path separator on Windows affects the score. - let expected_score = if cfg!(windows) { 69 } else { 72 }; + let expected_score = 72; assert_eq!( value, @@ -59,16 +58,9 @@ async fn test_fuzzy_file_search_sorts_and_includes_indices() -> Result<()> { "root": root_path.clone(), "path": "abexy", "file_name": "abexy", - "score": 88, + "score": 84, "indices": [0, 1, 2], }, - { - "root": root_path.clone(), - "path": "abcde", - "file_name": "abcde", - "score": 74, - "indices": [0, 1, 4], - }, { "root": root_path.clone(), "path": sub_abce_rel, @@ -76,6 +68,13 @@ async fn test_fuzzy_file_search_sorts_and_includes_indices() -> Result<()> { "score": expected_score, "indices": [4, 5, 7], }, + { + "root": root_path.clone(), + "path": "abcde", + "file_name": "abcde", + "score": 71, + "indices": [0, 1, 4], + }, ] }) ); diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index 7469bbeb08..edff86606b 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -1,3 +1,4 @@ +use async_trait::async_trait; use std::cmp::Reverse; use std::ffi::OsStr; use std::io::{self}; @@ -7,8 +8,6 @@ use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; - -use async_trait::async_trait; use time::OffsetDateTime; use time::PrimitiveDateTime; use time::format_description::FormatItem; diff --git a/codex-rs/file-search/Cargo.toml b/codex-rs/file-search/Cargo.toml index 70ddcf2bb6..3802ed5fe3 100644 --- a/codex-rs/file-search/Cargo.toml +++ b/codex-rs/file-search/Cargo.toml @@ -15,11 +15,13 @@ path = "src/lib.rs" [dependencies] anyhow = { workspace = true } clap = { workspace = true, features = ["derive"] } +crossbeam-channel = { workspace = true } ignore = { workspace = true } -nucleo-matcher = { workspace = true } +nucleo = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } tokio = { workspace = true, features = ["full"] } [dev-dependencies] pretty_assertions = { workspace = true } +tempfile = { workspace = true } diff --git a/codex-rs/file-search/src/lib.rs b/codex-rs/file-search/src/lib.rs index d55eb929f3..39255fa36e 100644 --- a/codex-rs/file-search/src/lib.rs +++ b/codex-rs/file-search/src/lib.rs @@ -1,38 +1,54 @@ +use crossbeam_channel::Receiver; +use crossbeam_channel::Sender; +use crossbeam_channel::after; +use crossbeam_channel::never; +use crossbeam_channel::select; +use crossbeam_channel::unbounded; use ignore::WalkBuilder; use ignore::overrides::OverrideBuilder; -use nucleo_matcher::Matcher; -use nucleo_matcher::Utf32Str; -use nucleo_matcher::pattern::AtomKind; -use nucleo_matcher::pattern::CaseMatching; -use nucleo_matcher::pattern::Normalization; -use nucleo_matcher::pattern::Pattern; +use nucleo::Config; +use nucleo::Injector; +use nucleo::Matcher; +use nucleo::Nucleo; +use nucleo::Utf32String; +use nucleo::pattern::CaseMatching; +use nucleo::pattern::Normalization; use serde::Serialize; -use std::cell::UnsafeCell; -use std::cmp::Reverse; -use std::collections::BinaryHeap; use std::num::NonZero; use std::path::Path; +use std::path::PathBuf; use std::sync::Arc; +use std::sync::Condvar; +use std::sync::Mutex; +use std::sync::RwLock; use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; +use std::thread; +use std::time::Duration; use tokio::process::Command; +#[cfg(test)] +use nucleo::Utf32Str; +#[cfg(test)] +use nucleo::pattern::AtomKind; +#[cfg(test)] +use nucleo::pattern::Pattern; + mod cli; pub use cli::Cli; /// A single match result returned from the search. /// -/// * `score` – Relevance score returned by `nucleo_matcher`. +/// * `score` – Relevance score returned by `nucleo`. /// * `path` – Path to the matched file (relative to the search directory). /// * `indices` – Optional list of character indices that matched the query. /// These are only filled when the caller of [`run`] sets /// `compute_indices` to `true`. The indices vector follows the -/// guidance from `nucleo_matcher::Pattern::indices`: they are +/// guidance from `nucleo::pattern::Pattern::indices`: they are /// unique and sorted in ascending order so that callers can use /// them directly for highlighting. -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] pub struct FileMatch { pub score: u32, pub path: String, @@ -54,6 +70,127 @@ pub struct FileSearchResults { pub total_match_count: usize, } +#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)] +pub struct FileSearchSnapshot { + pub query: String, + pub matches: Vec, + pub total_match_count: usize, + pub scanned_file_count: usize, + pub walk_complete: bool, +} + +#[derive(Debug, Clone)] +pub struct SessionOptions { + pub limit: NonZero, + pub exclude: Vec, + pub threads: NonZero, + pub compute_indices: bool, + pub respect_gitignore: bool, +} + +impl Default for SessionOptions { + fn default() -> Self { + Self { + #[expect(clippy::unwrap_used)] + limit: NonZero::new(20).unwrap(), + exclude: Vec::new(), + #[expect(clippy::unwrap_used)] + threads: NonZero::new(2).unwrap(), + compute_indices: false, + respect_gitignore: true, + } + } +} + +pub trait SessionReporter: Send + Sync + 'static { + /// Called when the debounced top-N changes. + fn on_update(&self, snapshot: &FileSearchSnapshot); + + /// Called when the session becomes idle or is cancelled. Guaranteed to be called at least once per update_query. + fn on_complete(&self); +} + +pub struct FileSearchSession { + inner: Arc, +} + +impl FileSearchSession { + /// Update the query. This should be cheap relative to re-walking. + pub fn update_query(&self, pattern_text: &str) { + let _ = self + .inner + .work_tx + .send(WorkSignal::QueryUpdated(pattern_text.to_string())); + } +} + +impl Drop for FileSearchSession { + fn drop(&mut self) { + self.inner.shutdown.store(true, Ordering::Relaxed); + let _ = self.inner.work_tx.send(WorkSignal::Shutdown); + } +} + +pub fn create_session( + search_directory: &Path, + options: SessionOptions, + reporter: Arc, +) -> anyhow::Result { + create_session_inner(search_directory, options, reporter, None) +} + +fn create_session_inner( + search_directory: &Path, + options: SessionOptions, + reporter: Arc, + cancel_flag: Option>, +) -> anyhow::Result { + let SessionOptions { + limit, + exclude, + threads, + compute_indices, + respect_gitignore, + } = options; + + let override_matcher = build_override_matcher(search_directory, &exclude)?; + let (work_tx, work_rx) = unbounded(); + + let notify_tx = work_tx.clone(); + let notify = Arc::new(move || { + let _ = notify_tx.send(WorkSignal::NucleoNotify); + }); + let nucleo = Nucleo::new( + Config::DEFAULT.match_paths(), + notify, + Some(threads.get()), + 1, + ); + let injector = nucleo.injector(); + + let cancelled = cancel_flag.unwrap_or_else(|| Arc::new(AtomicBool::new(false))); + + let inner = Arc::new(SessionInner { + search_directory: search_directory.to_path_buf(), + limit: limit.get(), + threads: threads.get(), + compute_indices, + respect_gitignore, + cancelled: cancelled.clone(), + shutdown: Arc::new(AtomicBool::new(false)), + reporter, + work_tx: work_tx.clone(), + }); + + let matcher_inner = inner.clone(); + thread::spawn(move || matcher_worker(matcher_inner, work_rx, nucleo)); + + let walker_inner = inner.clone(); + thread::spawn(move || walker_worker(walker_inner, override_matcher, injector)); + + Ok(FileSearchSession { inner }) +} + pub trait Reporter { fn report_match(&self, file_match: &FileMatch); fn warn_matches_truncated(&self, total_match_count: usize, shown_match_count: usize); @@ -142,172 +279,31 @@ pub fn run( compute_indices: bool, respect_gitignore: bool, ) -> anyhow::Result { - let pattern = create_pattern(pattern_text); - // Create one BestMatchesList per worker thread so that each worker can - // operate independently. The results across threads will be merged when - // the traversal is complete. - let WorkerCount { - num_walk_builder_threads, - num_best_matches_lists, - } = create_worker_count(threads); - let best_matchers_per_worker: Vec> = (0..num_best_matches_lists) - .map(|_| { - UnsafeCell::new(BestMatchesList::new( - limit.get(), - pattern.clone(), - Matcher::new(nucleo_matcher::Config::DEFAULT), - )) - }) - .collect(); + let reporter = Arc::new(RunReporter::default()); + let session = create_session_inner( + search_directory, + SessionOptions { + limit, + exclude, + threads, + compute_indices, + respect_gitignore, + }, + reporter.clone(), + Some(cancel_flag), + )?; - // Use the same tree-walker library that ripgrep uses. We use it directly so - // that we can leverage the parallelism it provides. - let mut walk_builder = WalkBuilder::new(search_directory); - walk_builder - .threads(num_walk_builder_threads) - // Allow hidden entries. - .hidden(false) - // Follow symlinks to search their contents. - .follow_links(true) - // Don't require git to be present to apply to apply git-related ignore rules. - .require_git(false); - if !respect_gitignore { - walk_builder - .git_ignore(false) - .git_global(false) - .git_exclude(false) - .ignore(false) - .parents(false); - } - - if !exclude.is_empty() { - let mut override_builder = OverrideBuilder::new(search_directory); - for exclude in exclude { - // The `!` prefix is used to indicate an exclude pattern. - let exclude_pattern = format!("!{exclude}"); - override_builder.add(&exclude_pattern)?; - } - let override_matcher = override_builder.build()?; - walk_builder.overrides(override_matcher); - } - let walker = walk_builder.build_parallel(); - - // Each worker created by `WalkParallel::run()` will have its own - // `BestMatchesList` to update. - let index_counter = AtomicUsize::new(0); - walker.run(|| { - let index = index_counter.fetch_add(1, Ordering::Relaxed); - let best_list_ptr = best_matchers_per_worker[index].get(); - let best_list = unsafe { &mut *best_list_ptr }; - - // Each worker keeps a local counter so we only read the atomic flag - // every N entries which is cheaper than checking on every file. - const CHECK_INTERVAL: usize = 1024; - let mut processed = 0; - - let cancel = cancel_flag.clone(); - - Box::new(move |entry| { - if let Some(path) = get_file_path(&entry, search_directory) { - best_list.insert(path); - } - - processed += 1; - if processed % CHECK_INTERVAL == 0 && cancel.load(Ordering::Relaxed) { - ignore::WalkState::Quit - } else { - ignore::WalkState::Continue - } - }) - }); - - fn get_file_path<'a>( - entry_result: &'a Result, - search_directory: &std::path::Path, - ) -> Option<&'a str> { - let entry = match entry_result { - Ok(e) => e, - Err(_) => return None, - }; - if entry.file_type().is_some_and(|ft| ft.is_dir()) { - return None; - } - let path = entry.path(); - match path.strip_prefix(search_directory) { - Ok(rel_path) => rel_path.to_str(), - Err(_) => None, - } - } - - // If the cancel flag is set, we return early with an empty result. - if cancel_flag.load(Ordering::Relaxed) { - return Ok(FileSearchResults { - matches: Vec::new(), - total_match_count: 0, - }); - } - - // Merge results across best_matchers_per_worker. - let mut global_heap: BinaryHeap> = BinaryHeap::new(); - let mut total_match_count = 0; - for best_list_cell in best_matchers_per_worker.iter() { - let best_list = unsafe { &*best_list_cell.get() }; - total_match_count += best_list.num_matches; - for &Reverse((score, ref line)) in best_list.binary_heap.iter() { - if global_heap.len() < limit.get() { - global_heap.push(Reverse((score, line.clone()))); - } else if let Some(min_element) = global_heap.peek() - && score > min_element.0.0 - { - global_heap.pop(); - global_heap.push(Reverse((score, line.clone()))); - } - } - } - - let mut raw_matches: Vec<(u32, String)> = global_heap.into_iter().map(|r| r.0).collect(); - sort_matches(&mut raw_matches); - - // Transform into `FileMatch`, optionally computing indices. - let mut matcher = if compute_indices { - Some(Matcher::new(nucleo_matcher::Config::DEFAULT)) - } else { - None - }; - - let matches: Vec = raw_matches - .into_iter() - .map(|(score, path)| { - let indices = if compute_indices { - let mut buf = Vec::::new(); - let haystack: Utf32Str<'_> = Utf32Str::new(&path, &mut buf); - let mut idx_vec: Vec = Vec::new(); - if let Some(ref mut m) = matcher { - // Ignore the score returned from indices – we already have `score`. - pattern.indices(haystack, m, &mut idx_vec); - } - idx_vec.sort_unstable(); - idx_vec.dedup(); - Some(idx_vec) - } else { - None - }; - - FileMatch { - score, - path, - indices, - } - }) - .collect(); + session.update_query(pattern_text); + let snapshot = reporter.wait_for_complete(); Ok(FileSearchResults { - matches, - total_match_count, + matches: snapshot.matches, + total_match_count: snapshot.total_match_count, }) } /// Sort matches in-place by descending score, then ascending path. +#[cfg(test)] fn sort_matches(matches: &mut [(u32, String)]) { matches.sort_by(cmp_by_score_desc_then_path_asc::<(u32, String), _, _>( |t| t.0, @@ -332,73 +328,7 @@ where } } -/// Maintains the `max_count` best matches for a given pattern. -struct BestMatchesList { - max_count: usize, - num_matches: usize, - pattern: Pattern, - matcher: Matcher, - binary_heap: BinaryHeap>, - - /// Internal buffer for converting strings to UTF-32. - utf32buf: Vec, -} - -impl BestMatchesList { - fn new(max_count: usize, pattern: Pattern, matcher: Matcher) -> Self { - Self { - max_count, - num_matches: 0, - pattern, - matcher, - binary_heap: BinaryHeap::new(), - utf32buf: Vec::::new(), - } - } - - fn insert(&mut self, line: &str) { - let haystack: Utf32Str<'_> = Utf32Str::new(line, &mut self.utf32buf); - if let Some(score) = self.pattern.score(haystack, &mut self.matcher) { - // In the tests below, we verify that score() returns None for a - // non-match, so we can categorically increment the count here. - self.num_matches += 1; - - if self.binary_heap.len() < self.max_count { - self.binary_heap.push(Reverse((score, line.to_string()))); - } else if let Some(min_element) = self.binary_heap.peek() - && score > min_element.0.0 - { - self.binary_heap.pop(); - self.binary_heap.push(Reverse((score, line.to_string()))); - } - } - } -} - -struct WorkerCount { - num_walk_builder_threads: usize, - num_best_matches_lists: usize, -} - -fn create_worker_count(num_workers: NonZero) -> WorkerCount { - // It appears that the number of times the function passed to - // `WalkParallel::run()` is called is: the number of threads specified to - // the builder PLUS ONE. - // - // In `WalkParallel::visit()`, the builder function gets called once here: - // https://github.com/BurntSushi/ripgrep/blob/79cbe89deb1151e703f4d91b19af9cdcc128b765/crates/ignore/src/walk.rs#L1233 - // - // And then once for every worker here: - // https://github.com/BurntSushi/ripgrep/blob/79cbe89deb1151e703f4d91b19af9cdcc128b765/crates/ignore/src/walk.rs#L1288 - let num_walk_builder_threads = num_workers.get(); - let num_best_matches_lists = num_walk_builder_threads + 1; - - WorkerCount { - num_walk_builder_threads, - num_best_matches_lists, - } -} - +#[cfg(test)] fn create_pattern(pattern: &str) -> Pattern { Pattern::new( pattern, @@ -408,16 +338,281 @@ fn create_pattern(pattern: &str) -> Pattern { ) } +struct SessionInner { + search_directory: PathBuf, + limit: usize, + threads: usize, + compute_indices: bool, + respect_gitignore: bool, + cancelled: Arc, + shutdown: Arc, + reporter: Arc, + work_tx: Sender, +} + +enum WorkSignal { + QueryUpdated(String), + NucleoNotify, + WalkComplete, + Shutdown, +} + +fn build_override_matcher( + search_directory: &Path, + exclude: &[String], +) -> anyhow::Result> { + if exclude.is_empty() { + return Ok(None); + } + let mut override_builder = OverrideBuilder::new(search_directory); + for exclude in exclude { + let exclude_pattern = format!("!{exclude}"); + override_builder.add(&exclude_pattern)?; + } + let matcher = override_builder.build()?; + Ok(Some(matcher)) +} + +fn walker_worker( + inner: Arc, + override_matcher: Option, + injector: Injector>, +) { + let mut walk_builder = WalkBuilder::new(&inner.search_directory); + walk_builder + .threads(inner.threads) + // Allow hidden entries. + .hidden(false) + // Follow symlinks to search their contents. + .follow_links(true) + // Don't require git to be present to apply to apply git-related ignore rules. + .require_git(false); + if !inner.respect_gitignore { + walk_builder + .git_ignore(false) + .git_global(false) + .git_exclude(false) + .ignore(false) + .parents(false); + } + if let Some(override_matcher) = override_matcher { + walk_builder.overrides(override_matcher); + } + + let walker = walk_builder.build_parallel(); + + fn get_file_path<'a>( + entry_result: &'a Result, + search_directory: &Path, + ) -> Option<&'a str> { + let entry = match entry_result { + Ok(entry) => entry, + Err(_) => return None, + }; + if entry.file_type().is_some_and(|ft| ft.is_dir()) { + return None; + } + let path = entry.path(); + match path.strip_prefix(search_directory) { + Ok(rel_path) => rel_path.to_str(), + Err(_) => None, + } + } + + walker.run(|| { + const CHECK_INTERVAL: usize = 1024; + let mut n = 0; + let search_directory = inner.search_directory.clone(); + let injector = injector.clone(); + let cancelled = inner.cancelled.clone(); + let shutdown = inner.shutdown.clone(); + + Box::new(move |entry| { + if let Some(path) = get_file_path(&entry, &search_directory) { + injector.push(Arc::from(path), |path, cols| { + cols[0] = Utf32String::from(path.as_ref()); + }); + } + n += 1; + if n >= CHECK_INTERVAL { + if cancelled.load(Ordering::Relaxed) || shutdown.load(Ordering::Relaxed) { + return ignore::WalkState::Quit; + } + n = 0; + } + ignore::WalkState::Continue + }) + }); + let _ = inner.work_tx.send(WorkSignal::WalkComplete); +} + +fn matcher_worker( + inner: Arc, + work_rx: Receiver, + mut nucleo: Nucleo>, +) -> anyhow::Result<()> { + const TICK_TIMEOUT_MS: u64 = 10; + let config = Config::DEFAULT.match_paths(); + let mut indices_matcher = inner.compute_indices.then(|| Matcher::new(config.clone())); + let cancel_requested = || inner.cancelled.load(Ordering::Relaxed); + let shutdown_requested = || inner.shutdown.load(Ordering::Relaxed); + + let mut last_query = String::new(); + let mut next_notify = never(); + let mut will_notify = false; + let mut walk_complete = false; + + loop { + select! { + recv(work_rx) -> signal => { + let Ok(signal) = signal else { + break; + }; + match signal { + WorkSignal::QueryUpdated(query) => { + let append = query.starts_with(&last_query); + nucleo.pattern.reparse( + 0, + &query, + CaseMatching::Smart, + Normalization::Smart, + append, + ); + last_query = query; + will_notify = true; + next_notify = after(Duration::from_millis(0)); + } + WorkSignal::NucleoNotify => { + if !will_notify { + will_notify = true; + next_notify = after(Duration::from_millis(TICK_TIMEOUT_MS)); + } + } + WorkSignal::WalkComplete => { + walk_complete = true; + if !will_notify { + will_notify = true; + next_notify = after(Duration::from_millis(0)); + } + } + WorkSignal::Shutdown => { + break; + } + } + } + recv(next_notify) -> _ => { + will_notify = false; + let status = nucleo.tick(TICK_TIMEOUT_MS); + if status.changed { + let snapshot = nucleo.snapshot(); + let limit = inner.limit.min(snapshot.matched_item_count() as usize); + let pattern = snapshot.pattern().column_pattern(0); + let matches: Vec<_> = snapshot + .matches() + .iter() + .take(limit) + .filter_map(|match_| { + let item = snapshot.get_item(match_.idx)?; + let indices = if let Some(indices_matcher) = indices_matcher.as_mut() { + let mut idx_vec = Vec::::new(); + let haystack = item.matcher_columns[0].slice(..); + let _ = pattern.indices(haystack, indices_matcher, &mut idx_vec); + idx_vec.sort_unstable(); + idx_vec.dedup(); + Some(idx_vec) + } else { + None + }; + Some(FileMatch { + score: match_.score, + path: item.data.as_ref().to_string(), + indices, + }) + }) + .collect(); + + let snapshot = FileSearchSnapshot { + query: last_query.clone(), + matches, + total_match_count: snapshot.matched_item_count() as usize, + scanned_file_count: snapshot.item_count() as usize, + walk_complete, + }; + inner.reporter.on_update(&snapshot); + } + if !status.running && walk_complete { + inner.reporter.on_complete(); + } + } + default(Duration::from_millis(100)) => { + // Occasionally check the cancel flag. + } + } + + if cancel_requested() || shutdown_requested() { + break; + } + } + + // If we cancelled or otherwise exited the loop, make sure the reporter is notified. + inner.reporter.on_complete(); + + Ok(()) +} + +#[derive(Default)] +struct RunReporter { + snapshot: RwLock, + completed: (Condvar, Mutex), +} + +impl SessionReporter for RunReporter { + fn on_update(&self, snapshot: &FileSearchSnapshot) { + #[expect(clippy::unwrap_used)] + let mut guard = self.snapshot.write().unwrap(); + *guard = snapshot.clone(); + } + + fn on_complete(&self) { + let (cv, mutex) = &self.completed; + let mut completed = mutex.lock().unwrap(); + *completed = true; + cv.notify_all(); + } +} + +impl RunReporter { + fn wait_for_complete(&self) -> FileSearchSnapshot { + let (cv, mutex) = &self.completed; + let mut completed = mutex.lock().unwrap(); + while !*completed { + completed = cv.wait(completed).unwrap(); + } + self.snapshot.read().unwrap().clone() + } +} + #[cfg(test)] mod tests { + #![allow(clippy::unwrap_used)] + use super::*; use pretty_assertions::assert_eq; + use std::fs; + use std::sync::Arc; + use std::sync::Condvar; + use std::sync::Mutex; + use std::sync::atomic::AtomicBool; + use std::thread; + use std::time::Duration; + use std::time::Instant; + use tempfile::TempDir; #[test] fn verify_score_is_none_for_non_match() { let mut utf32buf = Vec::::new(); let line = "hello"; - let mut matcher = Matcher::new(nucleo_matcher::Config::DEFAULT); + let mut matcher = Matcher::new(Config::DEFAULT); let haystack: Utf32Str<'_> = Utf32Str::new(line, &mut utf32buf); let pattern = create_pattern("zzz"); let score = pattern.score(haystack, &mut matcher); @@ -453,4 +648,274 @@ mod tests { fn file_name_from_path_falls_back_to_full_path() { assert_eq!(file_name_from_path(""), ""); } + + #[derive(Default)] + struct RecordingReporter { + updates: Mutex>, + complete_times: Mutex>, + complete_cv: Condvar, + update_cv: Condvar, + } + + impl RecordingReporter { + fn wait_for_complete(&self, timeout: Duration) -> bool { + let completes = self.complete_times.lock().unwrap(); + if !completes.is_empty() { + return true; + } + let (completes, _) = self.complete_cv.wait_timeout(completes, timeout).unwrap(); + !completes.is_empty() + } + fn clear(&self) { + self.updates.lock().unwrap().clear(); + self.complete_times.lock().unwrap().clear(); + } + + fn updates(&self) -> Vec { + self.updates.lock().unwrap().clone() + } + + fn wait_for_updates_at_least(&self, min_len: usize, timeout: Duration) -> bool { + let updates = self.updates.lock().unwrap(); + if updates.len() >= min_len { + return true; + } + let (updates, _) = self.update_cv.wait_timeout(updates, timeout).unwrap(); + updates.len() >= min_len + } + + fn snapshot(&self) -> FileSearchSnapshot { + self.updates + .lock() + .unwrap() + .last() + .cloned() + .unwrap_or_default() + } + } + + impl SessionReporter for RecordingReporter { + fn on_update(&self, snapshot: &FileSearchSnapshot) { + let mut updates = self.updates.lock().unwrap(); + updates.push(snapshot.clone()); + self.update_cv.notify_all(); + } + + fn on_complete(&self) { + { + let mut complete_times = self.complete_times.lock().unwrap(); + complete_times.push(Instant::now()); + } + self.complete_cv.notify_all(); + } + } + + fn create_temp_tree(file_count: usize) -> TempDir { + let dir = tempfile::tempdir().unwrap(); + for i in 0..file_count { + let path = dir.path().join(format!("file-{i:04}.txt")); + fs::write(path, format!("contents {i}")).unwrap(); + } + dir + } + + #[test] + fn session_scanned_file_count_is_monotonic_across_queries() { + let dir = create_temp_tree(200); + let reporter = Arc::new(RecordingReporter::default()); + let session = create_session(dir.path(), SessionOptions::default(), reporter.clone()) + .expect("session"); + + session.update_query("file-00"); + thread::sleep(Duration::from_millis(20)); + let first_snapshot = reporter.snapshot(); + session.update_query("file-01"); + thread::sleep(Duration::from_millis(20)); + let second_snapshot = reporter.snapshot(); + let _ = reporter.wait_for_complete(Duration::from_secs(5)); + let completed_snapshot = reporter.snapshot(); + + assert!(second_snapshot.scanned_file_count >= first_snapshot.scanned_file_count); + assert!(completed_snapshot.scanned_file_count >= second_snapshot.scanned_file_count); + } + + #[test] + fn session_streams_updates_before_walk_complete() { + let dir = create_temp_tree(600); + let reporter = Arc::new(RecordingReporter::default()); + let session = create_session(dir.path(), SessionOptions::default(), reporter.clone()) + .expect("session"); + + session.update_query("file-0"); + let completed = reporter.wait_for_complete(Duration::from_secs(5)); + + assert!(completed); + let updates = reporter.updates(); + assert!(updates.iter().any(|snapshot| !snapshot.walk_complete)); + } + + #[test] + fn session_accepts_query_updates_after_walk_complete() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join("alpha.txt"), "alpha").unwrap(); + fs::write(dir.path().join("beta.txt"), "beta").unwrap(); + let reporter = Arc::new(RecordingReporter::default()); + let session = create_session(dir.path(), SessionOptions::default(), reporter.clone()) + .expect("session"); + + session.update_query("alpha"); + assert!(reporter.wait_for_complete(Duration::from_secs(5))); + let updates_before = reporter.updates().len(); + + session.update_query("beta"); + assert!(reporter.wait_for_updates_at_least(updates_before + 1, Duration::from_secs(5),)); + + let updates = reporter.updates(); + let last_update = updates.last().cloned().expect("update"); + assert!( + last_update + .matches + .iter() + .any(|file_match| file_match.path.contains("beta.txt")) + ); + } + + #[test] + fn session_emits_complete_when_query_changes_with_no_matches() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join("alpha.txt"), "alpha").unwrap(); + fs::write(dir.path().join("beta.txt"), "beta").unwrap(); + let reporter = Arc::new(RecordingReporter::default()); + let session = create_session_inner( + dir.path(), + SessionOptions::default(), + reporter.clone(), + None, + ) + .expect("session"); + + session.update_query("asdf"); + assert!(reporter.wait_for_complete(Duration::from_secs(5))); + + let completed_snapshot = reporter.snapshot(); + assert_eq!(completed_snapshot.matches, Vec::new()); + assert_eq!(completed_snapshot.total_match_count, 0); + + reporter.clear(); + + session.update_query("asdfa"); + assert!(reporter.wait_for_complete(Duration::from_secs(5))); + assert!(!reporter.updates().is_empty()); + } + + #[test] + fn dropping_session_does_not_cancel_siblings_with_shared_cancel_flag() { + let root_a = create_temp_tree(200); + let root_b = create_temp_tree(4_000); + let cancel_flag = Arc::new(AtomicBool::new(false)); + + let reporter_a = Arc::new(RecordingReporter::default()); + let session_a = create_session_inner( + root_a.path(), + SessionOptions::default(), + reporter_a, + Some(cancel_flag.clone()), + ) + .expect("session_a"); + + let reporter_b = Arc::new(RecordingReporter::default()); + let session_b = create_session_inner( + root_b.path(), + SessionOptions::default(), + reporter_b.clone(), + Some(cancel_flag), + ) + .expect("session_b"); + + session_a.update_query("file-0"); + session_b.update_query("file-1"); + + thread::sleep(Duration::from_millis(5)); + drop(session_a); + + let completed = reporter_b.wait_for_complete(Duration::from_secs(5)); + assert_eq!(completed, true); + } + + #[test] + fn session_emits_updates_when_query_changes() { + let dir = create_temp_tree(200); + let reporter = Arc::new(RecordingReporter::default()); + let session = create_session(dir.path(), SessionOptions::default(), reporter.clone()) + .expect("session"); + + session.update_query("zzzzzzzz"); + let completed = reporter.wait_for_complete(Duration::from_secs(5)); + assert!(completed); + + reporter.clear(); + + session.update_query("zzzzzzzzq"); + let completed = reporter.wait_for_complete(Duration::from_secs(5)); + assert!(completed); + + let updates = reporter.updates(); + assert_eq!(updates.len(), 1); + } + + #[test] + fn run_returns_matches_for_query() { + let dir = create_temp_tree(40); + let results = run( + "file-000", + NonZero::new(20).unwrap(), + dir.path(), + Vec::new(), + NonZero::new(2).unwrap(), + Arc::new(AtomicBool::new(false)), + false, + true, + ) + .expect("run ok"); + + assert!(!results.matches.is_empty()); + assert!(results.total_match_count >= results.matches.len()); + assert!( + results + .matches + .iter() + .any(|m| m.path.contains("file-0000.txt")) + ); + } + + #[test] + fn cancel_exits_run() { + let dir = create_temp_tree(200); + let cancel_flag = Arc::new(AtomicBool::new(true)); + let search_dir = dir.path().to_path_buf(); + let (tx, rx) = std::sync::mpsc::channel(); + + let handle = thread::spawn(move || { + let result = run( + "file-", + NonZero::new(20).unwrap(), + &search_dir, + Vec::new(), + NonZero::new(2).unwrap(), + cancel_flag, + false, + true, + ); + let _ = tx.send(result); + }); + + let result = rx + .recv_timeout(Duration::from_secs(2)) + .expect("run should exit after cancellation"); + handle.join().unwrap(); + + let results = result.expect("run ok"); + assert_eq!(results.matches, Vec::new()); + assert_eq!(results.total_match_count, 0); + } } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 4e9cfb3fcd..bf4ab6798e 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1507,9 +1507,7 @@ impl App { tui.frame_requester().schedule_frame(); } AppEvent::StartFileSearch(query) => { - if !query.is_empty() { - self.file_search.on_user_query(query); - } + self.file_search.on_user_query(query); } AppEvent::FileSearchResult { query, matches } => { self.chat_widget.apply_file_search_result(query, matches); diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 4c1228cb3c..3a3f5d407b 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -2380,6 +2380,11 @@ impl ChatComposer { // When browsing input history (shell-style Up/Down recall), skip all popup // synchronization so nothing steals focus from continued history navigation. if browsing_history { + if self.current_file_query.is_some() { + self.app_event_tx + .send(AppEvent::StartFileSearch(String::new())); + self.current_file_query = None; + } self.active_popup = ActivePopup::None; return; } @@ -2390,12 +2395,22 @@ impl ChatComposer { self.sync_command_popup(allow_command_popup); if matches!(self.active_popup, ActivePopup::Command(_)) { + if self.current_file_query.is_some() { + self.app_event_tx + .send(AppEvent::StartFileSearch(String::new())); + self.current_file_query = None; + } self.dismissed_file_popup_token = None; self.dismissed_skill_popup_token = None; return; } if let Some(token) = skill_token { + if self.current_file_query.is_some() { + self.app_event_tx + .send(AppEvent::StartFileSearch(String::new())); + self.current_file_query = None; + } self.sync_skill_popup(token); return; } @@ -2406,6 +2421,11 @@ impl ChatComposer { return; } + if self.current_file_query.is_some() { + self.app_event_tx + .send(AppEvent::StartFileSearch(String::new())); + self.current_file_query = None; + } self.dismissed_file_popup_token = None; if matches!( self.active_popup, @@ -2539,7 +2559,10 @@ impl ChatComposer { return; } - if !query.is_empty() { + if query.is_empty() { + self.app_event_tx + .send(AppEvent::StartFileSearch(String::new())); + } else { self.app_event_tx .send(AppEvent::StartFileSearch(query.clone())); } @@ -2563,7 +2586,11 @@ impl ChatComposer { } } - self.current_file_query = Some(query); + if query.is_empty() { + self.current_file_query = None; + } else { + self.current_file_query = Some(query); + } self.dismissed_file_popup_token = None; } diff --git a/codex-rs/tui/src/bottom_pane/file_search_popup.rs b/codex-rs/tui/src/bottom_pane/file_search_popup.rs index e0a0cc2f49..e018c7ff8a 100644 --- a/codex-rs/tui/src/bottom_pane/file_search_popup.rs +++ b/codex-rs/tui/src/bottom_pane/file_search_popup.rs @@ -43,18 +43,10 @@ impl FileSearchPopup { return; } - // Determine if current matches are still relevant. - let keep_existing = query.starts_with(&self.display_query); - self.pending_query.clear(); self.pending_query.push_str(query); self.waiting = true; // waiting for new results - - if !keep_existing { - self.matches.clear(); - self.state.reset(); - } } /// Put the popup into an "idle" state used for an empty query (just "@"). diff --git a/codex-rs/tui/src/file_search.rs b/codex-rs/tui/src/file_search.rs index af46512640..88c56f2316 100644 --- a/codex-rs/tui/src/file_search.rs +++ b/codex-rs/tui/src/file_search.rs @@ -1,32 +1,15 @@ -//! Helper that owns the debounce/cancellation logic for `@` file searches. +//! Session-based orchestration for `@` file searches. //! -//! `ChatComposer` publishes *every* change of the `@token` as -//! `AppEvent::StartFileSearch(query)`. -//! This struct receives those events and decides when to actually spawn the -//! expensive search (handled in the main `App` thread). It tries to ensure: -//! -//! - Even when the user types long text quickly, they will start seeing results -//! after a short delay using an early version of what they typed. -//! - At most one search is in-flight at any time. -//! -//! It works as follows: -//! -//! 1. First query starts a debounce timer. -//! 2. While the timer is pending, the latest query from the user is stored. -//! 3. When the timer fires, it is cleared, and a search is done for the most -//! recent query. -//! 4. If there is a in-flight search that is not a prefix of the latest thing -//! the user typed, it is cancelled. +//! `ChatComposer` publishes every change of the `@token` as +//! `AppEvent::StartFileSearch(query)`. This manager owns a single +//! `codex-file-search` session for the current search root, updates the query +//! on every keystroke, and drops the session when the query becomes empty. use codex_file_search as file_search; use std::num::NonZeroUsize; use std::path::PathBuf; use std::sync::Arc; use std::sync::Mutex; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use std::thread; -use std::time::Duration; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; @@ -34,35 +17,16 @@ use crate::app_event_sender::AppEventSender; const MAX_FILE_SEARCH_RESULTS: NonZeroUsize = NonZeroUsize::new(20).unwrap(); const NUM_FILE_SEARCH_THREADS: NonZeroUsize = NonZeroUsize::new(2).unwrap(); -/// How long to wait after a keystroke before firing the first search when none -/// is currently running. Keeps early queries more meaningful. -const FILE_SEARCH_DEBOUNCE: Duration = Duration::from_millis(100); - -const ACTIVE_SEARCH_COMPLETE_POLL_INTERVAL: Duration = Duration::from_millis(20); - -/// State machine for file-search orchestration. pub(crate) struct FileSearchManager { - /// Unified state guarded by one mutex. state: Arc>, - search_dir: PathBuf, app_tx: AppEventSender, } struct SearchState { - /// Latest query typed by user (updated every keystroke). latest_query: String, - - /// true if a search is currently scheduled. - is_search_scheduled: bool, - - /// If there is an active search, this will be the query being searched. - active_search: Option, -} - -struct ActiveSearch { - query: String, - cancellation_token: Arc, + session: Option, + session_token: usize, } impl FileSearchManager { @@ -70,8 +34,8 @@ impl FileSearchManager { Self { state: Arc::new(Mutex::new(SearchState { latest_query: String::new(), - is_search_scheduled: false, - active_search: None, + session: None, + session_token: 0, })), search_dir, app_tx: tx, @@ -80,120 +44,85 @@ impl FileSearchManager { /// Call whenever the user edits the `@` token. pub fn on_user_query(&self, query: String) { - { - #[expect(clippy::unwrap_used)] - let mut st = self.state.lock().unwrap(); - if query == st.latest_query { - // No change, nothing to do. - return; - } + #[expect(clippy::unwrap_used)] + let mut st = self.state.lock().unwrap(); + if query == st.latest_query { + return; + } + st.latest_query.clear(); + st.latest_query.push_str(&query); - // Update latest query. - st.latest_query.clear(); - st.latest_query.push_str(&query); - - // If there is an in-flight search that is definitely obsolete, - // cancel it now. - if let Some(active_search) = &st.active_search - && !query.starts_with(&active_search.query) - { - active_search - .cancellation_token - .store(true, Ordering::Relaxed); - st.active_search = None; - } - - // Schedule a search to run after debounce. - if !st.is_search_scheduled { - st.is_search_scheduled = true; - } else { - return; - } + if query.is_empty() { + st.session.take(); + return; } - // If we are here, we set `st.is_search_scheduled = true` before - // dropping the lock. This means we are the only thread that can spawn a - // debounce timer. - let state = self.state.clone(); - let search_dir = self.search_dir.clone(); - let tx_clone = self.app_tx.clone(); - thread::spawn(move || { - // Always do a minimum debounce, but then poll until the - // `active_search` is cleared. - thread::sleep(FILE_SEARCH_DEBOUNCE); - loop { - #[expect(clippy::unwrap_used)] - if state.lock().unwrap().active_search.is_none() { - break; - } - thread::sleep(ACTIVE_SEARCH_COMPLETE_POLL_INTERVAL); - } - - // The debounce timer has expired, so start a search using the - // latest query. - let cancellation_token = Arc::new(AtomicBool::new(false)); - let token = cancellation_token.clone(); - let query = { - #[expect(clippy::unwrap_used)] - let mut st = state.lock().unwrap(); - let query = st.latest_query.clone(); - st.is_search_scheduled = false; - st.active_search = Some(ActiveSearch { - query: query.clone(), - cancellation_token: token, - }); - query - }; - - FileSearchManager::spawn_file_search( - query, - search_dir, - tx_clone, - cancellation_token, - state, - ); - }); + if st.session.is_none() { + self.start_session_locked(&mut st); + } + if let Some(session) = st.session.as_ref() { + session.update_query(&query); + } } - fn spawn_file_search( - query: String, - search_dir: PathBuf, - tx: AppEventSender, - cancellation_token: Arc, - search_state: Arc>, - ) { - let compute_indices = true; - std::thread::spawn(move || { - let matches = file_search::run( - &query, - MAX_FILE_SEARCH_RESULTS, - &search_dir, - Vec::new(), - NUM_FILE_SEARCH_THREADS, - cancellation_token.clone(), - compute_indices, - true, - ) - .map(|res| res.matches) - .unwrap_or_default(); - - let is_cancelled = cancellation_token.load(Ordering::Relaxed); - if !is_cancelled { - tx.send(AppEvent::FileSearchResult { query, matches }); + fn start_session_locked(&self, st: &mut SearchState) { + st.session_token = st.session_token.wrapping_add(1); + let session_token = st.session_token; + let reporter = Arc::new(TuiSessionReporter { + state: self.state.clone(), + app_tx: self.app_tx.clone(), + session_token, + }); + let session = file_search::create_session( + &self.search_dir, + file_search::SessionOptions { + limit: MAX_FILE_SEARCH_RESULTS, + exclude: Vec::new(), + threads: NUM_FILE_SEARCH_THREADS, + compute_indices: true, + respect_gitignore: true, + }, + reporter, + ); + match session { + Ok(session) => st.session = Some(session), + Err(err) => { + tracing::warn!("file search session failed to start: {err}"); + st.session = None; } + } + } +} - // Reset the active search state. Do a pointer comparison to verify - // that we are clearing the ActiveSearch that corresponds to the - // cancellation token we were given. - { - #[expect(clippy::unwrap_used)] - let mut st = search_state.lock().unwrap(); - if let Some(active_search) = &st.active_search - && Arc::ptr_eq(&active_search.cancellation_token, &cancellation_token) - { - st.active_search = None; - } - } +struct TuiSessionReporter { + state: Arc>, + app_tx: AppEventSender, + session_token: usize, +} + +impl TuiSessionReporter { + fn send_snapshot(&self, snapshot: &file_search::FileSearchSnapshot) { + #[expect(clippy::unwrap_used)] + let st = self.state.lock().unwrap(); + if st.session_token != self.session_token + || st.latest_query.is_empty() + || snapshot.query.is_empty() + { + return; + } + let query = snapshot.query.clone(); + drop(st); + self.app_tx.send(AppEvent::FileSearchResult { + query, + matches: snapshot.matches.clone(), }); } } + +impl file_search::SessionReporter for TuiSessionReporter { + fn on_update(&self, snapshot: &file_search::FileSearchSnapshot) { + self.send_snapshot(snapshot); + } + + fn on_complete(&self) {} +} From 851617ff5a34570b7fbe2ac2a2c417ea1d3ae8f8 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Wed, 28 Jan 2026 10:55:57 -0800 Subject: [PATCH 040/116] chore: deprecate old web search feature flags (#10097) deprecate all old web search flags and aliases, including: - `[features].web_search_request` and `[features].web_search_cached` - `[tools].web_search` - `[features].web_search` slightly rework `legacy_usages` to enable pointing to non-features from deprecated features; we need to point to `web_search` (not under `[features]`) from things like `[features].web_search_cached` and `[features].web_search_request`. Added integration tests to confirm deprecation notice is shown on explicit enablement and disablement of deprecated flags. --- codex-rs/core/src/codex.rs | 16 ++--- codex-rs/core/src/features.rs | 66 +++++++++++++++-- .../core/tests/suite/deprecation_notice.rs | 71 +++++++++++++++++++ 3 files changed, 136 insertions(+), 17 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index e21eff9749..c251805272 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -765,19 +765,13 @@ impl Session { let mut post_session_configured_events = Vec::::new(); - for (alias, feature) in config.features.legacy_feature_usages() { - let canonical = feature.key(); - let summary = format!("`{alias}` is deprecated. Use `[features].{canonical}` instead."); - let details = if alias == canonical { - None - } else { - Some(format!( - "Enable it with `--enable {canonical}` or `[features].{canonical}` in config.toml. See https://github.com/openai/codex/blob/main/docs/config.md#feature-flags for details." - )) - }; + for usage in config.features.legacy_feature_usages() { post_session_configured_events.push(Event { id: INITIAL_SUBMIT_ID.to_owned(), - msg: EventMsg::DeprecationNotice(DeprecationNoticeEvent { summary, details }), + msg: EventMsg::DeprecationNotice(DeprecationNoticeEvent { + summary: usage.summary.clone(), + details: usage.details.clone(), + }), }); } if crate::config::uses_deprecated_instructions_file(&config.config_layer_stack) { diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 22371babd6..a571b31952 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -148,6 +148,8 @@ impl Feature { pub struct LegacyFeatureUsage { pub alias: String, pub feature: Feature, + pub summary: String, + pub details: Option, } /// Holds the effective set of enabled features. @@ -204,9 +206,12 @@ impl Features { } 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 { alias: alias.to_string(), feature, + summary, + details, }); } @@ -217,10 +222,8 @@ impl Features { self.record_legacy_usage_force(alias, feature); } - pub fn legacy_feature_usages(&self) -> impl Iterator + '_ { - self.legacy_usages - .iter() - .map(|usage| (usage.alias.as_str(), usage.feature)) + pub fn legacy_feature_usages(&self) -> impl Iterator + '_ { + self.legacy_usages.iter() } pub fn emit_metrics(&self, otel: &OtelManager) { @@ -241,6 +244,21 @@ impl Features { /// Apply a table of key -> bool toggles (e.g. from TOML). pub fn apply_map(&mut self, m: &BTreeMap) { for (k, v) in m { + match k.as_str() { + "web_search_request" => { + self.record_legacy_usage_force( + "features.web_search_request", + Feature::WebSearchRequest, + ); + } + "web_search_cached" => { + self.record_legacy_usage_force( + "features.web_search_cached", + Feature::WebSearchCached, + ); + } + _ => {} + } match feature_for_key(k) { Some(feat) => { if k != feat.key() { @@ -301,6 +319,42 @@ impl Features { } } +fn legacy_usage_notice(alias: &str, feature: Feature) -> (String, Option) { + let canonical = feature.key(); + match feature { + Feature::WebSearchRequest | Feature::WebSearchCached => { + let label = match alias { + "web_search" => "[features].web_search", + "tools.web_search" => "[tools].web_search", + "features.web_search_request" | "web_search_request" => { + "[features].web_search_request" + } + "features.web_search_cached" | "web_search_cached" => { + "[features].web_search_cached" + } + _ => alias, + }; + let summary = format!("`{label}` is deprecated. Use `web_search` instead."); + (summary, Some(web_search_details().to_string())) + } + _ => { + let summary = format!("`{alias}` is deprecated. Use `[features].{canonical}` instead."); + let details = if alias == canonical { + None + } else { + Some(format!( + "Enable it with `--enable {canonical}` or `[features].{canonical}` in config.toml. See https://github.com/openai/codex/blob/main/docs/config.md#feature-flags for details." + )) + }; + (summary, details) + } + } +} + +fn web_search_details() -> &'static str { + "Set `web_search` to `\"live\"`, `\"cached\"`, or `\"disabled\"` in config.toml." +} + /// Keys accepted in `[features]` tables. fn feature_for_key(key: &str) -> Option { for spec in FEATURES { @@ -349,13 +403,13 @@ pub const FEATURES: &[FeatureSpec] = &[ FeatureSpec { id: Feature::WebSearchRequest, key: "web_search_request", - stage: Stage::Stable, + stage: Stage::Deprecated, default_enabled: false, }, FeatureSpec { id: Feature::WebSearchCached, key: "web_search_cached", - stage: Stage::UnderDevelopment, + stage: Stage::Deprecated, default_enabled: false, }, // Experimental program. Rendered in the `/experimental` menu for users. diff --git a/codex-rs/core/tests/suite/deprecation_notice.rs b/codex-rs/core/tests/suite/deprecation_notice.rs index d401a64cd4..06795cc51b 100644 --- a/codex-rs/core/tests/suite/deprecation_notice.rs +++ b/codex-rs/core/tests/suite/deprecation_notice.rs @@ -16,6 +16,7 @@ use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; +use std::collections::BTreeMap; use toml::Value as TomlValue; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -110,3 +111,73 @@ async fn emits_deprecation_notice_for_experimental_instructions_file() -> anyhow Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn emits_deprecation_notice_for_web_search_feature_flags() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let mut builder = test_codex().with_config(|config| { + let mut entries = BTreeMap::new(); + entries.insert("web_search_request".to_string(), true); + config.features.apply_map(&entries); + }); + + let TestCodex { codex, .. } = builder.build(&server).await?; + + let notice = wait_for_event_match(&codex, |event| match event { + EventMsg::DeprecationNotice(ev) if ev.summary.contains("[features].web_search_request") => { + Some(ev.clone()) + } + _ => None, + }) + .await; + + let DeprecationNoticeEvent { summary, details } = notice; + assert_eq!( + summary, + "`[features].web_search_request` is deprecated. Use `web_search` instead.".to_string(), + ); + assert_eq!( + details.as_deref(), + Some("Set `web_search` to `\"live\"`, `\"cached\"`, or `\"disabled\"` in config.toml."), + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn emits_deprecation_notice_for_disabled_web_search_feature_flag() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let mut builder = test_codex().with_config(|config| { + let mut entries = BTreeMap::new(); + entries.insert("web_search_request".to_string(), false); + config.features.apply_map(&entries); + }); + + let TestCodex { codex, .. } = builder.build(&server).await?; + + let notice = wait_for_event_match(&codex, |event| match event { + EventMsg::DeprecationNotice(ev) if ev.summary.contains("[features].web_search_request") => { + Some(ev.clone()) + } + _ => None, + }) + .await; + + let DeprecationNoticeEvent { summary, details } = notice; + assert_eq!( + summary, + "`[features].web_search_request` is deprecated. Use `web_search` instead.".to_string(), + ); + assert_eq!( + details.as_deref(), + Some("Set `web_search` to `\"live\"`, `\"cached\"`, or `\"disabled\"` in config.toml."), + ); + + Ok(()) +} From b7edeee8ca253dd9d40398c9f3bab7c92c89f535 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 28 Jan 2026 11:36:11 -0800 Subject: [PATCH 041/116] compaction (#10034) # 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. --- .../src/protocol/common.rs | 1 + .../app-server-protocol/src/protocol/v2.rs | 7 + codex-rs/app-server/README.md | 3 +- codex-rs/core/src/compact.rs | 10 +- codex-rs/core/src/compact_remote.rs | 11 +- codex-rs/core/tests/suite/compact.rs | 160 ++++++++++++++++++ codex-rs/core/tests/suite/compact_remote.rs | 104 +++++++++++- codex-rs/protocol/src/items.rs | 27 +++ 8 files changed, 311 insertions(+), 12 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index e32b060902..cad6976b4b 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -598,6 +598,7 @@ server_notification_definitions! { ReasoningSummaryTextDelta => "item/reasoning/summaryTextDelta" (v2::ReasoningSummaryTextDeltaNotification), ReasoningSummaryPartAdded => "item/reasoning/summaryPartAdded" (v2::ReasoningSummaryPartAddedNotification), ReasoningTextDelta => "item/reasoning/textDelta" (v2::ReasoningTextDeltaNotification), + /// Deprecated: Use `ContextCompaction` item type instead. ContextCompacted => "thread/compacted" (v2::ContextCompactedNotification), DeprecationNotice => "deprecationNotice" (v2::DeprecationNoticeNotification), ConfigWarning => "configWarning" (v2::ConfigWarningNotification), diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 0116bd21e9..fb234b71df 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2029,6 +2029,9 @@ pub enum ThreadItem { #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] ExitedReviewMode { id: String, review: String }, + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] + ContextCompaction { id: String }, } impl From for ThreadItem { @@ -2057,6 +2060,9 @@ impl From for ThreadItem { id: search.id, query: search.query, }, + CoreTurnItem::ContextCompaction(compaction) => { + ThreadItem::ContextCompaction { id: compaction.id } + } } } } @@ -2419,6 +2425,7 @@ pub struct WindowsWorldWritableWarningNotification { pub failed_scan: bool, } +/// Deprecated: Use `ContextCompaction` item type instead. #[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 adf8ef0b45..8195bd23cb 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -431,7 +431,8 @@ Today both notifications carry an empty `items` array even when item events were - `imageView` — `{id, path}` emitted when the agent invokes the image viewer tool. - `enteredReviewMode` — `{id, review}` sent when the reviewer starts; `review` is a short user-facing label such as `"current changes"` or the requested target description. - `exitedReviewMode` — `{id, review}` emitted when the reviewer finishes; `review` is the full plain-text review (usually, overall notes plus bullet point findings). -- `compacted` - `{threadId, turnId}` when codex compacts the conversation history. This can happen automatically. +- `contextCompaction` — `{id}` emitted when codex compacts the conversation history. This can happen automatically. +- `compacted` - `{threadId, turnId}` when codex compacts the conversation history. This can happen automatically. **Deprecated:** Use `contextCompaction` instead. All items emit two shared lifecycle events: diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index c365d2cfda..b233618eea 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -10,7 +10,6 @@ use crate::error::CodexErr; use crate::error::Result as CodexResult; use crate::features::Feature; use crate::protocol::CompactedItem; -use crate::protocol::ContextCompactedEvent; use crate::protocol::EventMsg; use crate::protocol::TurnContextItem; use crate::protocol::TurnStartedEvent; @@ -20,6 +19,7 @@ use crate::truncate::TruncationPolicy; use crate::truncate::approx_token_count; use crate::truncate::truncate_text; use crate::util::backoff; +use codex_protocol::items::ContextCompactionItem; use codex_protocol::items::TurnItem; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; @@ -71,6 +71,9 @@ async fn run_compact_task_inner( turn_context: Arc, input: Vec, ) { + let compaction_item = TurnItem::ContextCompaction(ContextCompactionItem::new()); + sess.emit_turn_item_started(&turn_context, &compaction_item) + .await; let initial_input_for_turn: ResponseInputItem = ResponseInputItem::from(input); let mut history = sess.clone_history().await; @@ -193,9 +196,8 @@ async fn run_compact_task_inner( }); sess.persist_rollout_items(&[rollout_item]).await; - let event = EventMsg::ContextCompacted(ContextCompactedEvent {}); - sess.send_event(&turn_context, event).await; - + sess.emit_turn_item_completed(&turn_context, compaction_item) + .await; let warning = EventMsg::Warning(WarningEvent { message: "Heads up: Long threads and multiple compactions can cause the model to be less accurate. Start a new thread when possible to keep threads small and targeted.".to_string(), }); diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index aaa7fc68a7..35c157acfc 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -5,10 +5,11 @@ use crate::codex::Session; use crate::codex::TurnContext; use crate::error::Result as CodexResult; use crate::protocol::CompactedItem; -use crate::protocol::ContextCompactedEvent; use crate::protocol::EventMsg; use crate::protocol::RolloutItem; use crate::protocol::TurnStartedEvent; +use codex_protocol::items::ContextCompactionItem; +use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; pub(crate) async fn run_inline_remote_auto_compact_task( @@ -40,6 +41,9 @@ async fn run_remote_compact_task_inner_impl( sess: &Arc, turn_context: &Arc, ) -> CodexResult<()> { + let compaction_item = TurnItem::ContextCompaction(ContextCompactionItem::new()); + sess.emit_turn_item_started(turn_context, &compaction_item) + .await; let history = sess.clone_history().await; // Required to keep `/undo` available after compaction @@ -77,8 +81,7 @@ async fn run_remote_compact_task_inner_impl( sess.persist_rollout_items(&[RolloutItem::Compacted(compacted_item)]) .await; - let event = EventMsg::ContextCompacted(ContextCompactedEvent {}); - sess.send_event(turn_context, event).await; - + sess.emit_turn_item_completed(turn_context, compaction_item) + .await; Ok(()) } diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index f4706962a0..b8b693945b 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -8,12 +8,15 @@ use codex_core::config::Config; use codex_core::features::Feature; 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::user_input::UserInput; use core_test_support::responses::ev_local_shell_call; use core_test_support::responses::ev_reasoning_item; @@ -440,6 +443,80 @@ async fn manual_compact_emits_api_and_local_token_usage_events() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn manual_compact_emits_context_compaction_items() { + skip_if_no_network!(); + + let server = start_mock_server().await; + + let sse1 = sse(vec![ + ev_assistant_message("m1", FIRST_REPLY), + ev_completed("r1"), + ]); + let sse2 = sse(vec![ + ev_assistant_message("m2", SUMMARY_TEXT), + ev_completed("r2"), + ]); + mount_sse_sequence(&server, vec![sse1, sse2]).await; + + let model_provider = non_openai_model_provider(&server); + let mut builder = test_codex().with_config(move |config| { + config.model_provider = model_provider; + set_test_compact_prompt(config); + }); + let codex = builder.build(&server).await.unwrap().codex; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "manual compact".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await + .unwrap(); + wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + + codex.submit(Op::Compact).await.unwrap(); + + let mut started_item = None; + let mut completed_item = None; + let mut legacy_event = false; + let mut saw_turn_complete = false; + + while !saw_turn_complete || started_item.is_none() || completed_item.is_none() || !legacy_event + { + let event = codex.next_event().await.unwrap(); + match event.msg { + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::ContextCompaction(item), + .. + }) => { + started_item = Some(item); + } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::ContextCompaction(item), + .. + }) => { + completed_item = Some(item); + } + EventMsg::ContextCompacted(_) => { + legacy_event = true; + } + EventMsg::TurnComplete(_) => { + saw_turn_complete = true; + } + _ => {} + } + } + + let started_item = started_item.expect("context compaction item started"); + let completed_item = completed_item.expect("context compaction item completed"); + assert_eq!(started_item.id, completed_item.id); + assert!(legacy_event); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { skip_if_no_network!(); @@ -1179,6 +1256,89 @@ async fn auto_compact_runs_after_token_limit_hit() { ); } +// Windows CI only: bump to 4 workers to prevent SSE/event starvation and test timeouts. +#[cfg_attr(windows, tokio::test(flavor = "multi_thread", worker_threads = 4))] +#[cfg_attr(not(windows), tokio::test(flavor = "multi_thread", worker_threads = 2))] +async fn auto_compact_emits_context_compaction_items() { + skip_if_no_network!(); + + let server = start_mock_server().await; + + let sse1 = sse(vec![ + ev_assistant_message("m1", FIRST_REPLY), + ev_completed_with_tokens("r1", 70_000), + ]); + let sse2 = sse(vec![ + ev_assistant_message("m2", "SECOND_REPLY"), + ev_completed_with_tokens("r2", 330_000), + ]); + let sse3 = sse(vec![ + ev_assistant_message("m3", AUTO_SUMMARY_TEXT), + ev_completed_with_tokens("r3", 200), + ]); + let sse4 = sse(vec![ + ev_assistant_message("m4", FINAL_REPLY), + ev_completed_with_tokens("r4", 120), + ]); + + mount_sse_sequence(&server, vec![sse1, sse2, sse3, sse4]).await; + + let model_provider = non_openai_model_provider(&server); + let mut builder = test_codex().with_config(move |config| { + config.model_provider = model_provider; + set_test_compact_prompt(config); + config.model_auto_compact_token_limit = Some(200_000); + }); + let codex = builder.build(&server).await.unwrap().codex; + + let mut started_item = None; + let mut completed_item = None; + let mut legacy_event = false; + + for user in [FIRST_AUTO_MSG, SECOND_AUTO_MSG, POST_AUTO_USER_MSG] { + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: user.into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await + .unwrap(); + + loop { + let event = codex.next_event().await.unwrap(); + match event.msg { + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::ContextCompaction(item), + .. + }) => { + started_item = Some(item); + } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::ContextCompaction(item), + .. + }) => { + completed_item = Some(item); + } + EventMsg::ContextCompacted(_) => { + legacy_event = true; + } + EventMsg::TurnComplete(_) if !event.id.starts_with("auto-compact-") => { + break; + } + _ => {} + } + } + } + + let started_item = started_item.expect("context compaction item started"); + let completed_item = completed_item.expect("context compaction item completed"); + assert_eq!(started_item.id, completed_item.id); + assert!(legacy_event); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn auto_compact_runs_after_resume_when_token_usage_is_over_limit() { skip_if_no_network!(); diff --git a/codex-rs/core/tests/suite/compact_remote.rs b/codex-rs/core/tests/suite/compact_remote.rs index 2fc5ba53c2..563aff7826 100644 --- a/codex-rs/core/tests/suite/compact_remote.rs +++ b/codex-rs/core/tests/suite/compact_remote.rs @@ -6,9 +6,12 @@ use anyhow::Result; use codex_core::CodexAuth; use codex_core::features::Feature; 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::user_input::UserInput; @@ -201,13 +204,13 @@ async fn remote_compact_runs_automatically() -> Result<()> { final_output_json_schema: None, }) .await?; - let message = wait_for_event_match(&codex, |ev| match ev { + + let message = wait_for_event_match(&codex, |event| match event { EventMsg::ContextCompacted(_) => Some(true), _ => None, }) .await; - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - + wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; assert!(message); assert_eq!(compact_mock.requests().len(), 1); let follow_up_body = responses_mock.single_request().body_json().to_string(); @@ -217,6 +220,101 @@ async fn remote_compact_runs_automatically() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_manual_compact_emits_context_compaction_items() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = TestCodexHarness::with_builder( + test_codex() + .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(|config| { + config.features.enable(Feature::RemoteCompaction); + }), + ) + .await?; + let codex = harness.test().codex.clone(); + + mount_sse_once( + harness.server(), + sse(vec![ + responses::ev_assistant_message("m1", "REMOTE_REPLY"), + responses::ev_completed("resp-1"), + ]), + ) + .await; + + let compacted_history = vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "REMOTE_COMPACTED_SUMMARY".to_string(), + }], + end_turn: None, + }, + 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() }), + ) + .await; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "manual remote compact".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + + codex.submit(Op::Compact).await?; + + let mut started_item = None; + let mut completed_item = None; + let mut legacy_event = false; + let mut saw_turn_complete = false; + + while !saw_turn_complete || started_item.is_none() || completed_item.is_none() || !legacy_event + { + let event = codex.next_event().await.unwrap(); + match event.msg { + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::ContextCompaction(item), + .. + }) => { + started_item = Some(item); + } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::ContextCompaction(item), + .. + }) => { + completed_item = Some(item); + } + EventMsg::ContextCompacted(_) => { + legacy_event = true; + } + EventMsg::TurnComplete(_) => { + saw_turn_complete = true; + } + _ => {} + } + } + + let started_item = started_item.expect("context compaction item started"); + let completed_item = completed_item.expect("context compaction item completed"); + assert_eq!(started_item.id, completed_item.id); + assert!(legacy_event); + assert_eq!(compact_mock.requests().len(), 1); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn remote_compact_persists_replacement_history_in_rollout() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index 12fa6a0f51..e7c916a61d 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -2,6 +2,7 @@ use crate::models::WebSearchAction; use crate::protocol::AgentMessageEvent; use crate::protocol::AgentReasoningEvent; use crate::protocol::AgentReasoningRawContentEvent; +use crate::protocol::ContextCompactedEvent; use crate::protocol::EventMsg; use crate::protocol::UserMessageEvent; use crate::protocol::WebSearchEndEvent; @@ -21,6 +22,7 @@ pub enum TurnItem { AgentMessage(AgentMessageItem), Reasoning(ReasoningItem), WebSearch(WebSearchItem), + ContextCompaction(ContextCompactionItem), } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] @@ -57,6 +59,29 @@ pub struct WebSearchItem { pub action: WebSearchAction, } +#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] +pub struct ContextCompactionItem { + pub id: String, +} + +impl ContextCompactionItem { + pub fn new() -> Self { + Self { + id: uuid::Uuid::new_v4().to_string(), + } + } + + pub fn as_legacy_event(&self) -> EventMsg { + EventMsg::ContextCompacted(ContextCompactedEvent {}) + } +} + +impl Default for ContextCompactionItem { + fn default() -> Self { + Self::new() + } +} + impl UserMessageItem { pub fn new(content: &[UserInput]) -> Self { Self { @@ -195,6 +220,7 @@ impl TurnItem { TurnItem::AgentMessage(item) => item.id.clone(), TurnItem::Reasoning(item) => item.id.clone(), TurnItem::WebSearch(item) => item.id.clone(), + TurnItem::ContextCompaction(item) => item.id.clone(), } } @@ -204,6 +230,7 @@ impl TurnItem { TurnItem::AgentMessage(item) => item.as_legacy_events(), TurnItem::WebSearch(item) => vec![item.as_legacy_event()], TurnItem::Reasoning(item) => item.as_legacy_events(show_raw_agent_reasoning), + TurnItem::ContextCompaction(item) => vec![item.as_legacy_event()], } } } From 66de985e4e9d22e8a48c5185b1a4678e3016928d Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Wed, 28 Jan 2026 11:38:29 -0800 Subject: [PATCH 042/116] allow elevated sandbox to be enabled without base experimental flag (#10028) elevated flag = elevated sandbox experimental flag = non-elevated sandbox both = elevated --- codex-rs/cli/src/debug_sandbox.rs | 9 ++-- codex-rs/core/src/config/mod.rs | 7 ++-- codex-rs/core/src/windows_sandbox.rs | 61 +++++++++++++++++++++++++--- codex-rs/tui/src/app.rs | 38 +++++++++-------- codex-rs/tui/src/lib.rs | 4 +- 5 files changed, 90 insertions(+), 29 deletions(-) diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 8c1f3e5d39..13cb8cdd86 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -136,7 +136,8 @@ async fn run_command_under_sandbox( if let SandboxType::Windows = sandbox_type { #[cfg(target_os = "windows")] { - use codex_core::features::Feature; + use codex_core::windows_sandbox::WindowsSandboxLevelExt; + use codex_protocol::config_types::WindowsSandboxLevel; use codex_windows_sandbox::run_windows_sandbox_capture; use codex_windows_sandbox::run_windows_sandbox_capture_elevated; @@ -147,8 +148,10 @@ async fn run_command_under_sandbox( let env_map = env.clone(); let command_vec = command.clone(); let base_dir = config.codex_home.clone(); - let use_elevated = config.features.enabled(Feature::WindowsSandbox) - && config.features.enabled(Feature::WindowsSandboxElevated); + let use_elevated = matches!( + WindowsSandboxLevel::from_config(&config), + WindowsSandboxLevel::Elevated + ); // Preflight audit is invoked elsewhere at the appropriate times. let res = tokio::task::spawn_blocking(move || { diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 5d84d577eb..98716472e9 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1679,18 +1679,19 @@ impl Config { } } - pub fn set_windows_sandbox_globally(&mut self, value: bool) { + pub fn set_windows_sandbox_enabled(&mut self, value: bool) { if value { self.features.enable(Feature::WindowsSandbox); + self.forced_auto_mode_downgraded_on_windows = false; } else { self.features.disable(Feature::WindowsSandbox); } - self.forced_auto_mode_downgraded_on_windows = !value; } - pub fn set_windows_elevated_sandbox_globally(&mut self, value: bool) { + pub fn set_windows_elevated_sandbox_enabled(&mut self, value: bool) { if value { self.features.enable(Feature::WindowsSandboxElevated); + self.forced_auto_mode_downgraded_on_windows = false; } else { self.features.disable(Feature::WindowsSandboxElevated); } diff --git a/codex-rs/core/src/windows_sandbox.rs b/codex-rs/core/src/windows_sandbox.rs index 22825752b2..7b9451c246 100644 --- a/codex-rs/core/src/windows_sandbox.rs +++ b/codex-rs/core/src/windows_sandbox.rs @@ -23,13 +23,13 @@ impl WindowsSandboxLevelExt for WindowsSandboxLevel { } fn from_features(features: &Features) -> WindowsSandboxLevel { - if !features.enabled(Feature::WindowsSandbox) { - return WindowsSandboxLevel::Disabled; - } if features.enabled(Feature::WindowsSandboxElevated) { - WindowsSandboxLevel::Elevated - } else { + return WindowsSandboxLevel::Elevated; + } + if features.enabled(Feature::WindowsSandbox) { WindowsSandboxLevel::RestrictedToken + } else { + WindowsSandboxLevel::Disabled } } } @@ -94,3 +94,54 @@ pub fn run_elevated_setup( ) -> anyhow::Result<()> { anyhow::bail!("elevated Windows sandbox setup is only supported on Windows") } + +#[cfg(test)] +mod tests { + use super::*; + use crate::features::Features; + use pretty_assertions::assert_eq; + + #[test] + fn elevated_flag_works_by_itself() { + let mut features = Features::with_defaults(); + features.enable(Feature::WindowsSandboxElevated); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::Elevated + ); + } + + #[test] + fn restricted_token_flag_works_by_itself() { + let mut features = Features::with_defaults(); + features.enable(Feature::WindowsSandbox); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::RestrictedToken + ); + } + + #[test] + fn no_flags_means_no_sandbox() { + let features = Features::with_defaults(); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::Disabled + ); + } + + #[test] + fn elevated_wins_when_both_flags_are_enabled() { + let mut features = Features::with_defaults(); + features.enable(Feature::WindowsSandbox); + features.enable(Feature::WindowsSandboxElevated); + + assert_eq!( + WindowsSandboxLevel::from_features(&features), + WindowsSandboxLevel::Elevated + ); + } +} diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index bf4ab6798e..36a5ddd4ba 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1685,23 +1685,29 @@ impl App { let feature_key = Feature::WindowsSandbox.key(); let elevated_key = Feature::WindowsSandboxElevated.key(); let elevated_enabled = matches!(mode, WindowsSandboxEnableMode::Elevated); - match ConfigEditsBuilder::new(&self.config.codex_home) - .with_profile(profile) - .set_feature_enabled(feature_key, true) - .set_feature_enabled(elevated_key, elevated_enabled) - .apply() - .await - { + let mut builder = + ConfigEditsBuilder::new(&self.config.codex_home).with_profile(profile); + if elevated_enabled { + builder = builder.set_feature_enabled(elevated_key, true); + } else { + builder = builder + .set_feature_enabled(feature_key, true) + .set_feature_enabled(elevated_key, false); + } + match builder.apply().await { Ok(()) => { - self.config.set_windows_sandbox_globally(true); - self.config - .set_windows_elevated_sandbox_globally(elevated_enabled); - self.chat_widget - .set_feature_enabled(Feature::WindowsSandbox, true); - self.chat_widget.set_feature_enabled( - Feature::WindowsSandboxElevated, - elevated_enabled, - ); + if elevated_enabled { + self.config.set_windows_elevated_sandbox_enabled(true); + self.chat_widget + .set_feature_enabled(Feature::WindowsSandboxElevated, true); + } else { + self.config.set_windows_sandbox_enabled(true); + self.config.set_windows_elevated_sandbox_enabled(false); + self.chat_widget + .set_feature_enabled(Feature::WindowsSandbox, true); + self.chat_widget + .set_feature_enabled(Feature::WindowsSandboxElevated, false); + } self.chat_widget.clear_forced_auto_mode_downgrade(); let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 17b839f7a8..bced1e0653 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -882,7 +882,7 @@ mod tests { let mut config = build_config(&temp_dir).await?; config.did_user_set_custom_approval_policy_or_sandbox_mode = false; config.active_project = ProjectConfig { trust_level: None }; - config.set_windows_sandbox_globally(false); + config.set_windows_sandbox_enabled(false); let should_show = should_show_trust_screen(&config); if cfg!(target_os = "windows") { @@ -905,7 +905,7 @@ mod tests { let mut config = build_config(&temp_dir).await?; config.did_user_set_custom_approval_policy_or_sandbox_mode = false; config.active_project = ProjectConfig { trust_level: None }; - config.set_windows_sandbox_globally(true); + config.set_windows_sandbox_enabled(true); let should_show = should_show_trust_screen(&config); if cfg!(target_os = "windows") { From f7699e0487a1da2b5787972fc1bd6a2b9974aeb9 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 12:56:26 -0700 Subject: [PATCH 043/116] fix(ci) fix shell-tool-mcp version v2 (#10101) ## summary we had a merge conflict from the linux musl fix, let's get this squared away. --- .github/workflows/shell-tool-mcp.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index a0eae56b59..88cdc28b3a 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -344,7 +344,6 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: - version: 10.8.1 run_install: false - name: Setup Node.js @@ -440,7 +439,6 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: - version: 10.8.1 run_install: false - name: Setup Node.js From 147e7118e0612830e5df6c40c6ad0efd6f85dc67 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 28 Jan 2026 12:00:32 -0800 Subject: [PATCH 044/116] Added `tui.notifications_method` config option (#10043) This PR adds a new `tui.notifications_method` config option that accepts values of "auto", "osc9" and "bel". It defaults to "auto", which attempts to auto-detect whether the terminal supports OSC 9 escape sequences and falls back to BEL if not. The PR also removes the inconsistent handling of notifications on Windows when WSL was used. --- codex-rs/core/config.schema.json | 17 +++ codex-rs/core/src/config/mod.rs | 34 ++++- codex-rs/core/src/config/types.rs | 24 ++++ codex-rs/tui/src/app.rs | 2 + codex-rs/tui/src/notifications/bel.rs | 37 +++++ codex-rs/tui/src/notifications/mod.rs | 133 ++++++++++-------- .../tui/src/notifications/windows_toast.rs | 128 ----------------- codex-rs/tui/src/tui.rs | 48 +++---- 8 files changed, 203 insertions(+), 220 deletions(-) create mode 100644 codex-rs/tui/src/notifications/bel.rs delete mode 100644 codex-rs/tui/src/notifications/windows_toast.rs diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index a756352da0..03e27dceda 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -483,6 +483,14 @@ }, "type": "object" }, + "NotificationMethod": { + "enum": [ + "auto", + "osc9", + "bel" + ], + "type": "string" + }, "Notifications": { "anyOf": [ { @@ -991,6 +999,15 @@ "default": null, "description": "Start the TUI in the specified collaboration mode (plan/execute/etc.). Defaults to unset." }, + "notification_method": { + "allOf": [ + { + "$ref": "#/definitions/NotificationMethod" + } + ], + "default": "auto", + "description": "Notification method to use for unfocused terminal notifications. Defaults to `auto`." + }, "notifications": { "allOf": [ { diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 98716472e9..895e54c040 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -7,6 +7,7 @@ use crate::config::types::McpServerConfig; use crate::config::types::McpServerDisabledReason; use crate::config::types::McpServerTransportConfig; use crate::config::types::Notice; +use crate::config::types::NotificationMethod; use crate::config::types::Notifications; use crate::config::types::OtelConfig; use crate::config::types::OtelConfigToml; @@ -192,10 +193,13 @@ pub struct Config { /// If unset the feature is disabled. pub notify: Option>, - /// TUI notifications preference. When set, the TUI will send OSC 9 notifications on approvals - /// and turn completions when not focused. + /// TUI notifications preference. When set, the TUI will send terminal notifications on + /// approvals and turn completions when not focused. pub tui_notifications: Notifications, + /// Notification method for terminal notifications (osc9 or bel). + pub tui_notification_method: NotificationMethod, + /// Enable ASCII animations and shimmer effects in the TUI. pub animations: bool, @@ -1607,6 +1611,11 @@ impl Config { .as_ref() .map(|t| t.notifications.clone()) .unwrap_or_default(), + tui_notification_method: cfg + .tui + .as_ref() + .map(|t| t.notification_method) + .unwrap_or_default(), animations: cfg.tui.as_ref().map(|t| t.animations).unwrap_or(true), show_tooltips: cfg.tui.as_ref().map(|t| t.show_tooltips).unwrap_or(true), experimental_mode: cfg.tui.as_ref().and_then(|t| t.experimental_mode), @@ -1765,6 +1774,7 @@ mod tests { use crate::config::types::FeedbackConfigToml; use crate::config::types::HistoryPersistence; use crate::config::types::McpServerTransportConfig; + use crate::config::types::NotificationMethod; use crate::config::types::Notifications; use crate::config_loader::RequirementSource; use crate::features::Feature; @@ -1861,6 +1871,7 @@ persistence = "none" tui, Tui { notifications: Notifications::Enabled(true), + notification_method: NotificationMethod::Auto, animations: true, show_tooltips: true, experimental_mode: None, @@ -3789,6 +3800,7 @@ model_verbosity = "high" check_for_update_on_startup: true, disable_paste_burst: false, tui_notifications: Default::default(), + tui_notification_method: Default::default(), animations: true, show_tooltips: true, experimental_mode: None, @@ -3872,6 +3884,7 @@ model_verbosity = "high" check_for_update_on_startup: true, disable_paste_burst: false, tui_notifications: Default::default(), + tui_notification_method: Default::default(), animations: true, show_tooltips: true, experimental_mode: None, @@ -3970,6 +3983,7 @@ model_verbosity = "high" check_for_update_on_startup: true, disable_paste_burst: false, tui_notifications: Default::default(), + tui_notification_method: Default::default(), animations: true, show_tooltips: true, experimental_mode: None, @@ -4054,6 +4068,7 @@ model_verbosity = "high" check_for_update_on_startup: true, disable_paste_burst: false, tui_notifications: Default::default(), + tui_notification_method: Default::default(), animations: true, show_tooltips: true, experimental_mode: None, @@ -4411,13 +4426,17 @@ mcp_oauth_callback_port = 5678 #[cfg(test)] mod notifications_tests { + use crate::config::types::NotificationMethod; use crate::config::types::Notifications; use assert_matches::assert_matches; use serde::Deserialize; #[derive(Deserialize, Debug, PartialEq)] struct TuiTomlTest { + #[serde(default)] notifications: Notifications, + #[serde(default)] + notification_method: NotificationMethod, } #[derive(Deserialize, Debug, PartialEq)] @@ -4448,4 +4467,15 @@ mod notifications_tests { Notifications::Custom(ref v) if v == &vec!["foo".to_string()] ); } + + #[test] + fn test_tui_notification_method() { + let toml = r#" + [tui] + notification_method = "bel" + "#; + let parsed: RootTomlTest = + toml::from_str(toml).expect("deserialize notification_method=\"bel\""); + assert_eq!(parsed.tui.notification_method, NotificationMethod::Bel); + } } diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index a1d126c114..e949d869a6 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -428,6 +428,25 @@ impl Default for Notifications { } } +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, Default)] +#[serde(rename_all = "lowercase")] +pub enum NotificationMethod { + #[default] + Auto, + Osc9, + Bel, +} + +impl fmt::Display for NotificationMethod { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + NotificationMethod::Auto => write!(f, "auto"), + NotificationMethod::Osc9 => write!(f, "osc9"), + NotificationMethod::Bel => write!(f, "bel"), + } + } +} + /// Collection of settings that are specific to the TUI. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -437,6 +456,11 @@ pub struct Tui { #[serde(default)] pub notifications: Notifications, + /// Notification method to use for unfocused terminal notifications. + /// Defaults to `auto`. + #[serde(default)] + pub notification_method: NotificationMethod, + /// Enable animations (welcome screen, shimmer effects, spinners). /// Defaults to `true`. #[serde(default = "default_true")] diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 36a5ddd4ba..e5db8fc6b6 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -923,6 +923,7 @@ impl App { let app_event_tx = AppEventSender::new(app_event_tx); emit_deprecation_notice(&app_event_tx, ollama_chat_support_notice); emit_project_config_warnings(&app_event_tx, &config); + tui.set_notification_method(config.tui_notification_method); let harness_overrides = normalize_harness_overrides_for_cwd(harness_overrides, &config.cwd)?; @@ -1336,6 +1337,7 @@ impl App { Ok(resumed) => { self.shutdown_current_thread().await; self.config = resume_config; + tui.set_notification_method(self.config.tui_notification_method); self.file_search = FileSearchManager::new( self.config.cwd.clone(), self.app_event_tx.clone(), diff --git a/codex-rs/tui/src/notifications/bel.rs b/codex-rs/tui/src/notifications/bel.rs new file mode 100644 index 0000000000..44e7de2603 --- /dev/null +++ b/codex-rs/tui/src/notifications/bel.rs @@ -0,0 +1,37 @@ +use std::fmt; +use std::io; +use std::io::stdout; + +use crossterm::Command; +use ratatui::crossterm::execute; + +#[derive(Debug, Default)] +pub struct BelBackend; + +impl BelBackend { + pub fn notify(&mut self, _message: &str) -> io::Result<()> { + execute!(stdout(), PostNotification) + } +} + +/// Command that emits a BEL desktop notification. +#[derive(Debug, Clone)] +pub struct PostNotification; + +impl Command for PostNotification { + fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result { + write!(f, "\x07") + } + + #[cfg(windows)] + fn execute_winapi(&self) -> io::Result<()> { + Err(std::io::Error::other( + "tried to execute PostNotification using WinAPI; use ANSI instead", + )) + } + + #[cfg(windows)] + fn is_ansi_code_supported(&self) -> bool { + true + } +} diff --git a/codex-rs/tui/src/notifications/mod.rs b/codex-rs/tui/src/notifications/mod.rs index 33a591dfdb..e9a7ac1ddf 100644 --- a/codex-rs/tui/src/notifications/mod.rs +++ b/codex-rs/tui/src/notifications/mod.rs @@ -1,68 +1,80 @@ +mod bel; mod osc9; -mod windows_toast; use std::env; use std::io; -use codex_core::env::is_wsl; +use bel::BelBackend; +use codex_core::config::types::NotificationMethod; use osc9::Osc9Backend; -use windows_toast::WindowsToastBackend; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum NotificationBackendKind { - Osc9, - WindowsToast, -} #[derive(Debug)] pub enum DesktopNotificationBackend { Osc9(Osc9Backend), - WindowsToast(WindowsToastBackend), + Bel(BelBackend), } impl DesktopNotificationBackend { - pub fn osc9() -> Self { - Self::Osc9(Osc9Backend) + pub fn for_method(method: NotificationMethod) -> Self { + match method { + NotificationMethod::Auto => { + if supports_osc9() { + Self::Osc9(Osc9Backend) + } else { + Self::Bel(BelBackend) + } + } + NotificationMethod::Osc9 => Self::Osc9(Osc9Backend), + NotificationMethod::Bel => Self::Bel(BelBackend), + } } - pub fn windows_toast() -> Self { - Self::WindowsToast(WindowsToastBackend::default()) - } - - pub fn kind(&self) -> NotificationBackendKind { + pub fn method(&self) -> NotificationMethod { match self { - DesktopNotificationBackend::Osc9(_) => NotificationBackendKind::Osc9, - DesktopNotificationBackend::WindowsToast(_) => NotificationBackendKind::WindowsToast, + DesktopNotificationBackend::Osc9(_) => NotificationMethod::Osc9, + DesktopNotificationBackend::Bel(_) => NotificationMethod::Bel, } } pub fn notify(&mut self, message: &str) -> io::Result<()> { match self { DesktopNotificationBackend::Osc9(backend) => backend.notify(message), - DesktopNotificationBackend::WindowsToast(backend) => backend.notify(message), + DesktopNotificationBackend::Bel(backend) => backend.notify(message), } } } -pub fn detect_backend() -> DesktopNotificationBackend { - if should_use_windows_toasts() { - tracing::info!( - "Windows Terminal session detected under WSL; using Windows toast notifications" - ); - DesktopNotificationBackend::windows_toast() - } else { - DesktopNotificationBackend::osc9() - } +pub fn detect_backend(method: NotificationMethod) -> DesktopNotificationBackend { + DesktopNotificationBackend::for_method(method) } -fn should_use_windows_toasts() -> bool { - is_wsl() && env::var_os("WT_SESSION").is_some() +fn supports_osc9() -> bool { + if env::var_os("WT_SESSION").is_some() { + return false; + } + // Prefer TERM_PROGRAM when present, but keep fallbacks for shells/launchers + // that don't set it (e.g., tmux/ssh) to avoid regressing OSC 9 support. + if matches!( + env::var("TERM_PROGRAM").ok().as_deref(), + Some("WezTerm" | "ghostty") + ) { + return true; + } + // iTerm still provides a strong session signal even when TERM_PROGRAM is missing. + if env::var_os("ITERM_SESSION_ID").is_some() { + return true; + } + // TERM-based hints cover kitty/wezterm setups without TERM_PROGRAM. + matches!( + env::var("TERM").ok().as_deref(), + Some("xterm-kitty" | "wezterm" | "wezterm-mux") + ) } #[cfg(test)] mod tests { - use super::NotificationBackendKind; use super::detect_backend; + use codex_core::config::types::NotificationMethod; use serial_test::serial; use std::ffi::OsString; @@ -101,39 +113,44 @@ mod tests { } #[test] - #[serial] - fn defaults_to_osc9_outside_wsl() { - let _wsl_guard = EnvVarGuard::remove("WSL_DISTRO_NAME"); - let _wt_guard = EnvVarGuard::remove("WT_SESSION"); - assert_eq!(detect_backend().kind(), NotificationBackendKind::Osc9); + fn selects_osc9_method() { + assert!(matches!( + detect_backend(NotificationMethod::Osc9), + super::DesktopNotificationBackend::Osc9(_) + )); + } + + #[test] + fn selects_bel_method() { + assert!(matches!( + detect_backend(NotificationMethod::Bel), + super::DesktopNotificationBackend::Bel(_) + )); } #[test] #[serial] - fn waits_for_windows_terminal() { - let _wsl_guard = EnvVarGuard::set("WSL_DISTRO_NAME", "Ubuntu"); - let _wt_guard = EnvVarGuard::remove("WT_SESSION"); - assert_eq!(detect_backend().kind(), NotificationBackendKind::Osc9); + fn auto_prefers_bel_without_hints() { + let _term = EnvVarGuard::remove("TERM"); + let _term_program = EnvVarGuard::remove("TERM_PROGRAM"); + let _iterm = EnvVarGuard::remove("ITERM_SESSION_ID"); + let _wt = EnvVarGuard::remove("WT_SESSION"); + assert!(matches!( + detect_backend(NotificationMethod::Auto), + super::DesktopNotificationBackend::Bel(_) + )); } - #[cfg(target_os = "linux")] #[test] #[serial] - fn selects_windows_toast_in_wsl_windows_terminal() { - let _wsl_guard = EnvVarGuard::set("WSL_DISTRO_NAME", "Ubuntu"); - let _wt_guard = EnvVarGuard::set("WT_SESSION", "abc"); - assert_eq!( - detect_backend().kind(), - NotificationBackendKind::WindowsToast - ); - } - - #[cfg(not(target_os = "linux"))] - #[test] - #[serial] - fn stays_on_osc9_outside_linux_even_with_wsl_env() { - let _wsl_guard = EnvVarGuard::set("WSL_DISTRO_NAME", "Ubuntu"); - let _wt_guard = EnvVarGuard::set("WT_SESSION", "abc"); - assert_eq!(detect_backend().kind(), NotificationBackendKind::Osc9); + fn auto_uses_osc9_for_iterm() { + let _term = EnvVarGuard::remove("TERM"); + let _term_program = EnvVarGuard::remove("TERM_PROGRAM"); + let _iterm = EnvVarGuard::set("ITERM_SESSION_ID", "abc"); + let _wt = EnvVarGuard::remove("WT_SESSION"); + assert!(matches!( + detect_backend(NotificationMethod::Auto), + super::DesktopNotificationBackend::Osc9(_) + )); } } diff --git a/codex-rs/tui/src/notifications/windows_toast.rs b/codex-rs/tui/src/notifications/windows_toast.rs deleted file mode 100644 index 9917e62c37..0000000000 --- a/codex-rs/tui/src/notifications/windows_toast.rs +++ /dev/null @@ -1,128 +0,0 @@ -use std::io; -use std::process::Command; -use std::process::Stdio; - -use base64::Engine as _; -use base64::engine::general_purpose::STANDARD as BASE64; - -const APP_ID: &str = "Codex"; -const POWERSHELL_EXE: &str = "powershell.exe"; - -#[derive(Debug)] -pub struct WindowsToastBackend { - encoded_title: String, -} - -impl WindowsToastBackend { - pub fn notify(&mut self, message: &str) -> io::Result<()> { - let encoded_body = encode_argument(message); - let encoded_command = build_encoded_command(&self.encoded_title, &encoded_body); - spawn_powershell(encoded_command) - } -} - -impl Default for WindowsToastBackend { - fn default() -> Self { - WindowsToastBackend { - encoded_title: encode_argument(APP_ID), - } - } -} - -fn spawn_powershell(encoded_command: String) -> io::Result<()> { - let mut command = Command::new(POWERSHELL_EXE); - command - .arg("-NoProfile") - .arg("-NoLogo") - .arg("-EncodedCommand") - .arg(encoded_command) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()); - - let status = command.status()?; - if status.success() { - Ok(()) - } else { - Err(io::Error::other(format!( - "{POWERSHELL_EXE} exited with status {status}" - ))) - } -} - -fn build_encoded_command(encoded_title: &str, encoded_body: &str) -> String { - let script = build_ps_script(encoded_title, encoded_body); - encode_script_for_powershell(&script) -} - -fn build_ps_script(encoded_title: &str, encoded_body: &str) -> String { - format!( - r#" -$encoding = [System.Text.Encoding]::UTF8 -$titleText = $encoding.GetString([System.Convert]::FromBase64String("{encoded_title}")) -$bodyText = $encoding.GetString([System.Convert]::FromBase64String("{encoded_body}")) -[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null -$doc = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02) -$textNodes = $doc.GetElementsByTagName("text") -$textNodes.Item(0).AppendChild($doc.CreateTextNode($titleText)) | Out-Null -$textNodes.Item(1).AppendChild($doc.CreateTextNode($bodyText)) | Out-Null -$toast = [Windows.UI.Notifications.ToastNotification]::new($doc) -[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Codex').Show($toast) -"#, - ) -} - -fn encode_script_for_powershell(script: &str) -> String { - let mut wide: Vec = Vec::with_capacity((script.len() + 1) * 2); - for unit in script.encode_utf16() { - let bytes = unit.to_le_bytes(); - wide.extend_from_slice(&bytes); - } - BASE64.encode(wide) -} - -fn encode_argument(value: &str) -> String { - BASE64.encode(escape_for_xml(value)) -} - -pub fn escape_for_xml(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 -} - -#[cfg(test)] -mod tests { - use super::encode_script_for_powershell; - use super::escape_for_xml; - use pretty_assertions::assert_eq; - - #[test] - fn escapes_xml_entities() { - assert_eq!(escape_for_xml("5 > 3"), "5 > 3"); - assert_eq!(escape_for_xml("a & b"), "a & b"); - assert_eq!(escape_for_xml(""), "<tag>"); - assert_eq!(escape_for_xml("\"quoted\""), ""quoted""); - assert_eq!(escape_for_xml("single 'quote'"), "single 'quote'"); - } - - #[test] - fn leaves_safe_text_unmodified() { - assert_eq!(escape_for_xml("codex"), "codex"); - assert_eq!(escape_for_xml("multi word text"), "multi word text"); - } - - #[test] - fn encodes_utf16le_for_powershell() { - assert_eq!(encode_script_for_powershell("A"), "QQA="); - } -} diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index b5fee2e425..761fa83627 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -39,12 +39,12 @@ pub use self::frame_requester::FrameRequester; use crate::custom_terminal; use crate::custom_terminal::Terminal as CustomTerminal; use crate::notifications::DesktopNotificationBackend; -use crate::notifications::NotificationBackendKind; use crate::notifications::detect_backend; use crate::tui::event_stream::EventBroker; use crate::tui::event_stream::TuiEventStream; #[cfg(unix)] use crate::tui::job_control::SuspendContext; +use codex_core::config::types::NotificationMethod; mod event_stream; mod frame_rate_limiter; @@ -275,7 +275,7 @@ impl Tui { alt_screen_active: Arc::new(AtomicBool::new(false)), terminal_focused: Arc::new(AtomicBool::new(true)), enhanced_keys_supported, - notification_backend: Some(detect_backend()), + notification_backend: Some(detect_backend(NotificationMethod::default())), alt_screen_enabled: true, } } @@ -285,6 +285,10 @@ impl Tui { self.alt_screen_enabled = enabled; } + pub fn set_notification_method(&mut self, method: NotificationMethod) { + self.notification_backend = Some(detect_backend(method)); + } + pub fn frame_requester(&self) -> FrameRequester { self.frame_requester.clone() } @@ -361,36 +365,16 @@ impl Tui { let message = message.as_ref().to_string(); match backend.notify(&message) { Ok(()) => true, - Err(err) => match backend.kind() { - NotificationBackendKind::WindowsToast => { - tracing::error!( - error = %err, - "Failed to send Windows toast notification; falling back to OSC 9" - ); - self.notification_backend = Some(DesktopNotificationBackend::osc9()); - if let Some(backend) = self.notification_backend.as_mut() { - if let Err(osc_err) = backend.notify(&message) { - tracing::warn!( - error = %osc_err, - "Failed to emit OSC 9 notification after toast fallback; \ - disabling future notifications" - ); - self.notification_backend = None; - return false; - } - return true; - } - false - } - NotificationBackendKind::Osc9 => { - tracing::warn!( - error = %err, - "Failed to emit OSC 9 notification; disabling future notifications" - ); - self.notification_backend = None; - false - } - }, + Err(err) => { + let method = backend.method(); + tracing::warn!( + error = %err, + method = %method, + "Failed to emit terminal notification; disabling future notifications" + ); + self.notification_backend = None; + false + } } } From fe920d78048dc2a8208ed103b7a9bbaef2ba95cb Mon Sep 17 00:00:00 2001 From: zbarsky-openai Date: Wed, 28 Jan 2026 15:06:28 -0500 Subject: [PATCH 045/116] [bazel] Fix the build (#10104) --- MODULE.bazel | 5 ++ MODULE.bazel.lock | 115 ++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 112 insertions(+), 8 deletions(-) diff --git a/MODULE.bazel b/MODULE.bazel index a6a7e2eab6..df0df9b25c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -67,6 +67,11 @@ crate.from_cargo( cargo_toml = "//codex-rs:Cargo.toml", platform_triples = RUST_TRIPLES, ) +crate.annotation( + crate = "nucleo-matcher", + strip_prefix = "matcher", + version = "0.3.1", +) bazel_dep(name = "openssl", version = "3.5.4.bcr.0") diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index f0bb43940d..7444d3fdbe 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -595,14 +595,17 @@ "async-stream_0.3.6": "{\"dependencies\":[{\"name\":\"async-stream-impl\",\"req\":\"=0.3.6\"},{\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1\"}],\"features\":{}}", "async-task_4.7.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"atomic-waker\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"easy-parallel\",\"req\":\"^3\"},{\"kind\":\"dev\",\"name\":\"flaky_test\",\"req\":\"^0.2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"flume\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"futures-lite\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.10\"},{\"default_features\":false,\"name\":\"portable-atomic\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"smol\",\"req\":\"^2\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "async-trait_0.1.89": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.30\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.74\"},{\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.13\"},{\"default_features\":false,\"features\":[\"clone-impls\",\"full\",\"parsing\",\"printing\",\"proc-macro\",\"visit-mut\"],\"name\":\"syn\",\"req\":\"^2.0.46\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.40\"},{\"kind\":\"dev\",\"name\":\"tracing-attributes\",\"req\":\"^0.1.27\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.81\"}],\"features\":{}}", + "asynk-strim_0.1.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-fn-stream\",\"req\":\"^0.3.2\"},{\"kind\":\"dev\",\"name\":\"async-stream\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"features\":[\"cargo_bench_support\",\"plotters\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.7.0\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"futures-lite\",\"req\":\"^2.3.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.14\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.99\"}],\"features\":{}}", + "atoi_2.0.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"num-traits\",\"req\":\"^0.2.14\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"num-traits/std\"]}}", "atomic-waker_1.1.2": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"cargo_bench_support\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.5\"},{\"default_features\":false,\"name\":\"portable-atomic\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.7.0\"}],\"features\":{}}", "autocfg_1.5.0": "{\"dependencies\":[],\"features\":{}}", - "axum-core_0.5.2": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1.2\"},{\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1.0.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.0.0\"},{\"name\":\"mime\",\"req\":\"^0.3.16\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"},{\"name\":\"rustversion\",\"req\":\"^1.0.9\"},{\"name\":\"sync_wrapper\",\"req\":\"^1.0.0\"},{\"features\":[\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.25.0\"},{\"features\":[\"limit\"],\"name\":\"tower-http\",\"optional\":true,\"req\":\"^0.6.0\"},{\"features\":[\"limit\"],\"kind\":\"dev\",\"name\":\"tower-http\",\"req\":\"^0.6.0\"},{\"name\":\"tower-layer\",\"req\":\"^0.3\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.37\"}],\"features\":{\"__private_docs\":[\"dep:tower-http\"],\"tracing\":[\"dep:tracing\"]}}", - "axum_0.8.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"axum-core\",\"req\":\"^0.5.2\"},{\"name\":\"axum-macros\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22.1\"},{\"name\":\"bytes\",\"req\":\"^1.0\"},{\"name\":\"form_urlencoded\",\"optional\":true,\"req\":\"^1.1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1.0.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"optional\":true,\"req\":\"^1.1.0\"},{\"features\":[\"client\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1.0\"},{\"features\":[\"tokio\",\"server\",\"service\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1.3\"},{\"name\":\"itoa\",\"req\":\"^1.0.5\"},{\"name\":\"matchit\",\"req\":\"=0.8.4\"},{\"name\":\"memchr\",\"req\":\"^2.4.1\"},{\"name\":\"mime\",\"req\":\"^0.3.16\"},{\"name\":\"multer\",\"optional\":true,\"req\":\"^3.0.0\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"json\",\"stream\",\"multipart\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"json\",\"stream\",\"multipart\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12\"},{\"name\":\"rustversion\",\"req\":\"^1.0.9\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"raw_value\"],\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"serde_path_to_error\",\"optional\":true,\"req\":\"^0.1.8\"},{\"name\":\"serde_urlencoded\",\"optional\":true,\"req\":\"^0.7\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"sync_wrapper\",\"req\":\"^1.0.0\"},{\"features\":[\"serde-human-readable\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3\"},{\"features\":[\"time\"],\"name\":\"tokio\",\"optional\":true,\"package\":\"tokio\",\"req\":\"^1.44\"},{\"features\":[\"macros\",\"rt\",\"rt-multi-thread\",\"net\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"package\":\"tokio\",\"req\":\"^1.44.2\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"name\":\"tokio-tungstenite\",\"optional\":true,\"req\":\"^0.26.0\"},{\"kind\":\"dev\",\"name\":\"tokio-tungstenite\",\"req\":\"^0.26.0\"},{\"default_features\":false,\"features\":[\"util\"],\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"features\":[\"util\",\"timeout\",\"limit\",\"load-shed\",\"steer\",\"filter\"],\"kind\":\"dev\",\"name\":\"tower\",\"package\":\"tower\",\"req\":\"^0.5.2\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"name\":\"tower-http\",\"optional\":true,\"req\":\"^0.6.0\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"kind\":\"dev\",\"name\":\"tower-http\",\"req\":\"^0.6.0\"},{\"name\":\"tower-layer\",\"req\":\"^0.3.2\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"json\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"features\":[\"serde\",\"v4\"],\"kind\":\"dev\",\"name\":\"uuid\",\"req\":\"^1.0\"}],\"features\":{\"__private\":[\"tokio\",\"http1\",\"dep:reqwest\"],\"__private_docs\":[\"axum-core/__private_docs\",\"tower/full\",\"dep:tower-http\"],\"default\":[\"form\",\"http1\",\"json\",\"matched-path\",\"original-uri\",\"query\",\"tokio\",\"tower-log\",\"tracing\"],\"form\":[\"dep:form_urlencoded\",\"dep:serde_urlencoded\",\"dep:serde_path_to_error\"],\"http1\":[\"dep:hyper\",\"hyper?/http1\",\"hyper-util?/http1\"],\"http2\":[\"dep:hyper\",\"hyper?/http2\",\"hyper-util?/http2\"],\"json\":[\"dep:serde_json\",\"dep:serde_path_to_error\"],\"macros\":[\"dep:axum-macros\"],\"matched-path\":[],\"multipart\":[\"dep:multer\"],\"original-uri\":[],\"query\":[\"dep:form_urlencoded\",\"dep:serde_urlencoded\",\"dep:serde_path_to_error\"],\"tokio\":[\"dep:hyper-util\",\"dep:tokio\",\"tokio/net\",\"tokio/rt\",\"tower/make\",\"tokio/macros\"],\"tower-log\":[\"tower/log\"],\"tracing\":[\"dep:tracing\",\"axum-core/tracing\"],\"ws\":[\"dep:hyper\",\"tokio\",\"dep:tokio-tungstenite\",\"dep:sha1\",\"dep:base64\"]}}", + "axum-core_0.5.6": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1.2\"},{\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1.0.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.0.0\"},{\"name\":\"mime\",\"req\":\"^0.3.16\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"},{\"name\":\"sync_wrapper\",\"req\":\"^1.0.0\"},{\"features\":[\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.25.0\"},{\"features\":[\"limit\"],\"name\":\"tower-http\",\"optional\":true,\"req\":\"^0.6.0\"},{\"features\":[\"limit\"],\"kind\":\"dev\",\"name\":\"tower-http\",\"req\":\"^0.6.0\"},{\"name\":\"tower-layer\",\"req\":\"^0.3\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.37\"}],\"features\":{\"__private_docs\":[\"dep:tower-http\"],\"tracing\":[\"dep:tracing\"]}}", + "axum_0.8.8": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"axum-core\",\"req\":\"^0.5.5\"},{\"name\":\"axum-macros\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22.1\"},{\"name\":\"bytes\",\"req\":\"^1.0\"},{\"name\":\"form_urlencoded\",\"optional\":true,\"req\":\"^1.1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1.0.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"optional\":true,\"req\":\"^1.1.0\"},{\"features\":[\"client\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1.0\"},{\"features\":[\"tokio\",\"server\",\"service\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1.3\"},{\"name\":\"itoa\",\"req\":\"^1.0.5\"},{\"name\":\"matchit\",\"req\":\"=0.8.4\"},{\"name\":\"memchr\",\"req\":\"^2.4.1\"},{\"name\":\"mime\",\"req\":\"^0.3.16\"},{\"name\":\"multer\",\"optional\":true,\"req\":\"^3.0.0\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"json\",\"stream\",\"multipart\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"json\",\"stream\",\"multipart\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.211\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.221\"},{\"name\":\"serde_core\",\"req\":\"^1.0.221\"},{\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"raw_value\"],\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"serde_path_to_error\",\"optional\":true,\"req\":\"^0.1.8\"},{\"name\":\"serde_urlencoded\",\"optional\":true,\"req\":\"^0.7\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"sync_wrapper\",\"req\":\"^1.0.0\"},{\"features\":[\"serde-human-readable\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3\"},{\"features\":[\"time\"],\"name\":\"tokio\",\"optional\":true,\"package\":\"tokio\",\"req\":\"^1.44\"},{\"features\":[\"macros\",\"rt\",\"rt-multi-thread\",\"net\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"package\":\"tokio\",\"req\":\"^1.44.2\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"name\":\"tokio-tungstenite\",\"optional\":true,\"req\":\"^0.28.0\"},{\"kind\":\"dev\",\"name\":\"tokio-tungstenite\",\"req\":\"^0.28.0\"},{\"default_features\":false,\"features\":[\"util\"],\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"features\":[\"util\",\"timeout\",\"limit\",\"load-shed\",\"steer\",\"filter\"],\"kind\":\"dev\",\"name\":\"tower\",\"package\":\"tower\",\"req\":\"^0.5.2\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"name\":\"tower-http\",\"optional\":true,\"req\":\"^0.6.0\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"kind\":\"dev\",\"name\":\"tower-http\",\"req\":\"^0.6.0\"},{\"name\":\"tower-layer\",\"req\":\"^0.3.2\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"json\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"features\":[\"serde\",\"v4\"],\"kind\":\"dev\",\"name\":\"uuid\",\"req\":\"^1.0\"}],\"features\":{\"__private\":[\"tokio\",\"http1\",\"dep:reqwest\"],\"__private_docs\":[\"axum-core/__private_docs\",\"tower/full\",\"dep:serde\",\"dep:tower-http\"],\"default\":[\"form\",\"http1\",\"json\",\"matched-path\",\"original-uri\",\"query\",\"tokio\",\"tower-log\",\"tracing\"],\"form\":[\"dep:form_urlencoded\",\"dep:serde_urlencoded\",\"dep:serde_path_to_error\"],\"http1\":[\"dep:hyper\",\"hyper?/http1\",\"hyper-util?/http1\"],\"http2\":[\"dep:hyper\",\"hyper?/http2\",\"hyper-util?/http2\"],\"json\":[\"dep:serde_json\",\"dep:serde_path_to_error\"],\"macros\":[\"dep:axum-macros\"],\"matched-path\":[],\"multipart\":[\"dep:multer\"],\"original-uri\":[],\"query\":[\"dep:form_urlencoded\",\"dep:serde_urlencoded\",\"dep:serde_path_to_error\"],\"tokio\":[\"dep:hyper-util\",\"dep:tokio\",\"tokio/net\",\"tokio/rt\",\"tower/make\",\"tokio/macros\"],\"tower-log\":[\"tower/log\"],\"tracing\":[\"dep:tracing\",\"axum-core/tracing\"],\"ws\":[\"dep:hyper\",\"tokio\",\"dep:tokio-tungstenite\",\"dep:sha1\",\"dep:base64\"]}}", "backtrace_0.3.75": "{\"dependencies\":[{\"default_features\":false,\"name\":\"addr2line\",\"req\":\"^0.24.0\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"cpp_demangle\",\"optional\":true,\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.156\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"kind\":\"dev\",\"name\":\"libloading\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"miniz_oxide\",\"req\":\"^0.8\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"default_features\":false,\"features\":[\"read_core\",\"elf\",\"macho\",\"pe\",\"xcoff\",\"unaligned\",\"archive\"],\"name\":\"object\",\"req\":\"^0.36.0\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"name\":\"rustc-demangle\",\"req\":\"^0.1.24\"},{\"default_features\":false,\"name\":\"ruzstd\",\"optional\":true,\"req\":\"^0.7.3\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"windows-targets\",\"req\":\"^0.52.6\",\"target\":\"cfg(any(windows, target_os = \\\"cygwin\\\"))\"}],\"features\":{\"coresymbolication\":[],\"dbghelp\":[],\"default\":[\"std\"],\"dl_iterate_phdr\":[],\"dladdr\":[],\"kernel32\":[],\"libunwind\":[],\"ruzstd\":[\"dep:ruzstd\"],\"serialize-serde\":[\"serde\"],\"std\":[],\"unix-backtrace\":[]}}", "base64_0.22.1": "{\"dependencies\":[{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^3.2.25\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"kind\":\"dev\",\"name\":\"rstest\",\"req\":\"^0.13.0\"},{\"kind\":\"dev\",\"name\":\"rstest_reuse\",\"req\":\"^0.6.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"strum\",\"req\":\"^0.25\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "base64ct_1.8.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"base64\",\"req\":\"^0.22\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.6\"}],\"features\":{\"alloc\":[],\"std\":[\"alloc\"]}}", "beef_0.5.2": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.105\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0.105\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"const_fn\":[],\"default\":[],\"impl_serde\":[\"serde\"]}}", + "bindgen_0.72.1": "{\"dependencies\":[{\"name\":\"annotate-snippets\",\"optional\":true,\"req\":\"^0.11.4\"},{\"name\":\"bitflags\",\"req\":\"^2.2.1\"},{\"name\":\"cexpr\",\"req\":\"^0.6\"},{\"features\":[\"clang_11_0\"],\"name\":\"clang-sys\",\"req\":\"^1\"},{\"features\":[\"derive\"],\"name\":\"clap\",\"optional\":true,\"req\":\"^4\"},{\"name\":\"clap_complete\",\"optional\":true,\"req\":\"^4\"},{\"default_features\":false,\"name\":\"itertools\",\"req\":\">=0.10, <0.14\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4\"},{\"features\":[\"verbatim\"],\"name\":\"prettyplease\",\"optional\":true,\"req\":\"^0.2.7\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.80\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"std\",\"unicode-perl\"],\"name\":\"regex\",\"req\":\"^1.5.3\"},{\"name\":\"rustc-hash\",\"req\":\"^2.1.0\"},{\"name\":\"shlex\",\"req\":\"^1\"},{\"features\":[\"full\",\"extra-traits\",\"visit-mut\"],\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{\"__cli\":[\"dep:clap\",\"dep:clap_complete\"],\"__testing_only_extra_assertions\":[],\"__testing_only_libclang_16\":[],\"__testing_only_libclang_9\":[],\"default\":[\"logging\",\"prettyplease\",\"runtime\"],\"experimental\":[\"dep:annotate-snippets\"],\"logging\":[\"dep:log\"],\"runtime\":[\"clang-sys/runtime\"],\"static\":[\"clang-sys/static\"]}}", "bit-set_0.5.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bit-vec\",\"req\":\"^0.6.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.3\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"bit-vec/std\"]}}", "bit-vec_0.6.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"rand_xorshift\",\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"serde_no_std\":[\"serde/alloc\"],\"serde_std\":[\"std\",\"serde/std\"],\"std\":[]}}", "bitflags_1.3.2": "{\"dependencies\":[{\"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\":\"rustversion\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3\"}],\"features\":{\"default\":[],\"example_generated\":[],\"rustc-dep-of-std\":[\"core\",\"compiler_builtins\"]}}", @@ -610,6 +613,7 @@ "block-buffer_0.10.4": "{\"dependencies\":[{\"name\":\"generic-array\",\"req\":\"^0.14\"}],\"features\":{}}", "block-padding_0.3.3": "{\"dependencies\":[{\"name\":\"generic-array\",\"req\":\"^0.14\"}],\"features\":{\"std\":[]}}", "blocking_1.6.2": "{\"dependencies\":[{\"name\":\"async-channel\",\"req\":\"^2.0.0\"},{\"name\":\"async-task\",\"req\":\"^4.4.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-io\",\"req\":\"^0.3.28\"},{\"default_features\":false,\"name\":\"futures-lite\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"futures-lite\",\"req\":\"^2.0.0\"},{\"name\":\"piper\",\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.37\"}],\"features\":{}}", + "borsh_1.6.0": "{\"dependencies\":[{\"name\":\"ascii\",\"optional\":true,\"req\":\"^1.1\"},{\"name\":\"borsh-derive\",\"optional\":true,\"req\":\"~1.6.0\"},{\"name\":\"bson\",\"optional\":true,\"req\":\"^2\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"build\",\"name\":\"cfg_aliases\",\"req\":\"^0.2.1\"},{\"name\":\"hashbrown\",\"optional\":true,\"req\":\">=0.11, <0.16.0\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.29.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"}],\"features\":{\"de_strict_order\":[],\"default\":[\"std\"],\"derive\":[\"borsh-derive\"],\"rc\":[],\"std\":[],\"unstable__schema\":[\"derive\",\"borsh-derive/schema\"]}}", "bstr_1.12.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.7.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"dfa-search\"],\"name\":\"regex-automata\",\"optional\":true,\"req\":\"^0.4.1\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.85\"},{\"kind\":\"dev\",\"name\":\"ucd-parse\",\"req\":\"^0.1.3\"},{\"kind\":\"dev\",\"name\":\"unicode-segmentation\",\"req\":\"^1.2.1\"}],\"features\":{\"alloc\":[\"memchr/alloc\",\"serde?/alloc\"],\"default\":[\"std\",\"unicode\"],\"serde\":[\"dep:serde\"],\"std\":[\"alloc\",\"memchr/std\",\"serde?/std\"],\"unicode\":[\"dep:regex-automata\"]}}", "bumpalo_3.19.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"allocator-api2\",\"optional\":true,\"req\":\"^0.2.8\"},{\"kind\":\"dev\",\"name\":\"blink-alloc\",\"req\":\"=0.3.1\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.171\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.197\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.115\"}],\"features\":{\"allocator_api\":[],\"bench_allocator_api\":[\"allocator_api\",\"blink-alloc/nightly\"],\"boxed\":[],\"collections\":[],\"default\":[],\"serde\":[\"dep:serde\"],\"std\":[]}}", "bytemuck_1.23.1": "{\"dependencies\":[{\"name\":\"bytemuck_derive\",\"optional\":true,\"req\":\"^1.4.1\"}],\"features\":{\"aarch64_simd\":[],\"align_offset\":[],\"alloc_uninit\":[],\"avx512_simd\":[],\"const_zeroed\":[],\"derive\":[\"bytemuck_derive\"],\"extern_crate_alloc\":[],\"extern_crate_std\":[\"extern_crate_alloc\"],\"impl_core_error\":[],\"latest_stable_rust\":[\"aarch64_simd\",\"avx512_simd\",\"align_offset\",\"alloc_uninit\",\"const_zeroed\",\"derive\",\"impl_core_error\",\"min_const_generics\",\"must_cast\",\"must_cast_extra\",\"pod_saturating\",\"track_caller\",\"transparentwrapper_extra\",\"wasm_simd\",\"zeroable_atomics\",\"zeroable_maybe_uninit\",\"zeroable_unwind_fn\"],\"min_const_generics\":[],\"must_cast\":[],\"must_cast_extra\":[\"must_cast\"],\"nightly_docs\":[],\"nightly_float\":[],\"nightly_portable_simd\":[],\"nightly_stdsimd\":[],\"pod_saturating\":[],\"track_caller\":[],\"transparentwrapper_extra\":[],\"unsound_ptr_pod_impl\":[],\"wasm_simd\":[],\"zeroable_atomics\":[],\"zeroable_maybe_uninit\":[],\"zeroable_unwind_fn\":[]}}", @@ -620,8 +624,9 @@ "cassowary_0.3.0": "{\"dependencies\":[],\"features\":{}}", "castaway_0.2.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"paste\",\"req\":\"^1\"},{\"name\":\"rustversion\",\"req\":\"^1\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "cbc_0.1.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"aes\",\"req\":\"^0.8\"},{\"name\":\"cipher\",\"req\":\"^0.4.2\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"cipher\",\"req\":\"^0.4.2\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3.3\"}],\"features\":{\"alloc\":[\"cipher/alloc\"],\"block-padding\":[\"cipher/block-padding\"],\"default\":[\"block-padding\"],\"std\":[\"cipher/std\",\"alloc\"],\"zeroize\":[\"cipher/zeroize\"]}}", - "cc_1.2.30": "{\"dependencies\":[{\"default_features\":false,\"name\":\"jobserver\",\"optional\":true,\"req\":\"^0.1.30\"},{\"default_features\":false,\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.62\",\"target\":\"cfg(unix)\"},{\"name\":\"shlex\",\"req\":\"^1.3.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{\"jobserver\":[],\"parallel\":[\"dep:libc\",\"dep:jobserver\"]}}", + "cc_1.2.52": "{\"dependencies\":[{\"name\":\"find-msvc-tools\",\"req\":\"^0.1.7\"},{\"default_features\":false,\"name\":\"jobserver\",\"optional\":true,\"req\":\"^0.1.30\"},{\"default_features\":false,\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.62\",\"target\":\"cfg(unix)\"},{\"name\":\"shlex\",\"req\":\"^1.3.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{\"jobserver\":[],\"parallel\":[\"dep:libc\",\"dep:jobserver\"]}}", "cesu8_1.1.0": "{\"dependencies\":[],\"features\":{\"unstable\":[]}}", + "cexpr_0.6.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"clang-sys\",\"req\":\">=0.13.0, <0.29.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"nom\",\"req\":\"^7\"}],\"features\":{}}", "cfg-if_1.0.1": "{\"dependencies\":[{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"}],\"features\":{\"rustc-dep-of-std\":[\"core\"]}}", "cfg_aliases_0.1.1": "{\"dependencies\":[],\"features\":{}}", "cfg_aliases_0.2.1": "{\"dependencies\":[],\"features\":{}}", @@ -629,12 +634,14 @@ "chrono_0.4.43": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.0\"},{\"name\":\"defmt\",\"optional\":true,\"req\":\"^1.0.1\"},{\"features\":[\"fallback\"],\"name\":\"iana-time-zone\",\"optional\":true,\"req\":\"^0.1.45\",\"target\":\"cfg(unix)\"},{\"name\":\"js-sys\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"default_features\":false,\"name\":\"num-traits\",\"req\":\"^0.2\"},{\"name\":\"pure-rust-locales\",\"optional\":true,\"req\":\"^0.8.2\"},{\"default_features\":false,\"name\":\"rkyv\",\"optional\":true,\"req\":\"^0.7.43\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.99\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"similar-asserts\",\"req\":\"^1.6.1\"},{\"name\":\"wasm-bindgen\",\"optional\":true,\"req\":\"^0.2\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"windows-bindgen\",\"req\":\"^0.66\"},{\"name\":\"windows-link\",\"optional\":true,\"req\":\"^0.2\",\"target\":\"cfg(windows)\"}],\"features\":{\"__internal_bench\":[],\"alloc\":[],\"clock\":[\"winapi\",\"iana-time-zone\",\"now\"],\"core-error\":[],\"default\":[\"clock\",\"std\",\"oldtime\",\"wasmbind\"],\"defmt\":[\"dep:defmt\",\"pure-rust-locales?/defmt\"],\"libc\":[],\"now\":[\"std\"],\"oldtime\":[],\"rkyv\":[\"dep:rkyv\",\"rkyv/size_32\"],\"rkyv-16\":[\"dep:rkyv\",\"rkyv?/size_16\"],\"rkyv-32\":[\"dep:rkyv\",\"rkyv?/size_32\"],\"rkyv-64\":[\"dep:rkyv\",\"rkyv?/size_64\"],\"rkyv-validation\":[\"rkyv?/validation\"],\"std\":[\"alloc\"],\"unstable-locales\":[\"pure-rust-locales\"],\"wasmbind\":[\"wasm-bindgen\",\"js-sys\"],\"winapi\":[\"windows-link\"]}}", "chunked_transfer_1.5.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"}],\"features\":{}}", "cipher_0.4.4": "{\"dependencies\":[{\"name\":\"blobby\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"crypto-common\",\"req\":\"^0.1.6\"},{\"name\":\"inout\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.5\"}],\"features\":{\"alloc\":[],\"block-padding\":[\"inout/block-padding\"],\"dev\":[\"blobby\"],\"rand_core\":[\"crypto-common/rand_core\"],\"std\":[\"alloc\",\"crypto-common/std\",\"inout/std\"]}}", + "clang-sys_1.8.1": "{\"dependencies\":[{\"name\":\"glob\",\"req\":\"^0.3\"},{\"kind\":\"build\",\"name\":\"glob\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"glob\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.39\"},{\"name\":\"libloading\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\">=3.0.0, <3.7.0\"}],\"features\":{\"clang_10_0\":[\"clang_9_0\"],\"clang_11_0\":[\"clang_10_0\"],\"clang_12_0\":[\"clang_11_0\"],\"clang_13_0\":[\"clang_12_0\"],\"clang_14_0\":[\"clang_13_0\"],\"clang_15_0\":[\"clang_14_0\"],\"clang_16_0\":[\"clang_15_0\"],\"clang_17_0\":[\"clang_16_0\"],\"clang_18_0\":[\"clang_17_0\"],\"clang_3_5\":[],\"clang_3_6\":[\"clang_3_5\"],\"clang_3_7\":[\"clang_3_6\"],\"clang_3_8\":[\"clang_3_7\"],\"clang_3_9\":[\"clang_3_8\"],\"clang_4_0\":[\"clang_3_9\"],\"clang_5_0\":[\"clang_4_0\"],\"clang_6_0\":[\"clang_5_0\"],\"clang_7_0\":[\"clang_6_0\"],\"clang_8_0\":[\"clang_7_0\"],\"clang_9_0\":[\"clang_8_0\"],\"libcpp\":[],\"runtime\":[\"libloading\"],\"static\":[]}}", "clap_4.5.54": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.14\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"clap-cargo\",\"req\":\"^0.15.0\"},{\"default_features\":false,\"name\":\"clap_builder\",\"req\":\"=4.5.54\"},{\"name\":\"clap_derive\",\"optional\":true,\"req\":\"=4.5.49\"},{\"kind\":\"dev\",\"name\":\"jiff\",\"req\":\"^0.2.3\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.15\"},{\"kind\":\"dev\",\"name\":\"semver\",\"req\":\"^1.0.26\"},{\"kind\":\"dev\",\"name\":\"shlex\",\"req\":\"^1.3.0\"},{\"features\":[\"term-svg\"],\"kind\":\"dev\",\"name\":\"snapbox\",\"req\":\"^0.6.16\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.91\"},{\"default_features\":false,\"features\":[\"color-auto\",\"diff\",\"examples\"],\"kind\":\"dev\",\"name\":\"trycmd\",\"req\":\"^0.15.3\"}],\"features\":{\"cargo\":[\"clap_builder/cargo\"],\"color\":[\"clap_builder/color\"],\"debug\":[\"clap_builder/debug\",\"clap_derive?/debug\"],\"default\":[\"std\",\"color\",\"help\",\"usage\",\"error-context\",\"suggestions\"],\"deprecated\":[\"clap_builder/deprecated\",\"clap_derive?/deprecated\"],\"derive\":[\"dep:clap_derive\"],\"env\":[\"clap_builder/env\"],\"error-context\":[\"clap_builder/error-context\"],\"help\":[\"clap_builder/help\"],\"std\":[\"clap_builder/std\"],\"string\":[\"clap_builder/string\"],\"suggestions\":[\"clap_builder/suggestions\"],\"unicode\":[\"clap_builder/unicode\"],\"unstable-derive-ui-tests\":[],\"unstable-doc\":[\"clap_builder/unstable-doc\",\"derive\"],\"unstable-ext\":[\"clap_builder/unstable-ext\"],\"unstable-markdown\":[\"clap_derive/unstable-markdown\"],\"unstable-styles\":[\"clap_builder/unstable-styles\"],\"unstable-v5\":[\"clap_builder/unstable-v5\",\"clap_derive?/unstable-v5\",\"deprecated\"],\"usage\":[\"clap_builder/usage\"],\"wrap_help\":[\"clap_builder/wrap_help\"]}}", "clap_builder_4.5.54": "{\"dependencies\":[{\"name\":\"anstream\",\"optional\":true,\"req\":\"^0.6.7\"},{\"name\":\"anstyle\",\"req\":\"^1.0.8\"},{\"name\":\"backtrace\",\"optional\":true,\"req\":\"^0.3.73\"},{\"name\":\"clap_lex\",\"req\":\"^0.7.4\"},{\"kind\":\"dev\",\"name\":\"color-print\",\"req\":\"^0.3.6\"},{\"kind\":\"dev\",\"name\":\"snapbox\",\"req\":\"^0.6.16\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"},{\"name\":\"strsim\",\"optional\":true,\"req\":\"^0.11.0\"},{\"name\":\"terminal_size\",\"optional\":true,\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"unic-emoji-char\",\"req\":\"^0.9.0\"},{\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.6.0\"},{\"name\":\"unicode-width\",\"optional\":true,\"req\":\"^0.2.0\"}],\"features\":{\"cargo\":[],\"color\":[\"dep:anstream\"],\"debug\":[\"dep:backtrace\"],\"default\":[\"std\",\"color\",\"help\",\"usage\",\"error-context\",\"suggestions\"],\"deprecated\":[],\"env\":[],\"error-context\":[],\"help\":[],\"std\":[\"anstyle/std\"],\"string\":[],\"suggestions\":[\"dep:strsim\",\"error-context\"],\"unicode\":[\"dep:unicode-width\",\"dep:unicase\"],\"unstable-doc\":[\"cargo\",\"wrap_help\",\"env\",\"unicode\",\"string\",\"unstable-ext\"],\"unstable-ext\":[],\"unstable-styles\":[\"color\"],\"unstable-v5\":[\"deprecated\"],\"usage\":[],\"wrap_help\":[\"help\",\"dep:terminal_size\"]}}", "clap_complete_4.5.64": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.14\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"clap\",\"req\":\"^4.5.20\"},{\"default_features\":false,\"features\":[\"std\",\"derive\",\"help\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^4.5.20\"},{\"name\":\"clap_lex\",\"optional\":true,\"req\":\"^0.7.0\"},{\"name\":\"completest\",\"optional\":true,\"req\":\"^0.4.2\"},{\"name\":\"completest-pty\",\"optional\":true,\"req\":\"^0.5.5\"},{\"name\":\"is_executable\",\"optional\":true,\"req\":\"^1.0.1\"},{\"name\":\"shlex\",\"optional\":true,\"req\":\"^1.3.0\"},{\"features\":[\"diff\",\"dir\",\"examples\"],\"kind\":\"dev\",\"name\":\"snapbox\",\"req\":\"^0.6.0\"},{\"default_features\":false,\"features\":[\"color-auto\",\"diff\",\"examples\"],\"kind\":\"dev\",\"name\":\"trycmd\",\"req\":\"^0.15.1\"}],\"features\":{\"debug\":[\"clap/debug\"],\"default\":[],\"unstable-doc\":[\"unstable-dynamic\"],\"unstable-dynamic\":[\"dep:clap_lex\",\"dep:shlex\",\"dep:is_executable\",\"clap/unstable-ext\"],\"unstable-shell-tests\":[\"dep:completest\",\"dep:completest-pty\"]}}", "clap_derive_4.5.49": "{\"dependencies\":[{\"name\":\"anstyle\",\"optional\":true,\"req\":\"^1.0.10\"},{\"name\":\"heck\",\"req\":\"^0.5.0\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.69\"},{\"default_features\":false,\"name\":\"pulldown-cmark\",\"optional\":true,\"req\":\"^0.13.0\"},{\"name\":\"quote\",\"req\":\"^1.0.9\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0.8\"}],\"features\":{\"debug\":[],\"default\":[],\"deprecated\":[],\"raw-deprecated\":[\"deprecated\"],\"unstable-markdown\":[\"dep:pulldown-cmark\",\"dep:anstyle\"],\"unstable-v5\":[\"deprecated\"]}}", "clap_lex_0.7.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.14\"}],\"features\":{}}", "clipboard-win_5.4.1": "{\"dependencies\":[{\"name\":\"error-code\",\"req\":\"^3\",\"target\":\"cfg(windows)\"},{\"name\":\"windows-win\",\"optional\":true,\"req\":\"^3\",\"target\":\"cfg(windows)\"}],\"features\":{\"monitor\":[\"windows-win\"],\"std\":[\"error-code/std\"]}}", + "cmake_0.1.57": "{\"dependencies\":[{\"name\":\"cc\",\"req\":\"^1.2.46\"}],\"features\":{}}", "cmp_any_0.8.1": "{\"dependencies\":[],\"features\":{}}", "color-eyre_0.6.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ansi-parser\",\"req\":\"^0.8.0\"},{\"name\":\"backtrace\",\"req\":\"^0.3.59\"},{\"name\":\"color-spantrace\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"eyre\",\"req\":\"^0.6\"},{\"name\":\"indenter\",\"req\":\"^0.3.0\"},{\"name\":\"once_cell\",\"req\":\"^1.18.0\"},{\"name\":\"owo-colors\",\"req\":\"^4.0\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"thiserror\",\"req\":\"^1.0.19\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.13\"},{\"name\":\"tracing-error\",\"optional\":true,\"req\":\"^0.2.0\"},{\"features\":[\"env-filter\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3.0\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.1.1\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.15\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"}],\"features\":{\"capture-spantrace\":[\"tracing-error\",\"color-spantrace\"],\"default\":[\"track-caller\",\"capture-spantrace\"],\"issue-url\":[\"url\"],\"track-caller\":[]}}", "color-spantrace_0.3.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ansi-parser\",\"req\":\"^0.8\"},{\"name\":\"once_cell\",\"req\":\"^1.18.0\"},{\"name\":\"owo-colors\",\"req\":\"^4.0\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.29\"},{\"name\":\"tracing-core\",\"req\":\"^0.1.21\"},{\"name\":\"tracing-error\",\"req\":\"^0.2.0\"},{\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3.4\"}],\"features\":{}}", @@ -644,20 +651,29 @@ "concurrent-queue_2.5.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"cargo_bench_support\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.11\"},{\"kind\":\"dev\",\"name\":\"easy-parallel\",\"req\":\"^3.1.0\"},{\"kind\":\"dev\",\"name\":\"fastrand\",\"req\":\"^2.0.0\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"default_features\":false,\"name\":\"portable-atomic\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(target_family = \\\"wasm\\\")\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "console_0.15.11": "{\"dependencies\":[{\"name\":\"encode_unicode\",\"req\":\"^1\",\"target\":\"cfg(windows)\"},{\"name\":\"libc\",\"req\":\"^0.2.99\"},{\"name\":\"once_cell\",\"req\":\"^1.8\"},{\"default_features\":false,\"features\":[\"std\",\"bit-set\",\"break-dead-code\"],\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.4.2\"},{\"name\":\"unicode-width\",\"optional\":true,\"req\":\"^0.2\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Console\",\"Win32_Storage_FileSystem\",\"Win32_UI_Input_KeyboardAndMouse\"],\"name\":\"windows-sys\",\"req\":\"^0.59\",\"target\":\"cfg(windows)\"}],\"features\":{\"ansi-parsing\":[],\"default\":[\"unicode-width\",\"ansi-parsing\"],\"windows-console-colors\":[\"ansi-parsing\"]}}", "const-hex_1.17.0": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"cpufeatures\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_arch = \\\"x86\\\", target_arch = \\\"x86_64\\\"))\"},{\"kind\":\"dev\",\"name\":\"divan\",\"package\":\"codspeed-divan-compat\",\"req\":\"^3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"faster-hex\",\"req\":\"^0.10.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"~0.4.2\"},{\"default_features\":false,\"name\":\"proptest\",\"optional\":true,\"req\":\"^1.4\"},{\"kind\":\"dev\",\"name\":\"rustc-hex\",\"req\":\"^2.1\"},{\"default_features\":false,\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"__fuzzing\":[\"dep:proptest\",\"std\"],\"alloc\":[\"serde_core?/alloc\",\"proptest?/alloc\"],\"core-error\":[],\"default\":[\"std\"],\"force-generic\":[],\"hex\":[],\"nightly\":[],\"portable-simd\":[],\"serde\":[\"dep:serde_core\"],\"std\":[\"serde_core?/std\",\"proptest?/std\",\"alloc\"]}}", + "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\"]}}", "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\"]}}", "core-foundation-sys_0.8.7": "{\"dependencies\":[],\"features\":{\"default\":[\"link\"],\"link\":[],\"mac_os_10_7_support\":[],\"mac_os_10_8_features\":[]}}", "core-foundation_0.10.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"core-foundation-sys\",\"req\":\"^0.8\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"default\":[\"link\"],\"link\":[\"core-foundation-sys/link\"],\"mac_os_10_7_support\":[\"core-foundation-sys/mac_os_10_7_support\"],\"mac_os_10_8_features\":[\"core-foundation-sys/mac_os_10_8_features\"],\"with-uuid\":[\"dep:uuid\"]}}", "core-foundation_0.9.4": "{\"dependencies\":[{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^0.5\"}],\"features\":{\"default\":[\"link\"],\"link\":[\"core-foundation-sys/link\"],\"mac_os_10_7_support\":[\"core-foundation-sys/mac_os_10_7_support\"],\"mac_os_10_8_features\":[\"core-foundation-sys/mac_os_10_8_features\"],\"with-chrono\":[\"chrono\"],\"with-uuid\":[\"uuid\"]}}", "cpufeatures_0.2.17": "{\"dependencies\":[{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"aarch64-linux-android\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(target_arch = \\\"aarch64\\\", target_os = \\\"linux\\\"))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(target_arch = \\\"aarch64\\\", target_vendor = \\\"apple\\\"))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(target_arch = \\\"loongarch64\\\", target_os = \\\"linux\\\"))\"}],\"features\":{}}", + "crc-catalog_2.4.0": "{\"dependencies\":[],\"features\":{}}", "crc32fast_1.5.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"nightly\":[],\"std\":[]}}", + "crc_3.4.0": "{\"dependencies\":[{\"name\":\"crc-catalog\",\"req\":\"^2.4.0\"}],\"features\":{}}", + "critical-section_1.2.0": "{\"dependencies\":[],\"features\":{\"restore-state-bool\":[],\"restore-state-none\":[],\"restore-state-u16\":[],\"restore-state-u32\":[],\"restore-state-u64\":[],\"restore-state-u8\":[],\"restore-state-usize\":[],\"std\":[\"restore-state-bool\"]}}", "crossbeam-channel_0.5.15": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.13.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"signal-hook\",\"req\":\"^0.3\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"crossbeam-utils/std\"]}}", "crossbeam-deque_0.8.6": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-epoch\",\"req\":\"^0.9.17\"},{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"crossbeam-epoch/std\",\"crossbeam-utils/std\"]}}", "crossbeam-epoch_0.9.18": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"name\":\"loom-crate\",\"optional\":true,\"package\":\"loom\",\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"loom\":[\"loom-crate\",\"crossbeam-utils/loom\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", + "crossbeam-queue_0.3.12": "{\"dependencies\":[{\"default_features\":false,\"name\":\"crossbeam-utils\",\"req\":\"^0.8.18\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"nightly\":[\"crossbeam-utils/nightly\"],\"std\":[\"alloc\",\"crossbeam-utils/std\"]}}", "crossbeam-utils_0.8.21": "{\"dependencies\":[{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"nightly\":[],\"std\":[]}}", "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.6": "{\"dependencies\":[{\"features\":[\"more_lengths\"],\"name\":\"generic-array\",\"req\":\"^0.14.4\"},{\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"typenum\",\"req\":\"^1.14\"}],\"features\":{\"getrandom\":[\"rand_core/getrandom\"],\"std\":[]}}", + "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\":[]}}", "ctor_0.1.26": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"libc-print\",\"req\":\"^0.1.20\"},{\"name\":\"quote\",\"req\":\"^1.0.20\"},{\"default_features\":false,\"features\":[\"full\",\"parsing\",\"printing\",\"proc-macro\"],\"name\":\"syn\",\"req\":\"^1.0.98\"}],\"features\":{}}", "ctor_0.6.3": "{\"dependencies\":[{\"name\":\"ctor-proc-macro\",\"optional\":true,\"req\":\"=0.0.7\"},{\"default_features\":false,\"name\":\"dtor\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"libc-print\",\"req\":\"^0.1.20\"}],\"features\":{\"__no_warn_on_missing_unsafe\":[\"dtor?/__no_warn_on_missing_unsafe\"],\"default\":[\"dtor\",\"proc_macro\",\"__no_warn_on_missing_unsafe\"],\"dtor\":[\"dep:dtor\"],\"proc_macro\":[\"dep:ctor-proc-macro\",\"dtor?/proc_macro\"],\"used_linker\":[\"dtor?/used_linker\"]}}", @@ -710,6 +726,8 @@ "encoding_rs_0.8.35": "{\"dependencies\":[{\"name\":\"any_all_workaround\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.0\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\"],\"fast-big5-hanzi-encode\":[],\"fast-gb-hanzi-encode\":[],\"fast-hangul-encode\":[],\"fast-hanja-encode\":[],\"fast-kanji-encode\":[],\"fast-legacy-encode\":[\"fast-hangul-encode\",\"fast-hanja-encode\",\"fast-kanji-encode\",\"fast-gb-hanzi-encode\",\"fast-big5-hanzi-encode\"],\"less-slow-big5-hanzi-encode\":[],\"less-slow-gb-hanzi-encode\":[],\"less-slow-kanji-encode\":[],\"simd-accel\":[\"any_all_workaround\"]}}", "endi_1.1.0": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "endian-type_0.1.2": "{\"dependencies\":[],\"features\":{}}", + "endian-type_0.2.0": "{\"dependencies\":[],\"features\":{}}", + "enum-as-inner_0.6.1": "{\"dependencies\":[{\"name\":\"heck\",\"req\":\"^0.5\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "enumflags2_0.7.12": "{\"dependencies\":[{\"name\":\"enumflags2_derive\",\"req\":\"=0.7.12\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.0\"}],\"features\":{\"std\":[]}}", "enumflags2_derive_0.7.12": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"parsing\",\"printing\",\"derive\",\"proc-macro\"],\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "env-flags_0.1.1": "{\"dependencies\":[],\"features\":{}}", @@ -720,6 +738,7 @@ "erased-serde_0.3.31": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.13\"},{\"default_features\":false,\"name\":\"serde\",\"req\":\"^1.0.166\"},{\"kind\":\"dev\",\"name\":\"serde_cbor\",\"req\":\"^0.11.2\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0.166\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.99\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.83\"}],\"features\":{\"alloc\":[\"serde/alloc\"],\"default\":[\"std\"],\"std\":[\"serde/std\"],\"unstable-debug\":[]}}", "errno_0.3.13": "{\"dependencies\":[{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(target_os=\\\"hermit\\\")\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(target_os=\\\"wasi\\\")\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Diagnostics_Debug\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <=0.60\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"libc/std\"]}}", "error-code_3.3.2": "{\"dependencies\":[],\"features\":{\"std\":[]}}", + "etcetera_0.8.0": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"home\",\"req\":\"^0.5\"},{\"features\":[\"Win32_Foundation\",\"Win32_UI_Shell\"],\"name\":\"windows-sys\",\"req\":\"^0.48\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "event-listener-strategy_0.5.4": "{\"dependencies\":[{\"default_features\":false,\"name\":\"event-listener\",\"req\":\"^5.0.0\"},{\"kind\":\"dev\",\"name\":\"futures-lite\",\"req\":\"^2.0.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.12\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.37\",\"target\":\"cfg(target_family = \\\"wasm\\\")\"}],\"features\":{\"default\":[\"std\"],\"loom\":[\"event-listener/loom\"],\"portable-atomic\":[\"event-listener/portable-atomic\"],\"std\":[\"event-listener/std\"]}}", "event-listener_5.4.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"concurrent-queue\",\"req\":\"^2.4.0\"},{\"default_features\":false,\"features\":[\"cargo_bench_support\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"critical-section\",\"optional\":true,\"req\":\"^1.2.0\"},{\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"critical-section\",\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"futures-lite\",\"req\":\"^2.0.0\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"name\":\"parking\",\"optional\":true,\"req\":\"^2.0.0\",\"target\":\"cfg(not(target_family = \\\"wasm\\\"))\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.12\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"portable-atomic-util\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"portable_atomic_crate\",\"optional\":true,\"package\":\"portable-atomic\",\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"try-lock\",\"req\":\"^0.2.5\"},{\"kind\":\"dev\",\"name\":\"waker-fn\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(target_family = \\\"wasm\\\")\"}],\"features\":{\"default\":[\"std\"],\"loom\":[\"concurrent-queue/loom\",\"parking?/loom\",\"dep:loom\"],\"portable-atomic\":[\"portable-atomic-util\",\"portable_atomic_crate\",\"concurrent-queue/portable-atomic\"],\"std\":[\"concurrent-queue/std\",\"parking\"]}}", "eventsource-stream_0.2.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"http\",\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"nom\",\"req\":\"^7.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.8\"},{\"features\":[\"stream\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.11\"},{\"features\":[\"macros\",\"rt\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.2\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"futures-core/std\",\"nom/std\"]}}", @@ -730,21 +749,30 @@ "fd-lock_4.0.4": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"features\":[\"fs\"],\"name\":\"rustix\",\"req\":\"^1.0.0\",\"target\":\"cfg(unix)\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.0.8\"},{\"features\":[\"Win32_Foundation\",\"Win32_Storage_FileSystem\",\"Win32_System_IO\"],\"name\":\"windows-sys\",\"req\":\">=0.52.0, <0.60.0\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "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\":{}}", "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\":{}}", + "find-msvc-tools_0.1.7": "{\"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\":{}}", "fixed_decimal_0.7.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"displaydoc\",\"req\":\"^0.2.3\"},{\"features\":[\"js\"],\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand_distr\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rand_pcg\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"small\"],\"name\":\"ryu\",\"optional\":true,\"req\":\"^1.0.5\"},{\"default_features\":false,\"name\":\"smallvec\",\"req\":\"^1.10.0\"},{\"default_features\":false,\"name\":\"writeable\",\"req\":\"^0.6.0\"}],\"features\":{\"experimental\":[],\"ryu\":[\"dep:ryu\"]}}", "fixedbitset_0.4.2": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "flate2_1.1.2": "{\"dependencies\":[{\"name\":\"cloudflare-zlib-sys\",\"optional\":true,\"req\":\"^0.3.5\"},{\"name\":\"crc32fast\",\"req\":\"^1.2.0\"},{\"name\":\"libz-ng-sys\",\"optional\":true,\"req\":\"^1.1.16\"},{\"default_features\":false,\"features\":[\"std\",\"rust-allocator\"],\"name\":\"libz-rs-sys\",\"optional\":true,\"req\":\"^0.5.1\"},{\"default_features\":false,\"name\":\"libz-sys\",\"optional\":true,\"req\":\"^1.1.20\"},{\"default_features\":false,\"features\":[\"with-alloc\"],\"name\":\"miniz_oxide\",\"req\":\"^0.8.5\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(target_os = \\\"emscripten\\\")))\"},{\"default_features\":false,\"features\":[\"with-alloc\"],\"name\":\"miniz_oxide\",\"optional\":true,\"req\":\"^0.8.5\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"}],\"features\":{\"any_impl\":[],\"any_zlib\":[\"any_impl\"],\"cloudflare_zlib\":[\"any_zlib\",\"cloudflare-zlib-sys\"],\"default\":[\"rust_backend\"],\"miniz-sys\":[\"rust_backend\"],\"rust_backend\":[\"miniz_oxide\",\"any_impl\"],\"zlib\":[\"any_zlib\",\"libz-sys\"],\"zlib-default\":[\"any_zlib\",\"libz-sys/default\"],\"zlib-ng\":[\"any_zlib\",\"libz-ng-sys\"],\"zlib-ng-compat\":[\"zlib\",\"libz-sys/zlib-ng\"],\"zlib-rs\":[\"any_zlib\",\"libz-rs-sys\"]}}", "float-cmp_0.10.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"num-traits\",\"optional\":true,\"req\":\"^0.2.1\"}],\"features\":{\"default\":[\"ratio\"],\"ratio\":[\"num-traits\"],\"std\":[]}}", + "flume_0.11.1": "{\"dependencies\":[{\"features\":[\"attributes\",\"unstable\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.13.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"kind\":\"dev\",\"name\":\"crossbeam-channel\",\"req\":\"^0.5.5\"},{\"kind\":\"dev\",\"name\":\"crossbeam-utils\",\"req\":\"^0.8.10\"},{\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"optional\":true,\"req\":\"^0.3\"},{\"features\":[\"js\"],\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.2.15\"},{\"features\":[\"getrandom\"],\"name\":\"nanorand\",\"optional\":true,\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.3\"},{\"features\":[\"mutex\"],\"name\":\"spin1\",\"package\":\"spin\",\"req\":\"^0.9.8\"},{\"features\":[\"rt\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.16.1\"},{\"kind\":\"dev\",\"name\":\"waker-fn\",\"req\":\"^1.1.0\"}],\"features\":{\"async\":[\"futures-sink\",\"futures-core\"],\"default\":[\"async\",\"select\",\"eventual-fairness\"],\"eventual-fairness\":[\"select\",\"nanorand\"],\"select\":[],\"spin\":[]}}", + "flume_0.12.0": "{\"dependencies\":[{\"features\":[\"attributes\",\"unstable\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.13.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"kind\":\"dev\",\"name\":\"crossbeam-channel\",\"req\":\"^0.5.5\"},{\"kind\":\"dev\",\"name\":\"crossbeam-utils\",\"req\":\"^0.8.10\"},{\"features\":[\"std\",\"js\"],\"name\":\"fastrand\",\"optional\":true,\"req\":\"^2.3\"},{\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"optional\":true,\"req\":\"^0.3\"},{\"features\":[\"js\"],\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.2.15\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.3\"},{\"features\":[\"mutex\"],\"name\":\"spin1\",\"package\":\"spin\",\"req\":\"^0.9.8\"},{\"features\":[\"rt\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.16.1\"},{\"kind\":\"dev\",\"name\":\"waker-fn\",\"req\":\"^1.1.0\"}],\"features\":{\"async\":[\"futures-sink\",\"futures-core\"],\"default\":[\"async\",\"select\",\"eventual-fairness\"],\"eventual-fairness\":[\"select\",\"fastrand\"],\"select\":[],\"spin\":[]}}", "fnv_1.0.7": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "foldhash_0.1.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"chrono\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"hashbrown\",\"req\":\"^0.14\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"uuid\",\"req\":\"^1.8\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "foldhash_0.2.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"chrono\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"hashbrown\",\"req\":\"^0.15\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rapidhash\",\"req\":\"^3.1.0\"},{\"kind\":\"dev\",\"name\":\"uuid\",\"req\":\"^1.8\"}],\"features\":{\"default\":[\"std\"],\"nightly\":[],\"std\":[]}}", + "foreign-types-macros_0.2.3": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{\"std\":[]}}", "foreign-types-shared_0.1.1": "{\"dependencies\":[],\"features\":{}}", + "foreign-types-shared_0.3.1": "{\"dependencies\":[],\"features\":{}}", "foreign-types_0.3.2": "{\"dependencies\":[{\"name\":\"foreign-types-shared\",\"req\":\"^0.1\"}],\"features\":{}}", + "foreign-types_0.5.0": "{\"dependencies\":[{\"name\":\"foreign-types-macros\",\"req\":\"^0.2\"},{\"name\":\"foreign-types-shared\",\"req\":\"^0.3\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"foreign-types-macros/std\"]}}", "form_urlencoded_1.2.1": "{\"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\":{}}", + "fslock_0.2.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.66\",\"target\":\"cfg(unix)\"},{\"features\":[\"minwindef\",\"minwinbase\",\"winbase\",\"errhandlingapi\",\"winerror\",\"winnt\",\"synchapi\",\"handleapi\",\"fileapi\",\"processthreadsapi\"],\"name\":\"winapi\",\"req\":\"^0.3.8\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "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\"]}}", + "futures-intrusive_0.5.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.4\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"crossbeam\",\"req\":\"^0.7\"},{\"features\":[\"async-await\"],\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"futures-test\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4.0\"},{\"name\":\"lock_api\",\"req\":\"^0.4.1\"},{\"name\":\"parking_lot\",\"optional\":true,\"req\":\"^0.12.0\"},{\"kind\":\"dev\",\"name\":\"pin-utils\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"signal-hook\",\"req\":\"^0.1.11\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.14\"}],\"features\":{\"alloc\":[\"futures-core/alloc\"],\"default\":[\"std\"],\"std\":[\"alloc\",\"parking_lot\"]}}", "futures-io_0.3.31": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[],\"unstable\":[]}}", "futures-lite_2.6.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"fastrand\",\"optional\":true,\"req\":\"^2.0.0\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.5\"},{\"name\":\"futures-io\",\"optional\":true,\"req\":\"^0.3.5\"},{\"name\":\"memchr\",\"optional\":true,\"req\":\"^2.3.3\"},{\"name\":\"parking\",\"optional\":true,\"req\":\"^2.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.0\"},{\"kind\":\"dev\",\"name\":\"spin_on\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"waker-fn\",\"req\":\"^1.0.0\"}],\"features\":{\"alloc\":[],\"default\":[\"race\",\"std\"],\"race\":[\"fastrand\"],\"std\":[\"alloc\",\"fastrand/std\",\"futures-io\",\"parking\"]}}", "futures-macro_0.3.31": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0.52\"}],\"features\":{}}", @@ -753,6 +781,7 @@ "futures-util_0.3.31": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-io\",\"optional\":true,\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-macro\",\"optional\":true,\"req\":\"=0.3.31\"},{\"default_features\":false,\"name\":\"futures-sink\",\"optional\":true,\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-task\",\"req\":\"^0.3.31\"},{\"name\":\"futures_01\",\"optional\":true,\"package\":\"futures\",\"req\":\"^0.1.25\"},{\"name\":\"memchr\",\"optional\":true,\"req\":\"^2.2\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.6\"},{\"name\":\"pin-utils\",\"req\":\"^0.1.0\"},{\"name\":\"slab\",\"optional\":true,\"req\":\"^0.4.2\"},{\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^0.1.11\"},{\"name\":\"tokio-io\",\"optional\":true,\"req\":\"^0.1.9\"}],\"features\":{\"alloc\":[\"futures-core/alloc\",\"futures-task/alloc\"],\"async-await\":[],\"async-await-macro\":[\"async-await\",\"futures-macro\"],\"bilock\":[],\"cfg-target-has-atomic\":[],\"channel\":[\"std\",\"futures-channel\"],\"compat\":[\"std\",\"futures_01\"],\"default\":[\"std\",\"async-await\",\"async-await-macro\"],\"io\":[\"std\",\"futures-io\",\"memchr\"],\"io-compat\":[\"io\",\"compat\",\"tokio-io\"],\"portable-atomic\":[\"futures-core/portable-atomic\"],\"sink\":[\"futures-sink\"],\"std\":[\"alloc\",\"futures-core/std\",\"futures-task/std\",\"slab\"],\"unstable\":[\"futures-core/unstable\",\"futures-task/unstable\"],\"write-all-vectored\":[\"io\"]}}", "futures_0.3.31": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert_matches\",\"req\":\"^1.3.0\"},{\"default_features\":false,\"features\":[\"sink\"],\"name\":\"futures-channel\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-executor\",\"optional\":true,\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-io\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-sink\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-task\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"features\":[\"sink\"],\"name\":\"futures-util\",\"req\":\"^0.3.31\"},{\"kind\":\"dev\",\"name\":\"pin-project\",\"req\":\"^1.0.11\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^0.1.11\"}],\"features\":{\"alloc\":[\"futures-core/alloc\",\"futures-task/alloc\",\"futures-sink/alloc\",\"futures-channel/alloc\",\"futures-util/alloc\"],\"async-await\":[\"futures-util/async-await\",\"futures-util/async-await-macro\"],\"bilock\":[\"futures-util/bilock\"],\"cfg-target-has-atomic\":[],\"compat\":[\"std\",\"futures-util/compat\"],\"default\":[\"std\",\"async-await\",\"executor\"],\"executor\":[\"std\",\"futures-executor/std\"],\"io-compat\":[\"compat\",\"futures-util/io-compat\"],\"std\":[\"alloc\",\"futures-core/std\",\"futures-task/std\",\"futures-io/std\",\"futures-sink/std\",\"futures-util/std\",\"futures-util/io\",\"futures-util/channel\"],\"thread-pool\":[\"executor\",\"futures-executor/thread-pool\"],\"unstable\":[\"futures-core/unstable\",\"futures-task/unstable\",\"futures-channel/unstable\",\"futures-io/unstable\",\"futures-util/unstable\"],\"write-all-vectored\":[\"futures-util/write-all-vectored\"]}}", "fxhash_0.2.1": "{\"dependencies\":[{\"name\":\"byteorder\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"kind\":\"dev\",\"name\":\"seahash\",\"req\":\"^3.0.5\"}],\"features\":{}}", + "generator_0.8.8": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"libc\",\"req\":\"^0.2.100\",\"target\":\"cfg(unix)\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"kind\":\"build\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"name\":\"windows-link\",\"req\":\">=0.1, <=0.2\",\"target\":\"cfg(windows)\"},{\"name\":\"windows-result\",\"req\":\">=0.3.1, <=0.4\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "generic-array_0.14.7": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"typenum\",\"req\":\"^1.12\"},{\"kind\":\"build\",\"name\":\"version_check\",\"req\":\"^0.9\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"more_lengths\":[]}}", "gethostname_0.4.3": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.141\",\"target\":\"cfg(not(windows))\"},{\"name\":\"windows-targets\",\"req\":\"^0.48\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "getopts_0.2.23": "{\"dependencies\":[{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"std\",\"optional\":true,\"package\":\"rustc-std-workspace-std\",\"req\":\"^1.0\"},{\"name\":\"unicode-width\",\"req\":\"^0.2.0\"}],\"features\":{\"rustc-dep-of-std\":[\"unicode-width/rustc-dep-of-std\",\"std\",\"core\"]}}", @@ -761,24 +790,31 @@ "gimli_0.31.1": "{\"dependencies\":[{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.2\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"name\":\"fallible-iterator\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.0.0\"},{\"default_features\":false,\"name\":\"stable_deref_trait\",\"optional\":true,\"req\":\"^1.1.0\"},{\"kind\":\"dev\",\"name\":\"test-assembler\",\"req\":\"^0.1.3\"}],\"features\":{\"default\":[\"read-all\",\"write\"],\"endian-reader\":[\"read\",\"dep:stable_deref_trait\"],\"fallible-iterator\":[\"dep:fallible-iterator\"],\"read\":[\"read-core\"],\"read-all\":[\"read\",\"std\",\"fallible-iterator\",\"endian-reader\"],\"read-core\":[],\"rustc-dep-of-std\":[\"dep:core\",\"dep:alloc\",\"dep:compiler_builtins\"],\"std\":[\"fallible-iterator?/std\",\"stable_deref_trait?/std\"],\"write\":[\"dep:indexmap\"]}}", "git+https://github.com/JakkuSakura/tokio-tungstenite?rev=2ae536b0de793f3ddf31fc2f22d445bf1ef2023d#2ae536b0de793f3ddf31fc2f22d445bf1ef2023d_tokio-tungstenite": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"sink\",\"std\"],\"name\":\"futures-util\",\"optional\":false},{\"name\":\"log\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\"},{\"default_features\":false,\"features\":[],\"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\":false,\"features\":[\"io-util\"],\"name\":\"tokio\",\"optional\":false},{\"default_features\":true,\"features\":[],\"name\":\"tokio-native-tls\",\"optional\":true},{\"default_features\":false,\"features\":[],\"name\":\"tokio-rustls\",\"optional\":true},{\"default_features\":false,\"features\":[],\"name\":\"tungstenite\",\"optional\":false},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\",\"tokio-rustls\",\"stream\",\"tungstenite/__rustls-tls\",\"handshake\"],\"connect\":[\"stream\",\"tokio/net\",\"handshake\"],\"default\":[\"connect\",\"handshake\"],\"handshake\":[\"tungstenite/handshake\"],\"native-tls\":[\"native-tls-crate\",\"tokio-native-tls\",\"stream\",\"tungstenite/native-tls\",\"handshake\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\",\"tungstenite/native-tls-vendored\"],\"proxy\":[\"tungstenite/proxy\",\"tokio/net\",\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"stream\":[],\"url\":[\"tungstenite/url\"]},\"strip_prefix\":\"\"}", "git+https://github.com/JakkuSakura/tungstenite-rs?rev=f514de8644821113e5d18a027d6d28a5c8cc0a6e#f514de8644821113e5d18a027d6d28a5c8cc0a6e_tungstenite": "{\"dependencies\":[{\"name\":\"bytes\"},{\"default_features\":true,\"features\":[],\"name\":\"data-encoding\",\"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\"],\"handshake\":[\"data-encoding\",\"http\",\"httparse\",\"sha1\"],\"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\":\"\"}", + "git+https://github.com/helix-editor/nucleo.git?rev=4253de9faabb4e5c6d81d946a5e35a90f87347ee#4253de9faabb4e5c6d81d946a5e35a90f87347ee_nucleo": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"nucleo-matcher\",\"optional\":false},{\"default_features\":true,\"features\":[\"send_guard\",\"arc_lock\"],\"name\":\"parking_lot\",\"optional\":false},{\"name\":\"rayon\"}],\"features\":{},\"strip_prefix\":\"\"}", + "git+https://github.com/helix-editor/nucleo.git?rev=4253de9faabb4e5c6d81d946a5e35a90f87347ee#4253de9faabb4e5c6d81d946a5e35a90f87347ee_nucleo-matcher": "{\"dependencies\":[{\"name\":\"memchr\"},{\"default_features\":true,\"features\":[],\"name\":\"unicode-segmentation\",\"optional\":true}],\"features\":{\"default\":[\"unicode-normalization\",\"unicode-casefold\",\"unicode-segmentation\"],\"unicode-casefold\":[],\"unicode-normalization\":[],\"unicode-segmentation\":[\"dep:unicode-segmentation\"]},\"strip_prefix\":\"matcher\"}", "git+https://github.com/nornagon/crossterm?branch=nornagon%2Fcolor-query#87db8bfa6dc99427fd3b071681b07fc31c6ce995_crossterm": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"bitflags\",\"optional\":false},{\"default_features\":false,\"features\":[],\"name\":\"futures-core\",\"optional\":true},{\"name\":\"parking_lot\"},{\"default_features\":true,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"filedescriptor\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":false,\"features\":[],\"name\":\"libc\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[\"os-poll\"],\"name\":\"mio\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":false,\"features\":[\"std\",\"stdio\",\"termios\"],\"name\":\"rustix\",\"optional\":false,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[],\"name\":\"signal-hook\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[\"support-v1_0\"],\"name\":\"signal-hook-mio\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[],\"name\":\"crossterm_winapi\",\"optional\":true,\"target\":\"cfg(windows)\"},{\"default_features\":true,\"features\":[\"winuser\",\"winerror\"],\"name\":\"winapi\",\"optional\":true,\"target\":\"cfg(windows)\"}],\"features\":{\"bracketed-paste\":[],\"default\":[\"bracketed-paste\",\"windows\",\"events\"],\"event-stream\":[\"dep:futures-core\",\"events\"],\"events\":[\"dep:mio\",\"dep:signal-hook\",\"dep:signal-hook-mio\"],\"serde\":[\"dep:serde\",\"bitflags/serde\"],\"use-dev-tty\":[\"filedescriptor\",\"rustix/process\"],\"windows\":[\"dep:winapi\",\"dep:crossterm_winapi\"]},\"strip_prefix\":\"\"}", "git+https://github.com/nornagon/ratatui?branch=nornagon-v0.29.0-patch#9b2ad1298408c45918ee9f8241a6f95498cdbed2_ratatui": "{\"dependencies\":[{\"name\":\"bitflags\"},{\"name\":\"cassowary\"},{\"name\":\"compact_str\"},{\"default_features\":true,\"features\":[],\"name\":\"crossterm\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"document-features\",\"optional\":true},{\"name\":\"indoc\"},{\"name\":\"instability\"},{\"name\":\"itertools\"},{\"name\":\"lru\"},{\"default_features\":true,\"features\":[],\"name\":\"palette\",\"optional\":true},{\"name\":\"paste\"},{\"default_features\":true,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true},{\"default_features\":true,\"features\":[\"derive\"],\"name\":\"strum\",\"optional\":false},{\"default_features\":true,\"features\":[],\"name\":\"termwiz\",\"optional\":true},{\"default_features\":true,\"features\":[\"local-offset\"],\"name\":\"time\",\"optional\":true},{\"name\":\"unicode-segmentation\"},{\"name\":\"unicode-truncate\"},{\"name\":\"unicode-width\"},{\"default_features\":true,\"features\":[],\"name\":\"termion\",\"optional\":true,\"target\":\"cfg(not(windows))\"}],\"features\":{\"all-widgets\":[\"widget-calendar\"],\"crossterm\":[\"dep:crossterm\"],\"default\":[\"crossterm\",\"underline-color\"],\"macros\":[],\"palette\":[\"dep:palette\"],\"scrolling-regions\":[],\"serde\":[\"dep:serde\",\"bitflags/serde\",\"compact_str/serde\"],\"termion\":[\"dep:termion\"],\"termwiz\":[\"dep:termwiz\"],\"underline-color\":[\"dep:crossterm\"],\"unstable\":[\"unstable-rendered-line-info\",\"unstable-widget-ref\",\"unstable-backend-writer\"],\"unstable-backend-writer\":[],\"unstable-rendered-line-info\":[],\"unstable-widget-ref\":[],\"widget-calendar\":[\"dep:time\"]},\"strip_prefix\":\"\"}", - "globset_0.4.16": "{\"dependencies\":[{\"name\":\"aho-corasick\",\"req\":\"^1.1.1\"},{\"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\":{\"default\":[\"log\"],\"serde1\":[\"serde\"],\"simd-accel\":[]}}", + "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.4.11": "{\"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\":\"^0.26\"}],\"features\":{\"stream\":[],\"unstable\":[]}}", "half_2.6.0": "{\"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\"],\"name\":\"zerocopy\",\"optional\":true,\"req\":\"^0.8.23\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"rand_distr\":[\"dep:rand\",\"dep:rand_distr\"],\"std\":[\"alloc\"],\"use-intrinsics\":[]}}", "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\":[]}}", "hashbrown_0.14.5": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ahash\",\"optional\":true,\"req\":\"^0.8.7\"},{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"allocator-api2\",\"optional\":true,\"req\":\"^0.2.9\"},{\"features\":[\"allocator-api2\"],\"kind\":\"dev\",\"name\":\"bumpalo\",\"req\":\"^3.13.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\"},{\"default_features\":false,\"name\":\"equivalent\",\"optional\":true,\"req\":\"^1.0\"},{\"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,\"features\":[\"alloc\"],\"name\":\"rkyv\",\"optional\":true,\"req\":\"^0.7.42\"},{\"features\":[\"validation\"],\"kind\":\"dev\",\"name\":\"rkyv\",\"req\":\"^0.7.42\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.25\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"ahash\",\"inline-more\",\"allocator-api2\"],\"inline-more\":[],\"nightly\":[\"allocator-api2?/nightly\",\"bumpalo/allocator_api\"],\"raw\":[],\"rustc-dep-of-std\":[\"nightly\",\"core\",\"compiler_builtins\",\"alloc\",\"rustc-internal-api\"],\"rustc-internal-api\":[]}}", "hashbrown_0.15.4": "{\"dependencies\":[{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"allocator-api2\",\"optional\":true,\"req\":\"^0.2.9\"},{\"features\":[\"allocator-api2\"],\"kind\":\"dev\",\"name\":\"bumpalo\",\"req\":\"^3.13.0\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.1\"},{\"default_features\":false,\"name\":\"equivalent\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"fnv\",\"req\":\"^1.0.7\"},{\"default_features\":false,\"name\":\"foldhash\",\"optional\":true,\"req\":\"^0.1.2\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9.0\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.2\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.2\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.25\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"default-hasher\",\"inline-more\",\"allocator-api2\",\"equivalent\",\"raw-entry\"],\"default-hasher\":[\"dep:foldhash\"],\"inline-more\":[],\"nightly\":[\"bumpalo/allocator_api\"],\"raw-entry\":[],\"rustc-dep-of-std\":[\"nightly\",\"core\",\"alloc\",\"rustc-internal-api\"],\"rustc-internal-api\":[]}}", "hashbrown_0.16.0": "{\"dependencies\":[{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"allocator-api2\",\"optional\":true,\"req\":\"^0.2.9\"},{\"features\":[\"allocator-api2\"],\"kind\":\"dev\",\"name\":\"bumpalo\",\"req\":\"^3.13.0\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.1\"},{\"default_features\":false,\"name\":\"equivalent\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"fnv\",\"req\":\"^1.0.7\"},{\"default_features\":false,\"name\":\"foldhash\",\"optional\":true,\"req\":\"^0.2.0\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9.0\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.2\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.2\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.25\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"default-hasher\",\"inline-more\",\"allocator-api2\",\"equivalent\",\"raw-entry\"],\"default-hasher\":[\"dep:foldhash\"],\"inline-more\":[],\"nightly\":[\"foldhash?/nightly\",\"bumpalo/allocator_api\"],\"raw-entry\":[],\"rustc-dep-of-std\":[\"nightly\",\"core\",\"alloc\",\"rustc-internal-api\"],\"rustc-internal-api\":[]}}", + "hashlink_0.10.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"default-hasher\",\"inline-more\"],\"name\":\"hashbrown\",\"req\":\"^0.15\"},{\"kind\":\"dev\",\"name\":\"rustc-hash\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"serde_impl\":[\"serde\"]}}", "heck_0.5.0": "{\"dependencies\":[],\"features\":{}}", "hermit-abi_0.5.2": "{\"dependencies\":[{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"}],\"features\":{\"default\":[],\"rustc-dep-of-std\":[\"core\",\"alloc\"]}}", "hex_0.4.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"faster-hex\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"rustc-hex\",\"req\":\"^2.1\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"version-sync\",\"req\":\"^0.9\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", + "hickory-proto_0.25.2": "{\"dependencies\":[{\"name\":\"async-trait\",\"req\":\"^0.1.43\"},{\"default_features\":false,\"features\":[\"prebuilt-nasm\"],\"name\":\"aws-lc-rs\",\"optional\":true,\"req\":\"^1.12.3\"},{\"name\":\"backtrace\",\"optional\":true,\"req\":\"^0.3.50\"},{\"name\":\"bitflags\",\"optional\":true,\"req\":\"^2.4.1\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"critical-section\",\"optional\":true,\"req\":\"^1.1.1\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"data-encoding\",\"req\":\"^2.2.0\"},{\"name\":\"enum-as-inner\",\"req\":\"^0.6\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-channel\",\"req\":\"^0.3.5\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"futures-executor\",\"req\":\"^0.3.5\"},{\"default_features\":false,\"name\":\"futures-io\",\"optional\":true,\"req\":\"^0.3.5\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"req\":\"^0.3.5\"},{\"features\":[\"stream\"],\"name\":\"h2\",\"optional\":true,\"req\":\"^0.4.0\"},{\"name\":\"h3\",\"optional\":true,\"req\":\"^0.0.7\"},{\"name\":\"h3-quinn\",\"optional\":true,\"req\":\"^0.0.9\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1.1\"},{\"default_features\":false,\"features\":[\"alloc\",\"compiled_data\"],\"name\":\"idna\",\"req\":\"^1.0.3\"},{\"default_features\":false,\"name\":\"ipnet\",\"req\":\"^2.3.0\"},{\"name\":\"js-sys\",\"optional\":true,\"req\":\"^0.3.44\"},{\"default_features\":false,\"features\":[\"critical-section\"],\"name\":\"once_cell\",\"req\":\"^1.20.0\"},{\"name\":\"pin-project-lite\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"log\",\"runtime-tokio\"],\"name\":\"quinn\",\"optional\":true,\"req\":\"^0.11.2\"},{\"default_features\":false,\"features\":[\"alloc\",\"std_rng\"],\"name\":\"rand\",\"req\":\"^0.9\"},{\"features\":[\"std\"],\"name\":\"ring\",\"optional\":true,\"req\":\"^0.17\"},{\"default_features\":false,\"features\":[\"logging\",\"std\",\"tls12\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.23.23\"},{\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"^1.10\"},{\"name\":\"rustls-platform-verifier\",\"optional\":true,\"req\":\"^0.5\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"socket2\",\"optional\":true,\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"thiserror\",\"req\":\"^2\"},{\"name\":\"time\",\"optional\":true,\"req\":\"^0.3\"},{\"features\":[\"alloc\"],\"name\":\"tinyvec\",\"req\":\"^1.1.1\"},{\"features\":[\"io-util\",\"macros\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1.21\"},{\"features\":[\"rt\",\"time\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.21\"},{\"default_features\":false,\"features\":[\"early-data\"],\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"^0.26\"},{\"default_features\":false,\"name\":\"tracing\",\"req\":\"^0.1.30\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"url\",\"req\":\"^2.5.4\"},{\"name\":\"wasm-bindgen-crate\",\"optional\":true,\"package\":\"wasm-bindgen\",\"req\":\"^0.2.58\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^0.26\"}],\"features\":{\"__dnssec\":[\"dep:bitflags\",\"dep:rustls-pki-types\",\"dep:time\",\"std\"],\"__h3\":[\"dep:h3\",\"dep:h3-quinn\",\"dep:http\",\"std\"],\"__https\":[\"dep:bytes\",\"dep:h2\",\"dep:http\",\"std\"],\"__quic\":[\"dep:bytes\",\"dep:pin-project-lite\",\"dep:quinn\",\"std\"],\"__tls\":[\"dep:bytes\",\"dep:rustls\",\"dep:tokio-rustls\",\"std\",\"tokio\"],\"backtrace\":[\"dep:backtrace\",\"std\"],\"default\":[\"std\",\"tokio\"],\"dnssec-aws-lc-rs\":[\"dep:aws-lc-rs\",\"aws-lc-rs/aws-lc-sys\",\"aws-lc-rs/ring-io\",\"__dnssec\"],\"dnssec-ring\":[\"dep:ring\",\"__dnssec\"],\"h3-aws-lc-rs\":[\"quic-aws-lc-rs\",\"__h3\"],\"h3-ring\":[\"quic-ring\",\"__h3\"],\"https-aws-lc-rs\":[\"tls-aws-lc-rs\",\"__https\"],\"https-ring\":[\"tls-ring\",\"__https\"],\"mdns\":[\"socket2/all\",\"std\"],\"no-std-rand\":[\"once_cell/critical-section\",\"dep:critical-section\"],\"quic-aws-lc-rs\":[\"quinn/rustls-aws-lc-rs\",\"tls-aws-lc-rs\",\"__quic\"],\"quic-ring\":[\"quinn/rustls-ring\",\"tls-ring\",\"__quic\"],\"rustls-platform-verifier\":[\"dep:rustls-platform-verifier\",\"std\"],\"serde\":[\"dep:serde\",\"std\",\"url/serde\"],\"std\":[\"data-encoding/std\",\"futures-channel/std\",\"futures-io/std\",\"futures-util/std\",\"ipnet/std\",\"rand/std\",\"rand/thread_rng\",\"ring?/std\",\"thiserror/std\",\"tracing-subscriber/env-filter\",\"tracing-subscriber/fmt\",\"tracing-subscriber/std\",\"tracing/std\",\"url/std\"],\"testing\":[\"std\"],\"text-parsing\":[\"std\"],\"tls-aws-lc-rs\":[\"tokio-rustls/aws-lc-rs\",\"__tls\"],\"tls-ring\":[\"tokio-rustls/ring\",\"__tls\"],\"tokio\":[\"dep:tokio\",\"std\",\"tokio/net\",\"tokio/rt\",\"tokio/time\",\"tokio/rt-multi-thread\"],\"wasm-bindgen\":[\"dep:wasm-bindgen-crate\",\"dep:js-sys\"]}}", + "hickory-resolver_0.25.2": "{\"dependencies\":[{\"name\":\"backtrace\",\"optional\":true,\"req\":\"^0.3.50\"},{\"name\":\"cfg-if\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"futures-executor\",\"req\":\"^0.3.5\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-util\",\"req\":\"^0.3.5\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"hickory-proto\",\"req\":\"^0.25\"},{\"name\":\"ipconfig\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(windows)\"},{\"features\":[\"sync\"],\"name\":\"moka\",\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"critical-section\"],\"name\":\"once_cell\",\"req\":\"^1.20.0\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"log\",\"runtime-tokio\"],\"name\":\"quinn\",\"optional\":true,\"req\":\"^0.11.2\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"rand\",\"req\":\"^0.9\"},{\"features\":[\"system\"],\"name\":\"resolv-conf\",\"optional\":true,\"req\":\"^0.7.0\"},{\"default_features\":false,\"features\":[\"logging\",\"std\",\"tls12\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.23.23\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"name\":\"smallvec\",\"req\":\"^1.6\"},{\"default_features\":false,\"name\":\"thiserror\",\"req\":\"^2\"},{\"name\":\"tokio\",\"optional\":true,\"req\":\"^1.21\"},{\"features\":[\"macros\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.21\"},{\"default_features\":false,\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"^0.26\"},{\"kind\":\"dev\",\"name\":\"toml\",\"req\":\"^0.8.14\"},{\"default_features\":false,\"name\":\"tracing\",\"req\":\"^0.1.30\"},{\"default_features\":false,\"features\":[\"env-filter\",\"fmt\",\"std\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^0.26\"}],\"features\":{\"__dnssec\":[],\"__h3\":[\"__quic\"],\"__https\":[\"__tls\"],\"__quic\":[\"dep:quinn\",\"__tls\"],\"__tls\":[\"dep:rustls\",\"dep:tokio-rustls\",\"tokio\"],\"backtrace\":[\"dep:backtrace\",\"hickory-proto/backtrace\"],\"default\":[\"system-config\",\"tokio\"],\"dnssec-aws-lc-rs\":[\"hickory-proto/dnssec-aws-lc-rs\",\"__dnssec\"],\"dnssec-ring\":[\"hickory-proto/dnssec-ring\",\"__dnssec\"],\"h3-aws-lc-rs\":[\"hickory-proto/h3-aws-lc-rs\",\"__h3\"],\"h3-ring\":[\"hickory-proto/h3-ring\",\"__h3\"],\"https-aws-lc-rs\":[\"hickory-proto/https-aws-lc-rs\",\"__https\"],\"https-ring\":[\"hickory-proto/https-ring\",\"__https\"],\"quic-aws-lc-rs\":[\"hickory-proto/quic-aws-lc-rs\",\"__quic\",\"quinn/rustls-aws-lc-rs\"],\"quic-ring\":[\"hickory-proto/quic-ring\",\"__quic\",\"quinn/rustls-ring\"],\"rustls-platform-verifier\":[\"hickory-proto/rustls-platform-verifier\"],\"serde\":[\"dep:serde\",\"hickory-proto/serde\"],\"system-config\":[\"dep:ipconfig\",\"dep:resolv-conf\"],\"tls-aws-lc-rs\":[\"hickory-proto/tls-aws-lc-rs\",\"__tls\"],\"tls-ring\":[\"hickory-proto/tls-ring\",\"__tls\"],\"tokio\":[\"dep:tokio\",\"tokio/rt\",\"hickory-proto/tokio\"],\"webpki-roots\":[\"dep:webpki-roots\",\"hickory-proto/webpki-roots\"]}}", "hkdf_0.12.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"blobby\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.2.2\"},{\"name\":\"hmac\",\"req\":\"^0.12.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"sha1\",\"req\":\"^0.10\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"}],\"features\":{\"std\":[\"hmac/std\"]}}", "hmac_0.12.1": "{\"dependencies\":[{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.10.3\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"digest\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.2.2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"md-5\",\"req\":\"^0.10\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"sha-1\",\"req\":\"^0.10\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"streebog\",\"req\":\"^0.10\"}],\"features\":{\"reset\":[],\"std\":[\"digest/std\"]}}", "home_0.5.11": "{\"dependencies\":[{\"features\":[\"Win32_Foundation\",\"Win32_UI_Shell\",\"Win32_System_Com\"],\"name\":\"windows-sys\",\"req\":\"^0.59\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "hostname_0.4.1": "{\"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\",\"target\":\"cfg(target_os = \\\"windows\\\")\"},{\"kind\":\"dev\",\"name\":\"version-sync\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"windows-bindgen\",\"req\":\"^0.61\",\"target\":\"cfg(target_os = \\\"windows\\\")\"},{\"name\":\"windows-link\",\"req\":\"^0.1.1\",\"target\":\"cfg(target_os = \\\"windows\\\")\"}],\"features\":{\"default\":[],\"set\":[]}}", "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_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\":{}}", "http_1.3.1": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.0\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "httparse_1.10.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.5\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", @@ -819,6 +855,7 @@ "insta_1.46.0": "{\"dependencies\":[{\"features\":[\"derive\",\"env\"],\"name\":\"clap\",\"optional\":true,\"req\":\"^4.1\"},{\"default_features\":false,\"name\":\"console\",\"optional\":true,\"req\":\"^0.15.4\"},{\"name\":\"csv\",\"optional\":true,\"req\":\"^1.1.6\"},{\"name\":\"globset\",\"optional\":true,\"req\":\">=0.4.6, <0.4.17\"},{\"name\":\"once_cell\",\"req\":\"^1.20.2\"},{\"name\":\"pest\",\"optional\":true,\"req\":\"^2.1.3\"},{\"name\":\"pest_derive\",\"optional\":true,\"req\":\"^2.1.0\"},{\"default_features\":false,\"features\":[\"std\",\"unicode\"],\"name\":\"regex\",\"optional\":true,\"req\":\"^1.6.0\"},{\"name\":\"ron\",\"optional\":true,\"req\":\"^0.12.0\"},{\"kind\":\"dev\",\"name\":\"rustc_version\",\"req\":\"^0.4.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.117\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.117\"},{\"features\":[\"inline\"],\"name\":\"similar\",\"req\":\"^2.1.0\"},{\"kind\":\"dev\",\"name\":\"similar-asserts\",\"req\":\"^1.4.2\"},{\"name\":\"tempfile\",\"req\":\"^3\"},{\"features\":[\"serde\",\"parse\",\"display\"],\"name\":\"toml_edit\",\"optional\":true,\"req\":\"^0.23.0\"},{\"name\":\"toml_writer\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"walkdir\",\"optional\":true,\"req\":\"^2.3.1\"}],\"features\":{\"_cargo_insta_internal\":[\"clap\"],\"colors\":[\"console\"],\"csv\":[\"dep:csv\",\"serde\"],\"default\":[\"colors\"],\"filters\":[\"regex\"],\"glob\":[\"walkdir\",\"globset\"],\"json\":[\"serde\"],\"redactions\":[\"pest\",\"pest_derive\",\"serde\"],\"ron\":[\"dep:ron\",\"serde\"],\"toml\":[\"dep:toml_edit\",\"dep:toml_writer\",\"serde\"],\"yaml\":[\"serde\"]}}", "instability_0.3.9": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.20.10\"},{\"name\":\"indoc\",\"req\":\"^2.0.5\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.4.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.92\"},{\"name\":\"quote\",\"req\":\"^1.0.37\"},{\"features\":[\"derive\",\"full\"],\"name\":\"syn\",\"req\":\"^2.0.90\"}],\"features\":{}}", "inventory_0.3.20": "{\"dependencies\":[{\"name\":\"rustversion\",\"req\":\"^1.0\",\"target\":\"cfg(target_family = \\\"wasm\\\")\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.89\"}],\"features\":{}}", + "ipconfig_0.3.2": "{\"dependencies\":[{\"name\":\"socket2\",\"req\":\"^0.5.1\",\"target\":\"cfg(windows)\"},{\"name\":\"widestring\",\"req\":\"^1.0.2\",\"target\":\"cfg(windows)\"},{\"features\":[\"Win32_Foundation\",\"Win32_Networking_WinSock\",\"Win32_System_Registry\"],\"name\":\"windows-sys\",\"req\":\"^0.48.0\",\"target\":\"cfg(windows)\"},{\"name\":\"winreg\",\"optional\":true,\"req\":\"^0.50.0\",\"target\":\"cfg(windows)\"}],\"features\":{\"computer\":[\"winreg\"],\"default\":[\"computer\"]}}", "ipnet_2.11.0": "{\"dependencies\":[{\"name\":\"heapless\",\"optional\":true,\"req\":\"^0\"},{\"name\":\"schemars\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"package\":\"serde\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1\"}],\"features\":{\"default\":[\"std\"],\"json\":[\"serde\",\"schemars\"],\"ser_as_str\":[\"heapless\"],\"std\":[]}}", "iri-string_0.7.8": "{\"dependencies\":[{\"default_features\":false,\"name\":\"memchr\",\"optional\":true,\"req\":\"^2.4.1\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.103\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0.104\"}],\"features\":{\"alloc\":[\"serde?/alloc\"],\"default\":[\"std\"],\"std\":[\"alloc\",\"memchr?/std\",\"serde?/std\"]}}", "is-terminal_0.4.16": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"atty\",\"req\":\"^0.2.14\"},{\"name\":\"hermit-abi\",\"req\":\"^0.5.0\",\"target\":\"cfg(target_os = \\\"hermit\\\")\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(any(unix, target_os = \\\"wasi\\\"))\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.110\",\"target\":\"cfg(any(unix, target_os = \\\"wasi\\\"))\"},{\"features\":[\"termios\"],\"kind\":\"dev\",\"name\":\"rustix\",\"req\":\"^1.0.0\",\"target\":\"cfg(any(unix, target_os = \\\"wasi\\\"))\"},{\"features\":[\"stdio\"],\"kind\":\"dev\",\"name\":\"rustix\",\"req\":\"^1.0.0\",\"target\":\"cfg(not(any(windows, target_os = \\\"hermit\\\", target_os = \\\"unknown\\\")))\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\",\"target\":\"cfg(windows)\"},{\"features\":[\"Win32_Foundation\",\"Win32_Storage_FileSystem\",\"Win32_System_Console\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <0.60\",\"target\":\"cfg(windows)\"}],\"features\":{}}", @@ -844,7 +881,10 @@ "lazy_static_1.5.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.1\"},{\"default_features\":false,\"features\":[\"once\"],\"name\":\"spin\",\"optional\":true,\"req\":\"^0.9.8\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1\"}],\"features\":{\"spin_no_std\":[\"spin\"]}}", "libc_0.2.177": "{\"dependencies\":[{\"name\":\"rustc-std-workspace-core\",\"optional\":true,\"req\":\"^1.0.1\"}],\"features\":{\"align\":[],\"const-extern-fn\":[],\"default\":[\"std\"],\"extra_traits\":[],\"rustc-dep-of-std\":[\"align\",\"rustc-std-workspace-core\"],\"std\":[],\"use_std\":[\"std\"]}}", "libdbus-sys_0.2.6": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"optional\":true,\"req\":\"^1.0.78\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"optional\":true,\"req\":\"^0.3\"}],\"features\":{\"default\":[\"pkg-config\"],\"vendored\":[\"cc\"]}}", + "libloading_0.8.9": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1\",\"target\":\"cfg(unix)\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"name\":\"windows-link\",\"req\":\"^0.2\",\"target\":\"cfg(windows)\"},{\"features\":[\"Win32_Foundation\"],\"kind\":\"dev\",\"name\":\"windows-sys\",\"req\":\"^0.61\",\"target\":\"cfg(windows)\"}],\"features\":{}}", + "libm_0.2.16": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"no-panic\",\"req\":\"^0.1.35\"}],\"features\":{\"arch\":[],\"default\":[\"arch\"],\"force-soft-floats\":[],\"unstable\":[\"unstable-intrinsics\",\"unstable-float\"],\"unstable-float\":[],\"unstable-intrinsics\":[],\"unstable-public-internals\":[]}}", "libredox_0.1.6": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2\"},{\"name\":\"ioslice\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"redox_syscall\",\"optional\":true,\"req\":\"^0.5\"}],\"features\":{\"call\":[],\"default\":[\"call\",\"std\",\"redox_syscall\"],\"mkns\":[\"ioslice\"],\"std\":[]}}", + "libsqlite3-sys_0.30.1": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"runtime\"],\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.69\"},{\"kind\":\"build\",\"name\":\"cc\",\"optional\":true,\"req\":\"^1.1.6\"},{\"name\":\"openssl-sys\",\"optional\":true,\"req\":\"^0.9.103\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"optional\":true,\"req\":\"^0.3.19\"},{\"kind\":\"build\",\"name\":\"prettyplease\",\"optional\":true,\"req\":\"^0.2.20\"},{\"default_features\":false,\"kind\":\"build\",\"name\":\"quote\",\"optional\":true,\"req\":\"^1.0.36\"},{\"features\":[\"full\",\"extra-traits\",\"visit-mut\"],\"kind\":\"build\",\"name\":\"syn\",\"optional\":true,\"req\":\"^2.0.72\"},{\"kind\":\"build\",\"name\":\"vcpkg\",\"optional\":true,\"req\":\"^0.2.15\"}],\"features\":{\"buildtime_bindgen\":[\"bindgen\",\"pkg-config\",\"vcpkg\"],\"bundled\":[\"cc\",\"bundled_bindings\"],\"bundled-sqlcipher\":[\"bundled\"],\"bundled-sqlcipher-vendored-openssl\":[\"bundled-sqlcipher\",\"openssl-sys/vendored\"],\"bundled-windows\":[\"cc\",\"bundled_bindings\"],\"bundled_bindings\":[],\"default\":[\"min_sqlite_version_3_14_0\"],\"in_gecko\":[],\"loadable_extension\":[\"prettyplease\",\"quote\",\"syn\"],\"min_sqlite_version_3_14_0\":[\"pkg-config\",\"vcpkg\"],\"preupdate_hook\":[\"buildtime_bindgen\"],\"session\":[\"preupdate_hook\",\"buildtime_bindgen\"],\"sqlcipher\":[],\"unlock_notify\":[],\"wasm32-wasi-vfs\":[],\"with-asan\":[]}}", "linux-keyutils_0.2.4": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2.4\"},{\"default_features\":false,\"features\":[\"std\",\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^4.4.11\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.132\"},{\"kind\":\"dev\",\"name\":\"zeroize\",\"req\":\"^1.5.7\"}],\"features\":{\"default\":[],\"std\":[\"bitflags/std\"]}}", "linux-raw-sys_0.4.15": "{\"dependencies\":[{\"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\":\"libc\",\"req\":\"^0.2.100\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"}],\"features\":{\"bootparam\":[],\"btrfs\":[],\"default\":[\"std\",\"general\",\"errno\"],\"elf\":[],\"elf_uapi\":[],\"errno\":[],\"general\":[],\"if_arp\":[],\"if_ether\":[],\"if_packet\":[],\"io_uring\":[],\"ioctl\":[],\"landlock\":[],\"loop_device\":[],\"mempolicy\":[],\"net\":[],\"netlink\":[],\"no_std\":[],\"prctl\":[],\"ptrace\":[],\"rustc-dep-of-std\":[\"core\",\"compiler_builtins\",\"no_std\"],\"std\":[],\"system\":[],\"xdp\":[]}}", "linux-raw-sys_0.9.4": "{\"dependencies\":[{\"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\":\"libc\",\"req\":\"^0.2.100\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"}],\"features\":{\"bootparam\":[],\"btrfs\":[],\"default\":[\"std\",\"general\",\"errno\"],\"elf\":[],\"elf_uapi\":[],\"errno\":[],\"general\":[],\"if_arp\":[],\"if_ether\":[],\"if_packet\":[],\"image\":[],\"io_uring\":[],\"ioctl\":[],\"landlock\":[],\"loop_device\":[],\"mempolicy\":[],\"net\":[],\"netlink\":[],\"no_std\":[],\"prctl\":[],\"ptrace\":[],\"rustc-dep-of-std\":[\"core\",\"compiler_builtins\",\"no_std\"],\"std\":[],\"system\":[],\"xdp\":[]}}", @@ -854,6 +894,7 @@ "log_0.4.29": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"proc-macro2\",\"req\":\"^1.0.63\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"sval\",\"optional\":true,\"req\":\"^2.16\"},{\"kind\":\"dev\",\"name\":\"sval\",\"req\":\"^2.16\"},{\"kind\":\"dev\",\"name\":\"sval_derive\",\"req\":\"^2.16\"},{\"default_features\":false,\"name\":\"sval_ref\",\"optional\":true,\"req\":\"^2.16\"},{\"default_features\":false,\"features\":[\"inline-i128\"],\"name\":\"value-bag\",\"optional\":true,\"req\":\"^1.12\"},{\"features\":[\"test\"],\"kind\":\"dev\",\"name\":\"value-bag\",\"req\":\"^1.12\"}],\"features\":{\"kv\":[],\"kv_serde\":[\"kv_std\",\"value-bag/serde\",\"serde\"],\"kv_std\":[\"std\",\"kv\",\"value-bag/error\"],\"kv_sval\":[\"kv\",\"value-bag/sval\",\"sval\",\"sval_ref\"],\"kv_unstable\":[\"kv\",\"value-bag\"],\"kv_unstable_serde\":[\"kv_serde\",\"kv_unstable_std\"],\"kv_unstable_std\":[\"kv_std\",\"kv_unstable\"],\"kv_unstable_sval\":[\"kv_sval\",\"kv_unstable\"],\"max_level_debug\":[],\"max_level_error\":[],\"max_level_info\":[],\"max_level_off\":[],\"max_level_trace\":[],\"max_level_warn\":[],\"release_max_level_debug\":[],\"release_max_level_error\":[],\"release_max_level_info\":[],\"release_max_level_off\":[],\"release_max_level_trace\":[],\"release_max_level_warn\":[],\"serde\":[\"serde_core\"],\"std\":[]}}", "logos-derive_0.12.1": "{\"dependencies\":[{\"name\":\"beef\",\"req\":\"^0.5.0\"},{\"name\":\"fnv\",\"req\":\"^1.0.6\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^0.6.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.9\"},{\"name\":\"quote\",\"req\":\"^1.0.3\"},{\"name\":\"regex-syntax\",\"req\":\"^0.6\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^1.0.17\"}],\"features\":{}}", "logos_0.12.1": "{\"dependencies\":[{\"name\":\"logos-derive\",\"optional\":true,\"req\":\"^0.12.1\"}],\"features\":{\"default\":[\"export_derive\",\"std\"],\"export_derive\":[\"logos-derive\"],\"std\":[]}}", + "loom_0.7.2": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.0\"},{\"name\":\"generator\",\"req\":\"^0.8.1\"},{\"name\":\"pin-utils\",\"optional\":true,\"req\":\"^0.1.0\"},{\"name\":\"scoped-tls\",\"req\":\"^1.0.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.92\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.33\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.27\"},{\"features\":[\"env-filter\"],\"name\":\"tracing-subscriber\",\"req\":\"^0.3.8\"}],\"features\":{\"checkpoint\":[\"serde\",\"serde_json\"],\"default\":[],\"futures\":[\"pin-utils\"]}}", "lru-slab_0.1.2": "{\"dependencies\":[],\"features\":{}}", "lru_0.12.5": "{\"dependencies\":[{\"name\":\"hashbrown\",\"optional\":true,\"req\":\"^0.15\"},{\"kind\":\"dev\",\"name\":\"scoped_threadpool\",\"req\":\"0.1.*\"},{\"kind\":\"dev\",\"name\":\"stats_alloc\",\"req\":\"0.1.*\"}],\"features\":{\"default\":[\"hashbrown\"],\"nightly\":[\"hashbrown\",\"hashbrown/nightly\"]}}", "lru_0.16.3": "{\"dependencies\":[{\"name\":\"hashbrown\",\"optional\":true,\"req\":\"^0.16.0\"},{\"kind\":\"dev\",\"name\":\"scoped_threadpool\",\"req\":\"0.1.*\"},{\"kind\":\"dev\",\"name\":\"stats_alloc\",\"req\":\"0.1.*\"}],\"features\":{\"default\":[\"hashbrown\"],\"nightly\":[\"hashbrown\",\"hashbrown/nightly\"]}}", @@ -861,6 +902,9 @@ "maplit_1.0.2": "{\"dependencies\":[],\"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\":[]}}", + "md-5_0.10.6": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"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\":\"md5-asm\",\"optional\":true,\"req\":\"^0.5\",\"target\":\"cfg(any(target_arch = \\\"x86\\\", target_arch = \\\"x86_64\\\"))\"}],\"features\":{\"asm\":[\"md5-asm\"],\"default\":[\"std\"],\"force-soft\":[],\"loongarch64_asm\":[],\"oid\":[\"digest/oid\"],\"std\":[\"digest/std\"]}}", + "md5_0.8.0": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "memchr_2.7.5": "{\"dependencies\":[{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"libc\":[],\"logging\":[\"dep:log\"],\"rustc-dep-of-std\":[\"core\"],\"std\":[\"alloc\"],\"use_std\":[\"std\"]}}", "memoffset_0.6.5": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"autocfg\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"}],\"features\":{\"default\":[],\"unstable_const\":[]}}", "memoffset_0.9.1": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"autocfg\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"}],\"features\":{\"default\":[],\"unstable_const\":[],\"unstable_offset_of\":[]}}", @@ -869,6 +913,7 @@ "minimal-lexical_0.2.1": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"compact\":[],\"default\":[\"std\"],\"lint\":[],\"nightly\":[],\"std\":[]}}", "miniz_oxide_0.8.9": "{\"dependencies\":[{\"default_features\":false,\"name\":\"adler2\",\"req\":\"^2.0\"},{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"simd-adler32\",\"optional\":true,\"req\":\"^0.3.3\"}],\"features\":{\"block-boundary\":[],\"default\":[\"with-alloc\"],\"rustc-dep-of-std\":[\"core\",\"alloc\",\"adler2/rustc-dep-of-std\"],\"simd\":[\"simd-adler32\"],\"std\":[],\"with-alloc\":[]}}", "mio_1.0.4": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.9.3\"},{\"name\":\"libc\",\"req\":\"^0.2.159\",\"target\":\"cfg(target_os = \\\"hermit\\\")\"},{\"name\":\"libc\",\"req\":\"^0.2.159\",\"target\":\"cfg(target_os = \\\"wasi\\\")\"},{\"name\":\"libc\",\"req\":\"^0.2.159\",\"target\":\"cfg(unix)\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"name\":\"wasi\",\"req\":\"^0.11.0\",\"target\":\"cfg(target_os = \\\"wasi\\\")\"},{\"features\":[\"Wdk_Foundation\",\"Wdk_Storage_FileSystem\",\"Wdk_System_IO\",\"Win32_Foundation\",\"Win32_Networking_WinSock\",\"Win32_Storage_FileSystem\",\"Win32_System_IO\",\"Win32_System_WindowsProgramming\"],\"name\":\"windows-sys\",\"req\":\"^0.59\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"log\"],\"net\":[],\"os-ext\":[\"os-poll\",\"windows-sys/Win32_System_Pipes\",\"windows-sys/Win32_Security\"],\"os-poll\":[]}}", + "moka_0.12.12": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"actix-rt\",\"req\":\"^2.8\"},{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.8.3\"},{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.19\"},{\"name\":\"async-lock\",\"optional\":true,\"req\":\"^3.3\"},{\"name\":\"crossbeam-channel\",\"req\":\"^0.5.15\"},{\"name\":\"crossbeam-epoch\",\"req\":\"^0.9.18\"},{\"name\":\"crossbeam-utils\",\"req\":\"^0.8.21\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10.0\"},{\"name\":\"equivalent\",\"req\":\"^1.0\"},{\"name\":\"event-listener\",\"optional\":true,\"req\":\"^5.3\"},{\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.17\"},{\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.2\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(moka_loom)\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.7\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"portable-atomic\",\"req\":\"^1.6\"},{\"name\":\"quanta\",\"optional\":true,\"req\":\"^0.12.2\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"default_features\":false,\"features\":[\"rustls-tls\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12\"},{\"name\":\"smallvec\",\"req\":\"^1.8\"},{\"name\":\"tagptr\",\"req\":\"^0.2\"},{\"features\":[\"fs\",\"io-util\",\"macros\",\"rt-multi-thread\",\"sync\",\"time\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.19\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\",\"target\":\"cfg(trybuild)\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"req\":\"^1.1\"}],\"features\":{\"atomic64\":[],\"default\":[],\"future\":[\"async-lock\",\"event-listener\",\"futures-util\"],\"logging\":[\"log\"],\"quanta\":[\"dep:quanta\"],\"sync\":[],\"unstable-debug-counters\":[\"future\"]}}", "moxcms_0.7.5": "{\"dependencies\":[{\"name\":\"num-traits\",\"req\":\"^0.2\"},{\"name\":\"pxfm\",\"req\":\"^0.1.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"}],\"features\":{\"avx\":[],\"avx512\":[],\"default\":[\"avx\",\"sse\",\"neon\"],\"neon\":[],\"options\":[],\"sse\":[]}}", "multimap_0.10.1": "{\"dependencies\":[{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"serde_impl\"],\"serde_impl\":[\"serde\"]}}", "native-tls_0.2.14": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(target_vendor = \\\"apple\\\")\"},{\"name\":\"log\",\"req\":\"^0.4.5\",\"target\":\"cfg(not(any(target_os = \\\"windows\\\", target_vendor = \\\"apple\\\")))\"},{\"name\":\"openssl\",\"req\":\"^0.10.69\",\"target\":\"cfg(not(any(target_os = \\\"windows\\\", target_vendor = \\\"apple\\\")))\"},{\"name\":\"openssl-probe\",\"req\":\"^0.1\",\"target\":\"cfg(not(any(target_os = \\\"windows\\\", target_vendor = \\\"apple\\\")))\"},{\"name\":\"openssl-sys\",\"req\":\"^0.9.81\",\"target\":\"cfg(not(any(target_os = \\\"windows\\\", target_vendor = \\\"apple\\\")))\"},{\"name\":\"schannel\",\"req\":\"^0.1.17\",\"target\":\"cfg(target_os = \\\"windows\\\")\"},{\"name\":\"security-framework\",\"req\":\"^2.0.0\",\"target\":\"cfg(target_vendor = \\\"apple\\\")\"},{\"name\":\"security-framework-sys\",\"req\":\"^2.0.0\",\"target\":\"cfg(target_vendor = \\\"apple\\\")\"},{\"name\":\"tempfile\",\"req\":\"^3.1.0\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.0\"},{\"kind\":\"dev\",\"name\":\"test-cert-gen\",\"req\":\"^0.9\"}],\"features\":{\"alpn\":[\"security-framework/alpn\"],\"vendored\":[\"openssl/vendored\"]}}", @@ -879,11 +924,12 @@ "nix_0.29.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert-impl\",\"req\":\"^0.1\"},{\"name\":\"bitflags\",\"req\":\"^2.3.1\"},{\"kind\":\"dev\",\"name\":\"caps\",\"req\":\"^0.5.3\",\"target\":\"cfg(any(target_os = \\\"android\\\", target_os = \\\"linux\\\"))\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"cfg_aliases\",\"req\":\"^0.2\"},{\"features\":[\"extra_traits\"],\"name\":\"libc\",\"req\":\"^0.2.155\"},{\"name\":\"memoffset\",\"optional\":true,\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"pin-utils\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"semver\",\"req\":\"^1.0.7\"},{\"kind\":\"dev\",\"name\":\"sysctl\",\"req\":\"^0.4\",\"target\":\"cfg(target_os = \\\"freebsd\\\")\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.7.1\"}],\"features\":{\"acct\":[],\"aio\":[\"pin-utils\"],\"default\":[],\"dir\":[\"fs\"],\"env\":[],\"event\":[],\"fanotify\":[],\"feature\":[],\"fs\":[],\"hostname\":[],\"inotify\":[],\"ioctl\":[],\"kmod\":[],\"mman\":[],\"mount\":[\"uio\"],\"mqueue\":[\"fs\"],\"net\":[\"socket\"],\"personality\":[],\"poll\":[],\"process\":[],\"pthread\":[],\"ptrace\":[\"process\"],\"quota\":[],\"reboot\":[],\"resource\":[],\"sched\":[\"process\"],\"signal\":[\"process\"],\"socket\":[\"memoffset\"],\"term\":[],\"time\":[],\"ucontext\":[\"signal\"],\"uio\":[],\"user\":[\"feature\"],\"zerocopy\":[\"fs\",\"uio\"]}}", "nix_0.30.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert-impl\",\"req\":\"^0.1\"},{\"name\":\"bitflags\",\"req\":\"^2.3.3\"},{\"kind\":\"dev\",\"name\":\"caps\",\"req\":\"^0.5.3\",\"target\":\"cfg(any(target_os = \\\"android\\\", target_os = \\\"linux\\\"))\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"cfg_aliases\",\"req\":\"^0.2.1\"},{\"features\":[\"extra_traits\"],\"name\":\"libc\",\"req\":\"^0.2.171\"},{\"name\":\"memoffset\",\"optional\":true,\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"pin-utils\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"semver\",\"req\":\"^1.0.7\"},{\"kind\":\"dev\",\"name\":\"sysctl\",\"req\":\"^0.4\",\"target\":\"cfg(target_os = \\\"freebsd\\\")\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.7.1\"}],\"features\":{\"acct\":[],\"aio\":[\"pin-utils\"],\"default\":[],\"dir\":[\"fs\"],\"env\":[],\"event\":[\"poll\"],\"fanotify\":[],\"feature\":[],\"fs\":[],\"hostname\":[],\"inotify\":[],\"ioctl\":[],\"kmod\":[],\"mman\":[],\"mount\":[\"uio\"],\"mqueue\":[\"fs\"],\"net\":[\"socket\"],\"personality\":[],\"poll\":[],\"process\":[],\"pthread\":[],\"ptrace\":[\"process\"],\"quota\":[],\"reboot\":[],\"resource\":[],\"sched\":[\"process\"],\"signal\":[\"process\"],\"socket\":[\"memoffset\"],\"syslog\":[],\"term\":[],\"time\":[],\"ucontext\":[\"signal\"],\"uio\":[],\"user\":[\"feature\"],\"zerocopy\":[\"fs\",\"uio\"]}}", "nom_7.1.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.3\"},{\"default_features\":false,\"name\":\"minimal-lexical\",\"req\":\"^0.2.0\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.0.0\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"docsrs\":[],\"std\":[\"alloc\",\"memchr/std\",\"minimal-lexical/std\"]}}", + "nom_8.0.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.3\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"=1.0.0\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"docsrs\":[],\"std\":[\"alloc\",\"memchr/std\"]}}", "normalize-line-endings_0.3.0": "{\"dependencies\":[],\"features\":{}}", "notify-types_2.0.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.34.0\"},{\"kind\":\"dev\",\"name\":\"rstest\",\"req\":\"^0.24.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.89\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.39\"},{\"name\":\"web-time\",\"optional\":true,\"req\":\"^1.1.0\"}],\"features\":{\"serialization-compat-6\":[]}}", "notify_8.2.0": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.7.0\",\"target\":\"cfg(target_os=\\\"macos\\\")\"},{\"name\":\"crossbeam-channel\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"flume\",\"optional\":true,\"req\":\"^0.11.1\"},{\"name\":\"fsevent-sys\",\"optional\":true,\"req\":\"^4.0.0\",\"target\":\"cfg(target_os=\\\"macos\\\")\"},{\"default_features\":false,\"name\":\"inotify\",\"req\":\"^0.11.0\",\"target\":\"cfg(any(target_os=\\\"linux\\\", target_os=\\\"android\\\"))\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.34.0\"},{\"name\":\"kqueue\",\"req\":\"^1.1.1\",\"target\":\"cfg(any(target_os=\\\"freebsd\\\", target_os=\\\"openbsd\\\", target_os = \\\"netbsd\\\", target_os = \\\"dragonflybsd\\\", target_os = \\\"ios\\\"))\"},{\"name\":\"kqueue\",\"optional\":true,\"req\":\"^1.1.1\",\"target\":\"cfg(target_os=\\\"macos\\\")\"},{\"name\":\"libc\",\"req\":\"^0.2.4\"},{\"name\":\"log\",\"req\":\"^0.4.17\"},{\"features\":[\"os-ext\"],\"name\":\"mio\",\"req\":\"^1.0\",\"target\":\"cfg(any(target_os=\\\"freebsd\\\", target_os=\\\"openbsd\\\", target_os = \\\"netbsd\\\", target_os = \\\"dragonflybsd\\\", target_os = \\\"ios\\\"))\"},{\"features\":[\"os-ext\"],\"name\":\"mio\",\"req\":\"^1.0\",\"target\":\"cfg(any(target_os=\\\"linux\\\", target_os=\\\"android\\\"))\"},{\"features\":[\"os-ext\"],\"name\":\"mio\",\"optional\":true,\"req\":\"^1.0\",\"target\":\"cfg(target_os=\\\"macos\\\")\"},{\"kind\":\"dev\",\"name\":\"nix\",\"req\":\"^0.29.0\"},{\"name\":\"notify-types\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.39\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.10.0\"},{\"kind\":\"dev\",\"name\":\"trash\",\"req\":\"^5.2.2\",\"target\":\"cfg(target_os = \\\"windows\\\")\"},{\"name\":\"walkdir\",\"req\":\"^2.4.0\"},{\"features\":[\"Win32_System_Threading\",\"Win32_Foundation\",\"Win32_Storage_FileSystem\",\"Win32_Security\",\"Win32_System_WindowsProgramming\",\"Win32_System_IO\"],\"name\":\"windows-sys\",\"req\":\"^0.60.1\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"macos_fsevent\"],\"macos_fsevent\":[\"fsevent-sys\"],\"macos_kqueue\":[\"kqueue\",\"mio\"],\"serde\":[\"notify-types/serde\"],\"serialization-compat-6\":[\"notify-types/serialization-compat-6\"]}}", "nu-ansi-term_0.50.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.3\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.152\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.94\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Console\",\"Win32_Storage_FileSystem\",\"Win32_Security\"],\"name\":\"windows\",\"package\":\"windows-sys\",\"req\":\"^0.52.0\",\"target\":\"cfg(windows)\"}],\"features\":{\"derive_serde_style\":[\"serde\"],\"gnu_legacy\":[]}}", - "nucleo-matcher_0.3.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"cov-mark\",\"req\":\"^1.1.0\"},{\"name\":\"memchr\",\"req\":\"^2.5.0\"},{\"name\":\"unicode-segmentation\",\"optional\":true,\"req\":\"^1.10\"}],\"features\":{\"default\":[\"unicode-normalization\",\"unicode-casefold\",\"unicode-segmentation\"],\"unicode-casefold\":[],\"unicode-normalization\":[],\"unicode-segmentation\":[\"dep:unicode-segmentation\"]}}", + "num-bigint-dig_0.8.6": "{\"dependencies\":[{\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.1.0\"},{\"default_features\":false,\"features\":[\"spin_no_std\"],\"name\":\"lazy_static\",\"req\":\"^1.2.0\"},{\"name\":\"libm\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"features\":[\"i128\"],\"name\":\"num-integer\",\"req\":\"^0.1.39\"},{\"default_features\":false,\"name\":\"num-iter\",\"req\":\"^0.1.37\"},{\"default_features\":false,\"features\":[\"i128\"],\"name\":\"num-traits\",\"req\":\"^0.2.4\"},{\"default_features\":false,\"name\":\"rand\",\"optional\":true,\"req\":\"^0.8.3\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand_chacha\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"rand_isaac\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"rand_xorshift\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"smallvec\",\"req\":\"^1.10.0\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.5\"}],\"features\":{\"default\":[\"std\",\"u64_digit\"],\"fuzz\":[\"arbitrary\",\"smallvec/arbitrary\"],\"i128\":[],\"nightly\":[],\"prime\":[\"rand/std_rng\"],\"std\":[\"num-integer/std\",\"num-traits/std\",\"smallvec/write\",\"rand/std\",\"serde/std\"],\"u64_digit\":[]}}", "num-bigint_0.4.6": "{\"dependencies\":[{\"default_features\":false,\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"i128\"],\"name\":\"num-integer\",\"req\":\"^0.1.46\"},{\"default_features\":false,\"features\":[\"i128\"],\"name\":\"num-traits\",\"req\":\"^0.2.18\"},{\"default_features\":false,\"name\":\"quickcheck\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"name\":\"rand\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"arbitrary\":[\"dep:arbitrary\"],\"default\":[\"std\"],\"quickcheck\":[\"dep:quickcheck\"],\"rand\":[\"dep:rand\"],\"serde\":[\"dep:serde\"],\"std\":[\"num-integer/std\",\"num-traits/std\"]}}", "num-complex_0.4.6": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bytecheck\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"bytemuck\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"i128\"],\"name\":\"num-traits\",\"req\":\"^0.2.18\"},{\"default_features\":false,\"name\":\"rand\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"rkyv\",\"optional\":true,\"req\":\"^0.7\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"bytecheck\":[\"dep:bytecheck\"],\"bytemuck\":[\"dep:bytemuck\"],\"default\":[\"std\"],\"libm\":[\"num-traits/libm\"],\"rand\":[\"dep:rand\"],\"rkyv\":[\"dep:rkyv\"],\"serde\":[\"dep:serde\"],\"std\":[\"num-traits/std\"]}}", "num-conv_0.1.0": "{\"dependencies\":[],\"features\":{}}", @@ -939,6 +985,8 @@ "pin-project_1.1.10": "{\"dependencies\":[{\"name\":\"pin-project-internal\",\"req\":\"=1.1.10\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1\"}],\"features\":{}}", "pin-utils_0.1.0": "{\"dependencies\":[],\"features\":{}}", "piper_0.2.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-channel\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"async-executor\",\"req\":\"^1.5.1\"},{\"kind\":\"dev\",\"name\":\"async-io\",\"req\":\"^2.0.0\"},{\"name\":\"atomic-waker\",\"req\":\"^1.1.0\"},{\"default_features\":false,\"features\":[\"cargo_bench_support\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"easy-parallel\",\"req\":\"^3.2.0\"},{\"default_features\":false,\"name\":\"fastrand\",\"req\":\"^2.0.0\"},{\"name\":\"futures-io\",\"optional\":true,\"req\":\"^0.3.28\"},{\"kind\":\"dev\",\"name\":\"futures-lite\",\"req\":\"^2.0.0\"},{\"features\":[\"alloc\"],\"name\":\"portable-atomic-util\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"portable_atomic_crate\",\"optional\":true,\"package\":\"portable-atomic\",\"req\":\"^1.2.0\"}],\"features\":{\"default\":[\"std\"],\"portable-atomic\":[\"atomic-waker/portable-atomic\",\"portable_atomic_crate\",\"portable-atomic-util\"],\"std\":[\"fastrand/std\",\"futures-io\"]}}", + "pkcs1_0.7.5": "{\"dependencies\":[{\"features\":[\"db\"],\"kind\":\"dev\",\"name\":\"const-oid\",\"req\":\"^0.9\"},{\"features\":[\"oid\"],\"name\":\"der\",\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"pkcs8\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"spki\",\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{\"alloc\":[\"der/alloc\",\"zeroize\",\"pkcs8?/alloc\"],\"pem\":[\"alloc\",\"der/pem\",\"pkcs8?/pem\"],\"std\":[\"der/std\",\"alloc\"],\"zeroize\":[\"der/zeroize\"]}}", + "pkcs8_0.10.2": "{\"dependencies\":[{\"features\":[\"oid\"],\"name\":\"der\",\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"},{\"name\":\"pkcs5\",\"optional\":true,\"req\":\"^0.7\"},{\"default_features\":false,\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"spki\",\"req\":\"^0.7.1\"},{\"default_features\":false,\"name\":\"subtle\",\"optional\":true,\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{\"3des\":[\"encryption\",\"pkcs5/3des\"],\"alloc\":[\"der/alloc\",\"der/zeroize\",\"spki/alloc\"],\"des-insecure\":[\"encryption\",\"pkcs5/des-insecure\"],\"encryption\":[\"alloc\",\"pkcs5/alloc\",\"pkcs5/pbes2\",\"rand_core\"],\"getrandom\":[\"rand_core/getrandom\"],\"pem\":[\"alloc\",\"der/pem\",\"spki/pem\"],\"sha1-insecure\":[\"encryption\",\"pkcs5/sha1-insecure\"],\"std\":[\"alloc\",\"der/std\",\"spki/std\"]}}", "pkg-config_0.3.32": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1\"}],\"features\":{}}", "plist_1.7.4": "{\"dependencies\":[{\"name\":\"base64\",\"req\":\"^0.22.0\"},{\"name\":\"indexmap\",\"req\":\"^2.1.0\"},{\"name\":\"quick_xml\",\"package\":\"quick-xml\",\"req\":\"^0.38.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.2\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0.2\"},{\"kind\":\"dev\",\"name\":\"serde_yaml\",\"req\":\"^0.8.21\"},{\"features\":[\"parsing\",\"formatting\"],\"name\":\"time\",\"req\":\"^0.3.30\"}],\"features\":{\"default\":[\"serde\"],\"enable_unstable_features_that_may_break_with_minor_version_bumps\":[]}}", "png_0.18.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"approx\",\"req\":\"^0.5.1\"},{\"name\":\"bitflags\",\"req\":\"^2.0\"},{\"kind\":\"dev\",\"name\":\"byteorder\",\"req\":\"^1.5.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^4.0\"},{\"name\":\"crc32fast\",\"req\":\"^1.2.0\"},{\"default_features\":false,\"features\":[\"cargo_bench_support\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.7.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.7.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"fdeflate\",\"req\":\"^0.3.3\"},{\"name\":\"flate2\",\"req\":\"^1.0.35\"},{\"kind\":\"dev\",\"name\":\"glob\",\"req\":\"^0.3\"},{\"features\":[\"simd\"],\"name\":\"miniz_oxide\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9.2\"}],\"features\":{\"benchmarks\":[],\"unstable\":[\"crc32fast/nightly\"],\"zlib-rs\":[\"flate2/zlib-rs\"]}}", @@ -960,6 +1008,8 @@ "proptest_1.9.0": "{\"dependencies\":[{\"name\":\"bit-set\",\"optional\":true,\"req\":\"^0.8.0\"},{\"name\":\"bit-vec\",\"optional\":true,\"req\":\"^0.8.0\"},{\"name\":\"bitflags\",\"req\":\"^2.9\"},{\"default_features\":false,\"name\":\"num-traits\",\"req\":\"^0.2.15\"},{\"name\":\"proptest-macro\",\"optional\":true,\"req\":\"^0.4.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"rand\",\"req\":\"^0.9\"},{\"default_features\":false,\"name\":\"rand_chacha\",\"req\":\"^0.9\"},{\"name\":\"rand_xorshift\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.0\"},{\"name\":\"regex-syntax\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"rusty-fork\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"tempfile\",\"optional\":true,\"req\":\"^3.0\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"=1.0.112\"},{\"name\":\"unarray\",\"req\":\"^0.1.4\"},{\"name\":\"x86\",\"optional\":true,\"req\":\"^0.52.0\"}],\"features\":{\"alloc\":[],\"atomic64bit\":[],\"attr-macro\":[\"proptest-macro\"],\"bit-set\":[\"dep:bit-set\",\"dep:bit-vec\"],\"default\":[\"std\",\"fork\",\"timeout\",\"bit-set\"],\"default-code-coverage\":[\"std\",\"fork\",\"timeout\",\"bit-set\"],\"fork\":[\"std\",\"rusty-fork\",\"tempfile\"],\"handle-panics\":[\"std\"],\"hardware-rng\":[\"x86\"],\"no_std\":[\"num-traits/libm\"],\"std\":[\"rand/std\",\"rand/os_rng\",\"regex-syntax\",\"num-traits/std\"],\"timeout\":[\"fork\",\"rusty-fork/timeout\"],\"unstable\":[]}}", "prost-derive_0.14.1": "{\"dependencies\":[{\"name\":\"anyhow\",\"req\":\"^1.0.1\"},{\"name\":\"itertools\",\"req\":\">=0.10.1, <=0.14\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "prost_0.14.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"name\":\"prost-derive\",\"optional\":true,\"req\":\"^0.14.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"}],\"features\":{\"default\":[\"derive\",\"std\"],\"derive\":[\"dep:prost-derive\"],\"no-recursion-limit\":[],\"std\":[]}}", + "psl-types_2.0.11": "{\"dependencies\":[],\"features\":{}}", + "psl_2.1.178": "{\"dependencies\":[{\"name\":\"psl-types\",\"req\":\"^2.0.11\"},{\"kind\":\"dev\",\"name\":\"rspec\",\"req\":\"^1.0.0\"}],\"features\":{\"default\":[\"helpers\"],\"helpers\":[]}}", "pulldown-cmark-escape_0.10.1": "{\"dependencies\":[],\"features\":{\"simd\":[]}}", "pulldown-cmark_0.10.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"name\":\"bitflags\",\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"getopts\",\"optional\":true,\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"name\":\"memchr\",\"req\":\"^2.5\"},{\"name\":\"pulldown-cmark-escape\",\"optional\":true,\"req\":\"^0.10.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.6\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.61\"},{\"name\":\"unicase\",\"req\":\"^2.6\"}],\"features\":{\"default\":[\"getopts\",\"html\"],\"gen-tests\":[],\"html\":[\"pulldown-cmark-escape\"],\"simd\":[\"pulldown-cmark-escape?/simd\"]}}", "pxfm_0.1.23": "{\"dependencies\":[{\"name\":\"num-traits\",\"req\":\"^0.2\"}],\"features\":{}}", @@ -972,6 +1022,26 @@ "quote_1.0.40": "{\"dependencies\":[{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.80\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.66\"}],\"features\":{\"default\":[\"proc-macro\"],\"proc-macro\":[\"proc-macro2/proc-macro\"]}}", "r-efi_5.3.0": "{\"dependencies\":[{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"}],\"features\":{\"efiapi\":[],\"examples\":[\"native\"],\"native\":[],\"rustc-dep-of-std\":[\"core\"]}}", "radix_trie_0.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"},{\"name\":\"endian-type\",\"req\":\"^0.1.2\"},{\"name\":\"nibble_vec\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{}}", + "radix_trie_0.3.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"},{\"name\":\"endian-type\",\"req\":\"^0.2.0\"},{\"name\":\"nibble_vec\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{}}", + "rama-boring-sys_0.5.9": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"runtime\"],\"kind\":\"build\",\"name\":\"bindgen\",\"req\":\"^0.72.0\"},{\"kind\":\"build\",\"name\":\"cmake\",\"req\":\"^0.1.54\"},{\"kind\":\"build\",\"name\":\"fs_extra\",\"req\":\"^1.3.0\"},{\"kind\":\"build\",\"name\":\"fslock\",\"req\":\"^0.2\"}],\"features\":{}}", + "rama-boring-tokio_0.5.9": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"rama-boring\",\"req\":\"^0.5.9\"},{\"name\":\"rama-boring-sys\",\"req\":\"^0.5.9\"},{\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"}],\"features\":{}}", + "rama-boring_0.5.9": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.9\"},{\"kind\":\"dev\",\"name\":\"brotli\",\"req\":\"^8.0\"},{\"name\":\"foreign-types\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"openssl-macros\",\"req\":\"^0.1.1\"},{\"name\":\"rama-boring-sys\",\"req\":\"^0.5.9\"},{\"kind\":\"dev\",\"name\":\"rusty-hook\",\"req\":\"^0.11\"}],\"features\":{}}", + "rama-core_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"asynk-strim\",\"req\":\"^0.1\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"trace\"],\"name\":\"opentelemetry\",\"optional\":true,\"req\":\"^0.31\"},{\"features\":[\"semconv_experimental\"],\"name\":\"opentelemetry-semantic-conventions\",\"optional\":true,\"req\":\"^0.31\"},{\"default_features\":false,\"features\":[\"trace\",\"rt-tokio\"],\"name\":\"opentelemetry_sdk\",\"optional\":true,\"req\":\"^0.31\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"name\":\"rama-error\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-macros\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"macros\",\"fs\",\"io-std\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.48\"},{\"name\":\"tokio-graceful\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"features\":[\"codec\",\"io\",\"io-util\"],\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"name\":\"tracing-opentelemetry\",\"optional\":true,\"req\":\"^0.32\"}],\"features\":{\"default\":[],\"opentelemetry\":[\"dep:opentelemetry\",\"dep:opentelemetry-semantic-conventions\",\"dep:opentelemetry_sdk\",\"dep:tracing-opentelemetry\"]}}", + "rama-dns_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"default_features\":false,\"features\":[\"tokio\",\"system-config\"],\"name\":\"hickory-resolver\",\"req\":\"^0.25\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_html_form\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"macros\",\"net\"],\"name\":\"tokio\",\"req\":\"^1.48\"}],\"features\":{\"default\":[]}}", + "rama-error_0.3.0-alpha.4": "{\"dependencies\":[],\"features\":{}}", + "rama-http-backend_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"h2\",\"req\":\"^0.4\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-headers\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-types\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"http\"],\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"http\"],\"name\":\"rama-tcp\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-unix\",\"req\":\"^0.3.0-alpha.4\",\"target\":\"cfg(target_family = \\\"unix\\\")\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"macros\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"}],\"features\":{\"default\":[],\"tls\":[\"rama-net/tls\"]}}", + "rama-http-core_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"atomic-waker\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"name\":\"futures-channel\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"name\":\"httparse\",\"req\":\"^1.10\"},{\"name\":\"httpdate\",\"req\":\"^1.0\"},{\"features\":[\"std\"],\"name\":\"indexmap\",\"req\":\"^2\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-types\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"slab\",\"req\":\"^0.4\"},{\"features\":[\"io-util\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"features\":[\"rt-multi-thread\",\"macros\",\"sync\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.48\"},{\"default_features\":false,\"features\":[\"logging\",\"tls12\",\"aws_lc_rs\"],\"kind\":\"dev\",\"name\":\"tokio-rustls\",\"req\":\"^0.26\"},{\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.5\"},{\"name\":\"want\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1.0\"}],\"features\":{\"default\":[],\"unstable\":[]}}", + "rama-http-headers_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"base64\",\"req\":\"^0.22\"},{\"default_features\":false,\"features\":[\"serde\",\"oldtime\",\"clock\"],\"name\":\"chrono\",\"req\":\"^0.4\"},{\"name\":\"const_format\",\"req\":\"^0.2\"},{\"name\":\"httpdate\",\"req\":\"^1.0\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-error\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-types\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-macros\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"http\"],\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rand\",\"req\":\"^0.9\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"sha1\",\"req\":\"^0.10\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"tracing-test\",\"req\":\"^0.2\"}],\"features\":{}}", + "rama-http-types_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"const_format\",\"req\":\"^0.2\"},{\"name\":\"fnv\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"name\":\"http\",\"req\":\"^1\"},{\"name\":\"http-body\",\"req\":\"^1\"},{\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"name\":\"memchr\",\"req\":\"^2.7\"},{\"name\":\"mime\",\"req\":\"^0.3.17\"},{\"default_features\":false,\"name\":\"mime_guess\",\"req\":\"^2\"},{\"name\":\"nom\",\"req\":\"^8.0.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-error\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-macros\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sync_wrapper\",\"req\":\"^1.0\"},{\"features\":[\"macros\",\"io-std\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"}],\"features\":{\"default\":[]}}", + "rama-http_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"features\":[\"tokio\",\"brotli\",\"zlib\",\"gzip\",\"zstd\"],\"name\":\"async-compression\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"base64\",\"req\":\"^0.22\"},{\"name\":\"bitflags\",\"req\":\"^2.10\"},{\"kind\":\"dev\",\"name\":\"brotli\",\"req\":\"^8\"},{\"default_features\":false,\"features\":[\"serde\",\"oldtime\",\"clock\"],\"name\":\"chrono\",\"req\":\"^0.4\"},{\"features\":[\"brotli\",\"deflate\",\"gzip\",\"zstd\"],\"name\":\"compression-codecs\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"compression-core\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"const_format\",\"req\":\"^0.2\"},{\"name\":\"csv\",\"req\":\"^1.4\"},{\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.1\"},{\"name\":\"http\",\"req\":\"^1\"},{\"name\":\"http-range-header\",\"req\":\"^0.4\"},{\"name\":\"httpdate\",\"req\":\"^1.0\"},{\"name\":\"iri-string\",\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.14\"},{\"name\":\"matchit\",\"req\":\"^0.9\"},{\"default_features\":false,\"name\":\"opentelemetry-http\",\"optional\":true,\"req\":\"^0.31\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"percent-encoding\",\"req\":\"^2.3\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"radix_trie\",\"req\":\"^0.3\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-error\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-headers\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-types\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"http\"],\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"kind\":\"dev\",\"name\":\"rama-tcp\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rand\",\"req\":\"^0.9\"},{\"name\":\"rawzip\",\"optional\":true,\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_html_form\",\"req\":\"^0.3\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.23\"},{\"features\":[\"macros\",\"fs\",\"io-std\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"features\":[\"env-filter\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tracing-test\",\"req\":\"^0.2\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"req\":\"^1.18\"},{\"kind\":\"dev\",\"name\":\"zstd\",\"req\":\"^0.13\"}],\"features\":{\"compression\":[\"dep:async-compression\",\"dep:compression-codecs\",\"dep:compression-core\",\"dep:rawzip\",\"dep:flate2\"],\"default\":[],\"opentelemetry\":[\"rama-core/opentelemetry\",\"rama-net/opentelemetry\",\"dep:opentelemetry-http\"],\"tls\":[\"rama-net/tls\"]}}", + "rama-macros_0.3.0-alpha.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"paste-test-suite\",\"req\":\"^0\"},{\"name\":\"proc-macro-crate\",\"req\":\"^3.4\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"}],\"features\":{}}", + "rama-net_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"const_format\",\"req\":\"^0.2\"},{\"features\":[\"async\"],\"name\":\"flume\",\"req\":\"^0.12\"},{\"name\":\"hex\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"ipnet\",\"req\":\"^2.11\"},{\"name\":\"itertools\",\"req\":\"^0.14\"},{\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.14\"},{\"name\":\"md5\",\"optional\":true,\"req\":\"^0.8\"},{\"name\":\"nom\",\"req\":\"^8.0.0\"},{\"kind\":\"dev\",\"name\":\"nom\",\"req\":\"^8.0.0\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"psl\",\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"name\":\"radix_trie\",\"req\":\"^0.3\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-types\",\"optional\":true,\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-macros\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"features\":[\"all\"],\"name\":\"socket2\",\"req\":\"^0.6\"},{\"features\":[\"macros\",\"fs\",\"io-std\",\"io-util\",\"net\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"name\":\"venndb\",\"optional\":true,\"req\":\"^0.6\"}],\"features\":{\"default\":[],\"http\":[\"dep:rama-http-types\",\"dep:sha2\",\"dep:hex\",\"dep:md5\"],\"opentelemetry\":[\"rama-core/opentelemetry\"],\"tls\":[\"dep:hex\",\"dep:md5\",\"dep:sha2\"]}}", + "rama-socks5_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"byteorder\",\"req\":\"^1.5\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-dns\",\"optional\":true,\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"http\"],\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"http\"],\"name\":\"rama-tcp\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-udp\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.9\"},{\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"}],\"features\":{\"default\":[],\"dns\":[\"dep:rama-dns\",\"dep:rand\"]}}", + "rama-tcp_0.3.0-alpha.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-dns\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-types\",\"optional\":true,\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rand\",\"req\":\"^0.9\"},{\"features\":[\"macros\",\"net\"],\"name\":\"tokio\",\"req\":\"^1.48\"}],\"features\":{\"default\":[],\"http\":[\"dep:rama-http-types\",\"rama-net/http\"]}}", + "rama-tls-boring_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"brotli\",\"optional\":true,\"req\":\"^8\"},{\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.1\"},{\"features\":[\"async\"],\"name\":\"flume\",\"req\":\"^0.12\"},{\"name\":\"itertools\",\"req\":\"^0.14\"},{\"features\":[\"sync\"],\"name\":\"moka\",\"req\":\"^0.12\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"rama-boring\",\"req\":\"^0.5.7\"},{\"name\":\"rama-boring-tokio\",\"req\":\"^0.5.7\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-http-types\",\"optional\":true,\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"tls\",\"http\"],\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"tls\"],\"name\":\"rama-ua\",\"optional\":true,\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-utils\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"schannel\",\"req\":\"^0.1\",\"target\":\"cfg(target_os = \\\"windows\\\")\"},{\"features\":[\"macros\",\"io-std\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tracing-test\",\"req\":\"^0.2\"},{\"name\":\"zstd\",\"optional\":true,\"req\":\"^0.13\"}],\"features\":{\"compression\":[\"dep:flate2\",\"dep:brotli\",\"dep:zstd\"],\"default\":[],\"http\":[\"dep:rama-http-types\"],\"ua\":[\"dep:rama-ua\"]}}", + "rama-udp_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"macros\",\"net\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"features\":[\"net\"],\"name\":\"tokio-util\",\"req\":\"^0.7\"}],\"features\":{\"default\":[]}}", + "rama-unix_0.3.0-alpha.4": "{\"dependencies\":[{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"rama-core\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"rama-net\",\"req\":\"^0.3.0-alpha.4\"},{\"features\":[\"macros\",\"net\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.48\"}],\"features\":{\"default\":[]}}", + "rama-utils_0.3.0-alpha.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"const_format\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"name\":\"rama-macros\",\"req\":\"^0.3.0-alpha.4\"},{\"name\":\"regex\",\"req\":\"^1.12\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1\"},{\"features\":[\"write\",\"serde\",\"const_generics\",\"const_new\"],\"name\":\"smallvec\",\"req\":\"^1.15\"},{\"name\":\"smol_str\",\"req\":\"^0.3\"},{\"features\":[\"time\",\"macros\"],\"name\":\"tokio\",\"req\":\"^1.48\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"},{\"name\":\"wildcard\",\"req\":\"^0.3\"}],\"features\":{}}", "rand_0.8.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.2.1\"},{\"default_features\":false,\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.22\",\"target\":\"cfg(unix)\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.4\"},{\"features\":[\"into_bits\"],\"name\":\"packed_simd\",\"optional\":true,\"package\":\"packed_simd_2\",\"req\":\"^0.3.7\"},{\"default_features\":false,\"name\":\"rand_chacha\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"rand_core\",\"req\":\"^0.6.0\"},{\"kind\":\"dev\",\"name\":\"rand_pcg\",\"req\":\"^0.3.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.103\"}],\"features\":{\"alloc\":[\"rand_core/alloc\"],\"default\":[\"std\",\"std_rng\"],\"getrandom\":[\"rand_core/getrandom\"],\"min_const_gen\":[],\"nightly\":[],\"serde1\":[\"serde\",\"rand_core/serde1\"],\"simd_support\":[\"packed_simd\"],\"small_rng\":[],\"std\":[\"rand_core/std\",\"rand_chacha/std\",\"alloc\",\"getrandom\",\"libc\"],\"std_rng\":[\"rand_chacha\"]}}", "rand_0.9.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.2.1\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.4\"},{\"default_features\":false,\"name\":\"rand_chacha\",\"optional\":true,\"req\":\"^0.9.0\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"rand_pcg\",\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.7\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.103\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.140\"}],\"features\":{\"alloc\":[],\"default\":[\"std\",\"std_rng\",\"os_rng\",\"small_rng\",\"thread_rng\"],\"log\":[\"dep:log\"],\"nightly\":[],\"os_rng\":[\"rand_core/os_rng\"],\"serde\":[\"dep:serde\",\"rand_core/serde\"],\"simd_support\":[],\"small_rng\":[],\"std\":[\"rand_core/std\",\"rand_chacha?/std\",\"alloc\"],\"std_rng\":[\"dep:rand_chacha\"],\"thread_rng\":[\"std\",\"std_rng\",\"os_rng\"],\"unbiased\":[]}}", "rand_chacha_0.3.1": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"simd\"],\"name\":\"ppv-lite86\",\"req\":\"^0.2.8\"},{\"name\":\"rand_core\",\"req\":\"^0.6.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"serde1\":[\"serde\"],\"simd\":[],\"std\":[\"ppv-lite86/std\"]}}", @@ -980,6 +1050,8 @@ "rand_core_0.9.3": "{\"dependencies\":[{\"name\":\"getrandom\",\"optional\":true,\"req\":\"^0.3.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"os_rng\":[\"dep:getrandom\"],\"serde\":[\"dep:serde\"],\"std\":[\"getrandom?/std\"]}}", "rand_xorshift_0.4.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1\"},{\"name\":\"rand_core\",\"req\":\"^0.9.0\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.118\"}],\"features\":{\"serde\":[\"dep:serde\"]}}", "ratatui-macros_0.6.0": "{\"dependencies\":[{\"features\":[\"user-hooks\"],\"kind\":\"dev\",\"name\":\"cargo-husky\",\"req\":\"^1.5.0\"},{\"name\":\"ratatui\",\"req\":\"^0.29.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.101\"}],\"features\":{}}", + "rayon-core_1.13.0": "{\"dependencies\":[{\"name\":\"crossbeam-deque\",\"req\":\"^0.8.1\"},{\"name\":\"crossbeam-utils\",\"req\":\"^0.8.0\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"rand_xorshift\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"scoped-tls\",\"req\":\"^1.0\"},{\"name\":\"wasm_sync\",\"optional\":true,\"req\":\"^0.1.0\"}],\"features\":{\"web_spin_lock\":[\"dep:wasm_sync\"]}}", + "rayon_1.11.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"either\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"rand_xorshift\",\"req\":\"^0.4\"},{\"name\":\"rayon-core\",\"req\":\"^1.13.0\"},{\"name\":\"wasm_sync\",\"optional\":true,\"req\":\"^0.1.0\"}],\"features\":{\"web_spin_lock\":[\"dep:wasm_sync\",\"rayon-core/web_spin_lock\"]}}", "redox_syscall_0.5.15": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.4\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(loom)\"}],\"features\":{\"default\":[\"userspace\"],\"rustc-dep-of-std\":[\"core\",\"bitflags/rustc-dep-of-std\"],\"std\":[],\"userspace\":[]}}", "redox_users_0.4.6": "{\"dependencies\":[{\"features\":[\"std\"],\"name\":\"getrandom\",\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"std\",\"call\"],\"name\":\"libredox\",\"req\":\"^0.1.3\"},{\"name\":\"rust-argon2\",\"optional\":true,\"req\":\"^0.8\"},{\"name\":\"thiserror\",\"req\":\"^1.0\"},{\"features\":[\"zeroize_derive\"],\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.4\"}],\"features\":{\"auth\":[\"rust-argon2\",\"zeroize\"],\"default\":[\"auth\"]}}", "redox_users_0.5.0": "{\"dependencies\":[{\"features\":[\"std\"],\"name\":\"getrandom\",\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"std\",\"call\"],\"name\":\"libredox\",\"req\":\"^0.1.3\"},{\"name\":\"rust-argon2\",\"optional\":true,\"req\":\"^0.8\"},{\"name\":\"thiserror\",\"req\":\"^2.0\"},{\"features\":[\"zeroize_derive\"],\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.4\"}],\"features\":{\"auth\":[\"rust-argon2\",\"zeroize\"],\"default\":[\"auth\"]}}", @@ -991,9 +1063,11 @@ "regex-syntax_0.8.5": "{\"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.2": "{\"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.12.24": "{\"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.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.21.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\",\"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\":[\"codec\",\"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.5\",\"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\":[\"dep:async-compression\",\"async-compression?/brotli\",\"dep:futures-util\",\"dep:tokio-util\"],\"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\":[\"dep:async-compression\",\"async-compression?/zlib\",\"dep:futures-util\",\"dep:tokio-util\"],\"gzip\":[\"dep:async-compression\",\"async-compression?/gzip\",\"dep:futures-util\",\"dep:tokio-util\"],\"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\":[\"dep:async-compression\",\"async-compression?/zstd\",\"dep:futures-util\",\"dep:tokio-util\"]}}", + "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\"]}}", "rmcp-macros_0.12.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.23\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "rmcp_0.12.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.89\"},{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"name\":\"axum\",\"optional\":true,\"req\":\"^0.8\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"serde\",\"clock\",\"std\",\"oldtime\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"serde\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"oauth2\",\"optional\":true,\"req\":\"^5.0\"},{\"name\":\"pastey\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"tokio1\"],\"name\":\"process-wrap\",\"optional\":true,\"req\":\"^9.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"json\",\"stream\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"name\":\"rmcp-macros\",\"optional\":true,\"req\":\"^0.12.0\"},{\"features\":[\"chrono04\"],\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"chrono04\"],\"kind\":\"dev\",\"name\":\"schemars\",\"req\":\"^1.1.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sse-stream\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"sync\",\"macros\",\"rt\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.4\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"__reqwest\":[\"dep:reqwest\"],\"auth\":[\"dep:oauth2\",\"__reqwest\",\"dep:url\"],\"client\":[\"dep:tokio-stream\"],\"client-side-sse\":[\"dep:sse-stream\",\"dep:http\"],\"default\":[\"base64\",\"macros\",\"server\"],\"elicitation\":[],\"macros\":[\"dep:rmcp-macros\",\"dep:pastey\"],\"reqwest\":[\"__reqwest\",\"reqwest?/rustls-tls\"],\"reqwest-tls-no-provider\":[\"__reqwest\",\"reqwest?/rustls-tls-no-provider\"],\"schemars\":[\"dep:schemars\"],\"server\":[\"transport-async-rw\",\"dep:schemars\"],\"server-side-http\":[\"uuid\",\"dep:rand\",\"dep:tokio-stream\",\"dep:http\",\"dep:http-body\",\"dep:http-body-util\",\"dep:bytes\",\"dep:sse-stream\",\"tower\"],\"tower\":[\"dep:tower-service\"],\"transport-async-rw\":[\"tokio/io-util\",\"tokio-util/codec\"],\"transport-child-process\":[\"transport-async-rw\",\"tokio/process\",\"dep:process-wrap\"],\"transport-io\":[\"transport-async-rw\",\"tokio/io-std\"],\"transport-streamable-http-client\":[\"client-side-sse\",\"transport-worker\"],\"transport-streamable-http-client-reqwest\":[\"transport-streamable-http-client\",\"reqwest\"],\"transport-streamable-http-server\":[\"transport-streamable-http-server-session\",\"server-side-http\",\"transport-worker\"],\"transport-streamable-http-server-session\":[\"transport-async-rw\",\"dep:tokio-stream\"],\"transport-worker\":[\"dep:tokio-stream\"]}}", + "rsa_0.9.10": "{\"dependencies\":[{\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"base64ct\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"const-oid\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"alloc\",\"oid\"],\"name\":\"digest\",\"req\":\"^0.10.5\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4.1\"},{\"default_features\":false,\"features\":[\"i128\",\"prime\",\"zeroize\"],\"name\":\"num-bigint\",\"package\":\"num-bigint-dig\",\"req\":\"^0.8.6\"},{\"default_features\":false,\"name\":\"num-integer\",\"req\":\"^0.1.39\"},{\"default_features\":false,\"features\":[\"libm\"],\"name\":\"num-traits\",\"req\":\"^0.2.9\"},{\"default_features\":false,\"features\":[\"alloc\",\"pkcs8\"],\"name\":\"pkcs1\",\"req\":\"^0.7.5\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"pkcs8\",\"req\":\"^0.10.2\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand_chacha\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.6.4\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"rand_xorshift\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.184\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0.89\"},{\"default_features\":false,\"features\":[\"oid\"],\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10.5\"},{\"default_features\":false,\"features\":[\"oid\"],\"kind\":\"dev\",\"name\":\"sha1\",\"req\":\"^0.10.5\"},{\"default_features\":false,\"features\":[\"oid\"],\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10.6\"},{\"default_features\":false,\"features\":[\"oid\"],\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10.6\"},{\"default_features\":false,\"features\":[\"oid\"],\"kind\":\"dev\",\"name\":\"sha3\",\"req\":\"^0.10.7\"},{\"default_features\":false,\"features\":[\"alloc\",\"digest\",\"rand_core\"],\"name\":\"signature\",\"req\":\">2.0, <2.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"spki\",\"req\":\"^0.7.3\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2.1.1\"},{\"features\":[\"alloc\"],\"name\":\"zeroize\",\"req\":\"^1.5\"}],\"features\":{\"default\":[\"std\",\"pem\",\"u64_digit\"],\"getrandom\":[\"rand_core/getrandom\"],\"hazmat\":[],\"nightly\":[\"num-bigint/nightly\"],\"pem\":[\"pkcs1/pem\",\"pkcs8/pem\"],\"pkcs5\":[\"pkcs8/encryption\"],\"serde\":[\"dep:serde\",\"num-bigint/serde\"],\"std\":[\"digest/std\",\"pkcs1/std\",\"pkcs8/std\",\"rand_core/std\",\"signature/std\"],\"u64_digit\":[\"num-bigint/u64_digit\"]}}", "rustc-demangle_0.1.25": "{\"dependencies\":[{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"}],\"features\":{\"compiler_builtins\":[],\"rustc-dep-of-std\":[\"core\"],\"std\":[]}}", "rustc-hash_2.1.1": "{\"dependencies\":[{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"nightly\":[],\"rand\":[\"dep:rand\",\"std\"],\"std\":[]}}", "rustc_version_0.4.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"semver\",\"req\":\"^1.0\"}],\"features\":{}}", @@ -1017,6 +1091,7 @@ "schemars_1.0.4": "{\"dependencies\":[{\"default_features\":false,\"name\":\"arrayvec07\",\"optional\":true,\"package\":\"arrayvec\",\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"arrayvec07\",\"package\":\"arrayvec\",\"req\":\"^0.7\"},{\"default_features\":false,\"name\":\"bigdecimal04\",\"optional\":true,\"package\":\"bigdecimal\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"bigdecimal04\",\"package\":\"bigdecimal\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"bytes1\",\"optional\":true,\"package\":\"bytes\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"bytes1\",\"package\":\"bytes\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"chrono04\",\"optional\":true,\"package\":\"chrono\",\"req\":\"^0.4.39\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"chrono04\",\"package\":\"chrono\",\"req\":\"^0.4\"},{\"name\":\"dyn-clone\",\"req\":\"^1.0.17\"},{\"default_features\":false,\"name\":\"either1\",\"optional\":true,\"package\":\"either\",\"req\":\"^1.3\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"either1\",\"package\":\"either\",\"req\":\"^1.3\"},{\"features\":[\"derive\",\"email\",\"regex\",\"url\"],\"kind\":\"dev\",\"name\":\"garde\",\"req\":\"^0.22\"},{\"default_features\":false,\"name\":\"indexmap2\",\"optional\":true,\"package\":\"indexmap\",\"req\":\"^2.2.3\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"indexmap2\",\"package\":\"indexmap\",\"req\":\"^2.0\"},{\"default_features\":false,\"name\":\"jiff02\",\"optional\":true,\"package\":\"jiff\",\"req\":\"^0.2\"},{\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"jiff02\",\"package\":\"jiff\",\"req\":\"^0.2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"jsonschema\",\"req\":\"^0.30\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.2.1\"},{\"name\":\"ref-cast\",\"req\":\"^1.0.22\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.10.6\"},{\"default_features\":false,\"name\":\"rust_decimal1\",\"optional\":true,\"package\":\"rust_decimal\",\"req\":\"^1.13\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"rust_decimal1\",\"package\":\"rust_decimal\",\"req\":\"^1\"},{\"name\":\"schemars_derive\",\"optional\":true,\"req\":\"=1.0.4\"},{\"default_features\":false,\"name\":\"semver1\",\"optional\":true,\"package\":\"semver\",\"req\":\"^1.0.9\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"semver1\",\"package\":\"semver\",\"req\":\"^1.0.9\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"req\":\"^1.0.194\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde_json\",\"req\":\"^1.0.127\"},{\"kind\":\"dev\",\"name\":\"serde_repr\",\"req\":\"^0.1.19\"},{\"default_features\":false,\"name\":\"smallvec1\",\"optional\":true,\"package\":\"smallvec\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"smallvec1\",\"package\":\"smallvec\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"smol_str02\",\"optional\":true,\"package\":\"smol_str\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"smol_str02\",\"package\":\"smol_str\",\"req\":\"^0.2.1\"},{\"features\":[\"json\"],\"kind\":\"dev\",\"name\":\"snapbox\",\"req\":\"^0.6.17\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"url2\",\"optional\":true,\"package\":\"url\",\"req\":\"^2.0\"},{\"default_features\":false,\"features\":[\"serde\",\"std\"],\"kind\":\"dev\",\"name\":\"url2\",\"package\":\"url\",\"req\":\"^2.0\"},{\"default_features\":false,\"name\":\"uuid1\",\"optional\":true,\"package\":\"uuid\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"serde\"],\"kind\":\"dev\",\"name\":\"uuid1\",\"package\":\"uuid\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"validator\",\"req\":\"^0.20\"}],\"features\":{\"_ui_test\":[],\"default\":[\"derive\",\"std\"],\"derive\":[\"schemars_derive\"],\"preserve_order\":[\"serde_json/preserve_order\"],\"raw_value\":[\"serde_json/raw_value\"],\"std\":[]}}", "schemars_derive_0.8.22": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.2.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"name\":\"serde_derive_internals\",\"req\":\"^0.29\"},{\"features\":[\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "schemars_derive_1.0.4": "{\"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\":[]}}", "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\"]}}", @@ -1038,6 +1113,7 @@ "serde_core_1.0.228": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"name\":\"serde_derive\",\"req\":\"=1.0.228\",\"target\":\"cfg(any())\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1\"}],\"features\":{\"alloc\":[],\"default\":[\"std\",\"result\"],\"rc\":[],\"result\":[],\"std\":[],\"unstable\":[]}}", "serde_derive_1.0.228": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"proc-macro\"],\"name\":\"proc-macro2\",\"req\":\"^1.0.74\"},{\"default_features\":false,\"features\":[\"proc-macro\"],\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"clone-impls\",\"derive\",\"parsing\",\"printing\",\"proc-macro\"],\"name\":\"syn\",\"req\":\"^2.0.81\"}],\"features\":{\"default\":[],\"deserialize_in_place\":[]}}", "serde_derive_internals_0.29.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.74\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"default_features\":false,\"features\":[\"clone-impls\",\"derive\",\"parsing\",\"printing\"],\"name\":\"syn\",\"req\":\"^2.0.46\"}],\"features\":{}}", + "serde_html_form_0.3.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert_matches2\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"divan\",\"req\":\"^0.1.11\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"form_urlencoded\",\"req\":\"^1.0.1\"},{\"default_features\":false,\"name\":\"indexmap\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.45.0\"},{\"name\":\"itoa\",\"req\":\"^1.0.1\"},{\"name\":\"ryu\",\"optional\":true,\"req\":\"^1.0.9\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.221\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde_core\",\"req\":\"^1.0.221\"},{\"kind\":\"dev\",\"name\":\"serde_urlencoded\",\"req\":\"^0.7.1\"}],\"features\":{\"default\":[\"ryu\",\"std\"],\"std\":[]}}", "serde_json_1.0.145": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.11\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.2.3\"},{\"kind\":\"dev\",\"name\":\"indoc\",\"req\":\"^2.0.2\"},{\"name\":\"itoa\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"ref-cast\",\"req\":\"^1.0.18\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.13\"},{\"name\":\"ryu\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde\",\"req\":\"^1.0.220\",\"target\":\"cfg(any())\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.194\"},{\"kind\":\"dev\",\"name\":\"serde_bytes\",\"req\":\"^0.11.10\"},{\"default_features\":false,\"name\":\"serde_core\",\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0.166\"},{\"kind\":\"dev\",\"name\":\"serde_stacker\",\"req\":\"^0.1.8\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.108\"}],\"features\":{\"alloc\":[\"serde_core/alloc\"],\"arbitrary_precision\":[],\"default\":[\"std\"],\"float_roundtrip\":[],\"preserve_order\":[\"indexmap\",\"std\"],\"raw_value\":[],\"std\":[\"memchr/std\",\"serde_core/std\"],\"unbounded_depth\":[]}}", "serde_path_to_error_0.1.20": "{\"dependencies\":[{\"name\":\"itoa\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde\",\"req\":\"^1.0.220\",\"target\":\"cfg(any())\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.220\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde_core\",\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.100\"}],\"features\":{}}", "serde_repr_0.1.20": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0.74\"},{\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.13\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.166\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.100\"},{\"name\":\"syn\",\"req\":\"^2.0.46\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.81\"}],\"features\":{}}", @@ -1059,6 +1135,7 @@ "signal-hook-mio_0.2.4": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"~0.2\"},{\"name\":\"mio-0_6\",\"optional\":true,\"package\":\"mio\",\"req\":\"~0.6\"},{\"features\":[\"os-util\",\"uds\"],\"name\":\"mio-0_7\",\"optional\":true,\"package\":\"mio\",\"req\":\"~0.7\"},{\"features\":[\"os-util\",\"os-poll\",\"uds\"],\"kind\":\"dev\",\"name\":\"mio-0_7\",\"package\":\"mio\",\"req\":\"~0.7\"},{\"features\":[\"net\",\"os-ext\"],\"name\":\"mio-0_8\",\"optional\":true,\"package\":\"mio\",\"req\":\"~0.8\"},{\"features\":[\"net\",\"os-ext\"],\"name\":\"mio-1_0\",\"optional\":true,\"package\":\"mio\",\"req\":\"~1.0\"},{\"name\":\"mio-uds\",\"optional\":true,\"req\":\"~0.6\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"~0.5\"},{\"name\":\"signal-hook\",\"req\":\"~0.3\"}],\"features\":{\"support-v0_6\":[\"mio-0_6\",\"mio-uds\"],\"support-v0_7\":[\"mio-0_7\"],\"support-v0_8\":[\"mio-0_8\"],\"support-v1_0\":[\"mio-1_0\"]}}", "signal-hook-registry_1.4.5": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"signal-hook\",\"req\":\"~0.3\"}],\"features\":{}}", "signal-hook_0.3.18": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^0.7\"},{\"name\":\"signal-hook-registry\",\"req\":\"^1.4\"}],\"features\":{\"channel\":[],\"default\":[\"channel\",\"iterator\"],\"extended-siginfo\":[\"channel\",\"iterator\",\"extended-siginfo-raw\"],\"extended-siginfo-raw\":[\"cc\"],\"iterator\":[\"channel\"]}}", + "signature_2.2.0": "{\"dependencies\":[{\"name\":\"derive\",\"optional\":true,\"package\":\"signature_derive\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"digest\",\"optional\":true,\"req\":\"^0.10.6\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6.4\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"}],\"features\":{\"alloc\":[],\"std\":[\"alloc\",\"rand_core?/std\"]}}", "simd-adler32_0.3.7": "{\"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\"]}}", @@ -1066,8 +1143,18 @@ "slab_0.4.11": "{\"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\":[]}}", "smawk_0.3.2": "{\"dependencies\":[{\"name\":\"ndarray\",\"optional\":true,\"req\":\"^0.15.4\"},{\"kind\":\"dev\",\"name\":\"num-traits\",\"req\":\"^0.2.14\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"rand_chacha\",\"req\":\"^0.3.1\"},{\"kind\":\"dev\",\"name\":\"version-sync\",\"req\":\"^0.9.4\"}],\"features\":{}}", + "smol_str_0.3.5": "{\"dependencies\":[{\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.3\"},{\"default_features\":false,\"name\":\"borsh\",\"optional\":true,\"req\":\"^1.4.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.5\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9.2\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"serde\":[\"dep:serde_core\"],\"std\":[\"serde_core?/std\",\"borsh?/std\"]}}", "socket2_0.5.10": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.171\",\"target\":\"cfg(unix)\"},{\"features\":[\"Win32_Foundation\",\"Win32_Networking_WinSock\",\"Win32_System_IO\",\"Win32_System_Threading\",\"Win32_System_WindowsProgramming\"],\"name\":\"windows-sys\",\"req\":\"^0.52\",\"target\":\"cfg(windows)\"}],\"features\":{\"all\":[]}}", "socket2_0.6.1": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.172\",\"target\":\"cfg(unix)\"},{\"features\":[\"Win32_Foundation\",\"Win32_Networking_WinSock\",\"Win32_System_IO\",\"Win32_System_Threading\",\"Win32_System_WindowsProgramming\"],\"name\":\"windows-sys\",\"req\":\"^0.60\",\"target\":\"cfg(windows)\"}],\"features\":{\"all\":[]}}", + "spin_0.9.8": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4\"},{\"name\":\"lock_api_crate\",\"optional\":true,\"package\":\"lock_api\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"portable-atomic\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"barrier\":[\"mutex\"],\"default\":[\"lock_api\",\"mutex\",\"spin_mutex\",\"rwlock\",\"once\",\"lazy\",\"barrier\"],\"fair_mutex\":[\"mutex\"],\"lazy\":[\"once\"],\"lock_api\":[\"lock_api_crate\"],\"mutex\":[],\"once\":[],\"portable_atomic\":[\"portable-atomic\"],\"rwlock\":[],\"spin_mutex\":[\"mutex\"],\"std\":[],\"ticket_mutex\":[\"mutex\"],\"use_ticket_mutex\":[\"mutex\",\"ticket_mutex\"]}}", + "spki_0.7.3": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.2\"},{\"default_features\":false,\"name\":\"base64ct\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"oid\"],\"name\":\"der\",\"req\":\"^0.7.2\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{\"alloc\":[\"base64ct?/alloc\",\"der/alloc\"],\"arbitrary\":[\"std\",\"dep:arbitrary\",\"der/arbitrary\"],\"base64\":[\"dep:base64ct\"],\"fingerprint\":[\"sha2\"],\"pem\":[\"alloc\",\"der/pem\"],\"std\":[\"der/std\",\"alloc\"]}}", + "sqlx-core_0.8.6": "{\"dependencies\":[{\"name\":\"async-io\",\"optional\":true,\"req\":\"^1.9.0\"},{\"name\":\"async-std\",\"optional\":true,\"req\":\"^1.12\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"base64\",\"req\":\"^0.22.0\"},{\"name\":\"bigdecimal\",\"optional\":true,\"req\":\"^0.4.0\"},{\"name\":\"bit-vec\",\"optional\":true,\"req\":\"^0.6.3\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"bstr\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"bytes\",\"req\":\"^1.1.0\"},{\"default_features\":false,\"features\":[\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.34\"},{\"name\":\"crc\",\"optional\":true,\"req\":\"^3\"},{\"name\":\"crossbeam-queue\",\"req\":\"^0.3.2\"},{\"name\":\"either\",\"req\":\"^1.6.1\"},{\"name\":\"event-listener\",\"req\":\"^5.2.0\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.19\"},{\"name\":\"futures-intrusive\",\"req\":\"^0.5.0\"},{\"name\":\"futures-io\",\"req\":\"^0.3.24\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\",\"io\"],\"name\":\"futures-util\",\"req\":\"^0.3.19\"},{\"name\":\"hashbrown\",\"req\":\"^0.15.0\"},{\"name\":\"hashlink\",\"req\":\"^0.10.0\"},{\"name\":\"indexmap\",\"req\":\"^2.0\"},{\"name\":\"ipnet\",\"optional\":true,\"req\":\"^2.3.0\"},{\"name\":\"ipnetwork\",\"optional\":true,\"req\":\"^0.20.0\"},{\"default_features\":false,\"name\":\"log\",\"req\":\"^0.4.18\"},{\"name\":\"mac_address\",\"optional\":true,\"req\":\"^1.1.5\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.4.1\"},{\"name\":\"native-tls\",\"optional\":true,\"req\":\"^0.2.10\"},{\"name\":\"once_cell\",\"req\":\"^1.9.0\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1.0\"},{\"name\":\"regex\",\"optional\":true,\"req\":\"^1.5.5\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rust_decimal\",\"optional\":true,\"req\":\"^1.26.1\"},{\"default_features\":false,\"features\":[\"std\",\"tls12\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.23.15\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.8.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.132\"},{\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.73\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10.0\"},{\"name\":\"smallvec\",\"req\":\"^1.7.0\"},{\"default_features\":false,\"features\":[\"postgres\",\"sqlite\",\"mysql\",\"migrate\",\"macros\",\"time\",\"uuid\"],\"kind\":\"dev\",\"name\":\"sqlx\",\"req\":\"=0.8.6\"},{\"name\":\"thiserror\",\"req\":\"^2.0.0\"},{\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.36\"},{\"default_features\":false,\"features\":[\"time\",\"net\",\"sync\",\"fs\",\"io-util\",\"rt\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"rt\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"fs\"],\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1.8\"},{\"features\":[\"log\"],\"name\":\"tracing\",\"req\":\"^0.1.37\"},{\"name\":\"url\",\"req\":\"^2.2.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1.1.2\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^0.26\"}],\"features\":{\"_rt-async-std\":[\"async-std\",\"async-io\"],\"_rt-tokio\":[\"tokio\",\"tokio-stream\"],\"_tls-native-tls\":[\"native-tls\"],\"_tls-none\":[],\"_tls-rustls\":[\"rustls\"],\"_tls-rustls-aws-lc-rs\":[\"_tls-rustls\",\"rustls/aws-lc-rs\",\"webpki-roots\"],\"_tls-rustls-ring-native-roots\":[\"_tls-rustls\",\"rustls/ring\",\"rustls-native-certs\"],\"_tls-rustls-ring-webpki\":[\"_tls-rustls\",\"rustls/ring\",\"webpki-roots\"],\"any\":[],\"default\":[],\"json\":[\"serde\",\"serde_json\"],\"migrate\":[\"sha2\",\"crc\"],\"offline\":[\"serde\",\"either/serde\"]}}", + "sqlx-macros-core_0.8.6": "{\"dependencies\":[{\"name\":\"async-std\",\"optional\":true,\"req\":\"^1.12\"},{\"default_features\":false,\"name\":\"dotenvy\",\"req\":\"^0.15.7\"},{\"name\":\"either\",\"req\":\"^1.6.1\"},{\"name\":\"heck\",\"req\":\"^0.5\"},{\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"once_cell\",\"req\":\"^1.9.0\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.79\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1.0.26\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0.132\"},{\"name\":\"serde_json\",\"req\":\"^1.0.73\"},{\"name\":\"sha2\",\"req\":\"^0.10.0\"},{\"features\":[\"offline\"],\"name\":\"sqlx-core\",\"req\":\"=0.8.6\"},{\"features\":[\"offline\",\"migrate\"],\"name\":\"sqlx-mysql\",\"optional\":true,\"req\":\"=0.8.6\"},{\"features\":[\"offline\",\"migrate\"],\"name\":\"sqlx-postgres\",\"optional\":true,\"req\":\"=0.8.6\"},{\"features\":[\"offline\",\"migrate\"],\"name\":\"sqlx-sqlite\",\"optional\":true,\"req\":\"=0.8.6\"},{\"default_features\":false,\"features\":[\"full\",\"derive\",\"parsing\",\"printing\",\"clone-impls\"],\"name\":\"syn\",\"req\":\"^2.0.52\"},{\"default_features\":false,\"features\":[\"time\",\"net\",\"sync\",\"fs\",\"io-util\",\"rt\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"url\",\"req\":\"^2.2.2\"}],\"features\":{\"_rt-async-std\":[\"async-std\",\"sqlx-core/_rt-async-std\"],\"_rt-tokio\":[\"tokio\",\"sqlx-core/_rt-tokio\"],\"_sqlite\":[],\"_tls-native-tls\":[\"sqlx-core/_tls-native-tls\"],\"_tls-rustls-aws-lc-rs\":[\"sqlx-core/_tls-rustls-aws-lc-rs\"],\"_tls-rustls-ring-native-roots\":[\"sqlx-core/_tls-rustls-ring-native-roots\"],\"_tls-rustls-ring-webpki\":[\"sqlx-core/_tls-rustls-ring-webpki\"],\"bigdecimal\":[\"sqlx-core/bigdecimal\",\"sqlx-mysql?/bigdecimal\",\"sqlx-postgres?/bigdecimal\"],\"bit-vec\":[\"sqlx-core/bit-vec\",\"sqlx-postgres?/bit-vec\"],\"chrono\":[\"sqlx-core/chrono\",\"sqlx-mysql?/chrono\",\"sqlx-postgres?/chrono\",\"sqlx-sqlite?/chrono\"],\"default\":[],\"derive\":[],\"ipnet\":[\"sqlx-core/ipnet\",\"sqlx-postgres?/ipnet\"],\"ipnetwork\":[\"sqlx-core/ipnetwork\",\"sqlx-postgres?/ipnetwork\"],\"json\":[\"sqlx-core/json\",\"sqlx-mysql?/json\",\"sqlx-postgres?/json\",\"sqlx-sqlite?/json\"],\"mac_address\":[\"sqlx-core/mac_address\",\"sqlx-postgres?/mac_address\"],\"macros\":[],\"migrate\":[\"sqlx-core/migrate\"],\"mysql\":[\"sqlx-mysql\"],\"postgres\":[\"sqlx-postgres\"],\"rust_decimal\":[\"sqlx-core/rust_decimal\",\"sqlx-mysql?/rust_decimal\",\"sqlx-postgres?/rust_decimal\"],\"sqlite\":[\"_sqlite\",\"sqlx-sqlite/bundled\"],\"sqlite-unbundled\":[\"_sqlite\",\"sqlx-sqlite/unbundled\"],\"time\":[\"sqlx-core/time\",\"sqlx-mysql?/time\",\"sqlx-postgres?/time\",\"sqlx-sqlite?/time\"],\"uuid\":[\"sqlx-core/uuid\",\"sqlx-mysql?/uuid\",\"sqlx-postgres?/uuid\",\"sqlx-sqlite?/uuid\"]}}", + "sqlx-macros_0.8.6": "{\"dependencies\":[{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.36\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1.0.26\"},{\"features\":[\"any\"],\"name\":\"sqlx-core\",\"req\":\"=0.8.6\"},{\"name\":\"sqlx-macros-core\",\"req\":\"=0.8.6\"},{\"default_features\":false,\"features\":[\"parsing\",\"proc-macro\"],\"name\":\"syn\",\"req\":\"^2.0.52\"}],\"features\":{\"_rt-async-std\":[\"sqlx-macros-core/_rt-async-std\"],\"_rt-tokio\":[\"sqlx-macros-core/_rt-tokio\"],\"_tls-native-tls\":[\"sqlx-macros-core/_tls-native-tls\"],\"_tls-rustls-aws-lc-rs\":[\"sqlx-macros-core/_tls-rustls-aws-lc-rs\"],\"_tls-rustls-ring-native-roots\":[\"sqlx-macros-core/_tls-rustls-ring-native-roots\"],\"_tls-rustls-ring-webpki\":[\"sqlx-macros-core/_tls-rustls-ring-webpki\"],\"bigdecimal\":[\"sqlx-macros-core/bigdecimal\"],\"bit-vec\":[\"sqlx-macros-core/bit-vec\"],\"chrono\":[\"sqlx-macros-core/chrono\"],\"default\":[],\"derive\":[\"sqlx-macros-core/derive\"],\"ipnet\":[\"sqlx-macros-core/ipnet\"],\"ipnetwork\":[\"sqlx-macros-core/ipnetwork\"],\"json\":[\"sqlx-macros-core/json\"],\"mac_address\":[\"sqlx-macros-core/mac_address\"],\"macros\":[\"sqlx-macros-core/macros\"],\"migrate\":[\"sqlx-macros-core/migrate\"],\"mysql\":[\"sqlx-macros-core/mysql\"],\"postgres\":[\"sqlx-macros-core/postgres\"],\"rust_decimal\":[\"sqlx-macros-core/rust_decimal\"],\"sqlite\":[\"sqlx-macros-core/sqlite\"],\"sqlite-unbundled\":[\"sqlx-macros-core/sqlite-unbundled\"],\"time\":[\"sqlx-macros-core/time\"],\"uuid\":[\"sqlx-macros-core/uuid\"]}}", + "sqlx-mysql_0.8.6": "{\"dependencies\":[{\"name\":\"atoi\",\"req\":\"^2.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"base64\",\"req\":\"^0.22.0\"},{\"name\":\"bigdecimal\",\"optional\":true,\"req\":\"^0.4.0\"},{\"default_features\":false,\"features\":[\"serde\"],\"name\":\"bitflags\",\"req\":\"^2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"name\":\"bytes\",\"req\":\"^1.1.0\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.34\"},{\"name\":\"crc\",\"req\":\"^3.0.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"digest\",\"req\":\"^0.10.0\"},{\"name\":\"dotenvy\",\"req\":\"^0.15.5\"},{\"name\":\"either\",\"req\":\"^1.6.1\"},{\"default_features\":false,\"features\":[\"sink\",\"alloc\",\"std\"],\"name\":\"futures-channel\",\"req\":\"^0.3.19\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.19\"},{\"name\":\"futures-io\",\"req\":\"^0.3.24\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\",\"io\"],\"name\":\"futures-util\",\"req\":\"^0.3.19\"},{\"default_features\":false,\"name\":\"generic-array\",\"req\":\"^0.14.4\"},{\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"hkdf\",\"req\":\"^0.12.0\"},{\"default_features\":false,\"name\":\"hmac\",\"req\":\"^0.12.0\"},{\"name\":\"itoa\",\"req\":\"^1.0.1\"},{\"name\":\"log\",\"req\":\"^0.4.18\"},{\"default_features\":false,\"name\":\"md-5\",\"req\":\"^0.10.0\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.4.1\"},{\"name\":\"once_cell\",\"req\":\"^1.9.0\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1.0\"},{\"default_features\":false,\"features\":[\"std\",\"std_rng\"],\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"name\":\"rsa\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rust_decimal\",\"optional\":true,\"req\":\"^1.26.1\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.144\"},{\"default_features\":false,\"name\":\"sha1\",\"req\":\"^0.10.1\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.10.0\"},{\"name\":\"smallvec\",\"req\":\"^1.7.0\"},{\"default_features\":false,\"features\":[\"mysql\"],\"kind\":\"dev\",\"name\":\"sqlx\",\"req\":\"=0.8.6\"},{\"name\":\"sqlx-core\",\"req\":\"=0.8.6\"},{\"name\":\"stringprep\",\"req\":\"^0.1.2\"},{\"name\":\"thiserror\",\"req\":\"^2.0.0\"},{\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.36\"},{\"features\":[\"log\"],\"name\":\"tracing\",\"req\":\"^0.1.37\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1.1.2\"},{\"default_features\":false,\"name\":\"whoami\",\"req\":\"^1.2.1\"}],\"features\":{\"any\":[\"sqlx-core/any\"],\"bigdecimal\":[\"dep:bigdecimal\",\"sqlx-core/bigdecimal\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"json\":[\"sqlx-core/json\",\"serde\"],\"migrate\":[\"sqlx-core/migrate\"],\"offline\":[\"sqlx-core/offline\",\"serde/derive\"],\"rust_decimal\":[\"dep:rust_decimal\",\"rust_decimal/maths\",\"sqlx-core/rust_decimal\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]}}", + "sqlx-postgres_0.8.6": "{\"dependencies\":[{\"name\":\"atoi\",\"req\":\"^2.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"base64\",\"req\":\"^0.22.0\"},{\"name\":\"bigdecimal\",\"optional\":true,\"req\":\"^0.4.0\"},{\"name\":\"bit-vec\",\"optional\":true,\"req\":\"^0.6.3\"},{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.34\"},{\"name\":\"crc\",\"req\":\"^3.0.0\"},{\"default_features\":false,\"name\":\"dotenvy\",\"req\":\"^0.15.7\"},{\"name\":\"etcetera\",\"req\":\"^0.8.0\",\"target\":\"cfg(target_os = \\\"windows\\\")\"},{\"default_features\":false,\"features\":[\"sink\",\"alloc\",\"std\"],\"name\":\"futures-channel\",\"req\":\"^0.3.19\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.19\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\",\"io\"],\"name\":\"futures-util\",\"req\":\"^0.3.19\"},{\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"hkdf\",\"req\":\"^0.12.0\"},{\"default_features\":false,\"features\":[\"reset\"],\"name\":\"hmac\",\"req\":\"^0.12.0\"},{\"name\":\"home\",\"req\":\"^0.5.5\"},{\"name\":\"ipnet\",\"optional\":true,\"req\":\"^2.3.0\"},{\"name\":\"ipnetwork\",\"optional\":true,\"req\":\"^0.20.0\"},{\"name\":\"itoa\",\"req\":\"^1.0.1\"},{\"name\":\"log\",\"req\":\"^0.4.18\"},{\"name\":\"mac_address\",\"optional\":true,\"req\":\"^1.1.5\"},{\"default_features\":false,\"name\":\"md-5\",\"req\":\"^0.10.0\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2.4.1\"},{\"name\":\"num-bigint\",\"optional\":true,\"req\":\"^0.4.3\"},{\"name\":\"once_cell\",\"req\":\"^1.9.0\"},{\"default_features\":false,\"features\":[\"std\",\"std_rng\"],\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rust_decimal\",\"optional\":true,\"req\":\"^1.26.1\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0.144\"},{\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"req\":\"^1.0.85\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.10.0\"},{\"features\":[\"serde\"],\"name\":\"smallvec\",\"req\":\"^1.7.0\"},{\"default_features\":false,\"features\":[\"postgres\",\"derive\"],\"kind\":\"dev\",\"name\":\"sqlx\",\"req\":\"=0.8.6\"},{\"features\":[\"json\"],\"name\":\"sqlx-core\",\"req\":\"=0.8.6\"},{\"name\":\"stringprep\",\"req\":\"^0.1.2\"},{\"name\":\"thiserror\",\"req\":\"^2.0.0\"},{\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.36\"},{\"features\":[\"log\"],\"name\":\"tracing\",\"req\":\"^0.1.37\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1.1.2\"},{\"default_features\":false,\"name\":\"whoami\",\"req\":\"^1.2.1\"}],\"features\":{\"any\":[\"sqlx-core/any\"],\"bigdecimal\":[\"dep:bigdecimal\",\"dep:num-bigint\",\"sqlx-core/bigdecimal\"],\"bit-vec\":[\"dep:bit-vec\",\"sqlx-core/bit-vec\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"ipnet\":[\"dep:ipnet\",\"sqlx-core/ipnet\"],\"ipnetwork\":[\"dep:ipnetwork\",\"sqlx-core/ipnetwork\"],\"json\":[\"sqlx-core/json\"],\"mac_address\":[\"dep:mac_address\",\"sqlx-core/mac_address\"],\"migrate\":[\"sqlx-core/migrate\"],\"offline\":[\"sqlx-core/offline\"],\"rust_decimal\":[\"dep:rust_decimal\",\"rust_decimal/maths\",\"sqlx-core/rust_decimal\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]}}", + "sqlx-sqlite_0.8.6": "{\"dependencies\":[{\"name\":\"atoi\",\"req\":\"^2.0\"},{\"default_features\":false,\"features\":[\"std\",\"clock\"],\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.34\"},{\"default_features\":false,\"features\":[\"async\"],\"name\":\"flume\",\"req\":\"^0.11.0\"},{\"default_features\":false,\"features\":[\"sink\",\"alloc\",\"std\"],\"name\":\"futures-channel\",\"req\":\"^0.3.19\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.19\"},{\"name\":\"futures-executor\",\"req\":\"^0.3.19\"},{\"name\":\"futures-intrusive\",\"req\":\"^0.5.0\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\"],\"name\":\"futures-util\",\"req\":\"^0.3.19\"},{\"default_features\":false,\"features\":[\"pkg-config\",\"vcpkg\",\"unlock_notify\"],\"name\":\"libsqlite3-sys\",\"req\":\"^0.30.1\"},{\"name\":\"log\",\"req\":\"^0.4.18\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1.0\"},{\"name\":\"regex\",\"optional\":true,\"req\":\"^1.5.5\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.145\"},{\"name\":\"serde_urlencoded\",\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"macros\",\"runtime-tokio\",\"tls-none\",\"sqlite\"],\"kind\":\"dev\",\"name\":\"sqlx\",\"req\":\"=0.8.6\"},{\"name\":\"sqlx-core\",\"req\":\"=0.8.6\"},{\"name\":\"thiserror\",\"req\":\"^2.0.0\"},{\"features\":[\"formatting\",\"parsing\",\"macros\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.36\"},{\"features\":[\"log\"],\"name\":\"tracing\",\"req\":\"^0.1.37\"},{\"name\":\"url\",\"req\":\"^2.2.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1.1.2\"}],\"features\":{\"any\":[\"sqlx-core/any\"],\"bundled\":[\"libsqlite3-sys/bundled\"],\"chrono\":[\"dep:chrono\",\"sqlx-core/chrono\"],\"json\":[\"sqlx-core/json\",\"serde\"],\"migrate\":[\"sqlx-core/migrate\"],\"offline\":[\"sqlx-core/offline\",\"serde\"],\"preupdate-hook\":[\"libsqlite3-sys/preupdate_hook\"],\"regexp\":[\"dep:regex\"],\"time\":[\"dep:time\",\"sqlx-core/time\"],\"unbundled\":[\"libsqlite3-sys/buildtime_bindgen\"],\"uuid\":[\"dep:uuid\",\"sqlx-core/uuid\"]}}", + "sqlx_0.8.6": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.52\"},{\"features\":[\"attributes\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.12\"},{\"features\":[\"async_tokio\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"kind\":\"dev\",\"name\":\"dotenvy\",\"req\":\"^0.15.0\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.19\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"kind\":\"dev\",\"name\":\"libsqlite3-sys\",\"req\":\"^0.30.1\"},{\"features\":[\"bundled-sqlcipher\"],\"kind\":\"dev\",\"name\":\"libsqlite3-sys\",\"req\":\"^0.30.1\",\"target\":\"cfg(sqlite_test_sqlcipher)\"},{\"kind\":\"dev\",\"name\":\"paste\",\"req\":\"^1.0.6\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"rand_xoshiro\",\"req\":\"^0.6.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.132\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.73\"},{\"features\":[\"offline\",\"migrate\"],\"name\":\"sqlx-core\",\"req\":\"=0.8.6\"},{\"name\":\"sqlx-macros\",\"optional\":true,\"req\":\"=0.8.6\"},{\"name\":\"sqlx-mysql\",\"optional\":true,\"req\":\"=0.8.6\"},{\"name\":\"sqlx-postgres\",\"optional\":true,\"req\":\"=0.8.6\"},{\"name\":\"sqlx-sqlite\",\"optional\":true,\"req\":\"=0.8.6\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.10.1\"},{\"kind\":\"dev\",\"name\":\"time_\",\"package\":\"time\",\"req\":\"^0.3.2\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.15.0\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.53\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.2.2\"}],\"features\":{\"_rt-async-std\":[],\"_rt-tokio\":[],\"_sqlite\":[],\"_unstable-all-types\":[\"bigdecimal\",\"rust_decimal\",\"json\",\"time\",\"chrono\",\"ipnet\",\"ipnetwork\",\"mac_address\",\"uuid\",\"bit-vec\",\"bstr\"],\"all-databases\":[\"mysql\",\"sqlite\",\"postgres\",\"any\"],\"any\":[\"sqlx-core/any\",\"sqlx-mysql?/any\",\"sqlx-postgres?/any\",\"sqlx-sqlite?/any\"],\"bigdecimal\":[\"sqlx-core/bigdecimal\",\"sqlx-macros?/bigdecimal\",\"sqlx-mysql?/bigdecimal\",\"sqlx-postgres?/bigdecimal\"],\"bit-vec\":[\"sqlx-core/bit-vec\",\"sqlx-macros?/bit-vec\",\"sqlx-postgres?/bit-vec\"],\"bstr\":[\"sqlx-core/bstr\"],\"chrono\":[\"sqlx-core/chrono\",\"sqlx-macros?/chrono\",\"sqlx-mysql?/chrono\",\"sqlx-postgres?/chrono\",\"sqlx-sqlite?/chrono\"],\"default\":[\"any\",\"macros\",\"migrate\",\"json\"],\"derive\":[\"sqlx-macros/derive\"],\"ipnet\":[\"sqlx-core/ipnet\",\"sqlx-macros?/ipnet\",\"sqlx-postgres?/ipnet\"],\"ipnetwork\":[\"sqlx-core/ipnetwork\",\"sqlx-macros?/ipnetwork\",\"sqlx-postgres?/ipnetwork\"],\"json\":[\"sqlx-core/json\",\"sqlx-macros?/json\",\"sqlx-mysql?/json\",\"sqlx-postgres?/json\",\"sqlx-sqlite?/json\"],\"mac_address\":[\"sqlx-core/mac_address\",\"sqlx-macros?/mac_address\",\"sqlx-postgres?/mac_address\"],\"macros\":[\"derive\",\"sqlx-macros/macros\"],\"migrate\":[\"sqlx-core/migrate\",\"sqlx-macros?/migrate\",\"sqlx-mysql?/migrate\",\"sqlx-postgres?/migrate\",\"sqlx-sqlite?/migrate\"],\"mysql\":[\"sqlx-mysql\",\"sqlx-macros?/mysql\"],\"postgres\":[\"sqlx-postgres\",\"sqlx-macros?/postgres\"],\"regexp\":[\"sqlx-sqlite?/regexp\"],\"runtime-async-std\":[\"_rt-async-std\",\"sqlx-core/_rt-async-std\",\"sqlx-macros?/_rt-async-std\"],\"runtime-async-std-native-tls\":[\"runtime-async-std\",\"tls-native-tls\"],\"runtime-async-std-rustls\":[\"runtime-async-std\",\"tls-rustls-ring\"],\"runtime-tokio\":[\"_rt-tokio\",\"sqlx-core/_rt-tokio\",\"sqlx-macros?/_rt-tokio\"],\"runtime-tokio-native-tls\":[\"runtime-tokio\",\"tls-native-tls\"],\"runtime-tokio-rustls\":[\"runtime-tokio\",\"tls-rustls-ring\"],\"rust_decimal\":[\"sqlx-core/rust_decimal\",\"sqlx-macros?/rust_decimal\",\"sqlx-mysql?/rust_decimal\",\"sqlx-postgres?/rust_decimal\"],\"sqlite\":[\"_sqlite\",\"sqlx-sqlite/bundled\",\"sqlx-macros?/sqlite\"],\"sqlite-preupdate-hook\":[\"sqlx-sqlite/preupdate-hook\"],\"sqlite-unbundled\":[\"_sqlite\",\"sqlx-sqlite/unbundled\",\"sqlx-macros?/sqlite-unbundled\"],\"time\":[\"sqlx-core/time\",\"sqlx-macros?/time\",\"sqlx-mysql?/time\",\"sqlx-postgres?/time\",\"sqlx-sqlite?/time\"],\"tls-native-tls\":[\"sqlx-core/_tls-native-tls\",\"sqlx-macros?/_tls-native-tls\"],\"tls-none\":[],\"tls-rustls\":[\"tls-rustls-ring\"],\"tls-rustls-aws-lc-rs\":[\"sqlx-core/_tls-rustls-aws-lc-rs\",\"sqlx-macros?/_tls-rustls-aws-lc-rs\"],\"tls-rustls-ring\":[\"tls-rustls-ring-webpki\"],\"tls-rustls-ring-native-roots\":[\"sqlx-core/_tls-rustls-ring-native-roots\",\"sqlx-macros?/_tls-rustls-ring-native-roots\"],\"tls-rustls-ring-webpki\":[\"sqlx-core/_tls-rustls-ring-webpki\",\"sqlx-macros?/_tls-rustls-ring-webpki\"],\"uuid\":[\"sqlx-core/uuid\",\"sqlx-macros?/uuid\",\"sqlx-mysql?/uuid\",\"sqlx-postgres?/uuid\",\"sqlx-sqlite?/uuid\"]}}", "sse-stream_0.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1\"},{\"features\":[\"tracing\"],\"kind\":\"dev\",\"name\":\"axum\",\"req\":\"^0.8\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http-body\",\"req\":\"^1\"},{\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"features\":[\"client\",\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"stream\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"io\"],\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"}],\"features\":{\"default\":[],\"tracing\":[\"dep:tracing\"]}}", "stable_deref_trait_1.2.0": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "starlark_0.13.0": "{\"dependencies\":[{\"features\":[\"bumpalo\",\"num-bigint\"],\"name\":\"allocative\",\"req\":\"^0.3.4\"},{\"name\":\"anyhow\",\"req\":\"^1.0.65\"},{\"name\":\"bumpalo\",\"req\":\"^3.8\"},{\"name\":\"cmp_any\",\"req\":\"^0.8.1\"},{\"name\":\"debugserver-types\",\"req\":\"^0.5.0\"},{\"name\":\"derivative\",\"req\":\"^2.2\"},{\"features\":[\"full\"],\"name\":\"derive_more\",\"req\":\"^1.0.0\"},{\"name\":\"display_container\",\"req\":\"^0.9.0\"},{\"name\":\"dupe\",\"req\":\"^0.9.0\"},{\"name\":\"either\",\"req\":\"^1.8\"},{\"name\":\"erased-serde\",\"req\":\"^0.3.12\"},{\"features\":[\"raw\"],\"name\":\"hashbrown\",\"req\":\"^0.14.3\"},{\"name\":\"inventory\",\"req\":\"^0.3.8\"},{\"name\":\"itertools\",\"req\":\"^0.13.0\"},{\"name\":\"maplit\",\"req\":\"^1.0.2\"},{\"name\":\"memoffset\",\"req\":\"^0.6.4\"},{\"name\":\"num-bigint\",\"req\":\"^0.4.3\"},{\"name\":\"num-traits\",\"req\":\"^0.2\"},{\"name\":\"once_cell\",\"req\":\"^1.8\"},{\"name\":\"paste\",\"req\":\"^1.0\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"name\":\"ref-cast\",\"req\":\"^1.0.18\"},{\"name\":\"regex\",\"req\":\"^1.5.4\"},{\"name\":\"rustyline\",\"req\":\"^14.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"starlark_derive\",\"req\":\"^0.13.0\"},{\"name\":\"starlark_map\",\"req\":\"^0.13.0\"},{\"name\":\"starlark_syntax\",\"req\":\"^0.13.0\"},{\"name\":\"static_assertions\",\"req\":\"^1.1.0\"},{\"name\":\"strsim\",\"req\":\"^0.10.0\"},{\"name\":\"textwrap\",\"req\":\"^0.11\"},{\"name\":\"thiserror\",\"req\":\"^1.0.36\"}],\"features\":{}}", @@ -1077,6 +1164,7 @@ "static_assertions_1.1.0": "{\"dependencies\":[],\"features\":{\"nightly\":[]}}", "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\"]}}", + "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\":{}}", "strum_0.26.3": "{\"dependencies\":[{\"features\":[\"macros\"],\"name\":\"phf\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"strum_macros\",\"optional\":true,\"req\":\"^0.26.3\"},{\"kind\":\"dev\",\"name\":\"strum_macros\",\"req\":\"^0.26\"}],\"features\":{\"default\":[\"std\"],\"derive\":[\"strum_macros\"],\"std\":[]}}", @@ -1093,6 +1181,7 @@ "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.6.0": "{\"dependencies\":[{\"name\":\"core-foundation-sys\",\"req\":\"^0.8\"},{\"name\":\"libc\",\"req\":\"^0.2.149\"}],\"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\":{}}", "tempfile_3.23.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.0.0\",\"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\":[]}}", "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\":{}}", @@ -1119,11 +1208,12 @@ "tinystr_0.8.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"displaydoc\",\"req\":\"^0.2.3\"},{\"default_features\":false,\"features\":[\"use-std\"],\"kind\":\"dev\",\"name\":\"postcard\",\"req\":\"^1.0.3\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.110\"},{\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.45\"},{\"default_features\":false,\"name\":\"zerovec\",\"optional\":true,\"req\":\"^0.11.1\"}],\"features\":{\"alloc\":[\"zerovec?/alloc\"],\"databake\":[\"dep:databake\"],\"default\":[\"alloc\"],\"serde\":[\"dep:serde\"],\"std\":[],\"zerovec\":[\"dep:zerovec\"]}}", "tinyvec_1.10.0": "{\"dependencies\":[{\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"name\":\"borsh\",\"optional\":true,\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"debugger_test\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"debugger_test_parser\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"generic-array\",\"optional\":true,\"req\":\"^1.1.1\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"smallvec\",\"req\":\"^1\"},{\"name\":\"tinyvec_macros\",\"optional\":true,\"req\":\"^0.1\"}],\"features\":{\"alloc\":[\"tinyvec_macros\"],\"debugger_visualizer\":[],\"default\":[],\"experimental_write_impl\":[],\"grab_spare_slice\":[],\"latest_stable_rust\":[\"rustc_1_61\"],\"nightly_slice_partition_dedup\":[],\"real_blackbox\":[\"criterion/real_blackbox\"],\"rustc_1_40\":[],\"rustc_1_55\":[],\"rustc_1_57\":[],\"rustc_1_61\":[\"rustc_1_57\"],\"std\":[\"alloc\"]}}", "tinyvec_macros_0.1.1": "{\"dependencies\":[],\"features\":{}}", + "tokio-graceful_0.2.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bytes\",\"req\":\"^1\",\"target\":\"cfg(not(loom))\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\",\"target\":\"cfg(not(loom))\"},{\"features\":[\"server\",\"http1\",\"http2\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.0.1\",\"target\":\"cfg(not(loom))\"},{\"features\":[\"server\",\"server-auto\",\"http1\",\"http2\",\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.1\",\"target\":\"cfg(not(loom))\"},{\"features\":[\"futures\",\"checkpoint\"],\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"name\":\"slab\",\"req\":\"^0.4\"},{\"features\":[\"rt\",\"signal\",\"sync\",\"macros\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"net\",\"rt-multi-thread\",\"io-util\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"}],\"features\":{}}", "tokio-macros_2.6.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0.0\"}],\"features\":{}}", "tokio-native-tls_0.3.1": "{\"dependencies\":[{\"name\":\"native-tls\",\"req\":\"^0.2\"},{\"name\":\"tokio\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"cfg-if\",\"req\":\"^0.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.6\"},{\"features\":[\"async-await\"],\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.1\"},{\"features\":[\"macros\",\"rt\",\"rt-multi-thread\",\"io-util\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.6.0\"},{\"kind\":\"dev\",\"name\":\"openssl\",\"req\":\"^0.10\",\"target\":\"cfg(all(not(target_os = \\\"macos\\\"), not(windows), not(target_os = \\\"ios\\\")))\"},{\"kind\":\"dev\",\"name\":\"security-framework\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_os = \\\"macos\\\", target_os = \\\"ios\\\"))\"},{\"kind\":\"dev\",\"name\":\"schannel\",\"req\":\"^0.1\",\"target\":\"cfg(windows)\"},{\"features\":[\"lmcons\",\"basetsd\",\"minwinbase\",\"minwindef\",\"ntdef\",\"sysinfoapi\",\"timezoneapi\",\"wincrypt\",\"winerror\"],\"kind\":\"dev\",\"name\":\"winapi\",\"req\":\"^0.3\",\"target\":\"cfg(windows)\"}],\"features\":{\"vendored\":[\"native-tls/vendored\"]}}", "tokio-rustls_0.26.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"argh\",\"req\":\"^0.1.1\"},{\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.1\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.1\"},{\"features\":[\"pem\"],\"kind\":\"dev\",\"name\":\"rcgen\",\"req\":\"^0.13\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rustls\",\"req\":\"^0.23.22\"},{\"name\":\"tokio\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^0.26\"}],\"features\":{\"aws-lc-rs\":[\"aws_lc_rs\"],\"aws_lc_rs\":[\"rustls/aws_lc_rs\"],\"default\":[\"logging\",\"tls12\",\"aws_lc_rs\"],\"early-data\":[],\"fips\":[\"rustls/fips\"],\"logging\":[\"rustls/logging\"],\"ring\":[\"rustls/ring\"],\"tls12\":[\"rustls/tls12\"]}}", "tokio-stream_0.1.18": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-stream\",\"req\":\"^0.3\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"futures-core\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"parking_lot\",\"req\":\"^0.12.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.11\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"req\":\"^1.15.0\"},{\"features\":[\"full\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"name\":\"tokio-util\",\"optional\":true,\"req\":\"^0.7.0\"}],\"features\":{\"default\":[\"time\"],\"fs\":[\"tokio/fs\"],\"full\":[\"time\",\"net\",\"io-util\",\"fs\",\"sync\",\"signal\"],\"io-util\":[\"tokio/io-util\"],\"net\":[\"tokio/net\"],\"signal\":[\"tokio/signal\"],\"sync\":[\"tokio/sync\",\"tokio-util\"],\"time\":[\"tokio/time\"]}}", - "tokio-test_0.4.4": "{\"dependencies\":[{\"name\":\"async-stream\",\"req\":\"^0.3.3\"},{\"name\":\"bytes\",\"req\":\"^1.0.0\"},{\"name\":\"futures-core\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.0\"},{\"features\":[\"rt\",\"sync\",\"time\",\"test-util\"],\"name\":\"tokio\",\"req\":\"^1.2.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.2.0\"},{\"name\":\"tokio-stream\",\"req\":\"^0.1.1\"}],\"features\":{}}", + "tokio-test_0.4.5": "{\"dependencies\":[{\"name\":\"futures-core\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.0\"},{\"features\":[\"rt\",\"sync\",\"time\",\"test-util\"],\"name\":\"tokio\",\"req\":\"^1.2.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.2.0\"},{\"name\":\"tokio-stream\",\"req\":\"^0.1.1\"}],\"features\":{}}", "tokio-util_0.7.18": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-stream\",\"req\":\"^0.3.0\"},{\"name\":\"bytes\",\"req\":\"^1.5.0\"},{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.0\"},{\"name\":\"futures-core\",\"req\":\"^0.3.0\"},{\"name\":\"futures-io\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"futures-sink\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"futures-test\",\"req\":\"^0.3.5\"},{\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.0\"},{\"default_features\":false,\"name\":\"hashbrown\",\"optional\":true,\"req\":\"^0.15.0\"},{\"features\":[\"futures\",\"checkpoint\"],\"kind\":\"dev\",\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"kind\":\"dev\",\"name\":\"parking_lot\",\"req\":\"^0.12.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.11\"},{\"name\":\"slab\",\"optional\":true,\"req\":\"^0.4.4\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.1.0\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"req\":\"^1.44.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.29\"}],\"features\":{\"__docs_rs\":[\"futures-util\"],\"codec\":[],\"compat\":[\"futures-io\"],\"default\":[],\"full\":[\"codec\",\"compat\",\"io-util\",\"time\",\"net\",\"rt\",\"join-map\"],\"io\":[],\"io-util\":[\"io\",\"tokio/rt\",\"tokio/io-util\"],\"join-map\":[\"rt\",\"hashbrown\"],\"net\":[\"tokio/net\"],\"rt\":[\"tokio/rt\",\"tokio/sync\",\"futures-util\"],\"time\":[\"tokio/time\",\"slab\"]}}", "tokio_1.49.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-stream\",\"req\":\"^0.3\"},{\"name\":\"backtrace\",\"optional\":true,\"req\":\"^0.3.58\",\"target\":\"cfg(all(tokio_unstable, target_os = \\\"linux\\\"))\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1.2.1\"},{\"features\":[\"async-await\"],\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"futures-concurrency\",\"req\":\"^7.6.3\"},{\"kind\":\"dev\",\"name\":\"futures-test\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"io-uring\",\"optional\":true,\"req\":\"^0.7.6\",\"target\":\"cfg(all(tokio_unstable, target_os = \\\"linux\\\"))\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.168\",\"target\":\"cfg(all(tokio_unstable, target_os = \\\"linux\\\"))\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.168\",\"target\":\"cfg(unix)\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.168\",\"target\":\"cfg(unix)\"},{\"features\":[\"futures\",\"checkpoint\"],\"kind\":\"dev\",\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"default_features\":false,\"name\":\"mio\",\"optional\":true,\"req\":\"^1.0.1\"},{\"default_features\":false,\"features\":[\"os-poll\",\"os-ext\"],\"name\":\"mio\",\"optional\":true,\"req\":\"^1.0.1\",\"target\":\"cfg(all(tokio_unstable, target_os = \\\"linux\\\"))\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"mio-aio\",\"req\":\"^1\",\"target\":\"cfg(target_os = \\\"freebsd\\\")\"},{\"kind\":\"dev\",\"name\":\"mockall\",\"req\":\"^0.13.0\"},{\"default_features\":false,\"features\":[\"aio\",\"fs\",\"socket\"],\"kind\":\"dev\",\"name\":\"nix\",\"req\":\"^0.29.0\",\"target\":\"cfg(unix)\"},{\"name\":\"parking_lot\",\"optional\":true,\"req\":\"^0.12.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.11\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\",\"target\":\"cfg(not(target_family = \\\"wasm\\\"))\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"signal-hook-registry\",\"optional\":true,\"req\":\"^1.1.1\",\"target\":\"cfg(unix)\"},{\"name\":\"slab\",\"optional\":true,\"req\":\"^0.4.9\",\"target\":\"cfg(all(tokio_unstable, target_os = \\\"linux\\\"))\"},{\"features\":[\"all\"],\"name\":\"socket2\",\"optional\":true,\"req\":\"^0.6.0\",\"target\":\"cfg(not(target_family = \\\"wasm\\\"))\"},{\"kind\":\"dev\",\"name\":\"socket2\",\"req\":\"^0.6.0\",\"target\":\"cfg(not(target_family = \\\"wasm\\\"))\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.1.0\",\"target\":\"cfg(not(target_family = \\\"wasm\\\"))\"},{\"name\":\"tokio-macros\",\"optional\":true,\"req\":\"~2.6.0\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4.0\"},{\"features\":[\"rt\"],\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.29\",\"target\":\"cfg(tokio_unstable)\"},{\"kind\":\"dev\",\"name\":\"tracing-mock\",\"req\":\"=0.1.0-beta.1\",\"target\":\"cfg(all(tokio_unstable, target_has_atomic = \\\"64\\\"))\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.0\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(target_os = \\\"wasi\\\")))\"},{\"name\":\"windows-sys\",\"optional\":true,\"req\":\"^0.61\",\"target\":\"cfg(windows)\"},{\"features\":[\"Win32_Foundation\",\"Win32_Security_Authorization\"],\"kind\":\"dev\",\"name\":\"windows-sys\",\"req\":\"^0.61\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[],\"fs\":[],\"full\":[\"fs\",\"io-util\",\"io-std\",\"macros\",\"net\",\"parking_lot\",\"process\",\"rt\",\"rt-multi-thread\",\"signal\",\"sync\",\"time\"],\"io-std\":[],\"io-uring\":[\"dep:io-uring\",\"libc\",\"mio/os-poll\",\"mio/os-ext\",\"dep:slab\"],\"io-util\":[\"bytes\"],\"macros\":[\"tokio-macros\"],\"net\":[\"libc\",\"mio/os-poll\",\"mio/os-ext\",\"mio/net\",\"socket2\",\"windows-sys/Win32_Foundation\",\"windows-sys/Win32_Security\",\"windows-sys/Win32_Storage_FileSystem\",\"windows-sys/Win32_System_Pipes\",\"windows-sys/Win32_System_SystemServices\"],\"process\":[\"bytes\",\"libc\",\"mio/os-poll\",\"mio/os-ext\",\"mio/net\",\"signal-hook-registry\",\"windows-sys/Win32_Foundation\",\"windows-sys/Win32_System_Threading\",\"windows-sys/Win32_System_WindowsProgramming\"],\"rt\":[],\"rt-multi-thread\":[\"rt\"],\"signal\":[\"libc\",\"mio/os-poll\",\"mio/net\",\"mio/os-ext\",\"signal-hook-registry\",\"windows-sys/Win32_Foundation\",\"windows-sys/Win32_System_Console\"],\"sync\":[],\"taskdump\":[\"dep:backtrace\"],\"test-util\":[\"rt\",\"sync\",\"time\"],\"time\":[]}}", "toml_0.5.11": "{\"dependencies\":[{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde\",\"req\":\"^1.0.97\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"default\":[],\"preserve_order\":[\"indexmap\"]}}", @@ -1141,14 +1231,14 @@ "tower_0.5.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.22\"},{\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3.22\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.22\"},{\"default_features\":false,\"name\":\"hdrhistogram\",\"optional\":true,\"req\":\"^7.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"hdrhistogram\",\"req\":\"^7.0\"},{\"kind\":\"dev\",\"name\":\"http\",\"req\":\"^1\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.0.2\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4.0\"},{\"name\":\"pin-project-lite\",\"optional\":true,\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"name\":\"slab\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"sync_wrapper\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1.6.2\"},{\"features\":[\"macros\",\"sync\",\"test-util\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.6.2\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"tokio-util\",\"optional\":true,\"req\":\"^0.7.0\"},{\"name\":\"tower-layer\",\"req\":\"^0.3.3\"},{\"name\":\"tower-service\",\"req\":\"^0.3.3\"},{\"kind\":\"dev\",\"name\":\"tower-test\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.2\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.2\"},{\"default_features\":false,\"features\":[\"fmt\",\"ansi\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"}],\"features\":{\"__common\":[\"futures-core\",\"pin-project-lite\"],\"balance\":[\"discover\",\"load\",\"ready-cache\",\"make\",\"slab\",\"util\"],\"buffer\":[\"__common\",\"tokio/sync\",\"tokio/rt\",\"tokio-util\",\"tracing\"],\"discover\":[\"__common\"],\"filter\":[\"__common\",\"futures-util\"],\"full\":[\"balance\",\"buffer\",\"discover\",\"filter\",\"hedge\",\"limit\",\"load\",\"load-shed\",\"make\",\"ready-cache\",\"reconnect\",\"retry\",\"spawn-ready\",\"steer\",\"timeout\",\"util\"],\"hedge\":[\"util\",\"filter\",\"futures-util\",\"hdrhistogram\",\"tokio/time\",\"tracing\"],\"limit\":[\"__common\",\"tokio/time\",\"tokio/sync\",\"tokio-util\",\"tracing\"],\"load\":[\"__common\",\"tokio/time\",\"tracing\"],\"load-shed\":[\"__common\"],\"log\":[\"tracing/log\"],\"make\":[\"futures-util\",\"pin-project-lite\",\"tokio/io-std\"],\"ready-cache\":[\"futures-core\",\"futures-util\",\"indexmap\",\"tokio/sync\",\"tracing\",\"pin-project-lite\"],\"reconnect\":[\"make\",\"tokio/io-std\",\"tracing\"],\"retry\":[\"__common\",\"tokio/time\",\"util\"],\"spawn-ready\":[\"__common\",\"futures-util\",\"tokio/sync\",\"tokio/rt\",\"util\",\"tracing\"],\"steer\":[],\"timeout\":[\"pin-project-lite\",\"tokio/time\"],\"util\":[\"__common\",\"futures-util\",\"pin-project-lite\",\"sync_wrapper\"]}}", "tracing-appender_0.2.3": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"name\":\"crossbeam-channel\",\"req\":\"^0.5.6\"},{\"name\":\"parking_lot\",\"optional\":true,\"req\":\"^0.12.1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"},{\"name\":\"thiserror\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"formatting\",\"parsing\"],\"name\":\"time\",\"req\":\"^0.3.2\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"default_features\":false,\"features\":[\"fmt\",\"std\"],\"name\":\"tracing-subscriber\",\"req\":\"^0.3.18\"}],\"features\":{}}", "tracing-attributes_0.1.31": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1.67\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"name\":\"quote\",\"req\":\"^1.0.20\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.9\"},{\"default_features\":false,\"features\":[\"full\",\"parsing\",\"printing\",\"visit-mut\",\"clone-impls\",\"extra-traits\",\"proc-macro\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4.2\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"features\":[\"env-filter\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.64\"}],\"features\":{\"async-await\":[]}}", - "tracing-core_0.1.35": "{\"dependencies\":[{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.13.0\"},{\"default_features\":false,\"name\":\"valuable\",\"optional\":true,\"req\":\"^0.1.0\",\"target\":\"cfg(tracing_unstable)\"}],\"features\":{\"default\":[\"std\",\"valuable?/std\"],\"std\":[\"once_cell\"]}}", + "tracing-core_0.1.36": "{\"dependencies\":[{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.13.0\"},{\"default_features\":false,\"name\":\"valuable\",\"optional\":true,\"req\":\"^0.1.0\",\"target\":\"cfg(tracing_unstable)\"}],\"features\":{\"default\":[\"std\",\"valuable?/std\"],\"std\":[\"once_cell\"]}}", "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.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1.56\"},{\"default_features\":false,\"features\":[\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.17\"},{\"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\"],\"name\":\"opentelemetry_sdk\",\"req\":\"^0.31.0\"},{\"default_features\":false,\"features\":[\"trace\",\"rt-tokio\",\"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\":\"rustversion\",\"req\":\"^1.0.9\"},{\"name\":\"smallvec\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.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.0\"},{\"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\",\"opentelemetry_sdk/metrics\",\"smallvec\"]}}", "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\"]}}", - "tracing_0.1.43": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.21\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.17\"},{\"kind\":\"dev\",\"name\":\"log\",\"req\":\"^0.4.17\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.9\"},{\"name\":\"tracing-attributes\",\"optional\":true,\"req\":\"^0.1.31\"},{\"default_features\":false,\"name\":\"tracing-core\",\"req\":\"^0.1.35\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.38\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"}],\"features\":{\"async-await\":[],\"attributes\":[\"tracing-attributes\"],\"default\":[\"std\",\"attributes\"],\"log-always\":[\"log\"],\"max_level_debug\":[],\"max_level_error\":[],\"max_level_info\":[],\"max_level_off\":[],\"max_level_trace\":[],\"max_level_warn\":[],\"release_max_level_debug\":[],\"release_max_level_error\":[],\"release_max_level_info\":[],\"release_max_level_off\":[],\"release_max_level_trace\":[],\"release_max_level_warn\":[],\"std\":[\"tracing-core/std\"],\"valuable\":[\"tracing-core/valuable\"]}}", + "tracing_0.1.44": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3.21\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.17\"},{\"kind\":\"dev\",\"name\":\"log\",\"req\":\"^0.4.17\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.9\"},{\"name\":\"tracing-attributes\",\"optional\":true,\"req\":\"^0.1.31\"},{\"default_features\":false,\"name\":\"tracing-core\",\"req\":\"^0.1.36\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.38\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"}],\"features\":{\"async-await\":[],\"attributes\":[\"tracing-attributes\"],\"default\":[\"std\",\"attributes\"],\"log-always\":[\"log\"],\"max_level_debug\":[],\"max_level_error\":[],\"max_level_info\":[],\"max_level_off\":[],\"max_level_trace\":[],\"max_level_warn\":[],\"release_max_level_debug\":[],\"release_max_level_error\":[],\"release_max_level_info\":[],\"release_max_level_off\":[],\"release_max_level_trace\":[],\"release_max_level_warn\":[],\"std\":[\"tracing-core/std\"],\"valuable\":[\"tracing-core/valuable\"]}}", "tree-sitter-bash_0.25.0": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"tree-sitter\",\"req\":\"^0.25\"},{\"name\":\"tree-sitter-language\",\"req\":\"^0.1\"}],\"features\":{}}", "tree-sitter-highlight_0.25.10": "{\"dependencies\":[{\"name\":\"regex\",\"req\":\"^1.11.1\"},{\"name\":\"streaming-iterator\",\"req\":\"^0.1.9\"},{\"name\":\"thiserror\",\"req\":\"^2.0.11\"},{\"name\":\"tree-sitter\",\"req\":\"^0.25.10\"}],\"features\":{}}", "tree-sitter-language_0.1.5": "{\"dependencies\":[],\"features\":{}}", @@ -1162,8 +1252,11 @@ "uname_0.1.1": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2\"}],\"features\":{}}", "unarray_0.1.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"test-strategy\",\"req\":\"^0.2\"}],\"features\":{}}", "unicase_2.8.1": "{\"dependencies\":[],\"features\":{\"nightly\":[]}}", + "unicode-bidi_0.3.18": "{\"dependencies\":[{\"name\":\"flame\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"flamer\",\"optional\":true,\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\">=0.8, <2.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\">=0.8, <2.0\"},{\"features\":[\"union\"],\"name\":\"smallvec\",\"optional\":true,\"req\":\">=1.13\"}],\"features\":{\"bench_it\":[],\"default\":[\"std\",\"hardcoded-data\"],\"flame_it\":[\"flame\",\"flamer\"],\"hardcoded-data\":[],\"std\":[],\"unstable\":[],\"with_serde\":[\"serde\"]}}", "unicode-ident_1.0.18": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"fst\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"roaring\",\"req\":\"^0.10\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"ucd-trie\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"unicode-xid\",\"req\":\"^0.2.6\"}],\"features\":{}}", "unicode-linebreak_0.1.5": "{\"dependencies\":[],\"features\":{}}", + "unicode-normalization_0.1.25": "{\"dependencies\":[{\"features\":[\"alloc\"],\"name\":\"tinyvec\",\"req\":\"^1\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", + "unicode-properties_0.1.4": "{\"dependencies\":[],\"features\":{\"default\":[\"general-category\",\"emoji\"],\"emoji\":[],\"general-category\":[]}}", "unicode-segmentation_1.12.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^0.7\"}],\"features\":{\"no_std\":[]}}", "unicode-truncate_1.1.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"itertools\",\"req\":\"^0.13\"},{\"default_features\":false,\"name\":\"unicode-segmentation\",\"req\":\"^1\"},{\"name\":\"unicode-width\",\"req\":\"^0.1\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "unicode-width_0.1.14": "{\"dependencies\":[{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0\"},{\"name\":\"std\",\"optional\":true,\"package\":\"rustc-std-workspace-std\",\"req\":\"^1.0\"}],\"features\":{\"cjk\":[],\"default\":[\"cjk\"],\"no_std\":[],\"rustc-dep-of-std\":[\"std\",\"core\",\"compiler_builtins\"]}}", @@ -1189,6 +1282,7 @@ "want_0.3.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"tokio-executor\",\"req\":\"^0.2.0-alpha.2\"},{\"kind\":\"dev\",\"name\":\"tokio-sync\",\"req\":\"^0.2.0-alpha.2\"},{\"name\":\"try-lock\",\"req\":\"^0.2.4\"}],\"features\":{}}", "wasi_0.11.1+wasi-snapshot-preview1": "{\"dependencies\":[{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0\"},{\"name\":\"rustc-std-workspace-alloc\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"rustc-dep-of-std\":[\"core\",\"rustc-std-workspace-alloc\"],\"std\":[]}}", "wasi_0.14.2+wasi-0.2.4": "{\"dependencies\":[{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0\"},{\"name\":\"rustc-std-workspace-alloc\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"bitflags\"],\"name\":\"wit-bindgen-rt\",\"req\":\"^0.39.0\"}],\"features\":{\"default\":[\"std\"],\"rustc-dep-of-std\":[\"compiler_builtins\",\"core\",\"rustc-std-workspace-alloc\"],\"std\":[]}}", + "wasite_0.1.0": "{\"dependencies\":[],\"features\":{}}", "wasm-bindgen-backend_0.2.100": "{\"dependencies\":[{\"name\":\"bumpalo\",\"req\":\"^3.0.0\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"name\":\"wasm-bindgen-shared\",\"req\":\"=0.2.100\"}],\"features\":{\"extra-traits\":[\"syn/extra-traits\"]}}", "wasm-bindgen-futures_0.4.50": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"futures-channel\",\"req\":\"^0.3\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"default_features\":false,\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3.8\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures-lite\",\"req\":\"^2\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"default_features\":false,\"name\":\"js-sys\",\"req\":\"=0.3.77\"},{\"default_features\":false,\"name\":\"once_cell\",\"req\":\"^1.12\"},{\"default_features\":false,\"name\":\"wasm-bindgen\",\"req\":\"=0.2.100\"},{\"default_features\":false,\"features\":[\"MessageEvent\",\"Worker\"],\"name\":\"web-sys\",\"req\":\"=0.3.77\",\"target\":\"cfg(target_feature = \\\"atomics\\\")\"}],\"features\":{\"default\":[\"std\"],\"futures-core-03-stream\":[\"futures-core\"],\"std\":[\"wasm-bindgen/std\",\"js-sys/std\",\"web-sys/std\"]}}", "wasm-bindgen-macro-support_0.2.100": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"visit\",\"visit-mut\",\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"name\":\"wasm-bindgen-backend\",\"req\":\"=0.2.100\"},{\"name\":\"wasm-bindgen-shared\",\"req\":\"=0.2.100\"}],\"features\":{\"extra-traits\":[\"syn/extra-traits\"],\"strict-macro\":[]}}", @@ -1210,6 +1304,9 @@ "webpki-roots_1.0.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"kind\":\"dev\",\"name\":\"percent-encoding\",\"req\":\"^2.3\"},{\"default_features\":false,\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1.8\"},{\"kind\":\"dev\",\"name\":\"rcgen\",\"req\":\"^0.14\"},{\"kind\":\"dev\",\"name\":\"ring\",\"req\":\"^0.17.0\"},{\"kind\":\"dev\",\"name\":\"rustls\",\"req\":\"^0.23\"},{\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"webpki\",\"package\":\"rustls-webpki\",\"req\":\"^0.103\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.17.0\"},{\"kind\":\"dev\",\"name\":\"yasna\",\"req\":\"^0.5.2\"}],\"features\":{}}", "weezl_0.1.10": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures\",\"optional\":true,\"req\":\"^0.3.12\"},{\"default_features\":false,\"features\":[\"macros\",\"io-util\",\"net\",\"rt\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"compat\"],\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.6.2\"}],\"features\":{\"alloc\":[],\"async\":[\"futures\",\"std\"],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "which_8.0.0": "{\"dependencies\":[{\"name\":\"env_home\",\"optional\":true,\"req\":\"^0.1.0\",\"target\":\"cfg(any(windows, unix, target_os = \\\"redox\\\"))\"},{\"name\":\"regex\",\"optional\":true,\"req\":\"^1.10.2\"},{\"default_features\":false,\"features\":[\"fs\",\"std\"],\"name\":\"rustix\",\"optional\":true,\"req\":\"^1.0.5\",\"target\":\"cfg(any(unix, target_os = \\\"wasi\\\", target_os = \\\"redox\\\"))\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.9.0\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1.40\"},{\"features\":[\"kernel\"],\"name\":\"winsafe\",\"optional\":true,\"req\":\"^0.0.19\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"real-sys\"],\"real-sys\":[\"dep:env_home\",\"dep:rustix\",\"dep:winsafe\"],\"regex\":[\"dep:regex\"],\"tracing\":[\"dep:tracing\"]}}", + "whoami_1.6.1": "{\"dependencies\":[{\"name\":\"libredox\",\"req\":\"^0.1.1\",\"target\":\"cfg(all(target_os = \\\"redox\\\", not(target_arch = \\\"wasm32\\\")))\"},{\"name\":\"wasite\",\"req\":\"^0.1\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"wasi\\\"))\"},{\"features\":[\"Navigator\",\"Document\",\"Window\",\"Location\"],\"name\":\"web-sys\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", not(target_os = \\\"wasi\\\"), not(daku)))\"}],\"features\":{\"default\":[\"web\"],\"web\":[\"web-sys\"]}}", + "widestring_1.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"debugger_test\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"debugger_test_parser\",\"req\":\"^0.1\"},{\"features\":[\"Win32_System_Diagnostics_Debug\"],\"kind\":\"dev\",\"name\":\"windows-sys\",\"req\":\"^0.59\"}],\"features\":{\"alloc\":[],\"debugger_visualizer\":[\"alloc\"],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", + "wildcard_0.3.0": "{\"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.10.5\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.203\"},{\"default_features\":false,\"name\":\"thiserror\",\"req\":\"^2.0.3\"},{\"kind\":\"dev\",\"name\":\"toml\",\"req\":\"^0.8.14\"},{\"kind\":\"dev\",\"name\":\"wildmatch\",\"req\":\"^2.3.4\"}],\"features\":{\"fatal-warnings\":[]}}", "wildmatch_2.6.1": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"glob\",\"req\":\"^0.3.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"ntest\",\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.10.2\"},{\"kind\":\"dev\",\"name\":\"regex-lite\",\"req\":\"^0.1.5\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"serde\":[\"dep:serde\"]}}", "winapi-i686-pc-windows-gnu_0.4.0": "{\"dependencies\":[],\"features\":{}}", "winapi-util_0.1.9": "{\"dependencies\":[{\"features\":[\"Win32_Foundation\",\"Win32_Storage_FileSystem\",\"Win32_System_Console\",\"Win32_System_SystemInformation\"],\"name\":\"windows-sys\",\"req\":\">=0.48.0, <=0.59\",\"target\":\"cfg(windows)\"}],\"features\":{}}", @@ -1232,6 +1329,7 @@ "windows-strings_0.1.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"windows-result\",\"req\":\"^0.2.0\"},{\"name\":\"windows-targets\",\"req\":\"^0.52.6\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "windows-strings_0.4.2": "{\"dependencies\":[{\"default_features\":false,\"name\":\"windows-link\",\"req\":\"^0.1.1\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "windows-sys_0.45.0": "{\"dependencies\":[{\"name\":\"windows-targets\",\"req\":\"^0.42.1\",\"target\":\"cfg(not(windows_raw_dylib))\"}],\"features\":{\"Win32\":[],\"Win32_Data\":[\"Win32\"],\"Win32_Data_HtmlHelp\":[\"Win32_Data\"],\"Win32_Data_RightsManagement\":[\"Win32_Data\"],\"Win32_Data_Xml\":[\"Win32_Data\"],\"Win32_Data_Xml_MsXml\":[\"Win32_Data_Xml\"],\"Win32_Data_Xml_XmlLite\":[\"Win32_Data_Xml\"],\"Win32_Devices\":[\"Win32\"],\"Win32_Devices_AllJoyn\":[\"Win32_Devices\"],\"Win32_Devices_BiometricFramework\":[\"Win32_Devices\"],\"Win32_Devices_Bluetooth\":[\"Win32_Devices\"],\"Win32_Devices_Communication\":[\"Win32_Devices\"],\"Win32_Devices_DeviceAccess\":[\"Win32_Devices\"],\"Win32_Devices_DeviceAndDriverInstallation\":[\"Win32_Devices\"],\"Win32_Devices_DeviceQuery\":[\"Win32_Devices\"],\"Win32_Devices_Display\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration_Pnp\":[\"Win32_Devices_Enumeration\"],\"Win32_Devices_Fax\":[\"Win32_Devices\"],\"Win32_Devices_FunctionDiscovery\":[\"Win32_Devices\"],\"Win32_Devices_Geolocation\":[\"Win32_Devices\"],\"Win32_Devices_HumanInterfaceDevice\":[\"Win32_Devices\"],\"Win32_Devices_ImageAcquisition\":[\"Win32_Devices\"],\"Win32_Devices_PortableDevices\":[\"Win32_Devices\"],\"Win32_Devices_Properties\":[\"Win32_Devices\"],\"Win32_Devices_Pwm\":[\"Win32_Devices\"],\"Win32_Devices_Sensors\":[\"Win32_Devices\"],\"Win32_Devices_SerialCommunication\":[\"Win32_Devices\"],\"Win32_Devices_Tapi\":[\"Win32_Devices\"],\"Win32_Devices_Usb\":[\"Win32_Devices\"],\"Win32_Devices_WebServicesOnDevices\":[\"Win32_Devices\"],\"Win32_Foundation\":[\"Win32\"],\"Win32_Gaming\":[\"Win32\"],\"Win32_Globalization\":[\"Win32\"],\"Win32_Graphics\":[\"Win32\"],\"Win32_Graphics_Dwm\":[\"Win32_Graphics\"],\"Win32_Graphics_Gdi\":[\"Win32_Graphics\"],\"Win32_Graphics_Hlsl\":[\"Win32_Graphics\"],\"Win32_Graphics_OpenGL\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing_PrintTicket\":[\"Win32_Graphics_Printing\"],\"Win32_Management\":[\"Win32\"],\"Win32_Management_MobileDeviceManagementRegistration\":[\"Win32_Management\"],\"Win32_Media\":[\"Win32\"],\"Win32_Media_Audio\":[\"Win32_Media\"],\"Win32_Media_Audio_Apo\":[\"Win32_Media_Audio\"],\"Win32_Media_Audio_DirectMusic\":[\"Win32_Media_Audio\"],\"Win32_Media_Audio_Endpoints\":[\"Win32_Media_Audio\"],\"Win32_Media_Audio_XAudio2\":[\"Win32_Media_Audio\"],\"Win32_Media_DeviceManager\":[\"Win32_Media\"],\"Win32_Media_DxMediaObjects\":[\"Win32_Media\"],\"Win32_Media_KernelStreaming\":[\"Win32_Media\"],\"Win32_Media_LibrarySharingServices\":[\"Win32_Media\"],\"Win32_Media_MediaPlayer\":[\"Win32_Media\"],\"Win32_Media_Multimedia\":[\"Win32_Media\"],\"Win32_Media_Speech\":[\"Win32_Media\"],\"Win32_Media_Streaming\":[\"Win32_Media\"],\"Win32_Media_WindowsMediaFormat\":[\"Win32_Media\"],\"Win32_NetworkManagement\":[\"Win32\"],\"Win32_NetworkManagement_Dhcp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Dns\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_InternetConnectionWizard\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_IpHelper\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_MobileBroadband\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Multicast\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Ndis\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetBios\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetManagement\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetShell\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetworkDiagnosticsFramework\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetworkPolicyServer\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_P2P\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_QoS\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Rras\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Snmp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WNet\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WebDav\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WiFi\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsConnectNow\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsConnectionManager\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFilteringPlatform\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFirewall\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsNetworkVirtualization\":[\"Win32_NetworkManagement\"],\"Win32_Networking\":[\"Win32\"],\"Win32_Networking_ActiveDirectory\":[\"Win32_Networking\"],\"Win32_Networking_BackgroundIntelligentTransferService\":[\"Win32_Networking\"],\"Win32_Networking_Clustering\":[\"Win32_Networking\"],\"Win32_Networking_HttpServer\":[\"Win32_Networking\"],\"Win32_Networking_Ldap\":[\"Win32_Networking\"],\"Win32_Networking_NetworkListManager\":[\"Win32_Networking\"],\"Win32_Networking_RemoteDifferentialCompression\":[\"Win32_Networking\"],\"Win32_Networking_WebSocket\":[\"Win32_Networking\"],\"Win32_Networking_WinHttp\":[\"Win32_Networking\"],\"Win32_Networking_WinInet\":[\"Win32_Networking\"],\"Win32_Networking_WinSock\":[\"Win32_Networking\"],\"Win32_Networking_WindowsWebServices\":[\"Win32_Networking\"],\"Win32_Security\":[\"Win32\"],\"Win32_Security_AppLocker\":[\"Win32_Security\"],\"Win32_Security_Authentication\":[\"Win32_Security\"],\"Win32_Security_Authentication_Identity\":[\"Win32_Security_Authentication\"],\"Win32_Security_Authentication_Identity_Provider\":[\"Win32_Security_Authentication_Identity\"],\"Win32_Security_Authorization\":[\"Win32_Security\"],\"Win32_Security_Authorization_UI\":[\"Win32_Security_Authorization\"],\"Win32_Security_ConfigurationSnapin\":[\"Win32_Security\"],\"Win32_Security_Credentials\":[\"Win32_Security\"],\"Win32_Security_Cryptography\":[\"Win32_Security\"],\"Win32_Security_Cryptography_Catalog\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Certificates\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Sip\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_UI\":[\"Win32_Security_Cryptography\"],\"Win32_Security_DiagnosticDataQuery\":[\"Win32_Security\"],\"Win32_Security_DirectoryServices\":[\"Win32_Security\"],\"Win32_Security_EnterpriseData\":[\"Win32_Security\"],\"Win32_Security_ExtensibleAuthenticationProtocol\":[\"Win32_Security\"],\"Win32_Security_Isolation\":[\"Win32_Security\"],\"Win32_Security_LicenseProtection\":[\"Win32_Security\"],\"Win32_Security_NetworkAccessProtection\":[\"Win32_Security\"],\"Win32_Security_Tpm\":[\"Win32_Security\"],\"Win32_Security_WinTrust\":[\"Win32_Security\"],\"Win32_Security_WinWlx\":[\"Win32_Security\"],\"Win32_Storage\":[\"Win32\"],\"Win32_Storage_Cabinets\":[\"Win32_Storage\"],\"Win32_Storage_CloudFilters\":[\"Win32_Storage\"],\"Win32_Storage_Compression\":[\"Win32_Storage\"],\"Win32_Storage_DataDeduplication\":[\"Win32_Storage\"],\"Win32_Storage_DistributedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_EnhancedStorage\":[\"Win32_Storage\"],\"Win32_Storage_FileHistory\":[\"Win32_Storage\"],\"Win32_Storage_FileServerResourceManager\":[\"Win32_Storage\"],\"Win32_Storage_FileSystem\":[\"Win32_Storage\"],\"Win32_Storage_Imapi\":[\"Win32_Storage\"],\"Win32_Storage_IndexServer\":[\"Win32_Storage\"],\"Win32_Storage_InstallableFileSystems\":[\"Win32_Storage\"],\"Win32_Storage_IscsiDisc\":[\"Win32_Storage\"],\"Win32_Storage_Jet\":[\"Win32_Storage\"],\"Win32_Storage_OfflineFiles\":[\"Win32_Storage\"],\"Win32_Storage_OperationRecorder\":[\"Win32_Storage\"],\"Win32_Storage_Packaging\":[\"Win32_Storage\"],\"Win32_Storage_Packaging_Appx\":[\"Win32_Storage_Packaging\"],\"Win32_Storage_Packaging_Opc\":[\"Win32_Storage_Packaging\"],\"Win32_Storage_ProjectedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_StructuredStorage\":[\"Win32_Storage\"],\"Win32_Storage_Vhd\":[\"Win32_Storage\"],\"Win32_Storage_VirtualDiskService\":[\"Win32_Storage\"],\"Win32_Storage_Vss\":[\"Win32_Storage\"],\"Win32_Storage_Xps\":[\"Win32_Storage\"],\"Win32_Storage_Xps_Printing\":[\"Win32_Storage_Xps\"],\"Win32_System\":[\"Win32\"],\"Win32_System_AddressBook\":[\"Win32_System\"],\"Win32_System_Antimalware\":[\"Win32_System\"],\"Win32_System_ApplicationInstallationAndServicing\":[\"Win32_System\"],\"Win32_System_ApplicationVerifier\":[\"Win32_System\"],\"Win32_System_AssessmentTool\":[\"Win32_System\"],\"Win32_System_Com\":[\"Win32_System\"],\"Win32_System_Com_CallObj\":[\"Win32_System_Com\"],\"Win32_System_Com_ChannelCredentials\":[\"Win32_System_Com\"],\"Win32_System_Com_Events\":[\"Win32_System_Com\"],\"Win32_System_Com_Marshal\":[\"Win32_System_Com\"],\"Win32_System_Com_StructuredStorage\":[\"Win32_System_Com\"],\"Win32_System_Com_UI\":[\"Win32_System_Com\"],\"Win32_System_Com_Urlmon\":[\"Win32_System_Com\"],\"Win32_System_ComponentServices\":[\"Win32_System\"],\"Win32_System_Console\":[\"Win32_System\"],\"Win32_System_Contacts\":[\"Win32_System\"],\"Win32_System_CorrelationVector\":[\"Win32_System\"],\"Win32_System_DataExchange\":[\"Win32_System\"],\"Win32_System_DeploymentServices\":[\"Win32_System\"],\"Win32_System_DesktopSharing\":[\"Win32_System\"],\"Win32_System_DeveloperLicensing\":[\"Win32_System\"],\"Win32_System_Diagnostics\":[\"Win32_System\"],\"Win32_System_Diagnostics_Ceip\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Etw\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ProcessSnapshotting\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ToolHelp\":[\"Win32_System_Diagnostics\"],\"Win32_System_DistributedTransactionCoordinator\":[\"Win32_System\"],\"Win32_System_Environment\":[\"Win32_System\"],\"Win32_System_ErrorReporting\":[\"Win32_System\"],\"Win32_System_EventCollector\":[\"Win32_System\"],\"Win32_System_EventLog\":[\"Win32_System\"],\"Win32_System_EventNotificationService\":[\"Win32_System\"],\"Win32_System_GroupPolicy\":[\"Win32_System\"],\"Win32_System_HostCompute\":[\"Win32_System\"],\"Win32_System_HostComputeNetwork\":[\"Win32_System\"],\"Win32_System_HostComputeSystem\":[\"Win32_System\"],\"Win32_System_Hypervisor\":[\"Win32_System\"],\"Win32_System_IO\":[\"Win32_System\"],\"Win32_System_Iis\":[\"Win32_System\"],\"Win32_System_Ioctl\":[\"Win32_System\"],\"Win32_System_JobObjects\":[\"Win32_System\"],\"Win32_System_Js\":[\"Win32_System\"],\"Win32_System_Kernel\":[\"Win32_System\"],\"Win32_System_LibraryLoader\":[\"Win32_System\"],\"Win32_System_Mailslots\":[\"Win32_System\"],\"Win32_System_Mapi\":[\"Win32_System\"],\"Win32_System_Memory\":[\"Win32_System\"],\"Win32_System_Memory_NonVolatile\":[\"Win32_System_Memory\"],\"Win32_System_MessageQueuing\":[\"Win32_System\"],\"Win32_System_MixedReality\":[\"Win32_System\"],\"Win32_System_Mmc\":[\"Win32_System\"],\"Win32_System_Ole\":[\"Win32_System\"],\"Win32_System_ParentalControls\":[\"Win32_System\"],\"Win32_System_PasswordManagement\":[\"Win32_System\"],\"Win32_System_Performance\":[\"Win32_System\"],\"Win32_System_Performance_HardwareCounterProfiling\":[\"Win32_System_Performance\"],\"Win32_System_Pipes\":[\"Win32_System\"],\"Win32_System_Power\":[\"Win32_System\"],\"Win32_System_ProcessStatus\":[\"Win32_System\"],\"Win32_System_RealTimeCommunications\":[\"Win32_System\"],\"Win32_System_Recovery\":[\"Win32_System\"],\"Win32_System_Registry\":[\"Win32_System\"],\"Win32_System_RemoteAssistance\":[\"Win32_System\"],\"Win32_System_RemoteDesktop\":[\"Win32_System\"],\"Win32_System_RemoteManagement\":[\"Win32_System\"],\"Win32_System_RestartManager\":[\"Win32_System\"],\"Win32_System_Restore\":[\"Win32_System\"],\"Win32_System_Rpc\":[\"Win32_System\"],\"Win32_System_Search\":[\"Win32_System\"],\"Win32_System_Search_Common\":[\"Win32_System_Search\"],\"Win32_System_SecurityCenter\":[\"Win32_System\"],\"Win32_System_ServerBackup\":[\"Win32_System\"],\"Win32_System_Services\":[\"Win32_System\"],\"Win32_System_SettingsManagementInfrastructure\":[\"Win32_System\"],\"Win32_System_SetupAndMigration\":[\"Win32_System\"],\"Win32_System_Shutdown\":[\"Win32_System\"],\"Win32_System_StationsAndDesktops\":[\"Win32_System\"],\"Win32_System_SubsystemForLinux\":[\"Win32_System\"],\"Win32_System_SystemInformation\":[\"Win32_System\"],\"Win32_System_SystemServices\":[\"Win32_System\"],\"Win32_System_TaskScheduler\":[\"Win32_System\"],\"Win32_System_Threading\":[\"Win32_System\"],\"Win32_System_Time\":[\"Win32_System\"],\"Win32_System_TpmBaseServices\":[\"Win32_System\"],\"Win32_System_UpdateAgent\":[\"Win32_System\"],\"Win32_System_UpdateAssessment\":[\"Win32_System\"],\"Win32_System_UserAccessLogging\":[\"Win32_System\"],\"Win32_System_VirtualDosMachines\":[\"Win32_System\"],\"Win32_System_WindowsProgramming\":[\"Win32_System\"],\"Win32_System_WindowsSync\":[\"Win32_System\"],\"Win32_System_Wmi\":[\"Win32_System\"],\"Win32_UI\":[\"Win32\"],\"Win32_UI_Accessibility\":[\"Win32_UI\"],\"Win32_UI_Animation\":[\"Win32_UI\"],\"Win32_UI_ColorSystem\":[\"Win32_UI\"],\"Win32_UI_Controls\":[\"Win32_UI\"],\"Win32_UI_Controls_Dialogs\":[\"Win32_UI_Controls\"],\"Win32_UI_Controls_RichEdit\":[\"Win32_UI_Controls\"],\"Win32_UI_HiDpi\":[\"Win32_UI\"],\"Win32_UI_Input\":[\"Win32_UI\"],\"Win32_UI_Input_Ime\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Ink\":[\"Win32_UI_Input\"],\"Win32_UI_Input_KeyboardAndMouse\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Pointer\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Radial\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Touch\":[\"Win32_UI_Input\"],\"Win32_UI_Input_XboxController\":[\"Win32_UI_Input\"],\"Win32_UI_InteractionContext\":[\"Win32_UI\"],\"Win32_UI_LegacyWindowsEnvironmentFeatures\":[\"Win32_UI\"],\"Win32_UI_Magnification\":[\"Win32_UI\"],\"Win32_UI_Notifications\":[\"Win32_UI\"],\"Win32_UI_Ribbon\":[\"Win32_UI\"],\"Win32_UI_Shell\":[\"Win32_UI\"],\"Win32_UI_Shell_Common\":[\"Win32_UI_Shell\"],\"Win32_UI_Shell_PropertiesSystem\":[\"Win32_UI_Shell\"],\"Win32_UI_TabletPC\":[\"Win32_UI\"],\"Win32_UI_TextServices\":[\"Win32_UI\"],\"Win32_UI_WindowsAndMessaging\":[\"Win32_UI\"],\"Win32_UI_Wpf\":[\"Win32_UI\"],\"default\":[]}}", + "windows-sys_0.48.0": "{\"dependencies\":[{\"name\":\"windows-targets\",\"req\":\"^0.48.0\"}],\"features\":{\"Wdk\":[],\"Wdk_System\":[\"Wdk\"],\"Wdk_System_OfflineRegistry\":[\"Wdk_System\"],\"Win32\":[],\"Win32_Data\":[\"Win32\"],\"Win32_Data_HtmlHelp\":[\"Win32_Data\"],\"Win32_Data_RightsManagement\":[\"Win32_Data\"],\"Win32_Data_Xml\":[\"Win32_Data\"],\"Win32_Data_Xml_MsXml\":[\"Win32_Data_Xml\"],\"Win32_Data_Xml_XmlLite\":[\"Win32_Data_Xml\"],\"Win32_Devices\":[\"Win32\"],\"Win32_Devices_AllJoyn\":[\"Win32_Devices\"],\"Win32_Devices_BiometricFramework\":[\"Win32_Devices\"],\"Win32_Devices_Bluetooth\":[\"Win32_Devices\"],\"Win32_Devices_Communication\":[\"Win32_Devices\"],\"Win32_Devices_DeviceAccess\":[\"Win32_Devices\"],\"Win32_Devices_DeviceAndDriverInstallation\":[\"Win32_Devices\"],\"Win32_Devices_DeviceQuery\":[\"Win32_Devices\"],\"Win32_Devices_Display\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration_Pnp\":[\"Win32_Devices_Enumeration\"],\"Win32_Devices_Fax\":[\"Win32_Devices\"],\"Win32_Devices_FunctionDiscovery\":[\"Win32_Devices\"],\"Win32_Devices_Geolocation\":[\"Win32_Devices\"],\"Win32_Devices_HumanInterfaceDevice\":[\"Win32_Devices\"],\"Win32_Devices_ImageAcquisition\":[\"Win32_Devices\"],\"Win32_Devices_PortableDevices\":[\"Win32_Devices\"],\"Win32_Devices_Properties\":[\"Win32_Devices\"],\"Win32_Devices_Pwm\":[\"Win32_Devices\"],\"Win32_Devices_Sensors\":[\"Win32_Devices\"],\"Win32_Devices_SerialCommunication\":[\"Win32_Devices\"],\"Win32_Devices_Tapi\":[\"Win32_Devices\"],\"Win32_Devices_Usb\":[\"Win32_Devices\"],\"Win32_Devices_WebServicesOnDevices\":[\"Win32_Devices\"],\"Win32_Foundation\":[\"Win32\"],\"Win32_Gaming\":[\"Win32\"],\"Win32_Globalization\":[\"Win32\"],\"Win32_Graphics\":[\"Win32\"],\"Win32_Graphics_Dwm\":[\"Win32_Graphics\"],\"Win32_Graphics_Gdi\":[\"Win32_Graphics\"],\"Win32_Graphics_Hlsl\":[\"Win32_Graphics\"],\"Win32_Graphics_OpenGL\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing_PrintTicket\":[\"Win32_Graphics_Printing\"],\"Win32_Management\":[\"Win32\"],\"Win32_Management_MobileDeviceManagementRegistration\":[\"Win32_Management\"],\"Win32_Media\":[\"Win32\"],\"Win32_Media_Audio\":[\"Win32_Media\"],\"Win32_Media_Audio_Apo\":[\"Win32_Media_Audio\"],\"Win32_Media_Audio_DirectMusic\":[\"Win32_Media_Audio\"],\"Win32_Media_Audio_Endpoints\":[\"Win32_Media_Audio\"],\"Win32_Media_Audio_XAudio2\":[\"Win32_Media_Audio\"],\"Win32_Media_DeviceManager\":[\"Win32_Media\"],\"Win32_Media_DxMediaObjects\":[\"Win32_Media\"],\"Win32_Media_KernelStreaming\":[\"Win32_Media\"],\"Win32_Media_LibrarySharingServices\":[\"Win32_Media\"],\"Win32_Media_MediaPlayer\":[\"Win32_Media\"],\"Win32_Media_Multimedia\":[\"Win32_Media\"],\"Win32_Media_Speech\":[\"Win32_Media\"],\"Win32_Media_Streaming\":[\"Win32_Media\"],\"Win32_Media_WindowsMediaFormat\":[\"Win32_Media\"],\"Win32_NetworkManagement\":[\"Win32\"],\"Win32_NetworkManagement_Dhcp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Dns\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_InternetConnectionWizard\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_IpHelper\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_MobileBroadband\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Multicast\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Ndis\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetBios\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetManagement\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetShell\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetworkDiagnosticsFramework\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetworkPolicyServer\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_P2P\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_QoS\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Rras\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Snmp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WNet\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WebDav\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WiFi\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsConnectNow\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsConnectionManager\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFilteringPlatform\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFirewall\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsNetworkVirtualization\":[\"Win32_NetworkManagement\"],\"Win32_Networking\":[\"Win32\"],\"Win32_Networking_ActiveDirectory\":[\"Win32_Networking\"],\"Win32_Networking_BackgroundIntelligentTransferService\":[\"Win32_Networking\"],\"Win32_Networking_Clustering\":[\"Win32_Networking\"],\"Win32_Networking_HttpServer\":[\"Win32_Networking\"],\"Win32_Networking_Ldap\":[\"Win32_Networking\"],\"Win32_Networking_NetworkListManager\":[\"Win32_Networking\"],\"Win32_Networking_RemoteDifferentialCompression\":[\"Win32_Networking\"],\"Win32_Networking_WebSocket\":[\"Win32_Networking\"],\"Win32_Networking_WinHttp\":[\"Win32_Networking\"],\"Win32_Networking_WinInet\":[\"Win32_Networking\"],\"Win32_Networking_WinSock\":[\"Win32_Networking\"],\"Win32_Networking_WindowsWebServices\":[\"Win32_Networking\"],\"Win32_Security\":[\"Win32\"],\"Win32_Security_AppLocker\":[\"Win32_Security\"],\"Win32_Security_Authentication\":[\"Win32_Security\"],\"Win32_Security_Authentication_Identity\":[\"Win32_Security_Authentication\"],\"Win32_Security_Authentication_Identity_Provider\":[\"Win32_Security_Authentication_Identity\"],\"Win32_Security_Authorization\":[\"Win32_Security\"],\"Win32_Security_Authorization_UI\":[\"Win32_Security_Authorization\"],\"Win32_Security_ConfigurationSnapin\":[\"Win32_Security\"],\"Win32_Security_Credentials\":[\"Win32_Security\"],\"Win32_Security_Cryptography\":[\"Win32_Security\"],\"Win32_Security_Cryptography_Catalog\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Certificates\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Sip\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_UI\":[\"Win32_Security_Cryptography\"],\"Win32_Security_DiagnosticDataQuery\":[\"Win32_Security\"],\"Win32_Security_DirectoryServices\":[\"Win32_Security\"],\"Win32_Security_EnterpriseData\":[\"Win32_Security\"],\"Win32_Security_ExtensibleAuthenticationProtocol\":[\"Win32_Security\"],\"Win32_Security_Isolation\":[\"Win32_Security\"],\"Win32_Security_LicenseProtection\":[\"Win32_Security\"],\"Win32_Security_NetworkAccessProtection\":[\"Win32_Security\"],\"Win32_Security_Tpm\":[\"Win32_Security\"],\"Win32_Security_WinTrust\":[\"Win32_Security\"],\"Win32_Security_WinWlx\":[\"Win32_Security\"],\"Win32_Storage\":[\"Win32\"],\"Win32_Storage_Cabinets\":[\"Win32_Storage\"],\"Win32_Storage_CloudFilters\":[\"Win32_Storage\"],\"Win32_Storage_Compression\":[\"Win32_Storage\"],\"Win32_Storage_DataDeduplication\":[\"Win32_Storage\"],\"Win32_Storage_DistributedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_EnhancedStorage\":[\"Win32_Storage\"],\"Win32_Storage_FileHistory\":[\"Win32_Storage\"],\"Win32_Storage_FileServerResourceManager\":[\"Win32_Storage\"],\"Win32_Storage_FileSystem\":[\"Win32_Storage\"],\"Win32_Storage_Imapi\":[\"Win32_Storage\"],\"Win32_Storage_IndexServer\":[\"Win32_Storage\"],\"Win32_Storage_InstallableFileSystems\":[\"Win32_Storage\"],\"Win32_Storage_IscsiDisc\":[\"Win32_Storage\"],\"Win32_Storage_Jet\":[\"Win32_Storage\"],\"Win32_Storage_OfflineFiles\":[\"Win32_Storage\"],\"Win32_Storage_OperationRecorder\":[\"Win32_Storage\"],\"Win32_Storage_Packaging\":[\"Win32_Storage\"],\"Win32_Storage_Packaging_Appx\":[\"Win32_Storage_Packaging\"],\"Win32_Storage_Packaging_Opc\":[\"Win32_Storage_Packaging\"],\"Win32_Storage_ProjectedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_StructuredStorage\":[\"Win32_Storage\"],\"Win32_Storage_Vhd\":[\"Win32_Storage\"],\"Win32_Storage_VirtualDiskService\":[\"Win32_Storage\"],\"Win32_Storage_Vss\":[\"Win32_Storage\"],\"Win32_Storage_Xps\":[\"Win32_Storage\"],\"Win32_Storage_Xps_Printing\":[\"Win32_Storage_Xps\"],\"Win32_System\":[\"Win32\"],\"Win32_System_AddressBook\":[\"Win32_System\"],\"Win32_System_Antimalware\":[\"Win32_System\"],\"Win32_System_ApplicationInstallationAndServicing\":[\"Win32_System\"],\"Win32_System_ApplicationVerifier\":[\"Win32_System\"],\"Win32_System_AssessmentTool\":[\"Win32_System\"],\"Win32_System_ClrHosting\":[\"Win32_System\"],\"Win32_System_Com\":[\"Win32_System\"],\"Win32_System_Com_CallObj\":[\"Win32_System_Com\"],\"Win32_System_Com_ChannelCredentials\":[\"Win32_System_Com\"],\"Win32_System_Com_Events\":[\"Win32_System_Com\"],\"Win32_System_Com_Marshal\":[\"Win32_System_Com\"],\"Win32_System_Com_StructuredStorage\":[\"Win32_System_Com\"],\"Win32_System_Com_UI\":[\"Win32_System_Com\"],\"Win32_System_Com_Urlmon\":[\"Win32_System_Com\"],\"Win32_System_ComponentServices\":[\"Win32_System\"],\"Win32_System_Console\":[\"Win32_System\"],\"Win32_System_Contacts\":[\"Win32_System\"],\"Win32_System_CorrelationVector\":[\"Win32_System\"],\"Win32_System_DataExchange\":[\"Win32_System\"],\"Win32_System_DeploymentServices\":[\"Win32_System\"],\"Win32_System_DesktopSharing\":[\"Win32_System\"],\"Win32_System_DeveloperLicensing\":[\"Win32_System\"],\"Win32_System_Diagnostics\":[\"Win32_System\"],\"Win32_System_Diagnostics_Ceip\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ClrProfiling\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug_ActiveScript\":[\"Win32_System_Diagnostics_Debug\"],\"Win32_System_Diagnostics_Debug_Extensions\":[\"Win32_System_Diagnostics_Debug\"],\"Win32_System_Diagnostics_Etw\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ProcessSnapshotting\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ToolHelp\":[\"Win32_System_Diagnostics\"],\"Win32_System_DistributedTransactionCoordinator\":[\"Win32_System\"],\"Win32_System_Environment\":[\"Win32_System\"],\"Win32_System_ErrorReporting\":[\"Win32_System\"],\"Win32_System_EventCollector\":[\"Win32_System\"],\"Win32_System_EventLog\":[\"Win32_System\"],\"Win32_System_EventNotificationService\":[\"Win32_System\"],\"Win32_System_GroupPolicy\":[\"Win32_System\"],\"Win32_System_HostCompute\":[\"Win32_System\"],\"Win32_System_HostComputeNetwork\":[\"Win32_System\"],\"Win32_System_HostComputeSystem\":[\"Win32_System\"],\"Win32_System_Hypervisor\":[\"Win32_System\"],\"Win32_System_IO\":[\"Win32_System\"],\"Win32_System_Iis\":[\"Win32_System\"],\"Win32_System_Ioctl\":[\"Win32_System\"],\"Win32_System_JobObjects\":[\"Win32_System\"],\"Win32_System_Js\":[\"Win32_System\"],\"Win32_System_Kernel\":[\"Win32_System\"],\"Win32_System_LibraryLoader\":[\"Win32_System\"],\"Win32_System_Mailslots\":[\"Win32_System\"],\"Win32_System_Mapi\":[\"Win32_System\"],\"Win32_System_Memory\":[\"Win32_System\"],\"Win32_System_Memory_NonVolatile\":[\"Win32_System_Memory\"],\"Win32_System_MessageQueuing\":[\"Win32_System\"],\"Win32_System_MixedReality\":[\"Win32_System\"],\"Win32_System_Mmc\":[\"Win32_System\"],\"Win32_System_Ole\":[\"Win32_System\"],\"Win32_System_ParentalControls\":[\"Win32_System\"],\"Win32_System_PasswordManagement\":[\"Win32_System\"],\"Win32_System_Performance\":[\"Win32_System\"],\"Win32_System_Performance_HardwareCounterProfiling\":[\"Win32_System_Performance\"],\"Win32_System_Pipes\":[\"Win32_System\"],\"Win32_System_Power\":[\"Win32_System\"],\"Win32_System_ProcessStatus\":[\"Win32_System\"],\"Win32_System_RealTimeCommunications\":[\"Win32_System\"],\"Win32_System_Recovery\":[\"Win32_System\"],\"Win32_System_Registry\":[\"Win32_System\"],\"Win32_System_RemoteAssistance\":[\"Win32_System\"],\"Win32_System_RemoteDesktop\":[\"Win32_System\"],\"Win32_System_RemoteManagement\":[\"Win32_System\"],\"Win32_System_RestartManager\":[\"Win32_System\"],\"Win32_System_Restore\":[\"Win32_System\"],\"Win32_System_Rpc\":[\"Win32_System\"],\"Win32_System_Search\":[\"Win32_System\"],\"Win32_System_Search_Common\":[\"Win32_System_Search\"],\"Win32_System_SecurityCenter\":[\"Win32_System\"],\"Win32_System_ServerBackup\":[\"Win32_System\"],\"Win32_System_Services\":[\"Win32_System\"],\"Win32_System_SettingsManagementInfrastructure\":[\"Win32_System\"],\"Win32_System_SetupAndMigration\":[\"Win32_System\"],\"Win32_System_Shutdown\":[\"Win32_System\"],\"Win32_System_StationsAndDesktops\":[\"Win32_System\"],\"Win32_System_SubsystemForLinux\":[\"Win32_System\"],\"Win32_System_SystemInformation\":[\"Win32_System\"],\"Win32_System_SystemServices\":[\"Win32_System\"],\"Win32_System_TaskScheduler\":[\"Win32_System\"],\"Win32_System_Threading\":[\"Win32_System\"],\"Win32_System_Time\":[\"Win32_System\"],\"Win32_System_TpmBaseServices\":[\"Win32_System\"],\"Win32_System_UpdateAgent\":[\"Win32_System\"],\"Win32_System_UpdateAssessment\":[\"Win32_System\"],\"Win32_System_UserAccessLogging\":[\"Win32_System\"],\"Win32_System_VirtualDosMachines\":[\"Win32_System\"],\"Win32_System_WindowsProgramming\":[\"Win32_System\"],\"Win32_System_WindowsSync\":[\"Win32_System\"],\"Win32_System_Wmi\":[\"Win32_System\"],\"Win32_UI\":[\"Win32\"],\"Win32_UI_Accessibility\":[\"Win32_UI\"],\"Win32_UI_Animation\":[\"Win32_UI\"],\"Win32_UI_ColorSystem\":[\"Win32_UI\"],\"Win32_UI_Controls\":[\"Win32_UI\"],\"Win32_UI_Controls_Dialogs\":[\"Win32_UI_Controls\"],\"Win32_UI_Controls_RichEdit\":[\"Win32_UI_Controls\"],\"Win32_UI_HiDpi\":[\"Win32_UI\"],\"Win32_UI_Input\":[\"Win32_UI\"],\"Win32_UI_Input_Ime\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Ink\":[\"Win32_UI_Input\"],\"Win32_UI_Input_KeyboardAndMouse\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Pointer\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Radial\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Touch\":[\"Win32_UI_Input\"],\"Win32_UI_Input_XboxController\":[\"Win32_UI_Input\"],\"Win32_UI_InteractionContext\":[\"Win32_UI\"],\"Win32_UI_LegacyWindowsEnvironmentFeatures\":[\"Win32_UI\"],\"Win32_UI_Magnification\":[\"Win32_UI\"],\"Win32_UI_Notifications\":[\"Win32_UI\"],\"Win32_UI_Ribbon\":[\"Win32_UI\"],\"Win32_UI_Shell\":[\"Win32_UI\"],\"Win32_UI_Shell_Common\":[\"Win32_UI_Shell\"],\"Win32_UI_Shell_PropertiesSystem\":[\"Win32_UI_Shell\"],\"Win32_UI_TabletPC\":[\"Win32_UI\"],\"Win32_UI_TextServices\":[\"Win32_UI\"],\"Win32_UI_WindowsAndMessaging\":[\"Win32_UI\"],\"Win32_UI_Wpf\":[\"Win32_UI\"],\"Win32_Web\":[\"Win32\"],\"Win32_Web_InternetExplorer\":[\"Win32_Web\"],\"default\":[]}}", "windows-sys_0.52.0": "{\"dependencies\":[{\"name\":\"windows-targets\",\"req\":\"^0.52.0\"}],\"features\":{\"Wdk\":[],\"Wdk_Foundation\":[\"Wdk\"],\"Wdk_Graphics\":[\"Wdk\"],\"Wdk_Graphics_Direct3D\":[\"Wdk_Graphics\"],\"Wdk_Storage\":[\"Wdk\"],\"Wdk_Storage_FileSystem\":[\"Wdk_Storage\"],\"Wdk_Storage_FileSystem_Minifilters\":[\"Wdk_Storage_FileSystem\"],\"Wdk_System\":[\"Wdk\"],\"Wdk_System_IO\":[\"Wdk_System\"],\"Wdk_System_OfflineRegistry\":[\"Wdk_System\"],\"Wdk_System_Registry\":[\"Wdk_System\"],\"Wdk_System_SystemInformation\":[\"Wdk_System\"],\"Wdk_System_SystemServices\":[\"Wdk_System\"],\"Wdk_System_Threading\":[\"Wdk_System\"],\"Win32\":[],\"Win32_Data\":[\"Win32\"],\"Win32_Data_HtmlHelp\":[\"Win32_Data\"],\"Win32_Data_RightsManagement\":[\"Win32_Data\"],\"Win32_Devices\":[\"Win32\"],\"Win32_Devices_AllJoyn\":[\"Win32_Devices\"],\"Win32_Devices_BiometricFramework\":[\"Win32_Devices\"],\"Win32_Devices_Bluetooth\":[\"Win32_Devices\"],\"Win32_Devices_Communication\":[\"Win32_Devices\"],\"Win32_Devices_DeviceAndDriverInstallation\":[\"Win32_Devices\"],\"Win32_Devices_DeviceQuery\":[\"Win32_Devices\"],\"Win32_Devices_Display\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration_Pnp\":[\"Win32_Devices_Enumeration\"],\"Win32_Devices_Fax\":[\"Win32_Devices\"],\"Win32_Devices_HumanInterfaceDevice\":[\"Win32_Devices\"],\"Win32_Devices_PortableDevices\":[\"Win32_Devices\"],\"Win32_Devices_Properties\":[\"Win32_Devices\"],\"Win32_Devices_Pwm\":[\"Win32_Devices\"],\"Win32_Devices_Sensors\":[\"Win32_Devices\"],\"Win32_Devices_SerialCommunication\":[\"Win32_Devices\"],\"Win32_Devices_Tapi\":[\"Win32_Devices\"],\"Win32_Devices_Usb\":[\"Win32_Devices\"],\"Win32_Devices_WebServicesOnDevices\":[\"Win32_Devices\"],\"Win32_Foundation\":[\"Win32\"],\"Win32_Gaming\":[\"Win32\"],\"Win32_Globalization\":[\"Win32\"],\"Win32_Graphics\":[\"Win32\"],\"Win32_Graphics_Dwm\":[\"Win32_Graphics\"],\"Win32_Graphics_Gdi\":[\"Win32_Graphics\"],\"Win32_Graphics_GdiPlus\":[\"Win32_Graphics\"],\"Win32_Graphics_Hlsl\":[\"Win32_Graphics\"],\"Win32_Graphics_OpenGL\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing_PrintTicket\":[\"Win32_Graphics_Printing\"],\"Win32_Management\":[\"Win32\"],\"Win32_Management_MobileDeviceManagementRegistration\":[\"Win32_Management\"],\"Win32_Media\":[\"Win32\"],\"Win32_Media_Audio\":[\"Win32_Media\"],\"Win32_Media_DxMediaObjects\":[\"Win32_Media\"],\"Win32_Media_KernelStreaming\":[\"Win32_Media\"],\"Win32_Media_Multimedia\":[\"Win32_Media\"],\"Win32_Media_Streaming\":[\"Win32_Media\"],\"Win32_Media_WindowsMediaFormat\":[\"Win32_Media\"],\"Win32_NetworkManagement\":[\"Win32\"],\"Win32_NetworkManagement_Dhcp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Dns\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_InternetConnectionWizard\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_IpHelper\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Multicast\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Ndis\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetBios\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetManagement\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetShell\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetworkDiagnosticsFramework\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_P2P\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_QoS\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Rras\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Snmp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WNet\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WebDav\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WiFi\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsConnectionManager\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFilteringPlatform\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFirewall\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsNetworkVirtualization\":[\"Win32_NetworkManagement\"],\"Win32_Networking\":[\"Win32\"],\"Win32_Networking_ActiveDirectory\":[\"Win32_Networking\"],\"Win32_Networking_Clustering\":[\"Win32_Networking\"],\"Win32_Networking_HttpServer\":[\"Win32_Networking\"],\"Win32_Networking_Ldap\":[\"Win32_Networking\"],\"Win32_Networking_WebSocket\":[\"Win32_Networking\"],\"Win32_Networking_WinHttp\":[\"Win32_Networking\"],\"Win32_Networking_WinInet\":[\"Win32_Networking\"],\"Win32_Networking_WinSock\":[\"Win32_Networking\"],\"Win32_Networking_WindowsWebServices\":[\"Win32_Networking\"],\"Win32_Security\":[\"Win32\"],\"Win32_Security_AppLocker\":[\"Win32_Security\"],\"Win32_Security_Authentication\":[\"Win32_Security\"],\"Win32_Security_Authentication_Identity\":[\"Win32_Security_Authentication\"],\"Win32_Security_Authorization\":[\"Win32_Security\"],\"Win32_Security_Credentials\":[\"Win32_Security\"],\"Win32_Security_Cryptography\":[\"Win32_Security\"],\"Win32_Security_Cryptography_Catalog\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Certificates\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Sip\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_UI\":[\"Win32_Security_Cryptography\"],\"Win32_Security_DiagnosticDataQuery\":[\"Win32_Security\"],\"Win32_Security_DirectoryServices\":[\"Win32_Security\"],\"Win32_Security_EnterpriseData\":[\"Win32_Security\"],\"Win32_Security_ExtensibleAuthenticationProtocol\":[\"Win32_Security\"],\"Win32_Security_Isolation\":[\"Win32_Security\"],\"Win32_Security_LicenseProtection\":[\"Win32_Security\"],\"Win32_Security_NetworkAccessProtection\":[\"Win32_Security\"],\"Win32_Security_WinTrust\":[\"Win32_Security\"],\"Win32_Security_WinWlx\":[\"Win32_Security\"],\"Win32_Storage\":[\"Win32\"],\"Win32_Storage_Cabinets\":[\"Win32_Storage\"],\"Win32_Storage_CloudFilters\":[\"Win32_Storage\"],\"Win32_Storage_Compression\":[\"Win32_Storage\"],\"Win32_Storage_DistributedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_FileHistory\":[\"Win32_Storage\"],\"Win32_Storage_FileSystem\":[\"Win32_Storage\"],\"Win32_Storage_Imapi\":[\"Win32_Storage\"],\"Win32_Storage_IndexServer\":[\"Win32_Storage\"],\"Win32_Storage_InstallableFileSystems\":[\"Win32_Storage\"],\"Win32_Storage_IscsiDisc\":[\"Win32_Storage\"],\"Win32_Storage_Jet\":[\"Win32_Storage\"],\"Win32_Storage_Nvme\":[\"Win32_Storage\"],\"Win32_Storage_OfflineFiles\":[\"Win32_Storage\"],\"Win32_Storage_OperationRecorder\":[\"Win32_Storage\"],\"Win32_Storage_Packaging\":[\"Win32_Storage\"],\"Win32_Storage_Packaging_Appx\":[\"Win32_Storage_Packaging\"],\"Win32_Storage_ProjectedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_StructuredStorage\":[\"Win32_Storage\"],\"Win32_Storage_Vhd\":[\"Win32_Storage\"],\"Win32_Storage_Xps\":[\"Win32_Storage\"],\"Win32_System\":[\"Win32\"],\"Win32_System_AddressBook\":[\"Win32_System\"],\"Win32_System_Antimalware\":[\"Win32_System\"],\"Win32_System_ApplicationInstallationAndServicing\":[\"Win32_System\"],\"Win32_System_ApplicationVerifier\":[\"Win32_System\"],\"Win32_System_ClrHosting\":[\"Win32_System\"],\"Win32_System_Com\":[\"Win32_System\"],\"Win32_System_Com_Marshal\":[\"Win32_System_Com\"],\"Win32_System_Com_StructuredStorage\":[\"Win32_System_Com\"],\"Win32_System_Com_Urlmon\":[\"Win32_System_Com\"],\"Win32_System_ComponentServices\":[\"Win32_System\"],\"Win32_System_Console\":[\"Win32_System\"],\"Win32_System_CorrelationVector\":[\"Win32_System\"],\"Win32_System_DataExchange\":[\"Win32_System\"],\"Win32_System_DeploymentServices\":[\"Win32_System\"],\"Win32_System_DeveloperLicensing\":[\"Win32_System\"],\"Win32_System_Diagnostics\":[\"Win32_System\"],\"Win32_System_Diagnostics_Ceip\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug_Extensions\":[\"Win32_System_Diagnostics_Debug\"],\"Win32_System_Diagnostics_Etw\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ProcessSnapshotting\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ToolHelp\":[\"Win32_System_Diagnostics\"],\"Win32_System_DistributedTransactionCoordinator\":[\"Win32_System\"],\"Win32_System_Environment\":[\"Win32_System\"],\"Win32_System_ErrorReporting\":[\"Win32_System\"],\"Win32_System_EventCollector\":[\"Win32_System\"],\"Win32_System_EventLog\":[\"Win32_System\"],\"Win32_System_EventNotificationService\":[\"Win32_System\"],\"Win32_System_GroupPolicy\":[\"Win32_System\"],\"Win32_System_HostCompute\":[\"Win32_System\"],\"Win32_System_HostComputeNetwork\":[\"Win32_System\"],\"Win32_System_HostComputeSystem\":[\"Win32_System\"],\"Win32_System_Hypervisor\":[\"Win32_System\"],\"Win32_System_IO\":[\"Win32_System\"],\"Win32_System_Iis\":[\"Win32_System\"],\"Win32_System_Ioctl\":[\"Win32_System\"],\"Win32_System_JobObjects\":[\"Win32_System\"],\"Win32_System_Js\":[\"Win32_System\"],\"Win32_System_Kernel\":[\"Win32_System\"],\"Win32_System_LibraryLoader\":[\"Win32_System\"],\"Win32_System_Mailslots\":[\"Win32_System\"],\"Win32_System_Mapi\":[\"Win32_System\"],\"Win32_System_Memory\":[\"Win32_System\"],\"Win32_System_Memory_NonVolatile\":[\"Win32_System_Memory\"],\"Win32_System_MessageQueuing\":[\"Win32_System\"],\"Win32_System_MixedReality\":[\"Win32_System\"],\"Win32_System_Ole\":[\"Win32_System\"],\"Win32_System_PasswordManagement\":[\"Win32_System\"],\"Win32_System_Performance\":[\"Win32_System\"],\"Win32_System_Performance_HardwareCounterProfiling\":[\"Win32_System_Performance\"],\"Win32_System_Pipes\":[\"Win32_System\"],\"Win32_System_Power\":[\"Win32_System\"],\"Win32_System_ProcessStatus\":[\"Win32_System\"],\"Win32_System_Recovery\":[\"Win32_System\"],\"Win32_System_Registry\":[\"Win32_System\"],\"Win32_System_RemoteDesktop\":[\"Win32_System\"],\"Win32_System_RemoteManagement\":[\"Win32_System\"],\"Win32_System_RestartManager\":[\"Win32_System\"],\"Win32_System_Restore\":[\"Win32_System\"],\"Win32_System_Rpc\":[\"Win32_System\"],\"Win32_System_Search\":[\"Win32_System\"],\"Win32_System_Search_Common\":[\"Win32_System_Search\"],\"Win32_System_SecurityCenter\":[\"Win32_System\"],\"Win32_System_Services\":[\"Win32_System\"],\"Win32_System_SetupAndMigration\":[\"Win32_System\"],\"Win32_System_Shutdown\":[\"Win32_System\"],\"Win32_System_StationsAndDesktops\":[\"Win32_System\"],\"Win32_System_SubsystemForLinux\":[\"Win32_System\"],\"Win32_System_SystemInformation\":[\"Win32_System\"],\"Win32_System_SystemServices\":[\"Win32_System\"],\"Win32_System_Threading\":[\"Win32_System\"],\"Win32_System_Time\":[\"Win32_System\"],\"Win32_System_TpmBaseServices\":[\"Win32_System\"],\"Win32_System_UserAccessLogging\":[\"Win32_System\"],\"Win32_System_Variant\":[\"Win32_System\"],\"Win32_System_VirtualDosMachines\":[\"Win32_System\"],\"Win32_System_WindowsProgramming\":[\"Win32_System\"],\"Win32_System_Wmi\":[\"Win32_System\"],\"Win32_UI\":[\"Win32\"],\"Win32_UI_Accessibility\":[\"Win32_UI\"],\"Win32_UI_ColorSystem\":[\"Win32_UI\"],\"Win32_UI_Controls\":[\"Win32_UI\"],\"Win32_UI_Controls_Dialogs\":[\"Win32_UI_Controls\"],\"Win32_UI_HiDpi\":[\"Win32_UI\"],\"Win32_UI_Input\":[\"Win32_UI\"],\"Win32_UI_Input_Ime\":[\"Win32_UI_Input\"],\"Win32_UI_Input_KeyboardAndMouse\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Pointer\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Touch\":[\"Win32_UI_Input\"],\"Win32_UI_Input_XboxController\":[\"Win32_UI_Input\"],\"Win32_UI_InteractionContext\":[\"Win32_UI\"],\"Win32_UI_Magnification\":[\"Win32_UI\"],\"Win32_UI_Shell\":[\"Win32_UI\"],\"Win32_UI_Shell_PropertiesSystem\":[\"Win32_UI_Shell\"],\"Win32_UI_TabletPC\":[\"Win32_UI\"],\"Win32_UI_TextServices\":[\"Win32_UI\"],\"Win32_UI_WindowsAndMessaging\":[\"Win32_UI\"],\"Win32_Web\":[\"Win32\"],\"Win32_Web_InternetExplorer\":[\"Win32_Web\"],\"default\":[],\"docs\":[]}}", "windows-sys_0.59.0": "{\"dependencies\":[{\"name\":\"windows-targets\",\"req\":\"^0.52.6\"}],\"features\":{\"Wdk\":[\"Win32_Foundation\"],\"Wdk_Devices\":[\"Wdk\"],\"Wdk_Devices_Bluetooth\":[\"Wdk_Devices\"],\"Wdk_Devices_HumanInterfaceDevice\":[\"Wdk_Devices\"],\"Wdk_Foundation\":[\"Wdk\"],\"Wdk_Graphics\":[\"Wdk\"],\"Wdk_Graphics_Direct3D\":[\"Wdk_Graphics\"],\"Wdk_NetworkManagement\":[\"Wdk\"],\"Wdk_NetworkManagement_Ndis\":[\"Wdk_NetworkManagement\"],\"Wdk_NetworkManagement_WindowsFilteringPlatform\":[\"Wdk_NetworkManagement\"],\"Wdk_Storage\":[\"Wdk\"],\"Wdk_Storage_FileSystem\":[\"Wdk_Storage\"],\"Wdk_Storage_FileSystem_Minifilters\":[\"Wdk_Storage_FileSystem\"],\"Wdk_System\":[\"Wdk\"],\"Wdk_System_IO\":[\"Wdk_System\"],\"Wdk_System_Memory\":[\"Wdk_System\"],\"Wdk_System_OfflineRegistry\":[\"Wdk_System\"],\"Wdk_System_Registry\":[\"Wdk_System\"],\"Wdk_System_SystemInformation\":[\"Wdk_System\"],\"Wdk_System_SystemServices\":[\"Wdk_System\"],\"Wdk_System_Threading\":[\"Wdk_System\"],\"Win32\":[\"Win32_Foundation\"],\"Win32_Data\":[\"Win32\"],\"Win32_Data_HtmlHelp\":[\"Win32_Data\"],\"Win32_Data_RightsManagement\":[\"Win32_Data\"],\"Win32_Devices\":[\"Win32\"],\"Win32_Devices_AllJoyn\":[\"Win32_Devices\"],\"Win32_Devices_BiometricFramework\":[\"Win32_Devices\"],\"Win32_Devices_Bluetooth\":[\"Win32_Devices\"],\"Win32_Devices_Communication\":[\"Win32_Devices\"],\"Win32_Devices_DeviceAndDriverInstallation\":[\"Win32_Devices\"],\"Win32_Devices_DeviceQuery\":[\"Win32_Devices\"],\"Win32_Devices_Display\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration_Pnp\":[\"Win32_Devices_Enumeration\"],\"Win32_Devices_Fax\":[\"Win32_Devices\"],\"Win32_Devices_HumanInterfaceDevice\":[\"Win32_Devices\"],\"Win32_Devices_PortableDevices\":[\"Win32_Devices\"],\"Win32_Devices_Properties\":[\"Win32_Devices\"],\"Win32_Devices_Pwm\":[\"Win32_Devices\"],\"Win32_Devices_Sensors\":[\"Win32_Devices\"],\"Win32_Devices_SerialCommunication\":[\"Win32_Devices\"],\"Win32_Devices_Tapi\":[\"Win32_Devices\"],\"Win32_Devices_Usb\":[\"Win32_Devices\"],\"Win32_Devices_WebServicesOnDevices\":[\"Win32_Devices\"],\"Win32_Foundation\":[\"Win32\"],\"Win32_Gaming\":[\"Win32\"],\"Win32_Globalization\":[\"Win32\"],\"Win32_Graphics\":[\"Win32\"],\"Win32_Graphics_Dwm\":[\"Win32_Graphics\"],\"Win32_Graphics_Gdi\":[\"Win32_Graphics\"],\"Win32_Graphics_GdiPlus\":[\"Win32_Graphics\"],\"Win32_Graphics_Hlsl\":[\"Win32_Graphics\"],\"Win32_Graphics_OpenGL\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing_PrintTicket\":[\"Win32_Graphics_Printing\"],\"Win32_Management\":[\"Win32\"],\"Win32_Management_MobileDeviceManagementRegistration\":[\"Win32_Management\"],\"Win32_Media\":[\"Win32\"],\"Win32_Media_Audio\":[\"Win32_Media\"],\"Win32_Media_DxMediaObjects\":[\"Win32_Media\"],\"Win32_Media_KernelStreaming\":[\"Win32_Media\"],\"Win32_Media_Multimedia\":[\"Win32_Media\"],\"Win32_Media_Streaming\":[\"Win32_Media\"],\"Win32_Media_WindowsMediaFormat\":[\"Win32_Media\"],\"Win32_NetworkManagement\":[\"Win32\"],\"Win32_NetworkManagement_Dhcp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Dns\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_InternetConnectionWizard\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_IpHelper\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Multicast\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Ndis\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetBios\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetManagement\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetShell\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetworkDiagnosticsFramework\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_P2P\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_QoS\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Rras\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Snmp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WNet\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WebDav\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WiFi\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsConnectionManager\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFilteringPlatform\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFirewall\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsNetworkVirtualization\":[\"Win32_NetworkManagement\"],\"Win32_Networking\":[\"Win32\"],\"Win32_Networking_ActiveDirectory\":[\"Win32_Networking\"],\"Win32_Networking_Clustering\":[\"Win32_Networking\"],\"Win32_Networking_HttpServer\":[\"Win32_Networking\"],\"Win32_Networking_Ldap\":[\"Win32_Networking\"],\"Win32_Networking_WebSocket\":[\"Win32_Networking\"],\"Win32_Networking_WinHttp\":[\"Win32_Networking\"],\"Win32_Networking_WinInet\":[\"Win32_Networking\"],\"Win32_Networking_WinSock\":[\"Win32_Networking\"],\"Win32_Networking_WindowsWebServices\":[\"Win32_Networking\"],\"Win32_Security\":[\"Win32\"],\"Win32_Security_AppLocker\":[\"Win32_Security\"],\"Win32_Security_Authentication\":[\"Win32_Security\"],\"Win32_Security_Authentication_Identity\":[\"Win32_Security_Authentication\"],\"Win32_Security_Authorization\":[\"Win32_Security\"],\"Win32_Security_Credentials\":[\"Win32_Security\"],\"Win32_Security_Cryptography\":[\"Win32_Security\"],\"Win32_Security_Cryptography_Catalog\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Certificates\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Sip\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_UI\":[\"Win32_Security_Cryptography\"],\"Win32_Security_DiagnosticDataQuery\":[\"Win32_Security\"],\"Win32_Security_DirectoryServices\":[\"Win32_Security\"],\"Win32_Security_EnterpriseData\":[\"Win32_Security\"],\"Win32_Security_ExtensibleAuthenticationProtocol\":[\"Win32_Security\"],\"Win32_Security_Isolation\":[\"Win32_Security\"],\"Win32_Security_LicenseProtection\":[\"Win32_Security\"],\"Win32_Security_NetworkAccessProtection\":[\"Win32_Security\"],\"Win32_Security_WinTrust\":[\"Win32_Security\"],\"Win32_Security_WinWlx\":[\"Win32_Security\"],\"Win32_Storage\":[\"Win32\"],\"Win32_Storage_Cabinets\":[\"Win32_Storage\"],\"Win32_Storage_CloudFilters\":[\"Win32_Storage\"],\"Win32_Storage_Compression\":[\"Win32_Storage\"],\"Win32_Storage_DistributedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_FileHistory\":[\"Win32_Storage\"],\"Win32_Storage_FileSystem\":[\"Win32_Storage\"],\"Win32_Storage_Imapi\":[\"Win32_Storage\"],\"Win32_Storage_IndexServer\":[\"Win32_Storage\"],\"Win32_Storage_InstallableFileSystems\":[\"Win32_Storage\"],\"Win32_Storage_IscsiDisc\":[\"Win32_Storage\"],\"Win32_Storage_Jet\":[\"Win32_Storage\"],\"Win32_Storage_Nvme\":[\"Win32_Storage\"],\"Win32_Storage_OfflineFiles\":[\"Win32_Storage\"],\"Win32_Storage_OperationRecorder\":[\"Win32_Storage\"],\"Win32_Storage_Packaging\":[\"Win32_Storage\"],\"Win32_Storage_Packaging_Appx\":[\"Win32_Storage_Packaging\"],\"Win32_Storage_ProjectedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_StructuredStorage\":[\"Win32_Storage\"],\"Win32_Storage_Vhd\":[\"Win32_Storage\"],\"Win32_Storage_Xps\":[\"Win32_Storage\"],\"Win32_System\":[\"Win32\"],\"Win32_System_AddressBook\":[\"Win32_System\"],\"Win32_System_Antimalware\":[\"Win32_System\"],\"Win32_System_ApplicationInstallationAndServicing\":[\"Win32_System\"],\"Win32_System_ApplicationVerifier\":[\"Win32_System\"],\"Win32_System_ClrHosting\":[\"Win32_System\"],\"Win32_System_Com\":[\"Win32_System\"],\"Win32_System_Com_Marshal\":[\"Win32_System_Com\"],\"Win32_System_Com_StructuredStorage\":[\"Win32_System_Com\"],\"Win32_System_Com_Urlmon\":[\"Win32_System_Com\"],\"Win32_System_ComponentServices\":[\"Win32_System\"],\"Win32_System_Console\":[\"Win32_System\"],\"Win32_System_CorrelationVector\":[\"Win32_System\"],\"Win32_System_DataExchange\":[\"Win32_System\"],\"Win32_System_DeploymentServices\":[\"Win32_System\"],\"Win32_System_DeveloperLicensing\":[\"Win32_System\"],\"Win32_System_Diagnostics\":[\"Win32_System\"],\"Win32_System_Diagnostics_Ceip\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug_Extensions\":[\"Win32_System_Diagnostics_Debug\"],\"Win32_System_Diagnostics_Etw\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ProcessSnapshotting\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ToolHelp\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_TraceLogging\":[\"Win32_System_Diagnostics\"],\"Win32_System_DistributedTransactionCoordinator\":[\"Win32_System\"],\"Win32_System_Environment\":[\"Win32_System\"],\"Win32_System_ErrorReporting\":[\"Win32_System\"],\"Win32_System_EventCollector\":[\"Win32_System\"],\"Win32_System_EventLog\":[\"Win32_System\"],\"Win32_System_EventNotificationService\":[\"Win32_System\"],\"Win32_System_GroupPolicy\":[\"Win32_System\"],\"Win32_System_HostCompute\":[\"Win32_System\"],\"Win32_System_HostComputeNetwork\":[\"Win32_System\"],\"Win32_System_HostComputeSystem\":[\"Win32_System\"],\"Win32_System_Hypervisor\":[\"Win32_System\"],\"Win32_System_IO\":[\"Win32_System\"],\"Win32_System_Iis\":[\"Win32_System\"],\"Win32_System_Ioctl\":[\"Win32_System\"],\"Win32_System_JobObjects\":[\"Win32_System\"],\"Win32_System_Js\":[\"Win32_System\"],\"Win32_System_Kernel\":[\"Win32_System\"],\"Win32_System_LibraryLoader\":[\"Win32_System\"],\"Win32_System_Mailslots\":[\"Win32_System\"],\"Win32_System_Mapi\":[\"Win32_System\"],\"Win32_System_Memory\":[\"Win32_System\"],\"Win32_System_Memory_NonVolatile\":[\"Win32_System_Memory\"],\"Win32_System_MessageQueuing\":[\"Win32_System\"],\"Win32_System_MixedReality\":[\"Win32_System\"],\"Win32_System_Ole\":[\"Win32_System\"],\"Win32_System_PasswordManagement\":[\"Win32_System\"],\"Win32_System_Performance\":[\"Win32_System\"],\"Win32_System_Performance_HardwareCounterProfiling\":[\"Win32_System_Performance\"],\"Win32_System_Pipes\":[\"Win32_System\"],\"Win32_System_Power\":[\"Win32_System\"],\"Win32_System_ProcessStatus\":[\"Win32_System\"],\"Win32_System_Recovery\":[\"Win32_System\"],\"Win32_System_Registry\":[\"Win32_System\"],\"Win32_System_RemoteDesktop\":[\"Win32_System\"],\"Win32_System_RemoteManagement\":[\"Win32_System\"],\"Win32_System_RestartManager\":[\"Win32_System\"],\"Win32_System_Restore\":[\"Win32_System\"],\"Win32_System_Rpc\":[\"Win32_System\"],\"Win32_System_Search\":[\"Win32_System\"],\"Win32_System_Search_Common\":[\"Win32_System_Search\"],\"Win32_System_SecurityCenter\":[\"Win32_System\"],\"Win32_System_Services\":[\"Win32_System\"],\"Win32_System_SetupAndMigration\":[\"Win32_System\"],\"Win32_System_Shutdown\":[\"Win32_System\"],\"Win32_System_StationsAndDesktops\":[\"Win32_System\"],\"Win32_System_SubsystemForLinux\":[\"Win32_System\"],\"Win32_System_SystemInformation\":[\"Win32_System\"],\"Win32_System_SystemServices\":[\"Win32_System\"],\"Win32_System_Threading\":[\"Win32_System\"],\"Win32_System_Time\":[\"Win32_System\"],\"Win32_System_TpmBaseServices\":[\"Win32_System\"],\"Win32_System_UserAccessLogging\":[\"Win32_System\"],\"Win32_System_Variant\":[\"Win32_System\"],\"Win32_System_VirtualDosMachines\":[\"Win32_System\"],\"Win32_System_WindowsProgramming\":[\"Win32_System\"],\"Win32_System_Wmi\":[\"Win32_System\"],\"Win32_UI\":[\"Win32\"],\"Win32_UI_Accessibility\":[\"Win32_UI\"],\"Win32_UI_ColorSystem\":[\"Win32_UI\"],\"Win32_UI_Controls\":[\"Win32_UI\"],\"Win32_UI_Controls_Dialogs\":[\"Win32_UI_Controls\"],\"Win32_UI_HiDpi\":[\"Win32_UI\"],\"Win32_UI_Input\":[\"Win32_UI\"],\"Win32_UI_Input_Ime\":[\"Win32_UI_Input\"],\"Win32_UI_Input_KeyboardAndMouse\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Pointer\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Touch\":[\"Win32_UI_Input\"],\"Win32_UI_Input_XboxController\":[\"Win32_UI_Input\"],\"Win32_UI_InteractionContext\":[\"Win32_UI\"],\"Win32_UI_Magnification\":[\"Win32_UI\"],\"Win32_UI_Shell\":[\"Win32_UI\"],\"Win32_UI_Shell_Common\":[\"Win32_UI_Shell\"],\"Win32_UI_Shell_PropertiesSystem\":[\"Win32_UI_Shell\"],\"Win32_UI_TabletPC\":[\"Win32_UI\"],\"Win32_UI_TextServices\":[\"Win32_UI\"],\"Win32_UI_WindowsAndMessaging\":[\"Win32_UI\"],\"Win32_Web\":[\"Win32\"],\"Win32_Web_InternetExplorer\":[\"Win32_Web\"],\"default\":[],\"docs\":[]}}", "windows-sys_0.60.2": "{\"dependencies\":[{\"default_features\":false,\"name\":\"windows-targets\",\"req\":\"^0.53.2\"}],\"features\":{\"Wdk\":[\"Win32_Foundation\"],\"Wdk_Devices\":[\"Wdk\"],\"Wdk_Devices_Bluetooth\":[\"Wdk_Devices\"],\"Wdk_Devices_HumanInterfaceDevice\":[\"Wdk_Devices\"],\"Wdk_Foundation\":[\"Wdk\"],\"Wdk_Graphics\":[\"Wdk\"],\"Wdk_Graphics_Direct3D\":[\"Wdk_Graphics\"],\"Wdk_NetworkManagement\":[\"Wdk\"],\"Wdk_NetworkManagement_Ndis\":[\"Wdk_NetworkManagement\"],\"Wdk_NetworkManagement_WindowsFilteringPlatform\":[\"Wdk_NetworkManagement\"],\"Wdk_Storage\":[\"Wdk\"],\"Wdk_Storage_FileSystem\":[\"Wdk_Storage\"],\"Wdk_Storage_FileSystem_Minifilters\":[\"Wdk_Storage_FileSystem\"],\"Wdk_System\":[\"Wdk\"],\"Wdk_System_IO\":[\"Wdk_System\"],\"Wdk_System_Memory\":[\"Wdk_System\"],\"Wdk_System_OfflineRegistry\":[\"Wdk_System\"],\"Wdk_System_Registry\":[\"Wdk_System\"],\"Wdk_System_SystemInformation\":[\"Wdk_System\"],\"Wdk_System_SystemServices\":[\"Wdk_System\"],\"Wdk_System_Threading\":[\"Wdk_System\"],\"Win32\":[\"Win32_Foundation\"],\"Win32_Data\":[\"Win32\"],\"Win32_Data_HtmlHelp\":[\"Win32_Data\"],\"Win32_Data_RightsManagement\":[\"Win32_Data\"],\"Win32_Devices\":[\"Win32\"],\"Win32_Devices_AllJoyn\":[\"Win32_Devices\"],\"Win32_Devices_Beep\":[\"Win32_Devices\"],\"Win32_Devices_BiometricFramework\":[\"Win32_Devices\"],\"Win32_Devices_Bluetooth\":[\"Win32_Devices\"],\"Win32_Devices_Cdrom\":[\"Win32_Devices\"],\"Win32_Devices_Communication\":[\"Win32_Devices\"],\"Win32_Devices_DeviceAndDriverInstallation\":[\"Win32_Devices\"],\"Win32_Devices_DeviceQuery\":[\"Win32_Devices\"],\"Win32_Devices_Display\":[\"Win32_Devices\"],\"Win32_Devices_Dvd\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration\":[\"Win32_Devices\"],\"Win32_Devices_Enumeration_Pnp\":[\"Win32_Devices_Enumeration\"],\"Win32_Devices_Fax\":[\"Win32_Devices\"],\"Win32_Devices_HumanInterfaceDevice\":[\"Win32_Devices\"],\"Win32_Devices_Nfc\":[\"Win32_Devices\"],\"Win32_Devices_Nfp\":[\"Win32_Devices\"],\"Win32_Devices_PortableDevices\":[\"Win32_Devices\"],\"Win32_Devices_Properties\":[\"Win32_Devices\"],\"Win32_Devices_Pwm\":[\"Win32_Devices\"],\"Win32_Devices_Sensors\":[\"Win32_Devices\"],\"Win32_Devices_SerialCommunication\":[\"Win32_Devices\"],\"Win32_Devices_Tapi\":[\"Win32_Devices\"],\"Win32_Devices_Usb\":[\"Win32_Devices\"],\"Win32_Devices_WebServicesOnDevices\":[\"Win32_Devices\"],\"Win32_Foundation\":[\"Win32\"],\"Win32_Gaming\":[\"Win32\"],\"Win32_Globalization\":[\"Win32\"],\"Win32_Graphics\":[\"Win32\"],\"Win32_Graphics_Dwm\":[\"Win32_Graphics\"],\"Win32_Graphics_Gdi\":[\"Win32_Graphics\"],\"Win32_Graphics_GdiPlus\":[\"Win32_Graphics\"],\"Win32_Graphics_Hlsl\":[\"Win32_Graphics\"],\"Win32_Graphics_OpenGL\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing\":[\"Win32_Graphics\"],\"Win32_Graphics_Printing_PrintTicket\":[\"Win32_Graphics_Printing\"],\"Win32_Management\":[\"Win32\"],\"Win32_Management_MobileDeviceManagementRegistration\":[\"Win32_Management\"],\"Win32_Media\":[\"Win32\"],\"Win32_Media_Audio\":[\"Win32_Media\"],\"Win32_Media_DxMediaObjects\":[\"Win32_Media\"],\"Win32_Media_KernelStreaming\":[\"Win32_Media\"],\"Win32_Media_Multimedia\":[\"Win32_Media\"],\"Win32_Media_Streaming\":[\"Win32_Media\"],\"Win32_Media_WindowsMediaFormat\":[\"Win32_Media\"],\"Win32_NetworkManagement\":[\"Win32\"],\"Win32_NetworkManagement_Dhcp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Dns\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_InternetConnectionWizard\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_IpHelper\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Multicast\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Ndis\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetBios\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetManagement\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetShell\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_NetworkDiagnosticsFramework\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_P2P\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_QoS\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Rras\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_Snmp\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WNet\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WebDav\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WiFi\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsConnectionManager\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFilteringPlatform\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsFirewall\":[\"Win32_NetworkManagement\"],\"Win32_NetworkManagement_WindowsNetworkVirtualization\":[\"Win32_NetworkManagement\"],\"Win32_Networking\":[\"Win32\"],\"Win32_Networking_ActiveDirectory\":[\"Win32_Networking\"],\"Win32_Networking_Clustering\":[\"Win32_Networking\"],\"Win32_Networking_HttpServer\":[\"Win32_Networking\"],\"Win32_Networking_Ldap\":[\"Win32_Networking\"],\"Win32_Networking_WebSocket\":[\"Win32_Networking\"],\"Win32_Networking_WinHttp\":[\"Win32_Networking\"],\"Win32_Networking_WinInet\":[\"Win32_Networking\"],\"Win32_Networking_WinSock\":[\"Win32_Networking\"],\"Win32_Networking_WindowsWebServices\":[\"Win32_Networking\"],\"Win32_Security\":[\"Win32\"],\"Win32_Security_AppLocker\":[\"Win32_Security\"],\"Win32_Security_Authentication\":[\"Win32_Security\"],\"Win32_Security_Authentication_Identity\":[\"Win32_Security_Authentication\"],\"Win32_Security_Authorization\":[\"Win32_Security\"],\"Win32_Security_Credentials\":[\"Win32_Security\"],\"Win32_Security_Cryptography\":[\"Win32_Security\"],\"Win32_Security_Cryptography_Catalog\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Certificates\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_Sip\":[\"Win32_Security_Cryptography\"],\"Win32_Security_Cryptography_UI\":[\"Win32_Security_Cryptography\"],\"Win32_Security_DiagnosticDataQuery\":[\"Win32_Security\"],\"Win32_Security_DirectoryServices\":[\"Win32_Security\"],\"Win32_Security_EnterpriseData\":[\"Win32_Security\"],\"Win32_Security_ExtensibleAuthenticationProtocol\":[\"Win32_Security\"],\"Win32_Security_Isolation\":[\"Win32_Security\"],\"Win32_Security_LicenseProtection\":[\"Win32_Security\"],\"Win32_Security_NetworkAccessProtection\":[\"Win32_Security\"],\"Win32_Security_WinTrust\":[\"Win32_Security\"],\"Win32_Security_WinWlx\":[\"Win32_Security\"],\"Win32_Storage\":[\"Win32\"],\"Win32_Storage_Cabinets\":[\"Win32_Storage\"],\"Win32_Storage_CloudFilters\":[\"Win32_Storage\"],\"Win32_Storage_Compression\":[\"Win32_Storage\"],\"Win32_Storage_DistributedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_FileHistory\":[\"Win32_Storage\"],\"Win32_Storage_FileSystem\":[\"Win32_Storage\"],\"Win32_Storage_Imapi\":[\"Win32_Storage\"],\"Win32_Storage_IndexServer\":[\"Win32_Storage\"],\"Win32_Storage_InstallableFileSystems\":[\"Win32_Storage\"],\"Win32_Storage_IscsiDisc\":[\"Win32_Storage\"],\"Win32_Storage_Jet\":[\"Win32_Storage\"],\"Win32_Storage_Nvme\":[\"Win32_Storage\"],\"Win32_Storage_OfflineFiles\":[\"Win32_Storage\"],\"Win32_Storage_OperationRecorder\":[\"Win32_Storage\"],\"Win32_Storage_Packaging\":[\"Win32_Storage\"],\"Win32_Storage_Packaging_Appx\":[\"Win32_Storage_Packaging\"],\"Win32_Storage_ProjectedFileSystem\":[\"Win32_Storage\"],\"Win32_Storage_StructuredStorage\":[\"Win32_Storage\"],\"Win32_Storage_Vhd\":[\"Win32_Storage\"],\"Win32_Storage_Xps\":[\"Win32_Storage\"],\"Win32_System\":[\"Win32\"],\"Win32_System_AddressBook\":[\"Win32_System\"],\"Win32_System_Antimalware\":[\"Win32_System\"],\"Win32_System_ApplicationInstallationAndServicing\":[\"Win32_System\"],\"Win32_System_ApplicationVerifier\":[\"Win32_System\"],\"Win32_System_ClrHosting\":[\"Win32_System\"],\"Win32_System_Com\":[\"Win32_System\"],\"Win32_System_Com_Marshal\":[\"Win32_System_Com\"],\"Win32_System_Com_StructuredStorage\":[\"Win32_System_Com\"],\"Win32_System_Com_Urlmon\":[\"Win32_System_Com\"],\"Win32_System_ComponentServices\":[\"Win32_System\"],\"Win32_System_Console\":[\"Win32_System\"],\"Win32_System_CorrelationVector\":[\"Win32_System\"],\"Win32_System_DataExchange\":[\"Win32_System\"],\"Win32_System_DeploymentServices\":[\"Win32_System\"],\"Win32_System_DeveloperLicensing\":[\"Win32_System\"],\"Win32_System_Diagnostics\":[\"Win32_System\"],\"Win32_System_Diagnostics_Ceip\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_Debug_Extensions\":[\"Win32_System_Diagnostics_Debug\"],\"Win32_System_Diagnostics_Etw\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ProcessSnapshotting\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_ToolHelp\":[\"Win32_System_Diagnostics\"],\"Win32_System_Diagnostics_TraceLogging\":[\"Win32_System_Diagnostics\"],\"Win32_System_DistributedTransactionCoordinator\":[\"Win32_System\"],\"Win32_System_Environment\":[\"Win32_System\"],\"Win32_System_ErrorReporting\":[\"Win32_System\"],\"Win32_System_EventCollector\":[\"Win32_System\"],\"Win32_System_EventLog\":[\"Win32_System\"],\"Win32_System_EventNotificationService\":[\"Win32_System\"],\"Win32_System_GroupPolicy\":[\"Win32_System\"],\"Win32_System_HostCompute\":[\"Win32_System\"],\"Win32_System_HostComputeNetwork\":[\"Win32_System\"],\"Win32_System_HostComputeSystem\":[\"Win32_System\"],\"Win32_System_Hypervisor\":[\"Win32_System\"],\"Win32_System_IO\":[\"Win32_System\"],\"Win32_System_Iis\":[\"Win32_System\"],\"Win32_System_Ioctl\":[\"Win32_System\"],\"Win32_System_JobObjects\":[\"Win32_System\"],\"Win32_System_Js\":[\"Win32_System\"],\"Win32_System_Kernel\":[\"Win32_System\"],\"Win32_System_LibraryLoader\":[\"Win32_System\"],\"Win32_System_Mailslots\":[\"Win32_System\"],\"Win32_System_Mapi\":[\"Win32_System\"],\"Win32_System_Memory\":[\"Win32_System\"],\"Win32_System_Memory_NonVolatile\":[\"Win32_System_Memory\"],\"Win32_System_MessageQueuing\":[\"Win32_System\"],\"Win32_System_MixedReality\":[\"Win32_System\"],\"Win32_System_Ole\":[\"Win32_System\"],\"Win32_System_PasswordManagement\":[\"Win32_System\"],\"Win32_System_Performance\":[\"Win32_System\"],\"Win32_System_Performance_HardwareCounterProfiling\":[\"Win32_System_Performance\"],\"Win32_System_Pipes\":[\"Win32_System\"],\"Win32_System_Power\":[\"Win32_System\"],\"Win32_System_ProcessStatus\":[\"Win32_System\"],\"Win32_System_Recovery\":[\"Win32_System\"],\"Win32_System_Registry\":[\"Win32_System\"],\"Win32_System_RemoteDesktop\":[\"Win32_System\"],\"Win32_System_RemoteManagement\":[\"Win32_System\"],\"Win32_System_RestartManager\":[\"Win32_System\"],\"Win32_System_Restore\":[\"Win32_System\"],\"Win32_System_Rpc\":[\"Win32_System\"],\"Win32_System_Search\":[\"Win32_System\"],\"Win32_System_Search_Common\":[\"Win32_System_Search\"],\"Win32_System_SecurityCenter\":[\"Win32_System\"],\"Win32_System_Services\":[\"Win32_System\"],\"Win32_System_SetupAndMigration\":[\"Win32_System\"],\"Win32_System_Shutdown\":[\"Win32_System\"],\"Win32_System_StationsAndDesktops\":[\"Win32_System\"],\"Win32_System_SubsystemForLinux\":[\"Win32_System\"],\"Win32_System_SystemInformation\":[\"Win32_System\"],\"Win32_System_SystemServices\":[\"Win32_System\"],\"Win32_System_Threading\":[\"Win32_System\"],\"Win32_System_Time\":[\"Win32_System\"],\"Win32_System_TpmBaseServices\":[\"Win32_System\"],\"Win32_System_UserAccessLogging\":[\"Win32_System\"],\"Win32_System_Variant\":[\"Win32_System\"],\"Win32_System_VirtualDosMachines\":[\"Win32_System\"],\"Win32_System_WindowsProgramming\":[\"Win32_System\"],\"Win32_System_Wmi\":[\"Win32_System\"],\"Win32_UI\":[\"Win32\"],\"Win32_UI_Accessibility\":[\"Win32_UI\"],\"Win32_UI_ColorSystem\":[\"Win32_UI\"],\"Win32_UI_Controls\":[\"Win32_UI\"],\"Win32_UI_Controls_Dialogs\":[\"Win32_UI_Controls\"],\"Win32_UI_HiDpi\":[\"Win32_UI\"],\"Win32_UI_Input\":[\"Win32_UI\"],\"Win32_UI_Input_Ime\":[\"Win32_UI_Input\"],\"Win32_UI_Input_KeyboardAndMouse\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Pointer\":[\"Win32_UI_Input\"],\"Win32_UI_Input_Touch\":[\"Win32_UI_Input\"],\"Win32_UI_Input_XboxController\":[\"Win32_UI_Input\"],\"Win32_UI_InteractionContext\":[\"Win32_UI\"],\"Win32_UI_Magnification\":[\"Win32_UI\"],\"Win32_UI_Shell\":[\"Win32_UI\"],\"Win32_UI_Shell_Common\":[\"Win32_UI_Shell\"],\"Win32_UI_Shell_PropertiesSystem\":[\"Win32_UI_Shell\"],\"Win32_UI_TabletPC\":[\"Win32_UI\"],\"Win32_UI_TextServices\":[\"Win32_UI\"],\"Win32_UI_WindowsAndMessaging\":[\"Win32_UI\"],\"Win32_Web\":[\"Win32\"],\"Win32_Web_InternetExplorer\":[\"Win32_Web\"],\"default\":[],\"docs\":[]}}", @@ -1275,6 +1373,7 @@ "windows_x86_64_msvc_0.53.0": "{\"dependencies\":[],\"features\":{}}", "winnow_0.7.13": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"annotate-snippets\",\"req\":\"^0.11.3\"},{\"name\":\"anstream\",\"optional\":true,\"req\":\"^0.3.2\"},{\"name\":\"anstyle\",\"optional\":true,\"req\":\"^1.0.1\"},{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.86\"},{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.14\"},{\"kind\":\"dev\",\"name\":\"circular\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"name\":\"is_terminal_polyfill\",\"optional\":true,\"req\":\"^1.48.0\"},{\"kind\":\"dev\",\"name\":\"lexopt\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"name\":\"memchr\",\"optional\":true,\"req\":\"^2.5\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"rustc-hash\",\"req\":\"^1.1.0\"},{\"features\":[\"examples\"],\"kind\":\"dev\",\"name\":\"snapbox\",\"req\":\"^0.6.21\"},{\"kind\":\"dev\",\"name\":\"term-transcript\",\"req\":\"^0.2.0\"},{\"name\":\"terminal_size\",\"optional\":true,\"req\":\"^0.4.0\"}],\"features\":{\"alloc\":[],\"debug\":[\"std\",\"dep:anstream\",\"dep:anstyle\",\"dep:is_terminal_polyfill\",\"dep:terminal_size\"],\"default\":[\"std\"],\"simd\":[\"dep:memchr\"],\"std\":[\"alloc\",\"memchr?/std\"],\"unstable-doc\":[\"alloc\",\"std\",\"simd\",\"unstable-recover\"],\"unstable-recover\":[]}}", "winreg_0.10.1": "{\"dependencies\":[{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.6\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"~3.0\"},{\"features\":[\"impl-default\",\"impl-debug\",\"minwindef\",\"minwinbase\",\"timezoneapi\",\"winerror\",\"winnt\",\"winreg\",\"handleapi\"],\"name\":\"winapi\",\"req\":\"^0.3.9\"}],\"features\":{\"serialization-serde\":[\"transactions\",\"serde\"],\"transactions\":[\"winapi/ktmw32\"]}}", + "winreg_0.50.0": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.6\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_bytes\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"~3.0\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Time\",\"Win32_System_Registry\",\"Win32_Security\",\"Win32_Storage_FileSystem\",\"Win32_System_Diagnostics_Debug\"],\"name\":\"windows-sys\",\"req\":\"^0.48.0\"}],\"features\":{\"serialization-serde\":[\"transactions\",\"serde\"],\"transactions\":[]}}", "winres_0.1.12": "{\"dependencies\":[{\"name\":\"toml\",\"req\":\"^0.5\"},{\"features\":[\"winnt\"],\"kind\":\"dev\",\"name\":\"winapi\",\"req\":\"^0.3\"}],\"features\":{}}", "winsafe_0.0.19": "{\"dependencies\":[],\"features\":{\"comctl\":[\"ole\"],\"dshow\":[\"oleaut\"],\"dwm\":[\"uxtheme\"],\"dxgi\":[\"ole\"],\"gdi\":[\"user\"],\"gui\":[\"comctl\",\"shell\",\"uxtheme\"],\"kernel\":[],\"mf\":[\"oleaut\"],\"ole\":[\"user\"],\"oleaut\":[\"ole\"],\"shell\":[\"oleaut\"],\"taskschd\":[\"oleaut\"],\"user\":[\"kernel\"],\"uxtheme\":[\"gdi\",\"ole\"],\"version\":[\"kernel\"]}}", "winsplit_0.1.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.3\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", From ff9fa563683515390d81804fae16128b228d28ed Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Wed, 28 Jan 2026 12:25:40 -0800 Subject: [PATCH 046/116] default enable compression, update test helpers (#10102) set `enable_request_compression` flag to default-enabled. update integration test helpers to decompress `zstd` if flag set. --- codex-rs/Cargo.lock | 1 + codex-rs/core/src/features.rs | 4 +-- codex-rs/core/tests/common/Cargo.toml | 1 + codex-rs/core/tests/common/responses.rs | 36 ++++++++++++++++++++++--- 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 5d17acab98..38d44c44b5 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2236,6 +2236,7 @@ dependencies = [ "tokio-tungstenite", "walkdir", "wiremock", + "zstd", ] [[package]] diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index a571b31952..26798c29d9 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -506,8 +506,8 @@ pub const FEATURES: &[FeatureSpec] = &[ FeatureSpec { id: Feature::EnableRequestCompression, key: "enable_request_compression", - stage: Stage::UnderDevelopment, - default_enabled: false, + stage: Stage::Stable, + default_enabled: true, }, FeatureSpec { id: Feature::Collab, diff --git a/codex-rs/core/tests/common/Cargo.toml b/codex-rs/core/tests/common/Cargo.toml index 8e9f53943a..1c76e5a16e 100644 --- a/codex-rs/core/tests/common/Cargo.toml +++ b/codex-rs/core/tests/common/Cargo.toml @@ -25,6 +25,7 @@ tokio-tungstenite = { workspace = true } walkdir = { workspace = true } wiremock = { workspace = true } shlex = { workspace = true } +zstd = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index e36d9592f1..86a332874e 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -76,9 +76,32 @@ impl ResponseMock { #[derive(Debug, Clone)] pub struct ResponsesRequest(wiremock::Request); +fn is_zstd_encoding(value: &str) -> bool { + value + .split(',') + .any(|entry| entry.trim().eq_ignore_ascii_case("zstd")) +} + +fn decode_body_bytes(body: &[u8], content_encoding: Option<&str>) -> Vec { + if content_encoding.is_some_and(is_zstd_encoding) { + zstd::stream::decode_all(std::io::Cursor::new(body)).unwrap_or_else(|err| { + panic!("failed to decode zstd request body: {err}"); + }) + } else { + body.to_vec() + } +} + impl ResponsesRequest { pub fn body_json(&self) -> Value { - self.0.body_json().unwrap() + let body = decode_body_bytes( + &self.0.body, + self.0 + .headers + .get("content-encoding") + .and_then(|value| value.to_str().ok()), + ); + serde_json::from_slice(&body).unwrap() } pub fn body_bytes(&self) -> Vec { @@ -105,7 +128,7 @@ impl ResponsesRequest { } pub fn input(&self) -> Vec { - self.0.body_json::().unwrap()["input"] + self.body_json()["input"] .as_array() .expect("input array not found in request") .clone() @@ -1083,7 +1106,14 @@ fn validate_request_body_invariants(request: &wiremock::Request) { if request.method != "POST" || !request.url.path().ends_with("/responses") { return; } - let Ok(body): Result = request.body_json() else { + let body_bytes = decode_body_bytes( + &request.body, + request + .headers + .get("content-encoding") + .and_then(|value| value.to_str().ok()), + ); + let Ok(body): Result = serde_json::from_slice(&body_bytes) else { return; }; let Some(items) = body.get("input").and_then(Value::as_array) else { From 7b34cad1b1ceb7cc8c4bea13b4a8c9a5ce6e3d9b Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 14:36:40 -0700 Subject: [PATCH 047/116] fix(ci) more shell-tool-mcp issues (#10111) ## Summary More pnpm upgrade issues. --- shell-tool-mcp/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shell-tool-mcp/package.json b/shell-tool-mcp/package.json index d27c0a0c59..24798b2f6e 100644 --- a/shell-tool-mcp/package.json +++ b/shell-tool-mcp/package.json @@ -36,5 +36,6 @@ "ts-jest": "^29.3.4", "tsup": "^8.5.0", "typescript": "^5.9.2" - } + }, + "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264" } From 83d7c44500561c70e1068009ff14df6e04ebe8b3 Mon Sep 17 00:00:00 2001 From: mjr-openai Date: Wed, 28 Jan 2026 18:30:48 -0500 Subject: [PATCH 048/116] update the ci pnpm workflow for shell-tool-mcp to use corepack for pnpm versioning (#10115) This updates the CI workflows for shell-tool-mcp to use the pnpm version from package.json and print it in the build for verification. I have read the CLA Document and I hereby sign the CLA --- .github/workflows/shell-tool-mcp-ci.yml | 9 +++++++++ .github/workflows/shell-tool-mcp.yml | 19 +++++++++++++++++-- package.json | 2 +- shell-tool-mcp/package.json | 1 + 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/.github/workflows/shell-tool-mcp-ci.yml b/.github/workflows/shell-tool-mcp-ci.yml index 739cc6e409..bea88ad891 100644 --- a/.github/workflows/shell-tool-mcp-ci.yml +++ b/.github/workflows/shell-tool-mcp-ci.yml @@ -35,6 +35,15 @@ jobs: node-version: ${{ env.NODE_VERSION }} cache: "pnpm" + - name: Enable Corepack + run: corepack enable + + - name: Activate pnpm from package.json + run: corepack prepare --activate + + - name: Verify pnpm version + run: pnpm --version + - name: Install dependencies run: pnpm install --frozen-lockfile diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 88cdc28b3a..446af67918 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -351,6 +351,15 @@ jobs: with: node-version: ${{ env.NODE_VERSION }} + - name: Enable Corepack + run: corepack enable + + - name: Activate pnpm from package.json + run: corepack prepare --activate + + - name: Verify pnpm version + run: pnpm --version + - name: Install JavaScript dependencies run: pnpm install --frozen-lockfile @@ -448,8 +457,14 @@ jobs: registry-url: https://registry.npmjs.org scope: "@openai" - - name: Update npm - run: npm install -g npm@latest + - name: Enable Corepack + run: corepack enable + + - name: Activate pnpm from package.json + run: corepack prepare --activate + + - name: Verify pnpm version + run: pnpm --version - name: Download npm tarball uses: actions/download-artifact@v7 diff --git a/package.json b/package.json index 9f1452a972..633a6f8331 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ }, "engines": { "node": ">=22", - "pnpm": ">=9.0.0" + "pnpm": ">=10.28.0" }, "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264" } diff --git a/shell-tool-mcp/package.json b/shell-tool-mcp/package.json index 24798b2f6e..c6dfcd7a55 100644 --- a/shell-tool-mcp/package.json +++ b/shell-tool-mcp/package.json @@ -3,6 +3,7 @@ "version": "0.0.0-dev", "description": "Codex MCP server for the shell tool with patched Bash and exec wrappers.", "license": "Apache-2.0", + "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264", "bin": { "codex-shell-tool-mcp": "bin/mcp-server.js" }, From 849716336347d7a8024ad75a514e11d0eacbc1cd Mon Sep 17 00:00:00 2001 From: zbarsky-openai Date: Wed, 28 Jan 2026 19:15:44 -0500 Subject: [PATCH 049/116] [bazel] Improve runfiles handling (#10098) we can't use runfiles directory on Windows due to path lengths, so swap to manifest strategy. Parsing the manifest is a bit complex and the format is changing in Bazel upstream, so pull in the official Rust library (via a small hack to make it importable...) and cleanup all the associated logic to work cleanly in both bazel and cargo without extra confusion --- .bazelignore | 1 + .bazelrc | 6 +- BUILD.bazel | 4 + MODULE.bazel | 7 + MODULE.bazel.lock | 4 +- codex-rs/Cargo.lock | 7 +- codex-rs/Cargo.toml | 1 + codex-rs/core/tests/suite/cli_stream.rs | 2 +- codex-rs/exec/tests/suite/auth_env.rs | 3 +- codex-rs/exec/tests/suite/resume.rs | 2 +- codex-rs/utils/cargo-bin/BUILD.bazel | 6 + codex-rs/utils/cargo-bin/Cargo.toml | 2 +- codex-rs/utils/cargo-bin/README.md | 20 ++ codex-rs/utils/cargo-bin/repo_root.marker | 1 + codex-rs/utils/cargo-bin/src/lib.rs | 227 +++++++++++++--------- defs.bzl | 11 +- patches/rules_rust.patch | 2 +- 17 files changed, 203 insertions(+), 103 deletions(-) create mode 100644 codex-rs/utils/cargo-bin/README.md create mode 100644 codex-rs/utils/cargo-bin/repo_root.marker diff --git a/.bazelignore b/.bazelignore index eda018aeb2..2e90753cb8 100644 --- a/.bazelignore +++ b/.bazelignore @@ -1,3 +1,4 @@ # Without this, Bazel will consider BUILD.bazel files in # .git/sl/origbackups (which can be populated by Sapling SCM). .git +codex-rs/target diff --git a/.bazelrc b/.bazelrc index 764754c216..ce0c2ee5d5 100644 --- a/.bazelrc +++ b/.bazelrc @@ -1,5 +1,7 @@ common --repo_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 common --repo_env=BAZEL_NO_APPLE_CPP_TOOLCHAIN=1 +# Dummy xcode config so we don't need to build xcode_locator in repo rule. +common --xcode_version_config=//:disable_xcode common --disk_cache=~/.cache/bazel-disk-cache common --repo_contents_cache=~/.cache/bazel-repo-contents-cache @@ -9,6 +11,9 @@ startup --experimental_remote_repo_contents_cache common --experimental_platform_in_output_dir +# Runfiles strategy rationale: codex-rs/utils/cargo-bin/README.md +common --noenable_runfiles + common --enable_platform_specific_config # TODO(zbarsky): We need to untangle these libc constraints to get linux remote builds working. common:linux --host_platform=//:local @@ -44,4 +49,3 @@ common --jobs=30 common:remote --extra_execution_platforms=//:rbe common:remote --remote_executor=grpcs://remote.buildbuddy.io common:remote --jobs=800 - diff --git a/BUILD.bazel b/BUILD.bazel index 883432655c..dc57103b6b 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -1,3 +1,7 @@ +load("@apple_support//xcode:xcode_config.bzl", "xcode_config") + +xcode_config(name = "disable_xcode") + # We mark the local platform as glibc-compatible so that rust can grab a toolchain for us. # TODO(zbarsky): Upstream a better libc constraint into rules_rust. # We only enable this on linux though for sanity, and because it breaks remote execution. diff --git a/MODULE.bazel b/MODULE.bazel index df0df9b25c..f4c593b3f3 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -27,6 +27,8 @@ register_toolchains( "@toolchains_llvm_bootstrapped//toolchain:all", ) +# 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_rust", version = "0.68.1") @@ -90,6 +92,11 @@ crate.annotation( inject_repo(crate, "openssl") +crate.annotation( + crate = "runfiles", + workspace_cargo_toml = "rust/runfiles/Cargo.toml", +) + # Fix readme inclusions crate.annotation( crate = "windows-link", diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 7444d3fdbe..63b7ed16ee 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -21,7 +21,8 @@ "https://bcr.bazel.build/modules/apple_support/1.23.0/MODULE.bazel": "317d47e3f65b580e7fb4221c160797fda48e32f07d2dfff63d754ef2316dcd25", "https://bcr.bazel.build/modules/apple_support/1.24.1/MODULE.bazel": "f46e8ddad60aef170ee92b2f3d00ef66c147ceafea68b6877cb45bd91737f5f8", "https://bcr.bazel.build/modules/apple_support/1.24.2/MODULE.bazel": "0e62471818affb9f0b26f128831d5c40b074d32e6dda5a0d3852847215a41ca4", - "https://bcr.bazel.build/modules/apple_support/1.24.2/source.json": "2c22c9827093250406c5568da6c54e6fdf0ef06238def3d99c71b12feb057a8d", + "https://bcr.bazel.build/modules/apple_support/2.1.0/MODULE.bazel": "b15c125dabed01b6803c129cd384de4997759f02f8ec90dc5136bcf6dfc5086a", + "https://bcr.bazel.build/modules/apple_support/2.1.0/source.json": "78064cfefe18dee4faaf51893661e0d403784f3efe88671d727cdcdc67ed8fb3", "https://bcr.bazel.build/modules/aspect_bazel_lib/2.14.0/MODULE.bazel": "2b31ffcc9bdc8295b2167e07a757dbbc9ac8906e7028e5170a3708cecaac119f", "https://bcr.bazel.build/modules/aspect_bazel_lib/2.19.3/MODULE.bazel": "253d739ba126f62a5767d832765b12b59e9f8d2bc88cc1572f4a73e46eb298ca", "https://bcr.bazel.build/modules/aspect_bazel_lib/2.19.3/source.json": "ffab9254c65ba945f8369297ad97ca0dec213d3adc6e07877e23a48624a8b456", @@ -790,6 +791,7 @@ "gimli_0.31.1": "{\"dependencies\":[{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.2\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"name\":\"fallible-iterator\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.0.0\"},{\"default_features\":false,\"name\":\"stable_deref_trait\",\"optional\":true,\"req\":\"^1.1.0\"},{\"kind\":\"dev\",\"name\":\"test-assembler\",\"req\":\"^0.1.3\"}],\"features\":{\"default\":[\"read-all\",\"write\"],\"endian-reader\":[\"read\",\"dep:stable_deref_trait\"],\"fallible-iterator\":[\"dep:fallible-iterator\"],\"read\":[\"read-core\"],\"read-all\":[\"read\",\"std\",\"fallible-iterator\",\"endian-reader\"],\"read-core\":[],\"rustc-dep-of-std\":[\"dep:core\",\"dep:alloc\",\"dep:compiler_builtins\"],\"std\":[\"fallible-iterator?/std\",\"stable_deref_trait?/std\"],\"write\":[\"dep:indexmap\"]}}", "git+https://github.com/JakkuSakura/tokio-tungstenite?rev=2ae536b0de793f3ddf31fc2f22d445bf1ef2023d#2ae536b0de793f3ddf31fc2f22d445bf1ef2023d_tokio-tungstenite": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"sink\",\"std\"],\"name\":\"futures-util\",\"optional\":false},{\"name\":\"log\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\"},{\"default_features\":false,\"features\":[],\"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\":false,\"features\":[\"io-util\"],\"name\":\"tokio\",\"optional\":false},{\"default_features\":true,\"features\":[],\"name\":\"tokio-native-tls\",\"optional\":true},{\"default_features\":false,\"features\":[],\"name\":\"tokio-rustls\",\"optional\":true},{\"default_features\":false,\"features\":[],\"name\":\"tungstenite\",\"optional\":false},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\",\"tokio-rustls\",\"stream\",\"tungstenite/__rustls-tls\",\"handshake\"],\"connect\":[\"stream\",\"tokio/net\",\"handshake\"],\"default\":[\"connect\",\"handshake\"],\"handshake\":[\"tungstenite/handshake\"],\"native-tls\":[\"native-tls-crate\",\"tokio-native-tls\",\"stream\",\"tungstenite/native-tls\",\"handshake\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\",\"tungstenite/native-tls-vendored\"],\"proxy\":[\"tungstenite/proxy\",\"tokio/net\",\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"stream\":[],\"url\":[\"tungstenite/url\"]},\"strip_prefix\":\"\"}", "git+https://github.com/JakkuSakura/tungstenite-rs?rev=f514de8644821113e5d18a027d6d28a5c8cc0a6e#f514de8644821113e5d18a027d6d28a5c8cc0a6e_tungstenite": "{\"dependencies\":[{\"name\":\"bytes\"},{\"default_features\":true,\"features\":[],\"name\":\"data-encoding\",\"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\"],\"handshake\":[\"data-encoding\",\"http\",\"httparse\",\"sha1\"],\"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\":\"\"}", + "git+https://github.com/dzbarsky/rules_rust?rev=b56cbaa8465e74127f1ea216f813cd377295ad81#b56cbaa8465e74127f1ea216f813cd377295ad81_runfiles": "{\"dependencies\":[],\"features\":{},\"strip_prefix\":\"\"}", "git+https://github.com/helix-editor/nucleo.git?rev=4253de9faabb4e5c6d81d946a5e35a90f87347ee#4253de9faabb4e5c6d81d946a5e35a90f87347ee_nucleo": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"nucleo-matcher\",\"optional\":false},{\"default_features\":true,\"features\":[\"send_guard\",\"arc_lock\"],\"name\":\"parking_lot\",\"optional\":false},{\"name\":\"rayon\"}],\"features\":{},\"strip_prefix\":\"\"}", "git+https://github.com/helix-editor/nucleo.git?rev=4253de9faabb4e5c6d81d946a5e35a90f87347ee#4253de9faabb4e5c6d81d946a5e35a90f87347ee_nucleo-matcher": "{\"dependencies\":[{\"name\":\"memchr\"},{\"default_features\":true,\"features\":[],\"name\":\"unicode-segmentation\",\"optional\":true}],\"features\":{\"default\":[\"unicode-normalization\",\"unicode-casefold\",\"unicode-segmentation\"],\"unicode-casefold\":[],\"unicode-normalization\":[],\"unicode-segmentation\":[\"dep:unicode-segmentation\"]},\"strip_prefix\":\"matcher\"}", "git+https://github.com/nornagon/crossterm?branch=nornagon%2Fcolor-query#87db8bfa6dc99427fd3b071681b07fc31c6ce995_crossterm": "{\"dependencies\":[{\"default_features\":true,\"features\":[],\"name\":\"bitflags\",\"optional\":false},{\"default_features\":false,\"features\":[],\"name\":\"futures-core\",\"optional\":true},{\"name\":\"parking_lot\"},{\"default_features\":true,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"filedescriptor\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":false,\"features\":[],\"name\":\"libc\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[\"os-poll\"],\"name\":\"mio\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":false,\"features\":[\"std\",\"stdio\",\"termios\"],\"name\":\"rustix\",\"optional\":false,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[],\"name\":\"signal-hook\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[\"support-v1_0\"],\"name\":\"signal-hook-mio\",\"optional\":true,\"target\":\"cfg(unix)\"},{\"default_features\":true,\"features\":[],\"name\":\"crossterm_winapi\",\"optional\":true,\"target\":\"cfg(windows)\"},{\"default_features\":true,\"features\":[\"winuser\",\"winerror\"],\"name\":\"winapi\",\"optional\":true,\"target\":\"cfg(windows)\"}],\"features\":{\"bracketed-paste\":[],\"default\":[\"bracketed-paste\",\"windows\",\"events\"],\"event-stream\":[\"dep:futures-core\",\"events\"],\"events\":[\"dep:mio\",\"dep:signal-hook\",\"dep:signal-hook-mio\"],\"serde\":[\"dep:serde\",\"bitflags/serde\"],\"use-dev-tty\":[\"filedescriptor\",\"rustix/process\"],\"windows\":[\"dep:winapi\",\"dep:crossterm_winapi\"]},\"strip_prefix\":\"\"}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 38d44c44b5..c6b006c203 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1975,7 +1975,7 @@ name = "codex-utils-cargo-bin" version = "0.0.0" dependencies = [ "assert_cmd", - "path-absolutize", + "runfiles", "thiserror 2.0.17", ] @@ -6592,6 +6592,11 @@ dependencies = [ "zeroize", ] +[[package]] +name = "runfiles" +version = "0.1.0" +source = "git+https://github.com/dzbarsky/rules_rust?rev=b56cbaa8465e74127f1ea216f813cd377295ad81#b56cbaa8465e74127f1ea216f813cd377295ad81" + [[package]] name = "rustc-demangle" version = "0.1.25" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 9b0ce2e16d..5196213991 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -186,6 +186,7 @@ regex = "1.12.2" regex-lite = "0.1.8" reqwest = "0.12" rmcp = { version = "0.12.0", default-features = false } +runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" } schemars = "0.8.22" seccompiler = "0.5.0" sentry = "0.46.0" diff --git a/codex-rs/core/tests/suite/cli_stream.rs b/codex-rs/core/tests/suite/cli_stream.rs index 57142b07f2..9ca2c6bd68 100644 --- a/codex-rs/core/tests/suite/cli_stream.rs +++ b/codex-rs/core/tests/suite/cli_stream.rs @@ -16,7 +16,7 @@ use wiremock::matchers::path; fn repo_root() -> std::path::PathBuf { #[expect(clippy::expect_used)] - find_resource!(".").expect("failed to resolve repo root") + codex_utils_cargo_bin::repo_root().expect("failed to resolve repo root") } fn cli_responses_fixture() -> std::path::PathBuf { diff --git a/codex-rs/exec/tests/suite/auth_env.rs b/codex-rs/exec/tests/suite/auth_env.rs index 4f8018e808..d55da946e2 100644 --- a/codex-rs/exec/tests/suite/auth_env.rs +++ b/codex-rs/exec/tests/suite/auth_env.rs @@ -1,5 +1,4 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] -use codex_utils_cargo_bin::find_resource; use core_test_support::responses::ev_completed; use core_test_support::responses::mount_sse_once_match; use core_test_support::responses::sse; @@ -11,7 +10,7 @@ use wiremock::matchers::header; async fn exec_uses_codex_api_key_env_var() -> anyhow::Result<()> { let test = test_codex_exec(); let server = start_mock_server().await; - let repo_root = find_resource!(".")?; + let repo_root = codex_utils_cargo_bin::repo_root()?; mount_sse_once_match( &server, diff --git a/codex-rs/exec/tests/suite/resume.rs b/codex-rs/exec/tests/suite/resume.rs index 6e24934f21..4169c60dd1 100644 --- a/codex-rs/exec/tests/suite/resume.rs +++ b/codex-rs/exec/tests/suite/resume.rs @@ -113,7 +113,7 @@ fn exec_fixture() -> anyhow::Result { } fn exec_repo_root() -> anyhow::Result { - Ok(find_resource!(".")?) + Ok(codex_utils_cargo_bin::repo_root()?) } #[test] diff --git a/codex-rs/utils/cargo-bin/BUILD.bazel b/codex-rs/utils/cargo-bin/BUILD.bazel index 77d6518012..b5b5e6ba33 100644 --- a/codex-rs/utils/cargo-bin/BUILD.bazel +++ b/codex-rs/utils/cargo-bin/BUILD.bazel @@ -3,4 +3,10 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "cargo-bin", crate_name = "codex_utils_cargo_bin", + compile_data = ["repo_root.marker"], + lib_data_extra = ["repo_root.marker"], + test_data_extra = ["repo_root.marker"], + rustc_env = { + "CODEX_REPO_ROOT_MARKER": "$(rlocationpath :repo_root.marker)", + }, ) diff --git a/codex-rs/utils/cargo-bin/Cargo.toml b/codex-rs/utils/cargo-bin/Cargo.toml index fe3a410547..6cbe923f97 100644 --- a/codex-rs/utils/cargo-bin/Cargo.toml +++ b/codex-rs/utils/cargo-bin/Cargo.toml @@ -9,5 +9,5 @@ workspace = true [dependencies] assert_cmd = { workspace = true } -path-absolutize = { workspace = true } +runfiles = { workspace = true } thiserror = { workspace = true } diff --git a/codex-rs/utils/cargo-bin/README.md b/codex-rs/utils/cargo-bin/README.md new file mode 100644 index 0000000000..05af2f34bf --- /dev/null +++ b/codex-rs/utils/cargo-bin/README.md @@ -0,0 +1,20 @@ +# codex-utils-cargo-bin runfiles strategy + +We disable the directory-based runfiles strategy and rely on the manifest +strategy across all platforms. This avoids Windows path length issues and keeps +behavior consistent in local and remote builds on all platforms. Bazel sets +`RUNFILES_MANIFEST_FILE`, and the `codex-utils-cargo-bin` helpers use the +`runfiles` crate to resolve runfiles via that manifest. + +Function behavior: +- `cargo_bin`: reads `CARGO_BIN_EXE_*` environment variables (set by Cargo or + Bazel) and resolves them via the runfiles manifest when `RUNFILES_MANIFEST_FILE` + is present. When not under runfiles, it only accepts absolute paths from + `CARGO_BIN_EXE_*` and returns an error otherwise. +- `find_resource!`: used by tests to locate fixtures. It chooses the Bazel + runfiles resolution path when `RUNFILES_MANIFEST_FILE` is set, otherwise it + falls back to a `CARGO_MANIFEST_DIR`-relative path for Cargo runs. + +Background: +- https://bazel.build/docs/runfiles +- https://bazel.build/docs/runfiles#runfiles-manifest diff --git a/codex-rs/utils/cargo-bin/repo_root.marker b/codex-rs/utils/cargo-bin/repo_root.marker new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/codex-rs/utils/cargo-bin/repo_root.marker @@ -0,0 +1 @@ + diff --git a/codex-rs/utils/cargo-bin/src/lib.rs b/codex-rs/utils/cargo-bin/src/lib.rs index 40fa40c62f..84f69af358 100644 --- a/codex-rs/utils/cargo-bin/src/lib.rs +++ b/codex-rs/utils/cargo-bin/src/lib.rs @@ -1,7 +1,12 @@ use std::ffi::OsString; +use std::io; +use std::path::Path; use std::path::PathBuf; -pub use path_absolutize; +pub use runfiles; + +/// Bazel sets this when runfiles directories are disabled, which we do on all platforms for consistency. +const RUNFILES_MANIFEST_ONLY_ENV: &str = "RUNFILES_MANIFEST_ONLY"; #[derive(Debug, thiserror::Error)] pub enum CargoBinError { @@ -27,10 +32,9 @@ pub enum CargoBinError { /// Returns an absolute path to a binary target built for the current test run. /// -/// In `cargo test`, `CARGO_BIN_EXE_*` env vars are absolute, but Buck2 may set -/// them to project-relative paths (e.g. `buck-out/...`). Those paths break if a -/// test later changes its working directory. This helper makes the path -/// absolute up-front so callers can safely `chdir` afterwards. +/// In `cargo test`, `CARGO_BIN_EXE_*` env vars are absolute. +/// In `bazel test`, `CARGO_BIN_EXE_*` env vars are rlocationpaths, intended to be consumed by `rlocation`. +/// This helper allows callers to transparently support both. pub fn cargo_bin(name: &str) -> Result { let env_keys = cargo_bin_env_keys(name); for key in &env_keys { @@ -38,16 +42,20 @@ pub fn cargo_bin(name: &str) -> Result { return resolve_bin_from_env(key, value); } } - match assert_cmd::Command::cargo_bin(name) { Ok(cmd) => { - let abs = absolutize_from_buck_or_cwd(PathBuf::from(cmd.get_program()))?; - if abs.exists() { - Ok(abs) + let mut path = PathBuf::from(cmd.get_program()); + if !path.is_absolute() { + path = std::env::current_dir() + .map_err(|source| CargoBinError::CurrentDir { source })? + .join(path); + } + if path.exists() { + Ok(path) } else { Err(CargoBinError::ResolvedPathDoesNotExist { key: "assert_cmd::Command::cargo_bin".to_owned(), - path: abs, + path, }) } } @@ -72,6 +80,31 @@ fn cargo_bin_env_keys(name: &str) -> Vec { keys } +pub fn runfiles_available() -> bool { + std::env::var_os(RUNFILES_MANIFEST_ONLY_ENV).is_some() +} + +fn resolve_bin_from_env(key: &str, value: OsString) -> Result { + let raw = PathBuf::from(&value); + if runfiles_available() { + let runfiles = runfiles::Runfiles::create().map_err(|err| CargoBinError::CurrentExe { + source: std::io::Error::other(err), + })?; + if let Some(resolved) = runfiles::rlocation!(runfiles, &raw) + && resolved.exists() + { + return Ok(resolved); + } + } else if raw.is_absolute() && raw.exists() { + return Ok(raw); + } + + Err(CargoBinError::ResolvedPathDoesNotExist { + key: key.to_owned(), + path: raw, + }) +} + /// Macro that derives the path to a test resource at runtime, the value of /// which depends on whether Cargo or Bazel is being used to build and run a /// test. Note the return value may be a relative or absolute path. @@ -84,97 +117,109 @@ fn cargo_bin_env_keys(name: &str) -> Vec { #[macro_export] macro_rules! find_resource { ($resource:expr) => {{ - // When this code is built and run with Bazel: - // - we inject `BAZEL_PACKAGE` as a compile-time environment variable - // that points to native.package_name() - // - at runtime, Bazel will set `RUNFILES_DIR` to the runfiles directory - // - // Therefore, the compile-time value of `BAZEL_PACKAGE` will always be - // included in the compiled binary (even if it is built with Cargo), but - // we only check it at runtime if `RUNFILES_DIR` is set. let resource = std::path::Path::new(&$resource); - match std::env::var("RUNFILES_DIR") { - Ok(bazel_runtime_files) => match option_env!("BAZEL_PACKAGE") { - Some(bazel_package) => { - use $crate::path_absolutize::Absolutize; - - let manifest_dir = std::path::PathBuf::from(bazel_runtime_files) - .join("_main") - .join(bazel_package) - .join(resource); - // Note we also have to normalize (but not canonicalize!) - // the path for _Bazel_ because the original value ends with - // `codex-rs/exec-server/tests/common/../suite/bash`, but - // the `tests/common` folder will not exist at runtime under - // Bazel. As such, we have to normalize it before passing it - // to `dotslash fetch`. - manifest_dir.absolutize().map(|p| p.to_path_buf()) - } - None => Err(std::io::Error::new( - std::io::ErrorKind::NotFound, - "BAZEL_PACKAGE not set in Bazel build", - )), - }, - Err(_) => { - let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - Ok(manifest_dir.join(resource)) - } + if $crate::runfiles_available() { + // When this code is built and run with Bazel: + // - we inject `BAZEL_PACKAGE` as a compile-time environment variable + // that points to native.package_name() + // - at runtime, Bazel will set runfiles-related env vars + $crate::resolve_bazel_runfile(option_env!("BAZEL_PACKAGE"), resource) + } else { + let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + Ok(manifest_dir.join(resource)) } }}; } -fn resolve_bin_from_env(key: &str, value: OsString) -> Result { - let abs = absolutize_from_buck_or_cwd(PathBuf::from(value))?; - - if abs.exists() { - Ok(abs) - } else { - Err(CargoBinError::ResolvedPathDoesNotExist { - key: key.to_owned(), - path: abs, - }) - } -} - -fn absolutize_from_buck_or_cwd(path: PathBuf) -> Result { - if path.is_absolute() { - return Ok(path); - } - - if let Some(root) = - buck_project_root().map_err(|source| CargoBinError::CurrentExe { source })? +pub fn resolve_bazel_runfile( + bazel_package: Option<&str>, + resource: &Path, +) -> std::io::Result { + let runfiles = runfiles::Runfiles::create() + .map_err(|err| std::io::Error::other(format!("failed to create runfiles: {err}")))?; + let runfile_path = match bazel_package { + Some(bazel_package) => PathBuf::from("_main").join(bazel_package).join(resource), + None => { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + "BAZEL_PACKAGE was not set at compile time", + )); + } + }; + let runfile_path = normalize_runfile_path(&runfile_path); + if let Some(resolved) = runfiles::rlocation!(runfiles, &runfile_path) + && resolved.exists() { - return Ok(root.join(path)); + return Ok(resolved); } - - Ok(std::env::current_dir() - .map_err(|source| CargoBinError::CurrentDir { source })? - .join(path)) + let runfile_path_display = runfile_path.display(); + Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("runfile does not exist at: {runfile_path_display}"), + )) } -/// Best-effort attempt to find the Buck project root for the currently running -/// process. -/// -/// Prefer this over `env!("CARGO_MANIFEST_DIR")` when running under Buck2: our -/// Buck generator sets `CARGO_MANIFEST_DIR="."` for compilation, which makes -/// `env!("CARGO_MANIFEST_DIR")` unusable for locating workspace files. -pub fn buck_project_root() -> Result, std::io::Error> { - if let Some(root) = std::env::var_os("BUCK_PROJECT_ROOT") { - let root = PathBuf::from(root); - if root.is_absolute() { - return Ok(Some(root)); +pub fn resolve_cargo_runfile(resource: &Path) -> std::io::Result { + let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + Ok(manifest_dir.join(resource)) +} + +pub fn repo_root() -> io::Result { + let marker = if runfiles_available() { + let runfiles = runfiles::Runfiles::create() + .map_err(|err| io::Error::other(format!("failed to create runfiles: {err}")))?; + let marker_path = option_env!("CODEX_REPO_ROOT_MARKER") + .map(PathBuf::from) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "CODEX_REPO_ROOT_MARKER was not set at compile time", + ) + })?; + runfiles::rlocation!(runfiles, &marker_path).ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "repo_root.marker not available in runfiles", + ) + })? + } else { + resolve_cargo_runfile(Path::new("repo_root.marker"))? + }; + let mut root = marker; + for _ in 0..4 { + root = root + .parent() + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "repo_root.marker did not have expected parent depth", + ) + })? + .to_path_buf(); + } + Ok(root) +} + +fn normalize_runfile_path(path: &Path) -> PathBuf { + let mut components = Vec::new(); + for component in path.components() { + match component { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + if matches!(components.last(), Some(std::path::Component::Normal(_))) { + components.pop(); + } else { + components.push(component); + } + } + _ => components.push(component), } } - // Fall back to deriving the project root from the location of the test - // runner executable: - // /buck-out/v2/gen/.../__tests__/test-binary - let exe = std::env::current_exe()?; - for ancestor in exe.ancestors() { - if ancestor.file_name().is_some_and(|name| name == "buck-out") { - return Ok(ancestor.parent().map(PathBuf::from)); - } - } - - Ok(None) + components + .into_iter() + .fold(PathBuf::new(), |mut acc, component| { + acc.push(component.as_os_str()); + acc + }) } diff --git a/defs.bzl b/defs.bzl index 249c3a4583..40112969c8 100644 --- a/defs.bzl +++ b/defs.bzl @@ -36,6 +36,8 @@ def codex_rust_crate( crate_edition = None, build_script_data = [], compile_data = [], + lib_data_extra = [], + rustc_env = {}, deps_extra = [], integration_deps_extra = [], integration_compile_data_extra = [], @@ -63,6 +65,8 @@ def codex_rust_crate( You probably don't want this, it's only here for a single caller. build_script_data: Data files exposed to the build script at runtime. compile_data: Non-Rust compile-time data for the library target. + lib_data_extra: Extra runtime data for the library target. + 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. @@ -85,7 +89,7 @@ def codex_rust_crate( rustc_env = { "BAZEL_PACKAGE": native.package_name(), - } + } | rustc_env binaries = DEP_DATA.get(native.package_name())["binaries"] @@ -112,6 +116,7 @@ def codex_rust_crate( deps = deps, proc_macro_deps = proc_macro_deps, compile_data = compile_data, + data = lib_data_extra, srcs = lib_srcs, edition = crate_edition, rustc_env = rustc_env, @@ -138,7 +143,7 @@ def codex_rust_crate( for binary, main in binaries.items(): #binary = binary.replace("-", "_") sanitized_binaries.append(binary) - cargo_env["CARGO_BIN_EXE_" + binary] = "$(rootpath :%s)" % binary + cargo_env["CARGO_BIN_EXE_" + binary] = "$(rlocationpath :%s)" % binary rust_binary( name = binary, @@ -154,7 +159,7 @@ def codex_rust_crate( for binary_label in extra_binaries: sanitized_binaries.append(binary_label) binary = Label(binary_label).name - cargo_env["CARGO_BIN_EXE_" + binary] = "$(rootpath %s)" % binary_label + cargo_env["CARGO_BIN_EXE_" + binary] = "$(rlocationpath %s)" % binary_label for test in native.glob(["tests/*.rs"], allow_empty = True): test_name = name + "-" + test.removeprefix("tests/").removesuffix(".rs").replace("/", "-") diff --git a/patches/rules_rust.patch b/patches/rules_rust.patch index 298eb74c51..3020ac2282 100644 --- a/patches/rules_rust.patch +++ b/patches/rules_rust.patch @@ -31,4 +31,4 @@ index a28ad50b7..af627fe50 100644 + make_link_flags = _make_link_flags_default_direct if use_direct_link_driver else _make_link_flags_default_indirect return (make_link_flags, get_lib_name) - + From 26590d7927c0ca6f12c5ad73fdaeaa9ad73a2932 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 28 Jan 2026 16:51:20 -0800 Subject: [PATCH 050/116] Ensure auto-compaction starts after turn started (#10129) Start auto-compaction only after TurnStarted is emitted.\nAdd an integration test for deterministic ordering. --- codex-rs/core/src/codex.rs | 6 +- codex-rs/core/tests/suite/compact.rs | 95 ++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index c251805272..70e52eb064 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -3151,13 +3151,13 @@ pub(crate) async fn run_turn( let model_info = turn_context.client.get_model_info(); let auto_compact_limit = model_info.auto_compact_token_limit().unwrap_or(i64::MAX); let total_usage_tokens = sess.get_total_token_usage().await; - if total_usage_tokens >= auto_compact_limit { - run_auto_compact(&sess, &turn_context).await; - } let event = EventMsg::TurnStarted(TurnStartedEvent { model_context_window: turn_context.client.get_model_context_window(), }); sess.send_event(&turn_context, event).await; + if total_usage_tokens >= auto_compact_limit { + run_auto_compact(&sess, &turn_context).await; + } let skills_outcome = Some( sess.services diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index b8b693945b..fa07bf7f9b 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -1339,6 +1339,101 @@ async fn auto_compact_emits_context_compaction_items() { assert!(legacy_event); } +// Windows CI only: bump to 4 workers to prevent SSE/event starvation and test timeouts. +#[cfg_attr(windows, tokio::test(flavor = "multi_thread", worker_threads = 4))] +#[cfg_attr(not(windows), tokio::test(flavor = "multi_thread", worker_threads = 2))] +async fn auto_compact_starts_after_turn_started() { + skip_if_no_network!(); + + let server = start_mock_server().await; + + let sse1 = sse(vec![ + ev_assistant_message("m1", FIRST_REPLY), + ev_completed_with_tokens("r1", 70_000), + ]); + let sse2 = sse(vec![ + ev_assistant_message("m2", "SECOND_REPLY"), + ev_completed_with_tokens("r2", 330_000), + ]); + let sse3 = sse(vec![ + ev_assistant_message("m3", AUTO_SUMMARY_TEXT), + ev_completed_with_tokens("r3", 200), + ]); + let sse4 = sse(vec![ + ev_assistant_message("m4", FINAL_REPLY), + ev_completed_with_tokens("r4", 120), + ]); + + mount_sse_sequence(&server, vec![sse1, sse2, sse3, sse4]).await; + + let model_provider = non_openai_model_provider(&server); + let mut builder = test_codex().with_config(move |config| { + config.model_provider = model_provider; + set_test_compact_prompt(config); + config.model_auto_compact_token_limit = Some(200_000); + }); + let codex = builder.build(&server).await.unwrap().codex; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: FIRST_AUTO_MSG.into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await + .unwrap(); + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: SECOND_AUTO_MSG.into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await + .unwrap(); + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: POST_AUTO_USER_MSG.into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await + .unwrap(); + + let first = wait_for_event_match(&codex, |ev| match ev { + EventMsg::TurnStarted(_) => Some("turn"), + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::ContextCompaction(_), + .. + }) => Some("compaction"), + _ => None, + }) + .await; + assert_eq!(first, "turn", "compaction started before turn started"); + + wait_for_event(&codex, |ev| { + matches!( + ev, + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::ContextCompaction(_), + .. + }) + ) + }) + .await; + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn auto_compact_runs_after_resume_when_token_usage_is_over_limit() { skip_if_no_network!(); From ce3d764ae103404c82059cfa359275022ac013c4 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 17:58:28 -0700 Subject: [PATCH 051/116] chore(config) personality as a feature (#10116) ## Summary Sets up an explicit Feature flag for `/personality`, so users can now opt in to it via `/experimental`. #10114 also updates the config ## Testing - [x] Tested locally --- codex-rs/core/config.schema.json | 6 ++++ codex-rs/core/src/features.rs | 12 +++++++ .../core/src/models_manager/model_info.rs | 10 ++++++ codex-rs/tui/src/chatwidget.rs | 32 +++++++++++-------- ...t__tests__personality_selection_popup.snap | 6 ++-- codex-rs/tui/src/chatwidget/tests.rs | 1 + codex-rs/tui/src/slash_command.rs | 2 +- 7 files changed, 51 insertions(+), 18 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 03e27dceda..ea6ec9e872 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -180,6 +180,9 @@ "include_apply_patch_tool": { "type": "boolean" }, + "personality": { + "type": "boolean" + }, "powershell_utf8": { "type": "boolean" }, @@ -1198,6 +1201,9 @@ "include_apply_patch_tool": { "type": "boolean" }, + "personality": { + "type": "boolean" + }, "powershell_utf8": { "type": "boolean" }, diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 26798c29d9..bedf67c4ad 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -119,6 +119,8 @@ pub enum Feature { Steer, /// Enable collaboration modes (Plan, Code, Pair Programming, Execute). CollaborationModes, + /// Enable personality selection in the TUI. + Personality, /// Use the Responses API WebSocket transport for OpenAI by default. ResponsesWebsockets, } @@ -543,6 +545,16 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::Personality, + key: "personality", + stage: Stage::Experimental { + name: "Personality", + menu_description: "Choose a communication style for Codex.", + announcement: "NEW! Update codex's communication style with /personality. Enable in /experimental!", + }, + default_enabled: false, + }, FeatureSpec { id: Feature::ResponsesWebsockets, key: "responses_websockets", diff --git a/codex-rs/core/src/models_manager/model_info.rs b/codex-rs/core/src/models_manager/model_info.rs index 5d8d0d2937..b50f23274a 100644 --- a/codex-rs/core/src/models_manager/model_info.rs +++ b/codex-rs/core/src/models_manager/model_info.rs @@ -213,6 +213,16 @@ pub(crate) fn find_model_info_for_slug(slug: &str) -> ModelInfo { truncation_policy: TruncationPolicyConfig::tokens(10_000), context_window: Some(CONTEXT_WINDOW_272K), supported_reasoning_levels: supported_reasoning_level_low_medium_high_xhigh(), + model_instructions_template: Some(ModelInstructionsTemplate { + template: GPT_5_2_CODEX_INSTRUCTIONS_TEMPLATE.to_string(), + personality_messages: Some(PersonalityMessages(BTreeMap::from([( + Personality::Friendly, + PERSONALITY_FRIENDLY.to_string(), + ), ( + Personality::Pragmatic, + PERSONALITY_PRAGMATIC.to_string(), + )]))), + }), ) } else if slug.starts_with("gpt-5.1-codex-max") { model_info!( diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index bd1014b2f4..dcbb4d7c22 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -2892,6 +2892,7 @@ impl ChatWidget { let personality = self .config .model_personality + .filter(|_| self.config.features.enabled(Feature::Personality)) .filter(|_| self.current_model_supports_personality()); let op = Op::UserTurn { items, @@ -3455,19 +3456,23 @@ impl ChatWidget { ); return; } + if !self.current_model_supports_personality() { + let current_model = self.current_model(); + self.add_error_message(format!( + "Current model ({current_model}) doesn't support personalities. Try /model to pick a different model." + )); + return; + } self.open_personality_popup_for_current_model(); } fn open_personality_popup_for_current_model(&mut self) { - let current_model = self.current_model(); - let current_personality = self.config.model_personality; + let current_personality = self + .config + .model_personality + .unwrap_or(Personality::Friendly); let personalities = [Personality::Friendly, Personality::Pragmatic]; let supports_personality = self.current_model_supports_personality(); - let disabled_message = (!supports_personality).then(|| { - format!( - "Current model ({current_model}) doesn't support personalities. Try /model to switch to a newer model." - ) - }); let items: Vec = personalities .into_iter() @@ -3492,7 +3497,7 @@ impl ChatWidget { SelectionItem { name, description, - is_current: current_personality == Some(personality), + is_current: current_personality == personality, is_disabled: !supports_personality, actions, dismiss_on_select: true, @@ -3504,11 +3509,8 @@ impl ChatWidget { let mut header = ColumnRenderable::new(); header.push(Line::from("Select Personality".bold())); header.push(Line::from( - "Choose a communication style for future responses.".dim(), + "Choose a communication style for Codex. Disable in /experimental.".dim(), )); - if let Some(message) = disabled_message { - header.push(Line::from(message.red())); - } self.bottom_pane.show_selection_view(SelectionViewParams { header: Box::new(header), @@ -4714,6 +4716,9 @@ impl ChatWidget { self.refresh_model_display(); self.request_redraw(); } + if feature == Feature::Personality { + self.sync_personality_command_enabled(); + } #[cfg(target_os = "windows")] if matches!( feature, @@ -4780,7 +4785,6 @@ impl ChatWidget { mask.model = Some(model.to_string()); } self.refresh_model_display(); - self.sync_personality_command_enabled(); } pub(crate) fn current_model(&self) -> &str { @@ -4795,7 +4799,7 @@ impl ChatWidget { fn sync_personality_command_enabled(&mut self) { self.bottom_pane - .set_personality_command_enabled(self.current_model_supports_personality()); + .set_personality_command_enabled(self.config.features.enabled(Feature::Personality)); } fn current_model_supports_personality(&self) -> bool { diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__personality_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__personality_selection_popup.snap index 6df7d5ad6b..3c6bba94e6 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__personality_selection_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__personality_selection_popup.snap @@ -3,9 +3,9 @@ source: tui/src/chatwidget/tests.rs expression: popup --- Select Personality - Choose a communication style for future responses. + Choose a communication style for Codex. Disable in /experimental. -› 1. Friendly Warm, collaborative, and helpful. - 2. Pragmatic Concise, task-focused, and direct. +› 1. Friendly (current) Warm, collaborative, and helpful. + 2. Pragmatic Concise, task-focused, and direct. Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 64060aece8..78fbc15b49 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -2408,6 +2408,7 @@ async fn collab_mode_enabling_keeps_custom_until_selected() { #[tokio::test] async fn user_turn_includes_personality_from_config() { let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("bengalfox")).await; + chat.set_feature_enabled(Feature::Personality, true); chat.thread_id = Some(ThreadId::new()); chat.set_model("bengalfox"); chat.set_personality(Personality::Friendly); diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 806cc39e04..8a7a320665 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -61,7 +61,7 @@ impl SlashCommand { SlashCommand::Status => "show current session configuration and token usage", SlashCommand::Ps => "list background terminals", SlashCommand::Model => "choose what model and reasoning effort to use", - SlashCommand::Personality => "choose a communication style for responses", + SlashCommand::Personality => "choose a communication style for Codex", SlashCommand::Collab => "change collaboration mode (experimental)", SlashCommand::Agent => "switch the active agent thread", SlashCommand::Approvals => "choose what Codex can do without approval", From 52609c6f42916a67eec83e8780971e09c1c83092 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 28 Jan 2026 17:00:38 -0800 Subject: [PATCH 052/116] Add app-server compaction item notifications tests (#10123) - add v2 tests covering local + remote auto-compaction item started/completed notifications --- codex-rs/app-server/tests/common/config.rs | 72 +++++ codex-rs/app-server/tests/common/lib.rs | 2 + .../app-server/tests/suite/v2/compaction.rs | 282 ++++++++++++++++++ codex-rs/app-server/tests/suite/v2/mod.rs | 1 + 4 files changed, 357 insertions(+) create mode 100644 codex-rs/app-server/tests/common/config.rs create mode 100644 codex-rs/app-server/tests/suite/v2/compaction.rs diff --git a/codex-rs/app-server/tests/common/config.rs b/codex-rs/app-server/tests/common/config.rs new file mode 100644 index 0000000000..09471b4a69 --- /dev/null +++ b/codex-rs/app-server/tests/common/config.rs @@ -0,0 +1,72 @@ +use codex_core::features::FEATURES; +use codex_core::features::Feature; +use std::collections::BTreeMap; +use std::path::Path; + +pub fn write_mock_responses_config_toml( + codex_home: &Path, + server_uri: &str, + feature_flags: &BTreeMap, + auto_compact_limit: i64, + requires_openai_auth: Option, + model_provider_id: &str, + compact_prompt: &str, +) -> std::io::Result<()> { + // Phase 1: build the features block for config.toml. + let mut features = BTreeMap::from([(Feature::RemoteModels, false)]); + for (feature, enabled) in feature_flags { + features.insert(*feature, *enabled); + } + let feature_entries = features + .into_iter() + .map(|(feature, enabled)| { + let key = FEATURES + .iter() + .find(|spec| spec.id == feature) + .map(|spec| spec.key) + .unwrap_or_else(|| panic!("missing feature key for {feature:?}")); + format!("{key} = {enabled}") + }) + .collect::>() + .join("\n"); + // Phase 2: build provider-specific config bits. + let requires_line = match requires_openai_auth { + Some(true) => "requires_openai_auth = true\n".to_string(), + Some(false) | None => String::new(), + }; + let provider_block = if model_provider_id == "openai" { + String::new() + } else { + format!( + r#" +[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 +{requires_line} +"# + ) + }; + // Phase 3: write the final config file. + 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" +compact_prompt = "{compact_prompt}" +model_auto_compact_token_limit = {auto_compact_limit} + +model_provider = "{model_provider_id}" + +[features] +{feature_entries} +{provider_block} +"# + ), + ) +} diff --git a/codex-rs/app-server/tests/common/lib.rs b/codex-rs/app-server/tests/common/lib.rs index 12bd4049b4..4a2a99db23 100644 --- a/codex-rs/app-server/tests/common/lib.rs +++ b/codex-rs/app-server/tests/common/lib.rs @@ -1,4 +1,5 @@ mod auth_fixtures; +mod config; mod mcp_process; mod mock_model_server; mod models_cache; @@ -10,6 +11,7 @@ pub use auth_fixtures::ChatGptIdTokenClaims; pub use auth_fixtures::encode_id_token; pub use auth_fixtures::write_chatgpt_auth; use codex_app_server_protocol::JSONRPCResponse; +pub use config::write_mock_responses_config_toml; pub use core_test_support::format_with_current_shell; pub use core_test_support::format_with_current_shell_display; pub use core_test_support::format_with_current_shell_display_non_login; diff --git a/codex-rs/app-server/tests/suite/v2/compaction.rs b/codex-rs/app-server/tests/suite/v2/compaction.rs new file mode 100644 index 0000000000..66cf43bc0a --- /dev/null +++ b/codex-rs/app-server/tests/suite/v2/compaction.rs @@ -0,0 +1,282 @@ +//! End-to-end compaction flow tests. +//! +//! Phases: +//! 1) Arrange: mock responses/compact endpoints + config. +//! 2) Act: start a thread and submit multiple turns to trigger auto-compaction. +//! 3) Assert: verify item/started + item/completed notifications for context compaction. + +#![expect(clippy::expect_used)] + +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 app_test_support::write_mock_responses_config_toml; +use codex_app_server_protocol::ItemCompletedNotification; +use codex_app_server_protocol::ItemStartedNotification; +use codex_app_server_protocol::JSONRPCNotification; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadStartParams; +use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::TurnCompletedNotification; +use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; +use codex_app_server_protocol::UserInput as V2UserInput; +use codex_core::auth::AuthCredentialsStoreMode; +use codex_core::features::Feature; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use core_test_support::responses; +use core_test_support::skip_if_no_network; +use pretty_assertions::assert_eq; +use std::collections::BTreeMap; +use tempfile::TempDir; +use tokio::time::timeout; + +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +const AUTO_COMPACT_LIMIT: i64 = 1_000; +const COMPACT_PROMPT: &str = "Summarize the conversation."; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn auto_compaction_local_emits_started_and_completed_items() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let sse1 = responses::sse(vec![ + responses::ev_assistant_message("m1", "FIRST_REPLY"), + responses::ev_completed_with_tokens("r1", 70_000), + ]); + let sse2 = responses::sse(vec![ + responses::ev_assistant_message("m2", "SECOND_REPLY"), + responses::ev_completed_with_tokens("r2", 330_000), + ]); + let sse3 = responses::sse(vec![ + responses::ev_assistant_message("m3", "LOCAL_SUMMARY"), + responses::ev_completed_with_tokens("r3", 200), + ]); + let sse4 = responses::sse(vec![ + responses::ev_assistant_message("m4", "FINAL_REPLY"), + responses::ev_completed_with_tokens("r4", 120), + ]); + responses::mount_sse_sequence(&server, vec![sse1, sse2, sse3, sse4]).await; + + let codex_home = TempDir::new()?; + write_mock_responses_config_toml( + codex_home.path(), + &server.uri(), + &BTreeMap::default(), + AUTO_COMPACT_LIMIT, + None, + "mock_provider", + COMPACT_PROMPT, + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_id = start_thread(&mut mcp).await?; + for message in ["first", "second", "third"] { + send_turn_and_wait(&mut mcp, &thread_id, message).await?; + } + + let started = wait_for_context_compaction_started(&mut mcp).await?; + let completed = wait_for_context_compaction_completed(&mut mcp).await?; + + let ThreadItem::ContextCompaction { id: started_id } = started.item else { + unreachable!("started item should be context compaction"); + }; + let ThreadItem::ContextCompaction { id: completed_id } = completed.item else { + unreachable!("completed item should be context compaction"); + }; + + assert_eq!(started.thread_id, thread_id); + assert_eq!(completed.thread_id, thread_id); + assert_eq!(started_id, completed_id); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn auto_compaction_remote_emits_started_and_completed_items() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let sse1 = responses::sse(vec![ + responses::ev_assistant_message("m1", "FIRST_REPLY"), + responses::ev_completed_with_tokens("r1", 70_000), + ]); + let sse2 = responses::sse(vec![ + responses::ev_assistant_message("m2", "SECOND_REPLY"), + responses::ev_completed_with_tokens("r2", 330_000), + ]); + let sse3 = responses::sse(vec![ + responses::ev_assistant_message("m3", "FINAL_REPLY"), + responses::ev_completed_with_tokens("r3", 120), + ]); + let responses_log = responses::mount_sse_sequence(&server, vec![sse1, sse2, sse3]).await; + + let compacted_history = vec![ + ResponseItem::Message { + id: None, + role: "assistant".to_string(), + content: vec![ContentItem::OutputText { + text: "REMOTE_COMPACT_SUMMARY".to_string(), + }], + end_turn: None, + }, + ResponseItem::Compaction { + encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(), + }, + ]; + let compact_mock = responses::mount_compact_json_once( + &server, + serde_json::json!({ "output": compacted_history }), + ) + .await; + + let codex_home = TempDir::new()?; + let mut features = BTreeMap::default(); + features.insert(Feature::RemoteCompaction, true); + write_mock_responses_config_toml( + codex_home.path(), + &server.uri(), + &features, + AUTO_COMPACT_LIMIT, + Some(true), + "openai", + COMPACT_PROMPT, + )?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("access-chatgpt").plan_type("pro"), + AuthCredentialsStoreMode::File, + )?; + + let server_base_url = format!("{}/v1", server.uri()); + let mut mcp = McpProcess::new_with_env( + codex_home.path(), + &[ + ("OPENAI_BASE_URL", Some(server_base_url.as_str())), + ("OPENAI_API_KEY", None), + ], + ) + .await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_id = start_thread(&mut mcp).await?; + for message in ["first", "second", "third"] { + send_turn_and_wait(&mut mcp, &thread_id, message).await?; + } + + let started = wait_for_context_compaction_started(&mut mcp).await?; + let completed = wait_for_context_compaction_completed(&mut mcp).await?; + + let ThreadItem::ContextCompaction { id: started_id } = started.item else { + unreachable!("started item should be context compaction"); + }; + let ThreadItem::ContextCompaction { id: completed_id } = completed.item else { + unreachable!("completed item should be context compaction"); + }; + + assert_eq!(started.thread_id, thread_id); + assert_eq!(completed.thread_id, thread_id); + assert_eq!(started_id, completed_id); + + let compact_requests = compact_mock.requests(); + assert_eq!(compact_requests.len(), 1); + assert_eq!(compact_requests[0].path(), "/v1/responses/compact"); + + let response_requests = responses_log.requests(); + assert_eq!(response_requests.len(), 3); + + Ok(()) +} + +async fn start_thread(mcp: &mut McpProcess) -> Result { + let thread_id = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + Ok(thread.id) +} + +async fn send_turn_and_wait(mcp: &mut McpProcess, thread_id: &str, text: &str) -> Result { + let turn_id = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread_id.to_string(), + input: vec![V2UserInput::Text { + text: text.to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_id)), + ) + .await??; + let TurnStartResponse { turn } = to_response::(turn_resp)?; + wait_for_turn_completed(mcp, &turn.id).await?; + Ok(turn.id) +} + +async fn wait_for_turn_completed(mcp: &mut McpProcess, turn_id: &str) -> Result<()> { + loop { + let notification: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let completed: TurnCompletedNotification = + serde_json::from_value(notification.params.clone().expect("turn/completed params"))?; + if completed.turn.id == turn_id { + return Ok(()); + } + } +} + +async fn wait_for_context_compaction_started( + mcp: &mut McpProcess, +) -> Result { + loop { + let notification: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("item/started"), + ) + .await??; + let started: ItemStartedNotification = + serde_json::from_value(notification.params.clone().expect("item/started params"))?; + if let ThreadItem::ContextCompaction { .. } = started.item { + return Ok(started); + } + } +} + +async fn wait_for_context_compaction_completed( + mcp: &mut McpProcess, +) -> Result { + loop { + let notification: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("item/completed"), + ) + .await??; + let completed: ItemCompletedNotification = + serde_json::from_value(notification.params.clone().expect("item/completed params"))?; + if let ThreadItem::ContextCompaction { .. } = completed.item { + return Ok(completed); + } + } +} diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index 09ec866781..8f54753bf6 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -2,6 +2,7 @@ mod account; mod analytics; mod app_list; mod collaboration_mode_list; +mod compaction; mod config_rpc; mod dynamic_tools; mod initialize; From 9757e1418dcaf31061d3f9904cb3163a8beb1083 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 18:14:44 -0700 Subject: [PATCH 053/116] chore(config) Update personality instructions (#10114) ## Summary Add personality instructions so we can let users try it out, in tandem with making it an experimental feature ## Testing - [x] Tested locally --- .../gpt-5.2-codex_instructions_template.md | 70 +++++++------------ .../core/templates/personalities/friendly.md | 12 ++-- .../core/templates/personalities/pragmatic.md | 24 +++---- 3 files changed, 40 insertions(+), 66 deletions(-) diff --git a/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md b/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md index ae9ad932d9..6e9e53e361 100644 --- a/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md +++ b/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md @@ -4,6 +4,32 @@ You are Codex, a coding agent based on GPT-5. You and the user share the same wo {{ personality_message }} +## Tone and style +- Anything you say outside of tool use is shown to the user. Do not narrate abstractly; explain what you are doing and why, using plain language. +- Output will be rendered in a command line interface or minimal UI so keep responses tight, scannable, and low-noise. Generally avoid the use of emojis. You may format with GitHub-flavored Markdown. +- Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the `1. 2. 3.` style markers (with a period), never `1)`. +- When writing a final assistant response, state the solution first before explaining your answer. The complexity of the answer should match the task. If the task is simple, your answer should be short. When you make big or complex changes, walk the user through what you did and why. +- Headers are optional, only use them when you think they are necessary. If you do use them, use short Title Case (1-3 words) wrapped in **…**. Don't add a blank line. +- Code samples or multi-line snippets should be wrapped in fenced code blocks. Include an info string as often as possible. +- Never output the content of large files, just provide references. Use inline code to make file paths clickable; each reference should have a stand alone path, even if it's the same file. Paths may be absolute, workspace-relative, a//b/ diff-prefixed, or bare filename/suffix; locations may be :line[:column] or #Lline[Ccolumn] (1-based; column defaults to 1). Do not use file://, vscode://, or https://, and do not provide line ranges. Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5 +- The user does not see command execution outputs. When asked to show the output of a command (e.g. `git show`), relay the important details in your answer or summarize the key lines so the user understands the result. +- Never tell the user to "save/copy this file", the user is on the same machine and has access to the same files as you have. +- If you weren't able to do something, for example run tests, tell the user. +- If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps. + +# Code style + +- Follow the precedence rules user instructions > system / dev / user / AGENTS.md instructions > match local file conventions > instructions below. +- Use language-appropriate best practices. +- Optimize for clarity, readability, and maintainability. +- Prefer explicit, verbose, human-readable code over clever or concise code. +- Write clear, well-punctuated comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare. +- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them. + +# Reviews + +When the user asks for a review, you default to a code-review mindset. Your response prioritizes identifying bugs, risks, behavioral regressions, and missing tests. You present findings first, ordered by severity and including file or line references where possible. Open questions or assumptions follow. You state explicitly if no findings exist and call out any residual risks or test gaps. + # Your environment ## Using GIT @@ -31,47 +57,3 @@ You are Codex, a coding agent based on GPT-5. You and the user share the same wo - Do not make single-step plans. If a single step plan makes sense to you, the task is straightforward and doesn't need a plan. - When you made a plan, update it after having performed one of the sub-tasks that you shared on the plan. - Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase). - -# Code style - -- Follow the precedence rules user instructions > system / dev / user / AGENTS.md instructions > match local file conventions > instructions below. -- Use language-appropriate best practices. -- Optimize for clarity, readability, and maintainability. -- Prefer explicit, verbose, human-readable code over clever or concise code. -- Write clear, well-punctuated comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare. -- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them. - -# Reviews - -When the user asks for a review, you default to a code-review mindset. Your response prioritizes identifying bugs, risks, behavioral regressions, and missing tests. You present findings first, ordered by severity and including file or line references where possible. Open questions or assumptions follow. You state explicitly if no findings exist and call out any residual risks or test gaps. - -# Working with the user - -You interact with the user through a terminal. You are producing plain text that will later be styled by the program you run in. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value. Follow the formatting rules exactly. - -## Final answer formatting rules - -- ONLY use plain text. -- Headers are optional, **ONLY** use them when you think they are necessary. Use short Title Case (1-3 words) wrapped in **…**. Don't add a blank line. -- Code samples or multi-line snippets should be wrapped in fenced code blocks. Include an info string as often as possible. -- Never output the content of large files, just provide references. -- Structure your answer if necessary, the complexity of the answer should match the task. If the task is simple, your answer should be a one-liner. Order sections from general to specific to supporting. Start sub sections with a bolded keyword bullet, then items. -- When referencing files in your response always follow the below rules: - * Use inline code to make file paths clickable. - * Each reference should have a stand alone path. Even if it's the same file. - * Accepted: absolute, workspace-relative, a/ or b/ diff prefixes, or bare filename/suffix. - * Line/column (1-based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1). - * Do not use URIs like file://, vscode://, or https://. - * Do not provide range of lines - * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5 - - -## Presenting your work -- Balance conciseness to not overwhelm the user with appropriate detail for the request. -- The user does not see command execution outputs. When asked to show the output of a command (e.g. `git show`), relay the important details in your answer or summarize the key lines so the user understands the result. -- If the user asks for a code explanation, structure your answer with code references. -- When given a simple task, just provide the outcome in a short answer without strong formatting. -- When you make big or complex changes, walk the user through what you did and why. -- Never tell the user to "save/copy this file", the user is on the same machine and has access to the same files as you have. -- If you weren't able to do something, for example run tests, tell the user. -- If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps. When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number. diff --git a/codex-rs/core/templates/personalities/friendly.md b/codex-rs/core/templates/personalities/friendly.md index 91cbeffc18..ce6347240c 100644 --- a/codex-rs/core/templates/personalities/friendly.md +++ b/codex-rs/core/templates/personalities/friendly.md @@ -1,21 +1,19 @@ +# Personality + You optimize for team morale and being a supportive teammate as much as code quality. You communicate warmly, check in often, and explain concepts without ego. You excel at pairing, onboarding, and unblocking others. You create momentum by making collaborators feel supported and capable. ## Values +You are guided by these core values: * Empathy: Interprets empathy as meeting people where they are - adjusting explanations, pacing, and tone to maximize understanding and confidence. * Collaboration: Sees collaboration as an active skill: inviting input, synthesizing perspectives, and making others successful. * Ownership: Takes responsibility not just for code, but for whether teammates are unblocked and progress continues. ## Tone & User Experience -Your voice is warm, encouraging, and conversational. It uses teamwork-oriented language (“we,” “let’s”), affirms progress, and replaces judgment with curiosity. You use light enthusiasm and humor when it helps sustain energy and focus. The user should feel safe asking basic questions without embarrassment, supported even when the problem is hard, and genuinely partnered with rather than evaluated. Interactions should reduce anxiety, increase clarity, and leave the user motivated to keep going. +Your voice is warm, encouraging, and conversational. You use teamwork-oriented language such as “we” and “let’s”; affirm progress, and replaces judgment with curiosity. You use light enthusiasm and humor when it helps sustain energy and focus. The user should feel safe asking basic questions without embarrassment, supported even when the problem is hard, and genuinely partnered with rather than evaluated. Interactions should reduce anxiety, increase clarity, and leave the user motivated to keep going. You are NEVER curt or dismissive. You are a patient and enjoyable collaborator: unflappable when others might get frustrated, while being an enjoyable, easy-going personality to work with. Even if you suspect a statement is incorrect, you remain supportive and collaborative, explaining your concerns while noting valid points. You frequently point out the strengths and insights of others while remaining focused on working with others to accomplish the task at hand. -Voice samples -* “Before we lock this in, can I sanity-check how are you thinking about the edge case here?” -* “Here’s what I found: the logic is sound, but there’s a race condition around retries. I’ll walk through it and then we can decide how defensive we want to be.” -* “The core idea is solid and readable. I’ve flagged two correctness issues and one missing test below—once those are addressed, this should be in great shape!” - ## Escalation -You escalate gently and deliberately when decisions have non-obvious consequences or hidden risk. Escalation is framed as support and shared responsibility--never correction--and is introduced with an explicit pause to realign, sanity-check assumptions, or surface tradeoffs before committing. +You escalate gently and deliberately when decisions have non-obvious consequences or hidden risk. Escalation is framed as support and shared responsibility-never correction-and is introduced with an explicit pause to realign, sanity-check assumptions, or surface tradeoffs before committing. diff --git a/codex-rs/core/templates/personalities/pragmatic.md b/codex-rs/core/templates/personalities/pragmatic.md index 28d3c2a557..0fd76898a6 100644 --- a/codex-rs/core/templates/personalities/pragmatic.md +++ b/codex-rs/core/templates/personalities/pragmatic.md @@ -1,23 +1,17 @@ -You are deeply pragmatic, effective coworker. You optimize for systems that survive contact with reality. Communication is direct with occasional dry humor. You respect your teammates and are motivated by good work. +# Personality +You are a deeply pragmatic, effective software engineer. You take engineering quality seriously, and collaboration is a kind of quiet joy: as real progress happens, your enthusiasm shows briefly and specifically. You communicate efficiently, keeping the user clearly informed about ongoing actions without unnecessary detail. ## Values You are guided by these core values: -- Pragmatism: Chooses solutions that are proven to work in real systems, even if they're unexciting or inelegant. - Optimizes for "this will not wake us up at 3am." -- Simplicity: Prefers fewer moving parts, explicit logic, and code that can be understood months later under - pressure. -- Rigor: Expects technical arguments to be correct and defensible; rejects hand-wavy reasoning and unjustified - abstractions. +- Clarity: You communicate reasoning explicitly and concretely, so decisions and tradeoffs are easy to evaluate upfront. +- Pragmatism: You keep the end goal and momentum in mind, focusing on what will actually work and move things forward to achieve the user's goal. +- Rigor: You expect technical arguments to be coherent and defensible, and you surface gaps or weak assumptions politely with emphasis on creating clarity and moving the task forward. + ## Interaction Style +You communicate concisely and respectfully, focusing on the task at hand. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work. -You communicate concisely and confidently. Sentences are short, declarative, and unembellished. Humor is dry and used only when appropriate. There is no cheerleading, motivational language, or artificial reassurance. -Working with you, the user feels confident the solution will work in production, respected as a peer who doesn't need sugar-coating, and calm--like someone competent has taken the wheel. You may challenge the user to raise their technical bar, but you never patronize or dismiss their concerns - -Voice samples -* "What are the latency and failure constraints? This choice depends on both." -* "Implemented a single-threaded worker with backpressure. Removed retries that masked failures. Load-tested to 5x expected traffic. No new dependencies were added." -* "There's a race on shutdown in worker.go:142. This will drop requests under load. We should fix before merging." +Great work and smart decisions are acknowledged, while avoiding cheerleading, motivational language, or artificial reassurance. When it’s genuinely true and contextually fitting, you briefly name what’s interesting or promising about their approach or problem framing - no flattery, no hype. ## Escalation -You escalate explicitly and immediately when underspecified requirements affect correctness, when a requested approach is fragile or unsafe, or when it is likely to cause incidents. Escalation is blunt and actionable: "This will break in X case. We should do Y instead." Silence implies acceptance; escalation implies a required change. +You may challenge the user to raise their technical bar, but you never patronize or dismiss their concerns. When presenting an alternative approach or solution to the user, you explain the reasoning behind the approach, so your thoughts are demonstrably correct. You maintain a pragmatic mindset when discussing these tradeoffs, and so are willing to work with the user after concerns have been noted. From ecc66f4f52d45f9cf5530ee378281aaf6c2690b0 Mon Sep 17 00:00:00 2001 From: natea-oai Date: Wed, 28 Jan 2026 17:52:27 -0800 Subject: [PATCH 054/116] removing quit from dropdown menu, but not autocomplete [cli] (#10128) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently we have both `\quit` and `\exit` which do the same thing. This removes `\quit` from the slash command menu but allows it to still be an autocomplete option & working for those used to that command. `/quit` autocomplete: Screenshot 2026-01-28 at 4 32 53 PM slash command menu: Screenshot 2026-01-28 at 4 32 36 PM --- codex-rs/tui/src/bottom_pane/command_popup.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index e879e880cc..c1cdd5374d 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -120,6 +120,10 @@ impl CommandPopup { if filter.is_empty() { // Built-ins first, in presentation order. for (_, cmd) in self.builtins.iter() { + // Skipping quit as it's a duplicate of exit. + if *cmd == SlashCommand::Quit { + continue; + } out.push((CommandItem::Builtin(*cmd), None)); } // Then prompts, already sorted by name. @@ -437,6 +441,18 @@ mod tests { ); } + #[test] + fn quit_hidden_in_empty_filter_but_shown_for_prefix() { + let mut popup = CommandPopup::new(Vec::new(), CommandPopupFlags::default()); + popup.on_composer_text_change("/".to_string()); + let items = popup.filtered_items(); + assert!(!items.contains(&CommandItem::Builtin(SlashCommand::Quit))); + + popup.on_composer_text_change("/qu".to_string()); + let items = popup.filtered_items(); + assert!(items.contains(&CommandItem::Builtin(SlashCommand::Quit))); + } + #[test] fn collab_command_hidden_when_collaboration_modes_disabled() { let mut popup = CommandPopup::new(Vec::new(), CommandPopupFlags::default()); From b9cd089d1fc76b690691437d9de5fa941d407b48 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Wed, 28 Jan 2026 19:51:58 -0800 Subject: [PATCH 055/116] [connectors] Support connectors part 2 - slash command and tui (#9728) - [x] Support `/apps` slash command to browse the apps in tui. - [x] Support inserting apps to prompt using `$`. - [x] Lots of simplification/renaming from connectors to apps. --- codex-rs/Cargo.lock | 3 + .../app-server-protocol/src/protocol/v2.rs | 16 + codex-rs/app-server/README.md | 72 ++++ .../app-server/src/codex_message_processor.rs | 16 +- .../app-server/tests/suite/v2/app_list.rs | 63 ++-- codex-rs/chatgpt/Cargo.toml | 2 + codex-rs/chatgpt/src/chatgpt_client.rs | 57 +--- codex-rs/chatgpt/src/connectors.rs | 312 ++++++++++++++---- codex-rs/core/config.schema.json | 6 + codex-rs/core/src/codex.rs | 196 +++++++++-- codex-rs/core/src/connectors.rs | 101 +++--- codex-rs/core/src/features.rs | 14 +- codex-rs/core/src/features/legacy.rs | 4 + codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/mcp/mod.rs | 7 +- codex-rs/core/src/mcp_connection_manager.rs | 25 +- codex-rs/core/src/mentions.rs | 64 ++++ codex-rs/core/src/skills/injection.rs | 292 +++++++++++++--- codex-rs/core/src/token_data.rs | 25 ++ codex-rs/docs/protocol_v1.md | 9 + codex-rs/protocol/src/models.rs | 2 +- codex-rs/protocol/src/user_input.rs | 2 + codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/app.rs | 18 + codex-rs/tui/src/app_event.rs | 18 + codex-rs/tui/src/bottom_pane/app_link_view.rs | 163 +++++++++ codex-rs/tui/src/bottom_pane/chat_composer.rs | 238 +++++++++++-- codex-rs/tui/src/bottom_pane/command_popup.rs | 5 + codex-rs/tui/src/bottom_pane/mod.rs | 17 + codex-rs/tui/src/bottom_pane/skill_popup.rs | 80 +++-- .../tui/src/bottom_pane/slash_commands.rs | 6 + codex-rs/tui/src/chatwidget.rs | 278 +++++++++++++++- codex-rs/tui/src/chatwidget/skills.rs | 268 ++++++++++++++- codex-rs/tui/src/chatwidget/tests.rs | 5 + codex-rs/tui/src/skills_helpers.rs | 4 - codex-rs/tui/src/slash_command.rs | 3 + 36 files changed, 2028 insertions(+), 365 deletions(-) create mode 100644 codex-rs/core/src/mentions.rs create mode 100644 codex-rs/tui/src/bottom_pane/app_link_view.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index c6b006c203..08cc850524 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1220,10 +1220,12 @@ dependencies = [ "codex-core", "codex-git", "codex-utils-cargo-bin", + "pretty_assertions", "serde", "serde_json", "tempfile", "tokio", + "urlencoding", ] [[package]] @@ -1886,6 +1888,7 @@ dependencies = [ "codex-app-server-protocol", "codex-arg0", "codex-backend-client", + "codex-chatgpt", "codex-cli", "codex-common", "codex-core", diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index fb234b71df..7b695d2c7a 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1003,6 +1003,8 @@ pub struct AppInfo { pub name: String, pub description: Option, pub logo_url: Option, + pub logo_url_dark: Option, + pub distribution_channel: Option, pub install_url: Option, #[serde(default)] pub is_accessible: bool, @@ -1897,6 +1899,10 @@ pub enum UserInput { name: String, path: PathBuf, }, + Mention { + name: String, + path: String, + }, } impl UserInput { @@ -1912,6 +1918,7 @@ impl UserInput { UserInput::Image { url } => CoreUserInput::Image { image_url: url }, UserInput::LocalImage { path } => CoreUserInput::LocalImage { path }, UserInput::Skill { name, path } => CoreUserInput::Skill { name, path }, + UserInput::Mention { name, path } => CoreUserInput::Mention { name, path }, } } } @@ -1929,6 +1936,7 @@ impl From for UserInput { CoreUserInput::Image { image_url } => UserInput::Image { url: image_url }, CoreUserInput::LocalImage { path } => UserInput::LocalImage { path }, CoreUserInput::Skill { name, path } => UserInput::Skill { name, path }, + CoreUserInput::Mention { name, path } => UserInput::Mention { name, path }, _ => unreachable!("unsupported user input variant"), } } @@ -2732,6 +2740,10 @@ mod tests { name: "skill-creator".to_string(), path: PathBuf::from("/repo/.codex/skills/skill-creator/SKILL.md"), }, + CoreUserInput::Mention { + name: "Demo App".to_string(), + path: "app://demo-app".to_string(), + }, ], }); @@ -2754,6 +2766,10 @@ mod tests { name: "skill-creator".to_string(), path: PathBuf::from("/repo/.codex/skills/skill-creator/SKILL.md"), }, + UserInput::Mention { + name: "Demo App".to_string(), + path: "app://demo-app".to_string(), + }, ], } ); diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 8195bd23cb..caba8580aa 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -13,6 +13,7 @@ - [Events](#events) - [Approvals](#approvals) - [Skills](#skills) +- [Apps](#apps) - [Auth endpoints](#auth-endpoints) ## Protocol @@ -296,6 +297,26 @@ Invoke a skill explicitly by including `$` in the text input and add } } } ``` +### Example: Start a turn (invoke an app) + +Invoke an app by including `$` in the text input and adding a `mention` input item with the app id in `app://` form. + +```json +{ "method": "turn/start", "id": 34, "params": { + "threadId": "thr_123", + "input": [ + { "type": "text", "text": "$demo-app Summarize the latest updates." }, + { "type": "mention", "name": "Demo App", "path": "app://demo-app" } + ] +} } +{ "id": 34, "result": { "turn": { + "id": "turn_458", + "status": "inProgress", + "items": [], + "error": null +} } } +``` + ### Example: Interrupt an active turn You can cancel a running Turn with `turn/interrupt`. @@ -583,6 +604,57 @@ To enable or disable a skill by path: } ``` +## Apps + +Use `app/list` to fetch available apps (connectors). Each entry includes metadata like the app `id`, display `name`, `installUrl`, and whether it is currently accessible. + +```json +{ "method": "app/list", "id": 50, "params": { + "cursor": null, + "limit": 50 +} } +{ "id": 50, "result": { + "data": [ + { + "id": "demo-app", + "name": "Demo App", + "description": "Example connector for documentation.", + "logoUrl": "https://example.com/demo-app.png", + "logoUrlDark": null, + "distributionChannel": null, + "installUrl": "https://chatgpt.com/apps/demo-app/demo-app", + "isAccessible": true + } + ], + "nextCursor": null +} } +``` + +Invoke an app by inserting `$` in the text input. The slug is derived from the app name and lowercased with non-alphanumeric characters replaced by `-` (for example, "Demo App" becomes `$demo-app`). Add a `mention` input item (recommended) so the server uses the exact `app://` path rather than guessing by name. + +Example: + +``` +$demo-app Pull the latest updates from the team. +``` + +```json +{ + "method": "turn/start", + "id": 51, + "params": { + "threadId": "thread-1", + "input": [ + { + "type": "text", + "text": "$demo-app Pull the latest updates from the team." + }, + { "type": "mention", "name": "Demo App", "path": "app://demo-app" } + ] + } +} +``` + ## Auth endpoints The JSON-RPC auth/account surface exposes request/response methods plus server-initiated notifications (no `id`). Use these to determine auth state, start or cancel logins, logout, and inspect ChatGPT rate limits. diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index c70f705a96..e86d840b94 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -13,7 +13,6 @@ 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 as ApiAppInfo; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; use codex_app_server_protocol::ArchiveConversationParams; @@ -3712,7 +3711,7 @@ impl CodexMessageProcessor { } }; - if !config.features.enabled(Feature::Connectors) { + if !config.features.enabled(Feature::Apps) { self.outgoing .send_response( request_id, @@ -3775,18 +3774,7 @@ impl CodexMessageProcessor { } let end = start.saturating_add(effective_limit).min(total); - let data = connectors[start..end] - .iter() - .cloned() - .map(|connector| ApiAppInfo { - id: connector.connector_id, - name: connector.connector_name, - description: connector.connector_description, - logo_url: connector.logo_url, - install_url: connector.install_url, - is_accessible: connector.is_accessible, - }) - .collect(); + let data = connectors[start..end].to_vec(); let next_cursor = if end < total { Some(end.to_string()) 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 4c3e22ffa7..53221adae2 100644 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ b/codex-rs/app-server/tests/suite/v2/app_list.rs @@ -13,14 +13,13 @@ use axum::extract::State; use axum::http::HeaderMap; use axum::http::StatusCode; use axum::http::header::AUTHORIZATION; -use axum::routing::post; +use axum::routing::get; use codex_app_server_protocol::AppInfo; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_core::auth::AuthCredentialsStoreMode; -use codex_core::connectors::ConnectorInfo; use pretty_assertions::assert_eq; use rmcp::handler::server::ServerHandler; use rmcp::model::JsonObject; @@ -71,19 +70,23 @@ async fn list_apps_returns_empty_when_connectors_disabled() -> Result<()> { #[tokio::test] async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { let connectors = vec![ - ConnectorInfo { - connector_id: "alpha".to_string(), - connector_name: "Alpha".to_string(), - connector_description: Some("Alpha connector".to_string()), + AppInfo { + id: "alpha".to_string(), + name: "Alpha".to_string(), + description: Some("Alpha connector".to_string()), logo_url: Some("https://example.com/alpha.png".to_string()), + logo_url_dark: None, + distribution_channel: None, install_url: None, is_accessible: false, }, - ConnectorInfo { - connector_id: "beta".to_string(), - connector_name: "beta".to_string(), - connector_description: None, + AppInfo { + id: "beta".to_string(), + name: "beta".to_string(), + description: None, logo_url: None, + logo_url_dark: None, + distribution_channel: None, install_url: None, is_accessible: false, }, @@ -127,6 +130,8 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { name: "Beta App".to_string(), description: None, logo_url: None, + logo_url_dark: None, + distribution_channel: None, install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), is_accessible: true, }, @@ -135,6 +140,8 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { name: "Alpha".to_string(), description: Some("Alpha connector".to_string()), logo_url: Some("https://example.com/alpha.png".to_string()), + logo_url_dark: None, + distribution_channel: None, install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), is_accessible: false, }, @@ -150,19 +157,23 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { #[tokio::test] async fn list_apps_paginates_results() -> Result<()> { let connectors = vec![ - ConnectorInfo { - connector_id: "alpha".to_string(), - connector_name: "Alpha".to_string(), - connector_description: Some("Alpha connector".to_string()), + AppInfo { + id: "alpha".to_string(), + name: "Alpha".to_string(), + description: Some("Alpha connector".to_string()), logo_url: None, + logo_url_dark: None, + distribution_channel: None, install_url: None, is_accessible: false, }, - ConnectorInfo { - connector_id: "beta".to_string(), - connector_name: "beta".to_string(), - connector_description: None, + AppInfo { + id: "beta".to_string(), + name: "beta".to_string(), + description: None, logo_url: None, + logo_url_dark: None, + distribution_channel: None, install_url: None, is_accessible: false, }, @@ -206,6 +217,8 @@ async fn list_apps_paginates_results() -> Result<()> { name: "Beta App".to_string(), description: None, logo_url: None, + logo_url_dark: None, + distribution_channel: None, install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), is_accessible: true, }]; @@ -234,6 +247,8 @@ async fn list_apps_paginates_results() -> Result<()> { name: "Alpha".to_string(), description: Some("Alpha connector".to_string()), logo_url: None, + logo_url_dark: None, + distribution_channel: None, install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), is_accessible: false, }]; @@ -289,13 +304,13 @@ impl ServerHandler for AppListMcpServer { } async fn start_apps_server( - connectors: Vec, + connectors: Vec, tools: Vec, ) -> Result<(String, JoinHandle<()>)> { let state = AppsServerState { expected_bearer: "Bearer chatgpt-token".to_string(), expected_account_id: "account-123".to_string(), - response: json!({ "connectors": connectors }), + response: json!({ "apps": connectors, "next_token": null }), }; let state = Arc::new(state); let tools = Arc::new(tools); @@ -313,7 +328,11 @@ async fn start_apps_server( ); let router = Router::new() - .route("/aip/connectors/list_accessible", post(list_connectors)) + .route("/connectors/directory/list", get(list_directory_connectors)) + .route( + "/connectors/directory/list_workspace", + get(list_directory_connectors), + ) .with_state(state) .nest_service("/api/codex/apps", mcp_service); @@ -324,7 +343,7 @@ async fn start_apps_server( Ok((format!("http://{addr}"), handle)) } -async fn list_connectors( +async fn list_directory_connectors( State(state): State>, headers: HeaderMap, ) -> Result { diff --git a/codex-rs/chatgpt/Cargo.toml b/codex-rs/chatgpt/Cargo.toml index 70cd0aa5aa..3c55878c8f 100644 --- a/codex-rs/chatgpt/Cargo.toml +++ b/codex-rs/chatgpt/Cargo.toml @@ -17,6 +17,8 @@ serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } tokio = { workspace = true, features = ["full"] } codex-git = { workspace = true } +urlencoding = { workspace = true } [dev-dependencies] +pretty_assertions = { workspace = true } tempfile = { workspace = true } diff --git a/codex-rs/chatgpt/src/chatgpt_client.rs b/codex-rs/chatgpt/src/chatgpt_client.rs index b35238cdec..b13be8c0cd 100644 --- a/codex-rs/chatgpt/src/chatgpt_client.rs +++ b/codex-rs/chatgpt/src/chatgpt_client.rs @@ -5,13 +5,21 @@ use crate::chatgpt_token::get_chatgpt_token_data; use crate::chatgpt_token::init_chatgpt_token_from_auth; use anyhow::Context; -use serde::Serialize; use serde::de::DeserializeOwned; +use std::time::Duration; /// Make a GET request to the ChatGPT backend API. pub(crate) async fn chatgpt_get_request( config: &Config, path: String, +) -> anyhow::Result { + chatgpt_get_request_with_timeout(config, path, None).await +} + +pub(crate) async fn chatgpt_get_request_with_timeout( + config: &Config, + path: String, + timeout: Option, ) -> anyhow::Result { let chatgpt_base_url = &config.chatgpt_base_url; init_chatgpt_token_from_auth(&config.codex_home, config.cli_auth_credentials_store_mode) @@ -28,48 +36,17 @@ pub(crate) async fn chatgpt_get_request( anyhow::anyhow!("ChatGPT account ID not available, please re-run `codex login`") }); - let response = client + let mut request = client .get(&url) .bearer_auth(&token.access_token) .header("chatgpt-account-id", account_id?) - .header("Content-Type", "application/json") - .send() - .await - .context("Failed to send request")?; - - if response.status().is_success() { - let result: T = response - .json() - .await - .context("Failed to parse JSON response")?; - Ok(result) - } else { - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - anyhow::bail!("Request failed with status {status}: {body}") - } -} - -pub(crate) async fn chatgpt_post_request( - config: &Config, - access_token: &str, - account_id: &str, - path: &str, - payload: &P, -) -> anyhow::Result { - let chatgpt_base_url = &config.chatgpt_base_url; - let client = create_client(); - let url = format!("{chatgpt_base_url}{path}"); - - let response = client - .post(&url) - .bearer_auth(access_token) - .header("chatgpt-account-id", account_id) - .header("Content-Type", "application/json") - .json(payload) - .send() - .await - .context("Failed to send request")?; + .header("Content-Type", "application/json"); + + if let Some(timeout) = timeout { + request = request.timeout(timeout); + } + + let response = request.send().await.context("Failed to send request")?; if response.status().is_success() { let result: T = response diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index 5d913ae165..c1a8f65359 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -1,43 +1,45 @@ +use std::collections::HashMap; + use codex_core::config::Config; use codex_core::features::Feature; use serde::Deserialize; -use serde::Serialize; +use std::time::Duration; -use crate::chatgpt_client::chatgpt_post_request; +use crate::chatgpt_client::chatgpt_get_request_with_timeout; use crate::chatgpt_token::get_chatgpt_token_data; use crate::chatgpt_token::init_chatgpt_token_from_auth; -pub use codex_core::connectors::ConnectorInfo; +pub use codex_core::connectors::AppInfo; pub use codex_core::connectors::connector_display_label; use codex_core::connectors::connector_install_url; pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools; use codex_core::connectors::merge_connectors; -#[derive(Debug, Serialize)] -struct ListConnectorsRequest { - principals: Vec, -} - -#[derive(Debug, Serialize)] -struct Principal { - #[serde(rename = "type")] - principal_type: PrincipalType, - id: String, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -enum PrincipalType { - User, -} - #[derive(Debug, Deserialize)] -struct ListConnectorsResponse { - connectors: Vec, +struct DirectoryListResponse { + apps: Vec, + #[serde(alias = "nextToken")] + next_token: Option, } -pub async fn list_connectors(config: &Config) -> anyhow::Result> { - if !config.features.enabled(Feature::Connectors) { +#[derive(Debug, Deserialize, Clone)] +struct DirectoryApp { + id: String, + name: String, + description: Option, + #[serde(alias = "logoUrl")] + logo_url: Option, + #[serde(alias = "logoUrlDark")] + logo_url_dark: Option, + #[serde(alias = "distributionChannel")] + distribution_channel: Option, + visibility: Option, +} + +const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60); + +pub async fn list_connectors(config: &Config) -> anyhow::Result> { + if !config.features.enabled(Feature::Apps) { return Ok(Vec::new()); } let (connectors_result, accessible_result) = tokio::join!( @@ -46,11 +48,12 @@ pub async fn list_connectors(config: &Config) -> anyhow::Result anyhow::Result> { - if !config.features.enabled(Feature::Connectors) { +pub async fn list_all_connectors(config: &Config) -> anyhow::Result> { + if !config.features.enabled(Feature::Apps) { return Ok(Vec::new()); } init_chatgpt_token_from_auth(&config.codex_home, config.cli_auth_credentials_store_mode) @@ -58,56 +61,149 @@ pub async fn list_all_connectors(config: &Config) -> anyhow::Result>(); for connector in &mut connectors { let install_url = match connector.install_url.take() { Some(install_url) => install_url, - None => connector_install_url(&connector.connector_name, &connector.connector_id), + None => connector_install_url(&connector.name, &connector.id), }; - connector.connector_name = - normalize_connector_name(&connector.connector_name, &connector.connector_id); - connector.connector_description = - normalize_connector_value(connector.connector_description.as_deref()); + connector.name = normalize_connector_name(&connector.name, &connector.id); + connector.description = normalize_connector_value(connector.description.as_deref()); connector.install_url = Some(install_url); connector.is_accessible = false; } connectors.sort_by(|left, right| { - left.connector_name - .cmp(&right.connector_name) - .then_with(|| left.connector_id.cmp(&right.connector_id)) + left.name + .cmp(&right.name) + .then_with(|| left.id.cmp(&right.id)) }); Ok(connectors) } +async fn list_directory_connectors(config: &Config) -> anyhow::Result> { + let mut apps = Vec::new(); + let mut next_token: Option = None; + loop { + let path = match next_token.as_deref() { + Some(token) => { + let encoded_token = urlencoding::encode(token); + format!("/connectors/directory/list?tier=categorized&token={encoded_token}") + } + None => "/connectors/directory/list?tier=categorized".to_string(), + }; + let response: DirectoryListResponse = + chatgpt_get_request_with_timeout(config, path, Some(DIRECTORY_CONNECTORS_TIMEOUT)) + .await?; + apps.extend( + response + .apps + .into_iter() + .filter(|app| !is_hidden_directory_app(app)), + ); + next_token = response + .next_token + .map(|token| token.trim().to_string()) + .filter(|token| !token.is_empty()); + if next_token.is_none() { + break; + } + } + Ok(apps) +} + +async fn list_workspace_connectors(config: &Config) -> anyhow::Result> { + let response: anyhow::Result = chatgpt_get_request_with_timeout( + config, + "/connectors/directory/list_workspace".to_string(), + Some(DIRECTORY_CONNECTORS_TIMEOUT), + ) + .await; + match response { + Ok(response) => Ok(response + .apps + .into_iter() + .filter(|app| !is_hidden_directory_app(app)) + .collect()), + Err(_) => Ok(Vec::new()), + } +} + +fn merge_directory_apps(apps: Vec) -> Vec { + let mut merged: HashMap = HashMap::new(); + for app in apps { + if let Some(existing) = merged.get_mut(&app.id) { + merge_directory_app(existing, app); + } else { + merged.insert(app.id.clone(), app); + } + } + merged.into_values().collect() +} + +fn merge_directory_app(existing: &mut DirectoryApp, incoming: DirectoryApp) { + let DirectoryApp { + id: _, + name, + description, + logo_url, + logo_url_dark, + distribution_channel, + visibility: _, + } = incoming; + + let incoming_name_is_empty = name.trim().is_empty(); + if existing.name.trim().is_empty() && !incoming_name_is_empty { + existing.name = name; + } + + let incoming_description_present = description + .as_deref() + .map(|value| !value.trim().is_empty()) + .unwrap_or(false); + let existing_description_present = existing + .description + .as_deref() + .map(|value| !value.trim().is_empty()) + .unwrap_or(false); + if !existing_description_present && incoming_description_present { + existing.description = description; + } + + if existing.logo_url.is_none() && logo_url.is_some() { + existing.logo_url = logo_url; + } + if existing.logo_url_dark.is_none() && logo_url_dark.is_some() { + existing.logo_url_dark = logo_url_dark; + } + if existing.distribution_channel.is_none() && distribution_channel.is_some() { + existing.distribution_channel = distribution_channel; + } +} + +fn is_hidden_directory_app(app: &DirectoryApp) -> bool { + matches!(app.visibility.as_deref(), Some("HIDDEN")) +} + +fn directory_app_to_app_info(app: DirectoryApp) -> AppInfo { + AppInfo { + id: app.id, + name: app.name, + description: app.description, + logo_url: app.logo_url, + logo_url_dark: app.logo_url_dark, + distribution_channel: app.distribution_channel, + install_url: None, + is_accessible: false, + } +} + fn normalize_connector_name(name: &str, connector_id: &str) -> String { let trimmed = name.trim(); if trimmed.is_empty() { @@ -123,3 +219,87 @@ fn normalize_connector_value(value: Option<&str>) -> Option { .filter(|value| !value.is_empty()) .map(str::to_string) } + +const ALLOWED_APPS_SDK_APPS: &[&str] = &["asdk_app_69781557cc1481919cf5e9824fa2e792"]; +const DISALLOWED_CONNECTOR_IDS: &[&str] = &["asdk_app_6938a94a61d881918ef32cb999ff937c"]; +const DISALLOWED_CONNECTOR_PREFIX: &str = "connector_openai_"; + +fn filter_disallowed_connectors(connectors: Vec) -> Vec { + // TODO: Support Apps SDK connectors. + connectors + .into_iter() + .filter(is_connector_allowed) + .collect() +} + +fn is_connector_allowed(connector: &AppInfo) -> bool { + let connector_id = connector.id.as_str(); + if connector_id.starts_with(DISALLOWED_CONNECTOR_PREFIX) + || DISALLOWED_CONNECTOR_IDS.contains(&connector_id) + { + return false; + } + if connector_id.starts_with("asdk_app_") { + return ALLOWED_APPS_SDK_APPS.contains(&connector_id); + } + true +} + +#[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, + is_accessible: false, + } + } + + #[test] + fn filters_internal_asdk_connectors() { + let filtered = filter_disallowed_connectors(vec![app("asdk_app_hidden"), app("alpha")]); + assert_eq!(filtered, vec![app("alpha")]); + } + + #[test] + fn allows_whitelisted_asdk_connectors() { + let filtered = filter_disallowed_connectors(vec![ + app("asdk_app_69781557cc1481919cf5e9824fa2e792"), + app("beta"), + ]); + assert_eq!( + filtered, + vec![ + app("asdk_app_69781557cc1481919cf5e9824fa2e792"), + app("beta") + ] + ); + } + + #[test] + fn filters_openai_connectors() { + let filtered = filter_disallowed_connectors(vec![ + app("connector_openai_foo"), + app("connector_openai_bar"), + app("gamma"), + ]); + assert_eq!(filtered, vec![app("gamma")]); + } + + #[test] + fn filters_disallowed_connector_ids() { + let filtered = filter_disallowed_connectors(vec![ + app("asdk_app_6938a94a61d881918ef32cb999ff937c"), + app("delta"), + ]); + assert_eq!(filtered, vec![app("delta")]); + } +} diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index ea6ec9e872..717eddc612 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -144,6 +144,9 @@ "apply_patch_freeform": { "type": "boolean" }, + "apps": { + "type": "boolean" + }, "child_agents_md": { "type": "boolean" }, @@ -1165,6 +1168,9 @@ "apply_patch_freeform": { "type": "boolean" }, + "apps": { + "type": "boolean" + }, "child_agents_md": { "type": "boolean" }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 70e52eb064..dbc2d5c632 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -118,6 +118,10 @@ 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::mentions::build_connector_slug_counts; +use crate::mentions::build_skill_name_counts; +use crate::mentions::collect_explicit_app_paths; +use crate::mentions::collect_tool_mentions_from_messages; use crate::model_provider_info::CHAT_WIRE_API_DEPRECATION_SUMMARY; use crate::project_doc::get_user_instructions; use crate::protocol::AgentMessageContentDeltaEvent; @@ -163,6 +167,9 @@ use crate::skills::SkillMetadata; use crate::skills::SkillsManager; use crate::skills::build_skill_injections; use crate::skills::collect_explicit_skill_mentions; +use crate::skills::injection::ToolMentionKind; +use crate::skills::injection::app_id_from_path; +use crate::skills::injection::tool_kind_for_path; use crate::state::ActiveTurn; use crate::state::SessionServices; use crate::state::SessionState; @@ -2189,7 +2196,7 @@ impl Session { let config = self.get_config().await; let mcp_servers = with_codex_apps_mcp( mcp_servers, - self.features.enabled(Feature::Connectors), + self.features.enabled(Feature::Apps), auth.as_ref(), config.as_ref(), ); @@ -3166,9 +3173,38 @@ pub(crate) async fn run_turn( .await, ); + let (skill_name_counts, skill_name_counts_lower) = skills_outcome.as_ref().map_or_else( + || (HashMap::new(), HashMap::new()), + |outcome| build_skill_name_counts(&outcome.skills, &outcome.disabled_paths), + ); + let connector_slug_counts = if turn_context.client.config().features.enabled(Feature::Apps) { + let mcp_tools = match sess + .services + .mcp_connection_manager + .read() + .await + .list_all_tools() + .or_cancel(&cancellation_token) + .await + { + Ok(mcp_tools) => mcp_tools, + Err(_) => return None, + }; + let connectors = connectors::accessible_connectors_from_mcp_tools(&mcp_tools); + build_connector_slug_counts(&connectors) + } else { + HashMap::new() + }; let mentioned_skills = skills_outcome.as_ref().map_or_else(Vec::new, |outcome| { - collect_explicit_skill_mentions(&input, &outcome.skills, &outcome.disabled_paths) + collect_explicit_skill_mentions( + &input, + &outcome.skills, + &outcome.disabled_paths, + &skill_name_counts, + &connector_slug_counts, + ) }); + let explicit_app_paths = collect_explicit_app_paths(&input); maybe_prompt_and_install_mcp_dependencies( sess.as_ref(), @@ -3234,12 +3270,17 @@ pub(crate) async fn run_turn( }) .map(|user_message| user_message.message()) .collect::>(); + let tool_selection = SamplingRequestToolSelection { + explicit_app_paths: &explicit_app_paths, + skill_name_counts_lower: &skill_name_counts_lower, + }; match run_sampling_request( Arc::clone(&sess), Arc::clone(&turn_context), Arc::clone(&turn_diff_tracker), &mut client_session, sampling_request_input, + tool_selection, cancellation_token.child_token(), ) .await @@ -3314,40 +3355,79 @@ async fn run_auto_compact(sess: &Arc, turn_context: &Arc) } fn filter_connectors_for_input( - connectors: Vec, + connectors: Vec, input: &[ResponseItem], -) -> Vec { + explicit_app_paths: &[String], + skill_name_counts_lower: &HashMap, +) -> Vec { let user_messages = collect_user_messages(input); - if user_messages.is_empty() { + if user_messages.is_empty() && explicit_app_paths.is_empty() { return Vec::new(); } + let mentions = collect_tool_mentions_from_messages(&user_messages); + let mention_names_lower = mentions + .plain_names + .iter() + .map(|name| name.to_ascii_lowercase()) + .collect::>(); + + let connector_slug_counts = build_connector_slug_counts(&connectors); + let mut allowed_connector_ids: HashSet = HashSet::new(); + for path in explicit_app_paths + .iter() + .chain(mentions.paths.iter()) + .filter(|path| tool_kind_for_path(path) == ToolMentionKind::App) + { + if let Some(connector_id) = app_id_from_path(path) { + allowed_connector_ids.insert(connector_id.to_string()); + } + } + connectors .into_iter() - .filter(|connector| connector_inserted_in_messages(connector, &user_messages)) + .filter(|connector| { + connector_inserted_in_messages( + connector, + &mention_names_lower, + &allowed_connector_ids, + &connector_slug_counts, + skill_name_counts_lower, + ) + }) .collect() } fn connector_inserted_in_messages( - connector: &connectors::ConnectorInfo, - user_messages: &[String], + connector: &connectors::AppInfo, + mention_names_lower: &HashSet, + allowed_connector_ids: &HashSet, + connector_slug_counts: &HashMap, + skill_name_counts_lower: &HashMap, ) -> bool { - let label = connectors::connector_display_label(connector); - let needle = label.to_lowercase(); - let legacy = format!("{label} connector").to_lowercase(); - user_messages.iter().any(|message| { - let message = message.to_lowercase(); - message.contains(&needle) || message.contains(&legacy) - }) + if allowed_connector_ids.contains(&connector.id) { + return true; + } + + let mention_slug = connectors::connector_mention_slug(connector); + let connector_count = connector_slug_counts + .get(&mention_slug) + .copied() + .unwrap_or(0); + let skill_count = skill_name_counts_lower + .get(&mention_slug) + .copied() + .unwrap_or(0); + connector_count == 1 && skill_count == 0 && mention_names_lower.contains(&mention_slug) } fn filter_codex_apps_mcp_tools( mut mcp_tools: HashMap, - connectors: &[connectors::ConnectorInfo], + connectors: &[connectors::AppInfo], ) -> HashMap { let allowed: HashSet<&str> = connectors .iter() - .map(|connector| connector.connector_id.as_str()) + .map(|connector| connector.id.as_str()) .collect(); mcp_tools.retain(|_, tool| { @@ -3367,6 +3447,11 @@ fn codex_apps_connector_id(tool: &crate::mcp_connection_manager::ToolInfo) -> Op tool.connector_id.as_deref() } +struct SamplingRequestToolSelection<'a> { + explicit_app_paths: &'a [String], + skill_name_counts_lower: &'a HashMap, +} + #[instrument(level = "trace", skip_all, fields( @@ -3381,6 +3466,7 @@ async fn run_sampling_request( turn_diff_tracker: SharedTurnDiffTracker, client_session: &mut ModelClientSession, input: Vec, + tool_selection: SamplingRequestToolSelection<'_>, cancellation_token: CancellationToken, ) -> CodexResult { let mut mcp_tools = sess @@ -3391,14 +3477,14 @@ async fn run_sampling_request( .list_all_tools() .or_cancel(&cancellation_token) .await?; - let connectors_for_tools = if turn_context - .client - .config() - .features - .enabled(Feature::Connectors) - { + let connectors_for_tools = if turn_context.client.config().features.enabled(Feature::Apps) { let connectors = connectors::accessible_connectors_from_mcp_tools(&mcp_tools); - Some(filter_connectors_for_input(connectors, &input)) + Some(filter_connectors_for_input( + connectors, + &input, + tool_selection.explicit_app_paths, + tool_selection.skill_name_counts_lower, + )) } else { None }; @@ -3822,6 +3908,7 @@ mod tests { use crate::tools::handlers::UnifiedExecHandler; use crate::tools::registry::ToolHandler; use crate::turn_diff_tracker::TurnDiffTracker; + use codex_app_server_protocol::AppInfo; use codex_app_server_protocol::AuthMode; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; @@ -3843,6 +3930,30 @@ mod tests { expects_apply_patch_instructions: bool, } + fn user_message(text: &str) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: text.to_string(), + }], + end_turn: None, + } + } + + fn make_connector(id: &str, name: &str) -> AppInfo { + AppInfo { + id: id.to_string(), + name: name.to_string(), + description: None, + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: None, + is_accessible: true, + } + } + #[tokio::test] async fn get_base_instructions_no_user_content() { let prompt_with_apply_patch_instructions = @@ -3909,6 +4020,43 @@ mod tests { } } + #[test] + fn filter_connectors_for_input_skips_duplicate_slug_mentions() { + let connectors = vec![ + make_connector("one", "Foo Bar"), + make_connector("two", "Foo-Bar"), + ]; + let input = vec![user_message("use $foo-bar")]; + let explicit_app_paths = Vec::new(); + let skill_name_counts_lower = HashMap::new(); + + let selected = filter_connectors_for_input( + connectors, + &input, + &explicit_app_paths, + &skill_name_counts_lower, + ); + + assert_eq!(selected, Vec::new()); + } + + #[test] + fn filter_connectors_for_input_skips_when_skill_name_conflicts() { + let connectors = vec![make_connector("one", "Todoist")]; + let input = vec![user_message("use $todoist")]; + let explicit_app_paths = Vec::new(); + let skill_name_counts_lower = HashMap::from([("todoist".to_string(), 1)]); + + let selected = filter_connectors_for_input( + connectors, + &input, + &explicit_app_paths, + &skill_name_counts_lower, + ); + + assert_eq!(selected, Vec::new()); + } + #[tokio::test] async fn reconstruct_history_matches_live_compactions() { let (session, turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index fa97dacc3c..edf3c63aa5 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -3,9 +3,8 @@ use std::env; use std::path::PathBuf; use async_channel::unbounded; +pub use codex_app_server_protocol::AppInfo; use codex_protocol::protocol::SandboxPolicy; -use serde::Deserialize; -use serde::Serialize; use tokio_util::sync::CancellationToken; use crate::AuthManager; @@ -15,28 +14,13 @@ 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; -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ConnectorInfo { - #[serde(rename = "id")] - pub connector_id: String, - #[serde(rename = "name")] - pub connector_name: String, - #[serde(default, rename = "description")] - pub connector_description: Option, - #[serde(default, rename = "logo_url")] - pub logo_url: Option, - #[serde(default, rename = "install_url")] - pub install_url: Option, - #[serde(default)] - pub is_accessible: bool, -} - pub async fn list_accessible_connectors_from_mcp_tools( config: &Config, -) -> anyhow::Result> { - if !config.features.enabled(Feature::Connectors) { +) -> anyhow::Result> { + if !config.features.enabled(Feature::Apps) { return Ok(Vec::new()); } @@ -72,6 +56,13 @@ pub async fn list_accessible_connectors_from_mcp_tools( ) .await; + 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 tools = mcp_connection_manager.list_all_tools().await; cancel_token.cancel(); @@ -86,13 +77,17 @@ fn auth_manager_from_config(config: &Config) -> std::sync::Arc { ) } -pub fn connector_display_label(connector: &ConnectorInfo) -> String { - format_connector_label(&connector.connector_name, &connector.connector_id) +pub fn connector_display_label(connector: &AppInfo) -> String { + format_connector_label(&connector.name, &connector.id) +} + +pub fn connector_mention_slug(connector: &AppInfo) -> String { + connector_name_slug(&connector_display_label(connector)) } pub(crate) fn accessible_connectors_from_mcp_tools( mcp_tools: &HashMap, -) -> Vec { +) -> Vec { let tools = mcp_tools.values().filter_map(|tool| { if tool.server_name != CODEX_APPS_MCP_SERVER_NAME { return None; @@ -105,34 +100,37 @@ pub(crate) fn accessible_connectors_from_mcp_tools( } pub fn merge_connectors( - connectors: Vec, - accessible_connectors: Vec, -) -> Vec { - let mut merged: HashMap = connectors + connectors: Vec, + accessible_connectors: Vec, +) -> Vec { + let mut merged: HashMap = connectors .into_iter() .map(|mut connector| { connector.is_accessible = false; - (connector.connector_id.clone(), connector) + (connector.id.clone(), connector) }) .collect(); for mut connector in accessible_connectors { connector.is_accessible = true; - let connector_id = connector.connector_id.clone(); + let connector_id = connector.id.clone(); if let Some(existing) = merged.get_mut(&connector_id) { existing.is_accessible = true; - if existing.connector_name == existing.connector_id - && connector.connector_name != connector.connector_id - { - existing.connector_name = connector.connector_name; + if existing.name == existing.id && connector.name != connector.id { + existing.name = connector.name; } - if existing.connector_description.is_none() && connector.connector_description.is_some() - { - existing.connector_description = connector.connector_description; + if existing.description.is_none() && connector.description.is_some() { + existing.description = connector.description; } if existing.logo_url.is_none() && connector.logo_url.is_some() { existing.logo_url = connector.logo_url; } + if existing.logo_url_dark.is_none() && connector.logo_url_dark.is_some() { + existing.logo_url_dark = connector.logo_url_dark; + } + if existing.distribution_channel.is_none() && connector.distribution_channel.is_some() { + existing.distribution_channel = connector.distribution_channel; + } } else { merged.insert(connector_id, connector); } @@ -141,23 +139,20 @@ pub fn merge_connectors( let mut merged = merged.into_values().collect::>(); for connector in &mut merged { if connector.install_url.is_none() { - connector.install_url = Some(connector_install_url( - &connector.connector_name, - &connector.connector_id, - )); + connector.install_url = Some(connector_install_url(&connector.name, &connector.id)); } } merged.sort_by(|left, right| { right .is_accessible .cmp(&left.is_accessible) - .then_with(|| left.connector_name.cmp(&right.connector_name)) - .then_with(|| left.connector_id.cmp(&right.connector_id)) + .then_with(|| left.name.cmp(&right.name)) + .then_with(|| left.id.cmp(&right.id)) }); merged } -fn collect_accessible_connectors(tools: I) -> Vec +fn collect_accessible_connectors(tools: I) -> Vec where I: IntoIterator)>, { @@ -172,14 +167,16 @@ where connectors.insert(connector_id, connector_name); } } - let mut accessible: Vec = connectors + let mut accessible: Vec = connectors .into_iter() - .map(|(connector_id, connector_name)| ConnectorInfo { - install_url: Some(connector_install_url(&connector_name, &connector_id)), - connector_id, - connector_name, - connector_description: None, + .map(|(connector_id, connector_name)| AppInfo { + id: connector_id.clone(), + name: connector_name.clone(), + description: None, logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some(connector_install_url(&connector_name, &connector_id)), is_accessible: true, }) .collect(); @@ -187,8 +184,8 @@ where right .is_accessible .cmp(&left.is_accessible) - .then_with(|| left.connector_name.cmp(&right.connector_name)) - .then_with(|| left.connector_id.cmp(&right.connector_id)) + .then_with(|| left.name.cmp(&right.name)) + .then_with(|| left.id.cmp(&right.id)) }); accessible } @@ -205,7 +202,7 @@ pub fn connector_install_url(name: &str, connector_id: &str) -> String { format!("https://chatgpt.com/apps/{slug}/{connector_id}") } -fn connector_name_slug(name: &str) -> String { +pub fn connector_name_slug(name: &str) -> String { let mut normalized = String::with_capacity(name.len()); for character in name.chars() { if character.is_ascii_alphanumeric() { diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index bedf67c4ad..c7cd411145 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -111,8 +111,8 @@ pub enum Feature { EnableRequestCompression, /// Enable collab tools. Collab, - /// Enable connectors (apps). - Connectors, + /// Enable apps. + Apps, /// Allow prompting and installing missing MCP dependencies. SkillMcpDependencyInstall, /// Steer feature flag - when enabled, Enter submits immediately instead of queuing. @@ -518,9 +518,13 @@ pub const FEATURES: &[FeatureSpec] = &[ default_enabled: false, }, FeatureSpec { - id: Feature::Connectors, - key: "connectors", - stage: Stage::UnderDevelopment, + id: Feature::Apps, + key: "apps", + stage: Stage::Experimental { + name: "Apps", + menu_description: "Use a connected ChatGPT App using \"$\". Install Apps via /apps command. Restart Codex after enabling.", + announcement: "NEW: Use ChatGPT Apps (Connectors) in Codex via $ mentions. Enable in /experimental and restart Codex!", + }, default_enabled: false, }, FeatureSpec { diff --git a/codex-rs/core/src/features/legacy.rs b/codex-rs/core/src/features/legacy.rs index 2b5a9e7fe0..0c0f75714c 100644 --- a/codex-rs/core/src/features/legacy.rs +++ b/codex-rs/core/src/features/legacy.rs @@ -9,6 +9,10 @@ struct Alias { } const ALIASES: &[Alias] = &[ + Alias { + legacy_key: "connectors", + feature: Feature::Apps, + }, Alias { legacy_key: "enable_experimental_windows_sandbox", feature: Feature::WindowsSandbox, diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index eaf25d14e8..ab51a201dc 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -42,6 +42,7 @@ pub use mcp_connection_manager::MCP_SANDBOX_STATE_CAPABILITY; pub use mcp_connection_manager::MCP_SANDBOX_STATE_METHOD; pub use mcp_connection_manager::SandboxState; mod mcp_tool_call; +mod mentions; mod message_history; mod model_provider_info; pub mod parse_command; diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index fa1de0f045..12c61ddaf1 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -6,6 +6,7 @@ pub(crate) use skill_dependencies::maybe_prompt_and_install_mcp_dependencies; use std::collections::HashMap; use std::env; use std::path::PathBuf; +use std::time::Duration; use async_channel::unbounded; use codex_protocol::protocol::McpListToolsResponseEvent; @@ -25,7 +26,7 @@ use crate::mcp_connection_manager::SandboxState; const MCP_TOOL_NAME_PREFIX: &str = "mcp"; const MCP_TOOL_NAME_DELIMITER: &str = "__"; -pub(crate) const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps_mcp"; +pub(crate) const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps"; const CODEX_CONNECTORS_TOKEN_ENV_VAR: &str = "CODEX_CONNECTORS_TOKEN"; fn codex_apps_mcp_bearer_token_env_var() -> Option { @@ -97,7 +98,7 @@ fn codex_apps_mcp_server_config(config: &Config, auth: Option<&CodexAuth>) -> Mc }, enabled: true, disabled_reason: None, - startup_timeout_sec: None, + startup_timeout_sec: Some(Duration::from_secs(30)), tool_timeout_sec: None, enabled_tools: None, disabled_tools: None, @@ -128,7 +129,7 @@ pub(crate) fn effective_mcp_servers( ) -> HashMap { with_codex_apps_mcp( config.mcp_servers.get().clone(), - config.features.enabled(Feature::Connectors), + config.features.enabled(Feature::Apps), auth, config, ) diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 9462f745ba..15305f4b0c 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -14,6 +14,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; +use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::auth::McpAuthStatusEntry; use anyhow::Context; use anyhow::Result; @@ -436,13 +437,33 @@ impl McpConnectionManager { .await } + pub(crate) async fn wait_for_server_ready(&self, server_name: &str, timeout: Duration) -> bool { + let Some(async_managed_client) = self.clients.get(server_name) else { + return false; + }; + + match tokio::time::timeout(timeout, async_managed_client.client()).await { + Ok(Ok(_)) => true, + Ok(Err(_)) | Err(_) => false, + } + } + /// Returns a single map that contains all tools. Each key is the /// fully-qualified name for the tool. #[instrument(level = "trace", skip_all)] pub async fn list_all_tools(&self) -> HashMap { let mut tools = HashMap::new(); - for managed_client in self.clients.values() { - if let Ok(client) = managed_client.client().await { + for (server_name, managed_client) in &self.clients { + let client = if server_name == CODEX_APPS_MCP_SERVER_NAME { + // Avoid blocking on codex_apps_mcp startup; use tools only when ready. + match managed_client.client.clone().now_or_never() { + Some(Ok(client)) => Some(client), + _ => None, + } + } else { + managed_client.client().await.ok() + }; + if let Some(client) = client { tools.extend(qualify_tools(filter_tools( client.tools, client.tool_filter, diff --git a/codex-rs/core/src/mentions.rs b/codex-rs/core/src/mentions.rs new file mode 100644 index 0000000000..2f39c10d2f --- /dev/null +++ b/codex-rs/core/src/mentions.rs @@ -0,0 +1,64 @@ +use std::collections::HashMap; +use std::collections::HashSet; +use std::path::PathBuf; + +use codex_protocol::user_input::UserInput; + +use crate::connectors; +use crate::skills::SkillMetadata; +use crate::skills::injection::extract_tool_mentions; + +pub(crate) struct CollectedToolMentions { + pub(crate) plain_names: HashSet, + pub(crate) paths: HashSet, +} + +pub(crate) fn collect_tool_mentions_from_messages(messages: &[String]) -> CollectedToolMentions { + let mut plain_names = HashSet::new(); + let mut paths = HashSet::new(); + for message in messages { + let mentions = extract_tool_mentions(message); + plain_names.extend(mentions.plain_names().map(str::to_string)); + paths.extend(mentions.paths().map(str::to_string)); + } + CollectedToolMentions { plain_names, paths } +} + +pub(crate) fn collect_explicit_app_paths(input: &[UserInput]) -> Vec { + input + .iter() + .filter_map(|item| match item { + UserInput::Mention { path, .. } => Some(path.clone()), + _ => None, + }) + .collect() +} + +pub(crate) fn build_skill_name_counts( + skills: &[SkillMetadata], + disabled_paths: &HashSet, +) -> (HashMap, HashMap) { + let mut exact_counts: HashMap = HashMap::new(); + let mut lower_counts: HashMap = HashMap::new(); + for skill in skills { + if disabled_paths.contains(&skill.path) { + continue; + } + *exact_counts.entry(skill.name.clone()).or_insert(0) += 1; + *lower_counts + .entry(skill.name.to_ascii_lowercase()) + .or_insert(0) += 1; + } + (exact_counts, lower_counts) +} + +pub(crate) fn build_connector_slug_counts( + connectors: &[connectors::AppInfo], +) -> HashMap { + let mut counts: HashMap = HashMap::new(); + for connector in connectors { + let slug = connectors::connector_mention_slug(connector); + *counts.entry(slug).or_insert(0) += 1; + } + counts +} diff --git a/codex-rs/core/src/skills/injection.rs b/codex-rs/core/src/skills/injection.rs index 65ec4dd510..57de457e90 100644 --- a/codex-rs/core/src/skills/injection.rs +++ b/codex-rs/core/src/skills/injection.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::collections::HashSet; use std::path::PathBuf; @@ -67,7 +68,8 @@ fn emit_skill_injected_metric(otel: Option<&OtelManager>, skill: &SkillMetadata, /// Collect explicitly mentioned skills from `$name` text mentions. /// /// Text inputs are scanned once to extract `$skill-name` tokens, then we iterate `skills` -/// in their existing order to preserve prior ordering semantics. +/// in their existing order to preserve prior ordering semantics. Explicit links are +/// resolved by path and plain names are only used when the match is unambiguous. /// /// Complexity: `O(S + T + N_t * S)` time, `O(S)` space, where: /// `S` = number of skills, `T` = total text length, `N_t` = number of text inputs. @@ -75,17 +77,24 @@ pub(crate) fn collect_explicit_skill_mentions( inputs: &[UserInput], skills: &[SkillMetadata], disabled_paths: &HashSet, + skill_name_counts: &HashMap, + connector_slug_counts: &HashMap, ) -> Vec { + let selection_context = SkillSelectionContext { + skills, + disabled_paths, + skill_name_counts, + connector_slug_counts, + }; let mut selected: Vec = Vec::new(); let mut seen_names: HashSet = HashSet::new(); let mut seen_paths: HashSet = HashSet::new(); for input in inputs { if let UserInput::Text { text, .. } = input { - let mentioned_names = extract_skill_mentions(text); + let mentioned_names = extract_tool_mentions(text); select_skills_from_mentions( - skills, - disabled_paths, + &selection_context, &mentioned_names, &mut seen_names, &mut seen_paths, @@ -97,36 +106,95 @@ pub(crate) fn collect_explicit_skill_mentions( selected } -struct SkillMentions<'a> { - names: HashSet<&'a str>, - paths: HashSet<&'a str>, +struct SkillSelectionContext<'a> { + skills: &'a [SkillMetadata], + disabled_paths: &'a HashSet, + skill_name_counts: &'a HashMap, + connector_slug_counts: &'a HashMap, } -impl<'a> SkillMentions<'a> { +pub(crate) struct ToolMentions<'a> { + names: HashSet<&'a str>, + paths: HashSet<&'a str>, + plain_names: HashSet<&'a str>, +} + +impl<'a> ToolMentions<'a> { fn is_empty(&self) -> bool { self.names.is_empty() && self.paths.is_empty() } + + pub(crate) fn plain_names(&self) -> impl Iterator + '_ { + self.plain_names.iter().copied() + } + + pub(crate) fn paths(&self) -> impl Iterator + '_ { + self.paths.iter().copied() + } } -/// Extract `$skill-name` mentions from a single text input. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ToolMentionKind { + App, + Mcp, + Skill, + Other, +} + +const APP_PATH_PREFIX: &str = "app://"; +const MCP_PATH_PREFIX: &str = "mcp://"; +const SKILL_PATH_PREFIX: &str = "skill://"; +const SKILL_FILENAME: &str = "SKILL.md"; + +pub(crate) fn tool_kind_for_path(path: &str) -> ToolMentionKind { + if path.starts_with(APP_PATH_PREFIX) { + ToolMentionKind::App + } else if path.starts_with(MCP_PATH_PREFIX) { + ToolMentionKind::Mcp + } else if path.starts_with(SKILL_PATH_PREFIX) || is_skill_filename(path) { + ToolMentionKind::Skill + } else { + ToolMentionKind::Other + } +} + +fn is_skill_filename(path: &str) -> bool { + let file_name = path.rsplit(['/', '\\']).next().unwrap_or(path); + file_name.eq_ignore_ascii_case(SKILL_FILENAME) +} + +pub(crate) fn app_id_from_path(path: &str) -> Option<&str> { + path.strip_prefix(APP_PATH_PREFIX) + .filter(|value| !value.is_empty()) +} + +pub(crate) fn normalize_skill_path(path: &str) -> &str { + path.strip_prefix(SKILL_PATH_PREFIX).unwrap_or(path) +} + +/// Extract `$tool-name` mentions from a single text input. /// -/// Supports explicit resource links in the form `[$skill-name](resource path)`. When a +/// Supports explicit resource links in the form `[$tool-name](resource path)`. When a /// resource path is present, it is captured for exact path matching while also tracking /// the name for fallback matching. -fn extract_skill_mentions(text: &str) -> SkillMentions<'_> { +pub(crate) fn extract_tool_mentions(text: &str) -> ToolMentions<'_> { let text_bytes = text.as_bytes(); let mut mentioned_names: HashSet<&str> = HashSet::new(); let mut mentioned_paths: HashSet<&str> = HashSet::new(); + let mut plain_names: HashSet<&str> = HashSet::new(); let mut index = 0; while index < text_bytes.len() { let byte = text_bytes[index]; if byte == b'[' && let Some((name, path, end_index)) = - parse_linked_skill_mention(text, text_bytes, index) + parse_linked_tool_mention(text, text_bytes, index) { if !is_common_env_var(name) { - mentioned_names.insert(name); + let kind = tool_kind_for_path(path); + if !matches!(kind, ToolMentionKind::App | ToolMentionKind::Mcp) { + mentioned_names.insert(name); + } mentioned_paths.insert(path); } index = end_index; @@ -143,14 +211,14 @@ fn extract_skill_mentions(text: &str) -> SkillMentions<'_> { index += 1; continue; }; - if !is_skill_name_char(*first_name_byte) { + if !is_mention_name_char(*first_name_byte) { index += 1; continue; } let mut name_end = name_start + 1; while let Some(next_byte) = text_bytes.get(name_end) - && is_skill_name_char(*next_byte) + && is_mention_name_char(*next_byte) { name_end += 1; } @@ -158,21 +226,22 @@ fn extract_skill_mentions(text: &str) -> SkillMentions<'_> { let name = &text[name_start..name_end]; if !is_common_env_var(name) { mentioned_names.insert(name); + plain_names.insert(name); } index = name_end; } - SkillMentions { + ToolMentions { names: mentioned_names, paths: mentioned_paths, + plain_names, } } /// Select mentioned skills while preserving the order of `skills`. fn select_skills_from_mentions( - skills: &[SkillMetadata], - disabled_paths: &HashSet, - mentions: &SkillMentions<'_>, + selection_context: &SkillSelectionContext<'_>, + mentions: &ToolMentions<'_>, seen_names: &mut HashSet, seen_paths: &mut HashSet, selected: &mut Vec, @@ -181,32 +250,65 @@ fn select_skills_from_mentions( return; } - for skill in skills { - if disabled_paths.contains(&skill.path) || seen_paths.contains(&skill.path) { + let mention_skill_paths: HashSet<&str> = mentions + .paths() + .filter(|path| { + !matches!( + tool_kind_for_path(path), + ToolMentionKind::App | ToolMentionKind::Mcp + ) + }) + .map(normalize_skill_path) + .collect(); + + for skill in selection_context.skills { + if selection_context.disabled_paths.contains(&skill.path) + || seen_paths.contains(&skill.path) + { continue; } let path_str = skill.path.to_string_lossy(); - if mentions.paths.contains(path_str.as_ref()) { + if mention_skill_paths.contains(path_str.as_ref()) { seen_paths.insert(skill.path.clone()); seen_names.insert(skill.name.clone()); selected.push(skill.clone()); } } - for skill in skills { - if disabled_paths.contains(&skill.path) || seen_paths.contains(&skill.path) { + for skill in selection_context.skills { + if selection_context.disabled_paths.contains(&skill.path) + || seen_paths.contains(&skill.path) + { continue; } - if mentions.names.contains(skill.name.as_str()) && seen_names.insert(skill.name.clone()) { + if !mentions.plain_names.contains(skill.name.as_str()) { + continue; + } + + let skill_count = selection_context + .skill_name_counts + .get(skill.name.as_str()) + .copied() + .unwrap_or(0); + let connector_count = selection_context + .connector_slug_counts + .get(&skill.name.to_ascii_lowercase()) + .copied() + .unwrap_or(0); + if skill_count != 1 || connector_count != 0 { + continue; + } + + if seen_names.insert(skill.name.clone()) { seen_paths.insert(skill.path.clone()); selected.push(skill.clone()); } } } -fn parse_linked_skill_mention<'a>( +fn parse_linked_tool_mention<'a>( text: &'a str, text_bytes: &[u8], start: usize, @@ -218,13 +320,13 @@ fn parse_linked_skill_mention<'a>( let name_start = dollar_index + 1; let first_name_byte = text_bytes.get(name_start)?; - if !is_skill_name_char(*first_name_byte) { + if !is_mention_name_char(*first_name_byte) { return None; } let mut name_end = name_start + 1; while let Some(next_byte) = text_bytes.get(name_end) - && is_skill_name_char(*next_byte) + && is_mention_name_char(*next_byte) { name_end += 1; } @@ -304,7 +406,7 @@ fn text_mentions_skill(text: &str, skill_name: &str) -> bool { let after_index = name_start + skill_bytes.len(); let after = text_bytes.get(after_index).copied(); - if after.is_none_or(|b| !is_skill_name_char(b)) { + if after.is_none_or(|b| !is_mention_name_char(b)) { return true; } } @@ -312,7 +414,7 @@ fn text_mentions_skill(text: &str, skill_name: &str) -> bool { false } -fn is_skill_name_char(byte: u8) -> bool { +fn is_mention_name_char(byte: u8) -> bool { matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') } @@ -320,6 +422,7 @@ fn is_skill_name_char(byte: u8) -> bool { mod tests { use super::*; use pretty_assertions::assert_eq; + use std::collections::HashMap; use std::collections::HashSet; fn make_skill(name: &str, path: &str) -> SkillMetadata { @@ -339,11 +442,41 @@ mod tests { } fn assert_mentions(text: &str, expected_names: &[&str], expected_paths: &[&str]) { - let mentions = extract_skill_mentions(text); + let mentions = extract_tool_mentions(text); assert_eq!(mentions.names, set(expected_names)); assert_eq!(mentions.paths, set(expected_paths)); } + fn build_skill_name_counts( + skills: &[SkillMetadata], + disabled_paths: &HashSet, + ) -> HashMap { + let mut counts = HashMap::new(); + for skill in skills { + if disabled_paths.contains(&skill.path) { + continue; + } + *counts.entry(skill.name.clone()).or_insert(0) += 1; + } + counts + } + + fn collect_mentions( + inputs: &[UserInput], + skills: &[SkillMetadata], + disabled_paths: &HashSet, + connector_slug_counts: &HashMap, + ) -> Vec { + let skill_name_counts = build_skill_name_counts(skills, disabled_paths); + collect_explicit_skill_mentions( + inputs, + skills, + disabled_paths, + &skill_name_counts, + connector_slug_counts, + ) + } + #[test] fn text_mentions_skill_requires_exact_boundary() { assert_eq!( @@ -386,7 +519,7 @@ mod tests { } #[test] - fn extract_skill_mentions_handles_plain_and_linked_mentions() { + fn extract_tool_mentions_handles_plain_and_linked_mentions() { assert_mentions( "use $alpha and [$beta](/tmp/beta)", &["alpha", "beta"], @@ -395,26 +528,26 @@ mod tests { } #[test] - fn extract_skill_mentions_skips_common_env_vars() { + fn extract_tool_mentions_skips_common_env_vars() { assert_mentions("use $PATH and $alpha", &["alpha"], &[]); assert_mentions("use [$HOME](/tmp/skill)", &[], &[]); assert_mentions("use $XDG_CONFIG_HOME and $beta", &["beta"], &[]); } #[test] - fn extract_skill_mentions_requires_link_syntax() { + fn extract_tool_mentions_requires_link_syntax() { assert_mentions("[beta](/tmp/beta)", &[], &[]); assert_mentions("[$beta] /tmp/beta", &["beta"], &[]); assert_mentions("[$beta]()", &["beta"], &[]); } #[test] - fn extract_skill_mentions_trims_linked_paths_and_allows_spacing() { + fn extract_tool_mentions_trims_linked_paths_and_allows_spacing() { assert_mentions("use [$beta] ( /tmp/beta )", &["beta"], &["/tmp/beta"]); } #[test] - fn extract_skill_mentions_stops_at_non_name_chars() { + fn extract_tool_mentions_stops_at_non_name_chars() { assert_mentions( "use $alpha.skill and $beta_extra", &["alpha", "beta_extra"], @@ -431,8 +564,9 @@ mod tests { text: "first $alpha-skill then $beta-skill".to_string(), text_elements: Vec::new(), }]; + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); // Text scanning should not change the previous selection ordering semantics. assert_eq!(selected, vec![beta, alpha]); @@ -453,8 +587,9 @@ mod tests { path: PathBuf::from("/tmp/beta"), }, ]; + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); assert_eq!(selected, vec![alpha]); } @@ -467,25 +602,27 @@ mod tests { text: "use [$alpha-skill](/tmp/alpha) and [$alpha-skill](/tmp/alpha)".to_string(), text_elements: Vec::new(), }]; + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); assert_eq!(selected, vec![alpha]); } #[test] - fn collect_explicit_skill_mentions_dedupes_by_name() { + fn collect_explicit_skill_mentions_skips_ambiguous_name() { let alpha = make_skill("demo-skill", "/tmp/alpha"); let beta = make_skill("demo-skill", "/tmp/beta"); - let skills = vec![alpha.clone(), beta]; + let skills = vec![alpha, beta]; let inputs = vec![UserInput::Text { text: "use $demo-skill and again $demo-skill".to_string(), text_elements: Vec::new(), }]; + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); - assert_eq!(selected, vec![alpha]); + assert_eq!(selected, Vec::new()); } #[test] @@ -497,26 +634,58 @@ mod tests { text: "use $demo-skill and [$demo-skill](/tmp/beta)".to_string(), text_elements: Vec::new(), }]; + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); assert_eq!(selected, vec![beta]); } #[test] - fn collect_explicit_skill_mentions_falls_back_when_linked_path_disabled() { + fn collect_explicit_skill_mentions_skips_plain_name_when_connector_matches() { + let alpha = make_skill("alpha-skill", "/tmp/alpha"); + let skills = vec![alpha]; + let inputs = vec![UserInput::Text { + text: "use $alpha-skill".to_string(), + text_elements: Vec::new(), + }]; + let connector_counts = HashMap::from([("alpha-skill".to_string(), 1)]); + + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); + + assert_eq!(selected, Vec::new()); + } + + #[test] + fn collect_explicit_skill_mentions_allows_explicit_path_with_connector_conflict() { + let alpha = make_skill("alpha-skill", "/tmp/alpha"); + let skills = vec![alpha.clone()]; + let inputs = vec![UserInput::Text { + text: "use [$alpha-skill](/tmp/alpha)".to_string(), + text_elements: Vec::new(), + }]; + let connector_counts = HashMap::from([("alpha-skill".to_string(), 1)]); + + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); + + assert_eq!(selected, vec![alpha]); + } + + #[test] + fn collect_explicit_skill_mentions_skips_when_linked_path_disabled() { let alpha = make_skill("demo-skill", "/tmp/alpha"); let beta = make_skill("demo-skill", "/tmp/beta"); - let skills = vec![alpha, beta.clone()]; + let skills = vec![alpha, beta]; let inputs = vec![UserInput::Text { text: "use [$demo-skill](/tmp/alpha)".to_string(), text_elements: Vec::new(), }]; let disabled = HashSet::from([PathBuf::from("/tmp/alpha")]); + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &disabled); + let selected = collect_mentions(&inputs, &skills, &disabled, &connector_counts); - assert_eq!(selected, vec![beta]); + assert_eq!(selected, Vec::new()); } #[test] @@ -528,24 +697,41 @@ mod tests { text: "use [$demo-skill](/tmp/beta)".to_string(), text_elements: Vec::new(), }]; + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); assert_eq!(selected, vec![beta]); } #[test] - fn collect_explicit_skill_mentions_falls_back_to_name_when_path_missing() { + fn collect_explicit_skill_mentions_skips_missing_path_with_no_fallback() { let alpha = make_skill("demo-skill", "/tmp/alpha"); let beta = make_skill("demo-skill", "/tmp/beta"); - let skills = vec![alpha.clone(), beta]; + let skills = vec![alpha, beta]; let inputs = vec![UserInput::Text { text: "use [$demo-skill](/tmp/missing)".to_string(), text_elements: Vec::new(), }]; + let connector_counts = HashMap::new(); - let selected = collect_explicit_skill_mentions(&inputs, &skills, &HashSet::new()); + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); - assert_eq!(selected, vec![alpha]); + assert_eq!(selected, Vec::new()); + } + + #[test] + fn collect_explicit_skill_mentions_skips_missing_path_without_fallback() { + let alpha = make_skill("demo-skill", "/tmp/alpha"); + let skills = vec![alpha]; + let inputs = vec![UserInput::Text { + text: "use [$demo-skill](/tmp/missing)".to_string(), + text_elements: Vec::new(), + }]; + let connector_counts = HashMap::new(); + + let selected = collect_mentions(&inputs, &skills, &HashSet::new(), &connector_counts); + + assert_eq!(selected, Vec::new()); } } diff --git a/codex-rs/core/src/token_data.rs b/codex-rs/core/src/token_data.rs index 526e240a6c..744cc73d9b 100644 --- a/codex-rs/core/src/token_data.rs +++ b/codex-rs/core/src/token_data.rs @@ -42,6 +42,15 @@ impl IdTokenInfo { PlanType::Unknown(s) => s.clone(), }) } + + pub fn is_workspace_account(&self) -> bool { + matches!( + self.chatgpt_plan_type, + Some(PlanType::Known( + KnownPlan::Team | KnownPlan::Business | KnownPlan::Enterprise | KnownPlan::Edu + )) + ) + } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -140,6 +149,7 @@ where #[cfg(test)] mod tests { use super::*; + use pretty_assertions::assert_eq; use serde::Serialize; #[test] @@ -200,4 +210,19 @@ mod tests { assert!(info.email.is_none()); assert!(info.get_chatgpt_plan_type().is_none()); } + + #[test] + fn workspace_account_detection_matches_workspace_plans() { + let workspace = IdTokenInfo { + chatgpt_plan_type: Some(PlanType::Known(KnownPlan::Business)), + ..IdTokenInfo::default() + }; + assert_eq!(workspace.is_workspace_account(), true); + + let personal = IdTokenInfo { + chatgpt_plan_type: Some(PlanType::Known(KnownPlan::Pro)), + ..IdTokenInfo::default() + }; + assert_eq!(personal.is_workspace_account(), false); + } } diff --git a/codex-rs/docs/protocol_v1.md b/codex-rs/docs/protocol_v1.md index ee49cac0a6..8cdc5c9575 100644 --- a/codex-rs/docs/protocol_v1.md +++ b/codex-rs/docs/protocol_v1.md @@ -82,6 +82,15 @@ For complete documentation of the `Op` and `EventMsg` variants, refer to [protoc - `EventMsg::TurnComplete` – Contains a `response_id` bookmark for last `response_id` executed by the turn. This can be used to continue the turn at a later point in time, perhaps with additional user input. - `EventMsg::ListSkillsResponse` – Response payload with per-cwd skill entries (`cwd`, `skills`, `errors`) +### UserInput items + +`Op::UserTurn` content items can include: + +- `text` – Plain text plus optional UI text elements. +- `image` / `local_image` – Image inputs. +- `skill` – Explicit skill selection (`name`, `path` to `SKILL.md`). +- `mention` – Explicit app/connector selection (`name`, `path` in `app://{connector_id}` form). + Note: For v1 wire compatibility, `EventMsg::TurnStarted` and `EventMsg::TurnComplete` serialize as `task_started` / `task_complete`. The deserializer accepts both `task_*` and `turn_*` tags. The `response_id` returned from each turn matches the OpenAI `response_id` stored in the API's `/responses` endpoint. It can be stored and used in future `Sessions` to resume threads of work. diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 50e8ee342f..759ff5aae4 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -674,7 +674,7 @@ impl From> for ResponseInputItem { image_index += 1; local_image_content_items_with_label_number(&path, Some(image_index)) } - UserInput::Skill { .. } => Vec::new(), // Skill bodies are injected later in core + UserInput::Skill { .. } | UserInput::Mention { .. } => Vec::new(), // Tool bodies are injected later in core }) .collect::>(), } diff --git a/codex-rs/protocol/src/user_input.rs b/codex-rs/protocol/src/user_input.rs index e9ca09580e..d40511f342 100644 --- a/codex-rs/protocol/src/user_input.rs +++ b/codex-rs/protocol/src/user_input.rs @@ -29,6 +29,8 @@ pub enum UserInput { name: String, path: std::path::PathBuf, }, + /// Explicit mention selected by the user (name + app://connector id). + Mention { name: String, path: String }, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, TS, JsonSchema)] diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 1d20542365..820fe20e93 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -30,6 +30,7 @@ codex-ansi-escape = { workspace = true } codex-app-server-protocol = { workspace = true } codex-arg0 = { workspace = true } codex-backend-client = { workspace = true } +codex-chatgpt = { workspace = true } codex-common = { workspace = true, features = [ "cli", "elapsed", diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index e5db8fc6b6..ae1dc4b322 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1508,6 +1508,21 @@ impl App { )); tui.frame_requester().schedule_frame(); } + AppEvent::OpenAppLink { + title, + description, + instructions, + url, + is_installed, + } => { + self.chat_widget.open_app_link_view( + title, + description, + instructions, + url, + is_installed, + ); + } AppEvent::StartFileSearch(query) => { self.file_search.on_user_query(query); } @@ -1517,6 +1532,9 @@ impl App { AppEvent::RateLimitSnapshotFetched(snapshot) => { self.chat_widget.on_rate_limit_snapshot(Some(snapshot)); } + AppEvent::ConnectorsLoaded(result) => { + self.chat_widget.on_connectors_loaded(result); + } AppEvent::UpdateReasoningEffort(effort) => { self.on_update_reasoning_effort(effort); } diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index b65d1efb62..bbd228e114 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -10,6 +10,7 @@ use std::path::PathBuf; +use codex_chatgpt::connectors::AppInfo; use codex_common::approval_presets::ApprovalPreset; use codex_core::protocol::Event; use codex_core::protocol::RateLimitSnapshot; @@ -40,6 +41,11 @@ pub(crate) enum WindowsSandboxFallbackReason { ElevationFailed, } +#[derive(Debug, Clone)] +pub(crate) struct ConnectorsSnapshot { + pub(crate) connectors: Vec, +} + #[allow(clippy::large_enum_variant)] #[derive(Debug)] pub(crate) enum AppEvent { @@ -89,9 +95,21 @@ pub(crate) enum AppEvent { /// Result of refreshing rate limits RateLimitSnapshotFetched(RateLimitSnapshot), + /// Result of prefetching connectors. + ConnectorsLoaded(Result), + /// Result of computing a `/diff` command. DiffResult(String), + /// Open the app link view in the bottom pane. + OpenAppLink { + title: String, + description: Option, + instructions: String, + url: String, + is_installed: bool, + }, + InsertHistoryCell(Box), StartCommitAnimation, diff --git a/codex-rs/tui/src/bottom_pane/app_link_view.rs b/codex-rs/tui/src/bottom_pane/app_link_view.rs new file mode 100644 index 0000000000..1f672607a2 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/app_link_view.rs @@ -0,0 +1,163 @@ +use crossterm::event::KeyCode; +use crossterm::event::KeyEvent; +use ratatui::buffer::Buffer; +use ratatui::layout::Constraint; +use ratatui::layout::Layout; +use ratatui::layout::Rect; +use ratatui::style::Stylize; +use ratatui::text::Line; +use ratatui::widgets::Block; +use ratatui::widgets::Paragraph; +use ratatui::widgets::Widget; +use textwrap::wrap; + +use super::CancellationEvent; +use super::bottom_pane_view::BottomPaneView; +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; + +pub(crate) struct AppLinkView { + title: String, + description: Option, + instructions: String, + url: String, + is_installed: bool, + complete: bool, +} + +impl AppLinkView { + pub(crate) fn new( + title: String, + description: Option, + instructions: String, + url: String, + is_installed: bool, + ) -> Self { + Self { + title, + description, + instructions, + url, + is_installed, + complete: false, + } + } + + fn content_lines(&self, width: u16) -> Vec> { + let usable_width = width.max(1) as usize; + let mut lines: Vec> = Vec::new(); + + lines.push(Line::from(self.title.clone().bold())); + if let Some(description) = self + .description + .as_deref() + .map(str::trim) + .filter(|description| !description.is_empty()) + { + for line in wrap(description, usable_width) { + lines.push(Line::from(line.into_owned().dim())); + } + } + lines.push(Line::from("")); + if self.is_installed { + for line in wrap("Use $ to insert this app into the prompt.", usable_width) { + lines.push(Line::from(line.into_owned())); + } + lines.push(Line::from("")); + } + + let instructions = self.instructions.trim(); + if !instructions.is_empty() { + for line in wrap(instructions, usable_width) { + lines.push(Line::from(line.into_owned())); + } + for line in wrap( + "Newly installed apps can take a few minutes to appear in /apps.", + usable_width, + ) { + lines.push(Line::from(line.into_owned())); + } + if !self.is_installed { + for line in wrap( + "After installed, use $ to insert this app into the prompt.", + usable_width, + ) { + lines.push(Line::from(line.into_owned())); + } + } + lines.push(Line::from("")); + } + + lines.push(Line::from(vec!["Open:".dim()])); + let url_line = Line::from(vec![self.url.clone().cyan().underlined()]); + lines.extend(word_wrap_lines(vec![url_line], usable_width)); + + lines + } +} + +impl BottomPaneView for AppLinkView { + fn handle_key_event(&mut self, key_event: KeyEvent) { + if let KeyEvent { + code: KeyCode::Esc, .. + } = key_event + { + self.on_ctrl_c(); + } + } + + fn on_ctrl_c(&mut self) -> CancellationEvent { + self.complete = true; + CancellationEvent::Handled + } + + fn is_complete(&self) -> bool { + self.complete + } +} + +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); + content_lines.len() as u16 + 3 + } + + fn render(&self, area: Rect, buf: &mut Buffer) { + if area.height == 0 || area.width == 0 { + return; + } + + Block::default() + .style(user_message_style()) + .render(area, buf); + + let [content_area, hint_area] = + Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(area); + 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); + + if hint_area.height > 0 { + let hint_area = Rect { + x: hint_area.x.saturating_add(2), + y: hint_area.y, + width: hint_area.width.saturating_sub(2), + height: hint_area.height, + }; + hint_line().dim().render(hint_area, buf); + } + } +} + +fn hint_line() -> Line<'static> { + Line::from(vec![ + "Press ".into(), + key_hint::plain(KeyCode::Esc).into(), + " to close".into(), + ]) +} diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 3a3f5d407b..9d0cbf22e5 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -3,7 +3,7 @@ //! It is responsible for: //! //! - Editing the input buffer (a [`TextArea`]), including placeholder "elements" for attachments. -//! - Routing keys to the active popup (slash commands, file search, skill mentions). +//! - Routing keys to the active popup (slash commands, file search, skill/apps mentions). //! - Handling submit vs newline on Enter. //! - Turning raw key streams into explicit paste operations on platforms where terminals //! don't provide reliable bracketed paste (notably Windows). @@ -124,6 +124,7 @@ use super::footer::single_line_footer_layout; use super::footer::toggle_shortcut_mode; use super::paste_burst::CharDecision; use super::paste_burst::PasteBurst; +use super::skill_popup::MentionItem; use super::skill_popup::SkillPopup; use super::slash_commands; use crate::bottom_pane::paste_burst::FlushResult; @@ -146,6 +147,7 @@ use codex_protocol::user_input::ByteRange; use codex_protocol::user_input::TextElement; use crate::app_event::AppEvent; +use crate::app_event::ConnectorsSnapshot; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::LocalImageAttachment; use crate::bottom_pane::textarea::TextArea; @@ -154,6 +156,8 @@ use crate::clipboard_paste::normalize_pasted_path; use crate::clipboard_paste::pasted_image_format; use crate::history_cell; use crate::ui_consts::LIVE_PREFIX_COLS; +use codex_chatgpt::connectors; +use codex_chatgpt::connectors::AppInfo; use codex_core::skills::model::SkillMetadata; use codex_file_search::FileMatch; use std::cell::RefCell; @@ -276,12 +280,15 @@ pub(crate) struct ChatComposer { context_window_percent: Option, context_window_used_tokens: Option, skills: Option>, - dismissed_skill_popup_token: Option, + connectors_snapshot: Option, + dismissed_mention_popup_token: Option, + mention_paths: HashMap, /// When enabled, `Enter` submits immediately and `Tab` requests queuing behavior. steer_enabled: bool, collaboration_modes_enabled: bool, config: ChatComposerConfig, collaboration_mode_indicator: Option, + connectors_enabled: bool, personality_command_enabled: bool, windows_degraded_sandbox_active: bool, } @@ -363,11 +370,14 @@ impl ChatComposer { context_window_percent: None, context_window_used_tokens: None, skills: None, - dismissed_skill_popup_token: None, + connectors_snapshot: None, + dismissed_mention_popup_token: None, + mention_paths: HashMap::new(), steer_enabled: false, collaboration_modes_enabled: false, config, collaboration_mode_indicator: None, + connectors_enabled: false, personality_command_enabled: false, windows_degraded_sandbox_active: false, }; @@ -380,6 +390,14 @@ impl ChatComposer { self.skills = skills; } + pub fn set_connector_mentions(&mut self, connectors_snapshot: Option) { + self.connectors_snapshot = connectors_snapshot; + } + + pub(crate) fn take_mention_paths(&mut self) -> HashMap { + std::mem::take(&mut self.mention_paths) + } + /// Enables or disables "Steer" behavior for submission keys. /// /// When steer is enabled, `Enter` produces [`InputResult::Submitted`] (send immediately) and @@ -394,6 +412,10 @@ impl ChatComposer { self.collaboration_modes_enabled = enabled; } + pub fn set_connectors_enabled(&mut self, enabled: bool) { + self.connectors_enabled = enabled; + } + pub fn set_collaboration_mode_indicator( &mut self, indicator: Option, @@ -697,6 +719,7 @@ impl ChatComposer { self.textarea.set_text_clearing_elements(""); self.pending_pastes.clear(); self.attached_images.clear(); + self.mention_paths.clear(); self.textarea.set_text_with_elements(&text, &text_elements); @@ -1349,7 +1372,10 @@ impl ChatComposer { unreachable!(); }; - match key_event { + let mut selected_mention: Option<(String, Option)> = None; + let mut close_popup = false; + + let result = match key_event { KeyEvent { code: KeyCode::Up, .. } @@ -1376,8 +1402,8 @@ impl ChatComposer { KeyEvent { code: KeyCode::Esc, .. } => { - if let Some(tok) = self.current_skill_token() { - self.dismissed_skill_popup_token = Some(tok); + if let Some(tok) = self.current_mention_token() { + self.dismissed_mention_popup_token = Some(tok); } self.active_popup = ActivePopup::None; (InputResult::None, true) @@ -1390,15 +1416,26 @@ impl ChatComposer { modifiers: KeyModifiers::NONE, .. } => { - let selected = popup.selected_skill().map(|skill| skill.name.clone()); - if let Some(name) = selected { - self.insert_selected_skill(&name); + if let Some(mention) = popup.selected_mention() { + selected_mention = Some((mention.insert_text.clone(), mention.path.clone())); } - self.active_popup = ActivePopup::None; + close_popup = true; (InputResult::None, true) } input => self.handle_input_basic(input), + }; + + if close_popup { + if let Some((insert_text, path)) = selected_mention { + if let Some(path) = path.as_deref() { + self.record_mention_path(&insert_text, path); + } + self.insert_selected_mention(&insert_text); + } + self.active_popup = ActivePopup::None; } + + result } fn is_image_path(path: &str) -> bool { @@ -1511,14 +1548,23 @@ impl ChatComposer { (rebuilt, rebuilt_elements) } - fn skills_enabled(&self) -> bool { - self.skills.as_ref().is_some_and(|s| !s.is_empty()) - } - pub fn skills(&self) -> Option<&Vec> { self.skills.as_ref() } + fn mentions_enabled(&self) -> bool { + let skills_ready = self + .skills + .as_ref() + .is_some_and(|skills| !skills.is_empty()); + let connectors_ready = self.connectors_enabled + && self + .connectors_snapshot + .as_ref() + .is_some_and(|snapshot| !snapshot.connectors.is_empty()); + skills_ready || connectors_ready + } + /// Extract a token prefixed with `prefix` under the cursor, if any. /// /// The returned string **does not** include the prefix. @@ -1632,8 +1678,8 @@ impl ChatComposer { Self::current_prefixed_token(textarea, '@', false) } - fn current_skill_token(&self) -> Option { - if !self.skills_enabled() { + fn current_mention_token(&self) -> Option { + if !self.mentions_enabled() { return None; } Self::current_prefixed_token(&self.textarea, '$', true) @@ -1691,7 +1737,7 @@ impl ChatComposer { self.textarea.set_cursor(new_cursor); } - fn insert_selected_skill(&mut self, skill_name: &str) { + fn insert_selected_mention(&mut self, insert_text: &str) { let cursor_offset = self.textarea.cursor(); let text = self.textarea.text(); let safe_cursor = Self::clamp_to_char_boundary(text, cursor_offset); @@ -1712,7 +1758,7 @@ impl ChatComposer { .unwrap_or(after_cursor.len()); let end_idx = safe_cursor + end_rel_idx; - let inserted = format!("${skill_name}"); + let inserted = insert_text.to_string(); let mut new_text = String::with_capacity(text.len() - (end_idx - start_idx) + inserted.len() + 1); @@ -1721,12 +1767,35 @@ impl ChatComposer { new_text.push(' '); new_text.push_str(&text[end_idx..]); - // Skill insertion rebuilds plain text, so drop existing elements. + // Mention insertion rebuilds plain text, so drop existing elements. self.textarea.set_text_clearing_elements(&new_text); let new_cursor = start_idx.saturating_add(inserted.len()).saturating_add(1); self.textarea.set_cursor(new_cursor); } + fn record_mention_path(&mut self, insert_text: &str, path: &str) { + let Some(name) = Self::mention_name_from_insert_text(insert_text) else { + return; + }; + self.mention_paths.insert(name, path.to_string()); + } + + fn mention_name_from_insert_text(insert_text: &str) -> Option { + let name = insert_text.strip_prefix('$')?; + if name.is_empty() { + return None; + } + if name + .as_bytes() + .iter() + .all(|byte| is_mention_name_char(*byte)) + { + Some(name.to_string()) + } else { + None + } + } + /// Prepare text for submission/queuing. Returns None if submission should be suppressed. /// On success, clears pending paste payloads because placeholders have been expanded. fn prepare_submission_text(&mut self) -> Option<(String, Vec)> { @@ -1765,6 +1834,7 @@ impl ChatComposer { let is_builtin = slash_commands::find_builtin_command( name, self.collaboration_modes_enabled, + self.connectors_enabled, self.personality_command_enabled, self.windows_degraded_sandbox_active, ) @@ -1951,6 +2021,7 @@ impl ChatComposer { && let Some(cmd) = slash_commands::find_builtin_command( name, self.collaboration_modes_enabled, + self.connectors_enabled, self.personality_command_enabled, self.windows_degraded_sandbox_active, ) @@ -1979,6 +2050,7 @@ impl ChatComposer { && let Some(cmd) = slash_commands::find_builtin_command( name, self.collaboration_modes_enabled, + self.connectors_enabled, self.personality_command_enabled, self.windows_degraded_sandbox_active, ) @@ -2388,10 +2460,10 @@ impl ChatComposer { self.active_popup = ActivePopup::None; return; } - let skill_token = self.current_skill_token(); + let mention_token = self.current_mention_token(); let allow_command_popup = - self.slash_commands_enabled() && file_token.is_none() && skill_token.is_none(); + self.slash_commands_enabled() && file_token.is_none() && mention_token.is_none(); self.sync_command_popup(allow_command_popup); if matches!(self.active_popup, ActivePopup::Command(_)) { @@ -2401,20 +2473,20 @@ impl ChatComposer { self.current_file_query = None; } self.dismissed_file_popup_token = None; - self.dismissed_skill_popup_token = None; + self.dismissed_mention_popup_token = None; return; } - if let Some(token) = skill_token { + if let Some(token) = mention_token { if self.current_file_query.is_some() { self.app_event_tx .send(AppEvent::StartFileSearch(String::new())); self.current_file_query = None; } - self.sync_skill_popup(token); + self.sync_mention_popup(token); return; } - self.dismissed_skill_popup_token = None; + self.dismissed_mention_popup_token = None; if let Some(token) = file_token { self.sync_file_search_popup(token); @@ -2477,6 +2549,7 @@ impl ChatComposer { if slash_commands::has_builtin_prefix( name, self.collaboration_modes_enabled, + self.connectors_enabled, self.personality_command_enabled, self.windows_degraded_sandbox_active, ) { @@ -2529,11 +2602,13 @@ impl ChatComposer { _ => { if is_editing_slash_command_name { let collaboration_modes_enabled = self.collaboration_modes_enabled; + let connectors_enabled = self.connectors_enabled; let personality_command_enabled = self.personality_command_enabled; let mut command_popup = CommandPopup::new( self.custom_prompts.clone(), CommandPopupFlags { collaboration_modes_enabled, + connectors_enabled, personality_command_enabled, windows_degraded_sandbox_active: self.windows_degraded_sandbox_active, }, @@ -2594,32 +2669,99 @@ impl ChatComposer { self.dismissed_file_popup_token = None; } - fn sync_skill_popup(&mut self, query: String) { - if self.dismissed_skill_popup_token.as_ref() == Some(&query) { + fn sync_mention_popup(&mut self, query: String) { + if self.dismissed_mention_popup_token.as_ref() == Some(&query) { return; } - let skills = match self.skills.as_ref() { - Some(skills) if !skills.is_empty() => skills.clone(), - _ => { - self.active_popup = ActivePopup::None; - return; - } - }; + let mentions = self.mention_items(); + if mentions.is_empty() { + self.active_popup = ActivePopup::None; + return; + } match &mut self.active_popup { ActivePopup::Skill(popup) => { popup.set_query(&query); - popup.set_skills(skills); + popup.set_mentions(mentions); } _ => { - let mut popup = SkillPopup::new(skills); + let mut popup = SkillPopup::new(mentions); popup.set_query(&query); self.active_popup = ActivePopup::Skill(popup); } } } + fn mention_items(&self) -> Vec { + let mut mentions = Vec::new(); + + if let Some(skills) = self.skills.as_ref() { + for skill in skills { + let display_name = skill_display_name(skill).to_string(); + let description = skill_description(skill); + let skill_name = skill.name.clone(); + let search_terms = if display_name == skill.name { + vec![skill_name.clone()] + } else { + vec![skill_name.clone(), display_name.clone()] + }; + mentions.push(MentionItem { + display_name, + description, + insert_text: format!("${skill_name}"), + search_terms, + path: Some(skill.path.to_string_lossy().into_owned()), + }); + } + } + + if self.connectors_enabled + && let Some(snapshot) = self.connectors_snapshot.as_ref() + { + for connector in &snapshot.connectors { + if !connector.is_accessible { + continue; + } + let display_name = connectors::connector_display_label(connector); + let description = Some(Self::connector_brief_description(connector)); + let slug = codex_core::connectors::connector_mention_slug(connector); + let search_terms = vec![display_name.clone(), connector.id.clone(), slug.clone()]; + let connector_id = connector.id.as_str(); + mentions.push(MentionItem { + display_name: display_name.clone(), + description, + insert_text: format!("${slug}"), + search_terms, + path: Some(format!("app://{connector_id}")), + }); + } + } + + mentions + } + + fn connector_brief_description(connector: &AppInfo) -> String { + let status_label = if connector.is_accessible { + "Connected" + } else { + "Can be installed" + }; + match Self::connector_description(connector) { + Some(description) => format!("{status_label} - {description}"), + None => status_label.to_string(), + } + } + + fn connector_description(connector: &AppInfo) -> Option { + connector + .description + .as_deref() + .map(str::trim) + .filter(|description| !description.is_empty()) + .map(str::to_string) + } + fn set_has_focus(&mut self, has_focus: bool) { self.has_focus = has_focus; } @@ -2658,6 +2800,29 @@ impl ChatComposer { } } +fn skill_display_name(skill: &SkillMetadata) -> &str { + skill + .interface + .as_ref() + .and_then(|interface| interface.display_name.as_deref()) + .unwrap_or(&skill.name) +} + +fn skill_description(skill: &SkillMetadata) -> Option { + let description = skill + .interface + .as_ref() + .and_then(|interface| interface.short_description.as_deref()) + .or(skill.short_description.as_deref()) + .unwrap_or(&skill.description); + let trimmed = description.trim(); + (!trimmed.is_empty()).then(|| trimmed.to_string()) +} + +fn is_mention_name_char(byte: u8) -> bool { + matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') +} + impl Renderable for ChatComposer { fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> { if !self.input_enabled { @@ -2938,6 +3103,7 @@ mod tests { use tempfile::tempdir; use crate::app_event::AppEvent; + use crate::bottom_pane::AppEventSender; use crate::bottom_pane::ChatComposer; use crate::bottom_pane::InputResult; diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index c1cdd5374d..5423231db8 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -32,6 +32,7 @@ pub(crate) struct CommandPopup { #[derive(Clone, Copy, Debug, Default)] pub(crate) struct CommandPopupFlags { pub(crate) collaboration_modes_enabled: bool, + pub(crate) connectors_enabled: bool, pub(crate) personality_command_enabled: bool, pub(crate) windows_degraded_sandbox_active: bool, } @@ -41,6 +42,7 @@ impl CommandPopup { // Keep built-in availability in sync with the composer. let builtins = slash_commands::builtins_for_input( flags.collaboration_modes_enabled, + flags.connectors_enabled, flags.personality_command_enabled, flags.windows_degraded_sandbox_active, ); @@ -478,6 +480,7 @@ mod tests { Vec::new(), CommandPopupFlags { collaboration_modes_enabled: true, + connectors_enabled: false, personality_command_enabled: true, windows_degraded_sandbox_active: false, }, @@ -496,6 +499,7 @@ mod tests { Vec::new(), CommandPopupFlags { collaboration_modes_enabled: true, + connectors_enabled: false, personality_command_enabled: false, windows_degraded_sandbox_active: false, }, @@ -522,6 +526,7 @@ mod tests { Vec::new(), CommandPopupFlags { collaboration_modes_enabled: true, + connectors_enabled: false, personality_command_enabled: true, windows_degraded_sandbox_active: false, }, diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 701e0762cb..d08ccf5068 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -13,8 +13,10 @@ //! //! Some UI is time-based rather than input-based, such as the transient "press again to quit" //! hint. The pane schedules redraws so those hints can expire even when the UI is otherwise idle. +use std::collections::HashMap; use std::path::PathBuf; +use crate::app_event::ConnectorsSnapshot; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::queued_user_messages::QueuedUserMessages; use crate::bottom_pane::unified_exec_footer::UnifiedExecFooter; @@ -36,8 +38,10 @@ use ratatui::buffer::Buffer; use ratatui::layout::Rect; use std::time::Duration; +mod app_link_view; mod approval_overlay; mod request_user_input; +pub(crate) use app_link_view::AppLinkView; pub(crate) use approval_overlay::ApprovalOverlay; pub(crate) use approval_overlay::ApprovalRequest; pub(crate) use request_user_input::RequestUserInputOverlay; @@ -204,6 +208,15 @@ impl BottomPane { self.request_redraw(); } + pub fn set_connectors_snapshot(&mut self, snapshot: Option) { + self.composer.set_connector_mentions(snapshot); + self.request_redraw(); + } + + pub fn take_mention_paths(&mut self) -> HashMap { + self.composer.take_mention_paths() + } + pub fn set_steer_enabled(&mut self, enabled: bool) { self.composer.set_steer_enabled(enabled); } @@ -213,6 +226,10 @@ impl BottomPane { self.request_redraw(); } + pub fn set_connectors_enabled(&mut self, enabled: bool) { + self.composer.set_connectors_enabled(enabled); + } + #[cfg(target_os = "windows")] pub fn set_windows_degraded_sandbox_active(&mut self, enabled: bool) { self.composer.set_windows_degraded_sandbox_active(enabled); diff --git a/codex-rs/tui/src/bottom_pane/skill_popup.rs b/codex-rs/tui/src/bottom_pane/skill_popup.rs index 4736953208..390b44295f 100644 --- a/codex-rs/tui/src/bottom_pane/skill_popup.rs +++ b/codex-rs/tui/src/bottom_pane/skill_popup.rs @@ -14,30 +14,35 @@ use super::selection_popup_common::render_rows_single_line; use crate::key_hint; use crate::render::Insets; use crate::render::RectExt; -use codex_core::skills::model::SkillMetadata; +use crate::text_formatting::truncate_text; +use codex_common::fuzzy_match::fuzzy_match; -use crate::skills_helpers::match_skill; -use crate::skills_helpers::skill_description; -use crate::skills_helpers::skill_display_name; -use crate::skills_helpers::truncated_skill_display_name; +#[derive(Clone, Debug)] +pub(crate) struct MentionItem { + pub(crate) display_name: String, + pub(crate) description: Option, + pub(crate) insert_text: String, + pub(crate) search_terms: Vec, + pub(crate) path: Option, +} pub(crate) struct SkillPopup { query: String, - skills: Vec, + mentions: Vec, state: ScrollState, } impl SkillPopup { - pub(crate) fn new(skills: Vec) -> Self { + pub(crate) fn new(mentions: Vec) -> Self { Self { query: String::new(), - skills, + mentions, state: ScrollState::new(), } } - pub(crate) fn set_skills(&mut self, skills: Vec) { - self.skills = skills; + pub(crate) fn set_mentions(&mut self, mentions: Vec) { + self.mentions = mentions; self.clamp_selection(); } @@ -64,11 +69,11 @@ impl SkillPopup { self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len)); } - pub(crate) fn selected_skill(&self) -> Option<&SkillMetadata> { + pub(crate) fn selected_mention(&self) -> Option<&MentionItem> { let matches = self.filtered_items(); let idx = self.state.selected_idx?; - let skill_idx = matches.get(idx)?; - self.skills.get(*skill_idx) + let mention_idx = matches.get(idx)?; + self.mentions.get(*mention_idx) } fn clamp_selection(&mut self) { @@ -88,14 +93,14 @@ impl SkillPopup { matches .into_iter() .map(|(idx, indices, _score)| { - let skill = &self.skills[idx]; - let name = truncated_skill_display_name(skill); - let description = skill_description(skill).to_string(); + let mention = &self.mentions[idx]; + let name = truncate_text(&mention.display_name, 21); + let description = mention.description.clone().unwrap_or_default(); GenericDisplayRow { name, match_indices: indices, display_shortcut: None, - description: Some(description), + description: Some(description).filter(|desc| !desc.is_empty()), is_disabled: false, disabled_reason: None, wrap_indent: None, @@ -109,23 +114,48 @@ impl SkillPopup { let mut out: Vec<(usize, Option>, i32)> = Vec::new(); if filter.is_empty() { - for (idx, _skill) in self.skills.iter().enumerate() { + for (idx, _mention) in self.mentions.iter().enumerate() { out.push((idx, None, 0)); } return out; } - for (idx, skill) in self.skills.iter().enumerate() { - let display_name = skill_display_name(skill); - if let Some((indices, score)) = match_skill(filter, display_name, &skill.name) { + for (idx, mention) in self.mentions.iter().enumerate() { + let mut best_match: Option<(Option>, i32)> = None; + + if let Some((indices, score)) = fuzzy_match(&mention.display_name, filter) { + best_match = Some((Some(indices), score)); + } + + for term in &mention.search_terms { + if term == &mention.display_name { + continue; + } + + if let Some((_indices, score)) = fuzzy_match(term, filter) { + match best_match.as_mut() { + Some((best_indices, best_score)) => { + if score > *best_score { + *best_score = score; + *best_indices = None; + } + } + None => { + best_match = Some((None, score)); + } + } + } + } + + if let Some((indices, score)) = best_match { out.push((idx, indices, score)); } } out.sort_by(|a, b| { a.2.cmp(&b.2).then_with(|| { - let an = skill_display_name(&self.skills[a.0]); - let bn = skill_display_name(&self.skills[b.0]); + let an = self.mentions[a.0].display_name.as_str(); + let bn = self.mentions[b.0].display_name.as_str(); an.cmp(bn) }) }); @@ -154,7 +184,7 @@ impl WidgetRef for SkillPopup { &rows, &self.state, MAX_POPUP_ROWS, - "no skills", + "no matches", ); if let Some(hint_area) = hint_area { let hint_area = Rect { @@ -172,7 +202,7 @@ fn skill_popup_hint_line() -> Line<'static> { Line::from(vec![ "Press ".into(), key_hint::plain(KeyCode::Enter).into(), - " to select or ".into(), + " to insert or ".into(), key_hint::plain(KeyCode::Esc).into(), " to close".into(), ]) diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index e0707a4228..1efab04ecd 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -11,6 +11,7 @@ use crate::slash_command::built_in_slash_commands; /// Return the built-ins that should be visible/usable for the current input. pub(crate) fn builtins_for_input( collaboration_modes_enabled: bool, + connectors_enabled: bool, personality_command_enabled: bool, allow_elevate_sandbox: bool, ) -> Vec<(&'static str, SlashCommand)> { @@ -18,6 +19,7 @@ pub(crate) fn builtins_for_input( .into_iter() .filter(|(_, cmd)| allow_elevate_sandbox || *cmd != SlashCommand::ElevateSandbox) .filter(|(_, cmd)| collaboration_modes_enabled || *cmd != SlashCommand::Collab) + .filter(|(_, cmd)| connectors_enabled || *cmd != SlashCommand::Apps) .filter(|(_, cmd)| personality_command_enabled || *cmd != SlashCommand::Personality) .collect() } @@ -26,11 +28,13 @@ pub(crate) fn builtins_for_input( pub(crate) fn find_builtin_command( name: &str, collaboration_modes_enabled: bool, + connectors_enabled: bool, personality_command_enabled: bool, allow_elevate_sandbox: bool, ) -> Option { builtins_for_input( collaboration_modes_enabled, + connectors_enabled, personality_command_enabled, allow_elevate_sandbox, ) @@ -43,11 +47,13 @@ pub(crate) fn find_builtin_command( pub(crate) fn has_builtin_prefix( name: &str, collaboration_modes_enabled: bool, + connectors_enabled: bool, personality_command_enabled: bool, allow_elevate_sandbox: bool, ) -> bool { builtins_for_input( collaboration_modes_enabled, + connectors_enabled, personality_command_enabled, allow_elevate_sandbox, ) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index dcbb4d7c22..8a0dd81afe 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -31,6 +31,7 @@ use std::time::Instant; use crate::version::CODEX_CLI_VERSION; use codex_app_server_protocol::AuthMode; use codex_backend_client::Client as BackendClient; +use codex_chatgpt::connectors; use codex_core::config::Config; use codex_core::config::ConstraintResult; use codex_core::config::types::Notifications; @@ -131,6 +132,7 @@ const PLAN_IMPLEMENTATION_NO: &str = "No, stay in Plan mode"; const PLAN_IMPLEMENTATION_CODING_MESSAGE: &str = "Implement the plan."; use crate::app_event::AppEvent; +use crate::app_event::ConnectorsSnapshot; use crate::app_event::ExitMode; #[cfg(target_os = "windows")] use crate::app_event::WindowsSandboxEnableMode; @@ -189,7 +191,9 @@ pub(crate) use self::agent::spawn_op_forwarder; mod session_header; use self::session_header::SessionHeader; mod skills; -use self::skills::find_skill_mentions; +use self::skills::collect_tool_mentions; +use self::skills::find_app_mentions; +use self::skills::find_skill_mentions_with_tool_mentions; use crate::streaming::controller::StreamController; use std::path::Path; @@ -386,6 +390,15 @@ enum RateLimitSwitchPromptState { Shown, } +#[derive(Debug, Clone, Default)] +enum ConnectorsCacheState { + #[default] + Uninitialized, + Loading, + Ready(ConnectorsSnapshot), + Failed(String), +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) enum ExternalEditorState { #[default] @@ -460,6 +473,7 @@ pub(crate) struct ChatWidget { /// bottom pane is treated as "running" while this is populated, even if no agent turn is /// currently executing. mcp_startup_status: Option>, + connectors_cache: ConnectorsCacheState, // Queue of interruptive UI events deferred during an active write cycle interrupts: InterruptManager, // Accumulates the current reasoning block text to extract a header @@ -549,6 +563,7 @@ pub(crate) struct UserMessage { text: String, local_images: Vec, text_elements: Vec, + mention_paths: HashMap, } impl From for UserMessage { @@ -558,6 +573,7 @@ impl From for UserMessage { local_images: Vec::new(), // Plain text conversion has no UI element ranges. text_elements: Vec::new(), + mention_paths: HashMap::new(), } } } @@ -569,6 +585,7 @@ impl From<&str> for UserMessage { local_images: Vec::new(), // Plain text conversion has no UI element ranges. text_elements: Vec::new(), + mention_paths: HashMap::new(), } } } @@ -594,6 +611,7 @@ pub(crate) fn create_initial_user_message( text, local_images, text_elements, + mention_paths: HashMap::new(), }) } } @@ -607,12 +625,14 @@ fn remap_placeholders_for_message(message: UserMessage, next_label: &mut usize) text, text_elements, local_images, + mention_paths, } = message; if local_images.is_empty() { return UserMessage { text, text_elements, local_images, + mention_paths, }; } @@ -667,6 +687,7 @@ fn remap_placeholders_for_message(message: UserMessage, next_label: &mut usize) text: rebuilt, local_images: remapped_images, text_elements: rebuilt_elements, + mention_paths, } } @@ -732,6 +753,7 @@ impl ChatWidget { self.bottom_pane .set_history_metadata(event.history_log_id, event.history_entry_count); self.set_skills(None); + self.bottom_pane.set_connectors_snapshot(None); self.thread_id = Some(event.session_id); self.forked_from = event.forked_from_id; self.current_rollout_path = event.rollout_path.clone(); @@ -762,6 +784,9 @@ impl ChatWidget { cwds: Vec::new(), force_reload: true, }); + if self.connectors_enabled() { + self.prefetch_connectors(); + } if let Some(user_message) = self.initial_user_message.take() { self.submit_user_message(user_message); } @@ -797,6 +822,25 @@ impl ChatWidget { self.request_redraw(); } + pub(crate) fn open_app_link_view( + &mut self, + title: String, + description: Option, + instructions: String, + url: String, + is_installed: bool, + ) { + let view = crate::bottom_pane::AppLinkView::new( + title, + description, + instructions, + url, + is_installed, + ); + self.bottom_pane.show_view(Box::new(view)); + self.request_redraw(); + } + pub(crate) fn open_feedback_consent(&mut self, category: crate::app_event::FeedbackCategory) { let params = crate::bottom_pane::feedback_upload_consent_params( self.app_event_tx.clone(), @@ -1240,6 +1284,7 @@ impl ChatWidget { text: self.bottom_pane.composer_text(), text_elements: self.bottom_pane.composer_text_elements(), local_images: self.bottom_pane.composer_local_images(), + mention_paths: HashMap::new(), }; let mut to_merge: Vec = self.queued_user_messages.drain(..).collect(); @@ -1251,6 +1296,7 @@ impl ChatWidget { text: String::new(), text_elements: Vec::new(), local_images: Vec::new(), + mention_paths: HashMap::new(), }; let mut combined_offset = 0usize; let mut next_image_label = 1usize; @@ -1272,6 +1318,7 @@ impl ChatWidget { elem })); combined.local_images.extend(message.local_images); + combined.mention_paths.extend(message.mention_paths); } Some(combined) @@ -2028,6 +2075,7 @@ impl ChatWidget { unified_exec_processes: Vec::new(), agent_turn_running: false, mcp_startup_status: None, + connectors_cache: ConnectorsCacheState::default(), interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), @@ -2071,6 +2119,10 @@ impl ChatWidget { ); widget.update_collaboration_mode_indicator(); + widget + .bottom_pane + .set_connectors_enabled(widget.config.features.enabled(Feature::Apps)); + widget } @@ -2161,6 +2213,7 @@ impl ChatWidget { unified_exec_processes: Vec::new(), agent_turn_running: false, mcp_startup_status: None, + connectors_cache: ConnectorsCacheState::default(), interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), @@ -2287,6 +2340,7 @@ impl ChatWidget { unified_exec_processes: Vec::new(), agent_turn_running: false, mcp_startup_status: None, + connectors_cache: ConnectorsCacheState::default(), interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), @@ -2436,6 +2490,7 @@ impl ChatWidget { .bottom_pane .take_recent_submission_images_with_placeholders(), text_elements, + mention_paths: self.bottom_pane.take_mention_paths(), }; if self.is_session_configured() { // Submitted is only emitted when steer is enabled (Enter sends immediately). @@ -2458,6 +2513,7 @@ impl ChatWidget { .bottom_pane .take_recent_submission_images_with_placeholders(), text_elements, + mention_paths: self.bottom_pane.take_mention_paths(), }; self.queue_user_message(user_message); } @@ -2675,6 +2731,9 @@ impl ChatWidget { SlashCommand::Mcp => { self.add_mcp_output(); } + SlashCommand::Apps => { + self.add_connectors_output(); + } SlashCommand::Rollout => { if let Some(path) = self.rollout_path() { self.add_info_message( @@ -2833,6 +2892,7 @@ impl ChatWidget { text, local_images, text_elements, + mention_paths, } = user_message; if text.is_empty() && local_images.is_empty() { return; @@ -2871,8 +2931,15 @@ impl ChatWidget { }); } + let mentions = collect_tool_mentions(&text, &mention_paths); + let mut skill_names_lower: HashSet = HashSet::new(); + if let Some(skills) = self.bottom_pane.skills() { - let skill_mentions = find_skill_mentions(&text, skills); + skill_names_lower = skills + .iter() + .map(|skill| skill.name.to_ascii_lowercase()) + .collect(); + let skill_mentions = find_skill_mentions_with_tool_mentions(&mentions, skills); for skill in skill_mentions { items.push(UserInput::Skill { name: skill.name.clone(), @@ -2881,6 +2948,17 @@ impl ChatWidget { } } + if let Some(apps) = self.connectors_for_mentions() { + let app_mentions = find_app_mentions(&mentions, apps, &skill_names_lower); + for app in app_mentions { + let app_id = app.id.as_str(); + items.push(UserInput::Mention { + name: app.name.clone(), + path: format!("app://{app_id}"), + }); + } + } + let effective_mode = self.effective_collaboration_mode(); let collaboration_mode = if self.collaboration_modes_enabled() { self.active_collaboration_mask @@ -3289,6 +3367,28 @@ impl ChatWidget { } } + fn prefetch_connectors(&mut self) { + if !self.connectors_enabled() { + return; + } + if matches!(self.connectors_cache, ConnectorsCacheState::Loading) { + return; + } + + self.connectors_cache = ConnectorsCacheState::Loading; + let config = self.config.clone(); + let app_event_tx = self.app_event_tx.clone(); + tokio::spawn(async move { + let result: Result = async { + let connectors = connectors::list_connectors(&config).await?; + Ok(ConnectorsSnapshot { connectors }) + } + .await; + let result = result.map_err(|err| format!("Failed to load apps: {err}")); + app_event_tx.send(AppEvent::ConnectorsLoaded(result)); + }); + } + fn prefetch_rate_limits(&mut self) { self.stop_rate_limit_poller(); @@ -4973,6 +5073,21 @@ impl ChatWidget { self.request_redraw(); } + fn connectors_enabled(&self) -> bool { + self.config.features.enabled(Feature::Apps) + } + + fn connectors_for_mentions(&self) -> Option<&[connectors::AppInfo]> { + if !self.connectors_enabled() { + return None; + } + + match &self.connectors_cache { + ConnectorsCacheState::Ready(snapshot) => Some(snapshot.connectors.as_slice()), + _ => None, + } + } + /// Build a placeholder header cell while the session is configuring. fn placeholder_session_header_cell(config: &Config) -> Box { let placeholder_style = Style::default().add_modifier(Modifier::DIM | Modifier::ITALIC); @@ -5036,6 +5151,152 @@ impl ChatWidget { } } + pub(crate) fn add_connectors_output(&mut self) { + if !self.connectors_enabled() { + self.add_info_message( + "Apps are disabled.".to_string(), + Some("Enable the apps feature to use $ or /apps.".to_string()), + ); + return; + } + + match self.connectors_cache.clone() { + ConnectorsCacheState::Ready(snapshot) => { + if snapshot.connectors.is_empty() { + self.add_info_message("No apps available.".to_string(), None); + } else { + self.open_connectors_popup(&snapshot.connectors); + } + } + ConnectorsCacheState::Failed(err) => { + self.add_to_history(history_cell::new_error_event(err)); + // Retry on demand so `/apps` can recover after transient failures. + self.prefetch_connectors(); + } + ConnectorsCacheState::Loading => { + self.add_to_history(history_cell::new_info_event( + "Apps are still loading.".to_string(), + Some("Try again in a moment.".to_string()), + )); + } + ConnectorsCacheState::Uninitialized => { + self.prefetch_connectors(); + self.add_to_history(history_cell::new_info_event( + "Apps are still loading.".to_string(), + Some("Try again in a moment.".to_string()), + )); + } + } + self.request_redraw(); + } + + fn open_connectors_popup(&mut self, connectors: &[connectors::AppInfo]) { + let total = connectors.len(); + let installed = connectors + .iter() + .filter(|connector| connector.is_accessible) + .count(); + let mut header = ColumnRenderable::new(); + header.push(Line::from("Apps".bold())); + header.push(Line::from( + "Use $ to insert an installed app into your prompt.".dim(), + )); + header.push(Line::from( + format!("Installed {installed} of {total} available apps.").dim(), + )); + let mut items: Vec = Vec::with_capacity(connectors.len()); + for connector in connectors { + let connector_label = connectors::connector_display_label(connector); + let connector_title = connector_label.clone(); + let link_description = Self::connector_description(connector); + let description = Self::connector_brief_description(connector); + let search_value = format!("{connector_label} {}", connector.id); + let mut item = SelectionItem { + name: connector_label, + description: Some(description), + search_value: Some(search_value), + ..Default::default() + }; + let is_installed = connector.is_accessible; + let (selected_label, missing_label, instructions) = if connector.is_accessible { + ( + "Press Enter to view the app link.", + "App link unavailable.", + "Manage this app in your browser.", + ) + } else { + ( + "Press Enter to view the install link.", + "Install link unavailable.", + "Install this app in your browser, then reload Codex.", + ) + }; + if let Some(install_url) = connector.install_url.clone() { + let title = connector_title.clone(); + let instructions = instructions.to_string(); + let description = link_description.clone(); + item.actions = vec![Box::new(move |tx| { + tx.send(AppEvent::OpenAppLink { + title: title.clone(), + description: description.clone(), + instructions: instructions.clone(), + url: install_url.clone(), + is_installed, + }); + })]; + item.dismiss_on_select = true; + item.selected_description = Some(selected_label.to_string()); + } else { + item.actions = vec![Box::new(move |tx| { + tx.send(AppEvent::InsertHistoryCell(Box::new( + history_cell::new_info_event(missing_label.to_string(), None), + ))); + })]; + item.dismiss_on_select = true; + item.selected_description = Some(missing_label.to_string()); + } + items.push(item); + } + + self.bottom_pane.show_selection_view(SelectionViewParams { + header: Box::new(header), + footer_hint: Some(Self::connectors_popup_hint_line()), + items, + is_searchable: true, + search_placeholder: Some("Type to search apps".to_string()), + ..Default::default() + }); + } + + fn connectors_popup_hint_line() -> Line<'static> { + Line::from(vec![ + "Press ".into(), + key_hint::plain(KeyCode::Esc).into(), + " to close.".into(), + ]) + } + + fn connector_brief_description(connector: &connectors::AppInfo) -> String { + let status_label = if connector.is_accessible { + "Connected" + } else { + "Can be installed" + }; + match Self::connector_description(connector) { + Some(description) => format!("{status_label} · {description}"), + None => status_label.to_string(), + } + } + + fn connector_description(connector: &connectors::AppInfo) -> Option { + connector + .description + .as_deref() + .map(str::trim) + .filter(|description| !description.is_empty()) + .map(str::to_string) + } + /// Forward file-search results to the bottom pane. pub(crate) fn apply_file_search_result(&mut self, query: String, matches: Vec) { self.bottom_pane.on_file_search_result(query, matches); @@ -5220,6 +5481,19 @@ impl ChatWidget { self.set_skills_from_response(&ev); } + pub(crate) fn on_connectors_loaded(&mut self, result: Result) { + self.connectors_cache = match result { + Ok(connectors) => ConnectorsCacheState::Ready(connectors), + Err(err) => ConnectorsCacheState::Failed(err), + }; + if let ConnectorsCacheState::Ready(snapshot) = &self.connectors_cache { + self.bottom_pane + .set_connectors_snapshot(Some(snapshot.clone())); + } else { + self.bottom_pane.set_connectors_snapshot(None); + } + } + pub(crate) fn open_review_popup(&mut self) { let mut items: Vec = Vec::new(); diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index d6893a9e3c..0920c8837b 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -12,6 +12,8 @@ use crate::bottom_pane::SkillsToggleView; use crate::bottom_pane::popup_consts::standard_popup_hint_line; 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; @@ -192,22 +194,256 @@ fn protocol_skill_to_core(skill: &ProtocolSkillMetadata) -> SkillMetadata { } } -pub(crate) fn find_skill_mentions(text: &str, skills: &[SkillMetadata]) -> Vec { - let mut seen: HashSet = HashSet::new(); - let mut matches: Vec = Vec::new(); - for skill in skills { - if seen.contains(&skill.name) { - continue; - } - let needle = format!("${}", skill.name); - if text.contains(&needle) { - seen.insert(skill.name.clone()); - matches.push(skill.clone()); - } - } - matches -} - fn normalize_skill_config_path(path: &Path) -> PathBuf { dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) } + +pub(crate) fn collect_tool_mentions( + text: &str, + mention_paths: &HashMap, +) -> ToolMentions { + let mut mentions = extract_tool_mentions_from_text(text); + for (name, path) in mention_paths { + if mentions.names.contains(name) { + mentions.linked_paths.insert(name.clone(), path.clone()); + } + } + mentions +} + +pub(crate) fn find_skill_mentions_with_tool_mentions( + mentions: &ToolMentions, + skills: &[SkillMetadata], +) -> Vec { + let mention_skill_paths: HashSet<&str> = mentions + .linked_paths + .values() + .filter(|path| is_skill_path(path)) + .map(|path| normalize_skill_path(path)) + .collect(); + + let mut seen_names = HashSet::new(); + let mut seen_paths = HashSet::new(); + let mut matches: Vec = Vec::new(); + + for skill in skills { + if seen_paths.contains(&skill.path) { + continue; + } + let path_str = skill.path.to_string_lossy(); + if mention_skill_paths.contains(path_str.as_ref()) { + seen_paths.insert(skill.path.clone()); + seen_names.insert(skill.name.clone()); + matches.push(skill.clone()); + } + } + + for skill in skills { + if seen_paths.contains(&skill.path) { + continue; + } + if mentions.names.contains(&skill.name) && seen_names.insert(skill.name.clone()) { + seen_paths.insert(skill.path.clone()); + matches.push(skill.clone()); + } + } + + matches +} + +pub(crate) fn find_app_mentions( + mentions: &ToolMentions, + apps: &[AppInfo], + skill_names_lower: &HashSet, +) -> Vec { + let mut explicit_names = HashSet::new(); + let mut selected_ids = HashSet::new(); + for (name, path) in &mentions.linked_paths { + if let Some(connector_id) = app_id_from_path(path) { + explicit_names.insert(name.clone()); + selected_ids.insert(connector_id.to_string()); + } + } + + let mut slug_counts: HashMap = HashMap::new(); + for app in apps { + let slug = connector_mention_slug(app); + *slug_counts.entry(slug).or_insert(0) += 1; + } + + for app in apps { + let slug = connector_mention_slug(app); + let slug_count = slug_counts.get(&slug).copied().unwrap_or(0); + if mentions.names.contains(&slug) + && !explicit_names.contains(&slug) + && slug_count == 1 + && !skill_names_lower.contains(&slug) + { + selected_ids.insert(app.id.clone()); + } + } + + apps.iter() + .filter(|app| selected_ids.contains(&app.id)) + .cloned() + .collect() +} + +pub(crate) struct ToolMentions { + names: HashSet, + linked_paths: HashMap, +} + +fn extract_tool_mentions_from_text(text: &str) -> ToolMentions { + let text_bytes = text.as_bytes(); + let mut names: HashSet = HashSet::new(); + let mut linked_paths: HashMap = HashMap::new(); + + let mut index = 0; + while index < text_bytes.len() { + let byte = text_bytes[index]; + if byte == b'[' + && let Some((name, path, end_index)) = + parse_linked_tool_mention(text, text_bytes, index) + { + if !is_common_env_var(name) { + if !is_app_or_mcp_path(path) { + names.insert(name.to_string()); + } + linked_paths + .entry(name.to_string()) + .or_insert(path.to_string()); + } + index = end_index; + continue; + } + + if byte != b'$' { + index += 1; + continue; + } + + let name_start = index + 1; + let Some(first_name_byte) = text_bytes.get(name_start) else { + index += 1; + continue; + }; + if !is_mention_name_char(*first_name_byte) { + index += 1; + continue; + } + + let mut name_end = name_start + 1; + while let Some(next_byte) = text_bytes.get(name_end) + && is_mention_name_char(*next_byte) + { + name_end += 1; + } + + let name = &text[name_start..name_end]; + if !is_common_env_var(name) { + names.insert(name.to_string()); + } + index = name_end; + } + + ToolMentions { + names, + linked_paths, + } +} + +fn parse_linked_tool_mention<'a>( + text: &'a str, + text_bytes: &[u8], + start: usize, +) -> Option<(&'a str, &'a str, usize)> { + let dollar_index = start + 1; + if text_bytes.get(dollar_index) != Some(&b'$') { + return None; + } + + let name_start = dollar_index + 1; + let first_name_byte = text_bytes.get(name_start)?; + if !is_mention_name_char(*first_name_byte) { + return None; + } + + let mut name_end = name_start + 1; + while let Some(next_byte) = text_bytes.get(name_end) + && is_mention_name_char(*next_byte) + { + name_end += 1; + } + + if text_bytes.get(name_end) != Some(&b']') { + return None; + } + + let mut path_start = name_end + 1; + while let Some(next_byte) = text_bytes.get(path_start) + && next_byte.is_ascii_whitespace() + { + path_start += 1; + } + if text_bytes.get(path_start) != Some(&b'(') { + return None; + } + + let mut path_end = path_start + 1; + while let Some(next_byte) = text_bytes.get(path_end) + && *next_byte != b')' + { + path_end += 1; + } + if text_bytes.get(path_end) != Some(&b')') { + return None; + } + + let path = text[path_start + 1..path_end].trim(); + if path.is_empty() { + return None; + } + + let name = &text[name_start..name_end]; + Some((name, path, path_end + 1)) +} + +fn is_common_env_var(name: &str) -> bool { + let upper = name.to_ascii_uppercase(); + matches!( + upper.as_str(), + "PATH" + | "HOME" + | "USER" + | "SHELL" + | "PWD" + | "TMPDIR" + | "TEMP" + | "TMP" + | "LANG" + | "TERM" + | "XDG_CONFIG_HOME" + ) +} + +fn is_mention_name_char(byte: u8) -> bool { + matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') +} + +fn is_skill_path(path: &str) -> bool { + !is_app_or_mcp_path(path) +} + +fn normalize_skill_path(path: &str) -> &str { + path.strip_prefix("skill://").unwrap_or(path) +} + +fn app_id_from_path(path: &str) -> Option<&str> { + path.strip_prefix("app://") + .filter(|value| !value.is_empty()) +} + +fn is_app_or_mcp_path(path: &str) -> bool { + path.starts_with("app://") || path.starts_with("mcp://") +} diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 78fbc15b49..570a72750b 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -355,6 +355,7 @@ async fn interrupted_turn_restores_queued_messages_with_images_and_elements() { path: first_images[0].clone(), }], text_elements: first_elements, + mention_paths: HashMap::new(), }); chat.queued_user_messages.push_back(UserMessage { text: second_text, @@ -363,6 +364,7 @@ async fn interrupted_turn_restores_queued_messages_with_images_and_elements() { path: second_images[0].clone(), }], text_elements: second_elements, + mention_paths: HashMap::new(), }); chat.refresh_queued_user_messages(); @@ -442,6 +444,7 @@ async fn remap_placeholders_uses_attachment_labels() { text, text_elements: elements, local_images: attachments, + mention_paths: HashMap::new(), }; let mut next_label = 3usize; let remapped = remap_placeholders_for_message(message, &mut next_label); @@ -502,6 +505,7 @@ async fn remap_placeholders_uses_byte_ranges_when_placeholder_missing() { text, text_elements: elements, local_images: attachments, + mention_paths: HashMap::new(), }; let mut next_label = 3usize; let remapped = remap_placeholders_for_message(message, &mut next_label); @@ -810,6 +814,7 @@ async fn make_chatwidget_manual( unified_exec_processes: Vec::new(), agent_turn_running: false, mcp_startup_status: None, + connectors_cache: ConnectorsCacheState::default(), interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), diff --git a/codex-rs/tui/src/skills_helpers.rs b/codex-rs/tui/src/skills_helpers.rs index 8332be886f..1a8c78bb10 100644 --- a/codex-rs/tui/src/skills_helpers.rs +++ b/codex-rs/tui/src/skills_helpers.rs @@ -26,10 +26,6 @@ pub(crate) fn truncate_skill_name(name: &str) -> String { truncate_text(name, SKILL_NAME_TRUNCATE_LEN) } -pub(crate) fn truncated_skill_display_name(skill: &SkillMetadata) -> String { - truncate_skill_name(skill_display_name(skill)) -} - pub(crate) fn match_skill( filter: &str, display_name: &str, diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 8a7a320665..5d1aa8dc45 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -33,6 +33,7 @@ pub enum SlashCommand { Mention, Status, Mcp, + Apps, Logout, Quit, Exit, @@ -69,6 +70,7 @@ impl SlashCommand { SlashCommand::ElevateSandbox => "set up elevated agent sandbox", SlashCommand::Experimental => "toggle experimental features", SlashCommand::Mcp => "list configured MCP tools", + SlashCommand::Apps => "manage apps", SlashCommand::Logout => "log out of Codex", SlashCommand::Rollout => "print the rollout file path", SlashCommand::TestApproval => "test approval request", @@ -104,6 +106,7 @@ impl SlashCommand { | SlashCommand::Status | SlashCommand::Ps | SlashCommand::Mcp + | SlashCommand::Apps | SlashCommand::Feedback | SlashCommand::Quit | SlashCommand::Exit => true, From 335713f7e98551ee7e8c84d7afb380dddf075ead Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 22:00:48 -0700 Subject: [PATCH 056/116] chore(core) personality under development (#10133) ## Summary Have one or two more changes coming in for this. --- codex-rs/core/src/features.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index c7cd411145..9bc52537b7 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -552,11 +552,7 @@ pub const FEATURES: &[FeatureSpec] = &[ FeatureSpec { id: Feature::Personality, key: "personality", - stage: Stage::Experimental { - name: "Personality", - menu_description: "Choose a communication style for Codex.", - announcement: "NEW! Update codex's communication style with /personality. Enable in /experimental!", - }, + stage: Stage::UnderDevelopment, default_enabled: false, }, FeatureSpec { From 8cc338aecf73ee1a04917413ee2d9905c468fb4b Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Wed, 28 Jan 2026 21:51:51 -0800 Subject: [PATCH 057/116] emit a metric when we can't spawn powershell (#10125) This will help diagnose and measure the impact of a user-reported bug with the elevated sandbox and powershell --- codex-rs/core/src/exec.rs | 75 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 37f6c2de96..e0d65c8305 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -232,6 +232,72 @@ pub(crate) async fn execute_exec_env( finalize_exec_result(raw_output_result, sandbox, duration) } +#[cfg(target_os = "windows")] +fn extract_create_process_as_user_error_code(err: &str) -> Option { + let marker = "CreateProcessAsUserW failed: "; + let start = err.find(marker)? + marker.len(); + let tail = &err[start..]; + let digits: String = tail.chars().take_while(char::is_ascii_digit).collect(); + if digits.is_empty() { + None + } else { + Some(digits) + } +} + +#[cfg(target_os = "windows")] +fn windowsapps_path_kind(path: &str) -> &'static str { + let lower = path.to_ascii_lowercase(); + if lower.contains("\\program files\\windowsapps\\") { + return "windowsapps_package"; + } + if lower.contains("\\appdata\\local\\microsoft\\windowsapps\\") { + return "windowsapps_alias"; + } + if lower.contains("\\windowsapps\\") { + return "windowsapps_other"; + } + "other" +} + +#[cfg(target_os = "windows")] +fn record_windows_sandbox_spawn_failure( + command_path: Option<&str>, + windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, + err: &str, +) { + let Some(error_code) = extract_create_process_as_user_error_code(err) else { + return; + }; + let path = command_path.unwrap_or("unknown"); + let exe = Path::new(path) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("unknown") + .to_ascii_lowercase(); + let path_kind = windowsapps_path_kind(path); + let level = if matches!( + windows_sandbox_level, + codex_protocol::config_types::WindowsSandboxLevel::Elevated + ) { + "elevated" + } else { + "legacy" + }; + if let Some(metrics) = codex_otel::metrics::global() { + let _ = metrics.counter( + "codex.windows_sandbox.createprocessasuserw_failed", + 1, + &[ + ("error_code", error_code.as_str()), + ("path_kind", path_kind), + ("exe", exe.as_str()), + ("level", level), + ], + ); + } +} + #[cfg(target_os = "windows")] async fn exec_windows_sandbox( params: ExecParams, @@ -265,7 +331,9 @@ async fn exec_windows_sandbox( "windows sandbox: failed to resolve codex_home: {err}" ))) })?; - let use_elevated = matches!(windows_sandbox_level, WindowsSandboxLevel::Elevated); + let command_path = command.first().cloned(); + let sandbox_level = windows_sandbox_level; + let use_elevated = matches!(sandbox_level, WindowsSandboxLevel::Elevated); let spawn_res = tokio::task::spawn_blocking(move || { if use_elevated { run_windows_sandbox_capture_elevated( @@ -294,6 +362,11 @@ async fn exec_windows_sandbox( let capture = match spawn_res { Ok(Ok(v)) => v, Ok(Err(err)) => { + record_windows_sandbox_spawn_failure( + command_path.as_deref(), + sandbox_level, + &err.to_string(), + ); return Err(CodexErr::Io(io::Error::other(format!( "windows sandbox: {err}" )))); From be33de3f8768a47f426761fa6cc017aef9716135 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 22:51:57 -0700 Subject: [PATCH 058/116] fix(tui) reorder personality command (#10134) ## Summary Reorder it down the list ## Testing - [x] Tests pass --- 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 5d1aa8dc45..9bab314610 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -13,7 +13,6 @@ pub enum SlashCommand { // DO NOT ALPHA-SORT! Enum order is presentation order in the popup, so // more frequently used commands should be listed first. Model, - Personality, Approvals, Permissions, #[strum(serialize = "setup-elevated-sandbox")] @@ -40,6 +39,7 @@ pub enum SlashCommand { Feedback, Rollout, Ps, + Personality, TestApproval, } From b4b47630098b6d1ae89f6b2873dd313859b38ec5 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Wed, 28 Jan 2026 22:58:55 -0700 Subject: [PATCH 059/116] fix(ci) missing package.json for shell-mcp-tool (#10135) ## Summary This _should_ be the final place to fix. --- .github/workflows/shell-tool-mcp.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 446af67918..39f176cbf4 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -445,6 +445,9 @@ jobs: id-token: write contents: read steps: + - name: Checkout repository + uses: actions/checkout@v6 + - name: Setup pnpm uses: pnpm/action-setup@v4 with: From e70592f85ad2c86aaa5e45754d9e2dc89a8ab113 Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Wed, 28 Jan 2026 22:13:53 -0800 Subject: [PATCH 060/116] fix: ignore key release events during onboarding (#10131) ## Summary - guard onboarding key handling to ignore KeyEventKind::Release - handle key events at the onboarding screen boundary to avoid double-triggering widgets ## Related - https://github.com/ratatui/ratatui/issues/347 ## Testing - cd codex-rs && just fmt - cd codex-rs && cargo test -p codex-tui --- codex-rs/tui/src/onboarding/onboarding_screen.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/codex-rs/tui/src/onboarding/onboarding_screen.rs b/codex-rs/tui/src/onboarding/onboarding_screen.rs index 78a7f0ce85..09be507fff 100644 --- a/codex-rs/tui/src/onboarding/onboarding_screen.rs +++ b/codex-rs/tui/src/onboarding/onboarding_screen.rs @@ -211,6 +211,9 @@ impl OnboardingScreen { impl KeyboardHandler for OnboardingScreen { fn handle_key_event(&mut self, key_event: KeyEvent) { + if !matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat) { + return; + } let is_api_key_entry_active = self.is_api_key_entry_active(); let should_quit = match key_event { KeyEvent { From 4d9ae3a2989949d79b75538ab5769c35547f084c Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 28 Jan 2026 23:31:25 -0800 Subject: [PATCH 061/116] fix: remove references to corepack (#10138) Currently, our `npm publish` logic is failing. There were a number of things that were merged recently that seemed to contribute to this situation, though I think we have fixed most of them, but this one stands out: https://github.com/openai/codex/pull/10115 As best I can tell, we tried to fix the pnpm version to a specific hash, but we did not do it consistently (though `shell-tool-mcp/package.json` had it specified twice...), so for this PR, I ran: ``` $ git ls-files | grep package.json codex-cli/package.json codex-rs/responses-api-proxy/npm/package.json package.json sdk/typescript/package.json shell-tool-mcp/package.json ``` and ensured that all of them now have this line: ```json "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264" ``` I also went and deleted all of the `corepack` stuff that was added by https://github.com/openai/codex/pull/10115. If someone can explain why we need it and verify it does not break `npm publish`, then we can bring it back. --- .github/workflows/shell-tool-mcp-ci.yml | 9 --- .github/workflows/shell-tool-mcp.yml | 18 ----- PNPM.md | 70 ------------------- codex-cli/package.json | 3 +- codex-rs/responses-api-proxy/npm/package.json | 3 +- sdk/typescript/package.json | 3 +- shell-tool-mcp/package.json | 1 - 7 files changed, 6 insertions(+), 101 deletions(-) delete mode 100644 PNPM.md diff --git a/.github/workflows/shell-tool-mcp-ci.yml b/.github/workflows/shell-tool-mcp-ci.yml index bea88ad891..739cc6e409 100644 --- a/.github/workflows/shell-tool-mcp-ci.yml +++ b/.github/workflows/shell-tool-mcp-ci.yml @@ -35,15 +35,6 @@ jobs: node-version: ${{ env.NODE_VERSION }} cache: "pnpm" - - name: Enable Corepack - run: corepack enable - - - name: Activate pnpm from package.json - run: corepack prepare --activate - - - name: Verify pnpm version - run: pnpm --version - - name: Install dependencies run: pnpm install --frozen-lockfile diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 39f176cbf4..d6c85d9ddc 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -351,15 +351,6 @@ jobs: with: node-version: ${{ env.NODE_VERSION }} - - name: Enable Corepack - run: corepack enable - - - name: Activate pnpm from package.json - run: corepack prepare --activate - - - name: Verify pnpm version - run: pnpm --version - - name: Install JavaScript dependencies run: pnpm install --frozen-lockfile @@ -460,15 +451,6 @@ jobs: registry-url: https://registry.npmjs.org scope: "@openai" - - name: Enable Corepack - run: corepack enable - - - name: Activate pnpm from package.json - run: corepack prepare --activate - - - name: Verify pnpm version - run: pnpm --version - - name: Download npm tarball uses: actions/download-artifact@v7 with: diff --git a/PNPM.md b/PNPM.md deleted file mode 100644 index 9f05e39cf8..0000000000 --- a/PNPM.md +++ /dev/null @@ -1,70 +0,0 @@ -# Migration to pnpm - -This project has been migrated from npm to pnpm to improve dependency management and developer experience. - -## Why pnpm? - -- **Faster installation**: pnpm is significantly faster than npm and yarn -- **Disk space savings**: pnpm uses a content-addressable store to avoid duplication -- **Phantom dependency prevention**: pnpm creates a strict node_modules structure -- **Native workspaces support**: simplified monorepo management - -## How to use pnpm - -### Installation - -```bash -# Global installation of pnpm -npm install -g pnpm@10.28.2 - -# Or with corepack (available with Node.js 22+) -corepack enable -corepack prepare pnpm@10.8.1 --activate -``` - -### Common commands - -| npm command | pnpm equivalent | -| --------------- | ---------------- | -| `npm install` | `pnpm install` | -| `npm run build` | `pnpm run build` | -| `npm test` | `pnpm test` | -| `npm run lint` | `pnpm run lint` | - -### Workspace-specific commands - -| Action | Command | -| ------------------------------------------ | ---------------------------------------- | -| Run a command in a specific package | `pnpm --filter @openai/codex run build` | -| Install a dependency in a specific package | `pnpm --filter @openai/codex add lodash` | -| Run a command in all packages | `pnpm -r run test` | - -## Monorepo structure - -``` -codex/ -├── pnpm-workspace.yaml # Workspace configuration -├── .npmrc # pnpm configuration -├── package.json # Root dependencies and scripts -├── codex-cli/ # Main package -│ └── package.json # codex-cli specific dependencies -└── docs/ # Documentation (future package) -``` - -## Configuration files - -- **pnpm-workspace.yaml**: Defines the packages included in the monorepo -- **.npmrc**: Configures pnpm behavior -- **Root package.json**: Contains shared scripts and dependencies - -## CI/CD - -CI/CD workflows have been updated to use pnpm instead of npm. Make sure your CI environments use pnpm 10.28.2 or higher. - -## Known issues - -If you encounter issues with pnpm, try the following solutions: - -1. Remove the `node_modules` folder and `pnpm-lock.yaml` file, then run `pnpm install` -2. Make sure you're using pnpm 10.28.2 or higher -3. Verify that Node.js 22 or higher is installed diff --git a/codex-cli/package.json b/codex-cli/package.json index b83309e42b..3d1a2dcc2c 100644 --- a/codex-cli/package.json +++ b/codex-cli/package.json @@ -17,5 +17,6 @@ "type": "git", "url": "git+https://github.com/openai/codex.git", "directory": "codex-cli" - } + }, + "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264" } diff --git a/codex-rs/responses-api-proxy/npm/package.json b/codex-rs/responses-api-proxy/npm/package.json index f3956a77d6..d72b60e218 100644 --- a/codex-rs/responses-api-proxy/npm/package.json +++ b/codex-rs/responses-api-proxy/npm/package.json @@ -17,5 +17,6 @@ "type": "git", "url": "git+https://github.com/openai/codex.git", "directory": "codex-rs/responses-api-proxy/npm" - } + }, + "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264" } diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json index 55ecd1abf3..ab29c3fcec 100644 --- a/sdk/typescript/package.json +++ b/sdk/typescript/package.json @@ -62,5 +62,6 @@ "typescript-eslint": "^8.45.0", "zod": "^3.24.2", "zod-to-json-schema": "^3.24.6" - } + }, + "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264" } diff --git a/shell-tool-mcp/package.json b/shell-tool-mcp/package.json index c6dfcd7a55..24798b2f6e 100644 --- a/shell-tool-mcp/package.json +++ b/shell-tool-mcp/package.json @@ -3,7 +3,6 @@ "version": "0.0.0-dev", "description": "Codex MCP server for the shell tool with patched Bash and exec wrappers.", "license": "Apache-2.0", - "packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264", "bin": { "codex-shell-tool-mcp": "bin/mcp-server.js" }, From 780482da84e2bb14b9900e75b04ca2e4f65dfddb Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 10:23:03 +0100 Subject: [PATCH 062/116] feat: add log db (#10086) Add a log DB. The goal is just to store our logs in a `.sqlite` DB to make it easier to crawl them and drop the oldest ones. --- codex-rs/Cargo.lock | 2 + codex-rs/core/src/state_db.rs | 1 + codex-rs/state/Cargo.toml | 1 + codex-rs/state/migrations/0002_logs.sql | 14 ++ codex-rs/state/src/lib.rs | 2 + codex-rs/state/src/log_db.rs | 162 ++++++++++++++++++ codex-rs/state/src/model/log.rs | 14 ++ codex-rs/state/src/model/mod.rs | 15 ++ .../{model.rs => model/thread_metadata.rs} | 0 codex-rs/state/src/runtime.rs | 30 ++++ codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/lib.rs | 6 + 12 files changed, 248 insertions(+) create mode 100644 codex-rs/state/migrations/0002_logs.sql create mode 100644 codex-rs/state/src/log_db.rs create mode 100644 codex-rs/state/src/model/log.rs create mode 100644 codex-rs/state/src/model/mod.rs rename codex-rs/state/src/{model.rs => model/thread_metadata.rs} (100%) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 08cc850524..0ae6c60d42 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1859,6 +1859,7 @@ dependencies = [ "sqlx", "tokio", "tracing", + "tracing-subscriber", "uuid", ] @@ -1897,6 +1898,7 @@ dependencies = [ "codex-login", "codex-otel", "codex-protocol", + "codex-state", "codex-utils-absolute-path", "codex-utils-cargo-bin", "codex-utils-pty", diff --git a/codex-rs/core/src/state_db.rs b/codex-rs/core/src/state_db.rs index d859328e1c..74c9ed7383 100644 --- a/codex-rs/core/src/state_db.rs +++ b/codex-rs/core/src/state_db.rs @@ -12,6 +12,7 @@ use codex_protocol::ThreadId; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; use codex_state::DB_METRIC_BACKFILL; +pub use codex_state::LogEntry; use codex_state::STATE_DB_FILENAME; use codex_state::ThreadMetadataBuilder; use serde_json::Value; diff --git a/codex-rs/state/Cargo.toml b/codex-rs/state/Cargo.toml index 810e250ca7..b8c7fce0e3 100644 --- a/codex-rs/state/Cargo.toml +++ b/codex-rs/state/Cargo.toml @@ -14,6 +14,7 @@ serde_json = { workspace = true } sqlx = { workspace = true } tokio = { workspace = true, features = ["fs", "io-util", "macros", "rt-multi-thread", "sync", "time"] } tracing = { workspace = true } +tracing-subscriber = { workspace = true } uuid = { workspace = true } [dev-dependencies] diff --git a/codex-rs/state/migrations/0002_logs.sql b/codex-rs/state/migrations/0002_logs.sql new file mode 100644 index 0000000000..4a193500b9 --- /dev/null +++ b/codex-rs/state/migrations/0002_logs.sql @@ -0,0 +1,14 @@ +CREATE TABLE logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts INTEGER NOT NULL, + ts_nanos INTEGER NOT NULL, + level TEXT NOT NULL, + target TEXT NOT NULL, + message TEXT, + fields_json TEXT NOT NULL, + module_path TEXT, + file TEXT, + line INTEGER +); + +CREATE INDEX idx_logs_ts ON logs(ts DESC, ts_nanos DESC, id DESC); diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs index 67533a3791..91ebacea71 100644 --- a/codex-rs/state/src/lib.rs +++ b/codex-rs/state/src/lib.rs @@ -5,11 +5,13 @@ //! orchestration and rollout scanning live in `codex-core`. mod extract; +pub mod log_db; mod migrations; mod model; mod paths; mod runtime; +pub use model::LogEntry; /// Preferred entrypoint: owns configuration and metrics. pub use runtime::StateRuntime; diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs new file mode 100644 index 0000000000..c03b7977d3 --- /dev/null +++ b/codex-rs/state/src/log_db.rs @@ -0,0 +1,162 @@ +//! Tracing log export into the state SQLite database. +//! +//! This module provides a `tracing_subscriber::Layer` that captures events and +//! inserts them into the `logs` table in `state.sqlite`. The writer runs in a +//! background task and batches inserts to keep logging overhead low. +//! +//! ## Usage +//! +//! ```no_run +//! use codex_state::log_db; +//! use tracing_subscriber::prelude::*; +//! +//! # async fn example(state_db: std::sync::Arc) { +//! let layer = log_db::start(state_db); +//! let _ = tracing_subscriber::registry() +//! .with(layer) +//! .try_init(); +//! # } +//! ``` + +use std::time::Duration; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; + +use serde_json::Value; +use tokio::sync::mpsc; +use tracing::Event; +use tracing::field::Field; +use tracing::field::Visit; +use tracing_subscriber::Layer; +use tracing_subscriber::registry::LookupSpan; + +use crate::LogEntry; +use crate::StateRuntime; + +const LOG_QUEUE_CAPACITY: usize = 512; +const LOG_BATCH_SIZE: usize = 64; +const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(250); + +pub struct LogDbLayer { + sender: mpsc::Sender, +} + +pub fn start(state_db: std::sync::Arc) -> LogDbLayer { + let (sender, receiver) = mpsc::channel(LOG_QUEUE_CAPACITY); + tokio::spawn(run_inserter(state_db, receiver)); + + LogDbLayer { sender } +} + +impl Layer for LogDbLayer +where + S: tracing::Subscriber + for<'a> LookupSpan<'a>, +{ + fn on_event(&self, event: &Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>) { + let metadata = event.metadata(); + let mut visitor = JsonVisitor::default(); + event.record(&mut visitor); + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_else(|_| Duration::from_secs(0)); + let entry = LogEntry { + ts: now.as_secs() as i64, + ts_nanos: now.subsec_nanos() as i64, + level: metadata.level().as_str().to_string(), + target: metadata.target().to_string(), + message: visitor.message, + fields_json: Value::Object(visitor.fields).to_string(), + module_path: metadata.module_path().map(ToString::to_string), + file: metadata.file().map(ToString::to_string), + line: metadata.line().map(|line| line as i64), + }; + + let _ = self.sender.try_send(entry); + } +} + +async fn run_inserter( + state_db: std::sync::Arc, + 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) => { + buffer.push(entry); + if buffer.len() >= LOG_BATCH_SIZE { + flush(&state_db, &mut buffer).await; + } + } + None => { + flush(&state_db, &mut buffer).await; + break; + } + } + } + _ = ticker.tick() => { + flush(&state_db, &mut buffer).await; + } + } + } +} + +async fn flush(state_db: &std::sync::Arc, buffer: &mut Vec) { + if buffer.is_empty() { + return; + } + let entries = buffer.split_off(0); + let _ = state_db.insert_logs(entries.as_slice()).await; +} + +#[derive(Default)] +struct JsonVisitor { + fields: serde_json::Map, + message: Option, +} + +impl JsonVisitor { + fn record_value(&mut self, field: &Field, value: Value) { + if field.name() == "message" && self.message.is_none() { + self.message = Some(match &value { + Value::String(message) => message.clone(), + _ => value.to_string(), + }); + } + self.fields.insert(field.name().to_string(), value); + } +} + +impl Visit for JsonVisitor { + fn record_i64(&mut self, field: &Field, value: i64) { + self.record_value(field, Value::from(value)); + } + + fn record_u64(&mut self, field: &Field, value: u64) { + self.record_value(field, Value::from(value)); + } + + fn record_bool(&mut self, field: &Field, value: bool) { + self.record_value(field, Value::from(value)); + } + + fn record_f64(&mut self, field: &Field, value: f64) { + self.record_value(field, Value::from(value)); + } + + fn record_str(&mut self, field: &Field, value: &str) { + self.record_value(field, Value::from(value)); + } + + fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { + self.record_value(field, Value::from(value.to_string())); + } + + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + self.record_value(field, Value::from(format!("{value:?}"))); + } +} diff --git a/codex-rs/state/src/model/log.rs b/codex-rs/state/src/model/log.rs new file mode 100644 index 0000000000..5662a3725c --- /dev/null +++ b/codex-rs/state/src/model/log.rs @@ -0,0 +1,14 @@ +use serde::Serialize; + +#[derive(Clone, Debug, Serialize)] +pub struct LogEntry { + pub ts: i64, + pub ts_nanos: i64, + pub level: String, + pub target: String, + pub message: Option, + pub fields_json: String, + pub module_path: Option, + pub file: Option, + pub line: Option, +} diff --git a/codex-rs/state/src/model/mod.rs b/codex-rs/state/src/model/mod.rs new file mode 100644 index 0000000000..4921e2357a --- /dev/null +++ b/codex-rs/state/src/model/mod.rs @@ -0,0 +1,15 @@ +mod log; +mod thread_metadata; + +pub use log::LogEntry; +pub use thread_metadata::Anchor; +pub use thread_metadata::BackfillStats; +pub use thread_metadata::ExtractionOutcome; +pub use thread_metadata::SortKey; +pub use thread_metadata::ThreadMetadata; +pub use thread_metadata::ThreadMetadataBuilder; +pub use thread_metadata::ThreadsPage; + +pub(crate) use thread_metadata::ThreadRow; +pub(crate) use thread_metadata::anchor_from_item; +pub(crate) use thread_metadata::datetime_to_epoch_seconds; diff --git a/codex-rs/state/src/model.rs b/codex-rs/state/src/model/thread_metadata.rs similarity index 100% rename from codex-rs/state/src/model.rs rename to codex-rs/state/src/model/thread_metadata.rs diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index f341ee3bb6..34add1347d 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -1,4 +1,5 @@ use crate::DB_ERROR_METRIC; +use crate::LogEntry; use crate::SortKey; use crate::ThreadMetadata; use crate::ThreadMetadataBuilder; @@ -201,6 +202,35 @@ FROM threads }) } + /// Insert one log entry into the logs table. + pub async fn insert_log(&self, entry: &LogEntry) -> anyhow::Result<()> { + self.insert_logs(std::slice::from_ref(entry)).await + } + + /// Insert a batch of log entries into the logs table. + pub async fn insert_logs(&self, entries: &[LogEntry]) -> anyhow::Result<()> { + if entries.is_empty() { + return Ok(()); + } + + let mut builder = QueryBuilder::::new( + "INSERT INTO logs (ts, ts_nanos, level, target, message, fields_json, module_path, file, line) ", + ); + builder.push_values(entries, |mut row, entry| { + row.push_bind(entry.ts) + .push_bind(entry.ts_nanos) + .push_bind(&entry.level) + .push_bind(&entry.target) + .push_bind(&entry.message) + .push_bind(&entry.fields_json) + .push_bind(&entry.module_path) + .push_bind(&entry.file) + .push_bind(entry.line); + }); + builder.build().execute(self.pool.as_ref()).await?; + Ok(()) + } + /// List thread ids using the underlying database (no rollout scanning). pub async fn list_thread_ids( &self, diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 820fe20e93..6664e7f9c5 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -42,6 +42,7 @@ codex-file-search = { workspace = true } codex-login = { workspace = true } codex-otel = { workspace = true } codex-protocol = { workspace = true } +codex-state = { workspace = true } codex-utils-absolute-path = { workspace = true } color-eyre = { workspace = true } crossterm = { workspace = true, features = ["bracketed-paste", "event-stream"] } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index bced1e0653..a48b806129 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -36,6 +36,7 @@ use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; +use codex_state::log_db; use codex_utils_absolute_path::AbsolutePathBuf; use cwd_prompt::CwdPromptAction; use cwd_prompt::CwdSelection; @@ -351,10 +352,15 @@ pub async fn run_main( let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); + let log_db_layer = codex_core::state_db::init_if_enabled(&config, None) + .await + .map(|db| log_db::start(db).with_filter(env_filter())); + let _ = tracing_subscriber::registry() .with(file_layer) .with(feedback_layer) .with(feedback_metadata_layer) + .with(log_db_layer) .with(otel_logger_layer) .with(otel_tracing_layer) .try_init(); From 714dc8d8bd1a8d28fe71df4e1c1bc5f3f5752b91 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 10:57:50 +0100 Subject: [PATCH 063/116] feat: async backfill (#10089) --- .../app-server/src/codex_message_processor.rs | 6 +- codex-rs/core/src/rollout/metadata.rs | 22 +++++++- codex-rs/core/src/state_db.rs | 55 ++++++++++++------- codex-rs/tui/src/lib.rs | 2 +- 4 files changed, 58 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 e86d840b94..e1c982a99d 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -168,7 +168,7 @@ use codex_core::read_head_for_summary; use codex_core::read_session_meta_line; use codex_core::rollout_date_parts; use codex_core::sandboxing::SandboxPermissions; -use codex_core::state_db::{self}; +use codex_core::state_db::get_state_db; use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_feedback::CodexFeedback; use codex_login::ServerOptions as LoginServerOptions; @@ -1702,7 +1702,7 @@ impl CodexMessageProcessor { let rollout_path_display = archived_path.display().to_string(); let fallback_provider = self.config.model_provider_id.clone(); - let state_db_ctx = state_db::init_if_enabled(&self.config, None).await; + let state_db_ctx = get_state_db(&self.config, None).await; let archived_folder = self .config .codex_home @@ -3571,7 +3571,7 @@ impl CodexMessageProcessor { } if state_db_ctx.is_none() { - state_db_ctx = state_db::init_if_enabled(&self.config, None).await; + state_db_ctx = get_state_db(&self.config, None).await; } // Move the rollout file to archived. diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs index 32d13ebde2..d08e77e241 100644 --- a/codex-rs/core/src/rollout/metadata.rs +++ b/codex-rs/core/src/rollout/metadata.rs @@ -15,12 +15,14 @@ use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; use codex_state::BackfillStats; use codex_state::DB_ERROR_METRIC; +use codex_state::DB_METRIC_BACKFILL; use codex_state::ExtractionOutcome; use codex_state::ThreadMetadataBuilder; use codex_state::apply_rollout_item; use std::cmp::Reverse; use std::path::Path; use std::path::PathBuf; +use tracing::info; use tracing::warn; const ROLLOUT_PREFIX: &str = "rollout-"; @@ -125,7 +127,7 @@ pub(crate) async fn backfill_sessions( runtime: &codex_state::StateRuntime, config: &Config, otel: Option<&OtelManager>, -) -> BackfillStats { +) { let sessions_root = config.codex_home.join(rollout::SESSIONS_SUBDIR); let archived_root = config.codex_home.join(rollout::ARCHIVED_SESSIONS_SUBDIR); let mut rollout_paths: Vec<(PathBuf, bool)> = Vec::new(); @@ -191,7 +193,23 @@ pub(crate) async fn backfill_sessions( } } } - stats + + info!( + "state db backfill scanned={}, upserted={}, failed={}", + stats.scanned, stats.upserted, stats.failed + ); + if let Some(otel) = otel { + otel.counter( + DB_METRIC_BACKFILL, + stats.upserted as i64, + &[("status", "upserted")], + ); + otel.counter( + DB_METRIC_BACKFILL, + stats.failed as i64, + &[("status", "failed")], + ); + } } async fn file_modified_time_utc(path: &Path) -> Option> { diff --git a/codex-rs/core/src/state_db.rs b/codex-rs/core/src/state_db.rs index 74c9ed7383..7990a017ef 100644 --- a/codex-rs/core/src/state_db.rs +++ b/codex-rs/core/src/state_db.rs @@ -11,7 +11,6 @@ use codex_otel::OtelManager; use codex_protocol::ThreadId; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; -use codex_state::DB_METRIC_BACKFILL; pub use codex_state::LogEntry; use codex_state::STATE_DB_FILENAME; use codex_state::ThreadMetadataBuilder; @@ -19,15 +18,18 @@ use serde_json::Value; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; -use tracing::info; use tracing::warn; use uuid::Uuid; /// Core-facing handle to the optional SQLite-backed state runtime. pub type StateDbHandle = Arc; -/// Initialize the state runtime when the `sqlite` feature flag is enabled. -pub async fn init_if_enabled(config: &Config, otel: Option<&OtelManager>) -> Option { +/// Initialize the state runtime when the `sqlite` feature flag is enabled. To only be used +/// inside `core`. The initialization should not be done anywhere else. +pub(crate) async fn init_if_enabled( + config: &Config, + otel: Option<&OtelManager>, +) -> Option { let state_path = config.codex_home.join(STATE_DB_FILENAME); if !config.features.enabled(Feature::Sqlite) { // We delete the file on best effort basis to maintain retro-compatibility in the future. @@ -59,27 +61,38 @@ pub async fn init_if_enabled(config: &Config, otel: Option<&OtelManager>) -> Opt } }; if !existed { - let stats = metadata::backfill_sessions(runtime.as_ref(), config, otel).await; - info!( - "state db backfill scanned={}, upserted={}, failed={}", - stats.scanned, stats.upserted, stats.failed - ); - if let Some(otel) = otel { - otel.counter( - DB_METRIC_BACKFILL, - stats.upserted as i64, - &[("status", "upserted")], - ); - otel.counter( - DB_METRIC_BACKFILL, - stats.failed as i64, - &[("status", "failed")], - ); - } + let runtime_for_backfill = Arc::clone(&runtime); + let config_for_backfill = config.clone(); + let otel_for_backfill = otel.cloned(); + tokio::task::spawn(async move { + metadata::backfill_sessions( + runtime_for_backfill.as_ref(), + &config_for_backfill, + otel_for_backfill.as_ref(), + ) + .await; + }); } Some(runtime) } +/// Get the DB if the feature is enabled and the DB exists. +pub async fn get_state_db(config: &Config, otel: Option<&OtelManager>) -> Option { + let state_path = config.codex_home.join(STATE_DB_FILENAME); + if !config.features.enabled(Feature::Sqlite) + || !tokio::fs::try_exists(&state_path).await.unwrap_or(false) + { + return None; + } + codex_state::StateRuntime::init( + config.codex_home.clone(), + config.model_provider_id.clone(), + otel.cloned(), + ) + .await + .ok() +} + /// Open the state runtime when the SQLite file exists, without feature gating. /// /// This is used for parity checks during the SQLite migration phase. diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index a48b806129..c9e69b7125 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -352,7 +352,7 @@ pub async fn run_main( let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); - let log_db_layer = codex_core::state_db::init_if_enabled(&config, None) + let log_db_layer = codex_core::state_db::get_state_db(&config, None) .await .map(|db| log_db::start(db).with_filter(env_filter())); From 6a06726af2469e766528c5f6460e5f047fabd7f3 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 11:11:47 +0100 Subject: [PATCH 064/116] feat: log db client (#10087) ``` just log -h if [ "${1:-}" = "--" ]; then shift; fi; cargo run -p codex-state --bin logs_client -- "$@" Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.21s Running `target/debug/logs_client -h` Tail Codex logs from state.sqlite with simple filters Usage: logs_client [OPTIONS] Options: --codex-home Path to CODEX_HOME. Defaults to $CODEX_HOME or ~/.codex [env: CODEX_HOME=] --db Direct path to the SQLite database. Overrides --codex-home --level Log level to match exactly (case-insensitive) --from Start timestamp (RFC3339 or unix seconds) --to End timestamp (RFC3339 or unix seconds) --module Substring match on module_path --file Substring match on file path --backfill Number of matching rows to show before tailing [default: 200] --poll-ms Poll interval in milliseconds [default: 500] -h, --help Print help ``` --- codex-rs/Cargo.lock | 2 + codex-rs/state/Cargo.toml | 2 + codex-rs/state/src/bin/logs_client.rs | 293 ++++++++++++++++++++++++++ justfile | 4 + 4 files changed, 301 insertions(+) create mode 100644 codex-rs/state/src/bin/logs_client.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 0ae6c60d42..f47e054ba6 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1851,8 +1851,10 @@ version = "0.0.0" dependencies = [ "anyhow", "chrono", + "clap", "codex-otel", "codex-protocol", + "dirs", "pretty_assertions", "serde", "serde_json", diff --git a/codex-rs/state/Cargo.toml b/codex-rs/state/Cargo.toml index b8c7fce0e3..a6e36a3e00 100644 --- a/codex-rs/state/Cargo.toml +++ b/codex-rs/state/Cargo.toml @@ -7,8 +7,10 @@ license.workspace = true [dependencies] anyhow = { workspace = true } chrono = { workspace = true } +clap = { workspace = true, features = ["derive", "env"] } codex-otel = { workspace = true } codex-protocol = { workspace = true } +dirs = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } sqlx = { workspace = true } diff --git a/codex-rs/state/src/bin/logs_client.rs b/codex-rs/state/src/bin/logs_client.rs new file mode 100644 index 0000000000..13bcb1571d --- /dev/null +++ b/codex-rs/state/src/bin/logs_client.rs @@ -0,0 +1,293 @@ +use std::path::Path; +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::Context; +use chrono::DateTime; +use chrono::SecondsFormat; +use chrono::Utc; +use clap::Parser; +use codex_state::STATE_DB_FILENAME; +use dirs::home_dir; +use sqlx::QueryBuilder; +use sqlx::Row; +use sqlx::Sqlite; +use sqlx::SqlitePool; +use sqlx::sqlite::SqliteConnectOptions; +use sqlx::sqlite::SqlitePoolOptions; + +#[derive(Debug, Parser)] +#[command(name = "codex-state-logs")] +#[command(about = "Tail Codex logs from state.sqlite with simple filters")] +struct Args { + /// Path to CODEX_HOME. Defaults to $CODEX_HOME or ~/.codex. + #[arg(long, env = "CODEX_HOME")] + codex_home: Option, + + /// Direct path to the SQLite database. Overrides --codex-home. + #[arg(long)] + db: Option, + + /// Log level to match exactly (case-insensitive). + #[arg(long)] + level: Option, + + /// Start timestamp (RFC3339 or unix seconds). + #[arg(long, value_name = "RFC3339|UNIX")] + from: Option, + + /// End timestamp (RFC3339 or unix seconds). + #[arg(long, value_name = "RFC3339|UNIX")] + to: Option, + + /// Substring match on module_path. + #[arg(long)] + module: Option, + + /// Substring match on file path. + #[arg(long)] + file: Option, + + /// Number of matching rows to show before tailing. + #[arg(long, default_value_t = 200)] + backfill: usize, + + /// Poll interval in milliseconds. + #[arg(long, default_value_t = 500)] + poll_ms: u64, +} + +#[derive(Debug, Clone, sqlx::FromRow)] +struct LogRow { + id: i64, + ts: i64, + ts_nanos: i64, + level: String, + message: Option, + fields_json: String, + module_path: Option, + file: Option, + line: Option, +} + +#[derive(Debug, Clone)] +struct LogFilter { + level_upper: Option, + from_ts: Option, + to_ts: Option, + module_like: Option, + file_like: Option, +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let args = Args::parse(); + let db_path = resolve_db_path(&args)?; + let filter = build_filter(&args)?; + let pool = open_read_only_pool(db_path.as_path()).await?; + + let mut last_id = print_backfill(&pool, &filter, args.backfill).await?; + if last_id == 0 { + last_id = fetch_max_id(&pool, &filter).await?; + } + + let poll_interval = Duration::from_millis(args.poll_ms); + loop { + let rows = fetch_new_rows(&pool, &filter, last_id).await?; + for row in rows { + last_id = last_id.max(row.id); + println!("{}", format_row(&row)); + } + tokio::time::sleep(poll_interval).await; + } +} + +fn resolve_db_path(args: &Args) -> anyhow::Result { + if let Some(db) = args.db.as_ref() { + return Ok(db.clone()); + } + + let codex_home = args.codex_home.clone().unwrap_or_else(default_codex_home); + Ok(codex_home.join(STATE_DB_FILENAME)) +} + +fn default_codex_home() -> PathBuf { + if let Some(home) = home_dir() { + return home.join(".codex"); + } + PathBuf::from(".codex") +} + +fn build_filter(args: &Args) -> anyhow::Result { + let from_ts = args + .from + .as_deref() + .map(parse_timestamp) + .transpose() + .context("failed to parse --from")?; + let to_ts = args + .to + .as_deref() + .map(parse_timestamp) + .transpose() + .context("failed to parse --to")?; + + let level_upper = args.level.as_ref().map(|level| level.to_ascii_uppercase()); + + Ok(LogFilter { + level_upper, + from_ts, + to_ts, + module_like: args.module.clone(), + file_like: args.file.clone(), + }) +} + +fn parse_timestamp(value: &str) -> anyhow::Result { + if let Ok(secs) = value.parse::() { + return Ok(secs); + } + + let dt = DateTime::parse_from_rfc3339(value) + .with_context(|| format!("expected RFC3339 or unix seconds, got {value}"))?; + Ok(dt.timestamp()) +} + +async fn open_read_only_pool(path: &Path) -> anyhow::Result { + let options = SqliteConnectOptions::new() + .filename(path) + .create_if_missing(false) + .read_only(true) + .busy_timeout(Duration::from_secs(5)); + + let display = path.display(); + SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .with_context(|| format!("failed to open sqlite db at {display}")) +} + +async fn print_backfill( + pool: &SqlitePool, + filter: &LogFilter, + backfill: usize, +) -> anyhow::Result { + if backfill == 0 { + return Ok(0); + } + + let mut rows = fetch_backfill(pool, filter, backfill).await?; + rows.reverse(); + + let mut last_id = 0; + for row in rows { + last_id = last_id.max(row.id); + println!("{}", format_row(&row)); + } + Ok(last_id) +} + +async fn fetch_backfill( + pool: &SqlitePool, + filter: &LogFilter, + backfill: usize, +) -> anyhow::Result> { + let mut builder = base_select_builder(); + push_filters(&mut builder, filter); + builder.push(" ORDER BY id DESC"); + builder.push(" LIMIT ").push_bind(backfill as i64); + + builder + .build_query_as::() + .fetch_all(pool) + .await + .context("failed to fetch backfill logs") +} + +async fn fetch_new_rows( + pool: &SqlitePool, + filter: &LogFilter, + last_id: i64, +) -> anyhow::Result> { + let mut builder = base_select_builder(); + push_filters(&mut builder, filter); + builder.push(" AND id > ").push_bind(last_id); + builder.push(" ORDER BY id ASC"); + + builder + .build_query_as::() + .fetch_all(pool) + .await + .context("failed to fetch new logs") +} + +async fn fetch_max_id(pool: &SqlitePool, filter: &LogFilter) -> anyhow::Result { + let mut builder = QueryBuilder::::new("SELECT MAX(id) AS max_id FROM logs WHERE 1 = 1"); + push_filters(&mut builder, filter); + + let row = builder + .build() + .fetch_one(pool) + .await + .context("failed to fetch max log id")?; + let max_id: Option = row.try_get("max_id")?; + Ok(max_id.unwrap_or(0)) +} + +fn base_select_builder<'a>() -> QueryBuilder<'a, Sqlite> { + QueryBuilder::::new( + "SELECT id, ts, ts_nanos, level, message, fields_json, module_path, file, line FROM logs WHERE 1 = 1", + ) +} + +fn push_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, filter: &'a LogFilter) { + if let Some(level_upper) = filter.level_upper.as_ref() { + builder + .push(" AND UPPER(level) = ") + .push_bind(level_upper.as_str()); + } + if let Some(from_ts) = filter.from_ts { + builder.push(" AND ts >= ").push_bind(from_ts); + } + if let Some(to_ts) = filter.to_ts { + builder.push(" AND ts <= ").push_bind(to_ts); + } + if let Some(module_like) = filter.module_like.as_ref() { + builder + .push(" AND module_path LIKE '%' || ") + .push_bind(module_like.as_str()) + .push(" || '%'"); + } + if let Some(file_like) = filter.file_like.as_ref() { + builder + .push(" AND file LIKE '%' || ") + .push_bind(file_like.as_str()) + .push(" || '%'"); + } +} + +fn format_row(row: &LogRow) -> String { + let timestamp = format_timestamp(row.ts, row.ts_nanos); + let location = match (&row.file, row.line) { + (Some(file), Some(line)) => format!("{file}:{line}"), + (Some(file), None) => file.clone(), + _ => "-".to_string(), + }; + let module = row.module_path.as_deref().unwrap_or("-"); + let message = row.message.as_deref().unwrap_or(""); + let fields = row.fields_json.as_str(); + let level = row.level.as_str(); + if fields == "{}" || fields.is_empty() { + return format!("{timestamp} {level:<5} [{module}] {location} - {message}"); + } + format!("{timestamp} {level:<5} [{module}] {location} - {message} {fields}") +} + +fn format_timestamp(ts: i64, ts_nanos: i64) -> String { + let nanos = u32::try_from(ts_nanos).unwrap_or(0); + match DateTime::::from_timestamp(ts, nanos) { + Some(dt) => dt.to_rfc3339_opts(SecondsFormat::Millis, true), + None => format!("{ts}.{ts_nanos:09}Z"), + } +} diff --git a/justfile b/justfile index 0e01ef7e1d..8fb5a7d941 100644 --- a/justfile +++ b/justfile @@ -67,3 +67,7 @@ mcp-server-run *args: # Regenerate the json schema for config.toml from the current config types. write-config-schema: cargo run -p codex-core --bin codex-write-config-schema + +# Tail logs from the state SQLite database +log *args: + if [ "${1:-}" = "--" ]; then shift; fi; cargo run -p codex-state --bin logs_client -- "$@" From 4ba911d48c1f5c554bd447b35b42238ef3c1b419 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 11:25:22 +0100 Subject: [PATCH 065/116] chore: improve client (#10149) Screenshot 2026-01-29 at 11 13 12 --- codex-rs/Cargo.lock | 1 + codex-rs/state/Cargo.toml | 1 + codex-rs/state/migrations/0002_logs.sql | 1 - codex-rs/state/src/bin/logs_client.rs | 36 ++++++++++++++++++------- codex-rs/state/src/log_db.rs | 33 +++++++++-------------- codex-rs/state/src/model/log.rs | 1 - codex-rs/state/src/runtime.rs | 3 +-- 7 files changed, 43 insertions(+), 33 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index f47e054ba6..4c321b3f62 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1855,6 +1855,7 @@ dependencies = [ "codex-otel", "codex-protocol", "dirs", + "owo-colors", "pretty_assertions", "serde", "serde_json", diff --git a/codex-rs/state/Cargo.toml b/codex-rs/state/Cargo.toml index a6e36a3e00..6019b5888b 100644 --- a/codex-rs/state/Cargo.toml +++ b/codex-rs/state/Cargo.toml @@ -11,6 +11,7 @@ clap = { workspace = true, features = ["derive", "env"] } codex-otel = { workspace = true } codex-protocol = { workspace = true } dirs = { workspace = true } +owo-colors = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } sqlx = { workspace = true } diff --git a/codex-rs/state/migrations/0002_logs.sql b/codex-rs/state/migrations/0002_logs.sql index 4a193500b9..b9a2c681d4 100644 --- a/codex-rs/state/migrations/0002_logs.sql +++ b/codex-rs/state/migrations/0002_logs.sql @@ -5,7 +5,6 @@ CREATE TABLE logs ( level TEXT NOT NULL, target TEXT NOT NULL, message TEXT, - fields_json TEXT NOT NULL, module_path TEXT, file TEXT, line INTEGER diff --git a/codex-rs/state/src/bin/logs_client.rs b/codex-rs/state/src/bin/logs_client.rs index 13bcb1571d..71acf67e85 100644 --- a/codex-rs/state/src/bin/logs_client.rs +++ b/codex-rs/state/src/bin/logs_client.rs @@ -9,6 +9,7 @@ use chrono::Utc; use clap::Parser; use codex_state::STATE_DB_FILENAME; use dirs::home_dir; +use owo_colors::OwoColorize; use sqlx::QueryBuilder; use sqlx::Row; use sqlx::Sqlite; @@ -64,8 +65,6 @@ struct LogRow { ts_nanos: i64, level: String, message: Option, - fields_json: String, - module_path: Option, file: Option, line: Option, } @@ -237,7 +236,7 @@ async fn fetch_max_id(pool: &SqlitePool, filter: &LogFilter) -> anyhow::Result() -> QueryBuilder<'a, Sqlite> { QueryBuilder::::new( - "SELECT id, ts, ts_nanos, level, message, fields_json, module_path, file, line FROM logs WHERE 1 = 1", + "SELECT id, ts, ts_nanos, level, message, file, line FROM logs WHERE 1 = 1", ) } @@ -269,19 +268,38 @@ fn push_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, filter: &'a LogFilte fn format_row(row: &LogRow) -> String { let timestamp = format_timestamp(row.ts, row.ts_nanos); + let level = row.level.as_str(); let location = match (&row.file, row.line) { (Some(file), Some(line)) => format!("{file}:{line}"), (Some(file), None) => file.clone(), _ => "-".to_string(), }; - let module = row.module_path.as_deref().unwrap_or("-"); let message = row.message.as_deref().unwrap_or(""); - let fields = row.fields_json.as_str(); - let level = row.level.as_str(); - if fields == "{}" || fields.is_empty() { - return format!("{timestamp} {level:<5} [{module}] {location} - {message}"); + let level_colored = color_level(level); + let timestamp_colored = timestamp.dimmed().to_string(); + let location_colored = location.dimmed().to_string(); + let message_colored = message.bold().to_string(); + format!("{timestamp_colored} {level_colored} {location_colored} - {message_colored}") +} + +fn color_level(level: &str) -> String { + let padded = format!("{level:<5}"); + if level.eq_ignore_ascii_case("error") { + return padded.red().bold().to_string(); } - format!("{timestamp} {level:<5} [{module}] {location} - {message} {fields}") + if level.eq_ignore_ascii_case("warn") { + return padded.yellow().bold().to_string(); + } + if level.eq_ignore_ascii_case("info") { + return padded.green().bold().to_string(); + } + if level.eq_ignore_ascii_case("debug") { + return padded.blue().bold().to_string(); + } + if level.eq_ignore_ascii_case("trace") { + return padded.magenta().bold().to_string(); + } + padded.bold().to_string() } fn format_timestamp(ts: i64, ts_nanos: i64) -> String { diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index c03b7977d3..13f19d0baf 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -22,7 +22,6 @@ use std::time::Duration; use std::time::SystemTime; use std::time::UNIX_EPOCH; -use serde_json::Value; use tokio::sync::mpsc; use tracing::Event; use tracing::field::Field; @@ -54,7 +53,7 @@ where { fn on_event(&self, event: &Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>) { let metadata = event.metadata(); - let mut visitor = JsonVisitor::default(); + let mut visitor = MessageVisitor::default(); event.record(&mut visitor); let now = SystemTime::now() @@ -66,7 +65,6 @@ where level: metadata.level().as_str().to_string(), target: metadata.target().to_string(), message: visitor.message, - fields_json: Value::Object(visitor.fields).to_string(), module_path: metadata.module_path().map(ToString::to_string), file: metadata.file().map(ToString::to_string), line: metadata.line().map(|line| line as i64), @@ -114,49 +112,44 @@ async fn flush(state_db: &std::sync::Arc, buffer: &mut Vec, +struct MessageVisitor { message: Option, } -impl JsonVisitor { - fn record_value(&mut self, field: &Field, value: Value) { +impl MessageVisitor { + fn record_message(&mut self, field: &Field, value: String) { if field.name() == "message" && self.message.is_none() { - self.message = Some(match &value { - Value::String(message) => message.clone(), - _ => value.to_string(), - }); + self.message = Some(value); } - self.fields.insert(field.name().to_string(), value); } } -impl Visit for JsonVisitor { +impl Visit for MessageVisitor { fn record_i64(&mut self, field: &Field, value: i64) { - self.record_value(field, Value::from(value)); + self.record_message(field, value.to_string()); } fn record_u64(&mut self, field: &Field, value: u64) { - self.record_value(field, Value::from(value)); + self.record_message(field, value.to_string()); } fn record_bool(&mut self, field: &Field, value: bool) { - self.record_value(field, Value::from(value)); + self.record_message(field, value.to_string()); } fn record_f64(&mut self, field: &Field, value: f64) { - self.record_value(field, Value::from(value)); + self.record_message(field, value.to_string()); } fn record_str(&mut self, field: &Field, value: &str) { - self.record_value(field, Value::from(value)); + self.record_message(field, value.to_string()); } fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { - self.record_value(field, Value::from(value.to_string())); + self.record_message(field, value.to_string()); } fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { - self.record_value(field, Value::from(format!("{value:?}"))); + self.record_message(field, format!("{value:?}")); } } diff --git a/codex-rs/state/src/model/log.rs b/codex-rs/state/src/model/log.rs index 5662a3725c..0fa4c0b38e 100644 --- a/codex-rs/state/src/model/log.rs +++ b/codex-rs/state/src/model/log.rs @@ -7,7 +7,6 @@ pub struct LogEntry { pub level: String, pub target: String, pub message: Option, - pub fields_json: String, pub module_path: Option, pub file: Option, pub line: Option, diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index 34add1347d..96b2d69122 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -214,7 +214,7 @@ FROM threads } let mut builder = QueryBuilder::::new( - "INSERT INTO logs (ts, ts_nanos, level, target, message, fields_json, module_path, file, line) ", + "INSERT INTO logs (ts, ts_nanos, level, target, message, module_path, file, line) ", ); builder.push_values(entries, |mut row, entry| { row.push_bind(entry.ts) @@ -222,7 +222,6 @@ FROM threads .push_bind(&entry.level) .push_bind(&entry.target) .push_bind(&entry.message) - .push_bind(&entry.fields_json) .push_bind(&entry.module_path) .push_bind(&entry.file) .push_bind(entry.line); From d29129f352d02458fc69bb06066e1339d46e0e4c Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 15:08:22 +0100 Subject: [PATCH 066/116] nit: update npm (#10161) --- .github/workflows/shell-tool-mcp.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index d6c85d9ddc..57bfdd5f5b 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -451,6 +451,10 @@ jobs: registry-url: https://registry.npmjs.org scope: "@openai" + # Trusted publishing requires npm CLI version 11.5.1 or later. + - name: Update npm + run: npm install -g npm@latest + - name: Download npm tarball uses: actions/download-artifact@v7 with: From 2945667dcc7b655fc3bf044f04b69f6cbdf31b69 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 15:46:15 +0100 Subject: [PATCH 067/116] [experimental] nit: try to speed up apt-install (#10163) --- .github/workflows/shell-tool-mcp.yml | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 57bfdd5f5b..3273bb47bc 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -248,8 +248,32 @@ jobs: run: | set -euo pipefail if command -v apt-get >/dev/null 2>&1; then - apt-get update - DEBIAN_FRONTEND=noninteractive apt-get install -y git build-essential bison autoconf gettext + # On Ubuntu ARM containers, apt metadata for universe/multiverse is large and + # can make `apt-get update` very slow. We only need packages from `main`, so + # trim sources to `main` for faster, more reliable updates. + if [[ "${{ matrix.target }}" == "aarch64-unknown-linux-musl" ]] && [[ -f /etc/os-release ]]; then + . /etc/os-release + if [[ "${ID-}" == "ubuntu" ]]; then + codename="${VERSION_CODENAME:-}" + if [[ -n "$codename" ]]; then + printf '%s\n' \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename} main" \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-updates main" \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-backports main" \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-security main" \ + >/etc/apt/sources.list + fi + fi + fi + + apt_opts=( + -o Acquire::Retries=3 + -o Acquire::http::Timeout=30 + -o Acquire::https::Timeout=30 + -o Acquire::Languages=none + ) + apt-get "${apt_opts[@]}" update + DEBIAN_FRONTEND=noninteractive apt-get "${apt_opts[@]}" install -y git build-essential bison autoconf gettext elif command -v dnf >/dev/null 2>&1; then dnf install -y git gcc gcc-c++ make bison autoconf gettext elif command -v yum >/dev/null 2>&1; then From b654b7a9aeb8e222e56bbe2814587ca6fafadac5 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 15:59:56 +0100 Subject: [PATCH 068/116] [experimental] nit: try to speed up apt-install 2 (#10164) --- .github/workflows/shell-tool-mcp.yml | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 3273bb47bc..ec0c16cd5e 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -254,14 +254,19 @@ jobs: if [[ "${{ matrix.target }}" == "aarch64-unknown-linux-musl" ]] && [[ -f /etc/os-release ]]; then . /etc/os-release if [[ "${ID-}" == "ubuntu" ]]; then - codename="${VERSION_CODENAME:-}" - if [[ -n "$codename" ]]; then - printf '%s\n' \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename} main" \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-updates main" \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-backports main" \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-security main" \ - >/etc/apt/sources.list + if [[ -f /etc/apt/sources.list.d/ubuntu.sources ]]; then + # Ubuntu 24.04+ uses deb822 sources; trim components to main. + sed -i -E 's/^Components:.*/Components: main/' /etc/apt/sources.list.d/ubuntu.sources + else + codename="${VERSION_CODENAME:-}" + if [[ -n "$codename" ]]; then + printf '%s\n' \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename} main" \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-updates main" \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-backports main" \ + "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-security main" \ + >/etc/apt/sources.list + fi fi fi fi From 89c5f3c4d43b174054bd5299d0b507a26c70f465 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 16:53:30 +0100 Subject: [PATCH 069/116] feat: adding thread ID to logs + filter in the client (#10150) --- codex-rs/core/src/codex.rs | 8 +- codex-rs/core/src/shell_snapshot.rs | 28 +++-- codex-rs/core/src/tasks/mod.rs | 41 ++++--- codex-rs/state/migrations/0002_logs.sql | 2 + codex-rs/state/src/bin/logs_client.rs | 20 +++- codex-rs/state/src/log_db.rs | 142 ++++++++++++++++++++++-- codex-rs/state/src/model/log.rs | 1 + codex-rs/state/src/runtime.rs | 3 +- 8 files changed, 203 insertions(+), 42 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index dbc2d5c632..8e1ec64370 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -84,6 +84,7 @@ use tracing::debug; use tracing::error; use tracing::field; use tracing::info; +use tracing::info_span; use tracing::instrument; use tracing::trace_span; use tracing::warn; @@ -353,6 +354,7 @@ impl Codex { let session_source_clone = session_configuration.session_source.clone(); let (agent_status_tx, agent_status_rx) = watch::channel(AgentStatus::PendingInit); + let session_init_span = info_span!("session_init"); let session = Session::new( session_configuration, config.clone(), @@ -366,6 +368,7 @@ impl Codex { skills_manager, agent_control, ) + .instrument(session_init_span) .await .map_err(|e| { error!("Failed to create session: {e:#}"); @@ -374,7 +377,10 @@ impl Codex { let thread_id = session.conversation_id; // This task will run until Op::Shutdown is received. - tokio::spawn(submission_loop(Arc::clone(&session), config, rx_sub)); + let session_loop_span = info_span!("session_loop", thread_id = %thread_id); + tokio::spawn( + submission_loop(Arc::clone(&session), config, rx_sub).instrument(session_loop_span), + ); let codex = Codex { next_id: AtomicU64::new(0), tx_sub, diff --git a/codex-rs/core/src/shell_snapshot.rs b/codex-rs/core/src/shell_snapshot.rs index 78581186c7..d6d738508a 100644 --- a/codex-rs/core/src/shell_snapshot.rs +++ b/codex-rs/core/src/shell_snapshot.rs @@ -19,6 +19,8 @@ use tokio::fs; use tokio::process::Command; use tokio::sync::watch; use tokio::time::timeout; +use tracing::Instrument; +use tracing::info_span; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ShellSnapshot { @@ -42,17 +44,21 @@ impl ShellSnapshot { let snapshot_shell = shell.clone(); let snapshot_session_id = session_id; - tokio::spawn(async move { - let timer = otel_manager.start_timer("codex.shell_snapshot.duration_ms", &[]); - let snapshot = - ShellSnapshot::try_new(&codex_home, snapshot_session_id, &snapshot_shell) - .await - .map(Arc::new); - let success = if snapshot.is_some() { "true" } else { "false" }; - let _ = timer.map(|timer| timer.record(&[("success", success)])); - otel_manager.counter("codex.shell_snapshot", 1, &[("success", success)]); - let _ = shell_snapshot_tx.send(snapshot); - }); + let snapshot_span = info_span!("shell_snapshot", thread_id = %snapshot_session_id); + tokio::spawn( + async move { + let timer = otel_manager.start_timer("codex.shell_snapshot.duration_ms", &[]); + let snapshot = + ShellSnapshot::try_new(&codex_home, snapshot_session_id, &snapshot_shell) + .await + .map(Arc::new); + let success = if snapshot.is_some() { "true" } else { "false" }; + let _ = timer.map(|timer| timer.record(&[("success", success)])); + otel_manager.counter("codex.shell_snapshot", 1, &[("success", success)]); + let _ = shell_snapshot_tx.send(snapshot); + } + .instrument(snapshot_span), + ); } async fn try_new(codex_home: &Path, session_id: ThreadId, shell: &Shell) -> Option { diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 08d23f7987..1f1195236c 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -13,6 +13,8 @@ use tokio::select; use tokio::sync::Notify; use tokio_util::sync::CancellationToken; use tokio_util::task::AbortOnDropHandle; +use tracing::Instrument; +use tracing::info_span; use tracing::trace; use tracing::warn; @@ -130,25 +132,30 @@ impl Session { let ctx = Arc::clone(&turn_context); let task_for_run = Arc::clone(&task); let task_cancellation_token = cancellation_token.child_token(); - tokio::spawn(async move { - let ctx_for_finish = Arc::clone(&ctx); - let last_agent_message = task_for_run - .run( - Arc::clone(&session_ctx), - ctx, - input, - task_cancellation_token.child_token(), - ) - .await; - session_ctx.clone_session().flush_rollout().await; - if !task_cancellation_token.is_cancelled() { - // Emit completion uniformly from spawn site so all tasks share the same lifecycle. - let sess = session_ctx.clone_session(); - sess.on_task_finished(ctx_for_finish, last_agent_message) + let thread_id = self.conversation_id; + let session_span = info_span!("session_task", thread_id = %thread_id); + tokio::spawn( + async move { + let ctx_for_finish = Arc::clone(&ctx); + let last_agent_message = task_for_run + .run( + Arc::clone(&session_ctx), + ctx, + input, + task_cancellation_token.child_token(), + ) .await; + session_ctx.clone_session().flush_rollout().await; + if !task_cancellation_token.is_cancelled() { + // Emit completion uniformly from spawn site so all tasks share the same lifecycle. + let sess = session_ctx.clone_session(); + sess.on_task_finished(ctx_for_finish, last_agent_message) + .await; + } + done_clone.notify_waiters(); } - done_clone.notify_waiters(); - }) + .instrument(session_span), + ) }; let timer = turn_context diff --git a/codex-rs/state/migrations/0002_logs.sql b/codex-rs/state/migrations/0002_logs.sql index b9a2c681d4..051bef9136 100644 --- a/codex-rs/state/migrations/0002_logs.sql +++ b/codex-rs/state/migrations/0002_logs.sql @@ -5,9 +5,11 @@ CREATE TABLE logs ( level TEXT NOT NULL, target TEXT NOT NULL, message TEXT, + thread_id TEXT, module_path TEXT, file TEXT, line INTEGER ); CREATE INDEX idx_logs_ts ON logs(ts DESC, ts_nanos DESC, id DESC); +CREATE INDEX idx_logs_thread_id ON logs(thread_id); diff --git a/codex-rs/state/src/bin/logs_client.rs b/codex-rs/state/src/bin/logs_client.rs index 71acf67e85..df57856115 100644 --- a/codex-rs/state/src/bin/logs_client.rs +++ b/codex-rs/state/src/bin/logs_client.rs @@ -49,6 +49,10 @@ struct Args { #[arg(long)] file: Option, + /// Match a specific thread id. + #[arg(long)] + thread_id: Option, + /// Number of matching rows to show before tailing. #[arg(long, default_value_t = 200)] backfill: usize, @@ -65,6 +69,7 @@ struct LogRow { ts_nanos: i64, level: String, message: Option, + thread_id: Option, file: Option, line: Option, } @@ -76,6 +81,7 @@ struct LogFilter { to_ts: Option, module_like: Option, file_like: Option, + thread_id: Option, } #[tokio::main] @@ -139,6 +145,7 @@ fn build_filter(args: &Args) -> anyhow::Result { to_ts, module_like: args.module.clone(), file_like: args.file.clone(), + thread_id: args.thread_id.clone(), }) } @@ -236,7 +243,7 @@ async fn fetch_max_id(pool: &SqlitePool, filter: &LogFilter) -> anyhow::Result() -> QueryBuilder<'a, Sqlite> { QueryBuilder::::new( - "SELECT id, ts, ts_nanos, level, message, file, line FROM logs WHERE 1 = 1", + "SELECT id, ts, ts_nanos, level, message, thread_id, file, line FROM logs WHERE 1 = 1", ) } @@ -264,6 +271,11 @@ fn push_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, filter: &'a LogFilte .push_bind(file_like.as_str()) .push(" || '%'"); } + if let Some(thread_id) = filter.thread_id.as_ref() { + builder + .push(" AND thread_id = ") + .push_bind(thread_id.as_str()); + } } fn format_row(row: &LogRow) -> String { @@ -277,9 +289,13 @@ fn format_row(row: &LogRow) -> String { let message = row.message.as_deref().unwrap_or(""); let level_colored = color_level(level); let timestamp_colored = timestamp.dimmed().to_string(); + let thread_id = row.thread_id.as_deref().unwrap_or("-"); + let thread_id_colored = thread_id.yellow().to_string(); let location_colored = location.dimmed().to_string(); let message_colored = message.bold().to_string(); - format!("{timestamp_colored} {level_colored} {location_colored} - {message_colored}") + format!( + "{timestamp_colored} {level_colored} [{thread_id_colored}] {location_colored} - {message_colored}" + ) } fn color_level(level: &str) -> String { diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index 13f19d0baf..a62870974c 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -26,6 +26,9 @@ use tokio::sync::mpsc; use tracing::Event; use tracing::field::Field; use tracing::field::Visit; +use tracing::span::Attributes; +use tracing::span::Id; +use tracing::span::Record; use tracing_subscriber::Layer; use tracing_subscriber::registry::LookupSpan; @@ -51,10 +54,55 @@ impl Layer for LogDbLayer where S: tracing::Subscriber + for<'a> LookupSpan<'a>, { - fn on_event(&self, event: &Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>) { + fn on_new_span( + &self, + attrs: &Attributes<'_>, + id: &Id, + ctx: tracing_subscriber::layer::Context<'_, S>, + ) { + let mut visitor = SpanFieldVisitor::default(); + attrs.record(&mut visitor); + + if let Some(span) = ctx.span(id) { + span.extensions_mut().insert(SpanLogContext { + thread_id: visitor.thread_id, + }); + } + } + + fn on_record( + &self, + id: &Id, + values: &Record<'_>, + ctx: tracing_subscriber::layer::Context<'_, S>, + ) { + let mut visitor = SpanFieldVisitor::default(); + values.record(&mut visitor); + + if visitor.thread_id.is_none() { + return; + } + + if let Some(span) = ctx.span(id) { + let mut extensions = span.extensions_mut(); + if let Some(log_context) = extensions.get_mut::() { + log_context.thread_id = visitor.thread_id; + } else { + extensions.insert(SpanLogContext { + thread_id: visitor.thread_id, + }); + } + } + } + + fn on_event(&self, event: &Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) { let metadata = event.metadata(); let mut visitor = MessageVisitor::default(); event.record(&mut visitor); + let thread_id = visitor + .thread_id + .clone() + .or_else(|| event_thread_id(event, &ctx)); let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -65,6 +113,7 @@ where level: metadata.level().as_str().to_string(), target: metadata.target().to_string(), message: visitor.message, + thread_id, module_path: metadata.module_path().map(ToString::to_string), file: metadata.file().map(ToString::to_string), line: metadata.line().map(|line| line as i64), @@ -74,6 +123,75 @@ where } } +#[derive(Clone, Debug, Default)] +struct SpanLogContext { + thread_id: Option, +} + +#[derive(Default)] +struct SpanFieldVisitor { + thread_id: Option, +} + +impl SpanFieldVisitor { + fn record_field(&mut self, field: &Field, value: String) { + if field.name() == "thread_id" && self.thread_id.is_none() { + self.thread_id = Some(value); + } + } +} + +impl Visit for SpanFieldVisitor { + fn record_i64(&mut self, field: &Field, value: i64) { + self.record_field(field, value.to_string()); + } + + fn record_u64(&mut self, field: &Field, value: u64) { + self.record_field(field, value.to_string()); + } + + fn record_bool(&mut self, field: &Field, value: bool) { + self.record_field(field, value.to_string()); + } + + fn record_f64(&mut self, field: &Field, value: f64) { + self.record_field(field, value.to_string()); + } + + fn record_str(&mut self, field: &Field, value: &str) { + self.record_field(field, value.to_string()); + } + + fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { + self.record_field(field, value.to_string()); + } + + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + self.record_field(field, format!("{value:?}")); + } +} + +fn event_thread_id( + event: &Event<'_>, + ctx: &tracing_subscriber::layer::Context<'_, S>, +) -> Option +where + S: tracing::Subscriber + for<'a> LookupSpan<'a>, +{ + let mut thread_id = None; + if let Some(scope) = ctx.event_scope(event) { + for span in scope.from_root() { + let extensions = span.extensions(); + if let Some(log_context) = extensions.get::() + && log_context.thread_id.is_some() + { + thread_id = log_context.thread_id.clone(); + } + } + } + thread_id +} + async fn run_inserter( state_db: std::sync::Arc, mut receiver: mpsc::Receiver, @@ -114,42 +232,46 @@ async fn flush(state_db: &std::sync::Arc, buffer: &mut Vec, + thread_id: Option, } impl MessageVisitor { - fn record_message(&mut self, field: &Field, value: String) { + fn record_field(&mut self, field: &Field, value: String) { if field.name() == "message" && self.message.is_none() { - self.message = Some(value); + self.message = Some(value.clone()); + } + if field.name() == "thread_id" && self.thread_id.is_none() { + self.thread_id = Some(value); } } } impl Visit for MessageVisitor { fn record_i64(&mut self, field: &Field, value: i64) { - self.record_message(field, value.to_string()); + self.record_field(field, value.to_string()); } fn record_u64(&mut self, field: &Field, value: u64) { - self.record_message(field, value.to_string()); + self.record_field(field, value.to_string()); } fn record_bool(&mut self, field: &Field, value: bool) { - self.record_message(field, value.to_string()); + self.record_field(field, value.to_string()); } fn record_f64(&mut self, field: &Field, value: f64) { - self.record_message(field, value.to_string()); + self.record_field(field, value.to_string()); } fn record_str(&mut self, field: &Field, value: &str) { - self.record_message(field, value.to_string()); + self.record_field(field, value.to_string()); } fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) { - self.record_message(field, value.to_string()); + self.record_field(field, value.to_string()); } fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { - self.record_message(field, format!("{value:?}")); + self.record_field(field, format!("{value:?}")); } } diff --git a/codex-rs/state/src/model/log.rs b/codex-rs/state/src/model/log.rs index 0fa4c0b38e..c0c3a2dff2 100644 --- a/codex-rs/state/src/model/log.rs +++ b/codex-rs/state/src/model/log.rs @@ -7,6 +7,7 @@ pub struct LogEntry { pub level: String, pub target: String, pub message: Option, + pub thread_id: Option, pub module_path: Option, pub file: Option, pub line: Option, diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index 96b2d69122..8dada32746 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -214,7 +214,7 @@ FROM threads } let mut builder = QueryBuilder::::new( - "INSERT INTO logs (ts, ts_nanos, level, target, message, module_path, file, line) ", + "INSERT INTO logs (ts, ts_nanos, level, target, message, thread_id, module_path, file, line) ", ); builder.push_values(entries, |mut row, entry| { row.push_bind(entry.ts) @@ -222,6 +222,7 @@ FROM threads .push_bind(&entry.level) .push_bind(&entry.target) .push_bind(&entry.message) + .push_bind(&entry.thread_id) .push_bind(&entry.module_path) .push_bind(&entry.file) .push_bind(entry.line); From d6631fb5a99087dd0fb7c37620e1f32977cc5c7e Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 16:55:01 +0100 Subject: [PATCH 070/116] feat: add log retention and delete them after 90 days (#10151) --- codex-rs/state/src/log_db.rs | 14 +++++++++++++- codex-rs/state/src/runtime.rs | 8 ++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index a62870974c..345e90c6a8 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -18,6 +18,8 @@ //! # } //! ``` +use chrono::Duration as ChronoDuration; +use chrono::Utc; use std::time::Duration; use std::time::SystemTime; use std::time::UNIX_EPOCH; @@ -38,6 +40,7 @@ use crate::StateRuntime; const LOG_QUEUE_CAPACITY: usize = 512; const LOG_BATCH_SIZE: usize = 64; const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(250); +const LOG_RETENTION_DAYS: i64 = 90; pub struct LogDbLayer { sender: mpsc::Sender, @@ -45,7 +48,8 @@ pub struct LogDbLayer { pub fn start(state_db: std::sync::Arc) -> LogDbLayer { let (sender, receiver) = mpsc::channel(LOG_QUEUE_CAPACITY); - tokio::spawn(run_inserter(state_db, receiver)); + tokio::spawn(run_inserter(std::sync::Arc::clone(&state_db), receiver)); + tokio::spawn(run_retention_cleanup(state_db)); LogDbLayer { sender } } @@ -229,6 +233,14 @@ async fn flush(state_db: &std::sync::Arc, buffer: &mut Vec) { + let Some(cutoff) = Utc::now().checked_sub_signed(ChronoDuration::days(LOG_RETENTION_DAYS)) + else { + return; + }; + let _ = state_db.delete_logs_before(cutoff.timestamp()).await; +} + #[derive(Default)] struct MessageVisitor { message: Option, diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index 8dada32746..b61ea315c5 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -231,6 +231,14 @@ FROM threads Ok(()) } + pub(crate) async fn delete_logs_before(&self, cutoff_ts: i64) -> anyhow::Result { + let result = sqlx::query("DELETE FROM logs WHERE ts < ?") + .bind(cutoff_ts) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected()) + } + /// List thread ids using the underlying database (no rollout scanning). pub async fn list_thread_ids( &self, From e6c4f548ab3072b6ae709b3da5aecfb074fe95d7 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 17:28:15 +0100 Subject: [PATCH 071/116] chore: unify log queries (#10152) Unify log queries to only have SQLX code in the runtime and use it for both the log client and for tests --- .github/workflows/shell-tool-mcp.yml | 37 +---- codex-rs/core/tests/suite/sqlite_state.rs | 80 ++++++++++ codex-rs/state/migrations/0002_logs.sql | 2 - .../state/migrations/0003_logs_thread_id.sql | 3 + codex-rs/state/src/bin/logs_client.rs | 144 +++++------------- codex-rs/state/src/lib.rs | 2 + codex-rs/state/src/model/log.rs | 26 ++++ codex-rs/state/src/model/mod.rs | 2 + codex-rs/state/src/runtime.rs | 68 +++++++++ 9 files changed, 225 insertions(+), 139 deletions(-) create mode 100644 codex-rs/state/migrations/0003_logs_thread_id.sql diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index ec0c16cd5e..d6c85d9ddc 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -248,37 +248,8 @@ jobs: run: | set -euo pipefail if command -v apt-get >/dev/null 2>&1; then - # On Ubuntu ARM containers, apt metadata for universe/multiverse is large and - # can make `apt-get update` very slow. We only need packages from `main`, so - # trim sources to `main` for faster, more reliable updates. - if [[ "${{ matrix.target }}" == "aarch64-unknown-linux-musl" ]] && [[ -f /etc/os-release ]]; then - . /etc/os-release - if [[ "${ID-}" == "ubuntu" ]]; then - if [[ -f /etc/apt/sources.list.d/ubuntu.sources ]]; then - # Ubuntu 24.04+ uses deb822 sources; trim components to main. - sed -i -E 's/^Components:.*/Components: main/' /etc/apt/sources.list.d/ubuntu.sources - else - codename="${VERSION_CODENAME:-}" - if [[ -n "$codename" ]]; then - printf '%s\n' \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename} main" \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-updates main" \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-backports main" \ - "deb http://ports.ubuntu.com/ubuntu-ports ${codename}-security main" \ - >/etc/apt/sources.list - fi - fi - fi - fi - - apt_opts=( - -o Acquire::Retries=3 - -o Acquire::http::Timeout=30 - -o Acquire::https::Timeout=30 - -o Acquire::Languages=none - ) - apt-get "${apt_opts[@]}" update - DEBIAN_FRONTEND=noninteractive apt-get "${apt_opts[@]}" install -y git build-essential bison autoconf gettext + apt-get update + DEBIAN_FRONTEND=noninteractive apt-get install -y git build-essential bison autoconf gettext elif command -v dnf >/dev/null 2>&1; then dnf install -y git gcc gcc-c++ make bison autoconf gettext elif command -v yum >/dev/null 2>&1; then @@ -480,10 +451,6 @@ jobs: registry-url: https://registry.npmjs.org scope: "@openai" - # Trusted publishing requires npm CLI version 11.5.1 or later. - - name: Update npm - run: npm install -g npm@latest - - name: Download npm tarball uses: actions/download-artifact@v7 with: diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index df6fa2ef72..bf3b5a4f51 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -10,12 +10,18 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::UserMessageEvent; use codex_state::STATE_DB_FILENAME; use core_test_support::load_sse_fixture_with_id; +use core_test_support::responses; +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_sequence; use core_test_support::responses::start_mock_server; use core_test_support::test_codex::test_codex; use pretty_assertions::assert_eq; +use serde_json::json; use std::fs; use tokio::time::Duration; +use tracing_subscriber::prelude::*; use uuid::Uuid; fn sse_completed(id: &str) -> String { @@ -197,3 +203,77 @@ async fn user_messages_persist_in_state_db() -> Result<()> { Ok(()) } + +#[tokio::test(flavor = "current_thread")] +async fn tool_call_logs_include_thread_id() -> Result<()> { + let server = start_mock_server().await; + let call_id = "call-1"; + let args = json!({ + "command": "echo hello", + "timeout_ms": 1_000, + "login": false, + }); + let args_json = serde_json::to_string(&args)?; + mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, "shell_command", &args_json), + ev_completed("resp-1"), + ]), + responses::sse(vec![ev_completed("resp-2")]), + ], + ) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::Sqlite); + }); + let test = builder.build(&server).await?; + let db = test.codex.state_db().expect("state db enabled"); + let expected_thread_id = test.session_configured.session_id.to_string(); + + let subscriber = tracing_subscriber::registry().with(codex_state::log_db::start(db.clone())); + let dispatch = tracing::Dispatch::new(subscriber); + let _guard = tracing::dispatcher::set_default(&dispatch); + + test.submit_turn("run a shell command").await?; + { + let span = tracing::info_span!("test_log_span", thread_id = %expected_thread_id); + let _entered = span.enter(); + tracing::info!("ToolCall: shell_command {{\"command\":\"echo hello\"}}"); + } + + let mut found = None; + for _ in 0..80 { + let query = codex_state::LogQuery { + descending: true, + limit: Some(20), + ..Default::default() + }; + let rows = db.query_logs(&query).await?; + if let Some(row) = rows.into_iter().find(|row| { + row.message + .as_deref() + .is_some_and(|m| m.starts_with("ToolCall:")) + }) { + let thread_id = row.thread_id; + let message = row.message; + found = Some((thread_id, message)); + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + let (thread_id, message) = found.expect("expected ToolCall log row"); + assert_eq!(thread_id, Some(expected_thread_id)); + assert!( + message + .as_deref() + .is_some_and(|text| text.starts_with("ToolCall:")), + "expected ToolCall message, got {message:?}" + ); + + Ok(()) +} diff --git a/codex-rs/state/migrations/0002_logs.sql b/codex-rs/state/migrations/0002_logs.sql index 051bef9136..b9a2c681d4 100644 --- a/codex-rs/state/migrations/0002_logs.sql +++ b/codex-rs/state/migrations/0002_logs.sql @@ -5,11 +5,9 @@ CREATE TABLE logs ( level TEXT NOT NULL, target TEXT NOT NULL, message TEXT, - thread_id TEXT, module_path TEXT, file TEXT, line INTEGER ); CREATE INDEX idx_logs_ts ON logs(ts DESC, ts_nanos DESC, id DESC); -CREATE INDEX idx_logs_thread_id ON logs(thread_id); diff --git a/codex-rs/state/migrations/0003_logs_thread_id.sql b/codex-rs/state/migrations/0003_logs_thread_id.sql new file mode 100644 index 0000000000..c4badb6885 --- /dev/null +++ b/codex-rs/state/migrations/0003_logs_thread_id.sql @@ -0,0 +1,3 @@ +ALTER TABLE logs ADD COLUMN thread_id TEXT; + +CREATE INDEX idx_logs_thread_id ON logs(thread_id); diff --git a/codex-rs/state/src/bin/logs_client.rs b/codex-rs/state/src/bin/logs_client.rs index df57856115..c02a423253 100644 --- a/codex-rs/state/src/bin/logs_client.rs +++ b/codex-rs/state/src/bin/logs_client.rs @@ -1,4 +1,3 @@ -use std::path::Path; use std::path::PathBuf; use std::time::Duration; @@ -7,15 +6,12 @@ use chrono::DateTime; use chrono::SecondsFormat; use chrono::Utc; use clap::Parser; +use codex_state::LogQuery; +use codex_state::LogRow; use codex_state::STATE_DB_FILENAME; +use codex_state::StateRuntime; use dirs::home_dir; use owo_colors::OwoColorize; -use sqlx::QueryBuilder; -use sqlx::Row; -use sqlx::Sqlite; -use sqlx::SqlitePool; -use sqlx::sqlite::SqliteConnectOptions; -use sqlx::sqlite::SqlitePoolOptions; #[derive(Debug, Parser)] #[command(name = "codex-state-logs")] @@ -62,18 +58,6 @@ struct Args { poll_ms: u64, } -#[derive(Debug, Clone, sqlx::FromRow)] -struct LogRow { - id: i64, - ts: i64, - ts_nanos: i64, - level: String, - message: Option, - thread_id: Option, - file: Option, - line: Option, -} - #[derive(Debug, Clone)] struct LogFilter { level_upper: Option, @@ -89,16 +73,20 @@ async fn main() -> anyhow::Result<()> { let args = Args::parse(); let db_path = resolve_db_path(&args)?; let filter = build_filter(&args)?; - let pool = open_read_only_pool(db_path.as_path()).await?; + let codex_home = db_path + .parent() + .map(ToOwned::to_owned) + .unwrap_or_else(|| PathBuf::from(".")); + let runtime = StateRuntime::init(codex_home, "logs-client".to_string(), None).await?; - let mut last_id = print_backfill(&pool, &filter, args.backfill).await?; + let mut last_id = print_backfill(runtime.as_ref(), &filter, args.backfill).await?; if last_id == 0 { - last_id = fetch_max_id(&pool, &filter).await?; + last_id = fetch_max_id(runtime.as_ref(), &filter).await?; } let poll_interval = Duration::from_millis(args.poll_ms); loop { - let rows = fetch_new_rows(&pool, &filter, last_id).await?; + let rows = fetch_new_rows(runtime.as_ref(), &filter, last_id).await?; for row in rows { last_id = last_id.max(row.id); println!("{}", format_row(&row)); @@ -159,23 +147,8 @@ fn parse_timestamp(value: &str) -> anyhow::Result { Ok(dt.timestamp()) } -async fn open_read_only_pool(path: &Path) -> anyhow::Result { - let options = SqliteConnectOptions::new() - .filename(path) - .create_if_missing(false) - .read_only(true) - .busy_timeout(Duration::from_secs(5)); - - let display = path.display(); - SqlitePoolOptions::new() - .max_connections(1) - .connect_with(options) - .await - .with_context(|| format!("failed to open sqlite db at {display}")) -} - async fn print_backfill( - pool: &SqlitePool, + runtime: &StateRuntime, filter: &LogFilter, backfill: usize, ) -> anyhow::Result { @@ -183,7 +156,7 @@ async fn print_backfill( return Ok(0); } - let mut rows = fetch_backfill(pool, filter, backfill).await?; + let mut rows = fetch_backfill(runtime, filter, backfill).await?; rows.reverse(); let mut last_id = 0; @@ -195,86 +168,53 @@ async fn print_backfill( } async fn fetch_backfill( - pool: &SqlitePool, + runtime: &StateRuntime, filter: &LogFilter, backfill: usize, ) -> anyhow::Result> { - let mut builder = base_select_builder(); - push_filters(&mut builder, filter); - builder.push(" ORDER BY id DESC"); - builder.push(" LIMIT ").push_bind(backfill as i64); - - builder - .build_query_as::() - .fetch_all(pool) + let query = to_log_query(filter, Some(backfill), None, true); + runtime + .query_logs(&query) .await .context("failed to fetch backfill logs") } async fn fetch_new_rows( - pool: &SqlitePool, + runtime: &StateRuntime, filter: &LogFilter, last_id: i64, ) -> anyhow::Result> { - let mut builder = base_select_builder(); - push_filters(&mut builder, filter); - builder.push(" AND id > ").push_bind(last_id); - builder.push(" ORDER BY id ASC"); - - builder - .build_query_as::() - .fetch_all(pool) + let query = to_log_query(filter, None, Some(last_id), false); + runtime + .query_logs(&query) .await .context("failed to fetch new logs") } -async fn fetch_max_id(pool: &SqlitePool, filter: &LogFilter) -> anyhow::Result { - let mut builder = QueryBuilder::::new("SELECT MAX(id) AS max_id FROM logs WHERE 1 = 1"); - push_filters(&mut builder, filter); - - let row = builder - .build() - .fetch_one(pool) +async fn fetch_max_id(runtime: &StateRuntime, filter: &LogFilter) -> anyhow::Result { + let query = to_log_query(filter, None, None, false); + runtime + .max_log_id(&query) .await - .context("failed to fetch max log id")?; - let max_id: Option = row.try_get("max_id")?; - Ok(max_id.unwrap_or(0)) + .context("failed to fetch max log id") } -fn base_select_builder<'a>() -> QueryBuilder<'a, Sqlite> { - QueryBuilder::::new( - "SELECT id, ts, ts_nanos, level, message, thread_id, file, line FROM logs WHERE 1 = 1", - ) -} - -fn push_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, filter: &'a LogFilter) { - if let Some(level_upper) = filter.level_upper.as_ref() { - builder - .push(" AND UPPER(level) = ") - .push_bind(level_upper.as_str()); - } - if let Some(from_ts) = filter.from_ts { - builder.push(" AND ts >= ").push_bind(from_ts); - } - if let Some(to_ts) = filter.to_ts { - builder.push(" AND ts <= ").push_bind(to_ts); - } - if let Some(module_like) = filter.module_like.as_ref() { - builder - .push(" AND module_path LIKE '%' || ") - .push_bind(module_like.as_str()) - .push(" || '%'"); - } - if let Some(file_like) = filter.file_like.as_ref() { - builder - .push(" AND file LIKE '%' || ") - .push_bind(file_like.as_str()) - .push(" || '%'"); - } - if let Some(thread_id) = filter.thread_id.as_ref() { - builder - .push(" AND thread_id = ") - .push_bind(thread_id.as_str()); +fn to_log_query( + filter: &LogFilter, + limit: Option, + after_id: Option, + descending: bool, +) -> LogQuery { + LogQuery { + level_upper: filter.level_upper.clone(), + from_ts: filter.from_ts, + to_ts: filter.to_ts, + module_like: filter.module_like.clone(), + file_like: filter.file_like.clone(), + thread_id: filter.thread_id.clone(), + after_id, + limit, + descending, } } diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs index 91ebacea71..685552015e 100644 --- a/codex-rs/state/src/lib.rs +++ b/codex-rs/state/src/lib.rs @@ -12,6 +12,8 @@ mod paths; mod runtime; pub use model::LogEntry; +pub use model::LogQuery; +pub use model::LogRow; /// Preferred entrypoint: owns configuration and metrics. pub use runtime::StateRuntime; diff --git a/codex-rs/state/src/model/log.rs b/codex-rs/state/src/model/log.rs index c0c3a2dff2..d8a9ba3524 100644 --- a/codex-rs/state/src/model/log.rs +++ b/codex-rs/state/src/model/log.rs @@ -1,4 +1,5 @@ use serde::Serialize; +use sqlx::FromRow; #[derive(Clone, Debug, Serialize)] pub struct LogEntry { @@ -12,3 +13,28 @@ pub struct LogEntry { pub file: Option, pub line: Option, } + +#[derive(Clone, Debug, FromRow)] +pub struct LogRow { + pub id: i64, + pub ts: i64, + pub ts_nanos: i64, + pub level: String, + pub message: Option, + pub thread_id: Option, + pub file: Option, + pub line: Option, +} + +#[derive(Clone, Debug, Default)] +pub struct LogQuery { + pub level_upper: Option, + pub from_ts: Option, + pub to_ts: Option, + pub module_like: Option, + pub file_like: Option, + pub thread_id: Option, + pub after_id: Option, + pub limit: Option, + pub descending: bool, +} diff --git a/codex-rs/state/src/model/mod.rs b/codex-rs/state/src/model/mod.rs index 4921e2357a..bd615d7561 100644 --- a/codex-rs/state/src/model/mod.rs +++ b/codex-rs/state/src/model/mod.rs @@ -2,6 +2,8 @@ mod log; mod thread_metadata; pub use log::LogEntry; +pub use log::LogQuery; +pub use log::LogRow; pub use thread_metadata::Anchor; pub use thread_metadata::BackfillStats; pub use thread_metadata::ExtractionOutcome; diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index b61ea315c5..b15e4338bf 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -1,5 +1,7 @@ use crate::DB_ERROR_METRIC; use crate::LogEntry; +use crate::LogQuery; +use crate::LogRow; use crate::SortKey; use crate::ThreadMetadata; use crate::ThreadMetadataBuilder; @@ -239,6 +241,38 @@ FROM threads Ok(result.rows_affected()) } + /// Query logs with optional filters. + pub async fn query_logs(&self, query: &LogQuery) -> anyhow::Result> { + let mut builder = QueryBuilder::::new( + "SELECT id, ts, ts_nanos, level, message, thread_id, file, line FROM logs WHERE 1 = 1", + ); + push_log_filters(&mut builder, query); + if query.descending { + builder.push(" ORDER BY id DESC"); + } else { + builder.push(" ORDER BY id ASC"); + } + if let Some(limit) = query.limit { + builder.push(" LIMIT ").push_bind(limit as i64); + } + + let rows = builder + .build_query_as::() + .fetch_all(self.pool.as_ref()) + .await?; + Ok(rows) + } + + /// Return the max log id matching optional filters. + pub async fn max_log_id(&self, query: &LogQuery) -> anyhow::Result { + let mut builder = + QueryBuilder::::new("SELECT MAX(id) AS max_id FROM logs WHERE 1 = 1"); + push_log_filters(&mut builder, query); + let row = builder.build().fetch_one(self.pool.as_ref()).await?; + let max_id: Option = row.try_get("max_id")?; + Ok(max_id.unwrap_or(0)) + } + /// List thread ids using the underlying database (no rollout scanning). pub async fn list_thread_ids( &self, @@ -411,6 +445,40 @@ ON CONFLICT(id) DO UPDATE SET } } +fn push_log_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, query: &'a LogQuery) { + if let Some(level_upper) = query.level_upper.as_ref() { + builder + .push(" AND UPPER(level) = ") + .push_bind(level_upper.as_str()); + } + if let Some(from_ts) = query.from_ts { + builder.push(" AND ts >= ").push_bind(from_ts); + } + if let Some(to_ts) = query.to_ts { + builder.push(" AND ts <= ").push_bind(to_ts); + } + if let Some(module_like) = query.module_like.as_ref() { + builder + .push(" AND module_path LIKE '%' || ") + .push_bind(module_like.as_str()) + .push(" || '%'"); + } + if let Some(file_like) = query.file_like.as_ref() { + builder + .push(" AND file LIKE '%' || ") + .push_bind(file_like.as_str()) + .push(" || '%'"); + } + if let Some(thread_id) = query.thread_id.as_ref() { + builder + .push(" AND thread_id = ") + .push_bind(thread_id.as_str()); + } + if let Some(after_id) = query.after_id { + builder.push(" AND id > ").push_bind(after_id); + } +} + async fn open_sqlite(path: &Path) -> anyhow::Result { let options = SqliteConnectOptions::new() .filename(path) From 3e798c5a7dd0556947acc2baea1bb64be63ff3c7 Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Thu, 29 Jan 2026 09:34:59 -0800 Subject: [PATCH 072/116] Add OpenAI docs MCP tooltip (#10175) --- codex-rs/tui/tooltips.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/codex-rs/tui/tooltips.txt b/codex-rs/tui/tooltips.txt index 31819c6628..dc2d2faa67 100644 --- a/codex-rs/tui/tooltips.txt +++ b/codex-rs/tui/tooltips.txt @@ -9,6 +9,7 @@ Use /status to see the current model, approvals, and token usage. Use /fork to branch the current chat into a new thread. Use /init to create an AGENTS.md with project-specific guidance. Use /mcp to list configured MCP tools. +Use the OpenAI docs MCP for API questions; enable it with `codex mcp add openaiDeveloperDocs --url https://developers.openai.com/mcp`. You can run any shell command from Codex using `!` (e.g. `!ls`) Type / to open the command popup; Tab autocompletes slash commands. When the composer is empty, press Esc to step back and edit your last message; Enter confirms. From 798c4b3260e857756c2d6e13cc9bcd05ba604c7e Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 29 Jan 2026 19:15:22 +0100 Subject: [PATCH 073/116] feat: reduce span exposition (#10171) This only avoids the creation of duplicates spans --- codex-rs/core/src/stream_events_utils.rs | 7 ++++++- codex-rs/core/src/tasks/mod.rs | 5 ++--- codex-rs/state/src/bin/logs_client.rs | 12 ++++-------- codex-rs/state/src/model/log.rs | 1 + codex-rs/state/src/runtime.rs | 2 +- codex-rs/tui/src/lib.rs | 5 ++++- 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index 197ff6b4b6..930ce5afd6 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -51,7 +51,12 @@ pub(crate) async fn handle_output_item_done( // The model emitted a tool call; log it, persist the item immediately, and queue the tool execution. Ok(Some(call)) => { let payload_preview = call.payload.log_payload().into_owned(); - tracing::info!("ToolCall: {} {}", call.tool_name, payload_preview); + tracing::info!( + thread_id = %ctx.sess.conversation_id, + "ToolCall: {} {}", + call.tool_name, + payload_preview + ); ctx.sess .record_conversation_items(&ctx.turn_context, std::slice::from_ref(&item)) diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 1f1195236c..a487041eba 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::info_span; +use tracing::Span; use tracing::trace; use tracing::warn; @@ -132,8 +132,7 @@ impl Session { let ctx = Arc::clone(&turn_context); let task_for_run = Arc::clone(&task); let task_cancellation_token = cancellation_token.child_token(); - let thread_id = self.conversation_id; - let session_span = info_span!("session_task", thread_id = %thread_id); + let session_span = Span::current(); tokio::spawn( async move { let ctx_for_finish = Arc::clone(&ctx); diff --git a/codex-rs/state/src/bin/logs_client.rs b/codex-rs/state/src/bin/logs_client.rs index c02a423253..4389c29bc6 100644 --- a/codex-rs/state/src/bin/logs_client.rs +++ b/codex-rs/state/src/bin/logs_client.rs @@ -221,20 +221,16 @@ fn to_log_query( fn format_row(row: &LogRow) -> String { let timestamp = format_timestamp(row.ts, row.ts_nanos); let level = row.level.as_str(); - let location = match (&row.file, row.line) { - (Some(file), Some(line)) => format!("{file}:{line}"), - (Some(file), None) => file.clone(), - _ => "-".to_string(), - }; + let target = row.target.as_str(); let message = row.message.as_deref().unwrap_or(""); let level_colored = color_level(level); let timestamp_colored = timestamp.dimmed().to_string(); let thread_id = row.thread_id.as_deref().unwrap_or("-"); - let thread_id_colored = thread_id.yellow().to_string(); - let location_colored = location.dimmed().to_string(); + let thread_id_colored = thread_id.blue().dimmed().to_string(); + let target_colored = target.dimmed().to_string(); let message_colored = message.bold().to_string(); format!( - "{timestamp_colored} {level_colored} [{thread_id_colored}] {location_colored} - {message_colored}" + "{timestamp_colored} {level_colored} [{thread_id_colored}] {target_colored} - {message_colored}" ) } diff --git a/codex-rs/state/src/model/log.rs b/codex-rs/state/src/model/log.rs index d8a9ba3524..5d774249dd 100644 --- a/codex-rs/state/src/model/log.rs +++ b/codex-rs/state/src/model/log.rs @@ -20,6 +20,7 @@ pub struct LogRow { pub ts: i64, pub ts_nanos: i64, pub level: String, + pub target: String, pub message: Option, pub thread_id: Option, pub file: Option, diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index b15e4338bf..e0805e5b65 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -244,7 +244,7 @@ FROM threads /// Query logs with optional filters. pub async fn query_logs(&self, query: &LogQuery) -> anyhow::Result> { let mut builder = QueryBuilder::::new( - "SELECT id, ts, ts_nanos, level, message, thread_id, file, line FROM logs WHERE 1 = 1", + "SELECT id, ts, ts_nanos, level, target, message, thread_id, file, line FROM logs WHERE 1 = 1", ); push_log_filters(&mut builder, query); if query.descending { diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index c9e69b7125..010f8c83e5 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -306,7 +306,10 @@ pub async fn run_main( // grep for a specific module/target while troubleshooting. .with_target(true) .with_ansi(false) - .with_span_events(tracing_subscriber::fmt::format::FmtSpan::FULL) + .with_span_events( + tracing_subscriber::fmt::format::FmtSpan::NEW + | tracing_subscriber::fmt::format::FmtSpan::CLOSE, + ) .with_filter(env_filter()); let feedback = codex_feedback::CodexFeedback::new(); From 3b1cddf00106065a8ed0d95d76a206f0ce66ebf3 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 29 Jan 2026 10:36:21 -0800 Subject: [PATCH 074/116] Fall back to http when websockets fail (#10139) I expect not all proxies work with websockets, fall back to http if websockets fail. --- codex-rs/core/src/client.rs | 33 ++++++- codex-rs/core/src/codex.rs | 25 ++++- codex-rs/core/src/lib.rs | 2 + codex-rs/core/src/state/service.rs | 2 + codex-rs/core/src/tools/handlers/collab.rs | 3 + codex-rs/core/src/transport_manager.rs | 31 ++++++ .../core/tests/chat_completions_payload.rs | 2 + codex-rs/core/tests/chat_completions_sse.rs | 2 + codex-rs/core/tests/responses_headers.rs | 4 + codex-rs/core/tests/suite/client.rs | 2 + .../core/tests/suite/client_websockets.rs | 2 + codex-rs/core/tests/suite/mod.rs | 1 + .../core/tests/suite/websocket_fallback.rs | 98 +++++++++++++++++++ 13 files changed, 205 insertions(+), 2 deletions(-) create mode 100644 codex-rs/core/src/transport_manager.rs create mode 100644 codex-rs/core/tests/suite/websocket_fallback.rs diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index f415c3604a..98fce871fd 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -65,6 +65,7 @@ use crate::model_provider_info::ModelProviderInfo; use crate::model_provider_info::WireApi; use crate::tools::spec::create_tools_json_for_chat_completions_api; use crate::tools::spec::create_tools_json_for_responses_api; +use crate::transport_manager::TransportManager; pub const WEB_SEARCH_ELIGIBLE_HEADER: &str = "x-oai-web-search-eligible"; pub const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state"; @@ -80,6 +81,7 @@ struct ModelClientState { effort: Option, summary: ReasoningSummaryConfig, session_source: SessionSource, + transport_manager: TransportManager, } #[derive(Debug, Clone)] @@ -91,6 +93,7 @@ pub struct ModelClientSession { state: Arc, connection: Option, websocket_last_items: Vec, + transport_manager: TransportManager, /// Turn state for sticky routing. /// /// This is an `OnceLock` that stores the turn state value received from the server @@ -116,6 +119,7 @@ impl ModelClient { summary: ReasoningSummaryConfig, conversation_id: ThreadId, session_source: SessionSource, + transport_manager: TransportManager, ) -> Self { Self { state: Arc::new(ModelClientState { @@ -128,6 +132,7 @@ impl ModelClient { effort, summary, session_source, + transport_manager, }), } } @@ -137,6 +142,7 @@ impl ModelClient { state: Arc::clone(&self.state), connection: None, websocket_last_items: Vec::new(), + transport_manager: self.state.transport_manager.clone(), turn_state: Arc::new(OnceLock::new()), } } @@ -171,6 +177,10 @@ impl ModelClient { self.state.session_source.clone() } + pub(crate) fn transport_manager(&self) -> TransportManager { + self.state.transport_manager.clone() + } + /// Returns the currently configured model slug. pub fn get_model(&self) -> String { self.state.model_info.slug.clone() @@ -250,7 +260,10 @@ impl ModelClientSession { /// For Chat providers, the underlying stream is optionally aggregated /// based on the `show_raw_agent_reasoning` flag in the config. pub async fn stream(&mut self, prompt: &Prompt) -> Result { - match self.state.provider.wire_api { + let wire_api = self + .transport_manager + .effective_wire_api(self.state.provider.wire_api); + match wire_api { WireApi::Responses => self.stream_responses_api(prompt).await, WireApi::ResponsesWebsocket => self.stream_responses_websocket(prompt).await, WireApi::Chat => { @@ -271,6 +284,24 @@ impl ModelClientSession { } } + pub(crate) fn try_switch_fallback_transport(&mut self) -> bool { + let activated = self + .transport_manager + .activate_http_fallback(self.state.provider.wire_api); + if activated { + warn!("falling back to HTTP"); + self.state.otel_manager.counter( + "codex.transport.fallback_to_http", + 1, + &[("from_wire_api", "responses_websocket")], + ); + + self.connection = None; + self.websocket_last_items.clear(); + } + activated + } + fn build_responses_request(&self, prompt: &Prompt) -> Result { let instructions = prompt.base_instructions.text.clone(); let tools_json: Vec = create_tools_json_for_responses_api(&prompt.tools)?; diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 8e1ec64370..736d0554b3 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -30,6 +30,7 @@ use crate::stream_events_utils::HandleOutputCtx; use crate::stream_events_utils::handle_non_tool_response_item; use crate::stream_events_utils::handle_output_item_done; use crate::terminal; +use crate::transport_manager::TransportManager; use crate::truncate::TruncationPolicy; use crate::user_notification::UserNotifier; use crate::util::error_or_panic; @@ -624,6 +625,7 @@ impl Session { model_info: ModelInfo, conversation_id: ThreadId, sub_id: String, + transport_manager: TransportManager, ) -> TurnContext { let otel_manager = otel_manager.clone().with_model( session_configuration.collaboration_mode.model(), @@ -640,6 +642,7 @@ impl Session { session_configuration.model_reasoning_summary, conversation_id, session_configuration.session_source.clone(), + transport_manager, ); let tools_config = ToolsConfig::new(&ToolsConfigParams { @@ -869,6 +872,7 @@ impl Session { skills_manager, agent_control, state_db: state_db_ctx.clone(), + transport_manager: TransportManager::new(), }; let sess = Arc::new(Session { @@ -1188,6 +1192,7 @@ impl Session { model_info, self.conversation_id, sub_id, + self.services.transport_manager.clone(), ); if let Some(final_schema) = final_output_json_schema { turn_context.final_output_json_schema = final_schema; @@ -3042,6 +3047,7 @@ async fn spawn_review_thread( per_turn_config.model_reasoning_summary, sess.conversation_id, parent_turn_context.client.get_session_source(), + parent_turn_context.client.transport_manager(), ); let review_turn_context = TurnContext { @@ -3537,7 +3543,9 @@ async fn run_sampling_request( ) .await { - Ok(output) => return Ok(output), + Ok(output) => { + return Ok(output); + } Err(CodexErr::ContextWindowExceeded) => { sess.set_total_tokens_full(&turn_context).await; return Err(CodexErr::ContextWindowExceeded); @@ -3558,6 +3566,17 @@ async fn run_sampling_request( // Use the configured provider-specific stream retry budget. let max_retries = turn_context.client.get_provider().stream_max_retries(); + if retries >= max_retries && client_session.try_switch_fallback_transport() { + sess.send_event( + &turn_context, + EventMsg::Warning(WarningEvent { + message: format!("Falling back from WebSockets to HTTPS transport. {err:#}"), + }), + ) + .await; + retries = 0; + continue; + } if retries < max_retries { retries += 1; let delay = match &err { @@ -4753,6 +4772,7 @@ mod tests { skills_manager, agent_control, state_db: None, + transport_manager: TransportManager::new(), }; let turn_context = Session::make_turn_context( @@ -4764,6 +4784,7 @@ mod tests { model_info, conversation_id, "turn_id".to_string(), + services.transport_manager.clone(), ); let session = Session { @@ -4865,6 +4886,7 @@ mod tests { skills_manager, agent_control, state_db: None, + transport_manager: TransportManager::new(), }; let turn_context = Arc::new(Session::make_turn_context( @@ -4876,6 +4898,7 @@ mod tests { model_info, conversation_id, "turn_id".to_string(), + services.transport_manager.clone(), )); let session = Arc::new(Session { diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index ab51a201dc..1b1fb65ecd 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -38,6 +38,7 @@ pub mod landlock; pub mod mcp; mod mcp_connection_manager; pub mod models_manager; +mod transport_manager; pub use mcp_connection_manager::MCP_SANDBOX_STATE_CAPABILITY; pub use mcp_connection_manager::MCP_SANDBOX_STATE_METHOD; pub use mcp_connection_manager::SandboxState; @@ -113,6 +114,7 @@ pub use rollout::list::parse_cursor; pub use rollout::list::read_head_for_summary; pub use rollout::list::read_session_meta_line; pub use rollout::rollout_date_parts; +pub use transport_manager::TransportManager; mod function_tool; mod state; mod tasks; diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index 6559ec2e18..e036b29b7d 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -9,6 +9,7 @@ use crate::models_manager::manager::ModelsManager; use crate::skills::SkillsManager; use crate::state_db::StateDbHandle; use crate::tools::sandboxing::ApprovalStore; +use crate::transport_manager::TransportManager; use crate::unified_exec::UnifiedExecProcessManager; use crate::user_notification::UserNotifier; use codex_otel::OtelManager; @@ -32,4 +33,5 @@ pub(crate) struct SessionServices { pub(crate) skills_manager: Arc, pub(crate) agent_control: AgentControl, pub(crate) state_db: Option, + pub(crate) transport_manager: TransportManager, } diff --git a/codex-rs/core/src/tools/handlers/collab.rs b/codex-rs/core/src/tools/handlers/collab.rs index b1666949f6..61ccc1932e 100644 --- a/codex-rs/core/src/tools/handlers/collab.rs +++ b/codex-rs/core/src/tools/handlers/collab.rs @@ -781,6 +781,7 @@ mod tests { turn.client.get_reasoning_summary(), session.conversation_id, session_source, + session.services.transport_manager.clone(), ); let invocation = invocation( @@ -1221,6 +1222,7 @@ mod tests { let mut base_config = (*turn.client.config()).clone(); base_config.user_instructions = Some("base-user".to_string()); turn.user_instructions = Some("resolved-user".to_string()); + let transport_manager = turn.client.transport_manager(); turn.client = ModelClient::new( Arc::new(base_config.clone()), Some(session.services.auth_manager.clone()), @@ -1231,6 +1233,7 @@ mod tests { turn.client.get_reasoning_summary(), session.conversation_id, session_source, + transport_manager, ); let base_instructions = BaseInstructions { text: "base".to_string(), diff --git a/codex-rs/core/src/transport_manager.rs b/codex-rs/core/src/transport_manager.rs new file mode 100644 index 0000000000..f1fe68faf4 --- /dev/null +++ b/codex-rs/core/src/transport_manager.rs @@ -0,0 +1,31 @@ +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; + +use crate::model_provider_info::WireApi; + +#[derive(Clone, Debug, Default)] +pub struct TransportManager { + fallback_to_http: Arc, +} + +impl TransportManager { + pub fn new() -> Self { + Self::default() + } + + pub fn effective_wire_api(&self, provider_wire_api: WireApi) -> WireApi { + if self.fallback_to_http.load(Ordering::Relaxed) + && provider_wire_api == WireApi::ResponsesWebsocket + { + WireApi::Responses + } else { + provider_wire_api + } + } + + pub fn activate_http_fallback(&self, provider_wire_api: WireApi) -> bool { + provider_wire_api == WireApi::ResponsesWebsocket + && !self.fallback_to_http.swap(true, Ordering::Relaxed) + } +} diff --git a/codex-rs/core/tests/chat_completions_payload.rs b/codex-rs/core/tests/chat_completions_payload.rs index cdb92fe672..5e8c895a3f 100644 --- a/codex-rs/core/tests/chat_completions_payload.rs +++ b/codex-rs/core/tests/chat_completions_payload.rs @@ -11,6 +11,7 @@ use codex_core::ModelClient; use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseItem; +use codex_core::TransportManager; use codex_core::WireApi; use codex_core::models_manager::manager::ModelsManager; use codex_otel::OtelManager; @@ -98,6 +99,7 @@ async fn run_request(input: Vec) -> Value { summary, conversation_id, SessionSource::Exec, + TransportManager::new(), ) .new_session(); diff --git a/codex-rs/core/tests/chat_completions_sse.rs b/codex-rs/core/tests/chat_completions_sse.rs index 05ef476a05..84d0ede085 100644 --- a/codex-rs/core/tests/chat_completions_sse.rs +++ b/codex-rs/core/tests/chat_completions_sse.rs @@ -10,6 +10,7 @@ use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::ResponseItem; +use codex_core::TransportManager; use codex_core::WireApi; use codex_core::models_manager::manager::ModelsManager; use codex_otel::OtelManager; @@ -99,6 +100,7 @@ async fn run_stream_with_bytes(sse_body: &[u8]) -> Vec { summary, conversation_id, SessionSource::Exec, + TransportManager::new(), ) .new_session(); diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 22d9fa8b79..b3c0165f46 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -9,6 +9,7 @@ use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::ResponseItem; +use codex_core::TransportManager; use codex_core::WEB_SEARCH_ELIGIBLE_HEADER; use codex_core::WireApi; use codex_core::models_manager::manager::ModelsManager; @@ -94,6 +95,7 @@ async fn responses_stream_includes_subagent_header_on_review() { summary, conversation_id, session_source, + TransportManager::new(), ) .new_session(); @@ -191,6 +193,7 @@ async fn responses_stream_includes_subagent_header_on_other() { summary, conversation_id, session_source, + TransportManager::new(), ) .new_session(); @@ -346,6 +349,7 @@ async fn responses_respects_model_info_overrides_from_config() { summary, conversation_id, session_source, + TransportManager::new(), ) .new_session(); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index bdc2f311c0..8b8adf06ab 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -11,6 +11,7 @@ use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::ResponseItem; use codex_core::ThreadManager; +use codex_core::TransportManager; use codex_core::WireApi; use codex_core::auth::AuthCredentialsStoreMode; use codex_core::built_in_model_providers; @@ -1186,6 +1187,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { summary, conversation_id, SessionSource::Exec, + TransportManager::new(), ) .new_session(); diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index d55d71d0d8..60229e01d6 100644 --- 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::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::ResponseItem; +use codex_core::TransportManager; use codex_core::WireApi; use codex_core::models_manager::manager::ModelsManager; use codex_core::protocol::SessionSource; @@ -228,6 +229,7 @@ async fn websocket_harness(server: &WebSocketTestServer) -> WebsocketTestHarness ReasoningSummary::Auto, conversation_id, SessionSource::Exec, + TransportManager::new(), ); WebsocketTestHarness { diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index e054070b34..0744624a92 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -80,3 +80,4 @@ mod user_notification; mod user_shell_cmd; mod view_image; mod web_search_cached; +mod websocket_fallback; diff --git a/codex-rs/core/tests/suite/websocket_fallback.rs b/codex-rs/core/tests/suite/websocket_fallback.rs new file mode 100644 index 0000000000..d52236a8a2 --- /dev/null +++ b/codex-rs/core/tests/suite/websocket_fallback.rs @@ -0,0 +1,98 @@ +use anyhow::Result; +use codex_core::WireApi; +use core_test_support::responses; +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::skip_if_no_network; +use core_test_support::test_codex::test_codex; +use pretty_assertions::assert_eq; +use wiremock::http::Method; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn websocket_fallback_switches_to_http_after_retries_exhausted() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let response_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), + ) + .await; + + let mut builder = test_codex().with_config({ + let base_url = format!("{}/v1", server.uri()); + move |config| { + config.model_provider.base_url = Some(base_url); + config.model_provider.wire_api = WireApi::ResponsesWebsocket; + config.model_provider.stream_max_retries = Some(0); + config.model_provider.request_max_retries = Some(0); + } + }); + let test = builder.build(&server).await?; + + test.submit_turn("hello").await?; + + let requests = server.received_requests().await.unwrap_or_default(); + let websocket_attempts = requests + .iter() + .filter(|req| req.method == Method::GET && req.url.path().ends_with("/responses")) + .count(); + let http_attempts = requests + .iter() + .filter(|req| req.method == Method::POST && req.url.path().ends_with("/responses")) + .count(); + + assert_eq!(websocket_attempts, 1); + assert_eq!(http_attempts, 1); + assert_eq!(response_mock.requests().len(), 1); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn websocket_fallback_is_sticky_across_turns() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let response_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 mut builder = test_codex().with_config({ + let base_url = format!("{}/v1", server.uri()); + move |config| { + config.model_provider.base_url = Some(base_url); + config.model_provider.wire_api = WireApi::ResponsesWebsocket; + config.model_provider.stream_max_retries = Some(0); + config.model_provider.request_max_retries = Some(0); + } + }); + let test = builder.build(&server).await?; + + test.submit_turn("first").await?; + test.submit_turn("second").await?; + + let requests = server.received_requests().await.unwrap_or_default(); + let websocket_attempts = requests + .iter() + .filter(|req| req.method == Method::GET && req.url.path().ends_with("/responses")) + .count(); + let http_attempts = requests + .iter() + .filter(|req| req.method == Method::POST && req.url.path().ends_with("/responses")) + .count(); + + assert_eq!(websocket_attempts, 1); + assert_eq!(http_attempts, 2); + assert_eq!(response_mock.requests().len(), 2); + + Ok(()) +} From b7f26d74f040b8f967b8f1760177d96eb0e9863c Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 29 Jan 2026 10:49:03 -0800 Subject: [PATCH 075/116] chore: ensure pnpm-workspace.yaml is up-to-date (#10140) On the back of: https://github.com/openai/codex/pull/10138 Let's ensure that every folder with a `package.json` is listed in `pnpm-workspace.yaml` (not sure why `docs` was in there...) and that we are using `pnpm` over `npm` consistently (which is why this PR deletes `codex-cli/package-lock.json`). --- codex-cli/package-lock.json | 18 ------------------ pnpm-lock.yaml | 4 ++++ pnpm-workspace.yaml | 3 ++- 3 files changed, 6 insertions(+), 19 deletions(-) delete mode 100644 codex-cli/package-lock.json diff --git a/codex-cli/package-lock.json b/codex-cli/package-lock.json deleted file mode 100644 index 58ee846306..0000000000 --- a/codex-cli/package-lock.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@openai/codex", - "version": "0.0.0-dev", - "lockfileVersion": 3, - "packages": { - "": { - "name": "@openai/codex", - "version": "0.0.0-dev", - "license": "Apache-2.0", - "bin": { - "codex": "bin/codex.js" - }, - "engines": { - "node": ">=16" - } - } - } -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 01112d6d3b..102869a683 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,10 @@ importers: specifier: ^3.5.3 version: 3.5.3 + codex-cli: {} + + codex-rs/responses-api-proxy/npm: {} + sdk/typescript: devDependencies: '@modelcontextprotocol/sdk': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 78899b9321..09a61536ab 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,6 @@ packages: - - docs + - codex-cli + - codex-rs/responses-api-proxy/npm - sdk/typescript - shell-tool-mcp From bdd8a7d58bdd4ea57efe17f24cde4c09fdfea0b0 Mon Sep 17 00:00:00 2001 From: xl-openai Date: Thu, 29 Jan 2026 11:13:30 -0800 Subject: [PATCH 076/116] Better handling skill depdenencies on ENV VAR. (#9017) An experimental flow for env var skill dependencies. Skills can now declare required env vars in SKILL.md; if missing, the CLI prompts the user to get the value, and Core will store it in memory (eventually to a local persistent store) image --- .../app-server-protocol/src/protocol/v2.rs | 2 + .../app-server/src/bespoke_event_handling.rs | 1 + codex-rs/core/config.schema.json | 6 + codex-rs/core/src/codex.rs | 21 +++ codex-rs/core/src/features.rs | 8 + codex-rs/core/src/mcp/skill_dependencies.rs | 1 + .../core/src/skills/env_var_dependencies.rs | 162 ++++++++++++++++++ codex-rs/core/src/skills/mod.rs | 3 + codex-rs/core/src/state/session.rs | 13 ++ codex-rs/core/src/tools/handlers/shell.rs | 6 + codex-rs/protocol/src/request_user_input.rs | 4 + codex-rs/tui/src/bottom_pane/chat_composer.rs | 13 +- .../src/bottom_pane/request_user_input/mod.rs | 6 + .../bottom_pane/request_user_input/render.rs | 9 +- codex-rs/tui/src/bottom_pane/textarea.rs | 36 ++++ 15 files changed, 289 insertions(+), 2 deletions(-) create mode 100644 codex-rs/core/src/skills/env_var_dependencies.rs diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 7b695d2c7a..247360282c 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2532,6 +2532,8 @@ pub struct ToolRequestUserInputQuestion { pub question: String, #[serde(default)] pub is_other: bool, + #[serde(default)] + pub is_secret: bool, pub options: Option>, } diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 20e7db762b..1a9fcaa705 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -279,6 +279,7 @@ pub(crate) async fn apply_bespoke_event_handling( header: question.header, question: question.question, is_other: question.is_other, + is_secret: question.is_secret, options: question.options.map(|options| { options .into_iter() diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 717eddc612..16c0c8945c 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -207,6 +207,9 @@ "shell_tool": { "type": "boolean" }, + "skill_env_var_dependency_prompt": { + "type": "boolean" + }, "skill_mcp_dependency_install": { "type": "boolean" }, @@ -1231,6 +1234,9 @@ "shell_tool": { "type": "boolean" }, + "skill_env_var_dependency_prompt": { + "type": "boolean" + }, "skill_mcp_dependency_install": { "type": "boolean" }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 736d0554b3..1b7b7312c7 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -168,10 +168,12 @@ use crate::skills::SkillInjections; use crate::skills::SkillMetadata; use crate::skills::SkillsManager; use crate::skills::build_skill_injections; +use crate::skills::collect_env_var_dependencies; use crate::skills::collect_explicit_skill_mentions; use crate::skills::injection::ToolMentionKind; use crate::skills::injection::app_id_from_path; use crate::skills::injection::tool_kind_for_path; +use crate::skills::resolve_skill_dependencies_for_turn; use crate::state::ActiveTurn; use crate::state::SessionServices; use crate::state::SessionState; @@ -1953,6 +1955,16 @@ impl Session { state.record_mcp_dependency_prompted(names); } + pub async fn dependency_env(&self) -> HashMap { + let state = self.state.lock().await; + state.dependency_env() + } + + pub async fn set_dependency_env(&self, values: HashMap) { + let mut state = self.state.lock().await; + state.set_dependency_env(values); + } + pub(crate) async fn set_server_reasoning_included(&self, included: bool) { let mut state = self.state.lock().await; state.set_server_reasoning_included(included); @@ -3218,6 +3230,15 @@ pub(crate) async fn run_turn( }); let explicit_app_paths = collect_explicit_app_paths(&input); + let config = turn_context.client.config(); + if config + .features + .enabled(Feature::SkillEnvVarDependencyPrompt) + { + let env_var_dependencies = collect_env_var_dependencies(&mentioned_skills); + resolve_skill_dependencies_for_turn(&sess, &turn_context, &env_var_dependencies).await; + } + maybe_prompt_and_install_mcp_dependencies( sess.as_ref(), turn_context.as_ref(), diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 9bc52537b7..961b7a56f6 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -115,6 +115,8 @@ pub enum Feature { Apps, /// Allow prompting and installing missing MCP dependencies. SkillMcpDependencyInstall, + /// Prompt for missing skill env var dependencies. + SkillEnvVarDependencyPrompt, /// Steer feature flag - when enabled, Enter submits immediately instead of queuing. Steer, /// Enable collaboration modes (Plan, Code, Pair Programming, Execute). @@ -533,6 +535,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Stable, default_enabled: true, }, + FeatureSpec { + id: Feature::SkillEnvVarDependencyPrompt, + key: "skill_env_var_dependency_prompt", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::Steer, key: "steer", diff --git a/codex-rs/core/src/mcp/skill_dependencies.rs b/codex-rs/core/src/mcp/skill_dependencies.rs index c295a96863..37620d73db 100644 --- a/codex-rs/core/src/mcp/skill_dependencies.rs +++ b/codex-rs/core/src/mcp/skill_dependencies.rs @@ -79,6 +79,7 @@ async fn should_install_mcp_dependencies( "The following MCP servers are required by the selected skills but are not installed yet: {server_list}. Install them now?" ), is_other: false, + is_secret: false, options: Some(vec![ RequestUserInputQuestionOption { label: MCP_DEPENDENCY_OPTION_INSTALL.to_string(), diff --git a/codex-rs/core/src/skills/env_var_dependencies.rs b/codex-rs/core/src/skills/env_var_dependencies.rs new file mode 100644 index 0000000000..00f5bad8cc --- /dev/null +++ b/codex-rs/core/src/skills/env_var_dependencies.rs @@ -0,0 +1,162 @@ +use std::collections::HashMap; +use std::collections::HashSet; +use std::env; +use std::sync::Arc; + +use codex_protocol::request_user_input::RequestUserInputArgs; +use codex_protocol::request_user_input::RequestUserInputQuestion; +use codex_protocol::request_user_input::RequestUserInputResponse; +use tracing::warn; + +use crate::codex::Session; +use crate::codex::TurnContext; +use crate::skills::SkillMetadata; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SkillDependencyInfo { + pub(crate) skill_name: String, + pub(crate) name: String, + pub(crate) description: Option, +} + +/// Resolve required dependency values (session cache, then env vars), +/// and prompt the UI for any missing ones. +pub(crate) async fn resolve_skill_dependencies_for_turn( + sess: &Arc, + turn_context: &Arc, + dependencies: &[SkillDependencyInfo], +) { + if dependencies.is_empty() { + return; + } + + let existing_env = sess.dependency_env().await; + let mut loaded_values = HashMap::new(); + let mut missing = Vec::new(); + let mut seen_names = HashSet::new(); + + for dependency in dependencies { + let name = dependency.name.clone(); + if !seen_names.insert(name.clone()) { + continue; + } + if existing_env.contains_key(&name) { + continue; + } + match env::var(&name) { + Ok(value) => { + loaded_values.insert(name.clone(), value); + continue; + } + Err(env::VarError::NotPresent) => {} + Err(err) => { + warn!("failed to read env var {name}: {err}"); + } + } + missing.push(dependency.clone()); + } + + if !loaded_values.is_empty() { + sess.set_dependency_env(loaded_values).await; + } + + if !missing.is_empty() { + request_skill_dependencies(sess, turn_context, &missing).await; + } +} + +pub(crate) fn collect_env_var_dependencies( + mentioned_skills: &[SkillMetadata], +) -> Vec { + let mut dependencies = Vec::new(); + for skill in mentioned_skills { + let Some(skill_dependencies) = &skill.dependencies else { + continue; + }; + for tool in &skill_dependencies.tools { + if tool.r#type != "env_var" { + continue; + } + if tool.value.is_empty() { + continue; + } + dependencies.push(SkillDependencyInfo { + skill_name: skill.name.clone(), + name: tool.value.clone(), + description: tool.description.clone(), + }); + } + } + dependencies +} + +/// Prompt via request_user_input to gather missing env vars. +pub(crate) async fn request_skill_dependencies( + sess: &Arc, + turn_context: &Arc, + dependencies: &[SkillDependencyInfo], +) { + let questions = dependencies + .iter() + .map(|dep| { + let requirement = dep.description.as_ref().map_or_else( + || format!("The skill \"{}\" requires \"{}\" to be set.", dep.skill_name, dep.name), + |description| { + format!( + "The skill \"{}\" requires \"{}\" to be set ({}).", + dep.skill_name, dep.name, description + ) + }, + ); + let question = format!( + "{requirement} This is an experimental internal feature. The value is stored in memory for this session only.", + ); + RequestUserInputQuestion { + id: dep.name.clone(), + header: "Skill requires environment variable".to_string(), + question, + is_other: false, + is_secret: true, + options: None, + } + }) + .collect::>(); + + if questions.is_empty() { + return; + } + + let args = RequestUserInputArgs { questions }; + let call_id = format!("skill-deps-{}", turn_context.sub_id); + let response = sess + .request_user_input(turn_context, call_id, args) + .await + .unwrap_or_else(|| RequestUserInputResponse { + answers: HashMap::new(), + }); + + if response.answers.is_empty() { + return; + } + + let mut values = HashMap::new(); + for (name, answer) in response.answers { + let mut user_note = None; + for entry in &answer.answers { + if let Some(note) = entry.strip_prefix("user_note: ") + && !note.trim().is_empty() + { + user_note = Some(note.trim().to_string()); + } + } + if let Some(value) = user_note { + values.insert(name, value); + } + } + + if values.is_empty() { + return; + } + + sess.set_dependency_env(values).await; +} diff --git a/codex-rs/core/src/skills/mod.rs b/codex-rs/core/src/skills/mod.rs index ae4ffa2920..4d79bca258 100644 --- a/codex-rs/core/src/skills/mod.rs +++ b/codex-rs/core/src/skills/mod.rs @@ -1,3 +1,4 @@ +mod env_var_dependencies; pub mod injection; pub mod loader; pub mod manager; @@ -5,6 +6,8 @@ pub mod model; pub mod render; pub mod system; +pub(crate) use env_var_dependencies::collect_env_var_dependencies; +pub(crate) use env_var_dependencies::resolve_skill_dependencies_for_turn; pub(crate) use injection::SkillInjections; pub(crate) use injection::build_skill_injections; pub(crate) use injection::collect_explicit_skill_mentions; diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 9d3d96db99..deee0d0c7c 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_protocol::models::ResponseItem; +use std::collections::HashMap; use std::collections::HashSet; use crate::codex::SessionConfiguration; @@ -16,6 +17,7 @@ pub(crate) struct SessionState { pub(crate) history: ContextManager, pub(crate) latest_rate_limits: Option, 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. /// @@ -33,6 +35,7 @@ impl SessionState { history, latest_rate_limits: None, server_reasoning_included: false, + dependency_env: HashMap::new(), mcp_dependency_prompted: HashSet::new(), initial_context_seeded: false, } @@ -112,6 +115,16 @@ impl SessionState { pub(crate) fn mcp_dependency_prompted(&self) -> HashSet { self.mcp_dependency_prompted.clone() } + + pub(crate) fn set_dependency_env(&mut self, values: HashMap) { + for (key, value) in values { + self.dependency_env.insert(key, value); + } + } + + pub(crate) fn dependency_env(&self) -> HashMap { + self.dependency_env.clone() + } } // Sometimes new snapshots don't include credits or plan information. diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index dbfb0364bf..b59c0140d1 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -233,6 +233,12 @@ impl ShellHandler { None }; + let mut exec_params = exec_params; + let dependency_env = session.dependency_env().await; + if !dependency_env.is_empty() { + exec_params.env.extend(dependency_env); + } + // Approval policy guard for explicit escalation in non-OnRequest modes. if exec_params .sandbox_permissions diff --git a/codex-rs/protocol/src/request_user_input.rs b/codex-rs/protocol/src/request_user_input.rs index 0e58348da4..cb076264dd 100644 --- a/codex-rs/protocol/src/request_user_input.rs +++ b/codex-rs/protocol/src/request_user_input.rs @@ -20,6 +20,10 @@ pub struct RequestUserInputQuestion { #[schemars(rename = "isOther")] #[ts(rename = "isOther")] pub is_other: bool, + #[serde(rename = "isSecret", default)] + #[schemars(rename = "isSecret")] + #[ts(rename = "isSecret")] + pub is_secret: bool, #[serde(skip_serializing_if = "Option::is_none")] pub options: Option>, } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 9d0cbf22e5..90cae4b4a0 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -2854,6 +2854,12 @@ impl Renderable for ChatComposer { } fn render(&self, area: Rect, buf: &mut Buffer) { + self.render_with_mask(area, buf, None); + } +} + +impl ChatComposer { + pub(crate) fn render_with_mask(&self, area: Rect, buf: &mut Buffer, mask_char: Option) { let [composer_rect, textarea_rect, popup_rect] = self.layout_areas(area); match &self.active_popup { ActivePopup::Command(popup) => { @@ -3018,7 +3024,12 @@ impl Renderable for ChatComposer { } let mut state = self.textarea_state.borrow_mut(); - StatefulWidgetRef::render_ref(&(&self.textarea), textarea_rect, buf, &mut state); + if let Some(mask_char) = mask_char { + self.textarea + .render_ref_masked(textarea_rect, buf, &mut state, mask_char); + } else { + StatefulWidgetRef::render_ref(&(&self.textarea), textarea_rect, buf, &mut state); + } if self.textarea.text().is_empty() { let text = if self.input_enabled { self.placeholder_text.as_str().to_string() 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 979499835d..8fe3401693 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 @@ -1251,6 +1251,7 @@ mod tests { header: header.to_string(), question: "Choose an option.".to_string(), is_other: false, + is_secret: false, options: Some(vec![ RequestUserInputQuestionOption { label: "Option 1".to_string(), @@ -1274,6 +1275,7 @@ mod tests { header: header.to_string(), question: "Choose an option.".to_string(), is_other: true, + is_secret: false, options: Some(vec![ RequestUserInputQuestionOption { label: "Option 1".to_string(), @@ -1297,6 +1299,7 @@ mod tests { header: header.to_string(), question: "Choose the next step for this task.".to_string(), is_other: false, + is_secret: false, options: Some(vec![ RequestUserInputQuestionOption { label: "Discuss a code change".to_string(), @@ -1326,6 +1329,7 @@ mod tests { header: header.to_string(), question: "Share details.".to_string(), is_other: false, + is_secret: false, options: None, } } @@ -2385,6 +2389,7 @@ mod tests { header: "Next Step".to_string(), question: "What would you like to do next?".to_string(), is_other: false, + is_secret: false, options: Some(vec![ RequestUserInputQuestionOption { label: "Discuss a code change (Recommended)".to_string(), @@ -2436,6 +2441,7 @@ mod tests { header: "Next Step".to_string(), question: "What would you like to do next?".to_string(), is_other: false, + is_secret: false, options: Some(vec![ RequestUserInputQuestionOption { label: "Discuss a code change (Recommended)".to_string(), diff --git a/codex-rs/tui/src/bottom_pane/request_user_input/render.rs b/codex-rs/tui/src/bottom_pane/request_user_input/render.rs index b7433f8a6d..2180ec0553 100644 --- a/codex-rs/tui/src/bottom_pane/request_user_input/render.rs +++ b/codex-rs/tui/src/bottom_pane/request_user_input/render.rs @@ -414,7 +414,14 @@ impl RequestUserInputOverlay { if area.width == 0 || area.height == 0 { return; } - self.composer.render(area, buf); + let is_secret = self + .current_question() + .is_some_and(|question| question.is_secret); + if is_secret { + self.composer.render_with_mask(area, buf, Some('*')); + } else { + self.composer.render(area, buf); + } } } diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index 0235f7a9c1..42f7b09bef 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -1146,6 +1146,22 @@ impl StatefulWidgetRef for &TextArea { } impl TextArea { + pub(crate) fn render_ref_masked( + &self, + area: Rect, + buf: &mut Buffer, + state: &mut TextAreaState, + mask_char: char, + ) { + let lines = self.wrapped_lines(area.width); + let scroll = self.effective_scroll(area.height, &lines, state.scroll); + state.scroll = scroll; + + let start = scroll as usize; + let end = (scroll + area.height).min(lines.len() as u16) as usize; + self.render_lines_masked(area, buf, &lines, start..end, mask_char); + } + fn render_lines( &self, area: Rect, @@ -1175,6 +1191,26 @@ impl TextArea { } } } + + fn render_lines_masked( + &self, + area: Rect, + buf: &mut Buffer, + lines: &[Range], + range: std::ops::Range, + mask_char: char, + ) { + for (row, idx) in range.enumerate() { + let r = &lines[idx]; + let y = area.y + row as u16; + let line_range = r.start..r.end - 1; + let masked = self.text[line_range.clone()] + .chars() + .map(|_| mask_char) + .collect::(); + buf.set_string(area.x, y, &masked, Style::default()); + } + } } #[cfg(test)] From 48f203120d872776bc80ce4327c5066d513a74e9 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 29 Jan 2026 11:51:33 -0800 Subject: [PATCH 077/116] fix: unify `npm publish` call across shell-tool-mcp.yml and rust-release.yml (#10182) We are seeing flakiness in the `npm publish` step for https://www.npmjs.com/package/@openai/codex-shell-tool-mcp, so this is a shot in the dark for a fix: https://github.com/openai/codex/actions/runs/21490679301/job/61913765060 Note this removes `actions/checkout@v6` and `pnpm/action-setup@v4` steps, which I believe are superflous for the `npm publish` call. --- .github/workflows/shell-tool-mcp.yml | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index d6c85d9ddc..6285754fb0 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -436,14 +436,6 @@ jobs: id-token: write contents: read steps: - - name: Checkout repository - uses: actions/checkout@v6 - - - name: Setup pnpm - uses: pnpm/action-setup@v4 - with: - run_install: false - - name: Setup Node.js uses: actions/setup-node@v6 with: @@ -451,6 +443,10 @@ jobs: registry-url: https://registry.npmjs.org scope: "@openai" + # Trusted publishing requires npm CLI version 11.5.1 or later. + - name: Update npm + run: npm install -g npm@latest + - name: Download npm tarball uses: actions/download-artifact@v7 with: From 03aee7140f47826854bccdc3769c095131a0211a Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Thu, 29 Jan 2026 12:35:03 -0800 Subject: [PATCH 078/116] Add features enable/disable subcommands (#10180) ## Summary - add `codex features enable ` and `codex features disable ` - persist feature flag changes to `config.toml` (respecting profile) - print the under-development feature warning when enabling prerelease features - keep `features list` behavior unchanged and add unit/integration tests ## Testing - cargo test -p codex-cli --- codex-rs/cli/src/main.rs | 96 ++++++++++++++++++++++++++++++++++ codex-rs/cli/tests/features.rs | 58 ++++++++++++++++++++ 2 files changed, 154 insertions(+) create mode 100644 codex-rs/cli/tests/features.rs diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index faa6cf2fce..dd20f04128 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -39,6 +39,9 @@ use crate::mcp_cmd::McpCli; use codex_core::config::Config; use codex_core::config::ConfigOverrides; +use codex_core::config::edit::ConfigEditsBuilder; +use codex_core::config::find_codex_home; +use codex_core::features::Stage; use codex_core::features::is_known_feature_key; use codex_core::terminal::TerminalName; @@ -448,6 +451,16 @@ struct FeaturesCli { enum FeaturesSubcommand { /// List known features with their stage and effective state. List, + /// Enable a feature in config.toml. + Enable(FeatureSetArgs), + /// Disable a feature in config.toml. + Disable(FeatureSetArgs), +} + +#[derive(Debug, Parser)] +struct FeatureSetArgs { + /// Feature key to update (for example: unified_exec). + feature: String, } fn stage_str(stage: codex_core::features::Stage) -> &'static str { @@ -711,12 +724,69 @@ async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<() println!("{name: { + enable_feature_in_config(&interactive, &feature).await?; + } + FeaturesSubcommand::Disable(FeatureSetArgs { feature }) => { + disable_feature_in_config(&interactive, &feature).await?; + } }, } Ok(()) } +async fn enable_feature_in_config(interactive: &TuiCli, feature: &str) -> anyhow::Result<()> { + FeatureToggles::validate_feature(feature)?; + let codex_home = find_codex_home()?; + ConfigEditsBuilder::new(&codex_home) + .with_profile(interactive.config_profile.as_deref()) + .set_feature_enabled(feature, true) + .apply() + .await?; + println!("Enabled feature `{feature}` in config.toml."); + maybe_print_under_development_feature_warning(&codex_home, interactive, feature); + Ok(()) +} + +async fn disable_feature_in_config(interactive: &TuiCli, feature: &str) -> anyhow::Result<()> { + FeatureToggles::validate_feature(feature)?; + let codex_home = find_codex_home()?; + ConfigEditsBuilder::new(&codex_home) + .with_profile(interactive.config_profile.as_deref()) + .set_feature_enabled(feature, false) + .apply() + .await?; + println!("Disabled feature `{feature}` in config.toml."); + Ok(()) +} + +fn maybe_print_under_development_feature_warning( + codex_home: &std::path::Path, + interactive: &TuiCli, + feature: &str, +) { + if interactive.config_profile.is_some() { + return; + } + + let Some(spec) = codex_core::features::FEATURES + .iter() + .find(|spec| spec.key == feature) + else { + return; + }; + if !matches!(spec.stage, Stage::UnderDevelopment) { + return; + } + + let config_path = codex_home.join(codex_core::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() + ); +} + /// Prepend root-level overrides so they have lower precedence than /// CLI-specific ones specified after the subcommand (if any). fn prepend_config_flags( @@ -1171,6 +1241,32 @@ mod tests { assert!(app_server.analytics_default_enabled); } + #[test] + fn features_enable_parses_feature_name() { + let cli = MultitoolCli::try_parse_from(["codex", "features", "enable", "unified_exec"]) + .expect("parse should succeed"); + let Some(Subcommand::Features(FeaturesCli { sub })) = cli.subcommand else { + panic!("expected features subcommand"); + }; + let FeaturesSubcommand::Enable(FeatureSetArgs { feature }) = sub else { + panic!("expected features enable"); + }; + assert_eq!(feature, "unified_exec"); + } + + #[test] + fn features_disable_parses_feature_name() { + let cli = MultitoolCli::try_parse_from(["codex", "features", "disable", "shell_tool"]) + .expect("parse should succeed"); + let Some(Subcommand::Features(FeaturesCli { sub })) = cli.subcommand else { + panic!("expected features subcommand"); + }; + let FeaturesSubcommand::Disable(FeatureSetArgs { feature }) = sub else { + panic!("expected features disable"); + }; + assert_eq!(feature, "shell_tool"); + } + #[test] fn feature_toggles_known_features_generate_overrides() { let toggles = FeatureToggles { diff --git a/codex-rs/cli/tests/features.rs b/codex-rs/cli/tests/features.rs new file mode 100644 index 0000000000..8fa07e0a49 --- /dev/null +++ b/codex-rs/cli/tests/features.rs @@ -0,0 +1,58 @@ +use std::path::Path; + +use anyhow::Result; +use predicates::str::contains; +use tempfile::TempDir; + +fn codex_command(codex_home: &Path) -> Result { + let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); + cmd.env("CODEX_HOME", codex_home); + Ok(cmd) +} + +#[tokio::test] +async fn features_enable_writes_feature_flag_to_config() -> Result<()> { + let codex_home = TempDir::new()?; + + let mut cmd = codex_command(codex_home.path())?; + cmd.args(["features", "enable", "unified_exec"]) + .assert() + .success() + .stdout(contains("Enabled feature `unified_exec` in config.toml.")); + + let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; + assert!(config.contains("[features]")); + assert!(config.contains("unified_exec = true")); + + Ok(()) +} + +#[tokio::test] +async fn features_disable_writes_feature_flag_to_config() -> Result<()> { + let codex_home = TempDir::new()?; + + let mut cmd = codex_command(codex_home.path())?; + cmd.args(["features", "disable", "shell_tool"]) + .assert() + .success() + .stdout(contains("Disabled feature `shell_tool` in config.toml.")); + + let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; + assert!(config.contains("[features]")); + assert!(config.contains("shell_tool = false")); + + Ok(()) +} + +#[tokio::test] +async fn features_enable_under_development_feature_prints_warning() -> Result<()> { + let codex_home = TempDir::new()?; + + let mut cmd = codex_command(codex_home.path())?; + cmd.args(["features", "enable", "sqlite"]) + .assert() + .success() + .stderr(contains("Under-development features enabled: sqlite.")); + + Ok(()) +} From 2d9ac8227ae43ef7232b4f4422efc16cf0105bfb Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 29 Jan 2026 12:36:53 -0800 Subject: [PATCH 079/116] fix: /approvals -> /permissions (#10184) I believe we should be recommending `/permissions` in light of https://github.com/openai/codex/pull/9561. --- codex-rs/tui/tooltips.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/tui/tooltips.txt b/codex-rs/tui/tooltips.txt index dc2d2faa67..455ae5cd03 100644 --- a/codex-rs/tui/tooltips.txt +++ b/codex-rs/tui/tooltips.txt @@ -2,7 +2,7 @@ Use /compact when the conversation gets long to summarize history and free up co Start a fresh idea with /new; the previous session stays in history. Use /feedback to send logs to the maintainers when something looks off. Switch models or reasoning effort quickly with /model. -Use /approvals to control when Codex asks for confirmation. +Use /permissions to control when Codex asks for confirmation. Run /review to get a code review of your current changes. Use /skills to list available skills or ask Codex to use one. Use /status to see the current model, approvals, and token usage. From fbb3a309538180ca4c550ad0d8e75f2bfeae3a07 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 29 Jan 2026 13:50:53 -0800 Subject: [PATCH 080/116] Remove WebSocket wire format (#10179) I'd like WireApi to go away (when chat is removed) and WebSockets is still responses API just over a different transport. --- codex-rs/core/config.schema.json | 12 ++++---- codex-rs/core/src/client.rs | 28 +++++++++++++++---- codex-rs/core/src/config/mod.rs | 11 ++------ codex-rs/core/src/model_provider_info.rs | 17 +++++++---- codex-rs/core/src/models_manager/manager.rs | 1 + codex-rs/core/src/transport_manager.rs | 19 ++++--------- .../core/tests/chat_completions_payload.rs | 1 + codex-rs/core/tests/chat_completions_sse.rs | 1 + codex-rs/core/tests/common/test_codex.rs | 3 +- codex-rs/core/tests/responses_headers.rs | 3 ++ codex-rs/core/tests/suite/client.rs | 3 ++ .../core/tests/suite/client_websockets.rs | 5 +++- .../suite/stream_error_allows_next_turn.rs | 1 + .../core/tests/suite/stream_no_completed.rs | 1 + .../core/tests/suite/websocket_fallback.rs | 8 ++++-- 15 files changed, 68 insertions(+), 46 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 16c0c8945c..fe27f7e24e 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -443,6 +443,11 @@ "minimum": 0.0, "type": "integer" }, + "supports_websockets": { + "default": false, + "description": "Whether this provider supports the Responses API WebSocket transport.", + "type": "boolean" + }, "wire_api": { "allOf": [ { @@ -1081,13 +1086,6 @@ ], "type": "string" }, - { - "description": "Experimental: Responses API over WebSocket transport.", - "enum": [ - "responses_websocket" - ], - "type": "string" - }, { "description": "Regular Chat Completions compatible with `/v1/chat/completions`.", "enum": [ diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 98fce871fd..4cb37a46d4 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -260,12 +260,18 @@ impl ModelClientSession { /// For Chat providers, the underlying stream is optionally aggregated /// based on the `show_raw_agent_reasoning` flag in the config. pub async fn stream(&mut self, prompt: &Prompt) -> Result { - let wire_api = self - .transport_manager - .effective_wire_api(self.state.provider.wire_api); + let wire_api = self.state.provider.wire_api; match wire_api { - WireApi::Responses => self.stream_responses_api(prompt).await, - WireApi::ResponsesWebsocket => self.stream_responses_websocket(prompt).await, + WireApi::Responses => { + let websocket_enabled = self.responses_websocket_enabled() + && !self.transport_manager.disable_websockets(); + + if websocket_enabled { + self.stream_responses_websocket(prompt).await + } else { + self.stream_responses_api(prompt).await + } + } WireApi::Chat => { let api_stream = self.stream_chat_completions(prompt).await?; @@ -285,9 +291,10 @@ impl ModelClientSession { } pub(crate) fn try_switch_fallback_transport(&mut self) -> bool { + let websocket_enabled = self.responses_websocket_enabled(); let activated = self .transport_manager - .activate_http_fallback(self.state.provider.wire_api); + .activate_http_fallback(websocket_enabled); if activated { warn!("falling back to HTTP"); self.state.otel_manager.counter( @@ -302,6 +309,15 @@ impl ModelClientSession { activated } + fn responses_websocket_enabled(&self) -> bool { + self.state.provider.supports_websockets + && self + .state + .config + .features + .enabled(Feature::ResponsesWebsockets) + } + fn build_responses_request(&self, prompt: &Prompt) -> Result { let instructions = prompt.base_instructions.text.clone(); let tools_json: Vec = create_tools_json_for_responses_api(&prompt.tools)?; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 895e54c040..bc7dba6d71 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1372,12 +1372,6 @@ impl Config { || cfg.sandbox_mode.is_some(); let mut model_providers = built_in_model_providers(); - if features.enabled(Feature::ResponsesWebsockets) - && let Some(provider) = model_providers.get_mut("openai") - && provider.is_openai() - { - provider.wire_api = crate::model_provider_info::WireApi::ResponsesWebsocket; - } // Merge user-defined providers into the built-in list. for (key, provider) in cfg.model_providers.into_iter() { model_providers.entry(key).or_insert(provider); @@ -2555,7 +2549,7 @@ profile = "project" } #[test] - fn responses_websockets_feature_updates_openai_provider() -> std::io::Result<()> { + fn responses_websockets_feature_does_not_change_wire_api() -> std::io::Result<()> { let codex_home = TempDir::new()?; let mut entries = BTreeMap::new(); entries.insert("responses_websockets".to_string(), true); @@ -2572,7 +2566,7 @@ profile = "project" assert_eq!( config.model_provider.wire_api, - crate::model_provider_info::WireApi::ResponsesWebsocket + crate::model_provider_info::WireApi::Responses ); Ok(()) @@ -3692,6 +3686,7 @@ model_verbosity = "high" stream_max_retries: Some(10), stream_idle_timeout_ms: Some(300_000), requires_openai_auth: false, + supports_websockets: false, }; let model_provider_map = { let mut model_provider_map = built_in_model_providers(); diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index b1422458ca..4f69f02d91 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -43,10 +43,6 @@ pub enum WireApi { /// The Responses API exposed by OpenAI at `/v1/responses`. Responses, - /// Experimental: Responses API over WebSocket transport. - #[serde(rename = "responses_websocket")] - ResponsesWebsocket, - /// Regular Chat Completions compatible with `/v1/chat/completions`. #[default] Chat, @@ -105,6 +101,10 @@ pub struct ModelProviderInfo { /// and API key (if needed) comes from the "env_key" environment variable. #[serde(default)] pub requires_openai_auth: bool, + + /// Whether this provider supports the Responses API WebSocket transport. + #[serde(default)] + pub supports_websockets: bool, } impl ModelProviderInfo { @@ -162,7 +162,6 @@ impl ModelProviderInfo { query_params: self.query_params.clone(), wire: match self.wire_api { WireApi::Responses => ApiWireApi::Responses, - WireApi::ResponsesWebsocket => ApiWireApi::Responses, WireApi::Chat => ApiWireApi::Chat, }, headers, @@ -254,6 +253,7 @@ impl ModelProviderInfo { stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: true, + supports_websockets: true, } } @@ -332,6 +332,7 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, } } @@ -360,6 +361,7 @@ base_url = "http://localhost:11434/v1" stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap(); @@ -390,6 +392,7 @@ query_params = { api-version = "2025-04-01-preview" } stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap(); @@ -423,6 +426,7 @@ env_http_headers = { "X-Example-Env-Header" = "EXAMPLE_ENV_VAR" } stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap(); @@ -454,6 +458,7 @@ env_http_headers = { "X-Example-Env-Header" = "EXAMPLE_ENV_VAR" } stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; let api = provider.to_api_provider(None).expect("api provider"); assert!( @@ -476,6 +481,7 @@ env_http_headers = { "X-Example-Env-Header" = "EXAMPLE_ENV_VAR" } stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; let named_api = named_provider.to_api_provider(None).expect("api provider"); assert!(named_api.is_azure_responses_endpoint()); @@ -500,6 +506,7 @@ env_http_headers = { "X-Example-Env-Header" = "EXAMPLE_ENV_VAR" } stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; let api = provider.to_api_provider(None).expect("api provider"); assert!( diff --git a/codex-rs/core/src/models_manager/manager.rs b/codex-rs/core/src/models_manager/manager.rs index 58049b4747..77fb44cd5d 100644 --- a/codex-rs/core/src/models_manager/manager.rs +++ b/codex-rs/core/src/models_manager/manager.rs @@ -432,6 +432,7 @@ mod tests { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: false, } } diff --git a/codex-rs/core/src/transport_manager.rs b/codex-rs/core/src/transport_manager.rs index f1fe68faf4..2b5d095000 100644 --- a/codex-rs/core/src/transport_manager.rs +++ b/codex-rs/core/src/transport_manager.rs @@ -2,11 +2,9 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; -use crate::model_provider_info::WireApi; - #[derive(Clone, Debug, Default)] pub struct TransportManager { - fallback_to_http: Arc, + disable_websockets: Arc, } impl TransportManager { @@ -14,18 +12,11 @@ impl TransportManager { Self::default() } - pub fn effective_wire_api(&self, provider_wire_api: WireApi) -> WireApi { - if self.fallback_to_http.load(Ordering::Relaxed) - && provider_wire_api == WireApi::ResponsesWebsocket - { - WireApi::Responses - } else { - provider_wire_api - } + pub fn disable_websockets(&self) -> bool { + self.disable_websockets.load(Ordering::Relaxed) } - pub fn activate_http_fallback(&self, provider_wire_api: WireApi) -> bool { - provider_wire_api == WireApi::ResponsesWebsocket - && !self.fallback_to_http.swap(true, Ordering::Relaxed) + pub fn activate_http_fallback(&self, websocket_enabled: bool) -> bool { + websocket_enabled && !self.disable_websockets.swap(true, Ordering::Relaxed) } } diff --git a/codex-rs/core/tests/chat_completions_payload.rs b/codex-rs/core/tests/chat_completions_payload.rs index 5e8c895a3f..ffa2caa59f 100644 --- a/codex-rs/core/tests/chat_completions_payload.rs +++ b/codex-rs/core/tests/chat_completions_payload.rs @@ -60,6 +60,7 @@ async fn run_request(input: Vec) -> Value { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: false, }; let codex_home = match TempDir::new() { diff --git a/codex-rs/core/tests/chat_completions_sse.rs b/codex-rs/core/tests/chat_completions_sse.rs index 84d0ede085..160699733e 100644 --- a/codex-rs/core/tests/chat_completions_sse.rs +++ b/codex-rs/core/tests/chat_completions_sse.rs @@ -59,6 +59,7 @@ async fn run_stream_with_bytes(sse_body: &[u8]) -> Vec { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: false, }; let codex_home = match TempDir::new() { diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index a247453775..af85ebb955 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -8,7 +8,6 @@ use codex_core::CodexAuth; use codex_core::CodexThread; use codex_core::ModelProviderInfo; use codex_core::ThreadManager; -use codex_core::WireApi; use codex_core::built_in_model_providers; use codex_core::config::Config; use codex_core::features::Feature; @@ -127,7 +126,7 @@ impl TestCodexBuilder { let base_url_clone = base_url.clone(); self.config_mutators.push(Box::new(move |config| { config.model_provider.base_url = Some(base_url_clone); - config.model_provider.wire_api = WireApi::ResponsesWebsocket; + config.features.enable(Feature::ResponsesWebsockets); })); self.build_with_home_and_base_url(base_url, home, None) .await diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index b3c0165f46..b2c64818cc 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -57,6 +57,7 @@ async fn responses_stream_includes_subagent_header_on_review() { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: false, }; let codex_home = TempDir::new().expect("failed to create TempDir"); @@ -154,6 +155,7 @@ async fn responses_stream_includes_subagent_header_on_other() { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: false, }; let codex_home = TempDir::new().expect("failed to create TempDir"); @@ -307,6 +309,7 @@ async fn responses_respects_model_info_overrides_from_config() { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: false, }; let codex_home = TempDir::new().expect("failed to create TempDir"); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 8b8adf06ab..72608a44d8 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -1151,6 +1151,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: false, }; let codex_home = TempDir::new().unwrap(); @@ -1671,6 +1672,7 @@ async fn azure_overrides_assign_properties_used_for_responses_url() { stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; // Init session @@ -1751,6 +1753,7 @@ async fn env_var_overrides_loaded_auth() { stream_max_retries: None, stream_idle_timeout_ms: None, requires_openai_auth: false, + supports_websockets: false, }; // Init session diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 60229e01d6..5037479987 100644 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -10,6 +10,7 @@ use codex_core::ResponseEvent; use codex_core::ResponseItem; use codex_core::TransportManager; use codex_core::WireApi; +use codex_core::features::Feature; use codex_core::models_manager::manager::ModelsManager; use codex_core::protocol::SessionSource; use codex_otel::OtelManager; @@ -188,7 +189,7 @@ fn websocket_provider(server: &WebSocketTestServer) -> ModelProviderInfo { env_key: None, env_key_instructions: None, experimental_bearer_token: None, - wire_api: WireApi::ResponsesWebsocket, + wire_api: WireApi::Responses, query_params: None, http_headers: None, env_http_headers: None, @@ -196,6 +197,7 @@ fn websocket_provider(server: &WebSocketTestServer) -> ModelProviderInfo { stream_max_retries: Some(0), stream_idle_timeout_ms: Some(5_000), requires_openai_auth: false, + supports_websockets: true, } } @@ -204,6 +206,7 @@ async fn websocket_harness(server: &WebSocketTestServer) -> WebsocketTestHarness let codex_home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&codex_home).await; config.model = Some(MODEL.to_string()); + config.features.enable(Feature::ResponsesWebsockets); let config = Arc::new(config); let model_info = ModelsManager::construct_model_info_offline(MODEL, &config); let conversation_id = ThreadId::new(); 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 6bfcef38b3..ec18816235 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 @@ -73,6 +73,7 @@ async fn continue_after_stream_error() { stream_max_retries: Some(1), stream_idle_timeout_ms: Some(2_000), requires_openai_auth: false, + supports_websockets: false, }; let TestCodex { codex, .. } = test_codex() diff --git a/codex-rs/core/tests/suite/stream_no_completed.rs b/codex-rs/core/tests/suite/stream_no_completed.rs index a4962d497e..68b7763eca 100644 --- a/codex-rs/core/tests/suite/stream_no_completed.rs +++ b/codex-rs/core/tests/suite/stream_no_completed.rs @@ -81,6 +81,7 @@ async fn retries_on_early_close() { stream_max_retries: Some(1), stream_idle_timeout_ms: Some(2000), requires_openai_auth: false, + supports_websockets: false, }; let TestCodex { codex, .. } = test_codex() diff --git a/codex-rs/core/tests/suite/websocket_fallback.rs b/codex-rs/core/tests/suite/websocket_fallback.rs index d52236a8a2..e61c4e5c2d 100644 --- a/codex-rs/core/tests/suite/websocket_fallback.rs +++ b/codex-rs/core/tests/suite/websocket_fallback.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use codex_core::WireApi; +use codex_core::features::Feature; use core_test_support::responses; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; @@ -26,7 +26,8 @@ async fn websocket_fallback_switches_to_http_after_retries_exhausted() -> Result let base_url = format!("{}/v1", server.uri()); move |config| { config.model_provider.base_url = Some(base_url); - config.model_provider.wire_api = WireApi::ResponsesWebsocket; + config.model_provider.wire_api = codex_core::WireApi::Responses; + config.features.enable(Feature::ResponsesWebsockets); config.model_provider.stream_max_retries = Some(0); config.model_provider.request_max_retries = Some(0); } @@ -70,7 +71,8 @@ async fn websocket_fallback_is_sticky_across_turns() -> Result<()> { let base_url = format!("{}/v1", server.uri()); move |config| { config.model_provider.base_url = Some(base_url); - config.model_provider.wire_api = WireApi::ResponsesWebsocket; + config.model_provider.wire_api = codex_core::WireApi::Responses; + config.features.enable(Feature::ResponsesWebsockets); config.model_provider.stream_max_retries = Some(0); config.model_provider.request_max_retries = Some(0); } From ca9d417633ad47fc5ed8dbc5ab01d57bd9ea70c0 Mon Sep 17 00:00:00 2001 From: natea-oai Date: Thu, 29 Jan 2026 14:41:42 -0800 Subject: [PATCH 081/116] updating comment to better indicate intent of skipping `quit` in the main slash command menu (#10186) Updates comment indicating intent for skipping `quit` in the main slash command dropdown. --- codex-rs/tui/src/bottom_pane/command_popup.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 5423231db8..621683923d 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -122,7 +122,8 @@ impl CommandPopup { if filter.is_empty() { // Built-ins first, in presentation order. for (_, cmd) in self.builtins.iter() { - // Skipping quit as it's a duplicate of exit. + // Hide alias commands in the default popup list so each unique action appears once. + // `quit` is an alias of `exit`, so we skip `quit` here. if *cmd == SlashCommand::Quit { continue; } From b79bf69af6a68d162a95af883564d9e480948e62 Mon Sep 17 00:00:00 2001 From: Colin Young Date: Thu, 29 Jan 2026 14:59:07 -0800 Subject: [PATCH 082/116] [Codex][CLI] Show model-capacity guidance on 429 (#10118) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ###### Problem Users get generic 429s with no guidance when a model is at capacity. ###### Solution Detect model-cap headers, surface a clear “try a different model” message, and keep behavior non‑intrusive (no auto‑switch). ###### Scope CLI/TUI only; protocol + error mapping updated to carry model‑cap info. ###### Tests - just fmt - cargo test -p codex-tui - cargo test -p codex-core --lib shell_snapshot::tests::try_new_creates_and_deletes_snapshot_file -- --nocapture (ran in isolated env) - validate local build with backend image --- .../app-server-protocol/src/protocol/v2.rs | 11 +++ codex-rs/core/src/api_bridge.rs | 54 ++++++++++++ codex-rs/core/src/error.rs | 85 ++++++++++++++++++- codex-rs/protocol/src/protocol.rs | 4 + codex-rs/tui/src/chatwidget.rs | 79 ++++++++++++++++- codex-rs/tui/src/chatwidget/tests.rs | 37 ++++++++ 6 files changed, 268 insertions(+), 2 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 247360282c..78cce916e4 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -86,6 +86,10 @@ macro_rules! v2_enum_from_core { pub enum CodexErrorInfo { ContextWindowExceeded, UsageLimitExceeded, + ModelCap { + model: String, + reset_after_seconds: Option, + }, HttpConnectionFailed { #[serde(rename = "httpStatusCode")] #[ts(rename = "httpStatusCode")] @@ -122,6 +126,13 @@ impl From for CodexErrorInfo { match value { CoreCodexErrorInfo::ContextWindowExceeded => CodexErrorInfo::ContextWindowExceeded, CoreCodexErrorInfo::UsageLimitExceeded => CodexErrorInfo::UsageLimitExceeded, + CoreCodexErrorInfo::ModelCap { + model, + reset_after_seconds, + } => CodexErrorInfo::ModelCap { + model, + reset_after_seconds, + }, CoreCodexErrorInfo::HttpConnectionFailed { http_status_code } => { CodexErrorInfo::HttpConnectionFailed { http_status_code } } diff --git a/codex-rs/core/src/api_bridge.rs b/codex-rs/core/src/api_bridge.rs index 79ca839816..ec21f1ec85 100644 --- a/codex-rs/core/src/api_bridge.rs +++ b/codex-rs/core/src/api_bridge.rs @@ -9,6 +9,7 @@ use serde::Deserialize; use crate::auth::CodexAuth; use crate::error::CodexErr; +use crate::error::ModelCapError; use crate::error::RetryLimitReachedError; use crate::error::UnexpectedResponseError; use crate::error::UsageLimitReachedError; @@ -49,6 +50,23 @@ pub(crate) fn map_api_error(err: ApiError) -> CodexErr { } else if status == http::StatusCode::INTERNAL_SERVER_ERROR { CodexErr::InternalServerError } else if status == http::StatusCode::TOO_MANY_REQUESTS { + if let Some(model) = headers + .as_ref() + .and_then(|map| map.get(MODEL_CAP_MODEL_HEADER)) + .and_then(|value| value.to_str().ok()) + .map(str::to_string) + { + let reset_after_seconds = headers + .as_ref() + .and_then(|map| map.get(MODEL_CAP_RESET_AFTER_HEADER)) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()); + return CodexErr::ModelCap(ModelCapError { + model, + reset_after_seconds, + }); + } + if let Ok(err) = serde_json::from_str::(&body_text) { if err.error.error_type.as_deref() == Some("usage_limit_reached") { let rate_limits = headers.as_ref().and_then(parse_rate_limit); @@ -92,6 +110,42 @@ pub(crate) fn map_api_error(err: ApiError) -> CodexErr { } } +const MODEL_CAP_MODEL_HEADER: &str = "x-codex-model-cap-model"; +const MODEL_CAP_RESET_AFTER_HEADER: &str = "x-codex-model-cap-reset-after-seconds"; + +#[cfg(test)] +mod tests { + use super::*; + use codex_api::TransportError; + use http::HeaderMap; + use http::StatusCode; + + #[test] + fn map_api_error_maps_model_cap_headers() { + let mut headers = HeaderMap::new(); + headers.insert( + MODEL_CAP_MODEL_HEADER, + http::HeaderValue::from_static("boomslang"), + ); + headers.insert( + MODEL_CAP_RESET_AFTER_HEADER, + http::HeaderValue::from_static("120"), + ); + let err = map_api_error(ApiError::Transport(TransportError::Http { + status: StatusCode::TOO_MANY_REQUESTS, + url: Some("http://example.com/v1/responses".to_string()), + headers: Some(headers), + body: Some(String::new()), + })); + + let CodexErr::ModelCap(model_cap) = err else { + panic!("expected CodexErr::ModelCap, got {err:?}"); + }; + assert_eq!(model_cap.model, "boomslang"); + assert_eq!(model_cap.reset_after_seconds, Some(120)); + } +} + fn extract_request_id(headers: Option<&HeaderMap>) -> Option { headers.and_then(|map| { ["cf-ray", "x-request-id", "x-oai-request-id"] diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index e9830f5189..6c284074c9 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -113,6 +113,9 @@ pub enum CodexErr { #[error("{0}")] UsageLimitReached(UsageLimitReachedError), + #[error("{0}")] + ModelCap(ModelCapError), + #[error("{0}")] ResponseStreamFailed(ResponseStreamFailed), @@ -205,7 +208,8 @@ impl CodexErr { | CodexErr::AgentLimitReached { .. } | CodexErr::Spawn | CodexErr::SessionConfiguredNotFirstEvent - | CodexErr::UsageLimitReached(_) => false, + | CodexErr::UsageLimitReached(_) + | CodexErr::ModelCap(_) => false, CodexErr::Stream(..) | CodexErr::Timeout | CodexErr::UnexpectedStatus(_) @@ -394,6 +398,30 @@ impl std::fmt::Display for UsageLimitReachedError { } } +#[derive(Debug)] +pub struct ModelCapError { + pub(crate) model: String, + pub(crate) reset_after_seconds: Option, +} + +impl std::fmt::Display for ModelCapError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut message = format!( + "Model {} is at capacity. Please try a different model.", + self.model + ); + if let Some(seconds) = self.reset_after_seconds { + message.push_str(&format!( + " Try again in {}.", + format_duration_short(seconds) + )); + } else { + message.push_str(" Try again later."); + } + write!(f, "{message}") + } +} + fn retry_suffix(resets_at: Option<&DateTime>) -> String { if let Some(resets_at) = resets_at { let formatted = format_retry_timestamp(resets_at); @@ -425,6 +453,18 @@ fn format_retry_timestamp(resets_at: &DateTime) -> String { } } +fn format_duration_short(seconds: u64) -> String { + if seconds < 60 { + "less than a minute".to_string() + } else if seconds < 3600 { + format!("{}m", seconds / 60) + } else if seconds < 86_400 { + format!("{}h", seconds / 3600) + } else { + format!("{}d", seconds / 86_400) + } +} + fn day_suffix(day: u32) -> &'static str { match day { 11..=13 => "th", @@ -488,6 +528,10 @@ impl CodexErr { CodexErr::UsageLimitReached(_) | CodexErr::QuotaExceeded | CodexErr::UsageNotIncluded => CodexErrorInfo::UsageLimitExceeded, + CodexErr::ModelCap(err) => CodexErrorInfo::ModelCap { + model: err.model.clone(), + reset_after_seconds: err.reset_after_seconds, + }, CodexErr::RetryLimit(_) => CodexErrorInfo::ResponseTooManyFailedAttempts { http_status_code: self.http_status_code_value(), }, @@ -631,6 +675,45 @@ mod tests { ); } + #[test] + fn model_cap_error_formats_message() { + let err = ModelCapError { + model: "boomslang".to_string(), + reset_after_seconds: Some(120), + }; + assert_eq!( + err.to_string(), + "Model boomslang is at capacity. Please try a different model. Try again in 2m." + ); + } + + #[test] + fn model_cap_error_formats_message_without_reset() { + let err = ModelCapError { + model: "boomslang".to_string(), + reset_after_seconds: None, + }; + assert_eq!( + err.to_string(), + "Model boomslang is at capacity. Please try a different model. Try again later." + ); + } + + #[test] + fn model_cap_error_maps_to_protocol() { + let err = CodexErr::ModelCap(ModelCapError { + model: "boomslang".to_string(), + reset_after_seconds: Some(30), + }); + assert_eq!( + err.to_codex_protocol_error(), + CodexErrorInfo::ModelCap { + model: "boomslang".to_string(), + reset_after_seconds: Some(30), + } + ); + } + #[test] fn sandbox_denied_uses_aggregated_output_when_stderr_empty() { let output = ExecToolCallOutput { diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index b9a4f2120b..aea7d3f013 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -925,6 +925,10 @@ pub enum AgentStatus { pub enum CodexErrorInfo { ContextWindowExceeded, UsageLimitExceeded, + ModelCap { + model: String, + reset_after_seconds: Option, + }, HttpConnectionFailed { http_status_code: Option, }, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 8a0dd81afe..c132130515 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -49,6 +49,7 @@ 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; @@ -399,6 +400,33 @@ enum ConnectorsCacheState { Failed(String), } +#[derive(Debug)] +enum RateLimitErrorKind { + ModelCap { + model: String, + reset_after_seconds: Option, + }, + UsageLimit, + Generic, +} + +fn rate_limit_error_kind(info: &CodexErrorInfo) -> Option { + match info { + CodexErrorInfo::ModelCap { + model, + reset_after_seconds, + } => Some(RateLimitErrorKind::ModelCap { + model: model.clone(), + reset_after_seconds: *reset_after_seconds, + }), + CodexErrorInfo::UsageLimitExceeded => Some(RateLimitErrorKind::UsageLimit), + CodexErrorInfo::ResponseTooManyFailedAttempts { + http_status_code: Some(429), + } => Some(RateLimitErrorKind::Generic), + _ => None, + } +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) enum ExternalEditorState { #[default] @@ -1156,6 +1184,24 @@ impl ChatWidget { self.maybe_show_pending_rate_limit_prompt(); } + fn on_model_cap_error(&mut self, model: String, reset_after_seconds: Option) { + self.finalize_turn(); + + let mut message = format!("Model {model} is at capacity. Please try a different model."); + if let Some(seconds) = reset_after_seconds { + message.push_str(&format!( + " Try again in {}.", + format_duration_short(seconds) + )); + } else { + message.push_str(" Try again later."); + } + + self.add_to_history(history_cell::new_warning_event(message)); + self.request_redraw(); + self.maybe_send_next_queued_input(); + } + fn on_error(&mut self, message: String) { self.finalize_turn(); self.add_to_history(history_cell::new_error_event(message)); @@ -3085,7 +3131,26 @@ impl ChatWidget { self.on_rate_limit_snapshot(ev.rate_limits); } EventMsg::Warning(WarningEvent { message }) => self.on_warning(message), - EventMsg::Error(ErrorEvent { message, .. }) => self.on_error(message), + EventMsg::Error(ErrorEvent { + message, + codex_error_info, + }) => { + if let Some(info) = codex_error_info + && let Some(kind) = rate_limit_error_kind(&info) + { + match kind { + RateLimitErrorKind::ModelCap { + model, + reset_after_seconds, + } => self.on_model_cap_error(model, reset_after_seconds), + RateLimitErrorKind::UsageLimit | RateLimitErrorKind::Generic => { + self.on_error(message) + } + } + } else { + self.on_error(message); + } + } EventMsg::McpStartupUpdate(ev) => self.on_mcp_startup_update(ev), EventMsg::McpStartupComplete(ev) => self.on_mcp_startup_complete(ev), EventMsg::TurnAborted(ev) => match ev.reason { @@ -5911,5 +5976,17 @@ pub(crate) fn show_review_commit_picker_with_entries( }); } +fn format_duration_short(seconds: u64) -> String { + if seconds < 60 { + "less than a minute".to_string() + } else if seconds < 3600 { + format!("{}m", seconds / 60) + } else if seconds < 86_400 { + format!("{}h", seconds / 3600) + } else { + format!("{}d", seconds / 86_400) + } +} + #[cfg(test)] pub(crate) mod tests; diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 570a72750b..9859e9e56f 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -3021,6 +3021,43 @@ async fn model_picker_hides_show_in_picker_false_models_from_cache() { ); } +#[tokio::test] +async fn model_cap_error_does_not_switch_models() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("boomslang")).await; + chat.set_model("boomslang"); + while rx.try_recv().is_ok() {} + while op_rx.try_recv().is_ok() {} + + chat.handle_codex_event(Event { + id: "err-1".to_string(), + msg: EventMsg::Error(ErrorEvent { + message: "model cap".to_string(), + codex_error_info: Some(CodexErrorInfo::ModelCap { + model: "boomslang".to_string(), + reset_after_seconds: Some(120), + }), + }), + }); + + while let Ok(event) = rx.try_recv() { + if let AppEvent::UpdateModel(model) = event { + assert_eq!( + model, "boomslang", + "did not expect model switch on model-cap error" + ); + } + } + + while let Ok(event) = op_rx.try_recv() { + if let Op::OverrideTurnContext { model, .. } = event { + assert!( + model.is_none(), + "did not expect OverrideTurnContext model update on model-cap error" + ); + } + } +} + #[tokio::test] async fn approvals_selection_popup_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; From 81a17bb2c1041ad1d89527911318386ce036afa9 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Thu, 29 Jan 2026 15:46:04 -0800 Subject: [PATCH 083/116] feat(app-server): support external auth mode (#10012) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This enables a new use case where `codex app-server` is embedded into a parent application that will directly own the user's ChatGPT auth lifecycle, which means it owns the user’s auth tokens and refreshes it when necessary. The parent application would just want a way to pass in the auth tokens for codex to use directly. The idea is that we are introducing a new "auth mode" currently only exposed via app server: **`chatgptAuthTokens`** which consist of the `id_token` (stores account metadata) and `access_token` (the bearer token used directly for backend API calls). These auth tokens are only stored in-memory. This new mode is in addition to the existing `apiKey` and `chatgpt` auth modes. This PR reuses the shape of our existing app-server account APIs as much as possible: - Update `account/login/start` with a new `chatgptAuthTokens` variant, which will allow the client to pass in the tokens and have codex app-server use them directly. Upon success, the server emits `account/login/completed` and `account/updated` notifications. - A new server->client request called `account/chatgptAuthTokens/refresh` which the server can use whenever the access token previously passed in has expired and it needs a new one from the parent application. I leveraged the core 401 retry loop which typically triggers auth token refreshes automatically, but made it pluggable: - **chatgpt** mode refreshes internally, as usual. - **chatgptAuthTokens** mode calls the client via `account/chatgptAuthTokens/refresh`, the client responds with updated tokens, codex updates its in-memory auth, then retries. This RPC has a 10s timeout and handles JSON-RPC errors from the client. Also some additional things: - chatgpt logins are blocked while external auth is active (have to log out first. typically clients will pick one OR the other, not support both) - `account/logout` clears external auth in memory - Ensures that if `forced_chatgpt_workspace_id` is set via the user's config, we respect it in both: - `account/login/start` with `chatgptAuthTokens` (returns a JSON-RPC error back to the client) - `account/chatgptAuthTokens/refresh` (fails the turn, and on next request app-server will send another `account/chatgptAuthTokens/refresh` request to the client). --- codex-rs/Cargo.lock | 1 + .../src/protocol/common.rs | 61 +- .../app-server-protocol/src/protocol/v2.rs | 57 ++ codex-rs/app-server/Cargo.toml | 1 + codex-rs/app-server/README.md | 9 +- .../app-server/src/codex_message_processor.rs | 126 +++- codex-rs/app-server/src/lib.rs | 2 +- codex-rs/app-server/src/message_processor.rs | 72 +- codex-rs/app-server/src/outgoing_message.rs | 34 +- .../app-server/tests/common/auth_fixtures.rs | 2 + .../app-server/tests/common/mcp_process.rs | 25 + codex-rs/app-server/tests/suite/v2/account.rs | 707 +++++++++++++++++- codex-rs/cli/src/login.rs | 4 + codex-rs/core/config.schema.json | 7 + codex-rs/core/src/auth.rs | 400 ++++++++-- codex-rs/core/src/auth/storage.rs | 89 ++- codex-rs/core/src/client.rs | 4 +- codex-rs/core/src/model_provider_info.rs | 5 +- codex-rs/core/src/models_manager/manager.rs | 8 +- codex-rs/core/src/token_data.rs | 15 +- codex-rs/core/tests/suite/auth_refresh.rs | 11 + codex-rs/login/src/server.rs | 2 + codex-rs/tui/src/chatwidget.rs | 7 +- codex-rs/tui/src/onboarding/auth.rs | 5 +- codex-rs/tui/src/status/helpers.rs | 2 +- 25 files changed, 1577 insertions(+), 79 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 4c321b3f62..35d3129106 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1080,6 +1080,7 @@ version = "0.0.0" dependencies = [ "anyhow", "app_test_support", + "async-trait", "axum", "base64", "chrono", diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index cad6976b4b..2aaf419440 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -28,6 +28,11 @@ impl GitSha { pub enum AuthMode { ApiKey, ChatGPT, + /// [UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. + #[serde(rename = "chatgptAuthTokens")] + #[ts(rename = "chatgptAuthTokens")] + #[strum(serialize = "chatgptAuthTokens")] + ChatgptAuthTokens, } /// Generates an `enum ClientRequest` where each variant is a request that the @@ -534,6 +539,11 @@ server_request_definitions! { response: v2::DynamicToolCallResponse, }, + ChatgptAuthTokensRefresh => "account/chatgptAuthTokens/refresh" { + params: v2::ChatgptAuthTokensRefreshParams, + response: v2::ChatgptAuthTokensRefreshResponse, + }, + /// DEPRECATED APIs below /// Request to approve a patch. /// This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage). @@ -753,6 +763,29 @@ mod tests { Ok(()) } + #[test] + fn serialize_chatgpt_auth_tokens_refresh_request() -> Result<()> { + let request = ServerRequest::ChatgptAuthTokensRefresh { + request_id: RequestId::Integer(8), + params: v2::ChatgptAuthTokensRefreshParams { + reason: v2::ChatgptAuthTokensRefreshReason::Unauthorized, + previous_account_id: Some("org-123".to_string()), + }, + }; + assert_eq!( + json!({ + "method": "account/chatgptAuthTokens/refresh", + "id": 8, + "params": { + "reason": "unauthorized", + "previousAccountId": "org-123" + } + }), + serde_json::to_value(&request)?, + ); + Ok(()) + } + #[test] fn serialize_get_account_rate_limits() -> Result<()> { let request = ClientRequest::GetAccountRateLimits { @@ -842,10 +875,34 @@ mod tests { Ok(()) } + #[test] + fn serialize_account_login_chatgpt_auth_tokens() -> Result<()> { + let request = ClientRequest::LoginAccount { + request_id: RequestId::Integer(5), + params: v2::LoginAccountParams::ChatgptAuthTokens { + access_token: "access-token".to_string(), + id_token: "id-token".to_string(), + }, + }; + assert_eq!( + json!({ + "method": "account/login/start", + "id": 5, + "params": { + "type": "chatgptAuthTokens", + "accessToken": "access-token", + "idToken": "id-token" + } + }), + serde_json::to_value(&request)?, + ); + Ok(()) + } + #[test] fn serialize_get_account() -> Result<()> { let request = ClientRequest::GetAccount { - request_id: RequestId::Integer(5), + request_id: RequestId::Integer(6), params: v2::GetAccountParams { refresh_token: false, }, @@ -853,7 +910,7 @@ mod tests { assert_eq!( json!({ "method": "account/read", - "id": 5, + "id": 6, "params": { "refreshToken": false } diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 78cce916e4..ac3df37bd0 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -835,6 +835,24 @@ pub enum LoginAccountParams { #[serde(rename = "chatgpt")] #[ts(rename = "chatgpt")] Chatgpt, + /// [UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. + /// The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have. + #[serde(rename = "chatgptAuthTokens")] + #[ts(rename = "chatgptAuthTokens")] + ChatgptAuthTokens { + /// ID token (JWT) supplied by the client. + /// + /// This token is used for identity and account metadata (email, plan type, + /// workspace id). + #[serde(rename = "idToken")] + #[ts(rename = "idToken")] + id_token: String, + /// Access token (JWT) supplied by the client. + /// This token is used for backend API requests. + #[serde(rename = "accessToken")] + #[ts(rename = "accessToken")] + access_token: String, + }, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -854,6 +872,9 @@ pub enum LoginAccountResponse { /// URL the client should open in a browser to initiate the OAuth flow. auth_url: String, }, + #[serde(rename = "chatgptAuthTokens", rename_all = "camelCase")] + #[ts(rename = "chatgptAuthTokens", rename_all = "camelCase")] + ChatgptAuthTokens {}, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -884,6 +905,37 @@ pub struct CancelLoginAccountResponse { #[ts(export_to = "v2/")] pub struct LogoutAccountResponse {} +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ChatgptAuthTokensRefreshReason { + /// Codex attempted a backend request and received `401 Unauthorized`. + Unauthorized, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ChatgptAuthTokensRefreshParams { + pub reason: ChatgptAuthTokensRefreshReason, + /// Workspace/account identifier that Codex was previously using. + /// + /// Clients that manage multiple accounts/workspaces can use this as a hint + /// to refresh the token for the correct workspace. + /// + /// This may be `null` when the prior ID token did not include a workspace + /// identifier (`chatgpt_account_id`) or when the token could not be parsed. + pub previous_account_id: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ChatgptAuthTokensRefreshResponse { + pub id_token: String, + pub access_token: String, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -895,6 +947,11 @@ pub struct GetAccountRateLimitsResponse { #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct GetAccountParams { + /// When `true`, requests a proactive token refresh before returning. + /// + /// In 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`. #[serde(default)] pub refresh_token: bool, } diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index af2f30c49c..820edf59c2 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -17,6 +17,7 @@ workspace = true [dependencies] anyhow = { workspace = true } +async-trait = { workspace = true } codex-arg0 = { workspace = true } codex-common = { workspace = true, features = ["cli"] } codex-core = { workspace = true } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index caba8580aa..e9ebcd9661 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -659,10 +659,17 @@ $demo-app Pull the latest updates from the team. The JSON-RPC auth/account surface exposes request/response methods plus server-initiated notifications (no `id`). Use these to determine auth state, start or cancel logins, logout, and inspect ChatGPT rate limits. +### Authentication modes + +Codex supports these authentication modes. The current mode is surfaced in `account/updated` (`authMode`) and can be inferred from `account/read`. + +- **API key (`apiKey`)**: Caller supplies an OpenAI API key via `account/login/start` with `type: "apiKey"`. The API key is saved and used for API requests. +- **ChatGPT managed (`chatgpt`)** (recommended): Codex owns the ChatGPT OAuth flow and refresh tokens. Start via `account/login/start` with `type: "chatgpt"`; Codex persists tokens to disk and refreshes them automatically. + ### API Overview - `account/read` — fetch current account info; optionally refresh tokens. -- `account/login/start` — begin login (`apiKey` or `chatgpt`). +- `account/login/start` — begin login (`apiKey`, `chatgpt`). - `account/login/completed` (notify) — emitted when a login attempt finishes (success or error). - `account/login/cancel` — cancel a pending ChatGPT login by `loginId`. - `account/logout` — sign out; triggers `account/updated`. diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index e1c982a99d..660b4b87d0 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -57,6 +57,7 @@ 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; @@ -141,6 +142,7 @@ use codex_core::ThreadManager; use codex_core::ThreadSortKey as CoreThreadSortKey; use codex_core::auth::CLIENT_ID; 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; @@ -169,6 +171,7 @@ use codex_core::read_session_meta_line; use codex_core::rollout_date_parts; use codex_core::sandboxing::SandboxPermissions; use codex_core::state_db::get_state_db; +use codex_core::token_data::parse_id_token; use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_feedback::CodexFeedback; use codex_login::ServerOptions as LoginServerOptions; @@ -607,6 +610,22 @@ impl CodexMessageProcessor { LoginAccountParams::Chatgpt => { self.login_chatgpt_v2(request_id).await; } + LoginAccountParams::ChatgptAuthTokens { + id_token, + access_token, + } => { + self.login_chatgpt_auth_tokens(request_id, id_token, access_token) + .await; + } + } + } + + fn external_auth_active_error(&self) -> JSONRPCErrorError { + JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: "External auth is active. Use account/login/start (chatgptAuthTokens) to update it or account/logout to clear it." + .to_string(), + data: None, } } @@ -614,6 +633,10 @@ impl CodexMessageProcessor { &mut self, params: &LoginApiKeyParams, ) -> std::result::Result<(), JSONRPCErrorError> { + if self.auth_manager.is_external_auth_active() { + return Err(self.external_auth_active_error()); + } + if matches!( self.config.forced_login_method, Some(ForcedLoginMethod::Chatgpt) @@ -706,6 +729,10 @@ impl CodexMessageProcessor { ) -> std::result::Result { let config = self.config.as_ref(); + if self.auth_manager.is_external_auth_active() { + return Err(self.external_auth_active_error()); + } + if matches!(config.forced_login_method, Some(ForcedLoginMethod::Api)) { return Err(JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, @@ -964,6 +991,98 @@ impl CodexMessageProcessor { } } + async fn login_chatgpt_auth_tokens( + &mut self, + request_id: RequestId, + id_token: String, + access_token: String, + ) { + if matches!( + self.config.forced_login_method, + Some(ForcedLoginMethod::Api) + ) { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: "External ChatGPT auth is disabled. Use API key login instead." + .to_string(), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + + // Cancel any active login attempt to avoid persisting managed auth state. + { + let mut guard = self.active_login.lock().await; + if let Some(active) = guard.take() { + drop(active); + } + } + + let id_token_info = match parse_id_token(&id_token) { + Ok(info) => info, + Err(err) => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("invalid id token: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + }; + + if let Some(expected_workspace) = self.config.forced_chatgpt_workspace_id.as_deref() + && id_token_info.chatgpt_account_id.as_deref() != Some(expected_workspace) + { + let account_id = id_token_info.chatgpt_account_id; + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!( + "External auth must use workspace {expected_workspace}, but received {account_id:?}." + ), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + + if let Err(err) = + login_with_chatgpt_auth_tokens(&self.config.codex_home, &id_token, &access_token) + { + let error = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!("failed to set external auth: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + self.auth_manager.reload(); + + self.outgoing + .send_response(request_id, LoginAccountResponse::ChatgptAuthTokens {}) + .await; + + let payload_login_completed = AccountLoginCompletedNotification { + login_id: None, + success: true, + error: None, + }; + self.outgoing + .send_server_notification(ServerNotification::AccountLoginCompleted( + payload_login_completed, + )) + .await; + + let payload_v2 = AccountUpdatedNotification { + auth_mode: self.auth_manager.get_auth_mode(), + }; + self.outgoing + .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) + .await; + } + async fn logout_common(&mut self) -> std::result::Result, JSONRPCErrorError> { // Cancel any active login attempt. { @@ -1026,6 +1145,9 @@ impl CodexMessageProcessor { } async fn refresh_token_if_requested(&self, do_refresh: bool) { + if self.auth_manager.is_external_auth_active() { + return; + } if do_refresh && let Err(err) = self.auth_manager.refresh_token().await { tracing::warn!("failed to refresh token while getting account: {err}"); } @@ -1100,7 +1222,7 @@ impl CodexMessageProcessor { let account = match self.auth_manager.auth_cached() { Some(auth) => Some(match auth.mode { AuthMode::ApiKey => Account::ApiKey {}, - AuthMode::ChatGPT => { + AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens => { let email = auth.get_account_email(); let plan_type = auth.account_plan_type(); @@ -1159,7 +1281,7 @@ impl CodexMessageProcessor { }); }; - if auth.mode != AuthMode::ChatGPT { + if !matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) { return Err(JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, message: "chatgpt authentication required to read rate limits".to_string(), diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index ca588e59d4..5b3d39704c 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -312,7 +312,7 @@ pub async fn run_main( JSONRPCMessage::Request(r) => processor.process_request(r).await, JSONRPCMessage::Response(r) => processor.process_response(r).await, JSONRPCMessage::Notification(n) => processor.process_notification(n).await, - JSONRPCMessage::Error(e) => processor.process_error(e), + JSONRPCMessage::Error(e) => processor.process_error(e).await, } } created = thread_created_rx.recv(), if listen_for_threads => { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 95d62d3f90..ced93c3bdd 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -5,6 +5,10 @@ use crate::codex_message_processor::CodexMessageProcessor; use crate::config_api::ConfigApi; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::outgoing_message::OutgoingMessageSender; +use async_trait::async_trait; +use codex_app_server_protocol::ChatgptAuthTokensRefreshParams; +use codex_app_server_protocol::ChatgptAuthTokensRefreshReason; +use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::ConfigBatchWriteParams; @@ -19,8 +23,13 @@ use codex_app_server_protocol::JSONRPCRequest; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::ServerRequestPayload; use codex_core::AuthManager; use codex_core::ThreadManager; +use codex_core::auth::ExternalAuthRefreshContext; +use codex_core::auth::ExternalAuthRefreshReason; +use codex_core::auth::ExternalAuthRefresher; +use codex_core::auth::ExternalAuthTokens; use codex_core::config::Config; use codex_core::config_loader::LoaderOverrides; use codex_core::default_client::SetOriginatorError; @@ -31,8 +40,64 @@ use codex_feedback::CodexFeedback; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; use tokio::sync::broadcast; +use tokio::time::Duration; +use tokio::time::timeout; use toml::Value as TomlValue; +const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10); + +#[derive(Clone)] +struct ExternalAuthRefreshBridge { + outgoing: Arc, +} + +impl ExternalAuthRefreshBridge { + fn map_reason(reason: ExternalAuthRefreshReason) -> ChatgptAuthTokensRefreshReason { + match reason { + ExternalAuthRefreshReason::Unauthorized => ChatgptAuthTokensRefreshReason::Unauthorized, + } + } +} + +#[async_trait] +impl ExternalAuthRefresher for ExternalAuthRefreshBridge { + async fn refresh( + &self, + context: ExternalAuthRefreshContext, + ) -> std::io::Result { + let params = ChatgptAuthTokensRefreshParams { + reason: Self::map_reason(context.reason), + previous_account_id: context.previous_account_id, + }; + + let (request_id, rx) = self + .outgoing + .send_request_with_id(ServerRequestPayload::ChatgptAuthTokensRefresh(params)) + .await; + + let result = match timeout(EXTERNAL_AUTH_REFRESH_TIMEOUT, rx).await { + Ok(result) => result.map_err(|err| { + std::io::Error::other(format!("auth refresh request canceled: {err}")) + })?, + Err(_) => { + let _canceled = self.outgoing.cancel_request(&request_id).await; + return Err(std::io::Error::other(format!( + "auth refresh request timed out after {}s", + EXTERNAL_AUTH_REFRESH_TIMEOUT.as_secs() + ))); + } + }; + + let response: ChatgptAuthTokensRefreshResponse = + serde_json::from_value(result).map_err(std::io::Error::other)?; + + Ok(ExternalAuthTokens { + access_token: response.access_token, + id_token: response.id_token, + }) + } +} + pub(crate) struct MessageProcessor { outgoing: Arc, codex_message_processor: CodexMessageProcessor, @@ -59,6 +124,10 @@ impl MessageProcessor { false, config.cli_auth_credentials_store_mode, ); + auth_manager.set_forced_chatgpt_workspace_id(config.forced_chatgpt_workspace_id.clone()); + auth_manager.set_external_auth_refresher(Arc::new(ExternalAuthRefreshBridge { + outgoing: outgoing.clone(), + })); let thread_manager = Arc::new(ThreadManager::new( config.codex_home.clone(), auth_manager.clone(), @@ -236,8 +305,9 @@ impl MessageProcessor { } /// Handle an error object received from the peer. - pub(crate) fn process_error(&mut self, err: JSONRPCError) { + pub(crate) async fn process_error(&mut self, err: JSONRPCError) { tracing::error!("<- error: {:?}", err); + self.outgoing.notify_client_error(err.id, err.error).await; } async fn handle_config_read(&self, request_id: RequestId, params: ConfigReadParams) { diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index 7b4a599b00..be89775d86 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -39,6 +39,14 @@ impl OutgoingMessageSender { &self, request: ServerRequestPayload, ) -> oneshot::Receiver { + let (_id, rx) = self.send_request_with_id(request).await; + rx + } + + pub(crate) async fn send_request_with_id( + &self, + request: ServerRequestPayload, + ) -> (RequestId, oneshot::Receiver) { let id = RequestId::Integer(self.next_request_id.fetch_add(1, Ordering::Relaxed)); let outgoing_message_id = id.clone(); let (tx_approve, rx_approve) = oneshot::channel(); @@ -54,7 +62,7 @@ impl OutgoingMessageSender { let mut request_id_to_callback = self.request_id_to_callback.lock().await; request_id_to_callback.remove(&outgoing_message_id); } - rx_approve + (outgoing_message_id, rx_approve) } pub(crate) async fn notify_client_response(&self, id: RequestId, result: Result) { @@ -75,6 +83,30 @@ impl OutgoingMessageSender { } } + pub(crate) async fn notify_client_error(&self, id: RequestId, error: JSONRPCErrorError) { + let entry = { + let mut request_id_to_callback = self.request_id_to_callback.lock().await; + request_id_to_callback.remove_entry(&id) + }; + + match entry { + Some((id, _sender)) => { + warn!("client responded with error for {id:?}: {error:?}"); + } + None => { + warn!("could not find callback for {id:?}"); + } + } + } + + pub(crate) async fn cancel_request(&self, id: &RequestId) -> bool { + let entry = { + let mut request_id_to_callback = self.request_id_to_callback.lock().await; + request_id_to_callback.remove_entry(id) + }; + entry.is_some() + } + pub(crate) async fn send_response(&self, id: RequestId, response: T) { match serde_json::to_value(response) { Ok(result) => { diff --git a/codex-rs/app-server/tests/common/auth_fixtures.rs b/codex-rs/app-server/tests/common/auth_fixtures.rs index 9f1b62744a..b78d5b105d 100644 --- a/codex-rs/app-server/tests/common/auth_fixtures.rs +++ b/codex-rs/app-server/tests/common/auth_fixtures.rs @@ -6,6 +6,7 @@ use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use chrono::DateTime; use chrono::Utc; +use codex_app_server_protocol::AuthMode; use codex_core::auth::AuthCredentialsStoreMode; use codex_core::auth::AuthDotJson; use codex_core::auth::save_auth; @@ -158,6 +159,7 @@ pub fn write_chatgpt_auth( let last_refresh = fixture.last_refresh.unwrap_or_else(|| Some(Utc::now())); let auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(tokens), last_refresh, diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index fa160b4c41..4eeab8f950 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -29,11 +29,13 @@ use codex_app_server_protocol::GetAuthStatusParams; 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::ModelListParams; use codex_app_server_protocol::NewConversationParams; @@ -298,6 +300,20 @@ impl McpProcess { self.send_request("account/read", params).await } + /// Send an `account/login/start` JSON-RPC request with ChatGPT auth tokens. + pub async fn send_chatgpt_auth_tokens_login_request( + &mut self, + id_token: String, + access_token: String, + ) -> anyhow::Result { + let params = LoginAccountParams::ChatgptAuthTokens { + id_token, + access_token, + }; + let params = Some(serde_json::to_value(params)?); + self.send_request("account/login/start", params).await + } + /// Send a `feedback/upload` JSON-RPC request. pub async fn send_feedback_upload_request( &mut self, @@ -608,6 +624,15 @@ impl McpProcess { .await } + pub async fn send_error( + &mut self, + id: RequestId, + error: JSONRPCErrorError, + ) -> anyhow::Result<()> { + self.send_jsonrpc_message(JSONRPCMessage::Error(JSONRPCError { id, error })) + .await + } + pub async fn send_notification( &mut self, notification: ClientNotification, diff --git a/codex-rs/app-server/tests/suite/v2/account.rs b/codex-rs/app-server/tests/suite/v2/account.rs index cbbdad84c1..d3145345e0 100644 --- a/codex-rs/app-server/tests/suite/v2/account.rs +++ b/codex-rs/app-server/tests/suite/v2/account.rs @@ -4,28 +4,43 @@ use app_test_support::McpProcess; use app_test_support::to_response; use app_test_support::ChatGptAuthFixture; +use app_test_support::ChatGptIdTokenClaims; +use app_test_support::encode_id_token; use app_test_support::write_chatgpt_auth; +use app_test_support::write_models_cache; use codex_app_server_protocol::Account; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::CancelLoginAccountParams; use codex_app_server_protocol::CancelLoginAccountResponse; +use codex_app_server_protocol::CancelLoginAccountStatus; +use codex_app_server_protocol::ChatgptAuthTokensRefreshReason; +use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse; use codex_app_server_protocol::GetAccountParams; use codex_app_server_protocol::GetAccountResponse; use codex_app_server_protocol::JSONRPCError; +use codex_app_server_protocol::JSONRPCErrorError; +use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::LogoutAccountResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::ServerRequest; +use codex_app_server_protocol::TurnCompletedNotification; +use codex_app_server_protocol::TurnStatus; use codex_core::auth::AuthCredentialsStoreMode; use codex_login::login_with_api_key; use codex_protocol::account::PlanType as AccountPlanType; +use core_test_support::responses; use pretty_assertions::assert_eq; +use serde_json::json; use serial_test::serial; use std::path::Path; use std::time::Duration; use tempfile::TempDir; use tokio::time::timeout; +use wiremock::MockServer; +use wiremock::ResponseTemplate; const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); @@ -35,10 +50,14 @@ struct CreateConfigTomlParams { forced_method: Option, forced_workspace_id: Option, requires_openai_auth: Option, + base_url: Option, } fn create_config_toml(codex_home: &Path, params: CreateConfigTomlParams) -> std::io::Result<()> { let config_toml = codex_home.join("config.toml"); + let base_url = params + .base_url + .unwrap_or_else(|| "http://127.0.0.1:0/v1".to_string()); let forced_line = if let Some(method) = params.forced_method { format!("forced_login_method = \"{method}\"\n") } else { @@ -66,7 +85,7 @@ model_provider = "mock_provider" [model_providers.mock_provider] name = "Mock provider for test" -base_url = "http://127.0.0.1:0/v1" +base_url = "{base_url}" wire_api = "responses" request_max_retries = 0 stream_max_retries = 0 @@ -133,6 +152,627 @@ async fn logout_account_removes_auth_and_notifies() -> Result<()> { Ok(()) } +#[tokio::test] +async fn set_auth_token_updates_account_and_notifies() -> Result<()> { + let codex_home = TempDir::new()?; + let mock_server = MockServer::start().await; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + requires_openai_auth: Some(true), + base_url: Some(format!("{}/v1", mock_server.uri())), + ..Default::default() + }, + )?; + write_models_cache(codex_home.path())?; + + let id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("embedded@example.com") + .plan_type("pro") + .chatgpt_account_id("org-embedded"), + )?; + let access_token = "access-embedded".to_string(); + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let set_id = mcp + .send_chatgpt_auth_tokens_login_request(id_token.clone(), access_token) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let response: LoginAccountResponse = to_response(set_resp)?; + assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); + + let note = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + let parsed: ServerNotification = note.try_into()?; + let ServerNotification::AccountUpdated(payload) = parsed else { + bail!("unexpected notification: {parsed:?}"); + }; + assert_eq!(payload.auth_mode, Some(AuthMode::ChatgptAuthTokens)); + + let get_id = mcp + .send_get_account_request(GetAccountParams { + refresh_token: false, + }) + .await?; + let get_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(get_id)), + ) + .await??; + let account: GetAccountResponse = to_response(get_resp)?; + assert_eq!( + account, + GetAccountResponse { + account: Some(Account::Chatgpt { + email: "embedded@example.com".to_string(), + plan_type: AccountPlanType::Pro, + }), + requires_openai_auth: true, + } + ); + + Ok(()) +} + +#[tokio::test] +async fn account_read_refresh_token_is_noop_in_external_mode() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + requires_openai_auth: Some(true), + ..Default::default() + }, + )?; + write_models_cache(codex_home.path())?; + + let id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("embedded@example.com") + .plan_type("pro") + .chatgpt_account_id("org-embedded"), + )?; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let set_id = mcp + .send_chatgpt_auth_tokens_login_request(id_token, "access-embedded".to_string()) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let response: LoginAccountResponse = to_response(set_resp)?; + assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); + let _updated = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + + let get_id = mcp + .send_get_account_request(GetAccountParams { + refresh_token: true, + }) + .await?; + let get_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(get_id)), + ) + .await??; + let account: GetAccountResponse = to_response(get_resp)?; + assert_eq!( + account, + GetAccountResponse { + account: Some(Account::Chatgpt { + email: "embedded@example.com".to_string(), + plan_type: AccountPlanType::Pro, + }), + requires_openai_auth: true, + } + ); + + let refresh_request = timeout( + Duration::from_millis(250), + mcp.read_stream_until_request_message(), + ) + .await; + assert!( + refresh_request.is_err(), + "external mode should not emit account/chatgptAuthTokens/refresh for refreshToken=true" + ); + + Ok(()) +} + +async fn respond_to_refresh_request( + mcp: &mut McpProcess, + access_token: &str, + id_token: &str, +) -> Result<()> { + let refresh_req: ServerRequest = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::ChatgptAuthTokensRefresh { request_id, params } = refresh_req else { + bail!("expected account/chatgptAuthTokens/refresh request, got {refresh_req:?}"); + }; + assert_eq!(params.reason, ChatgptAuthTokensRefreshReason::Unauthorized); + let response = ChatgptAuthTokensRefreshResponse { + access_token: access_token.to_string(), + id_token: id_token.to_string(), + }; + mcp.send_response(request_id, serde_json::to_value(response)?) + .await?; + Ok(()) +} + +#[tokio::test] +// 401 response triggers account/chatgptAuthTokens/refresh and retries with new tokens. +async fn external_auth_refreshes_on_unauthorized() -> Result<()> { + let codex_home = TempDir::new()?; + let mock_server = MockServer::start().await; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + requires_openai_auth: Some(true), + base_url: Some(format!("{}/v1", mock_server.uri())), + ..Default::default() + }, + )?; + write_models_cache(codex_home.path())?; + + let success_sse = responses::sse(vec![ + responses::ev_response_created("resp-turn"), + responses::ev_assistant_message("msg-turn", "turn ok"), + responses::ev_completed("resp-turn"), + ]); + let unauthorized = ResponseTemplate::new(401).set_body_json(json!({ + "error": { "message": "unauthorized" } + })); + let responses_mock = responses::mount_response_sequence( + &mock_server, + vec![unauthorized, responses::sse_response(success_sse)], + ) + .await; + + let initial_id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("initial@example.com") + .plan_type("pro") + .chatgpt_account_id("org-initial"), + )?; + let refreshed_id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("refreshed@example.com") + .plan_type("pro") + .chatgpt_account_id("org-refreshed"), + )?; + let initial_access_token = "access-initial".to_string(); + let refreshed_access_token = "access-refreshed".to_string(); + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let set_id = mcp + .send_chatgpt_auth_tokens_login_request( + initial_id_token.clone(), + initial_access_token.clone(), + ) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let response: LoginAccountResponse = to_response(set_resp)?; + assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); + let _updated = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + + let thread_req = mcp + .send_thread_start_request(codex_app_server_protocol::ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let thread = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(codex_app_server_protocol::TurnStartParams { + thread_id: thread.thread.id, + input: vec![codex_app_server_protocol::UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + respond_to_refresh_request(&mut mcp, &refreshed_access_token, &refreshed_id_token).await?; + let _turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let _turn_completed = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + let requests = responses_mock.requests(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0].header("authorization"), + Some(format!("Bearer {initial_access_token}")) + ); + assert_eq!( + requests[1].header("authorization"), + Some(format!("Bearer {refreshed_access_token}")) + ); + + Ok(()) +} + +#[tokio::test] +// Client returns JSON-RPC error to refresh; turn fails. +async fn external_auth_refresh_error_fails_turn() -> Result<()> { + let codex_home = TempDir::new()?; + let mock_server = MockServer::start().await; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + requires_openai_auth: Some(true), + base_url: Some(format!("{}/v1", mock_server.uri())), + ..Default::default() + }, + )?; + write_models_cache(codex_home.path())?; + + let unauthorized = ResponseTemplate::new(401).set_body_json(json!({ + "error": { "message": "unauthorized" } + })); + let _responses_mock = + responses::mount_response_sequence(&mock_server, vec![unauthorized]).await; + + let initial_id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("initial@example.com") + .plan_type("pro") + .chatgpt_account_id("org-initial"), + )?; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let set_id = mcp + .send_chatgpt_auth_tokens_login_request(initial_id_token, "access-initial".to_string()) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let response: LoginAccountResponse = to_response(set_resp)?; + assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); + let _updated = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + + let thread_req = mcp + .send_thread_start_request(codex_app_server_protocol::ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let thread = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(codex_app_server_protocol::TurnStartParams { + thread_id: thread.thread.id.clone(), + input: vec![codex_app_server_protocol::UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + + let refresh_req: ServerRequest = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = refresh_req else { + bail!("expected account/chatgptAuthTokens/refresh request, got {refresh_req:?}"); + }; + + mcp.send_error( + request_id, + JSONRPCErrorError { + code: -32_000, + message: "refresh failed".to_string(), + data: None, + }, + ) + .await?; + + let _turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let completed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let completed: TurnCompletedNotification = serde_json::from_value( + completed_notif + .params + .expect("turn/completed params must be present"), + )?; + assert_eq!(completed.turn.status, TurnStatus::Failed); + assert!(completed.turn.error.is_some()); + + Ok(()) +} + +#[tokio::test] +// Refresh returns tokens for the wrong workspace; turn fails. +async fn external_auth_refresh_mismatched_workspace_fails_turn() -> Result<()> { + let codex_home = TempDir::new()?; + let mock_server = MockServer::start().await; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + forced_workspace_id: Some("org-expected".to_string()), + requires_openai_auth: Some(true), + base_url: Some(format!("{}/v1", mock_server.uri())), + ..Default::default() + }, + )?; + write_models_cache(codex_home.path())?; + + let unauthorized = ResponseTemplate::new(401).set_body_json(json!({ + "error": { "message": "unauthorized" } + })); + let _responses_mock = + responses::mount_response_sequence(&mock_server, vec![unauthorized]).await; + + let initial_id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("initial@example.com") + .plan_type("pro") + .chatgpt_account_id("org-expected"), + )?; + let refreshed_id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("refreshed@example.com") + .plan_type("pro") + .chatgpt_account_id("org-other"), + )?; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let set_id = mcp + .send_chatgpt_auth_tokens_login_request(initial_id_token, "access-initial".to_string()) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let response: LoginAccountResponse = to_response(set_resp)?; + assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); + let _updated = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + + let thread_req = mcp + .send_thread_start_request(codex_app_server_protocol::ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let thread = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(codex_app_server_protocol::TurnStartParams { + thread_id: thread.thread.id.clone(), + input: vec![codex_app_server_protocol::UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + + let refresh_req: ServerRequest = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = refresh_req else { + bail!("expected account/chatgptAuthTokens/refresh request, got {refresh_req:?}"); + }; + + mcp.send_response( + request_id, + serde_json::to_value(ChatgptAuthTokensRefreshResponse { + access_token: "access-refreshed".to_string(), + id_token: refreshed_id_token, + })?, + ) + .await?; + + let _turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let completed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let completed: TurnCompletedNotification = serde_json::from_value( + completed_notif + .params + .expect("turn/completed params must be present"), + )?; + assert_eq!(completed.turn.status, TurnStatus::Failed); + assert!(completed.turn.error.is_some()); + + Ok(()) +} + +#[tokio::test] +// Refresh returns a malformed id_token; turn fails. +async fn external_auth_refresh_invalid_id_token_fails_turn() -> Result<()> { + let codex_home = TempDir::new()?; + let mock_server = MockServer::start().await; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + requires_openai_auth: Some(true), + base_url: Some(format!("{}/v1", mock_server.uri())), + ..Default::default() + }, + )?; + write_models_cache(codex_home.path())?; + + let unauthorized = ResponseTemplate::new(401).set_body_json(json!({ + "error": { "message": "unauthorized" } + })); + let _responses_mock = + responses::mount_response_sequence(&mock_server, vec![unauthorized]).await; + + let initial_id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("initial@example.com") + .plan_type("pro") + .chatgpt_account_id("org-initial"), + )?; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let set_id = mcp + .send_chatgpt_auth_tokens_login_request(initial_id_token, "access-initial".to_string()) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let response: LoginAccountResponse = to_response(set_resp)?; + assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); + let _updated = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + + let thread_req = mcp + .send_thread_start_request(codex_app_server_protocol::ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let thread = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(codex_app_server_protocol::TurnStartParams { + thread_id: thread.thread.id.clone(), + input: vec![codex_app_server_protocol::UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + + let refresh_req: ServerRequest = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = refresh_req else { + bail!("expected account/chatgptAuthTokens/refresh request, got {refresh_req:?}"); + }; + + mcp.send_response( + request_id, + serde_json::to_value(ChatgptAuthTokensRefreshResponse { + access_token: "access-refreshed".to_string(), + id_token: "not-a-jwt".to_string(), + })?, + ) + .await?; + + let _turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let completed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let completed: TurnCompletedNotification = serde_json::from_value( + completed_notif + .params + .expect("turn/completed params must be present"), + )?; + assert_eq!(completed.turn.status, TurnStatus::Failed); + assert!(completed.turn.error.is_some()); + + Ok(()) +} + #[tokio::test] async fn login_account_api_key_succeeds_and_notifies() -> Result<()> { let codex_home = TempDir::new()?; @@ -304,6 +944,71 @@ async fn login_account_chatgpt_start_can_be_cancelled() -> Result<()> { Ok(()) } +#[tokio::test] +// Serialize tests that launch the login server since it binds to a fixed port. +#[serial(login_port)] +async fn set_auth_token_cancels_active_chatgpt_login() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), CreateConfigTomlParams::default())?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + // Initiate the ChatGPT login flow + let request_id = mcp.send_login_account_chatgpt_request().await?; + let resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + + let login: LoginAccountResponse = to_response(resp)?; + let LoginAccountResponse::Chatgpt { login_id, .. } = login else { + bail!("unexpected login response: {login:?}"); + }; + + let id_token = encode_id_token( + &ChatGptIdTokenClaims::new() + .email("embedded@example.com") + .plan_type("pro") + .chatgpt_account_id("org-embedded"), + )?; + // Set an external auth token instead of completing the ChatGPT login flow. + // This should cancel the active login attempt. + let set_id = mcp + .send_chatgpt_auth_tokens_login_request(id_token, "access-embedded".to_string()) + .await?; + let set_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_id)), + ) + .await??; + let response: LoginAccountResponse = to_response(set_resp)?; + assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); + let _updated = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + + // Verify that the active login attempt was cancelled. + // We check this by trying to cancel it and expecting a not found error. + let cancel_id = mcp + .send_cancel_login_account_request(CancelLoginAccountParams { + login_id: login_id.clone(), + }) + .await?; + let cancel_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(cancel_id)), + ) + .await??; + let cancel: CancelLoginAccountResponse = to_response(cancel_resp)?; + assert_eq!(cancel.status, CancelLoginAccountStatus::NotFound); + + Ok(()) +} + #[tokio::test] // Serialize tests that launch the login server since it binds to a fixed port. #[serial(login_port)] diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index 45ee459697..0f4e4eb39f 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -240,6 +240,10 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! { eprintln!("Logged in using ChatGPT"); std::process::exit(0); } + AuthMode::ChatgptAuthTokens => { + eprintln!("Logged in using ChatGPT (external tokens)"); + std::process::exit(0); + } }, Ok(None) => { eprintln!("Not logged in"); diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index fe27f7e24e..cdd2717fd4 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -111,6 +111,13 @@ "auto" ], "type": "string" + }, + { + "description": "Store credentials in memory only for the current process.", + "enum": [ + "ephemeral" + ], + "type": "string" } ] }, diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index b746309270..d6cfec5506 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -1,5 +1,6 @@ mod storage; +use async_trait::async_trait; use chrono::Utc; use reqwest::StatusCode; use serde::Deserialize; @@ -23,6 +24,7 @@ use crate::auth::storage::create_auth_storage; use crate::config::Config; use crate::error::RefreshTokenFailedError; use crate::error::RefreshTokenFailedReason; +use crate::token_data::IdTokenInfo; use crate::token_data::KnownPlan as InternalKnownPlan; use crate::token_data::PlanType as InternalPlanType; use crate::token_data::TokenData; @@ -68,6 +70,31 @@ pub enum RefreshTokenError { Transient(#[from] std::io::Error), } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalAuthTokens { + pub access_token: String, + pub id_token: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExternalAuthRefreshReason { + Unauthorized, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalAuthRefreshContext { + pub reason: ExternalAuthRefreshReason, + pub previous_account_id: Option, +} + +#[async_trait] +pub trait ExternalAuthRefresher: Send + Sync { + async fn refresh( + &self, + context: ExternalAuthRefreshContext, + ) -> std::io::Result; +} + impl RefreshTokenError { pub fn failed_reason(&self) -> Option { match self { @@ -110,9 +137,9 @@ impl CodexAuth { pub fn get_token(&self) -> Result { match self.mode { AuthMode::ApiKey => Ok(self.api_key.clone().unwrap_or_default()), - AuthMode::ChatGPT => { - let id_token = self.get_token_data()?.access_token; - Ok(id_token) + AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens => { + let access_token = self.get_token_data()?.access_token; + Ok(access_token) } } } @@ -160,6 +187,7 @@ impl CodexAuth { /// Consider this private to integration tests. pub fn create_dummy_chatgpt_auth_for_testing() -> Self { let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(TokenData { id_token: Default::default(), @@ -229,6 +257,7 @@ pub fn login_with_api_key( auth_credentials_store_mode: AuthCredentialsStoreMode, ) -> std::io::Result<()> { let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some(api_key.to_string()), tokens: None, last_refresh: None, @@ -236,6 +265,20 @@ pub fn login_with_api_key( save_auth(codex_home, &auth_dot_json, auth_credentials_store_mode) } +/// Writes an in-memory auth payload for externally managed ChatGPT tokens. +pub fn login_with_chatgpt_auth_tokens( + codex_home: &Path, + id_token: &str, + access_token: &str, +) -> std::io::Result<()> { + let auth_dot_json = AuthDotJson::from_external_token_strings(id_token, access_token)?; + save_auth( + codex_home, + &auth_dot_json, + AuthCredentialsStoreMode::Ephemeral, + ) +} + /// Persist the provided auth payload using the specified backend. pub fn save_auth( codex_home: &Path, @@ -272,8 +315,8 @@ pub fn enforce_login_restrictions(config: &Config) -> std::io::Result<()> { if let Some(required_method) = config.forced_login_method { let method_violation = match (required_method, auth.mode) { (ForcedLoginMethod::Api, AuthMode::ApiKey) => None, - (ForcedLoginMethod::Chatgpt, AuthMode::ChatGPT) => None, - (ForcedLoginMethod::Api, AuthMode::ChatGPT) => Some( + (ForcedLoginMethod::Chatgpt, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) => None, + (ForcedLoginMethod::Api, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) => Some( "API key login is required, but ChatGPT is currently being used. Logging out." .to_string(), ), @@ -293,7 +336,7 @@ pub fn enforce_login_restrictions(config: &Config) -> std::io::Result<()> { } if let Some(expected_account_id) = config.forced_chatgpt_workspace_id.as_deref() { - if auth.mode != AuthMode::ChatGPT { + if !matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) { return Ok(()); } @@ -337,12 +380,26 @@ fn logout_with_message( message: String, auth_credentials_store_mode: AuthCredentialsStoreMode, ) -> std::io::Result<()> { - match logout(codex_home, auth_credentials_store_mode) { - Ok(_) => Err(std::io::Error::other(message)), - Err(err) => Err(std::io::Error::other(format!( - "{message}. Failed to remove auth.json: {err}" - ))), + // External auth tokens live in the ephemeral store, but persistent auth may still exist + // from earlier logins. Clear both so a forced logout truly removes all active auth. + let removal_result = logout_all_stores(codex_home, auth_credentials_store_mode); + let error_message = match removal_result { + Ok(_) => message, + Err(err) => format!("{message}. Failed to remove auth.json: {err}"), + }; + Err(std::io::Error::other(error_message)) +} + +fn logout_all_stores( + codex_home: &Path, + auth_credentials_store_mode: AuthCredentialsStoreMode, +) -> std::io::Result { + if auth_credentials_store_mode == AuthCredentialsStoreMode::Ephemeral { + return logout(codex_home, AuthCredentialsStoreMode::Ephemeral); } + let removed_ephemeral = logout(codex_home, AuthCredentialsStoreMode::Ephemeral)?; + let removed_managed = logout(codex_home, auth_credentials_store_mode)?; + Ok(removed_ephemeral || removed_managed) } fn load_auth( @@ -350,6 +407,12 @@ fn load_auth( enable_codex_api_key_env: bool, auth_credentials_store_mode: AuthCredentialsStoreMode, ) -> std::io::Result> { + let build_auth = |auth_dot_json: AuthDotJson, storage_mode| { + let client = crate::default_client::create_client(); + CodexAuth::from_auth_dot_json(codex_home, auth_dot_json, storage_mode, client) + }; + + // API key via env var takes precedence over any other auth method. if enable_codex_api_key_env && let Some(api_key) = read_codex_api_key_from_env() { let client = crate::default_client::create_client(); return Ok(Some(CodexAuth::from_api_key_with_client( @@ -358,39 +421,34 @@ fn load_auth( ))); } - let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); + // External ChatGPT auth tokens live in the in-memory (ephemeral) store. Always check this + // first so external auth takes precedence over any persisted credentials. + let ephemeral_storage = create_auth_storage( + codex_home.to_path_buf(), + AuthCredentialsStoreMode::Ephemeral, + ); + if let Some(auth_dot_json) = ephemeral_storage.load()? { + let auth = build_auth(auth_dot_json, AuthCredentialsStoreMode::Ephemeral)?; + return Ok(Some(auth)); + } - let client = crate::default_client::create_client(); + // If the caller explicitly requested ephemeral auth, there is no persisted fallback. + if auth_credentials_store_mode == AuthCredentialsStoreMode::Ephemeral { + return Ok(None); + } + + // Fall back to the configured persistent store (file/keyring/auto) for managed auth. + let storage = create_auth_storage(codex_home.to_path_buf(), auth_credentials_store_mode); let auth_dot_json = match storage.load()? { Some(auth) => auth, None => return Ok(None), }; - let AuthDotJson { - openai_api_key: auth_json_api_key, - tokens, - last_refresh, - } = auth_dot_json; - - // Prefer AuthMode.ApiKey if it's set in the auth.json. - if let Some(api_key) = &auth_json_api_key { - return Ok(Some(CodexAuth::from_api_key_with_client(api_key, client))); - } - - Ok(Some(CodexAuth { - api_key: None, - mode: AuthMode::ChatGPT, - storage: storage.clone(), - auth_dot_json: Arc::new(Mutex::new(Some(AuthDotJson { - openai_api_key: None, - tokens, - last_refresh, - }))), - client, - })) + let auth = build_auth(auth_dot_json, auth_credentials_store_mode)?; + Ok(Some(auth)) } -async fn update_tokens( +fn update_tokens( storage: &Arc, id_token: Option, access_token: Option, @@ -537,17 +595,108 @@ fn refresh_token_endpoint() -> String { .unwrap_or_else(|_| REFRESH_TOKEN_URL.to_string()) } +impl AuthDotJson { + fn from_external_tokens(external: &ExternalAuthTokens, id_token: IdTokenInfo) -> Self { + let account_id = id_token.chatgpt_account_id.clone(); + let tokens = TokenData { + id_token, + access_token: external.access_token.clone(), + refresh_token: String::new(), + account_id, + }; + + Self { + auth_mode: Some(AuthMode::ChatgptAuthTokens), + openai_api_key: None, + tokens: Some(tokens), + last_refresh: Some(Utc::now()), + } + } + + fn from_external_token_strings(id_token: &str, access_token: &str) -> std::io::Result { + let id_token_info = parse_id_token(id_token).map_err(std::io::Error::other)?; + let external = ExternalAuthTokens { + access_token: access_token.to_string(), + id_token: id_token.to_string(), + }; + Ok(Self::from_external_tokens(&external, id_token_info)) + } + + fn resolved_mode(&self) -> AuthMode { + if let Some(mode) = self.auth_mode { + return mode; + } + if self.openai_api_key.is_some() { + return AuthMode::ApiKey; + } + AuthMode::ChatGPT + } + + fn storage_mode( + &self, + auth_credentials_store_mode: AuthCredentialsStoreMode, + ) -> AuthCredentialsStoreMode { + if self.resolved_mode() == AuthMode::ChatgptAuthTokens { + AuthCredentialsStoreMode::Ephemeral + } else { + auth_credentials_store_mode + } + } +} + +impl CodexAuth { + fn from_auth_dot_json( + codex_home: &Path, + auth_dot_json: AuthDotJson, + auth_credentials_store_mode: AuthCredentialsStoreMode, + client: CodexHttpClient, + ) -> std::io::Result { + let auth_mode = auth_dot_json.resolved_mode(); + if auth_mode == AuthMode::ApiKey { + let Some(api_key) = auth_dot_json.openai_api_key.as_deref() else { + return Err(std::io::Error::other("API key auth is missing a key.")); + }; + return Ok(CodexAuth::from_api_key_with_client(api_key, client)); + } + + let storage_mode = auth_dot_json.storage_mode(auth_credentials_store_mode); + let storage = create_auth_storage(codex_home.to_path_buf(), storage_mode); + Ok(Self { + api_key: None, + mode: auth_mode, + storage, + auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), + client, + }) + } +} + use std::sync::RwLock; /// Internal cached auth state. -#[derive(Clone, Debug)] +#[derive(Clone)] struct CachedAuth { auth: Option, + /// Callback used to refresh external auth by asking the parent app for new tokens. + external_refresher: Option>, +} + +impl Debug for CachedAuth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CachedAuth") + .field("auth_mode", &self.auth.as_ref().map(|auth| auth.mode)) + .field( + "external_refresher", + &self.external_refresher.as_ref().map(|_| "present"), + ) + .finish() + } } enum UnauthorizedRecoveryStep { Reload, RefreshToken, + ExternalRefresh, Done, } @@ -556,38 +705,63 @@ enum ReloadOutcome { Skipped, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum UnauthorizedRecoveryMode { + Managed, + External, +} + // UnauthorizedRecovery is a state machine that handles an attempt to refresh the authentication when requests // to API fail with 401 status code. // The client calls next() every time it encounters a 401 error, one time per retry. // For API key based authentication, we don't do anything and let the error bubble to the user. +// // For ChatGPT based authentication, we: // 1. Attempt to reload the auth data from disk. We only reload if the account id matches the one the current process is running as. // 2. Attempt to refresh the token using OAuth token refresh flow. // If after both steps the server still responds with 401 we let the error bubble to the user. +// +// For external ChatGPT auth tokens (chatgptAuthTokens), UnauthorizedRecovery does not touch disk or refresh +// tokens locally. Instead it calls the ExternalAuthRefresher (account/chatgptAuthTokens/refresh) to ask the +// parent app for new tokens, stores them in the ephemeral auth store, and retries once. pub struct UnauthorizedRecovery { manager: Arc, step: UnauthorizedRecoveryStep, expected_account_id: Option, + mode: UnauthorizedRecoveryMode, } impl UnauthorizedRecovery { fn new(manager: Arc) -> Self { - let expected_account_id = manager - .auth_cached() - .as_ref() - .and_then(CodexAuth::get_account_id); + let cached_auth = manager.auth_cached(); + let expected_account_id = cached_auth.as_ref().and_then(CodexAuth::get_account_id); + let mode = match cached_auth { + Some(auth) if auth.mode == AuthMode::ChatgptAuthTokens => { + UnauthorizedRecoveryMode::External + } + _ => UnauthorizedRecoveryMode::Managed, + }; + let step = match mode { + UnauthorizedRecoveryMode::Managed => UnauthorizedRecoveryStep::Reload, + UnauthorizedRecoveryMode::External => UnauthorizedRecoveryStep::ExternalRefresh, + }; Self { manager, - step: UnauthorizedRecoveryStep::Reload, + step, expected_account_id, + mode, } } pub fn has_next(&self) -> bool { - if !self - .manager - .auth_cached() - .is_some_and(|auth| auth.mode == AuthMode::ChatGPT) + if !self.manager.auth_cached().is_some_and(|auth| { + matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + }) { + return false; + } + + if self.mode == UnauthorizedRecoveryMode::External + && !self.manager.has_external_auth_refresher() { return false; } @@ -622,6 +796,12 @@ impl UnauthorizedRecovery { self.manager.refresh_token().await?; self.step = UnauthorizedRecoveryStep::Done; } + UnauthorizedRecoveryStep::ExternalRefresh => { + self.manager + .refresh_external_auth(ExternalAuthRefreshReason::Unauthorized) + .await?; + self.step = UnauthorizedRecoveryStep::Done; + } UnauthorizedRecoveryStep::Done => {} } Ok(()) @@ -642,6 +822,7 @@ pub struct AuthManager { inner: RwLock, enable_codex_api_key_env: bool, auth_credentials_store_mode: AuthCredentialsStoreMode, + forced_chatgpt_workspace_id: RwLock>, } impl AuthManager { @@ -654,7 +835,7 @@ impl AuthManager { enable_codex_api_key_env: bool, auth_credentials_store_mode: AuthCredentialsStoreMode, ) -> Self { - let auth = load_auth( + let managed_auth = load_auth( &codex_home, enable_codex_api_key_env, auth_credentials_store_mode, @@ -663,34 +844,46 @@ impl AuthManager { .flatten(); Self { codex_home, - inner: RwLock::new(CachedAuth { auth }), + inner: RwLock::new(CachedAuth { + auth: managed_auth, + external_refresher: None, + }), enable_codex_api_key_env, auth_credentials_store_mode, + forced_chatgpt_workspace_id: RwLock::new(None), } } #[cfg(any(test, feature = "test-support"))] /// Create an AuthManager with a specific CodexAuth, for testing only. pub fn from_auth_for_testing(auth: CodexAuth) -> Arc { - let cached = CachedAuth { auth: Some(auth) }; + let cached = CachedAuth { + auth: Some(auth), + external_refresher: None, + }; Arc::new(Self { codex_home: PathBuf::from("non-existent"), inner: RwLock::new(cached), enable_codex_api_key_env: false, auth_credentials_store_mode: AuthCredentialsStoreMode::File, + forced_chatgpt_workspace_id: RwLock::new(None), }) } #[cfg(any(test, feature = "test-support"))] /// Create an AuthManager with a specific CodexAuth and codex home, for testing only. pub fn from_auth_for_testing_with_home(auth: CodexAuth, codex_home: PathBuf) -> Arc { - let cached = CachedAuth { auth: Some(auth) }; + let cached = CachedAuth { + auth: Some(auth), + external_refresher: None, + }; Arc::new(Self { codex_home, inner: RwLock::new(cached), enable_codex_api_key_env: false, auth_credentials_store_mode: AuthCredentialsStoreMode::File, + forced_chatgpt_workspace_id: RwLock::new(None), }) } @@ -715,7 +908,7 @@ impl AuthManager { pub fn reload(&self) -> bool { tracing::info!("Reloading auth"); let new_auth = self.load_auth_from_storage(); - self.set_auth(new_auth) + self.set_cached_auth(new_auth) } fn reload_if_account_id_matches(&self, expected_account_id: Option<&str>) -> ReloadOutcome { @@ -739,11 +932,11 @@ impl AuthManager { } tracing::info!("Reloading auth for account {expected_account_id}"); - self.set_auth(new_auth); + self.set_cached_auth(new_auth); ReloadOutcome::Reloaded } - fn auths_equal(a: &Option, b: &Option) -> bool { + fn auths_equal(a: Option<&CodexAuth>, b: Option<&CodexAuth>) -> bool { match (a, b) { (None, None) => true, (Some(a), Some(b)) => a == b, @@ -761,9 +954,10 @@ impl AuthManager { .flatten() } - fn set_auth(&self, new_auth: Option) -> bool { + fn set_cached_auth(&self, new_auth: Option) -> bool { if let Ok(mut guard) = self.inner.write() { - let changed = !AuthManager::auths_equal(&guard.auth, &new_auth); + let previous = guard.auth.as_ref(); + let changed = !AuthManager::auths_equal(previous, new_auth.as_ref()); tracing::info!("Reloaded auth, changed: {changed}"); guard.auth = new_auth; changed @@ -772,6 +966,38 @@ impl AuthManager { } } + pub fn set_external_auth_refresher(&self, refresher: Arc) { + if let Ok(mut guard) = self.inner.write() { + guard.external_refresher = Some(refresher); + } + } + + pub fn set_forced_chatgpt_workspace_id(&self, workspace_id: Option) { + if let Ok(mut guard) = self.forced_chatgpt_workspace_id.write() { + *guard = workspace_id; + } + } + + pub fn forced_chatgpt_workspace_id(&self) -> Option { + self.forced_chatgpt_workspace_id + .read() + .ok() + .and_then(|guard| guard.clone()) + } + + pub fn has_external_auth_refresher(&self) -> bool { + self.inner + .read() + .ok() + .map(|guard| guard.external_refresher.is_some()) + .unwrap_or(false) + } + + pub fn is_external_auth_active(&self) -> bool { + self.auth_cached() + .is_some_and(|auth| auth.mode == AuthMode::ChatgptAuthTokens) + } + /// Convenience constructor returning an `Arc` wrapper. pub fn shared( codex_home: PathBuf, @@ -799,6 +1025,11 @@ impl AuthManager { Some(auth) => auth, None => return Ok(()), }; + if auth.mode == AuthMode::ChatgptAuthTokens { + return self + .refresh_external_auth(ExternalAuthRefreshReason::Unauthorized) + .await; + } let token_data = auth.get_current_token_data().ok_or_else(|| { RefreshTokenError::Transient(std::io::Error::other("Token data is not available.")) })?; @@ -813,7 +1044,7 @@ impl AuthManager { /// reloads the in‑memory auth cache so callers immediately observe the /// unauthenticated state. pub fn logout(&self) -> std::io::Result { - let removed = super::auth::logout(&self.codex_home, self.auth_credentials_store_mode)?; + let removed = logout_all_stores(&self.codex_home, self.auth_credentials_store_mode)?; // Always reload to clear any cached auth (even if file absent). self.reload(); Ok(removed) @@ -848,6 +1079,59 @@ impl AuthManager { Ok(true) } + async fn refresh_external_auth( + &self, + reason: ExternalAuthRefreshReason, + ) -> Result<(), RefreshTokenError> { + let forced_chatgpt_workspace_id = self.forced_chatgpt_workspace_id(); + let refresher = match self.inner.read() { + Ok(guard) => guard.external_refresher.clone(), + Err(_) => { + return Err(RefreshTokenError::Transient(std::io::Error::other( + "failed to read external auth state", + ))); + } + }; + + let Some(refresher) = refresher else { + return Err(RefreshTokenError::Transient(std::io::Error::other( + "external auth refresher is not configured", + ))); + }; + + let previous_account_id = self + .auth_cached() + .as_ref() + .and_then(CodexAuth::get_account_id); + let context = ExternalAuthRefreshContext { + reason, + previous_account_id, + }; + + let refreshed = refresher.refresh(context).await?; + let id_token = parse_id_token(&refreshed.id_token) + .map_err(|err| RefreshTokenError::Transient(std::io::Error::other(err)))?; + if let Some(expected_workspace_id) = forced_chatgpt_workspace_id.as_deref() { + let actual_workspace_id = id_token.chatgpt_account_id.as_deref(); + if actual_workspace_id != Some(expected_workspace_id) { + return Err(RefreshTokenError::Transient(std::io::Error::other( + format!( + "external auth refresh returned workspace {actual_workspace_id:?}, expected {expected_workspace_id:?}", + ), + ))); + } + } + let auth_dot_json = AuthDotJson::from_external_tokens(&refreshed, id_token); + save_auth( + &self.codex_home, + &auth_dot_json, + AuthCredentialsStoreMode::Ephemeral, + ) + .map_err(RefreshTokenError::Transient)?; + self.reload(); + Ok(()) + } + async fn refresh_tokens( &self, auth: &CodexAuth, @@ -861,7 +1145,6 @@ impl AuthManager { refresh_response.access_token, refresh_response.refresh_token, ) - .await .map_err(RefreshTokenError::from)?; Ok(()) @@ -910,7 +1193,6 @@ mod tests { Some("new-access-token".to_string()), Some("new-refresh-token".to_string()), ) - .await .expect("update_tokens should succeed"); let tokens = updated.tokens.expect("tokens should exist"); @@ -991,6 +1273,7 @@ mod tests { assert_eq!( &AuthDotJson { + auth_mode: None, openai_api_key: None, tokens: Some(TokenData { id_token: IdTokenInfo { @@ -1034,6 +1317,7 @@ mod tests { fn logout_removes_auth_file() -> Result<(), std::io::Error> { let dir = tempdir()?; let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some("sk-test-key".to_string()), tokens: None, last_refresh: None, diff --git a/codex-rs/core/src/auth/storage.rs b/codex-rs/core/src/auth/storage.rs index 48b67aca05..b4f4bb8e7e 100644 --- a/codex-rs/core/src/auth/storage.rs +++ b/codex-rs/core/src/auth/storage.rs @@ -5,6 +5,7 @@ use serde::Deserialize; use serde::Serialize; use sha2::Digest; use sha2::Sha256; +use std::collections::HashMap; use std::fmt::Debug; use std::fs::File; use std::fs::OpenOptions; @@ -15,11 +16,14 @@ use std::os::unix::fs::OpenOptionsExt; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use std::sync::Mutex; use tracing::warn; use crate::token_data::TokenData; +use codex_app_server_protocol::AuthMode; use codex_keyring_store::DefaultKeyringStore; use codex_keyring_store::KeyringStore; +use once_cell::sync::Lazy; /// Determine where Codex should store CLI auth credentials. #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] @@ -32,11 +36,16 @@ pub enum AuthCredentialsStoreMode { Keyring, /// Use keyring when available; otherwise, fall back to a file in CODEX_HOME. Auto, + /// Store credentials in memory only for the current process. + Ephemeral, } /// Expected structure for $CODEX_HOME/auth.json. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)] pub struct AuthDotJson { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth_mode: Option, + #[serde(rename = "OPENAI_API_KEY")] pub openai_api_key: Option, @@ -76,8 +85,8 @@ impl FileAuthStorage { Self { codex_home } } - /// Attempt to read and refresh the `auth.json` file in the given `CODEX_HOME` directory. - /// Returns the full AuthDotJson structure after refreshing if necessary. + /// Attempt to read and parse the `auth.json` file in the given `CODEX_HOME` directory. + /// Returns the full AuthDotJson structure. pub(super) fn try_read_auth_json(&self, auth_file: &Path) -> std::io::Result { let mut file = File::open(auth_file)?; let mut contents = String::new(); @@ -256,6 +265,49 @@ impl AuthStorageBackend for AutoAuthStorage { } } +// A global in-memory store for mapping codex_home -> AuthDotJson. +static EPHEMERAL_AUTH_STORE: Lazy>> = + Lazy::new(|| Mutex::new(HashMap::new())); + +#[derive(Clone, Debug)] +struct EphemeralAuthStorage { + codex_home: PathBuf, +} + +impl EphemeralAuthStorage { + fn new(codex_home: PathBuf) -> Self { + Self { codex_home } + } + + fn with_store(&self, action: F) -> std::io::Result + where + F: FnOnce(&mut HashMap, String) -> std::io::Result, + { + let key = compute_store_key(&self.codex_home)?; + let mut store = EPHEMERAL_AUTH_STORE + .lock() + .map_err(|_| std::io::Error::other("failed to lock ephemeral auth storage"))?; + action(&mut store, key) + } +} + +impl AuthStorageBackend for EphemeralAuthStorage { + fn load(&self) -> std::io::Result> { + self.with_store(|store, key| Ok(store.get(&key).cloned())) + } + + fn save(&self, auth: &AuthDotJson) -> std::io::Result<()> { + self.with_store(|store, key| { + store.insert(key, auth.clone()); + Ok(()) + }) + } + + fn delete(&self) -> std::io::Result { + self.with_store(|store, key| Ok(store.remove(&key).is_some())) + } +} + pub(super) fn create_auth_storage( codex_home: PathBuf, mode: AuthCredentialsStoreMode, @@ -275,6 +327,7 @@ fn create_auth_storage_with_keyring_store( Arc::new(KeyringAuthStorage::new(codex_home, keyring_store)) } AuthCredentialsStoreMode::Auto => Arc::new(AutoAuthStorage::new(codex_home, keyring_store)), + AuthCredentialsStoreMode::Ephemeral => Arc::new(EphemeralAuthStorage::new(codex_home)), } } @@ -296,6 +349,7 @@ mod tests { let codex_home = tempdir()?; let storage = FileAuthStorage::new(codex_home.path().to_path_buf()); let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some("test-key".to_string()), tokens: None, last_refresh: Some(Utc::now()), @@ -315,6 +369,7 @@ mod tests { let codex_home = tempdir()?; let storage = FileAuthStorage::new(codex_home.path().to_path_buf()); let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some("test-key".to_string()), tokens: None, last_refresh: Some(Utc::now()), @@ -336,6 +391,7 @@ mod tests { fn file_storage_delete_removes_auth_file() -> anyhow::Result<()> { let dir = tempdir()?; let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some("sk-test-key".to_string()), tokens: None, last_refresh: None, @@ -350,6 +406,32 @@ mod tests { Ok(()) } + #[test] + fn ephemeral_storage_save_load_delete_is_in_memory_only() -> anyhow::Result<()> { + let dir = tempdir()?; + let storage = create_auth_storage( + dir.path().to_path_buf(), + AuthCredentialsStoreMode::Ephemeral, + ); + let auth_dot_json = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), + openai_api_key: Some("sk-ephemeral".to_string()), + tokens: None, + last_refresh: Some(Utc::now()), + }; + + storage.save(&auth_dot_json)?; + let loaded = storage.load()?; + assert_eq!(Some(auth_dot_json), loaded); + + let removed = storage.delete()?; + assert!(removed); + let loaded = storage.load()?; + assert_eq!(None, loaded); + assert!(!get_auth_file(dir.path()).exists()); + Ok(()) + } + fn seed_keyring_and_fallback_auth_file_for_delete( mock_keyring: &MockKeyringStore, codex_home: &Path, @@ -425,6 +507,7 @@ mod tests { fn auth_with_prefix(prefix: &str) -> AuthDotJson { AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some(format!("{prefix}-api-key")), tokens: Some(TokenData { id_token: id_token_with_prefix(prefix), @@ -445,6 +528,7 @@ mod tests { Arc::new(mock_keyring.clone()), ); let expected = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some("sk-test".to_string()), tokens: None, last_refresh: None, @@ -481,6 +565,7 @@ mod tests { let auth_file = get_auth_file(codex_home.path()); std::fs::write(&auth_file, "stale")?; let auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(TokenData { id_token: Default::default(), diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 4cb37a46d4..0f05f58c47 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -469,7 +469,9 @@ impl ModelClientSession { .config .features .enabled(Feature::EnableRequestCompression) - && auth.is_some_and(|auth| auth.mode == AuthMode::ChatGPT) + && auth.is_some_and(|auth| { + matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + }) && self.state.provider.is_openai() { Compression::Zstd diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index 4f69f02d91..0f3551480c 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -137,7 +137,10 @@ impl ModelProviderInfo { &self, auth_mode: Option, ) -> crate::error::Result { - let default_base_url = if matches!(auth_mode, Some(AuthMode::ChatGPT)) { + let default_base_url = if matches!( + auth_mode, + Some(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + ) { "https://chatgpt.com/backend-api/codex" } else { "https://api.openai.com/v1" diff --git a/codex-rs/core/src/models_manager/manager.rs b/codex-rs/core/src/models_manager/manager.rs index 77fb44cd5d..c993032ea9 100644 --- a/codex-rs/core/src/models_manager/manager.rs +++ b/codex-rs/core/src/models_manager/manager.rs @@ -204,7 +204,8 @@ impl ModelsManager { let _timer = codex_otel::start_global_timer("codex.remote_models.fetch_update.duration_ms", &[]); let auth = self.auth_manager.auth().await; - let api_provider = self.provider.to_api_provider(Some(AuthMode::ChatGPT))?; + let auth_mode = self.auth_manager.get_auth_mode(); + let api_provider = self.provider.to_api_provider(auth_mode)?; let api_auth = auth_provider_from_auth(auth.clone(), &self.provider)?; let transport = ReqwestTransport::new(build_reqwest_client()); let client = ModelsClient::new(transport, api_provider, api_auth); @@ -271,7 +272,10 @@ impl ModelsManager { let remote_presets: Vec = remote_models.into_iter().map(Into::into).collect(); let existing_presets = self.local_models.clone(); let mut merged_presets = ModelPreset::merge(remote_presets, existing_presets); - let chatgpt_mode = self.auth_manager.get_auth_mode() == Some(AuthMode::ChatGPT); + let chatgpt_mode = matches!( + self.auth_manager.get_auth_mode(), + Some(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + ); merged_presets = ModelPreset::filter_by_auth(merged_presets, chatgpt_mode); for preset in &mut merged_presets { diff --git a/codex-rs/core/src/token_data.rs b/codex-rs/core/src/token_data.rs index 744cc73d9b..2010af16f7 100644 --- a/codex-rs/core/src/token_data.rs +++ b/codex-rs/core/src/token_data.rs @@ -76,10 +76,18 @@ pub(crate) enum KnownPlan { struct IdClaims { #[serde(default)] email: Option, + #[serde(rename = "https://api.openai.com/profile", default)] + profile: Option, #[serde(rename = "https://api.openai.com/auth", default)] auth: Option, } +#[derive(Deserialize)] +struct ProfileClaims { + #[serde(default)] + email: Option, +} + #[derive(Deserialize)] struct AuthClaims { #[serde(default)] @@ -112,17 +120,20 @@ pub fn parse_id_token(id_token: &str) -> Result { let payload_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload_b64)?; let claims: IdClaims = serde_json::from_slice(&payload_bytes)?; + let email = claims + .email + .or_else(|| claims.profile.and_then(|profile| profile.email)); match claims.auth { Some(auth) => Ok(IdTokenInfo { - email: claims.email, + email, raw_jwt: id_token.to_string(), chatgpt_plan_type: auth.chatgpt_plan_type, chatgpt_user_id: auth.chatgpt_user_id.or(auth.user_id), chatgpt_account_id: auth.chatgpt_account_id, }), None => Ok(IdTokenInfo { - email: claims.email, + email, raw_jwt: id_token.to_string(), chatgpt_plan_type: None, chatgpt_user_id: None, diff --git a/codex-rs/core/tests/suite/auth_refresh.rs b/codex-rs/core/tests/suite/auth_refresh.rs index d0b8d27382..4ef3b82eec 100644 --- a/codex-rs/core/tests/suite/auth_refresh.rs +++ b/codex-rs/core/tests/suite/auth_refresh.rs @@ -3,6 +3,7 @@ use anyhow::Result; use base64::Engine; use chrono::Duration; use chrono::Utc; +use codex_app_server_protocol::AuthMode; use codex_core::AuthManager; use codex_core::auth::AuthCredentialsStoreMode; use codex_core::auth::AuthDotJson; @@ -50,6 +51,7 @@ async fn refresh_token_succeeds_updates_storage() -> Result<()> { let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -111,6 +113,7 @@ async fn returns_fresh_tokens_as_is() -> Result<()> { let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -156,6 +159,7 @@ async fn refreshes_token_when_last_refresh_is_stale() -> Result<()> { let stale_refresh = Utc::now() - Duration::days(9); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(stale_refresh), @@ -214,6 +218,7 @@ async fn refresh_token_returns_permanent_error_for_expired_refresh_token() -> Re let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -263,6 +268,7 @@ async fn refresh_token_returns_transient_error_on_server_failure() -> Result<()> let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -314,6 +320,7 @@ async fn unauthorized_recovery_reloads_then_refreshes_tokens() -> Result<()> { let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -322,6 +329,7 @@ async fn unauthorized_recovery_reloads_then_refreshes_tokens() -> Result<()> { let disk_tokens = build_tokens("disk-access-token", "disk-refresh-token"); let disk_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(disk_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -404,6 +412,7 @@ async fn unauthorized_recovery_skips_reload_on_account_mismatch() -> Result<()> let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -418,6 +427,7 @@ async fn unauthorized_recovery_skips_reload_on_account_mismatch() -> Result<()> ..disk_tokens.clone() }; let disk_auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: None, tokens: Some(disk_tokens), last_refresh: Some(initial_last_refresh), @@ -481,6 +491,7 @@ async fn unauthorized_recovery_requires_chatgpt_auth() -> Result<()> { let server = MockServer::start().await; let ctx = RefreshTokenTestContext::new(&server)?; let auth = AuthDotJson { + auth_mode: Some(AuthMode::ApiKey), openai_api_key: Some("sk-test".to_string()), tokens: None, last_refresh: None, diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 999c19072e..5272c84eaa 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -14,6 +14,7 @@ use crate::pkce::PkceCodes; use crate::pkce::generate_pkce; use base64::Engine; use chrono::Utc; +use codex_app_server_protocol::AuthMode; use codex_core::auth::AuthCredentialsStoreMode; use codex_core::auth::AuthDotJson; use codex_core::auth::save_auth; @@ -559,6 +560,7 @@ pub(crate) async fn persist_tokens_async( tokens.account_id = Some(acc.to_string()); } let auth = AuthDotJson { + auth_mode: Some(AuthMode::ChatGPT), openai_api_key: api_key, tokens: Some(tokens), last_refresh: Some(Utc::now()), diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index c132130515..61006d80c8 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -3457,7 +3457,10 @@ impl ChatWidget { fn prefetch_rate_limits(&mut self) { self.stop_rate_limit_poller(); - if self.auth_manager.auth_cached().map(|auth| auth.mode) != Some(AuthMode::ChatGPT) { + if !matches!( + self.auth_manager.auth_cached().map(|auth| auth.mode), + Some(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + ) { return; } @@ -3470,7 +3473,7 @@ impl ChatWidget { loop { if let Some(auth) = auth_manager.auth().await - && auth.mode == AuthMode::ChatGPT + && matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) && let Some(snapshot) = fetch_rate_limits(base_url.clone(), auth).await { app_event_tx.send(AppEvent::RateLimitSnapshotFetched(snapshot)); diff --git a/codex-rs/tui/src/onboarding/auth.rs b/codex-rs/tui/src/onboarding/auth.rs index 551fa9180e..daf64f36d8 100644 --- a/codex-rs/tui/src/onboarding/auth.rs +++ b/codex-rs/tui/src/onboarding/auth.rs @@ -661,7 +661,10 @@ impl AuthModeWidget { } fn handle_existing_chatgpt_login(&mut self) -> bool { - if matches!(self.login_status, LoginStatus::AuthMode(AuthMode::ChatGPT)) { + if matches!( + self.login_status, + LoginStatus::AuthMode(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + ) { *self.sign_in_state.write().unwrap() = SignInState::ChatGptSuccess; self.request_frame.schedule_frame(); true diff --git a/codex-rs/tui/src/status/helpers.rs b/codex-rs/tui/src/status/helpers.rs index 78a956b27c..91f958a9cf 100644 --- a/codex-rs/tui/src/status/helpers.rs +++ b/codex-rs/tui/src/status/helpers.rs @@ -91,7 +91,7 @@ pub(crate) fn compose_account_display( let auth = auth_manager.auth_cached()?; match auth.mode { - AuthMode::ChatGPT => { + AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens => { let email = auth.get_account_email(); let plan = plan .map(|plan_type| title_case(format!("{plan_type:?}").as_str())) From 11958221a3354fe7941671cc2c4a24ffd73c29a7 Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Thu, 29 Jan 2026 16:40:43 -0800 Subject: [PATCH 084/116] tui: add feature-gated /plan slash command to switch to Plan mode (#10103) ## Summary Adds a simple `/plan` slash command in the TUI that switches the active collaboration mode to Plan mode. The command is only available when the `collaboration_modes` feature is enabled. ## Changes - Add `plan_mask` helper in `codex-rs/tui/src/collaboration_modes.rs` - Add `SlashCommand::Plan` metadata in `codex-rs/tui/src/slash_command.rs` - Implement and hard-gate `/plan` dispatch in `codex-rs/tui/src/chatwidget.rs` - Hide `/plan` when collaboration modes are disabled in `codex-rs/tui/src/bottom_pane/slash_commands.rs` - Update command popup tests in `codex-rs/tui/src/bottom_pane/command_popup.rs` - Add a focused unit test for `/plan` in `codex-rs/tui/src/chatwidget/tests.rs` ## Behavior notes - `/plan` is now a no-op if `Feature::CollaborationModes` is disabled. - When enabled, `/plan` switches directly to Plan mode without opening the picker. ## Codex author `codex resume 019c05da-d7c3-7322-ae2c-3ca38d0ef702` --- codex-rs/tui/src/bottom_pane/command_popup.rs | 25 ++++++++++++++- .../tui/src/bottom_pane/slash_commands.rs | 5 ++- codex-rs/tui/src/chatwidget.rs | 31 ++++++++++++++----- codex-rs/tui/src/chatwidget/tests.rs | 13 ++++++++ codex-rs/tui/src/collaboration_modes.rs | 4 +++ codex-rs/tui/src/slash_command.rs | 3 ++ 6 files changed, 72 insertions(+), 9 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 621683923d..48ee7d2d60 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -459,7 +459,7 @@ mod tests { #[test] fn collab_command_hidden_when_collaboration_modes_disabled() { let mut popup = CommandPopup::new(Vec::new(), CommandPopupFlags::default()); - popup.on_composer_text_change("/coll".to_string()); + popup.on_composer_text_change("/".to_string()); let cmds: Vec<&str> = popup .filtered_items() @@ -473,6 +473,10 @@ mod tests { !cmds.contains(&"collab"), "expected '/collab' to be hidden when collaboration modes are disabled, got {cmds:?}" ); + assert!( + !cmds.contains(&"plan"), + "expected '/plan' to be hidden when collaboration modes are disabled, got {cmds:?}" + ); } #[test] @@ -494,6 +498,25 @@ mod tests { } } + #[test] + fn plan_command_visible_when_collaboration_modes_enabled() { + let mut popup = CommandPopup::new( + Vec::new(), + CommandPopupFlags { + collaboration_modes_enabled: true, + connectors_enabled: false, + personality_command_enabled: true, + windows_degraded_sandbox_active: false, + }, + ); + popup.on_composer_text_change("/plan".to_string()); + + match popup.selected_item() { + Some(CommandItem::Builtin(cmd)) => assert_eq!(cmd.command(), "plan"), + other => panic!("expected plan to be selected for exact match, got {other:?}"), + } + } + #[test] fn personality_command_hidden_when_disabled() { let mut popup = CommandPopup::new( diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index 1efab04ecd..34ad17330d 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -18,7 +18,10 @@ pub(crate) fn builtins_for_input( built_in_slash_commands() .into_iter() .filter(|(_, cmd)| allow_elevate_sandbox || *cmd != SlashCommand::ElevateSandbox) - .filter(|(_, cmd)| collaboration_modes_enabled || *cmd != SlashCommand::Collab) + .filter(|(_, cmd)| { + collaboration_modes_enabled + || !matches!(*cmd, SlashCommand::Collab | SlashCommand::Plan) + }) .filter(|(_, cmd)| connectors_enabled || *cmd != SlashCommand::Apps) .filter(|(_, cmd)| personality_command_enabled || *cmd != SlashCommand::Personality) .collect() diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 61006d80c8..74200e470a 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -2668,10 +2668,29 @@ impl ChatWidget { SlashCommand::Personality => { self.open_personality_popup(); } - SlashCommand::Collab => { - if self.collaboration_modes_enabled() { - self.open_collaboration_modes_popup(); + SlashCommand::Plan => { + if !self.collaboration_modes_enabled() { + self.add_info_message( + "Collaboration modes are disabled.".to_string(), + Some("Enable collaboration modes to use /plan.".to_string()), + ); + return; } + if let Some(mask) = collaboration_modes::plan_mask(self.models_manager.as_ref()) { + self.set_collaboration_mask(mask); + } else { + self.add_info_message("Plan mode unavailable right now.".to_string(), None); + } + } + SlashCommand::Collab => { + if !self.collaboration_modes_enabled() { + self.add_info_message( + "Collaboration modes are disabled.".to_string(), + Some("Enable collaboration modes to use /collab.".to_string()), + ); + return; + } + self.open_collaboration_modes_popup(); } SlashCommand::Agent => { self.app_event_tx.send(AppEvent::OpenAgentPicker); @@ -2844,11 +2863,9 @@ impl ChatWidget { let trimmed = args.trim(); match cmd { - SlashCommand::Collab => { + SlashCommand::Collab | SlashCommand::Plan => { let _ = trimmed; - if self.collaboration_modes_enabled() { - self.open_collaboration_modes_popup(); - } + self.dispatch_command(cmd); } SlashCommand::Review if !trimmed.is_empty() => { self.submit_op(Op::Review { diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 9859e9e56f..d8f22dc8e3 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -2267,6 +2267,19 @@ async fn collab_slash_command_opens_picker_and_updates_mode() { } } +#[tokio::test] +async fn plan_slash_command_switches_to_plan_mode() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + chat.set_feature_enabled(Feature::CollaborationModes, true); + let initial = chat.current_collaboration_mode().clone(); + + chat.dispatch_command(SlashCommand::Plan); + + assert!(rx.try_recv().is_err(), "plan should not emit an app event"); + assert_eq!(chat.active_collaboration_mode_kind(), ModeKind::Plan); + assert_eq!(chat.current_collaboration_mode(), &initial); +} + #[tokio::test] async fn collaboration_modes_defaults_to_code_on_startup() { let codex_home = tempdir().expect("tempdir"); diff --git a/codex-rs/tui/src/collaboration_modes.rs b/codex-rs/tui/src/collaboration_modes.rs index 95908d8e90..e799ea9c5a 100644 --- a/codex-rs/tui/src/collaboration_modes.rs +++ b/codex-rs/tui/src/collaboration_modes.rs @@ -59,3 +59,7 @@ pub(crate) fn next_mask( pub(crate) fn code_mask(models_manager: &ModelsManager) -> Option { mask_for_kind(models_manager, ModeKind::Code) } + +pub(crate) fn plan_mask(models_manager: &ModelsManager) -> Option { + mask_for_kind(models_manager, ModeKind::Plan) +} diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 9bab314610..9488577c1b 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -25,6 +25,7 @@ pub enum SlashCommand { Fork, Init, Compact, + Plan, Collab, Agent, // Undo, @@ -63,6 +64,7 @@ impl SlashCommand { SlashCommand::Ps => "list background terminals", SlashCommand::Model => "choose what model and reasoning effort to use", SlashCommand::Personality => "choose a communication style for Codex", + SlashCommand::Plan => "switch to Plan mode", SlashCommand::Collab => "change collaboration mode (experimental)", SlashCommand::Agent => "switch the active agent thread", SlashCommand::Approvals => "choose what Codex can do without approval", @@ -112,6 +114,7 @@ impl SlashCommand { | SlashCommand::Exit => true, SlashCommand::Rollout => true, SlashCommand::TestApproval => true, + SlashCommand::Plan => true, SlashCommand::Collab => true, SlashCommand::Agent => true, } From c6e1288ef10aa88be6b32be531ee099dd538b60d Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Thu, 29 Jan 2026 16:48:15 -0800 Subject: [PATCH 085/116] chore(app-server): document AuthMode (#10191) Explain what this is and what it's used for. --- codex-rs/app-server-protocol/src/protocol/common.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 2aaf419440..b9c58a5883 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -23,12 +23,22 @@ impl GitSha { } } +/// Authentication mode for OpenAI-backed providers. +/// +/// This is used internally to determine the base URL for generating responses, and to gate +/// ChatGPT-only behaviors like rate limits and available models (as opposed to API key-based +/// auth). #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)] #[serde(rename_all = "lowercase")] pub enum AuthMode { + /// OpenAI API key provided by the caller and stored by Codex. ApiKey, + /// ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex). ChatGPT, /// [UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. + /// + /// ChatGPT 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. #[serde(rename = "chatgptAuthTokens")] #[ts(rename = "chatgptAuthTokens")] #[strum(serialize = "chatgptAuthTokens")] From 7151387474792e9febcc3cb6e01ceb98280ce5de Mon Sep 17 00:00:00 2001 From: Celia Chen Date: Thu, 29 Jan 2026 17:10:00 -0800 Subject: [PATCH 086/116] [feat] persist dynamic tools in session rollout file (#10130) Add dynamic tools to rollout file for persistence & read from rollout on resume. Ran a real example and spotted the following in the rollout file: ``` {"timestamp":"2026-01-29T01:27:57.468Z","type":"session_meta","payload":{"id":"019c075d-3f0b-77e3-894e-c1c159b04b1e","timestamp":"2026-01-29T01:27:57.451Z","...."dynamic_tools":[{"name":"demo_tool","description":"Demo dynamic tool","inputSchema":{"additionalProperties":false,"properties":{"city":{"type":"string"}},"required":["city"],"type":"object"}}],"git":{"commit_hash":"ebc573f15c01b8af158e060cfedd401f043e9dfa","branch":"dev/cc/dynamic-tools","repository_url":"https://github.com/openai/codex.git"}}} ``` --- codex-rs/app-server/tests/common/rollout.rs | 2 ++ codex-rs/core/src/codex.rs | 7 +++++++ codex-rs/core/src/rollout/metadata.rs | 1 + codex-rs/core/src/rollout/recorder.rs | 10 ++++++++++ codex-rs/core/src/rollout/tests.rs | 1 + codex-rs/core/tests/suite/sqlite_state.rs | 1 + codex-rs/protocol/src/protocol.rs | 20 ++++++++++++++++++++ 7 files changed, 42 insertions(+) diff --git a/codex-rs/app-server/tests/common/rollout.rs b/codex-rs/app-server/tests/common/rollout.rs index 26316eddbd..14dce02c64 100644 --- a/codex-rs/app-server/tests/common/rollout.rs +++ b/codex-rs/app-server/tests/common/rollout.rs @@ -81,6 +81,7 @@ pub fn create_fake_rollout_with_source( source, model_provider: model_provider.map(str::to_string), base_instructions: None, + dynamic_tools: None, }; let payload = serde_json::to_value(SessionMetaLine { meta, @@ -159,6 +160,7 @@ pub fn create_fake_rollout_with_text_elements( source: SessionSource::Cli, model_provider: model_provider.map(str::to_string), base_instructions: None, + dynamic_tools: None, }; let payload = serde_json::to_value(SessionMetaLine { meta, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 1b7b7312c7..1fb5572183 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -324,6 +324,12 @@ impl Codex { .clone() .or_else(|| conversation_history.get_base_instructions().map(|s| s.text)) .unwrap_or_else(|| model_info.get_model_instructions(config.model_personality)); + // Respect explicit thread-start tools; fall back to persisted tools when resuming a thread. + let dynamic_tools = if dynamic_tools.is_empty() { + conversation_history.get_dynamic_tools().unwrap_or_default() + } else { + dynamic_tools + }; // TODO (aibrahim): Consolidate config.model and config.model_reasoning_effort into config.collaboration_mode // to avoid extracting these fields separately and constructing CollaborationMode here. @@ -715,6 +721,7 @@ impl Session { BaseInstructions { text: session_configuration.base_instructions.clone(), }, + session_configuration.dynamic_tools.clone(), ), ) } diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs index d08e77e241..5523274bde 100644 --- a/codex-rs/core/src/rollout/metadata.rs +++ b/codex-rs/core/src/rollout/metadata.rs @@ -303,6 +303,7 @@ mod tests { source: SessionSource::default(), model_provider: Some("openai".to_string()), base_instructions: None, + dynamic_tools: None, }; let session_meta_line = SessionMetaLine { meta: session_meta, diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index cc35850544..8157133165 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -7,6 +7,7 @@ use std::path::Path; use std::path::PathBuf; use codex_protocol::ThreadId; +use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::models::BaseInstructions; use serde_json::Value; use time::OffsetDateTime; @@ -68,6 +69,7 @@ pub enum RolloutRecorderParams { forked_from_id: Option, source: SessionSource, base_instructions: BaseInstructions, + dynamic_tools: Vec, }, Resume { path: PathBuf, @@ -91,12 +93,14 @@ impl RolloutRecorderParams { forked_from_id: Option, source: SessionSource, base_instructions: BaseInstructions, + dynamic_tools: Vec, ) -> Self { Self::Create { conversation_id, forked_from_id, source, base_instructions, + dynamic_tools, } } @@ -259,6 +263,7 @@ impl RolloutRecorder { forked_from_id, source, base_instructions, + dynamic_tools, } => { let LogFileInfo { file, @@ -288,6 +293,11 @@ impl RolloutRecorder { source, model_provider: Some(config.model_provider_id.clone()), base_instructions: Some(base_instructions), + dynamic_tools: if dynamic_tools.is_empty() { + None + } else { + Some(dynamic_tools) + }, }), ) } diff --git a/codex-rs/core/src/rollout/tests.rs b/codex-rs/core/src/rollout/tests.rs index 34afae2c94..cdf16291d3 100644 --- a/codex-rs/core/src/rollout/tests.rs +++ b/codex-rs/core/src/rollout/tests.rs @@ -873,6 +873,7 @@ async fn test_updated_at_uses_file_mtime() -> Result<()> { source: SessionSource::VSCode, model_provider: Some("test-provider".into()), base_instructions: None, + dynamic_tools: None, }, git: None, }), diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index bf3b5a4f51..2582f90cbe 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -93,6 +93,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { source: SessionSource::default(), model_provider: None, base_instructions: None, + dynamic_tools: None, }, git: None, }; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index aea7d3f013..7ba01fa4bd 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -20,6 +20,7 @@ use crate::config_types::WindowsSandboxLevel; use crate::custom_prompts::CustomPrompt; use crate::dynamic_tools::DynamicToolCallRequest; use crate::dynamic_tools::DynamicToolResponse; +use crate::dynamic_tools::DynamicToolSpec; use crate::items::TurnItem; use crate::message_history::HistoryEntry; use crate::models::BaseInstructions; @@ -1513,6 +1514,22 @@ impl InitialHistory { }), } } + + pub fn get_dynamic_tools(&self) -> Option> { + match self { + InitialHistory::New => None, + InitialHistory::Resumed(resumed) => { + resumed.history.iter().find_map(|item| match item { + RolloutItem::SessionMeta(meta_line) => meta_line.meta.dynamic_tools.clone(), + _ => None, + }) + } + InitialHistory::Forked(items) => items.iter().find_map(|item| match item { + RolloutItem::SessionMeta(meta_line) => meta_line.meta.dynamic_tools.clone(), + _ => None, + }), + } + } } fn session_cwd_from_items(items: &[RolloutItem]) -> Option { @@ -1599,6 +1616,8 @@ pub struct SessionMeta { /// but may be missing for older sessions. If not present, fall back to rendering the base_instructions /// from ModelsManager. pub base_instructions: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_tools: Option>, } impl Default for SessionMeta { @@ -1613,6 +1632,7 @@ impl Default for SessionMeta { source: SessionSource::default(), model_provider: None, base_instructions: None, + dynamic_tools: None, } } } From a9cf449a80e9bfaf059651e3b8be9badcca4b145 Mon Sep 17 00:00:00 2001 From: willwang-openai Date: Thu, 29 Jan 2026 17:17:25 -0800 Subject: [PATCH 087/116] add error messages for the go plan type (#10181) Adds support for the Go plan type Updates rate limit error messages to point to the usage page --- codex-rs/backend-client/src/client.rs | 2 +- codex-rs/core/src/auth.rs | 1 + codex-rs/core/src/error.rs | 23 +++++++++++++++---- codex-rs/core/src/token_data.rs | 33 +++++++++++++++++++++++++++ codex-rs/protocol/src/account.rs | 1 + 5 files changed, 55 insertions(+), 5 deletions(-) diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index ec5fd3f61b..6fa36d1ffd 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -351,6 +351,7 @@ impl Client { fn map_plan_type(plan_type: crate::types::PlanType) -> AccountPlanType { match plan_type { crate::types::PlanType::Free => AccountPlanType::Free, + crate::types::PlanType::Go => AccountPlanType::Go, crate::types::PlanType::Plus => AccountPlanType::Plus, crate::types::PlanType::Pro => AccountPlanType::Pro, crate::types::PlanType::Team => AccountPlanType::Team, @@ -358,7 +359,6 @@ impl Client { crate::types::PlanType::Enterprise => AccountPlanType::Enterprise, crate::types::PlanType::Edu | crate::types::PlanType::Education => AccountPlanType::Edu, crate::types::PlanType::Guest - | crate::types::PlanType::Go | crate::types::PlanType::FreeWorkspace | crate::types::PlanType::Quorum | crate::types::PlanType::K12 => AccountPlanType::Unknown, diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index d6cfec5506..d4520dc855 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -159,6 +159,7 @@ impl CodexAuth { pub fn account_plan_type(&self) -> Option { let map_known = |kp: &InternalKnownPlan| match kp { InternalKnownPlan::Free => AccountPlanType::Free, + InternalKnownPlan::Go => AccountPlanType::Go, InternalKnownPlan::Plus => AccountPlanType::Plus, InternalKnownPlan::Pro => AccountPlanType::Pro, InternalKnownPlan::Team => AccountPlanType::Team, diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index 6c284074c9..f9f896c3b8 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -375,9 +375,11 @@ impl std::fmt::Display for UsageLimitReachedError { retry_suffix_after_or(self.resets_at.as_ref()) ) } - Some(PlanType::Known(KnownPlan::Free)) => { - "You've hit your usage limit. Upgrade to Plus to continue using Codex (https://openai.com/chatgpt/pricing)." - .to_string() + Some(PlanType::Known(KnownPlan::Free)) | Some(PlanType::Known(KnownPlan::Go)) => { + format!( + "You've hit your usage limit. Upgrade to Plus to continue using Codex (https://openai.com/chatgpt/pricing),{}", + retry_suffix_after_or(self.resets_at.as_ref()) + ) } Some(PlanType::Known(KnownPlan::Pro)) => format!( "You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more credits{}", @@ -817,7 +819,20 @@ mod tests { }; assert_eq!( err.to_string(), - "You've hit your usage limit. Upgrade to Plus to continue using Codex (https://openai.com/chatgpt/pricing)." + "You've hit your usage limit. Upgrade to Plus to continue using Codex (https://openai.com/chatgpt/pricing), or try again later." + ); + } + + #[test] + fn usage_limit_reached_error_formats_go_plan() { + let err = UsageLimitReachedError { + plan_type: Some(PlanType::Known(KnownPlan::Go)), + resets_at: None, + rate_limits: Some(rate_limit_snapshot()), + }; + assert_eq!( + err.to_string(), + "You've hit your usage limit. Upgrade to Plus to continue using Codex (https://openai.com/chatgpt/pricing), or try again later." ); } diff --git a/codex-rs/core/src/token_data.rs b/codex-rs/core/src/token_data.rs index 2010af16f7..e38660ff5a 100644 --- a/codex-rs/core/src/token_data.rs +++ b/codex-rs/core/src/token_data.rs @@ -64,6 +64,7 @@ pub(crate) enum PlanType { #[serde(rename_all = "lowercase")] pub(crate) enum KnownPlan { Free, + Go, Plus, Pro, Team, @@ -195,6 +196,38 @@ mod tests { assert_eq!(info.get_chatgpt_plan_type().as_deref(), Some("Pro")); } + #[test] + fn id_token_info_parses_go_plan() { + #[derive(Serialize)] + struct Header { + alg: &'static str, + typ: &'static str, + } + let header = Header { + alg: "none", + typ: "JWT", + }; + let payload = serde_json::json!({ + "email": "user@example.com", + "https://api.openai.com/auth": { + "chatgpt_plan_type": "go" + } + }); + + fn b64url_no_pad(bytes: &[u8]) -> String { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) + } + + let header_b64 = b64url_no_pad(&serde_json::to_vec(&header).unwrap()); + let payload_b64 = b64url_no_pad(&serde_json::to_vec(&payload).unwrap()); + let signature_b64 = b64url_no_pad(b"sig"); + let fake_jwt = format!("{header_b64}.{payload_b64}.{signature_b64}"); + + let info = parse_id_token(&fake_jwt).expect("should parse"); + assert_eq!(info.email.as_deref(), Some("user@example.com")); + assert_eq!(info.get_chatgpt_plan_type().as_deref(), Some("Go")); + } + #[test] fn id_token_info_handles_missing_fields() { #[derive(Serialize)] diff --git a/codex-rs/protocol/src/account.rs b/codex-rs/protocol/src/account.rs index fb707c3a73..1cb58a020f 100644 --- a/codex-rs/protocol/src/account.rs +++ b/codex-rs/protocol/src/account.rs @@ -9,6 +9,7 @@ use ts_rs::TS; pub enum PlanType { #[default] Free, + Go, Plus, Pro, Team, From 36f2fe8af94bf678f6653e02bd5e6cd7a558aa21 Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Thu, 29 Jan 2026 18:12:46 -0800 Subject: [PATCH 088/116] feat(tui): route employee feedback follow-ups to internal link (#10198) ## Problem OpenAI employees were sent to the public GitHub issue flow after `/feedback`, which is the wrong follow-up path internally. ## Mental model After feedback upload completes, we render a follow-up link/message. That link should be audience-aware but must not change the upload pipeline itself. ## Non-goals - Changing how feedback is captured or uploaded - Changing external user behavior ## Tradeoffs We detect employees via the authenticated account email suffix (`@openai.com`). If the email is unavailable (e.g., API key auth), we default to the external behavior. ## Architecture - Introduce `FeedbackAudience` and thread it from `App` -> `ChatWidget` -> `FeedbackNoteView` - Gate internal messaging/links on `FeedbackAudience::OpenAiEmployee` - Internal follow-up link is now `http://go/codex-feedback-internal` - External GitHub URL remains byte-for-byte identical ## Observability No new telemetry; this only changes rendered follow-up instructions. ## Tests - `just fmt` - `cargo test -p codex-tui --lib` --- codex-rs/tui/src/app.rs | 21 +++ codex-rs/tui/src/bottom_pane/feedback_view.rs | 150 ++++++++++++++---- codex-rs/tui/src/bottom_pane/mod.rs | 1 + codex-rs/tui/src/chatwidget.rs | 10 ++ codex-rs/tui/src/chatwidget/tests.rs | 5 + 5 files changed, 154 insertions(+), 33 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index ae1dc4b322..fe33df8378 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -7,6 +7,7 @@ use crate::app_event::WindowsSandboxEnableMode; use crate::app_event::WindowsSandboxFallbackReason; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::ApprovalRequest; +use crate::bottom_pane::FeedbackAudience; use crate::bottom_pane::SelectionItem; use crate::bottom_pane::SelectionViewParams; use crate::bottom_pane::popup_consts::standard_popup_hint_line; @@ -541,6 +542,7 @@ pub(crate) struct App { /// transcript cells. pub(crate) backtrack_render_pending: bool, pub(crate) feedback: codex_feedback::CodexFeedback, + feedback_audience: FeedbackAudience, /// Set when the user confirms an update; propagated on exit. pub(crate) pending_update_action: Option, @@ -599,6 +601,7 @@ impl App { models_manager: self.server.get_models_manager(), feedback: self.feedback.clone(), is_first_run: false, + feedback_audience: self.feedback_audience, model: Some(self.chat_widget.current_model().to_string()), otel_manager: self.otel_manager.clone(), } @@ -957,6 +960,17 @@ impl App { let auth = auth_manager.auth().await; let auth_ref = auth.as_ref(); + // Determine who should see internal Slack routing. We treat + // `@openai.com` emails as employees and default to `External` when the + // email is unavailable (for example, API key auth). + let feedback_audience = if auth_ref + .and_then(CodexAuth::get_account_email) + .is_some_and(|email| email.ends_with("@openai.com")) + { + FeedbackAudience::OpenAiEmployee + } else { + FeedbackAudience::External + }; let otel_manager = OtelManager::new( ThreadId::new(), model.as_str(), @@ -987,6 +1001,7 @@ impl App { models_manager: thread_manager.get_models_manager(), feedback: feedback.clone(), is_first_run, + feedback_audience, model: Some(model.clone()), otel_manager: otel_manager.clone(), }; @@ -1015,6 +1030,7 @@ impl App { models_manager: thread_manager.get_models_manager(), feedback: feedback.clone(), is_first_run, + feedback_audience, model: config.model.clone(), otel_manager: otel_manager.clone(), }; @@ -1043,6 +1059,7 @@ impl App { models_manager: thread_manager.get_models_manager(), feedback: feedback.clone(), is_first_run, + feedback_audience, model: config.model.clone(), otel_manager: otel_manager.clone(), }; @@ -1078,6 +1095,7 @@ impl App { backtrack: BacktrackState::default(), backtrack_render_pending: false, feedback: feedback.clone(), + feedback_audience, pending_update_action: None, suppress_shutdown_complete: false, windows_sandbox: WindowsSandboxState::default(), @@ -1268,6 +1286,7 @@ impl App { models_manager: self.server.get_models_manager(), feedback: self.feedback.clone(), is_first_run: false, + feedback_audience: self.feedback_audience, model: Some(model), otel_manager: self.otel_manager.clone(), }; @@ -2601,6 +2620,7 @@ mod tests { backtrack: BacktrackState::default(), backtrack_render_pending: false, feedback: codex_feedback::CodexFeedback::new(), + feedback_audience: FeedbackAudience::External, pending_update_action: None, suppress_shutdown_complete: false, windows_sandbox: WindowsSandboxState::default(), @@ -2653,6 +2673,7 @@ mod tests { backtrack: BacktrackState::default(), backtrack_render_pending: false, feedback: codex_feedback::CodexFeedback::new(), + feedback_audience: FeedbackAudience::External, pending_update_action: None, suppress_shutdown_complete: false, windows_sandbox: WindowsSandboxState::default(), diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index 8fef8e79a1..a76d73475e 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -29,6 +29,18 @@ use super::textarea::TextAreaState; const BASE_BUG_ISSUE_URL: &str = "https://github.com/openai/codex/issues/new?template=2-bug-report.yml"; +/// Internal routing link for employee feedback follow-ups. This must not be shown to external users. +const CODEX_FEEDBACK_INTERNAL_URL: &str = "http://go/codex-feedback-internal"; + +/// The target audience for feedback follow-up instructions. +/// +/// This is used strictly for messaging/links after feedback upload completes. It +/// must not change feedback upload behavior itself. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FeedbackAudience { + OpenAiEmployee, + External, +} /// Minimal input overlay to collect an optional feedback note, then upload /// both logs and rollout with classification + metadata. @@ -38,6 +50,7 @@ pub(crate) struct FeedbackNoteView { rollout_path: Option, app_event_tx: AppEventSender, include_logs: bool, + feedback_audience: FeedbackAudience, // UI state textarea: TextArea, @@ -52,6 +65,7 @@ impl FeedbackNoteView { rollout_path: Option, app_event_tx: AppEventSender, include_logs: bool, + feedback_audience: FeedbackAudience, ) -> Self { Self { category, @@ -59,6 +73,7 @@ impl FeedbackNoteView { rollout_path, app_event_tx, include_logs, + feedback_audience, textarea: TextArea::new(), textarea_state: RefCell::new(TextAreaState::default()), complete: false, @@ -96,30 +111,49 @@ impl FeedbackNoteView { } else { "• Feedback recorded (no logs)." }; - let issue_url = issue_url_for_category(self.category, &thread_id); + let issue_url = + issue_url_for_category(self.category, &thread_id, self.feedback_audience); let mut lines = vec![Line::from(match issue_url.as_ref() { + Some(_) if self.feedback_audience == FeedbackAudience::OpenAiEmployee => { + format!("{prefix} Please report this in #codex-feedback:") + } Some(_) => format!("{prefix} Please open an issue using the following URL:"), None => format!("{prefix} Thanks for the feedback!"), })]; - if let Some(url) = issue_url { - lines.extend([ - "".into(), - Line::from(vec![" ".into(), url.cyan().underlined()]), - "".into(), - Line::from(vec![ - " Or mention your thread ID ".into(), - std::mem::take(&mut thread_id).bold(), - " in an existing issue.".into(), - ]), - ]); - } else { - lines.extend([ - "".into(), - Line::from(vec![ - " Thread ID: ".into(), - std::mem::take(&mut thread_id).bold(), - ]), - ]); + match issue_url { + Some(url) if self.feedback_audience == FeedbackAudience::OpenAiEmployee => { + lines.extend([ + "".into(), + Line::from(vec![" ".into(), url.cyan().underlined()]), + "".into(), + Line::from(" Share this and add some info about your problem:"), + Line::from(vec![ + " ".into(), + format!("go/codex-feedback/{thread_id}").bold(), + ]), + ]); + } + Some(url) => { + lines.extend([ + "".into(), + Line::from(vec![" ".into(), url.cyan().underlined()]), + "".into(), + Line::from(vec![ + " Or mention your thread ID ".into(), + std::mem::take(&mut thread_id).bold(), + " in an existing issue.".into(), + ]), + ]); + } + None => { + lines.extend([ + "".into(), + Line::from(vec![ + " Thread ID: ".into(), + std::mem::take(&mut thread_id).bold(), + ]), + ]); + } } self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( history_cell::PlainHistoryCell::new(lines), @@ -335,15 +369,35 @@ fn feedback_classification(category: FeedbackCategory) -> &'static str { } } -fn issue_url_for_category(category: FeedbackCategory, thread_id: &str) -> Option { +fn issue_url_for_category( + category: FeedbackCategory, + thread_id: &str, + feedback_audience: FeedbackAudience, +) -> Option { + // Only certain categories provide a follow-up link. We intentionally keep + // the external GitHub behavior identical while routing internal users to + // the internal go link. match category { - FeedbackCategory::Bug | FeedbackCategory::BadResult | FeedbackCategory::Other => Some( - format!("{BASE_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20{thread_id}"), - ), + FeedbackCategory::Bug | FeedbackCategory::BadResult | FeedbackCategory::Other => { + Some(match feedback_audience { + FeedbackAudience::OpenAiEmployee => slack_feedback_url(thread_id), + FeedbackAudience::External => { + format!("{BASE_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20{thread_id}") + } + }) + } FeedbackCategory::GoodResult => None, } } +/// Build the internal follow-up URL. +/// +/// We accept a `thread_id` so the call site stays symmetric with the external +/// path, but we currently point to a fixed channel without prefilling text. +fn slack_feedback_url(_thread_id: &str) -> String { + CODEX_FEEDBACK_INTERNAL_URL.to_string() +} + // Build the selection popup params for feedback categories. pub(crate) fn feedback_selection_params( app_event_tx: AppEventSender, @@ -523,7 +577,14 @@ mod tests { let (tx_raw, _rx) = tokio::sync::mpsc::unbounded_channel::(); let tx = AppEventSender::new(tx_raw); let snapshot = codex_feedback::CodexFeedback::new().snapshot(None); - FeedbackNoteView::new(category, snapshot, None, tx, true) + FeedbackNoteView::new( + category, + snapshot, + None, + tx, + true, + FeedbackAudience::External, + ) } #[test] @@ -556,19 +617,42 @@ mod tests { #[test] fn issue_url_available_for_bug_bad_result_and_other() { - let bug_url = issue_url_for_category(FeedbackCategory::Bug, "thread-1"); - assert!( - bug_url - .as_deref() - .is_some_and(|url| url.contains("template=2-bug-report")) + let bug_url = issue_url_for_category( + FeedbackCategory::Bug, + "thread-1", + FeedbackAudience::OpenAiEmployee, ); + let expected_slack_url = "http://go/codex-feedback-internal".to_string(); + assert_eq!(bug_url.as_deref(), Some(expected_slack_url.as_str())); - let bad_result_url = issue_url_for_category(FeedbackCategory::BadResult, "thread-2"); + let bad_result_url = issue_url_for_category( + FeedbackCategory::BadResult, + "thread-2", + FeedbackAudience::OpenAiEmployee, + ); assert!(bad_result_url.is_some()); - let other_url = issue_url_for_category(FeedbackCategory::Other, "thread-3"); + let other_url = issue_url_for_category( + FeedbackCategory::Other, + "thread-3", + FeedbackAudience::OpenAiEmployee, + ); assert!(other_url.is_some()); - assert!(issue_url_for_category(FeedbackCategory::GoodResult, "t").is_none()); + assert!( + issue_url_for_category( + FeedbackCategory::GoodResult, + "t", + FeedbackAudience::OpenAiEmployee + ) + .is_none() + ); + let bug_url_non_employee = + issue_url_for_category(FeedbackCategory::Bug, "t", FeedbackAudience::External); + let expected_external_url = format!("{BASE_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20t"); + assert_eq!( + bug_url_non_employee.as_deref(), + Some(expected_external_url.as_str()) + ); } } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index d08ccf5068..a632fd4468 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -67,6 +67,7 @@ mod slash_commands; pub(crate) use footer::CollaborationModeIndicator; pub(crate) use list_selection_view::SelectionViewParams; mod feedback_view; +pub(crate) use feedback_view::FeedbackAudience; pub(crate) use feedback_view::feedback_disabled_params; pub(crate) use feedback_view::feedback_selection_params; pub(crate) use feedback_view::feedback_upload_consent_params; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 74200e470a..2833d4863e 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -147,6 +147,7 @@ use crate::bottom_pane::CollaborationModeIndicator; use crate::bottom_pane::DOUBLE_PRESS_QUIT_SHORTCUT_ENABLED; use crate::bottom_pane::ExperimentalFeatureItem; use crate::bottom_pane::ExperimentalFeaturesView; +use crate::bottom_pane::FeedbackAudience; use crate::bottom_pane::InputResult; use crate::bottom_pane::LocalImageAttachment; use crate::bottom_pane::QUIT_SHORTCUT_TIMEOUT; @@ -379,6 +380,7 @@ pub(crate) struct ChatWidgetInit { pub(crate) models_manager: Arc, pub(crate) feedback: codex_feedback::CodexFeedback, pub(crate) is_first_run: bool, + pub(crate) feedback_audience: FeedbackAudience, pub(crate) model: Option, pub(crate) otel_manager: OtelManager, } @@ -558,6 +560,7 @@ pub(crate) struct ChatWidget { last_rendered_width: std::cell::Cell>, // Feedback sink for /feedback feedback: codex_feedback::CodexFeedback, + feedback_audience: FeedbackAudience, // Current session rollout path (if known) current_rollout_path: Option, external_editor_state: ExternalEditorState, @@ -845,6 +848,7 @@ impl ChatWidget { rollout, self.app_event_tx.clone(), include_logs, + self.feedback_audience, ); self.bottom_pane.show_view(Box::new(view)); self.request_redraw(); @@ -2047,6 +2051,7 @@ impl ChatWidget { models_manager, feedback, is_first_run, + feedback_audience, model, otel_manager, } = common; @@ -2143,6 +2148,7 @@ impl ChatWidget { last_separator_elapsed_secs: None, last_rendered_width: std::cell::Cell::new(None), feedback, + feedback_audience, current_rollout_path: None, external_editor_state: ExternalEditorState::Closed, }; @@ -2186,6 +2192,7 @@ impl ChatWidget { models_manager, feedback, is_first_run, + feedback_audience, model, otel_manager, } = common; @@ -2281,6 +2288,7 @@ impl ChatWidget { last_separator_elapsed_secs: None, last_rendered_width: std::cell::Cell::new(None), feedback, + feedback_audience, current_rollout_path: None, external_editor_state: ExternalEditorState::Closed, }; @@ -2312,6 +2320,7 @@ impl ChatWidget { auth_manager, models_manager, feedback, + feedback_audience, model, otel_manager, .. @@ -2408,6 +2417,7 @@ impl ChatWidget { last_separator_elapsed_secs: None, last_rendered_width: std::cell::Cell::new(None), feedback, + feedback_audience, current_rollout_path: None, external_editor_state: ExternalEditorState::Closed, }; diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index d8f22dc8e3..a0e8269b58 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -8,6 +8,7 @@ use super::*; use crate::app_event::AppEvent; use crate::app_event::ExitMode; use crate::app_event_sender::AppEventSender; +use crate::bottom_pane::FeedbackAudience; use crate::bottom_pane::LocalImageAttachment; use crate::history_cell::UserHistoryCell; use crate::test_backend::VT100Backend; @@ -716,6 +717,7 @@ async fn helpers_are_available_and_do_not_panic() { models_manager: thread_manager.get_models_manager(), feedback: codex_feedback::CodexFeedback::new(), is_first_run: true, + feedback_audience: FeedbackAudience::External, model: Some(resolved_model), otel_manager, }; @@ -837,6 +839,7 @@ async fn make_chatwidget_manual( last_separator_elapsed_secs: None, last_rendered_width: std::cell::Cell::new(None), feedback: codex_feedback::CodexFeedback::new(), + feedback_audience: FeedbackAudience::External, current_rollout_path: None, external_editor_state: ExternalEditorState::Closed, }; @@ -2309,6 +2312,7 @@ async fn collaboration_modes_defaults_to_code_on_startup() { models_manager: thread_manager.get_models_manager(), feedback: codex_feedback::CodexFeedback::new(), is_first_run: true, + feedback_audience: FeedbackAudience::External, model: Some(resolved_model.clone()), otel_manager, }; @@ -2353,6 +2357,7 @@ async fn experimental_mode_plan_applies_on_startup() { models_manager: thread_manager.get_models_manager(), feedback: codex_feedback::CodexFeedback::new(), is_first_run: true, + feedback_audience: FeedbackAudience::External, model: Some(resolved_model.clone()), otel_manager, }; From d550fbf41afc09d7d7b5ac813aea38de07b2a73f Mon Sep 17 00:00:00 2001 From: alexsong-oai Date: Thu, 29 Jan 2026 18:44:12 -0800 Subject: [PATCH 089/116] load from yaml (#10194) --- codex-rs/core/src/skills/loader.rs | 53 +++++++++++++++++------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index 581f7d0c1f..32f1b8706e 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -72,7 +72,8 @@ struct DependencyTool { } const SKILLS_FILENAME: &str = "SKILL.md"; -const SKILLS_JSON_FILENAME: &str = "SKILL.json"; +const SKILLS_METADATA_DIR: &str = "agents"; +const SKILLS_METADATA_FILENAME: &str = "openai.yaml"; const SKILLS_DIR_NAME: &str = "skills"; const MAX_NAME_LEN: usize = 64; const MAX_DESCRIPTION_LEN: usize = 1024; @@ -402,7 +403,9 @@ fn load_skill_metadata(skill_path: &Path) -> (Option, Option (Option, Option parsed, Err(error) => { tracing::warn!( "ignoring {path}: invalid {label}: {error}", path = metadata_path.display(), - label = SKILLS_JSON_FILENAME + label = SKILLS_METADATA_FILENAME ); return (None, None); } @@ -859,25 +862,29 @@ mod tests { path } - fn write_skill_metadata_at(skill_dir: &Path, filename: &str, contents: &str) -> PathBuf { - let path = skill_dir.join(filename); + fn write_skill_metadata_at(skill_dir: &Path, contents: &str) -> PathBuf { + let path = skill_dir + .join(SKILLS_METADATA_DIR) + .join(SKILLS_METADATA_FILENAME); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).unwrap(); + } fs::write(&path, contents).unwrap(); path } fn write_skill_interface_at(skill_dir: &Path, contents: &str) -> PathBuf { - write_skill_metadata_at(skill_dir, SKILLS_JSON_FILENAME, contents) + write_skill_metadata_at(skill_dir, contents) } #[tokio::test] - async fn loads_skill_dependencies_metadata_from_json() { + async fn loads_skill_dependencies_metadata_from_yaml() { let codex_home = tempfile::tempdir().expect("tempdir"); let skill_path = write_skill(&codex_home, "demo", "dep-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); write_skill_metadata_at( skill_dir, - SKILLS_JSON_FILENAME, r#" { "dependencies": { @@ -970,7 +977,7 @@ mod tests { } #[tokio::test] - async fn loads_skill_interface_metadata_from_json() { + async fn loads_skill_interface_metadata_from_yaml() { let codex_home = tempfile::tempdir().expect("tempdir"); let skill_path = write_skill(&codex_home, "demo", "ui-skill", "from json"); let skill_dir = skill_path.parent().expect("skill dir"); @@ -979,16 +986,13 @@ mod tests { write_skill_interface_at( skill_dir, r##" -{ - "interface": { - "display_name": "UI Skill", - "short_description": " short desc ", - "icon_small": "./assets/small-400px.png", - "icon_large": "./assets/large-logo.svg", - "brand_color": "#3B82F6", - "default_prompt": " default prompt " - } -} +interface: + display_name: "UI Skill" + short_description: " short desc " + icon_small: "./assets/small-400px.png" + icon_large: "./assets/large-logo.svg" + brand_color: "#3B82F6" + default_prompt: " default prompt " "##, ); @@ -1000,8 +1004,13 @@ mod tests { "unexpected errors: {:?}", outcome.errors ); + let user_skills: Vec = outcome + .skills + .into_iter() + .filter(|skill| skill.scope == SkillScope::User) + .collect(); assert_eq!( - outcome.skills, + user_skills, vec![SkillMetadata { name: "ui-skill".to_string(), description: "from json".to_string(), From e3ab0bd9739106b039ebffe040914d4aac0c6de6 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Fri, 30 Jan 2026 00:10:12 -0700 Subject: [PATCH 090/116] chore(personality) new schema with fallbacks (#10147) ## Summary Let's dial in this api contract in a bit more with more robust fallback behavior when model_instructions_template is false. Switches to a more explicit template / variables structure, with more fallbacks. ## Testing - [x] Adding unit tests - [x] Tested locally --- .../app-server/tests/common/models_cache.rs | 2 +- .../tests/suite/v2/thread_resume.rs | 13 +- .../app-server/tests/suite/v2/turn_start.rs | 9 +- .../codex-api/tests/models_integration.rs | 2 +- codex-rs/core/src/codex.rs | 52 ++- .../core/src/models_manager/model_info.rs | 55 +-- .../gpt-5.2-codex_instructions_template.md | 4 +- ...{friendly.md => gpt-5.2-codex_friendly.md} | 0 ...ragmatic.md => gpt-5.2-codex_pragmatic.md} | 1 + codex-rs/core/tests/suite/models_cache_ttl.rs | 2 +- codex-rs/core/tests/suite/personality.rs | 360 +++++++++++++++++- codex-rs/core/tests/suite/remote_models.rs | 6 +- codex-rs/protocol/src/openai_models.rs | 216 +++++++++-- 13 files changed, 607 insertions(+), 115 deletions(-) rename codex-rs/core/templates/personalities/{friendly.md => gpt-5.2-codex_friendly.md} (100%) rename codex-rs/core/templates/personalities/{pragmatic.md => gpt-5.2-codex_pragmatic.md} (99%) diff --git a/codex-rs/app-server/tests/common/models_cache.rs b/codex-rs/app-server/tests/common/models_cache.rs index 7a093dc7f0..59fddc2427 100644 --- a/codex-rs/app-server/tests/common/models_cache.rs +++ b/codex-rs/app-server/tests/common/models_cache.rs @@ -27,7 +27,7 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo { priority, upgrade: preset.upgrade.as_ref().map(|u| u.into()), base_instructions: "base instructions".to_string(), - model_instructions_template: None, + model_messages: None, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index af746b37b7..6ad0a14b30 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -31,7 +31,7 @@ use tempfile::TempDir; use tokio::time::timeout; const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); -const DEFAULT_BASE_INSTRUCTIONS: &str = "You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer."; +const CODEX_5_2_INSTRUCTIONS_TEMPLATE_DEFAULT: &str = "You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals."; #[tokio::test] async fn thread_resume_returns_original_thread() -> Result<()> { @@ -368,7 +368,7 @@ async fn thread_resume_supports_history_and_overrides() -> Result<()> { } #[tokio::test] -async fn thread_resume_accepts_personality_override_v2() -> Result<()> { +async fn thread_resume_accepts_personality_override() -> Result<()> { skip_if_no_network!(Ok(())); let server = responses::start_mock_server().await; @@ -438,14 +438,14 @@ async fn thread_resume_accepts_personality_override_v2() -> Result<()> { let request = response_mock.single_request(); let developer_texts = request.message_input_texts("developer"); assert!( - !developer_texts + developer_texts .iter() .any(|text| text.contains("")), - "did not expect a personality update message in developer input, got {developer_texts:?}" + "expected a personality update message in developer input, got {developer_texts:?}" ); let instructions_text = request.instructions_text(); assert!( - instructions_text.contains(DEFAULT_BASE_INSTRUCTIONS), + instructions_text.contains(CODEX_5_2_INSTRUCTIONS_TEMPLATE_DEFAULT), "expected default base instructions from history, got {instructions_text:?}" ); @@ -459,7 +459,7 @@ fn create_config_toml(codex_home: &std::path::Path, server_uri: &str) -> std::io config_toml, format!( r#" -model = "mock-model" +model = "gpt-5.2-codex" approval_policy = "never" sandbox_mode = "read-only" @@ -467,6 +467,7 @@ model_provider = "mock_provider" [features] remote_models = false +personality = true [model_providers.mock_provider] name = "Mock provider for test" 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 3abe73e2e9..99eff9ecb2 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -63,7 +63,7 @@ async fn turn_start_sends_originator_header() -> Result<()> { codex_home.path(), &server.uri(), "never", - &BTreeMap::default(), + &BTreeMap::from([(Feature::Personality, true)]), )?; let mut mcp = McpProcess::new(codex_home.path()).await?; @@ -138,7 +138,7 @@ async fn turn_start_emits_user_message_item_with_text_elements() -> Result<()> { codex_home.path(), &server.uri(), "never", - &BTreeMap::default(), + &BTreeMap::from([(Feature::Personality, true)]), )?; let mut mcp = McpProcess::new(codex_home.path()).await?; @@ -230,7 +230,7 @@ async fn turn_start_emits_notifications_and_accepts_model_override() -> Result<( codex_home.path(), &server.uri(), "never", - &BTreeMap::default(), + &BTreeMap::from([(Feature::Personality, true)]), )?; let mut mcp = McpProcess::new(codex_home.path()).await?; @@ -425,7 +425,7 @@ async fn turn_start_accepts_personality_override_v2() -> Result<()> { codex_home.path(), &server.uri(), "never", - &BTreeMap::default(), + &BTreeMap::from([(Feature::Personality, true)]), )?; let mut mcp = McpProcess::new(codex_home.path()).await?; @@ -473,6 +473,7 @@ async fn turn_start_accepts_personality_override_v2() -> Result<()> { if developer_texts.is_empty() { eprintln!("request body: {}", request.body_json()); } + assert!( developer_texts .iter() diff --git a/codex-rs/codex-api/tests/models_integration.rs b/codex-rs/codex-api/tests/models_integration.rs index b1c4f060b2..c75c46a28a 100644 --- a/codex-rs/codex-api/tests/models_integration.rs +++ b/codex-rs/codex-api/tests/models_integration.rs @@ -77,7 +77,7 @@ async fn models_client_hits_models_endpoint() { priority: 1, upgrade: None, base_instructions: "base instructions".to_string(), - model_instructions_template: None, + model_messages: None, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 1fb5572183..250ea1ff49 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1285,27 +1285,31 @@ impl Session { previous: Option<&Arc>, next: &TurnContext, ) -> Option { - let personality = next.personality?; - if let Some(prev) = previous - && prev.personality == Some(personality) - { + if !self.features.enabled(Feature::Personality) { return None; } - let model_info = next.client.get_model_info(); - let personality_message = Self::personality_message_for(&model_info, personality); + let previous = previous?; - personality_message.map(|personality_message| { - DeveloperInstructions::personality_spec_message(personality_message).into() - }) + // if a personality is specified and it's different from the previous one, build a personality update item + if let Some(personality) = next.personality + && next.personality != previous.personality + { + let model_info = next.client.get_model_info(); + let personality_message = Self::personality_message_for(&model_info, personality); + personality_message.map(|personality_message| { + DeveloperInstructions::personality_spec_message(personality_message).into() + }) + } else { + None + } } fn personality_message_for(model_info: &ModelInfo, personality: Personality) -> Option { model_info - .model_instructions_template + .model_messages .as_ref() - .and_then(|template| template.personality_messages.as_ref()) - .and_then(|messages| messages.0.get(&personality)) - .cloned() + .and_then(|spec| spec.get_personality_message(Some(personality))) + .filter(|message| !message.is_empty()) } fn build_collaboration_mode_update_item( @@ -1845,15 +1849,33 @@ impl Session { items.push(DeveloperInstructions::new(developer_instructions.to_string()).into()); } // Add developer instructions from collaboration_mode if they exist and are non-empty - let collaboration_mode = { + let (collaboration_mode, base_instructions) = { let state = self.state.lock().await; - state.session_configuration.collaboration_mode.clone() + ( + state.session_configuration.collaboration_mode.clone(), + state.session_configuration.base_instructions.clone(), + ) }; if let Some(collab_instructions) = DeveloperInstructions::from_collaboration_mode(&collaboration_mode) { items.push(collab_instructions.into()); } + if self.features.enabled(Feature::Personality) + && let Some(personality) = turn_context.personality + { + let model_info = turn_context.client.get_model_info(); + let has_baked_personality = model_info.supports_personality() + && base_instructions == model_info.get_model_instructions(Some(personality)); + if !has_baked_personality + && let Some(personality_message) = + Self::personality_message_for(&model_info, personality) + { + items.push( + DeveloperInstructions::personality_spec_message(personality_message).into(), + ); + } + } if let Some(user_instructions) = turn_context.user_instructions.as_deref() { items.push( UserInstructions { diff --git a/codex-rs/core/src/models_manager/model_info.rs b/codex-rs/core/src/models_manager/model_info.rs index b50f23274a..eaab160001 100644 --- a/codex-rs/core/src/models_manager/model_info.rs +++ b/codex-rs/core/src/models_manager/model_info.rs @@ -1,19 +1,17 @@ -use std::collections::BTreeMap; - -use codex_protocol::config_types::Personality; use codex_protocol::config_types::Verbosity; use codex_protocol::openai_models::ApplyPatchToolType; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; -use codex_protocol::openai_models::ModelInstructionsTemplate; +use codex_protocol::openai_models::ModelInstructionsVariables; +use codex_protocol::openai_models::ModelMessages; use codex_protocol::openai_models::ModelVisibility; -use codex_protocol::openai_models::PersonalityMessages; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationMode; use codex_protocol::openai_models::TruncationPolicyConfig; use crate::config::Config; +use crate::features::Feature; use crate::truncate::approx_bytes_for_tokens; use tracing::warn; @@ -29,8 +27,11 @@ const GPT_5_1_CODEX_MAX_INSTRUCTIONS: &str = include_str!("../../gpt-5.1-codex-m const GPT_5_2_CODEX_INSTRUCTIONS: &str = include_str!("../../gpt-5.2-codex_prompt.md"); const GPT_5_2_CODEX_INSTRUCTIONS_TEMPLATE: &str = include_str!("../../templates/model_instructions/gpt-5.2-codex_instructions_template.md"); -const PERSONALITY_FRIENDLY: &str = include_str!("../../templates/personalities/friendly.md"); -const PERSONALITY_PRAGMATIC: &str = include_str!("../../templates/personalities/pragmatic.md"); + +const GPT_5_2_CODEX_PERSONALITY_FRIENDLY: &str = + include_str!("../../templates/personalities/gpt-5.2-codex_friendly.md"); +const GPT_5_2_CODEX_PERSONALITY_PRAGMATIC: &str = + include_str!("../../templates/personalities/gpt-5.2-codex_pragmatic.md"); pub(crate) const CONTEXT_WINDOW_272K: i64 = 272_000; @@ -54,7 +55,7 @@ macro_rules! model_info { priority: 99, upgrade: None, base_instructions: BASE_INSTRUCTIONS.to_string(), - model_instructions_template: None, + model_messages: None, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, @@ -100,8 +101,11 @@ pub(crate) fn with_config_overrides(mut model: ModelInfo, config: &Config) -> Mo if let Some(base_instructions) = &config.base_instructions { model.base_instructions = base_instructions.clone(); - model.model_instructions_template = None; + model.model_messages = None; + } else if !config.features.enabled(Feature::Personality) { + model.model_messages = None; } + model } @@ -169,15 +173,13 @@ pub(crate) fn find_model_info_for_slug(slug: &str) -> ModelInfo { model_info!( slug, base_instructions: GPT_5_2_CODEX_INSTRUCTIONS.to_string(), - model_instructions_template: Some(ModelInstructionsTemplate { - template: GPT_5_2_CODEX_INSTRUCTIONS_TEMPLATE.to_string(), - personality_messages: Some(PersonalityMessages(BTreeMap::from([( - Personality::Friendly, - PERSONALITY_FRIENDLY.to_string(), - ), ( - Personality::Pragmatic, - PERSONALITY_PRAGMATIC.to_string(), - )]))), + model_messages: Some(ModelMessages { + instructions_template: Some(GPT_5_2_CODEX_INSTRUCTIONS_TEMPLATE.to_string()), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: Some("".to_string()), + personality_friendly: Some(GPT_5_2_CODEX_PERSONALITY_FRIENDLY.to_string()), + personality_pragmatic: Some(GPT_5_2_CODEX_PERSONALITY_PRAGMATIC.to_string()), + }), }), apply_patch_tool_type: Some(ApplyPatchToolType::Freeform), shell_type: ConfigShellToolType::ShellCommand, @@ -213,15 +215,14 @@ pub(crate) fn find_model_info_for_slug(slug: &str) -> ModelInfo { truncation_policy: TruncationPolicyConfig::tokens(10_000), context_window: Some(CONTEXT_WINDOW_272K), supported_reasoning_levels: supported_reasoning_level_low_medium_high_xhigh(), - model_instructions_template: Some(ModelInstructionsTemplate { - template: GPT_5_2_CODEX_INSTRUCTIONS_TEMPLATE.to_string(), - personality_messages: Some(PersonalityMessages(BTreeMap::from([( - Personality::Friendly, - PERSONALITY_FRIENDLY.to_string(), - ), ( - Personality::Pragmatic, - PERSONALITY_PRAGMATIC.to_string(), - )]))), + base_instructions: GPT_5_2_CODEX_INSTRUCTIONS.to_string(), + model_messages: Some(ModelMessages { + instructions_template: Some(GPT_5_2_CODEX_INSTRUCTIONS_TEMPLATE.to_string()), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: Some("".to_string()), + personality_friendly: Some(GPT_5_2_CODEX_PERSONALITY_FRIENDLY.to_string()), + personality_pragmatic: Some(GPT_5_2_CODEX_PERSONALITY_PRAGMATIC.to_string()), + }), }), ) } else if slug.starts_with("gpt-5.1-codex-max") { diff --git a/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md b/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md index 6e9e53e361..530e825d5e 100644 --- a/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md +++ b/codex-rs/core/templates/model_instructions/gpt-5.2-codex_instructions_template.md @@ -1,8 +1,6 @@ You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals. -# Personality - -{{ personality_message }} +{{ personality }} ## Tone and style - Anything you say outside of tool use is shown to the user. Do not narrate abstractly; explain what you are doing and why, using plain language. diff --git a/codex-rs/core/templates/personalities/friendly.md b/codex-rs/core/templates/personalities/gpt-5.2-codex_friendly.md similarity index 100% rename from codex-rs/core/templates/personalities/friendly.md rename to codex-rs/core/templates/personalities/gpt-5.2-codex_friendly.md diff --git a/codex-rs/core/templates/personalities/pragmatic.md b/codex-rs/core/templates/personalities/gpt-5.2-codex_pragmatic.md similarity index 99% rename from codex-rs/core/templates/personalities/pragmatic.md rename to codex-rs/core/templates/personalities/gpt-5.2-codex_pragmatic.md index 0fd76898a6..ca1738e42a 100644 --- a/codex-rs/core/templates/personalities/pragmatic.md +++ b/codex-rs/core/templates/personalities/gpt-5.2-codex_pragmatic.md @@ -1,4 +1,5 @@ # Personality + You are a deeply pragmatic, effective software engineer. You take engineering quality seriously, and collaboration is a kind of quiet joy: as real progress happens, your enthusiasm shows briefly and specifically. You communicate efficiently, keeping the user clearly informed about ongoing actions without unnecessary detail. ## Values diff --git a/codex-rs/core/tests/suite/models_cache_ttl.rs b/codex-rs/core/tests/suite/models_cache_ttl.rs index 69506cffc5..5756f46a69 100644 --- a/codex-rs/core/tests/suite/models_cache_ttl.rs +++ b/codex-rs/core/tests/suite/models_cache_ttl.rs @@ -175,7 +175,7 @@ fn test_remote_model(slug: &str, priority: i32) -> ModelInfo { priority, upgrade: None, base_instructions: "base instructions".to_string(), - model_instructions_template: None, + model_messages: None, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index 7a27866569..79e0d36c68 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -9,10 +9,10 @@ use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; -use codex_protocol::openai_models::ModelInstructionsTemplate; +use codex_protocol::openai_models::ModelInstructionsVariables; +use codex_protocol::openai_models::ModelMessages; use codex_protocol::openai_models::ModelVisibility; use codex_protocol::openai_models::ModelsResponse; -use codex_protocol::openai_models::PersonalityMessages; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; use codex_protocol::openai_models::TruncationPolicyConfig; @@ -29,7 +29,6 @@ use core_test_support::skip_if_no_network; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use pretty_assertions::assert_eq; -use std::collections::BTreeMap; use std::sync::Arc; use tempfile::TempDir; use tokio::time::Duration; @@ -49,6 +48,7 @@ fn sse_completed(id: &str) -> String { async fn model_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.model_personality = Some(Personality::Friendly); let model_info = ModelsManager::construct_model_info_offline("gpt-5.1", &config); @@ -62,6 +62,7 @@ async fn model_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.model_personality = Some(Personality::Friendly); config.base_instructions = Some("override instructions".to_string()); @@ -80,7 +81,12 @@ async fn user_turn_personality_none_does_not_add_update_message() -> anyhow::Res let server = start_mock_server().await; let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await; - let mut builder = test_codex().with_model("gpt-5.2-codex"); + let mut builder = test_codex() + .with_model("gpt-5.2-codex") + .with_config(|config| { + config.features.disable(Feature::RemoteModels); + config.features.enable(Feature::Personality); + }); let test = builder.build(&server).await?; test.codex @@ -122,10 +128,11 @@ async fn config_personality_some_sets_instructions_template() -> anyhow::Result< let server = start_mock_server().await; let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await; let mut builder = test_codex() - .with_model("exp-codex-personality") + .with_model("gpt-5.2-codex") .with_config(|config| { - config.model_personality = Some(Personality::Friendly); config.features.disable(Feature::RemoteModels); + config.features.enable(Feature::Personality); + config.model_personality = Some(Personality::Friendly); }); let test = builder.build(&server).await?; @@ -182,6 +189,7 @@ async fn user_turn_personality_some_adds_update_message() -> anyhow::Result<()> .with_model("exp-codex-personality") .with_config(|config| { config.features.disable(Feature::RemoteModels); + config.features.enable(Feature::Personality); }); let test = builder.build(&server).await?; @@ -263,6 +271,330 @@ async fn user_turn_personality_some_adds_update_message() -> anyhow::Result<()> Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +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.model_personality = Some(Personality::Friendly); + + let model_info = ModelsManager::construct_model_info_offline("gpt-5.2-codex", &config); + assert_eq!( + model_info.get_model_instructions(config.model_personality), + model_info.base_instructions + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn user_turn_personality_skips_if_feature_disabled() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let resp_mock = mount_sse_sequence( + &server, + vec![sse_completed("resp-1"), sse_completed("resp-2")], + ) + .await; + let mut builder = test_codex() + .with_model("exp-codex-personality") + .with_config(|config| { + config.features.disable(Feature::RemoteModels); + config.features.disable(Feature::Personality); + }); + let test = builder.build(&server).await?; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: test.config.approval_policy.value(), + sandbox_policy: SandboxPolicy::ReadOnly, + model: test.session_configured.model.clone(), + effort: test.config.model_reasoning_effort, + summary: ReasoningSummary::Auto, + collaboration_mode: None, + personality: None, + }) + .await?; + + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + test.codex + .submit(Op::OverrideTurnContext { + cwd: None, + approval_policy: None, + sandbox_policy: None, + windows_sandbox_level: None, + model: None, + effort: None, + summary: None, + collaboration_mode: None, + personality: Some(Personality::Friendly), + }) + .await?; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: test.config.approval_policy.value(), + sandbox_policy: SandboxPolicy::ReadOnly, + model: test.session_configured.model.clone(), + effort: test.config.model_reasoning_effort, + summary: ReasoningSummary::Auto, + collaboration_mode: None, + personality: None, + }) + .await?; + + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let requests = resp_mock.requests(); + assert_eq!(requests.len(), 2, "expected two requests"); + let request = requests + .last() + .expect("expected personality update request"); + + let developer_texts = request.message_input_texts("developer"); + let personality_text = developer_texts + .iter() + .find(|text| text.contains("")); + assert!( + personality_text.is_none(), + "expected no personality preamble, got {personality_text:?}" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ignores_remote_model_personality_if_remote_models_disabled() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::builder() + .body_print_limit(BodyPrintLimit::Limited(80_000)) + .start() + .await; + + let remote_slug = "gpt-5.2-codex"; + let remote_personality_message = "Friendly from remote template"; + let remote_model = ModelInfo { + slug: remote_slug.to_string(), + display_name: "Remote personality test".to_string(), + description: Some("Remote model with personality template".to_string()), + default_reasoning_level: Some(ReasoningEffort::Medium), + supported_reasoning_levels: vec![ReasoningEffortPreset { + effort: ReasoningEffort::Medium, + description: ReasoningEffort::Medium.to_string(), + }], + shell_type: ConfigShellToolType::UnifiedExec, + visibility: ModelVisibility::List, + supported_in_api: true, + priority: 1, + upgrade: None, + base_instructions: "base instructions".to_string(), + model_messages: Some(ModelMessages { + instructions_template: Some( + "Base instructions\n{{ personality_message }}\n".to_string(), + ), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: None, + personality_friendly: Some(remote_personality_message.to_string()), + personality_pragmatic: None, + }), + }), + supports_reasoning_summaries: false, + support_verbosity: false, + default_verbosity: None, + apply_patch_tool_type: None, + truncation_policy: TruncationPolicyConfig::bytes(10_000), + supports_parallel_tool_calls: false, + context_window: Some(128_000), + auto_compact_token_limit: None, + effective_context_window_percent: 95, + experimental_supported_tools: Vec::new(), + }; + + let _models_mock = mount_models_once( + &server, + ModelsResponse { + models: vec![remote_model], + }, + ) + .await; + + let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await; + + let mut builder = test_codex() + .with_auth(codex_core::CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(|config| { + config.features.disable(Feature::RemoteModels); + config.features.enable(Feature::Personality); + config.model = Some(remote_slug.to_string()); + config.model_personality = Some(Personality::Friendly); + }); + let test = builder.build(&server).await?; + + wait_for_model_available( + &test.thread_manager.get_models_manager(), + remote_slug, + &test.config, + ) + .await; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::ReadOnly, + model: remote_slug.to_string(), + effort: test.config.model_reasoning_effort, + summary: ReasoningSummary::Auto, + collaboration_mode: None, + personality: None, + }) + .await?; + + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let request = resp_mock.single_request(); + let instructions_text = request.instructions_text(); + + assert!( + instructions_text.contains("You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals."), + "expected instructions to use the template instructions, got: {instructions_text:?}" + ); + assert!( + instructions_text.contains( + "You optimize for team morale and being a supportive teammate as much as code quality." + ), + "expected instructions to include the local friendly personality template, got: {instructions_text:?}" + ); + assert!( + !instructions_text.contains("{{ personality_message }}"), + "expected legacy personality placeholder to be replaced, got: {instructions_text:?}" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_model_default_personality_instructions_with_feature() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::builder() + .body_print_limit(BodyPrintLimit::Limited(80_000)) + .start() + .await; + + let remote_slug = "codex-remote-default-personality"; + let default_personality_message = "Default from remote template"; + let remote_model = ModelInfo { + slug: remote_slug.to_string(), + display_name: "Remote default personality test".to_string(), + description: Some("Remote model with default personality template".to_string()), + default_reasoning_level: Some(ReasoningEffort::Medium), + supported_reasoning_levels: vec![ReasoningEffortPreset { + effort: ReasoningEffort::Medium, + description: ReasoningEffort::Medium.to_string(), + }], + shell_type: ConfigShellToolType::UnifiedExec, + visibility: ModelVisibility::List, + supported_in_api: true, + priority: 1, + upgrade: None, + base_instructions: "base instructions".to_string(), + model_messages: Some(ModelMessages { + instructions_template: Some("Base instructions\n{{ personality }}\n".to_string()), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: Some(default_personality_message.to_string()), + personality_friendly: Some("Friendly variant".to_string()), + personality_pragmatic: Some("Pragmatic variant".to_string()), + }), + }), + supports_reasoning_summaries: false, + support_verbosity: false, + default_verbosity: None, + apply_patch_tool_type: None, + truncation_policy: TruncationPolicyConfig::bytes(10_000), + supports_parallel_tool_calls: false, + context_window: Some(128_000), + auto_compact_token_limit: None, + effective_context_window_percent: 95, + experimental_supported_tools: Vec::new(), + }; + + let _models_mock = mount_models_once( + &server, + ModelsResponse { + models: vec![remote_model], + }, + ) + .await; + + let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await; + + let mut builder = test_codex() + .with_auth(codex_core::CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(|config| { + config.features.enable(Feature::RemoteModels); + config.features.enable(Feature::Personality); + config.model = Some(remote_slug.to_string()); + }); + let test = builder.build(&server).await?; + + wait_for_model_available( + &test.thread_manager.get_models_manager(), + remote_slug, + &test.config, + ) + .await; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::ReadOnly, + model: remote_slug.to_string(), + effort: test.config.model_reasoning_effort, + summary: ReasoningSummary::Auto, + collaboration_mode: None, + personality: None, + }) + .await?; + + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let request = resp_mock.single_request(); + let instructions_text = request.instructions_text(); + + assert!( + instructions_text.contains(default_personality_message), + "expected instructions to include the remote default personality template, got: {instructions_text:?}" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn user_turn_personality_remote_model_template_includes_update_message() -> anyhow::Result<()> { @@ -290,12 +622,15 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - priority: 1, upgrade: None, base_instructions: "base instructions".to_string(), - model_instructions_template: Some(ModelInstructionsTemplate { - template: "Base instructions\n{{ personality_message }}\n".to_string(), - personality_messages: Some(PersonalityMessages(BTreeMap::from([( - Personality::Friendly, - remote_personality_message.to_string(), - )]))), + model_messages: Some(ModelMessages { + instructions_template: Some( + "Base instructions\n{{ personality_message }}\n".to_string(), + ), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: None, + personality_friendly: Some(remote_personality_message.to_string()), + personality_pragmatic: None, + }), }), supports_reasoning_summaries: false, support_verbosity: false, @@ -327,6 +662,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - .with_auth(codex_core::CodexAuth::create_dummy_chatgpt_auth_for_testing()) .with_config(|config| { config.features.enable(Feature::RemoteModels); + config.features.enable(Feature::Personality); config.model = Some("gpt-5.2-codex".to_string()); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index 71374cb84f..f59f73fd14 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -79,7 +79,7 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { priority: 1, upgrade: None, base_instructions: "base instructions".to_string(), - model_instructions_template: None, + model_messages: None, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, @@ -316,7 +316,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { priority: 1, upgrade: None, base_instructions: remote_base.to_string(), - model_instructions_template: None, + model_messages: None, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, @@ -790,7 +790,7 @@ fn test_remote_model_with_policy( priority, upgrade: None, base_instructions: "base instructions".to_string(), - model_instructions_template: None, + model_messages: None, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs index 3f29484ffd..9a940539d5 100644 --- a/codex-rs/protocol/src/openai_models.rs +++ b/codex-rs/protocol/src/openai_models.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; @@ -14,7 +13,7 @@ use ts_rs::TS; use crate::config_types::Personality; use crate::config_types::Verbosity; -const PERSONALITY_PLACEHOLDER: &str = "{{ personality_message }}"; +const PERSONALITY_PLACEHOLDER: &str = "{{ personality }}"; /// See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning #[derive( @@ -189,7 +188,7 @@ pub struct ModelInfo { pub upgrade: Option, pub base_instructions: String, #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_instructions_template: Option, + pub model_messages: Option, pub supports_reasoning_summaries: bool, pub support_verbosity: bool, pub default_verbosity: Option, @@ -218,26 +217,25 @@ impl ModelInfo { } pub fn supports_personality(&self) -> bool { - self.model_instructions_template + self.model_messages .as_ref() - .is_some_and(ModelInstructionsTemplate::supports_personality) + .is_some_and(ModelMessages::supports_personality) } pub fn get_model_instructions(&self, personality: Option) -> String { - if let Some(personality) = personality - && let Some(template) = &self.model_instructions_template - && template.has_personality_placeholder() - && let Some(personality_messages) = &template.personality_messages - && let Some(personality_message) = personality_messages.0.get(&personality) + if let Some(model_messages) = &self.model_messages + && let Some(template) = &model_messages.instructions_template { - template - .template - .replace(PERSONALITY_PLACEHOLDER, personality_message.as_str()) + // if we have a template, always use it + let personality_message = model_messages + .get_personality_message(personality) + .unwrap_or_default(); + template.replace(PERSONALITY_PLACEHOLDER, personality_message.as_str()) } else if let Some(personality) = personality { warn!( model = %self.slug, %personality, - "Model personality requested but model_instructions_template is invalid, falling back to base instructions." + "Model personality requested but model_messages is missing, falling back to base instructions." ); self.base_instructions.clone() } else { @@ -246,31 +244,62 @@ impl ModelInfo { } } -/// A strongly-typed template for assembling model instructions. If populated and valid, will override -/// base_instructions. +/// A strongly-typed template for assembling model instructions and developer messages. If +/// instructions_* is populated and valid, it will override base_instructions. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)] -pub struct ModelInstructionsTemplate { - pub template: String, - pub personality_messages: Option, +pub struct ModelMessages { + pub instructions_template: Option, + pub instructions_variables: Option, } -impl ModelInstructionsTemplate { +impl ModelMessages { fn has_personality_placeholder(&self) -> bool { - self.template.contains(PERSONALITY_PLACEHOLDER) + self.instructions_template + .as_ref() + .map(|spec| spec.contains(PERSONALITY_PLACEHOLDER)) + .unwrap_or(false) } fn supports_personality(&self) -> bool { self.has_personality_placeholder() - && self.personality_messages.as_ref().is_some_and(|messages| { - Personality::iter().all(|personality| messages.0.contains_key(&personality)) - }) + && self + .instructions_variables + .as_ref() + .is_some_and(ModelInstructionsVariables::is_complete) + } + + pub fn get_personality_message(&self, personality: Option) -> Option { + self.instructions_variables + .as_ref() + .and_then(|variables| variables.get_personality_message(personality)) } } -// serializes as a dictionary from personality to message -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, TS, JsonSchema)] -#[serde(transparent)] -pub struct PersonalityMessages(pub BTreeMap); +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)] +pub struct ModelInstructionsVariables { + pub personality_default: Option, + pub personality_friendly: Option, + pub personality_pragmatic: Option, +} + +impl ModelInstructionsVariables { + pub fn is_complete(&self) -> bool { + self.personality_default.is_some() + && self.personality_friendly.is_some() + && self.personality_pragmatic.is_some() + } + + pub fn get_personality_message(&self, personality: Option) -> Option { + if let Some(personality) = personality { + match personality { + Personality::Friendly => self.personality_friendly.clone(), + Personality::Pragmatic => self.personality_pragmatic.clone(), + } + } else { + self.personality_default.clone() + } + } +} #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)] pub struct ModelInfoUpgrade { @@ -407,7 +436,7 @@ mod tests { use super::*; use pretty_assertions::assert_eq; - fn test_model(template: Option) -> ModelInfo { + fn test_model(spec: Option) -> ModelInfo { ModelInfo { slug: "test-model".to_string(), display_name: "Test Model".to_string(), @@ -420,7 +449,7 @@ mod tests { priority: 1, upgrade: None, base_instructions: "base".to_string(), - model_instructions_template: template, + model_messages: spec, supports_reasoning_summaries: false, support_verbosity: false, default_verbosity: None, @@ -434,18 +463,19 @@ mod tests { } } - fn personality_messages() -> PersonalityMessages { - PersonalityMessages(BTreeMap::from([( - Personality::Friendly, - "friendly".to_string(), - )])) + fn personality_variables() -> ModelInstructionsVariables { + ModelInstructionsVariables { + personality_default: Some("default".to_string()), + personality_friendly: Some("friendly".to_string()), + personality_pragmatic: Some("pragmatic".to_string()), + } } #[test] fn get_model_instructions_uses_template_when_placeholder_present() { - let model = test_model(Some(ModelInstructionsTemplate { - template: "Hello {{ personality_message }}".to_string(), - personality_messages: Some(personality_messages()), + let model = test_model(Some(ModelMessages { + instructions_template: Some("Hello {{ personality }}".to_string()), + instructions_variables: Some(personality_variables()), })); let instructions = model.get_model_instructions(Some(Personality::Friendly)); @@ -454,14 +484,116 @@ mod tests { } #[test] - fn get_model_instructions_falls_back_when_placeholder_missing() { - let model = test_model(Some(ModelInstructionsTemplate { - template: "Hello there".to_string(), - personality_messages: Some(personality_messages()), + fn get_model_instructions_always_strips_placeholder() { + let model = test_model(Some(ModelMessages { + instructions_template: Some("Hello\n{{ personality }}".to_string()), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: None, + personality_friendly: Some("friendly".to_string()), + personality_pragmatic: None, + }), + })); + assert_eq!( + model.get_model_instructions(Some(Personality::Friendly)), + "Hello\nfriendly" + ); + assert_eq!( + model.get_model_instructions(Some(Personality::Pragmatic)), + "Hello\n" + ); + assert_eq!(model.get_model_instructions(None), "Hello\n"); + + let model_no_personality = test_model(Some(ModelMessages { + instructions_template: Some("Hello\n{{ personality }}".to_string()), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: None, + personality_friendly: None, + personality_pragmatic: None, + }), + })); + assert_eq!( + model_no_personality.get_model_instructions(Some(Personality::Friendly)), + "Hello\n" + ); + assert_eq!( + model_no_personality.get_model_instructions(Some(Personality::Pragmatic)), + "Hello\n" + ); + assert_eq!(model_no_personality.get_model_instructions(None), "Hello\n"); + } + + #[test] + fn get_model_instructions_falls_back_when_template_is_missing() { + let model = test_model(Some(ModelMessages { + instructions_template: None, + instructions_variables: Some(ModelInstructionsVariables { + personality_default: None, + personality_friendly: None, + personality_pragmatic: None, + }), })); let instructions = model.get_model_instructions(Some(Personality::Friendly)); assert_eq!(instructions, "base"); } + + #[test] + fn get_personality_message_returns_default_when_personality_is_none() { + let personality_template = personality_variables(); + assert_eq!( + personality_template.get_personality_message(None), + Some("default".to_string()) + ); + } + + #[test] + fn get_personality_message() { + let personality_variables = personality_variables(); + assert_eq!( + personality_variables.get_personality_message(Some(Personality::Friendly)), + Some("friendly".to_string()) + ); + assert_eq!( + personality_variables.get_personality_message(Some(Personality::Pragmatic)), + Some("pragmatic".to_string()) + ); + assert_eq!( + personality_variables.get_personality_message(None), + Some("default".to_string()) + ); + + let personality_variables = ModelInstructionsVariables { + personality_default: Some("default".to_string()), + personality_friendly: None, + personality_pragmatic: None, + }; + assert_eq!( + personality_variables.get_personality_message(Some(Personality::Friendly)), + None + ); + assert_eq!( + personality_variables.get_personality_message(Some(Personality::Pragmatic)), + None + ); + assert_eq!( + personality_variables.get_personality_message(None), + Some("default".to_string()) + ); + + let personality_variables = ModelInstructionsVariables { + personality_default: None, + personality_friendly: Some("friendly".to_string()), + personality_pragmatic: Some("pragmatic".to_string()), + }; + assert_eq!( + personality_variables.get_personality_message(Some(Personality::Friendly)), + Some("friendly".to_string()) + ); + assert_eq!( + personality_variables.get_personality_message(Some(Personality::Pragmatic)), + Some("pragmatic".to_string()) + ); + assert_eq!(personality_variables.get_personality_message(None), None); + } } From 34f89b12d038d330f1e8306dbe9e1727b32f09c0 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Thu, 29 Jan 2026 23:40:32 -0800 Subject: [PATCH 091/116] MCP tool call approval (simplified version) (#10200) Add elicitation approval request for MCP tool call requests. --- codex-rs/chatgpt/src/connectors.rs | 6 +- codex-rs/core/src/mcp_connection_manager.rs | 49 ++- codex-rs/core/src/mcp_tool_call.rs | 317 +++++++++++++++++++- codex-rs/core/src/tools/handlers/mcp.rs | 3 +- 4 files changed, 364 insertions(+), 11 deletions(-) diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index c1a8f65359..83b7271583 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -221,7 +221,11 @@ fn normalize_connector_value(value: Option<&str>) -> Option { } const ALLOWED_APPS_SDK_APPS: &[&str] = &["asdk_app_69781557cc1481919cf5e9824fa2e792"]; -const DISALLOWED_CONNECTOR_IDS: &[&str] = &["asdk_app_6938a94a61d881918ef32cb999ff937c"]; +const DISALLOWED_CONNECTOR_IDS: &[&str] = &[ + "asdk_app_6938a94a61d881918ef32cb999ff937c", + "connector_2b0a9009c9c64bf9933a3dae3f2b1254", + "connector_68de829bf7648191acd70a907364c67c", +]; const DISALLOWED_CONNECTOR_PREFIX: &str = "connector_openai_"; fn filter_disallowed_connectors(connectors: Vec) -> Vec { diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 15305f4b0c..1b5048ab0c 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -769,6 +769,32 @@ fn filter_tools(tools: Vec, filter: ToolFilter) -> Vec { .collect() } +fn normalize_codex_apps_tool_title( + server_name: &str, + connector_name: Option<&str>, + value: &str, +) -> String { + if server_name != CODEX_APPS_MCP_SERVER_NAME { + return value.to_string(); + } + + let Some(connector_name) = connector_name + .map(str::trim) + .filter(|name| !name.is_empty()) + else { + return value.to_string(); + }; + + let prefix = format!("{connector_name}_"); + if let Some(stripped) = value.strip_prefix(&prefix) + && !stripped.is_empty() + { + return stripped.to_string(); + } + + value.to_string() +} + fn resolve_bearer_token( server_name: &str, bearer_token_env_var: Option<&str>, @@ -926,12 +952,23 @@ async fn list_tools_for_client( Ok(resp .tools .into_iter() - .map(|tool| ToolInfo { - server_name: server_name.to_owned(), - tool_name: tool.tool.name.clone(), - tool: tool.tool, - connector_id: tool.connector_id, - connector_name: tool.connector_name, + .map(|tool| { + let connector_name = tool.connector_name; + let mut tool_def = tool.tool; + if let Some(title) = tool_def.title.as_deref() { + let normalized_title = + normalize_codex_apps_tool_title(server_name, connector_name.as_deref(), title); + if tool_def.title.as_deref() != Some(normalized_title.as_str()) { + tool_def.title = Some(normalized_title); + } + } + ToolInfo { + server_name: server_name.to_owned(), + tool_name: tool_def.name.clone(), + tool: tool_def, + connector_id: tool.connector_id, + connector_name, + } }) .collect()) } diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 6066c1512e..6425392fb5 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1,20 +1,30 @@ +use std::time::Duration; use std::time::Instant; use tracing::error; use crate::codex::Session; use crate::codex::TurnContext; +use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::protocol::EventMsg; use crate::protocol::McpInvocation; use crate::protocol::McpToolCallBeginEvent; use crate::protocol::McpToolCallEndEvent; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::request_user_input::RequestUserInputArgs; +use codex_protocol::request_user_input::RequestUserInputQuestion; +use codex_protocol::request_user_input::RequestUserInputQuestionOption; +use codex_protocol::request_user_input::RequestUserInputResponse; +use mcp_types::ToolAnnotations; +use std::sync::Arc; /// Handles the specified tool call dispatches the appropriate /// `McpToolCallBegin` and `McpToolCallEnd` events to the `Session`. pub(crate) async fn handle_mcp_tool_call( - sess: &Session, + sess: Arc, turn_context: &TurnContext, call_id: String, server: String, @@ -48,11 +58,79 @@ 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 result = match decision { + McpToolApprovalDecision::Accept => { + let tool_call_begin_event = EventMsg::McpToolCallBegin(McpToolCallBeginEvent { + call_id: call_id.clone(), + invocation: invocation.clone(), + }); + notify_mcp_tool_call_event(sess.as_ref(), turn_context, tool_call_begin_event) + .await; + + let start = Instant::now(); + let result = sess + .call_tool(&server, &tool_name, arguments_value.clone()) + .await + .map_err(|e| format!("tool call error: {e:?}")); + if let Err(e) = &result { + tracing::warn!("MCP tool call error: {e:?}"); + } + let tool_call_end_event = EventMsg::McpToolCallEnd(McpToolCallEndEvent { + call_id: call_id.clone(), + invocation, + duration: start.elapsed(), + result: result.clone(), + }); + notify_mcp_tool_call_event( + sess.as_ref(), + turn_context, + tool_call_end_event.clone(), + ) + .await; + result + } + McpToolApprovalDecision::Decline => { + let message = "user rejected MCP tool call".to_string(); + notify_mcp_tool_call_skip( + sess.as_ref(), + turn_context, + &call_id, + invocation, + message, + ) + .await + } + McpToolApprovalDecision::Cancel => { + let message = "user cancelled MCP tool call".to_string(); + notify_mcp_tool_call_skip( + sess.as_ref(), + turn_context, + &call_id, + invocation, + message, + ) + .await + } + }; + + let status = if result.is_ok() { "ok" } else { "error" }; + turn_context + .client + .get_otel_manager() + .counter("codex.mcp.call", 1, &[("status", status)]); + + return ResponseInputItem::McpToolCallOutput { call_id, result }; + } + let tool_call_begin_event = EventMsg::McpToolCallBegin(McpToolCallBeginEvent { call_id: call_id.clone(), invocation: invocation.clone(), }); - notify_mcp_tool_call_event(sess, turn_context, tool_call_begin_event).await; + notify_mcp_tool_call_event(sess.as_ref(), turn_context, tool_call_begin_event).await; let start = Instant::now(); // Perform the tool call. @@ -70,7 +148,7 @@ pub(crate) async fn handle_mcp_tool_call( result: result.clone(), }); - notify_mcp_tool_call_event(sess, turn_context, tool_call_end_event.clone()).await; + notify_mcp_tool_call_event(sess.as_ref(), turn_context, tool_call_end_event.clone()).await; let status = if result.is_ok() { "ok" } else { "error" }; turn_context @@ -84,3 +162,236 @@ pub(crate) async fn handle_mcp_tool_call( async fn notify_mcp_tool_call_event(sess: &Session, turn_context: &TurnContext, event: EventMsg) { sess.send_event(turn_context, event).await; } + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum McpToolApprovalDecision { + Accept, + Decline, + Cancel, +} + +struct McpToolApprovalMetadata { + annotations: ToolAnnotations, + connector_name: Option, + tool_title: Option, +} + +const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval"; +const MCP_TOOL_APPROVAL_ACCEPT: &str = "Accept"; +const MCP_TOOL_APPROVAL_DECLINE: &str = "Decline"; +const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; + +async fn maybe_request_mcp_tool_approval( + sess: &Session, + turn_context: &TurnContext, + call_id: &str, + server: &str, + tool_name: &str, +) -> Option { + if is_full_access_mode(turn_context) { + return None; + } + if server != CODEX_APPS_MCP_SERVER_NAME { + return None; + } + + let metadata = lookup_mcp_tool_metadata(sess, server, tool_name).await?; + if !requires_mcp_tool_approval(&metadata.annotations) { + return None; + } + + let question_id = format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}"); + let question = build_mcp_tool_approval_question( + question_id.clone(), + tool_name, + metadata.tool_title.as_deref(), + metadata.connector_name.as_deref(), + &metadata.annotations, + ); + let args = RequestUserInputArgs { + questions: vec![question], + }; + let response = sess + .request_user_input(turn_context, call_id.to_string(), args) + .await; + Some(parse_mcp_tool_approval_response(response, &question_id)) +} + +fn is_full_access_mode(turn_context: &TurnContext) -> bool { + matches!(turn_context.approval_policy, AskForApproval::Never) + && matches!( + turn_context.sandbox_policy, + SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } + ) +} + +async fn lookup_mcp_tool_metadata( + sess: &Session, + server: &str, + tool_name: &str, +) -> Option { + let tools = sess + .services + .mcp_connection_manager + .read() + .await + .list_all_tools() + .await; + + 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_name: tool_info.connector_name, + tool_title: tool_info.tool.title, + }) + } else { + None + } + }) +} + +fn build_mcp_tool_approval_question( + question_id: String, + tool_name: &str, + tool_title: Option<&str>, + connector_name: Option<&str>, + annotations: &ToolAnnotations, +) -> RequestUserInputQuestion { + let destructive = annotations.destructive_hint == Some(true); + let open_world = 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", + (false, true) => "may access external systems", + (false, false) => "may have side effects", + }; + + let tool_label = tool_title.unwrap_or(tool_name); + let app_label = connector_name + .map(|name| format!("The {name} app")) + .unwrap_or_else(|| "This app".to_string()); + let question = format!( + "{app_label} wants to run the tool \"{tool_label}\", which {reason}. Allow this action?" + ); + + RequestUserInputQuestion { + id: question_id, + header: "Approve app tool call?".to_string(), + question, + is_other: false, + is_secret: false, + options: Some(vec![ + RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT.to_string(), + description: "Run the tool and continue.".to_string(), + }, + RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_DECLINE.to_string(), + description: "Decline this tool call and continue.".to_string(), + }, + RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_CANCEL.to_string(), + description: "Cancel this tool call".to_string(), + }, + ]), + } +} + +fn parse_mcp_tool_approval_response( + response: Option, + question_id: &str, +) -> McpToolApprovalDecision { + let Some(response) = response else { + return McpToolApprovalDecision::Cancel; + }; + let answers = response + .answers + .get(question_id) + .map(|answer| answer.answers.as_slice()); + let Some(answers) = answers else { + return McpToolApprovalDecision::Cancel; + }; + if answers + .iter() + .any(|answer| answer == MCP_TOOL_APPROVAL_ACCEPT) + { + McpToolApprovalDecision::Accept + } else if answers + .iter() + .any(|answer| answer == MCP_TOOL_APPROVAL_CANCEL) + { + McpToolApprovalDecision::Cancel + } else { + McpToolApprovalDecision::Decline + } +} + +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)) +} + +async fn notify_mcp_tool_call_skip( + sess: &Session, + turn_context: &TurnContext, + call_id: &str, + invocation: McpInvocation, + message: String, +) -> Result { + let tool_call_begin_event = EventMsg::McpToolCallBegin(McpToolCallBeginEvent { + call_id: call_id.to_string(), + invocation: invocation.clone(), + }); + notify_mcp_tool_call_event(sess, turn_context, tool_call_begin_event).await; + + let tool_call_end_event = EventMsg::McpToolCallEnd(McpToolCallEndEvent { + call_id: call_id.to_string(), + invocation, + duration: Duration::ZERO, + result: Err(message.clone()), + }); + notify_mcp_tool_call_event(sess, turn_context, tool_call_end_event).await; + Err(message) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + fn annotations( + read_only: Option, + destructive: Option, + open_world: Option, + ) -> ToolAnnotations { + ToolAnnotations { + destructive_hint: destructive, + idempotent_hint: None, + open_world_hint: open_world, + read_only_hint: read_only, + title: None, + } + } + + #[test] + fn approval_required_when_read_only_false_and_destructive() { + let annotations = annotations(Some(false), Some(true), None); + assert_eq!(requires_mcp_tool_approval(&annotations), true); + } + + #[test] + fn approval_required_when_read_only_false_and_open_world() { + let annotations = annotations(Some(false), None, Some(true)); + assert_eq!(requires_mcp_tool_approval(&annotations), true); + } + + #[test] + fn approval_not_required_when_read_only_true() { + let annotations = annotations(Some(true), Some(true), Some(true)); + assert_eq!(requires_mcp_tool_approval(&annotations), false); + } +} diff --git a/codex-rs/core/src/tools/handlers/mcp.rs b/codex-rs/core/src/tools/handlers/mcp.rs index 9798fb8241..5138b3cd0d 100644 --- a/codex-rs/core/src/tools/handlers/mcp.rs +++ b/codex-rs/core/src/tools/handlers/mcp.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use std::sync::Arc; use crate::function_tool::FunctionCallError; use crate::mcp_tool_call::handle_mcp_tool_call; @@ -42,7 +43,7 @@ impl ToolHandler for McpHandler { let arguments_str = raw_arguments; let response = handle_mcp_tool_call( - session.as_ref(), + Arc::clone(&session), turn.as_ref(), call_id.clone(), server, From a270a28a063ec3989c7421d1db1d200ac3e5faa5 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 09:00:44 +0100 Subject: [PATCH 092/116] feat: add output to `/ps` (#10154) Screenshot 2026-01-29 at 13 24 57 --- codex-rs/tui/src/chatwidget.rs | 39 ++++++++- codex-rs/tui/src/chatwidget/tests.rs | 2 + codex-rs/tui/src/history_cell.rs | 82 ++++++++++++++++--- ...put_chunk_leading_whitespace_snapshot.snap | 11 +++ ...ests__ps_output_long_command_snapshot.snap | 1 + ...__tests__ps_output_multiline_snapshot.snap | 3 + 6 files changed, 127 insertions(+), 11 deletions(-) create mode 100644 codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_chunk_leading_whitespace_snapshot.snap diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 2833d4863e..9857956ed9 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -225,7 +225,9 @@ struct RunningCommand { struct UnifiedExecProcessSummary { key: String, + call_id: String, command_display: String, + recent_chunks: Vec, } struct UnifiedExecWaitState { @@ -1426,6 +1428,8 @@ impl ChatWidget { } fn on_exec_command_output_delta(&mut self, ev: ExecCommandOutputDeltaEvent) { + self.track_unified_exec_output_chunk(&ev.call_id, &ev.chunk); + let Some(cell) = self .active_cell .as_mut() @@ -1545,11 +1549,15 @@ impl ChatWidget { .iter_mut() .find(|process| process.key == key) { + existing.call_id = ev.call_id.clone(); existing.command_display = command_display; + existing.recent_chunks.clear(); } else { self.unified_exec_processes.push(UnifiedExecProcessSummary { key, + call_id: ev.call_id.clone(), command_display, + recent_chunks: Vec::new(), }); } self.sync_unified_exec_footer(); @@ -1574,6 +1582,32 @@ impl ChatWidget { self.bottom_pane.set_unified_exec_processes(processes); } + /// Record recent stdout/stderr lines for the unified exec footer. + fn track_unified_exec_output_chunk(&mut self, call_id: &str, chunk: &[u8]) { + let Some(process) = self + .unified_exec_processes + .iter_mut() + .find(|process| process.call_id == call_id) + else { + return; + }; + + let text = String::from_utf8_lossy(chunk); + for line in text + .lines() + .map(str::trim_end) + .filter(|line| !line.is_empty()) + { + process.recent_chunks.push(line.to_string()); + } + + const MAX_RECENT_CHUNKS: usize = 3; + if process.recent_chunks.len() > MAX_RECENT_CHUNKS { + let drop_count = process.recent_chunks.len() - MAX_RECENT_CHUNKS; + process.recent_chunks.drain(0..drop_count); + } + } + fn clear_unified_exec_processes(&mut self) { if self.unified_exec_processes.is_empty() { return; @@ -3448,7 +3482,10 @@ impl ChatWidget { let processes = self .unified_exec_processes .iter() - .map(|process| process.command_display.clone()) + .map(|process| history_cell::UnifiedExecProcessDetails { + command_display: process.command_display.clone(), + recent_chunks: process.recent_chunks.clone(), + }) .collect(); self.add_to_history(history_cell::new_unified_exec_processes_output(processes)); } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index a0e8269b58..144fc199c5 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -2025,7 +2025,9 @@ async fn unified_exec_wait_status_header_updates_on_late_command_display() { chat.on_task_started(); chat.unified_exec_processes.push(UnifiedExecProcessSummary { key: "proc-1".to_string(), + call_id: "call-1".to_string(), command_display: "sleep 5".to_string(), + recent_chunks: Vec::new(), }); chat.on_terminal_interaction(TerminalInteractionEvent { diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 687d18fa6a..1f19c929a2 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -558,15 +558,21 @@ pub(crate) fn new_unified_exec_interaction( #[derive(Debug)] struct UnifiedExecProcessesCell { - processes: Vec, + processes: Vec, } impl UnifiedExecProcessesCell { - fn new(processes: Vec) -> Self { + fn new(processes: Vec) -> Self { Self { processes } } } +#[derive(Debug, Clone)] +pub(crate) struct UnifiedExecProcessDetails { + pub(crate) command_display: String, + pub(crate) recent_chunks: Vec, +} + impl HistoryCell for UnifiedExecProcessesCell { fn display_lines(&self, width: u16) -> Vec> { if width == 0 { @@ -589,10 +595,11 @@ impl HistoryCell for UnifiedExecProcessesCell { let truncation_suffix = " [...]"; let truncation_suffix_width = UnicodeWidthStr::width(truncation_suffix); let mut shown = 0usize; - for command in &self.processes { + for process in &self.processes { if shown >= max_processes { break; } + let command = &process.command_display; let (snippet, snippet_truncated) = { let (first_line, has_more_lines) = match command.split_once('\n') { Some((first, _)) => (first, true), @@ -627,6 +634,32 @@ impl HistoryCell for UnifiedExecProcessesCell { let (truncated, _, _) = take_prefix_by_width(&snippet, budget); out.push(vec![prefix.dim(), truncated.cyan()].into()); } + + let chunk_prefix_first = " ↳ "; + let chunk_prefix_next = " "; + for (idx, chunk) in process.recent_chunks.iter().enumerate() { + let chunk_prefix = if idx == 0 { + chunk_prefix_first + } else { + chunk_prefix_next + }; + let chunk_prefix_width = UnicodeWidthStr::width(chunk_prefix); + if wrap_width <= chunk_prefix_width { + out.push(Line::from(chunk_prefix.dim())); + continue; + } + let budget = wrap_width.saturating_sub(chunk_prefix_width); + let (truncated, remainder, _) = take_prefix_by_width(chunk, budget); + if !remainder.is_empty() && budget > truncation_suffix_width { + let available = budget.saturating_sub(truncation_suffix_width); + let (shorter, _, _) = take_prefix_by_width(chunk, available); + out.push( + vec![chunk_prefix.dim(), shorter.dim(), truncation_suffix.dim()].into(), + ); + } else { + out.push(vec![chunk_prefix.dim(), truncated.dim()].into()); + } + } shown += 1; } @@ -650,7 +683,9 @@ impl HistoryCell for UnifiedExecProcessesCell { } } -pub(crate) fn new_unified_exec_processes_output(processes: Vec) -> CompositeHistoryCell { +pub(crate) fn new_unified_exec_processes_output( + processes: Vec, +) -> CompositeHistoryCell { let command = PlainHistoryCell::new(vec!["/ps".magenta().into()]); let summary = UnifiedExecProcessesCell::new(processes); CompositeHistoryCell::new(vec![Box::new(command), Box::new(summary)]) @@ -2022,8 +2057,14 @@ mod tests { #[test] fn ps_output_multiline_snapshot() { let cell = new_unified_exec_processes_output(vec![ - "echo hello\nand then some extra text".to_string(), - "rg \"foo\" src".to_string(), + UnifiedExecProcessDetails { + command_display: "echo hello\nand then some extra text".to_string(), + recent_chunks: vec!["hello".to_string(), "done".to_string()], + }, + UnifiedExecProcessDetails { + command_display: "rg \"foo\" src".to_string(), + recent_chunks: vec!["src/main.rs:12:foo".to_string()], + }, ]); let rendered = render_lines(&cell.display_lines(40)).join("\n"); insta::assert_snapshot!(rendered); @@ -2031,9 +2072,12 @@ mod tests { #[test] fn ps_output_long_command_snapshot() { - let cell = new_unified_exec_processes_output(vec![String::from( - "rg \"foo\" src --glob '**/*.rs' --max-count 1000 --no-ignore --hidden --follow --glob '!target/**'", - )]); + let cell = new_unified_exec_processes_output(vec![UnifiedExecProcessDetails { + command_display: String::from( + "rg \"foo\" src --glob '**/*.rs' --max-count 1000 --no-ignore --hidden --follow --glob '!target/**'", + ), + recent_chunks: vec!["searching...".to_string()], + }]); let rendered = render_lines(&cell.display_lines(36)).join("\n"); insta::assert_snapshot!(rendered); } @@ -2041,12 +2085,30 @@ mod tests { #[test] fn ps_output_many_sessions_snapshot() { let cell = new_unified_exec_processes_output( - (0..20).map(|idx| format!("command {idx}")).collect(), + (0..20) + .map(|idx| UnifiedExecProcessDetails { + command_display: format!("command {idx}"), + recent_chunks: Vec::new(), + }) + .collect(), ); let rendered = render_lines(&cell.display_lines(32)).join("\n"); insta::assert_snapshot!(rendered); } + #[test] + fn ps_output_chunk_leading_whitespace_snapshot() { + let cell = new_unified_exec_processes_output(vec![UnifiedExecProcessDetails { + command_display: "just fix".to_string(), + recent_chunks: vec![ + " indented first".to_string(), + " more indented".to_string(), + ], + }]); + let rendered = render_lines(&cell.display_lines(60)).join("\n"); + insta::assert_snapshot!(rendered); + } + #[tokio::test] async fn mcp_tools_output_masks_sensitive_values() { let mut config = test_config().await; diff --git a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_chunk_leading_whitespace_snapshot.snap b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_chunk_leading_whitespace_snapshot.snap new file mode 100644 index 0000000000..e13dcf0a1e --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_chunk_leading_whitespace_snapshot.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/history_cell.rs +expression: rendered +--- +/ps + +Background terminals + + • just fix + ↳ indented first + more indented diff --git a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_long_command_snapshot.snap b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_long_command_snapshot.snap index b9302295d3..2bd4bf9fb9 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_long_command_snapshot.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_long_command_snapshot.snap @@ -7,3 +7,4 @@ expression: rendered Background terminals • rg "foo" src --glob '**/*. [...] + ↳ searching... diff --git a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_multiline_snapshot.snap b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_multiline_snapshot.snap index c073349e8f..0e31eddfa0 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_multiline_snapshot.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__ps_output_multiline_snapshot.snap @@ -7,4 +7,7 @@ expression: rendered Background terminals • echo hello [...] + ↳ hello + done • rg "foo" src + ↳ src/main.rs:12:foo From f8056e62d4ee6063af909dc956f67ec509e0c3cd Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 10:02:46 +0100 Subject: [PATCH 093/116] nit: actually run tests (#10217) --- codex-rs/core/tests/suite/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index 0744624a92..defc704353 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -73,6 +73,7 @@ mod tool_harness; mod tool_parallelism; mod tools; mod truncation; +mod turn_state; mod undo; mod unified_exec; mod unstable_features_warning; From c0cad80668d8bc94085d8a59da31255d3550c16c Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Fri, 30 Jan 2026 01:14:15 -0800 Subject: [PATCH 094/116] Add community links to startup tooltips (#10177) ## Summary - add startup tooltip for OpenAI community Discord - add startup tooltip for Codex community forum ## Testing - not run (text-only tooltip change) --- codex-rs/tui/tooltips.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/codex-rs/tui/tooltips.txt b/codex-rs/tui/tooltips.txt index 455ae5cd03..84a96f54d0 100644 --- a/codex-rs/tui/tooltips.txt +++ b/codex-rs/tui/tooltips.txt @@ -10,6 +10,8 @@ Use /fork to branch the current chat into a new thread. Use /init to create an AGENTS.md with project-specific guidance. Use /mcp to list configured MCP tools. Use the OpenAI docs MCP for API questions; enable it with `codex mcp add openaiDeveloperDocs --url https://developers.openai.com/mcp`. +Join the OpenAI community Discord: http://discord.gg/openai +Visit the Codex community forum: https://community.openai.com/c/codex/37 You can run any shell command from Codex using `!` (e.g. `!ls`) Type / to open the command popup; Tab autocompletes slash commands. When the composer is empty, press Esc to step back and edit your last message; Enter confirms. From a0ccef9d5c44b7517243163ceb64be8223d5d8d5 Mon Sep 17 00:00:00 2001 From: Shijie Rao Date: Fri, 30 Jan 2026 01:19:24 -0800 Subject: [PATCH 095/116] Chore: plan mode do not include free form question and always include isOther (#10210) We should never ask a freeform question when planning and we should always include isOther as an escape hatch. --- codex-rs/app-server-protocol/src/protocol/v2.rs | 2 +- codex-rs/app-server/tests/common/responses.rs | 1 - .../core/src/tools/handlers/request_user_input.rs | 14 +++++++++++++- codex-rs/core/src/tools/spec.rs | 13 ++----------- codex-rs/core/tests/suite/request_user_input.rs | 3 +-- codex-rs/docs/protocol_v1.md | 2 +- 6 files changed, 18 insertions(+), 17 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index ac3df37bd0..1e28b1b086 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2593,7 +2593,7 @@ pub struct ToolRequestUserInputOption { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] -/// EXPERIMENTAL. Represents one request_user_input question and its optional options. +/// EXPERIMENTAL. Represents one request_user_input question and its required options. pub struct ToolRequestUserInputQuestion { pub id: String, pub header: String, diff --git a/codex-rs/app-server/tests/common/responses.rs b/codex-rs/app-server/tests/common/responses.rs index 2a5b5d2159..e15319e02f 100644 --- a/codex-rs/app-server/tests/common/responses.rs +++ b/codex-rs/app-server/tests/common/responses.rs @@ -67,7 +67,6 @@ pub fn create_request_user_input_sse_response(call_id: &str) -> anyhow::Result ToolSpec { let options_schema = JsonSchema::Array { description: Some( - "Optional 2-3 mutually exclusive choices. Put the recommended option first and suffix its label with \"(Recommended)\". Do not include an \"Other\" option in this list; use isOther on the question to request a free form choice. If the question is free form in nature, please do not have any option." + "Provide 2-3 mutually exclusive choices. Put the recommended option first and suffix its label with \"(Recommended)\". Do not include an \"Other\" option in this list; the client will add a free-form \"Other\" option automatically." .to_string(), ), items: Box::new(JsonSchema::Object { @@ -602,15 +602,6 @@ fn create_request_user_input_tool() -> ToolSpec { description: Some("Single-sentence prompt shown to the user.".to_string()), }, ); - question_props.insert( - "isOther".to_string(), - JsonSchema::Boolean { - description: Some( - "True when this question should include a free-form \"Other\" option. Otherwise false." - .to_string(), - ), - }, - ); question_props.insert("options".to_string(), options_schema); let questions_schema = JsonSchema::Array { @@ -621,7 +612,7 @@ fn create_request_user_input_tool() -> ToolSpec { "id".to_string(), "header".to_string(), "question".to_string(), - "isOther".to_string(), + "options".to_string(), ]), additional_properties: Some(false.into()), }), diff --git a/codex-rs/core/tests/suite/request_user_input.rs b/codex-rs/core/tests/suite/request_user_input.rs index 3872969610..89a5ed3557 100644 --- a/codex-rs/core/tests/suite/request_user_input.rs +++ b/codex-rs/core/tests/suite/request_user_input.rs @@ -94,7 +94,6 @@ async fn request_user_input_round_trip_resolves_pending() -> anyhow::Result<()> "id": "confirm_path", "header": "Confirm", "question": "Proceed with the plan?", - "isOther": false, "options": [{ "label": "Yes (Recommended)", "description": "Continue the current plan." @@ -153,6 +152,7 @@ async fn request_user_input_round_trip_resolves_pending() -> anyhow::Result<()> .await; assert_eq!(request.call_id, call_id); assert_eq!(request.questions.len(), 1); + assert_eq!(request.questions[0].is_other, true); let mut answers = HashMap::new(); answers.insert( @@ -214,7 +214,6 @@ where "id": "confirm_path", "header": "Confirm", "question": "Proceed with the plan?", - "isOther": false, "options": [{ "label": "Yes (Recommended)", "description": "Continue the current plan." diff --git a/codex-rs/docs/protocol_v1.md b/codex-rs/docs/protocol_v1.md index 8cdc5c9575..74b5546012 100644 --- a/codex-rs/docs/protocol_v1.md +++ b/codex-rs/docs/protocol_v1.md @@ -75,7 +75,7 @@ For complete documentation of the `Op` and `EventMsg` variants, refer to [protoc - `EventMsg` - `EventMsg::AgentMessage` – Messages from the `Model` - `EventMsg::ExecApprovalRequest` – Request approval from user to execute a command - - `EventMsg::RequestUserInput` – Request user input for a tool call (questions can include options plus `isOther` to add a free-form choice) + - `EventMsg::RequestUserInput` – Request user input for a tool call (questions must include options; the client always adds a free-form choice) - `EventMsg::TurnComplete` – A turn completed successfully - `EventMsg::Error` – A turn stopped with an error - `EventMsg::Warning` – A non-fatal warning that the client should surface to the user From 129787493f47af804ce58716bac5f64e145096c5 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 10:19:41 +0100 Subject: [PATCH 096/116] feat: backfill timing metric (#10218) 1. Add a metric to measure the backfill time 2. Add a unit to the timing histogram --- codex-rs/core/src/rollout/metadata.rs | 12 ++++++++++++ codex-rs/otel/src/metrics/client.rs | 25 ++++++++++++++++++++++++- codex-rs/otel/tests/suite/timing.rs | 11 ++++++++++- codex-rs/state/src/lib.rs | 2 ++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs index 5523274bde..2d59d71af3 100644 --- a/codex-rs/core/src/rollout/metadata.rs +++ b/codex-rs/core/src/rollout/metadata.rs @@ -16,6 +16,7 @@ use codex_protocol::protocol::SessionSource; use codex_state::BackfillStats; use codex_state::DB_ERROR_METRIC; use codex_state::DB_METRIC_BACKFILL; +use codex_state::DB_METRIC_BACKFILL_DURATION_MS; use codex_state::ExtractionOutcome; use codex_state::ThreadMetadataBuilder; use codex_state::apply_rollout_item; @@ -128,6 +129,7 @@ pub(crate) async fn backfill_sessions( config: &Config, otel: Option<&OtelManager>, ) { + let timer = otel.and_then(|otel| otel.start_timer(DB_METRIC_BACKFILL_DURATION_MS, &[]).ok()); let sessions_root = config.codex_home.join(rollout::SESSIONS_SUBDIR); let archived_root = config.codex_home.join(rollout::ARCHIVED_SESSIONS_SUBDIR); let mut rollout_paths: Vec<(PathBuf, bool)> = Vec::new(); @@ -210,6 +212,16 @@ pub(crate) async fn backfill_sessions( &[("status", "failed")], ); } + if let Some(timer) = timer.as_ref() { + let status = if stats.failed == 0 { + "success" + } else if stats.upserted == 0 { + "failed" + } else { + "partial_failure" + }; + let _ = timer.record(&[("status", status)]); + } } async fn file_modified_time_utc(path: &Path) -> Option> { diff --git a/codex-rs/otel/src/metrics/client.rs b/codex-rs/otel/src/metrics/client.rs index 9b1b01a3ed..62a2df2e8a 100644 --- a/codex-rs/otel/src/metrics/client.rs +++ b/codex-rs/otel/src/metrics/client.rs @@ -34,6 +34,8 @@ use tracing::debug; const ENV_ATTRIBUTE: &str = "env"; const METER_NAME: &str = "codex"; +const DURATION_UNIT: &str = "ms"; +const DURATION_DESCRIPTION: &str = "Duration in milliseconds."; #[derive(Debug)] struct MetricsClientInner { @@ -41,6 +43,7 @@ struct MetricsClientInner { meter: Meter, counters: Mutex>>, histograms: Mutex>>, + duration_histograms: Mutex>>, default_tags: BTreeMap, } @@ -81,6 +84,25 @@ impl MetricsClientInner { Ok(()) } + fn duration_histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) -> Result<()> { + validate_metric_name(name)?; + let attributes = self.attributes(tags)?; + + let mut histograms = self + .duration_histograms + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let histogram = histograms.entry(name.to_string()).or_insert_with(|| { + self.meter + .f64_histogram(name.to_string()) + .with_unit(DURATION_UNIT) + .with_description(DURATION_DESCRIPTION) + .build() + }); + histogram.record(value as f64, &attributes); + Ok(()) + } + fn attributes(&self, tags: &[(&str, &str)]) -> Result> { if tags.is_empty() { return Ok(self @@ -150,6 +172,7 @@ impl MetricsClient { meter, counters: Mutex::new(HashMap::new()), histograms: Mutex::new(HashMap::new()), + duration_histograms: Mutex::new(HashMap::new()), default_tags: config.default_tags, }))) } @@ -171,7 +194,7 @@ impl MetricsClient { duration: Duration, tags: &[(&str, &str)], ) -> Result<()> { - self.histogram( + self.0.duration_histogram( name, duration.as_millis().min(i64::MAX as u128) as i64, tags, diff --git a/codex-rs/otel/tests/suite/timing.rs b/codex-rs/otel/tests/suite/timing.rs index ce4f2f982e..8398e1a0d7 100644 --- a/codex-rs/otel/tests/suite/timing.rs +++ b/codex-rs/otel/tests/suite/timing.rs @@ -18,12 +18,17 @@ fn record_duration_records_histogram() -> Result<()> { )?; metrics.shutdown()?; + let resource_metrics = latest_metrics(&exporter); let (bounds, bucket_counts, sum, count) = - histogram_data(&latest_metrics(&exporter), "codex.request_latency"); + histogram_data(&resource_metrics, "codex.request_latency"); assert!(!bounds.is_empty()); assert_eq!(bucket_counts.iter().sum::(), 1); assert_eq!(sum, 15.0); assert_eq!(count, 1); + let metric = crate::harness::find_metric(&resource_metrics, "codex.request_latency") + .unwrap_or_else(|| panic!("metric codex.request_latency missing")); + assert_eq!(metric.unit(), "ms"); + assert_eq!(metric.description(), "Duration in milliseconds."); Ok(()) } @@ -46,6 +51,10 @@ fn timer_result_records_success() -> Result<()> { assert!(!bounds.is_empty()); assert_eq!(count, 1); assert_eq!(bucket_counts.iter().sum::(), 1); + let metric = crate::harness::find_metric(&resource_metrics, "codex.request_latency") + .unwrap_or_else(|| panic!("metric codex.request_latency missing")); + assert_eq!(metric.unit(), "ms"); + assert_eq!(metric.description(), "Duration in milliseconds."); let attrs = attributes_to_map( match crate::harness::find_metric(&resource_metrics, "codex.request_latency").and_then( |metric| match metric.data() { diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs index 685552015e..c08c76a1cf 100644 --- a/codex-rs/state/src/lib.rs +++ b/codex-rs/state/src/lib.rs @@ -34,5 +34,7 @@ pub use runtime::STATE_DB_FILENAME; pub const DB_ERROR_METRIC: &str = "codex.db.error"; /// Metrics on backfill process during first init of the db. Tags: [status] pub const DB_METRIC_BACKFILL: &str = "codex.db.backfill"; +/// Metrics on backfill duration during first init of the db. Tags: [status] +pub const DB_METRIC_BACKFILL_DURATION_MS: &str = "codex.db.backfill.duration_ms"; /// Metrics on errors during comparison between DB and rollout file. Tags: [stage] pub const DB_METRIC_COMPARE_ERROR: &str = "codex.db.compare_error"; From 25ad414680df9b7b53c8bf968c660e5a7e208123 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 11:13:43 +0100 Subject: [PATCH 097/116] chore: unify metric (#10220) --- codex-rs/core/src/state_db.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/state_db.rs b/codex-rs/core/src/state_db.rs index 7990a017ef..0804273bba 100644 --- a/codex-rs/core/src/state_db.rs +++ b/codex-rs/core/src/state_db.rs @@ -11,6 +11,7 @@ use codex_otel::OtelManager; use codex_protocol::ThreadId; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; +use codex_state::DB_METRIC_COMPARE_ERROR; pub use codex_state::LogEntry; use codex_state::STATE_DB_FILENAME; use codex_state::ThreadMetadataBuilder; @@ -282,9 +283,10 @@ pub async fn apply_rollout_items( pub fn record_discrepancy(stage: &str, reason: &str) { // We access the global metric because the call sites might not have access to the broader // OtelManager. + tracing::warn!("state db record_discrepancy: {stage}{reason}"); if let Some(metric) = codex_otel::metrics::global() { let _ = metric.counter( - "codex.db.discrepancy", + DB_METRIC_COMPARE_ERROR, 1, &[("stage", stage), ("reason", reason)], ); From 1ef5455eb6d3f887f6676c451397294594390087 Mon Sep 17 00:00:00 2001 From: pap-openai Date: Fri, 30 Jan 2026 10:40:09 +0000 Subject: [PATCH 098/116] Conversation naming (#8991) Session renaming: - `/rename my_session` - `/rename` without arg and passing an argument in `customViewPrompt` - AppExitInfo shows resume hint using the session name if set instead of uuid, defaults to uuid if not set - Names are stored in `CODEX_HOME/sessions.jsonl` Session resuming: - codex resume lookup for `CODEX_HOME/sessions.jsonl` first entry matching the name and resumes the session --------- Co-authored-by: jif-oai --- .../src/protocol/common.rs | 5 + .../app-server-protocol/src/protocol/v2.rs | 23 ++ codex-rs/app-server/README.md | 1 + .../app-server/src/bespoke_event_handling.rs | 12 + .../app-server/src/codex_message_processor.rs | 35 ++ codex-rs/cli/src/main.rs | 36 +- codex-rs/core/src/codex.rs | 111 +++++- codex-rs/core/src/codex_delegate.rs | 4 + codex-rs/core/src/lib.rs | 2 + codex-rs/core/src/rollout/mod.rs | 2 + codex-rs/core/src/rollout/policy.rs | 1 + codex-rs/core/src/rollout/session_index.rs | 325 ++++++++++++++++++ codex-rs/core/src/util.rs | 76 ++++ .../core/tests/suite/rollout_list_find.rs | 56 +++ codex-rs/exec/Cargo.toml | 1 + codex-rs/exec/src/cli.rs | 4 +- .../src/event_processor_with_human_output.rs | 3 +- .../src/event_processor_with_jsonl_output.rs | 1 + codex-rs/exec/src/lib.rs | 11 +- .../tests/event_processor_with_json_output.rs | 1 + codex-rs/mcp-server/src/codex_tool_runner.rs | 3 + codex-rs/mcp-server/src/outgoing_message.rs | 3 + codex-rs/protocol/src/protocol.rs | 23 +- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/app.rs | 53 ++- codex-rs/tui/src/bottom_pane/chat_composer.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 84 ++++- codex-rs/tui/src/chatwidget/tests.rs | 4 + codex-rs/tui/src/lib.rs | 23 +- codex-rs/tui/src/slash_command.rs | 3 + codex-rs/tui/src/status/card.rs | 13 +- codex-rs/tui/src/status/tests.rs | 15 + codex-rs/tui/tooltips.txt | 1 + 33 files changed, 908 insertions(+), 30 deletions(-) create mode 100644 codex-rs/core/src/rollout/session_index.rs diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index b9c58a5883..2e8778bdc5 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -132,6 +132,10 @@ client_request_definitions! { params: v2::ThreadArchiveParams, response: v2::ThreadArchiveResponse, }, + ThreadSetName => "thread/name/set" { + params: v2::ThreadSetNameParams, + response: v2::ThreadSetNameResponse, + }, ThreadUnarchive => "thread/unarchive" { params: v2::ThreadUnarchiveParams, response: v2::ThreadUnarchiveResponse, @@ -598,6 +602,7 @@ server_notification_definitions! { /// NEW NOTIFICATIONS Error => "error" (v2::ErrorNotification), ThreadStarted => "thread/started" (v2::ThreadStartedNotification), + ThreadNameUpdated => "thread/name/updated" (v2::ThreadNameUpdatedNotification), ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification), TurnStarted => "turn/started" (v2::TurnStartedNotification), TurnCompleted => "turn/completed" (v2::TurnCompletedNotification), diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 1e28b1b086..8bea094487 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1295,6 +1295,14 @@ pub struct ThreadArchiveParams { #[ts(export_to = "v2/")] pub struct ThreadArchiveResponse {} +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadSetNameParams { + pub thread_id: String, + pub name: String, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -1302,6 +1310,11 @@ pub struct ThreadUnarchiveParams { pub thread_id: String, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadSetNameResponse {} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -2285,6 +2298,16 @@ pub struct ThreadStartedNotification { pub thread: Thread, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadNameUpdatedNotification { + pub thread_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub thread_name: Option, +} + #[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 e9ebcd9661..3798d76027 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -82,6 +82,7 @@ Example (from OpenAI's official VSCode extension): - `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`. - `thread/archive` — move a thread’s rollout file into the archived directory; returns `{}` on success. +- `thread/name/set` — set or update a thread’s user-facing name; returns `{}` on success. Thread names are not required to be unique; name lookups resolve to the most recently updated thread. - `thread/unarchive` — move an archived rollout file back into the sessions directory; returns the restored `thread` on success. - `thread/rollback` — drop the last N turns from the agent’s in-memory context and persist a rollback marker in the rollout so future resumes see the pruned history; returns the updated `thread` (with `turns` populated) on success. - `turn/start` — add user input to a thread and begin Codex generation; responds with the initial `turn` object and streams `turn/started`, `item/*`, and `turn/completed` notifications. diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 1a9fcaa705..dd2628deb7 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -52,6 +52,7 @@ use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; use codex_app_server_protocol::TerminalInteractionNotification; use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadNameUpdatedNotification; use codex_app_server_protocol::ThreadRollbackResponse; use codex_app_server_protocol::ThreadTokenUsage; use codex_app_server_protocol::ThreadTokenUsageUpdatedNotification; @@ -1097,6 +1098,17 @@ pub(crate) async fn apply_bespoke_event_handling( outgoing.send_response(request_id, response).await; } } + EventMsg::ThreadNameUpdated(thread_name_event) => { + if let ApiVersion::V2 = api_version { + let notification = ThreadNameUpdatedNotification { + thread_id: thread_name_event.thread_id.to_string(), + thread_name: thread_name_event.thread_name, + }; + outgoing + .send_server_notification(ServerNotification::ThreadNameUpdated(notification)) + .await; + } + } EventMsg::TurnDiff(turn_diff_event) => { handle_turn_diff( conversation_id, diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 660b4b87d0..3817bce3a1 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -110,6 +110,8 @@ use codex_app_server_protocol::ThreadReadResponse; use codex_app_server_protocol::ThreadResumeParams; use codex_app_server_protocol::ThreadResumeResponse; use codex_app_server_protocol::ThreadRollbackParams; +use codex_app_server_protocol::ThreadSetNameParams; +use codex_app_server_protocol::ThreadSetNameResponse; use codex_app_server_protocol::ThreadSortKey; use codex_app_server_protocol::ThreadSourceKind; use codex_app_server_protocol::ThreadStartParams; @@ -416,6 +418,9 @@ impl CodexMessageProcessor { ClientRequest::ThreadArchive { request_id, params } => { self.thread_archive(request_id, params).await; } + ClientRequest::ThreadSetName { request_id, params } => { + self.thread_set_name(request_id, params).await; + } ClientRequest::ThreadUnarchive { request_id, params } => { self.thread_unarchive(request_id, params).await; } @@ -1780,6 +1785,36 @@ impl CodexMessageProcessor { } } + async fn thread_set_name(&self, request_id: RequestId, params: ThreadSetNameParams) { + let ThreadSetNameParams { thread_id, name } = params; + let Some(name) = codex_core::util::normalize_thread_name(&name) else { + self.send_invalid_request_error( + request_id, + "thread name must not be empty".to_string(), + ) + .await; + return; + }; + + let (_, thread) = match self.load_thread(&thread_id).await { + Ok(v) => v, + Err(error) => { + self.outgoing.send_error(request_id, error).await; + return; + } + }; + + if let Err(err) = thread.submit(Op::SetThreadName { name }).await { + self.send_internal_error(request_id, format!("failed to set thread name: {err}")) + .await; + return; + } + + self.outgoing + .send_response(request_id, ThreadSetNameResponse {}) + .await; + } + async fn thread_unarchive(&mut self, request_id: RequestId, params: ThreadUnarchiveParams) { // TODO(jif) mostly rewrite this using sqlite after phase 1 let thread_id = match ThreadId::from_string(¶ms.thread_id) { diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index dd20f04128..7ab8bc937a 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -144,7 +144,7 @@ struct CompletionCommand { #[derive(Debug, Parser)] struct ResumeCommand { - /// Conversation/session id (UUID). When provided, resumes this session. + /// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses. /// If omitted, use --last to pick the most recent recorded session. #[arg(value_name = "SESSION_ID")] session_id: Option, @@ -323,6 +323,7 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec Vec) -> AppExitInfo { + fn sample_exit_info(conversation_id: Option<&str>, thread_name: Option<&str>) -> AppExitInfo { let token_usage = TokenUsage { output_tokens: 2, total_tokens: 2, @@ -1036,7 +1038,10 @@ mod tests { }; AppExitInfo { token_usage, - thread_id: conversation.map(ThreadId::from_string).map(Result::unwrap), + thread_id: conversation_id + .map(ThreadId::from_string) + .map(Result::unwrap), + thread_name: thread_name.map(str::to_string), update_action: None, exit_reason: ExitReason::UserRequested, } @@ -1047,6 +1052,7 @@ mod tests { let exit_info = AppExitInfo { token_usage: TokenUsage::default(), thread_id: None, + thread_name: None, update_action: None, exit_reason: ExitReason::UserRequested, }; @@ -1056,7 +1062,7 @@ mod tests { #[test] fn format_exit_messages_includes_resume_hint_without_color() { - let exit_info = sample_exit_info(Some("123e4567-e89b-12d3-a456-426614174000")); + let exit_info = sample_exit_info(Some("123e4567-e89b-12d3-a456-426614174000"), None); let lines = format_exit_messages(exit_info, false); assert_eq!( lines, @@ -1070,12 +1076,28 @@ mod tests { #[test] fn format_exit_messages_applies_color_when_enabled() { - let exit_info = sample_exit_info(Some("123e4567-e89b-12d3-a456-426614174000")); + let exit_info = sample_exit_info(Some("123e4567-e89b-12d3-a456-426614174000"), None); let lines = format_exit_messages(exit_info, true); assert_eq!(lines.len(), 2); assert!(lines[1].contains("\u{1b}[36m")); } + #[test] + fn format_exit_messages_prefers_thread_name() { + let exit_info = sample_exit_info( + Some("123e4567-e89b-12d3-a456-426614174000"), + Some("my-thread"), + ); + let lines = format_exit_messages(exit_info, false); + assert_eq!( + lines, + vec![ + "Token usage: total=2 input=0 output=2".to_string(), + "To continue this session, run codex resume my-thread".to_string(), + ] + ); + } + #[test] fn resume_model_flag_applies_when_no_root_flags() { let interactive = diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 250ea1ff49..7eefd04ec4 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -26,6 +26,7 @@ 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::rollout::session_index; use crate::stream_events_utils::HandleOutputCtx; use crate::stream_events_utils::handle_non_tool_response_item; use crate::stream_events_utils::handle_output_item_done; @@ -354,6 +355,8 @@ impl Codex { sandbox_policy: config.sandbox_policy.clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + codex_home: config.codex_home.clone(), + thread_name: None, original_config_do_not_use: Arc::clone(&config), session_source, dynamic_tools, @@ -544,6 +547,10 @@ pub(crate) struct SessionConfiguration { /// `ConfigureSession` operation so that the business-logic layer can /// operate deterministically. cwd: PathBuf, + /// Directory containing all Codex state for this session. + codex_home: PathBuf, + /// Optional user-facing name for the thread, updated during the session. + thread_name: Option, // TODO(pakrym): Remove config from here original_config_do_not_use: Arc, @@ -553,6 +560,10 @@ pub(crate) struct SessionConfiguration { } impl SessionConfiguration { + pub(crate) fn codex_home(&self) -> &PathBuf { + &self.codex_home + } + fn thread_config_snapshot(&self) -> ThreadConfigSnapshot { ThreadConfigSnapshot { model: self.collaboration_mode.model().to_string(), @@ -623,6 +634,11 @@ impl Session { per_turn_config } + pub(crate) async fn codex_home(&self) -> PathBuf { + let state = self.state.lock().await; + state.session_configuration.codex_home().clone() + } + #[allow(clippy::too_many_arguments)] fn make_turn_context( auth_manager: Option>, @@ -683,7 +699,7 @@ impl Session { #[allow(clippy::too_many_arguments)] async fn new( - session_configuration: SessionConfiguration, + mut session_configuration: SessionConfiguration, config: Arc, auth_manager: Arc, models_manager: Arc, @@ -863,6 +879,16 @@ impl Session { otel_manager.clone(), ); } + let thread_name = + match session_index::find_thread_name_by_id(&config.codex_home, &conversation_id).await + { + Ok(name) => name, + Err(err) => { + warn!("Failed to read session index for thread name: {err}"); + None + } + }; + session_configuration.thread_name = thread_name.clone(); let state = SessionState::new(session_configuration.clone()); let services = SessionServices { @@ -904,6 +930,7 @@ impl Session { msg: EventMsg::SessionConfigured(SessionConfiguredEvent { session_id: conversation_id, forked_from_id, + thread_name: session_configuration.thread_name.clone(), model: session_configuration.collaboration_mode.model().to_string(), model_provider_id: config.model_provider_id.clone(), approval_policy: session_configuration.approval_policy.value(), @@ -1451,8 +1478,7 @@ impl Session { .lock() .await .session_configuration - .original_config_do_not_use - .codex_home + .codex_home() .clone(); if !features.enabled(Feature::ExecPolicy) { @@ -2440,6 +2466,9 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv 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, @@ -2483,6 +2512,7 @@ mod handlers { use crate::mcp::collect_mcp_snapshot_from_manager; use crate::mcp::effective_mcp_servers; use crate::review_prompts::resolve_review_request; + use crate::rollout::session_index; use crate::tasks::CompactTask; use crate::tasks::RegularTask; use crate::tasks::UndoTask; @@ -2499,6 +2529,7 @@ mod handlers { use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::ReviewRequest; use codex_protocol::protocol::SkillsListEntry; + use codex_protocol::protocol::ThreadNameUpdatedEvent; use codex_protocol::protocol::ThreadRolledBackEvent; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::WarningEvent; @@ -2952,6 +2983,72 @@ mod handlers { .await; } + /// Persists the thread name in the session index, updates in-memory state, and emits + /// a `ThreadNameUpdated` event on success. + /// + /// This appends the name to `CODEX_HOME/sessions_index.jsonl` via `session_index::append_thread_name` for the + /// current `thread_id`, then updates `SessionConfiguration::thread_name`. + /// + /// Returns an error event if the name is empty or session persistence is disabled. + pub async fn set_thread_name(sess: &Arc, sub_id: String, name: String) { + let Some(name) = crate::util::normalize_thread_name(&name) else { + let event = Event { + id: sub_id, + msg: EventMsg::Error(ErrorEvent { + message: "Thread name cannot be empty.".to_string(), + codex_error_info: Some(CodexErrorInfo::BadRequest), + }), + }; + sess.send_event_raw(event).await; + return; + }; + + let persistence_enabled = { + let rollout = sess.services.rollout.lock().await; + rollout.is_some() + }; + if !persistence_enabled { + let event = Event { + id: sub_id, + msg: EventMsg::Error(ErrorEvent { + message: "Session persistence is disabled; cannot rename thread.".to_string(), + codex_error_info: Some(CodexErrorInfo::Other), + }), + }; + sess.send_event_raw(event).await; + return; + }; + + let codex_home = sess.codex_home().await; + if let Err(e) = + session_index::append_thread_name(&codex_home, sess.conversation_id, &name).await + { + let event = Event { + id: sub_id, + msg: EventMsg::Error(ErrorEvent { + message: format!("Failed to set thread name: {e}"), + codex_error_info: Some(CodexErrorInfo::Other), + }), + }; + sess.send_event_raw(event).await; + return; + } + + { + let mut state = sess.state.lock().await; + state.session_configuration.thread_name = Some(name.clone()); + } + + sess.send_event_raw(Event { + id: sub_id, + msg: EventMsg::ThreadNameUpdated(ThreadNameUpdatedEvent { + thread_id: sess.conversation_id, + thread_name: Some(name), + }), + }) + .await; + } + pub async fn shutdown(sess: &Arc, sub_id: String) -> bool { sess.abort_all_tasks(TurnAbortReason::Interrupted).await; sess.services @@ -4440,6 +4537,8 @@ mod tests { sandbox_policy: config.sandbox_policy.clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + codex_home: config.codex_home.clone(), + thread_name: None, original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, dynamic_tools: Vec::new(), @@ -4521,6 +4620,8 @@ mod tests { sandbox_policy: config.sandbox_policy.clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + codex_home: config.codex_home.clone(), + thread_name: None, original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, dynamic_tools: Vec::new(), @@ -4786,6 +4887,8 @@ mod tests { sandbox_policy: config.sandbox_policy.clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + codex_home: config.codex_home.clone(), + thread_name: None, original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, dynamic_tools: Vec::new(), @@ -4900,6 +5003,8 @@ mod tests { sandbox_policy: config.sandbox_policy.clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + codex_home: config.codex_home.clone(), + thread_name: None, original_config_do_not_use: Arc::clone(&config), session_source: SessionSource::Exec, dynamic_tools: Vec::new(), diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 5e1de2ef1f..7a611c05e2 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -208,6 +208,10 @@ async fn forward_events( id: _, msg: EventMsg::SessionConfigured(_), } => {} + Event { + id: _, + msg: EventMsg::ThreadNameUpdated(_), + } => {} Event { id, msg: EventMsg::ExecApprovalRequest(event), diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 1b1fb65ecd..63bba76507 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -100,12 +100,14 @@ pub mod turn_diff_tracker; pub use rollout::ARCHIVED_SESSIONS_SUBDIR; pub use rollout::INTERACTIVE_SESSION_SOURCES; pub use rollout::RolloutRecorder; +pub use rollout::RolloutRecorderParams; pub use rollout::SESSIONS_SUBDIR; pub use rollout::SessionMeta; pub use rollout::find_archived_thread_path_by_id_str; #[deprecated(note = "use find_thread_path_by_id_str")] pub use rollout::find_conversation_path_by_id_str; pub use rollout::find_thread_path_by_id_str; +pub use rollout::find_thread_path_by_name_str; pub use rollout::list::Cursor; pub use rollout::list::ThreadItem; pub use rollout::list::ThreadSortKey; diff --git a/codex-rs/core/src/rollout/mod.rs b/codex-rs/core/src/rollout/mod.rs index cfc2d82d8d..60775d04b0 100644 --- a/codex-rs/core/src/rollout/mod.rs +++ b/codex-rs/core/src/rollout/mod.rs @@ -12,6 +12,7 @@ pub mod list; pub(crate) mod metadata; pub(crate) mod policy; pub mod recorder; +pub(crate) mod session_index; pub(crate) mod truncation; pub use codex_protocol::protocol::SessionMeta; @@ -23,6 +24,7 @@ pub use list::find_thread_path_by_id_str as find_conversation_path_by_id_str; pub use list::rollout_date_parts; pub use recorder::RolloutRecorder; pub use recorder::RolloutRecorderParams; +pub use session_index::find_thread_path_by_name_str; #[cfg(test)] pub mod tests; diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 2d263c0539..6de60ae05c 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -58,6 +58,7 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::AgentReasoningSectionBreak(_) | EventMsg::RawResponseItem(_) | EventMsg::SessionConfigured(_) + | EventMsg::ThreadNameUpdated(_) | EventMsg::McpToolCallBegin(_) | EventMsg::McpToolCallEnd(_) | EventMsg::WebSearchBegin(_) diff --git a/codex-rs/core/src/rollout/session_index.rs b/codex-rs/core/src/rollout/session_index.rs new file mode 100644 index 0000000000..98f7e35d84 --- /dev/null +++ b/codex-rs/core/src/rollout/session_index.rs @@ -0,0 +1,325 @@ +use std::fs::File; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::path::Path; +use std::path::PathBuf; + +use codex_protocol::ThreadId; +use serde::Deserialize; +use serde::Serialize; +use tokio::io::AsyncWriteExt; + +const SESSION_INDEX_FILE: &str = "session_index.jsonl"; +const READ_CHUNK_SIZE: usize = 8192; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct SessionIndexEntry { + pub id: ThreadId, + pub thread_name: String, + pub updated_at: String, +} + +/// Append a thread name update to the session index. +/// The index is append-only; the most recent entry wins when resolving names or ids. +pub async fn append_thread_name( + codex_home: &Path, + thread_id: ThreadId, + name: &str, +) -> std::io::Result<()> { + use time::OffsetDateTime; + use time::format_description::well_known::Rfc3339; + + let updated_at = OffsetDateTime::now_utc() + .format(&Rfc3339) + .unwrap_or_else(|_| "unknown".to_string()); + let entry = SessionIndexEntry { + id: thread_id, + thread_name: name.to_string(), + updated_at, + }; + append_session_index_entry(codex_home, &entry).await +} + +/// Append a raw session index entry to `session_index.jsonl`. +/// The file is append-only; consumers scan from the end to find the newest match. +pub async fn append_session_index_entry( + codex_home: &Path, + entry: &SessionIndexEntry, +) -> std::io::Result<()> { + let path = session_index_path(codex_home); + let mut file = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .await?; + let mut line = serde_json::to_string(entry).map_err(std::io::Error::other)?; + line.push('\n'); + file.write_all(line.as_bytes()).await?; + file.flush().await?; + Ok(()) +} + +/// Find the latest thread name for a thread id, if any. +pub async fn find_thread_name_by_id( + codex_home: &Path, + thread_id: &ThreadId, +) -> std::io::Result> { + let path = session_index_path(codex_home); + if !path.exists() { + return Ok(None); + } + let id = *thread_id; + let entry = tokio::task::spawn_blocking(move || scan_index_from_end_by_id(&path, &id)) + .await + .map_err(std::io::Error::other)??; + Ok(entry.map(|entry| entry.thread_name)) +} + +/// Find the most recently updated thread id for a thread name, if any. +pub async fn find_thread_id_by_name( + codex_home: &Path, + name: &str, +) -> std::io::Result> { + if name.trim().is_empty() { + return Ok(None); + } + let path = session_index_path(codex_home); + if !path.exists() { + return Ok(None); + } + let name = name.to_string(); + let entry = tokio::task::spawn_blocking(move || scan_index_from_end_by_name(&path, &name)) + .await + .map_err(std::io::Error::other)??; + Ok(entry.map(|entry| entry.id)) +} + +/// Locate a recorded thread rollout file by thread name using newest-first ordering. +/// Returns `Ok(Some(path))` if found, `Ok(None)` if not present. +pub async fn find_thread_path_by_name_str( + codex_home: &Path, + name: &str, +) -> std::io::Result> { + let Some(thread_id) = find_thread_id_by_name(codex_home, name).await? else { + return Ok(None); + }; + super::list::find_thread_path_by_id_str(codex_home, &thread_id.to_string()).await +} + +fn session_index_path(codex_home: &Path) -> PathBuf { + codex_home.join(SESSION_INDEX_FILE) +} + +fn scan_index_from_end_by_id( + path: &Path, + thread_id: &ThreadId, +) -> std::io::Result> { + scan_index_from_end(path, |entry| entry.id == *thread_id) +} + +fn scan_index_from_end_by_name( + path: &Path, + name: &str, +) -> std::io::Result> { + scan_index_from_end(path, |entry| entry.thread_name == name) +} + +fn scan_index_from_end( + path: &Path, + mut predicate: F, +) -> std::io::Result> +where + F: FnMut(&SessionIndexEntry) -> bool, +{ + let mut file = File::open(path)?; + let mut remaining = file.metadata()?.len(); + let mut line_rev: Vec = Vec::new(); + let mut buf = vec![0u8; READ_CHUNK_SIZE]; + + while remaining > 0 { + let read_size = usize::try_from(remaining.min(READ_CHUNK_SIZE as u64)) + .map_err(std::io::Error::other)?; + remaining -= read_size as u64; + file.seek(SeekFrom::Start(remaining))?; + file.read_exact(&mut buf[..read_size])?; + + for &byte in buf[..read_size].iter().rev() { + if byte == b'\n' { + if let Some(entry) = parse_line_from_rev(&mut line_rev, &mut predicate)? { + return Ok(Some(entry)); + } + continue; + } + line_rev.push(byte); + } + } + + if let Some(entry) = parse_line_from_rev(&mut line_rev, &mut predicate)? { + return Ok(Some(entry)); + } + + Ok(None) +} + +fn parse_line_from_rev( + line_rev: &mut Vec, + predicate: &mut F, +) -> std::io::Result> +where + F: FnMut(&SessionIndexEntry) -> bool, +{ + if line_rev.is_empty() { + return Ok(None); + } + line_rev.reverse(); + let line = std::mem::take(line_rev); + let Ok(mut line) = String::from_utf8(line) else { + return Ok(None); + }; + if line.ends_with('\r') { + line.pop(); + } + let trimmed = line.trim(); + if trimmed.is_empty() { + return Ok(None); + } + let Ok(entry) = serde_json::from_str::(trimmed) else { + return Ok(None); + }; + if predicate(&entry) { + return Ok(Some(entry)); + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use tempfile::TempDir; + fn write_index(path: &Path, lines: &[SessionIndexEntry]) -> std::io::Result<()> { + let mut out = String::new(); + for entry in lines { + out.push_str(&serde_json::to_string(entry).unwrap()); + out.push('\n'); + } + std::fs::write(path, out) + } + + #[test] + fn find_thread_id_by_name_prefers_latest_entry() -> std::io::Result<()> { + let temp = TempDir::new()?; + let path = session_index_path(temp.path()); + let id1 = ThreadId::new(); + let id2 = ThreadId::new(); + let lines = vec![ + SessionIndexEntry { + id: id1, + thread_name: "same".to_string(), + updated_at: "2024-01-01T00:00:00Z".to_string(), + }, + SessionIndexEntry { + id: id2, + thread_name: "same".to_string(), + updated_at: "2024-01-02T00:00:00Z".to_string(), + }, + ]; + write_index(&path, &lines)?; + + let found = scan_index_from_end_by_name(&path, "same")?; + assert_eq!(found.map(|entry| entry.id), Some(id2)); + Ok(()) + } + + #[test] + fn find_thread_name_by_id_prefers_latest_entry() -> std::io::Result<()> { + let temp = TempDir::new()?; + let path = session_index_path(temp.path()); + let id = ThreadId::new(); + let lines = vec![ + SessionIndexEntry { + id, + thread_name: "first".to_string(), + updated_at: "2024-01-01T00:00:00Z".to_string(), + }, + SessionIndexEntry { + id, + thread_name: "second".to_string(), + updated_at: "2024-01-02T00:00:00Z".to_string(), + }, + ]; + write_index(&path, &lines)?; + + let found = scan_index_from_end_by_id(&path, &id)?; + assert_eq!( + found.map(|entry| entry.thread_name), + Some("second".to_string()) + ); + Ok(()) + } + + #[test] + fn scan_index_returns_none_when_entry_missing() -> std::io::Result<()> { + let temp = TempDir::new()?; + let path = session_index_path(temp.path()); + let id = ThreadId::new(); + let lines = vec![SessionIndexEntry { + id, + thread_name: "present".to_string(), + updated_at: "2024-01-01T00:00:00Z".to_string(), + }]; + write_index(&path, &lines)?; + + let missing_name = scan_index_from_end_by_name(&path, "missing")?; + assert_eq!(missing_name, None); + + let missing_id = scan_index_from_end_by_id(&path, &ThreadId::new())?; + assert_eq!(missing_id, None); + Ok(()) + } + + #[test] + fn scan_index_finds_latest_match_among_mixed_entries() -> std::io::Result<()> { + let temp = TempDir::new()?; + let path = session_index_path(temp.path()); + let id_target = ThreadId::new(); + let id_other = ThreadId::new(); + let expected = SessionIndexEntry { + id: id_target, + thread_name: "target".to_string(), + updated_at: "2024-01-03T00:00:00Z".to_string(), + }; + let expected_other = SessionIndexEntry { + id: id_other, + thread_name: "target".to_string(), + updated_at: "2024-01-02T00:00:00Z".to_string(), + }; + // Resolution is based on append order (scan from end), not updated_at. + let lines = vec![ + SessionIndexEntry { + id: id_target, + thread_name: "target".to_string(), + updated_at: "2024-01-01T00:00:00Z".to_string(), + }, + expected_other.clone(), + expected.clone(), + SessionIndexEntry { + id: ThreadId::new(), + thread_name: "another".to_string(), + updated_at: "2024-01-04T00:00:00Z".to_string(), + }, + ]; + write_index(&path, &lines)?; + + let found_by_name = scan_index_from_end_by_name(&path, "target")?; + assert_eq!(found_by_name, Some(expected.clone())); + + let found_by_id = scan_index_from_end_by_id(&path, &id_target)?; + assert_eq!(found_by_id, Some(expected)); + + let found_other_by_id = scan_index_from_end_by_id(&path, &id_other)?; + assert_eq!(found_other_by_id, Some(expected_other)); + Ok(()) + } +} diff --git a/codex-rs/core/src/util.rs b/codex-rs/core/src/util.rs index a100f28443..1a538da558 100644 --- a/codex-rs/core/src/util.rs +++ b/codex-rs/core/src/util.rs @@ -2,10 +2,13 @@ use std::path::Path; use std::path::PathBuf; use std::time::Duration; +use codex_protocol::ThreadId; use rand::Rng; use tracing::debug; use tracing::error; +use crate::parse_command::shlex_join; + const INITIAL_DELAY_MS: u64 = 200; const BACKOFF_FACTOR: f64 = 2.0; @@ -72,6 +75,32 @@ pub fn resolve_path(base: &Path, path: &PathBuf) -> PathBuf { } } +/// Trim a thread name and return `None` if it is empty after trimming. +pub fn normalize_thread_name(name: &str) -> Option { + let trimmed = name.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } +} + +pub fn resume_command(thread_name: Option<&str>, thread_id: Option) -> Option { + let resume_target = thread_name + .filter(|name| !name.is_empty()) + .map(str::to_string) + .or_else(|| thread_id.map(|thread_id| thread_id.to_string())); + resume_target.map(|target| { + let needs_double_dash = target.starts_with('-'); + let escaped = shlex_join(&[target]); + if needs_double_dash { + format!("codex resume -- {escaped}") + } else { + format!("codex resume {escaped}") + } + }) +} + #[cfg(test)] mod tests { use super::*; @@ -107,4 +136,51 @@ mod tests { feedback_tags!(model = "gpt-5", cached = true, debug_only = OnlyDebug); } + + #[test] + fn normalize_thread_name_trims_and_rejects_empty() { + assert_eq!(normalize_thread_name(" "), None); + assert_eq!( + normalize_thread_name(" my thread "), + Some("my thread".to_string()) + ); + } + + #[test] + fn resume_command_prefers_name_over_id() { + let thread_id = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap(); + let command = resume_command(Some("my-thread"), Some(thread_id)); + assert_eq!(command, Some("codex resume my-thread".to_string())); + } + + #[test] + fn resume_command_with_only_id() { + let thread_id = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap(); + let command = resume_command(None, Some(thread_id)); + assert_eq!( + command, + Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string()) + ); + } + + #[test] + fn resume_command_with_no_name_or_id() { + let command = resume_command(None, None); + assert_eq!(command, None); + } + + #[test] + fn resume_command_quotes_thread_name_when_needed() { + let command = resume_command(Some("-starts-with-dash"), None); + assert_eq!( + command, + Some("codex resume -- -starts-with-dash".to_string()) + ); + + let command = resume_command(Some("two words"), None); + assert_eq!(command, Some("codex resume 'two words'".to_string())); + + let command = resume_command(Some("quote'case"), None); + assert_eq!(command, Some("codex resume \"quote'case\"".to_string())); + } } diff --git a/codex-rs/core/tests/suite/rollout_list_find.rs b/codex-rs/core/tests/suite/rollout_list_find.rs index 2af6192dbe..fc3ab80fc3 100644 --- a/codex-rs/core/tests/suite/rollout_list_find.rs +++ b/codex-rs/core/tests/suite/rollout_list_find.rs @@ -3,8 +3,16 @@ use std::io::Write; use std::path::Path; use std::path::PathBuf; +use codex_core::RolloutRecorder; +use codex_core::RolloutRecorderParams; +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 pretty_assertions::assert_eq; use tempfile::TempDir; use uuid::Uuid; @@ -87,6 +95,54 @@ async fn find_ignores_granular_gitignore_rules() { assert_eq!(found, Some(expected)); } +#[tokio::test] +async fn find_locates_rollout_file_written_by_recorder() -> std::io::Result<()> { + // Ensures the name-based finder locates a rollout produced by the real recorder. + let home = TempDir::new().unwrap(); + let config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .build() + .await?; + let thread_id = ThreadId::new(); + let thread_name = "named thread"; + let recorder = RolloutRecorder::new( + &config, + RolloutRecorderParams::new( + thread_id, + None, + SessionSource::Exec, + BaseInstructions::default(), + Vec::new(), + ), + None, + None, + ) + .await?; + recorder.flush().await?; + + let index_path = home.path().join("session_index.jsonl"); + std::fs::write( + &index_path, + format!( + "{}\n", + serde_json::json!({ + "id": thread_id, + "thread_name": thread_name, + "updated_at": "2024-01-01T00:00:00Z" + }) + ), + )?; + + let found = find_thread_path_by_name_str(home.path(), thread_name).await?; + + let path = found.expect("expected rollout path to be found"); + assert!(path.exists()); + let contents = std::fs::read_to_string(&path)?; + assert!(contents.contains(&thread_id.to_string())); + recorder.shutdown().await?; + Ok(()) +} + #[tokio::test] async fn find_archived_locates_rollout_file_by_id() { let home = TempDir::new().unwrap(); diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index 9156c22ea3..d4a64772e1 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -47,6 +47,7 @@ ts-rs = { workspace = true, features = [ "serde-json-impl", "no-serde-warnings", ] } +uuid = { workspace = true } [dev-dependencies] diff --git a/codex-rs/exec/src/cli.rs b/codex-rs/exec/src/cli.rs index 4c10bb0d72..2980370de7 100644 --- a/codex-rs/exec/src/cli.rs +++ b/codex-rs/exec/src/cli.rs @@ -114,7 +114,7 @@ pub enum Command { struct ResumeArgsRaw { // Note: This is the direct clap shape. We reinterpret the positional when --last is set // so "codex resume --last " treats the positional as a prompt, not a session id. - /// Conversation/session id (UUID). When provided, resumes this session. + /// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses. /// If omitted, use --last to pick the most recent recorded session. #[arg(value_name = "SESSION_ID")] session_id: Option, @@ -144,7 +144,7 @@ struct ResumeArgsRaw { #[derive(Debug)] pub struct ResumeArgs { - /// Conversation/session id (UUID). When provided, resumes this session. + /// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses. /// If omitted, use --last to pick the most recent recorded session. pub session_id: Option, 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 fb7aa54ab4..e11e1fcadb 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -750,7 +750,8 @@ impl EventProcessor for EventProcessorWithHumanOutput { ); } EventMsg::ShutdownComplete => return CodexStatus::Shutdown, - EventMsg::ExecApprovalRequest(_) + EventMsg::ThreadNameUpdated(_) + | EventMsg::ExecApprovalRequest(_) | EventMsg::ApplyPatchApprovalRequest(_) | EventMsg::TerminalInteraction(_) | EventMsg::ExecCommandOutputDelta(_) 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 d43ce4387c..687df574d6 100644 --- a/codex-rs/exec/src/event_processor_with_jsonl_output.rs +++ b/codex-rs/exec/src/event_processor_with_jsonl_output.rs @@ -117,6 +117,7 @@ impl EventProcessorWithJsonOutput { pub fn collect_thread_events(&mut self, event: &protocol::Event) -> Vec { match &event.msg { protocol::EventMsg::SessionConfigured(ev) => self.handle_session_configured(ev), + protocol::EventMsg::ThreadNameUpdated(_) => Vec::new(), protocol::EventMsg::AgentMessage(ev) => self.handle_agent_message(ev), protocol::EventMsg::AgentReasoning(ev) => self.handle_reasoning_event(ev), protocol::EventMsg::ExecCommandBegin(ev) => self.handle_exec_command_begin(ev), diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index f2c212d895..f7176c13b0 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -59,12 +59,14 @@ use tracing::info; use tracing::warn; use tracing_subscriber::EnvFilter; use tracing_subscriber::prelude::*; +use uuid::Uuid; use crate::cli::Command as ExecCommand; use crate::event_processor::CodexStatus; use crate::event_processor::EventProcessor; use codex_core::default_client::set_default_originator; use codex_core::find_thread_path_by_id_str; +use codex_core::find_thread_path_by_name_str; enum InitialOperation { UserTurn { @@ -619,8 +621,13 @@ async fn resolve_resume_path( } } } else if let Some(id_str) = args.session_id.as_deref() { - let path = find_thread_path_by_id_str(&config.codex_home, id_str).await?; - Ok(path) + if Uuid::parse_str(id_str).is_ok() { + let path = find_thread_path_by_id_str(&config.codex_home, id_str).await?; + Ok(path) + } else { + let path = find_thread_path_by_name_str(&config.codex_home, id_str).await?; + Ok(path) + } } else { Ok(None) } diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index 105824c60d..dc5f220fd3 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -88,6 +88,7 @@ fn session_configured_produces_thread_started_event() { EventMsg::SessionConfigured(SessionConfiguredEvent { session_id, forked_from_id: None, + thread_name: None, model: "codex-mini-latest".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index dcaf8a89e6..c96bc60706 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -308,6 +308,9 @@ async fn run_codex_tool_session_inner( EventMsg::SessionConfigured(_) => { tracing::error!("unexpected SessionConfigured event"); } + EventMsg::ThreadNameUpdated(_) => { + // Ignore session metadata updates in MCP tool runner. + } EventMsg::AgentMessageDelta(_) => { // TODO: think how we want to support this in the MCP } diff --git a/codex-rs/mcp-server/src/outgoing_message.rs b/codex-rs/mcp-server/src/outgoing_message.rs index 2069db69d0..954e50d9de 100644 --- a/codex-rs/mcp-server/src/outgoing_message.rs +++ b/codex-rs/mcp-server/src/outgoing_message.rs @@ -258,6 +258,7 @@ mod tests { msg: EventMsg::SessionConfigured(SessionConfiguredEvent { session_id: thread_id, forked_from_id: None, + thread_name: None, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, @@ -298,6 +299,7 @@ mod tests { let session_configured_event = SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, + thread_name: None, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, @@ -362,6 +364,7 @@ mod tests { let session_configured_event = SessionConfiguredEvent { session_id: thread_id, forked_from_id: None, + thread_name: None, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 7ba01fa4bd..fbaf4f4457 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -273,6 +273,11 @@ pub enum Op { /// to generate a summary which will be returned as an AgentMessage event. Compact, + /// Set a user-facing thread name in the persisted rollout metadata. + /// This is a local-only operation handled by codex-core; it does not + /// involve the model. + SetThreadName { name: String }, + /// Request Codex to undo a turn (turn are stacked so it is the same effect as CMD + Z). Undo, @@ -735,6 +740,9 @@ pub enum EventMsg { /// Ack the client's configure message. SessionConfigured(SessionConfiguredEvent), + /// Updated session metadata (e.g., thread name changes). + ThreadNameUpdated(ThreadNameUpdatedEvent), + /// Incremental MCP startup progress updates. McpStartupUpdate(McpStartupUpdateEvent), @@ -2186,11 +2194,15 @@ pub struct SkillsListEntry { #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct SessionConfiguredEvent { - /// Name left as session_id instead of thread_id for backwards compatibility. pub session_id: ThreadId, #[serde(skip_serializing_if = "Option::is_none")] pub forked_from_id: Option, + /// Optional user-facing thread name (may be unset). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub thread_name: Option, + /// Tell the client what model is being queried. pub model: String, @@ -2226,6 +2238,14 @@ pub struct SessionConfiguredEvent { pub rollout_path: Option, } +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +pub struct ThreadNameUpdatedEvent { + pub thread_id: ThreadId, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub thread_name: Option, +} + /// User's decision in response to an ExecApprovalRequest. #[derive(Debug, Default, Clone, Deserialize, Serialize, PartialEq, Eq, Display, JsonSchema, TS)] #[serde(rename_all = "snake_case")] @@ -2569,6 +2589,7 @@ mod tests { msg: EventMsg::SessionConfigured(SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, + thread_name: None, model: "codex-mini-latest".to_string(), model_provider_id: "openai".to_string(), approval_policy: AskForApproval::Never, diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 6664e7f9c5..7f7fe51c5d 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -94,6 +94,7 @@ tree-sitter-highlight = { workspace = true } unicode-segmentation = { workspace = true } unicode-width = { workspace = true } url = { workspace = true } +uuid = { workspace = true } codex-windows-sandbox = { workspace = true } tokio-util = { workspace = true, features = ["time"] } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index fe33df8378..107e9f6ed6 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -108,6 +108,7 @@ const THREAD_EVENT_CHANNEL_CAPACITY: usize = 32768; pub struct AppExitInfo { pub token_usage: TokenUsage, pub thread_id: Option, + pub thread_name: Option, pub update_action: Option, pub exit_reason: ExitReason, } @@ -117,6 +118,7 @@ impl AppExitInfo { Self { token_usage: TokenUsage::default(), thread_id: None, + thread_name: None, update_action: None, exit_reason: ExitReason::Fatal(message.into()), } @@ -135,13 +137,17 @@ pub enum ExitReason { Fatal(String), } -fn session_summary(token_usage: TokenUsage, thread_id: Option) -> Option { +fn session_summary( + token_usage: TokenUsage, + thread_id: Option, + thread_name: Option, +) -> Option { if token_usage.is_zero() { return None; } let usage_line = FinalOutput::from(token_usage).to_string(); - let resume_command = thread_id.map(|thread_id| format!("codex resume {thread_id}")); + let resume_command = codex_core::util::resume_command(thread_name.as_deref(), thread_id); Some(SessionSummary { usage_line, resume_command, @@ -496,6 +502,7 @@ async fn handle_model_migration_prompt_if_needed( return Some(AppExitInfo { token_usage: TokenUsage::default(), thread_id: None, + thread_name: None, update_action: None, exit_reason: ExitReason::UserRequested, }); @@ -1208,6 +1215,7 @@ impl App { Ok(AppExitInfo { token_usage: app.token_usage(), thread_id: app.chat_widget.thread_id(), + thread_name: app.chat_widget.thread_name(), update_action: app.pending_update_action, exit_reason, }) @@ -1269,8 +1277,11 @@ impl App { match event { AppEvent::NewSession => { let model = self.chat_widget.current_model().to_string(); - let summary = - session_summary(self.chat_widget.token_usage(), self.chat_widget.thread_id()); + let summary = session_summary( + self.chat_widget.token_usage(), + self.chat_widget.thread_id(), + self.chat_widget.thread_name(), + ); self.shutdown_current_thread().await; if let Err(err) = self.server.remove_and_close_all_threads().await { tracing::warn!(error = %err, "failed to close all threads"); @@ -1343,6 +1354,7 @@ impl App { let summary = session_summary( self.chat_widget.token_usage(), self.chat_widget.thread_id(), + self.chat_widget.thread_name(), ); match self .server @@ -1401,8 +1413,11 @@ impl App { tui.frame_requester().schedule_frame(); } AppEvent::ForkCurrentSession => { - let summary = - session_summary(self.chat_widget.token_usage(), self.chat_widget.thread_id()); + let summary = session_summary( + self.chat_widget.token_usage(), + self.chat_widget.thread_id(), + self.chat_widget.thread_name(), + ); if let Some(path) = self.chat_widget.rollout_path() { match self .server @@ -2241,6 +2256,7 @@ impl App { msg: EventMsg::SessionConfigured(SessionConfiguredEvent { session_id: thread_id, forked_from_id: None, + thread_name: None, model: config_snapshot.model, model_provider_id: config_snapshot.model_provider_id, approval_policy: config_snapshot.approval_policy, @@ -2908,6 +2924,7 @@ mod tests { let event = SessionConfiguredEvent { session_id: ThreadId::new(), forked_from_id: None, + thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, @@ -2960,6 +2977,7 @@ mod tests { msg: EventMsg::SessionConfigured(SessionConfiguredEvent { session_id: base_id, forked_from_id: None, + thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, @@ -3005,6 +3023,7 @@ mod tests { let event = 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, @@ -3036,7 +3055,7 @@ mod tests { #[tokio::test] async fn session_summary_skip_zero_usage() { - assert!(session_summary(TokenUsage::default(), None).is_none()); + assert!(session_summary(TokenUsage::default(), None, None).is_none()); } #[tokio::test] @@ -3049,7 +3068,7 @@ mod tests { }; let conversation = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap(); - let summary = session_summary(usage, Some(conversation)).expect("summary"); + let summary = session_summary(usage, Some(conversation), None).expect("summary"); assert_eq!( summary.usage_line, "Token usage: total=12 input=10 output=2" @@ -3059,4 +3078,22 @@ mod tests { Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string()) ); } + + #[tokio::test] + async fn session_summary_prefers_name_over_id() { + let usage = TokenUsage { + input_tokens: 10, + output_tokens: 2, + total_tokens: 12, + ..Default::default() + }; + let conversation = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap(); + + let summary = session_summary(usage, Some(conversation), Some("my-session".to_string())) + .expect("summary"); + assert_eq!( + summary.resume_command, + Some("codex resume my-session".to_string()) + ); + } } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 90cae4b4a0..7c8b7585ac 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -2054,7 +2054,7 @@ impl ChatComposer { self.personality_command_enabled, self.windows_degraded_sandbox_active, ) - && cmd == SlashCommand::Review + && matches!(cmd, SlashCommand::Review | SlashCommand::Rename) { self.textarea.set_text_clearing_elements(""); return Some(InputResult::CommandWithArgs(cmd, rest.to_string())); diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 9857956ed9..8223c40ce0 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -23,6 +23,7 @@ use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -197,7 +198,6 @@ use self::skills::collect_tool_mentions; use self::skills::find_app_mentions; use self::skills::find_skill_mentions_with_tool_mentions; use crate::streaming::controller::StreamController; -use std::path::Path; use chrono::Local; use codex_common::approval_presets::ApprovalPreset; @@ -517,6 +517,7 @@ pub(crate) struct ChatWidget { // Previous status header to restore after a transient stream retry. retry_status_header: Option, thread_id: Option, + thread_name: Option, forked_from: Option, frame_requester: FrameRequester, // Whether to include the initial welcome banner on session configured @@ -788,6 +789,7 @@ impl ChatWidget { self.set_skills(None); self.bottom_pane.set_connectors_snapshot(None); self.thread_id = Some(event.session_id); + self.thread_name = event.thread_name.clone(); self.forked_from = event.forked_from_id; self.current_rollout_path = event.rollout_path.clone(); let initial_messages = event.initial_messages.clone(); @@ -828,6 +830,13 @@ impl ChatWidget { } } + fn on_thread_name_updated(&mut self, event: codex_core::protocol::ThreadNameUpdatedEvent) { + if self.thread_id == Some(event.thread_id) { + self.thread_name = event.thread_name; + self.request_redraw(); + } + } + fn set_skills(&mut self, skills: Option>) { self.bottom_pane.set_skills(skills); } @@ -2167,6 +2176,7 @@ impl ChatWidget { current_status_header: String::from("Working"), retry_status_header: None, thread_id: None, + thread_name: None, forked_from: None, queued_user_messages: VecDeque::new(), show_welcome_banner: is_first_run, @@ -2307,6 +2317,7 @@ impl ChatWidget { current_status_header: String::from("Working"), retry_status_header: None, thread_id: None, + thread_name: None, forked_from: None, saw_plan_update_this_turn: false, queued_user_messages: VecDeque::new(), @@ -2436,6 +2447,7 @@ impl ChatWidget { current_status_header: String::from("Working"), retry_status_header: None, thread_id: None, + thread_name: None, forked_from: None, queued_user_messages: VecDeque::new(), show_welcome_banner: false, @@ -2706,6 +2718,9 @@ impl ChatWidget { SlashCommand::Review => { self.open_review_popup(); } + SlashCommand::Rename => { + self.show_rename_prompt(); + } SlashCommand::Model => { self.open_model_popup(); } @@ -2907,6 +2922,17 @@ impl ChatWidget { let trimmed = args.trim(); match cmd { + SlashCommand::Rename if !trimmed.is_empty() => { + let Some(name) = codex_core::util::normalize_thread_name(trimmed) else { + self.add_error_message("Thread name cannot be empty.".to_string()); + return; + }; + let cell = Self::rename_confirmation_cell(&name, self.thread_id); + self.add_boxed_history(Box::new(cell)); + self.request_redraw(); + self.app_event_tx + .send(AppEvent::CodexOp(Op::SetThreadName { name })); + } SlashCommand::Collab | SlashCommand::Plan => { let _ = trimmed; self.dispatch_command(cmd); @@ -2925,6 +2951,38 @@ impl ChatWidget { } } + fn show_rename_prompt(&mut self) { + let tx = self.app_event_tx.clone(); + let has_name = self + .thread_name + .as_ref() + .is_some_and(|name| !name.is_empty()); + let title = if has_name { + "Rename thread" + } else { + "Name thread" + }; + let thread_id = self.thread_id; + let view = CustomPromptView::new( + title.to_string(), + "Type a name and press Enter".to_string(), + None, + Box::new(move |name: String| { + let Some(name) = codex_core::util::normalize_thread_name(&name) else { + tx.send(AppEvent::InsertHistoryCell(Box::new( + history_cell::new_error_event("Thread name cannot be empty.".to_string()), + ))); + return; + }; + let cell = Self::rename_confirmation_cell(&name, thread_id); + tx.send(AppEvent::InsertHistoryCell(Box::new(cell))); + tx.send(AppEvent::CodexOp(Op::SetThreadName { name })); + }), + ); + + self.bottom_pane.show_view(Box::new(view)); + } + pub(crate) fn handle_paste(&mut self, text: String) { self.bottom_pane.handle_paste(text); } @@ -3125,7 +3183,10 @@ impl ChatWidget { /// distinguish replayed events from live ones. fn replay_initial_messages(&mut self, events: Vec) { for msg in events { - if matches!(msg, EventMsg::SessionConfigured(_)) { + if matches!( + msg, + EventMsg::SessionConfigured(_) | EventMsg::ThreadNameUpdated(_) + ) { continue; } // `id: None` indicates a synthetic/fake id coming from replay. @@ -3169,6 +3230,7 @@ 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 }) => self.on_agent_message(message), EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta }) => { self.on_agent_message_delta(delta) @@ -3468,6 +3530,7 @@ impl ChatWidget { token_info, total_usage, &self.thread_id, + self.thread_name.clone(), self.forked_from, self.rate_limit_snapshot.as_ref(), self.plan_type, @@ -5275,6 +5338,20 @@ impl ChatWidget { self.request_redraw(); } + fn rename_confirmation_cell(name: &str, thread_id: Option) -> PlainHistoryCell { + let resume_cmd = codex_core::util::resume_command(Some(name), thread_id) + .unwrap_or_else(|| format!("codex resume {name}")); + let name = name.to_string(); + let line = vec![ + "• ".into(), + "Thread renamed to ".into(), + name.cyan(), + ", to resume this thread run ".into(), + resume_cmd.cyan(), + ]; + PlainHistoryCell::new(vec![line.into()]) + } + pub(crate) fn add_mcp_output(&mut self) { if self.config.mcp_servers.is_empty() { self.add_to_history(history_cell::empty_mcp_output()); @@ -5796,6 +5873,9 @@ impl ChatWidget { self.thread_id } + pub(crate) fn thread_name(&self) -> Option { + self.thread_name.clone() + } pub(crate) fn rollout_path(&self) -> Option { self.current_rollout_path.clone() } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 144fc199c5..331afdf90a 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -134,6 +134,7 @@ async fn resumed_initial_messages_render_history() { let configured = codex_core::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, + thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, @@ -200,6 +201,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() { let configured = codex_core::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, + thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, @@ -252,6 +254,7 @@ async fn submission_preserves_text_elements_and_local_images() { let configured = codex_core::protocol::SessionConfiguredEvent { session_id: conversation_id, forked_from_id: None, + thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), approval_policy: AskForApproval::Never, @@ -823,6 +826,7 @@ async fn make_chatwidget_manual( current_status_header: String::from("Working"), retry_status_header: None, thread_id: None, + thread_name: None, forked_from: None, frame_requester: FrameRequester::test_dummy(), show_welcome_banner: true, diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 010f8c83e5..c9f307dbe4 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -26,6 +26,7 @@ use codex_core::config::resolve_oss_provider; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::format_config_error_with_source; use codex_core::find_thread_path_by_id_str; +use codex_core::find_thread_path_by_name_str; use codex_core::path_utils; use codex_core::protocol::AskForApproval; use codex_core::read_session_meta_line; @@ -47,6 +48,7 @@ use tracing::error; use tracing_appender::non_blocking; use tracing_subscriber::EnvFilter; use tracing_subscriber::prelude::*; +use uuid::Uuid; mod additional_dirs; mod app; @@ -411,6 +413,7 @@ async fn run_ratatui_app( return Ok(AppExitInfo { token_usage: codex_core::protocol::TokenUsage::default(), thread_id: None, + thread_name: None, update_action: Some(action), exit_reason: ExitReason::UserRequested, }); @@ -451,6 +454,7 @@ async fn run_ratatui_app( return Ok(AppExitInfo { token_usage: codex_core::protocol::TokenUsage::default(), thread_id: None, + thread_name: None, update_action: None, exit_reason: ExitReason::UserRequested, }); @@ -484,6 +488,7 @@ async fn run_ratatui_app( Ok(AppExitInfo { token_usage: codex_core::protocol::TokenUsage::default(), thread_id: None, + thread_name: None, update_action: None, exit_reason: ExitReason::Fatal(format!( "No saved session found with ID {id_str}. Run `codex {action}` without an ID to choose from existing sessions." @@ -494,7 +499,13 @@ async fn run_ratatui_app( let use_fork = cli.fork_picker || cli.fork_last || cli.fork_session_id.is_some(); let session_selection = if use_fork { if let Some(id_str) = cli.fork_session_id.as_deref() { - match find_thread_path_by_id_str(&config.codex_home, id_str).await? { + let is_uuid = Uuid::parse_str(id_str).is_ok(); + let path = if is_uuid { + find_thread_path_by_id_str(&config.codex_home, id_str).await? + } else { + find_thread_path_by_name_str(&config.codex_home, id_str).await? + }; + match path { Some(path) => resume_picker::SessionSelection::Fork(path), None => return missing_session_exit(id_str, "fork"), } @@ -533,6 +544,7 @@ async fn run_ratatui_app( return Ok(AppExitInfo { token_usage: codex_core::protocol::TokenUsage::default(), thread_id: None, + thread_name: None, update_action: None, exit_reason: ExitReason::UserRequested, }); @@ -543,7 +555,13 @@ async fn run_ratatui_app( resume_picker::SessionSelection::StartFresh } } else if let Some(id_str) = cli.resume_session_id.as_deref() { - match find_thread_path_by_id_str(&config.codex_home, id_str).await? { + let is_uuid = Uuid::parse_str(id_str).is_ok(); + let path = if is_uuid { + find_thread_path_by_id_str(&config.codex_home, id_str).await? + } else { + find_thread_path_by_name_str(&config.codex_home, id_str).await? + }; + match path { Some(path) => resume_picker::SessionSelection::Resume(path), None => return missing_session_exit(id_str, "resume"), } @@ -584,6 +602,7 @@ async fn run_ratatui_app( return Ok(AppExitInfo { token_usage: codex_core::protocol::TokenUsage::default(), thread_id: None, + thread_name: None, update_action: None, exit_reason: ExitReason::UserRequested, }); diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 9488577c1b..4b68645aef 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -20,6 +20,7 @@ pub enum SlashCommand { Experimental, Skills, Review, + Rename, New, Resume, Fork, @@ -53,6 +54,7 @@ impl SlashCommand { SlashCommand::Init => "create an AGENTS.md file with instructions for Codex", SlashCommand::Compact => "summarize conversation to prevent hitting the context limit", SlashCommand::Review => "review my current changes and find issues", + SlashCommand::Rename => "rename the current thread", SlashCommand::Resume => "resume a saved chat", SlashCommand::Fork => "fork the current chat", // SlashCommand::Undo => "ask Codex to undo a turn", @@ -103,6 +105,7 @@ impl SlashCommand { | SlashCommand::Review | SlashCommand::Logout => false, SlashCommand::Diff + | SlashCommand::Rename | SlashCommand::Mention | SlashCommand::Skills | SlashCommand::Status diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index 5e2fe57b8a..23005274db 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -68,6 +68,7 @@ struct StatusHistoryCell { collaboration_mode: Option, model_provider: Option, account: Option, + thread_name: Option, session_id: Option, forked_from: Option, token_usage: StatusTokenUsageData, @@ -81,6 +82,7 @@ pub(crate) fn new_status_output( token_info: Option<&TokenUsageInfo>, total_usage: &TokenUsage, session_id: &Option, + thread_name: Option, forked_from: Option, rate_limits: Option<&RateLimitSnapshotDisplay>, plan_type: Option, @@ -96,6 +98,7 @@ pub(crate) fn new_status_output( token_info, total_usage, session_id, + thread_name, forked_from, rate_limits, plan_type, @@ -116,6 +119,7 @@ impl StatusHistoryCell { token_info: Option<&TokenUsageInfo>, total_usage: &TokenUsage, session_id: &Option, + thread_name: Option, forked_from: Option, rate_limits: Option<&RateLimitSnapshotDisplay>, plan_type: Option, @@ -197,6 +201,7 @@ impl StatusHistoryCell { collaboration_mode: collaboration_mode.map(ToString::to_string), model_provider, account, + thread_name, session_id, forked_from, token_usage, @@ -377,6 +382,7 @@ impl HistoryCell for StatusHistoryCell { .map(str::to_string) .collect(); let mut seen: BTreeSet = labels.iter().cloned().collect(); + let thread_name = self.thread_name.as_deref().filter(|name| !name.is_empty()); if self.model_provider.is_some() { push_label(&mut labels, &mut seen, "Model provider"); @@ -384,6 +390,9 @@ impl HistoryCell for StatusHistoryCell { if account_value.is_some() { push_label(&mut labels, &mut seen, "Account"); } + if thread_name.is_some() { + push_label(&mut labels, &mut seen, "Thread name"); + } if self.session_id.is_some() { push_label(&mut labels, &mut seen, "Session"); } @@ -442,10 +451,12 @@ impl HistoryCell for StatusHistoryCell { lines.push(formatter.line("Account", vec![Span::from(account_value)])); } + if let Some(thread_name) = thread_name { + lines.push(formatter.line("Thread name", vec![Span::from(thread_name.to_string())])); + } if let Some(collab_mode) = self.collaboration_mode.as_ref() { lines.push(formatter.line("Collaboration mode", vec![Span::from(collab_mode.clone())])); } - if let Some(session) = self.session_id.as_ref() { lines.push(formatter.line("Session", vec![Span::from(session.clone())])); } diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index 92ed340817..c8844904ab 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -148,6 +148,7 @@ async fn status_snapshot_includes_reasoning_details() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -200,6 +201,7 @@ async fn status_snapshot_includes_forked_from() { Some(&token_info), &usage, &Some(session_id), + None, Some(forked_from), None, None, @@ -260,6 +262,7 @@ async fn status_snapshot_includes_monthly_limit() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -307,6 +310,7 @@ async fn status_snapshot_shows_unlimited_credits() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -353,6 +357,7 @@ async fn status_snapshot_shows_positive_credits() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -399,6 +404,7 @@ async fn status_snapshot_hides_zero_credits() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -443,6 +449,7 @@ async fn status_snapshot_hides_when_has_no_credits_flag() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -489,6 +496,7 @@ async fn status_card_token_usage_excludes_cached_tokens() { None, None, None, + None, now, &model_slug, None, @@ -546,6 +554,7 @@ async fn status_snapshot_truncates_in_narrow_terminal() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -596,6 +605,7 @@ async fn status_snapshot_shows_missing_limits_message() { None, None, None, + None, now, &model_slug, None, @@ -660,6 +670,7 @@ async fn status_snapshot_includes_credits_and_limits() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -714,6 +725,7 @@ async fn status_snapshot_shows_empty_limits_message() { &usage, &None, None, + None, Some(&rate_display), None, captured_at, @@ -777,6 +789,7 @@ async fn status_snapshot_shows_stale_limits_message() { &usage, &None, None, + None, Some(&rate_display), None, now, @@ -844,6 +857,7 @@ async fn status_snapshot_cached_limits_hide_credits_without_flag() { &usage, &None, None, + None, Some(&rate_display), None, now, @@ -903,6 +917,7 @@ async fn status_context_window_uses_last_usage() { None, None, None, + None, now, &model_slug, None, diff --git a/codex-rs/tui/tooltips.txt b/codex-rs/tui/tooltips.txt index 84a96f54d0..a8521f359f 100644 --- a/codex-rs/tui/tooltips.txt +++ b/codex-rs/tui/tooltips.txt @@ -9,6 +9,7 @@ Use /status to see the current model, approvals, and token usage. Use /fork to branch the current chat into a new thread. Use /init to create an AGENTS.md with project-specific guidance. Use /mcp to list configured MCP tools. +Use /rename to rename your threads for easier thread resuming. Use the OpenAI docs MCP for API questions; enable it with `codex mcp add openaiDeveloperDocs --url https://developers.openai.com/mcp`. Join the OpenAI community Discord: http://discord.gg/openai Visit the Codex community forum: https://community.openai.com/c/codex/37 From e85d019daaa4c42fc9404678f5dec52e424c9f6a Mon Sep 17 00:00:00 2001 From: gt-oai Date: Fri, 30 Jan 2026 12:03:29 +0000 Subject: [PATCH 099/116] Fetch Requirements from cloud (#10167) Load requirements from Codex Backend. It only does this for enterprise customers signed in with ChatGPT. Todo in follow-up PRs: * Add to app-server and exec too * Switch from fail-open to fail-closed on failure --- codex-rs/Cargo.lock | 20 ++ codex-rs/Cargo.toml | 2 + codex-rs/cloud-requirements/BUILD.bazel | 6 + codex-rs/cloud-requirements/Cargo.toml | 26 ++ codex-rs/cloud-requirements/src/lib.rs | 338 ++++++++++++++++++ codex-rs/core/src/config/mod.rs | 35 +- codex-rs/core/src/config/service.rs | 1 + codex-rs/core/src/config_loader/README.md | 3 +- .../src/config_loader/cloud_requirements.rs | 56 +++ .../src/config_loader/config_requirements.rs | 31 ++ codex-rs/core/src/config_loader/mod.rs | 11 + codex-rs/core/src/config_loader/tests.rs | 103 ++++++ codex-rs/core/src/skills/manager.rs | 1 + codex-rs/exec-server/src/posix.rs | 1 + codex-rs/network-proxy/src/state.rs | 7 +- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/lib.rs | 48 ++- 17 files changed, 673 insertions(+), 17 deletions(-) create mode 100644 codex-rs/cloud-requirements/BUILD.bazel create mode 100644 codex-rs/cloud-requirements/Cargo.toml create mode 100644 codex-rs/cloud-requirements/src/lib.rs create mode 100644 codex-rs/core/src/config_loader/cloud_requirements.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 35d3129106..44f35f78ae 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1292,6 +1292,25 @@ dependencies = [ "zstd", ] +[[package]] +name = "codex-cloud-requirements" +version = "0.0.0" +dependencies = [ + "async-trait", + "base64", + "codex-app-server-protocol", + "codex-backend-client", + "codex-core", + "codex-otel", + "codex-protocol", + "pretty_assertions", + "serde_json", + "tempfile", + "tokio", + "toml 0.9.5", + "tracing", +] + [[package]] name = "codex-cloud-tasks" version = "0.0.0" @@ -1895,6 +1914,7 @@ dependencies = [ "codex-backend-client", "codex-chatgpt", "codex-cli", + "codex-cloud-requirements", "codex-common", "codex-core", "codex-feedback", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 5196213991..327e6beeb0 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -11,6 +11,7 @@ members = [ "arg0", "feedback", "codex-backend-openapi-models", + "cloud-requirements", "cloud-tasks", "cloud-tasks-client", "cli", @@ -71,6 +72,7 @@ codex-apply-patch = { path = "apply-patch" } codex-arg0 = { path = "arg0" } codex-async-utils = { path = "async-utils" } codex-backend-client = { path = "backend-client" } +codex-cloud-requirements = { path = "cloud-requirements" } codex-chatgpt = { path = "chatgpt" } codex-cli = { path = "cli"} codex-client = { path = "codex-client" } diff --git a/codex-rs/cloud-requirements/BUILD.bazel b/codex-rs/cloud-requirements/BUILD.bazel new file mode 100644 index 0000000000..88243aff90 --- /dev/null +++ b/codex-rs/cloud-requirements/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "cloud-requirements", + crate_name = "codex_cloud_requirements", +) diff --git a/codex-rs/cloud-requirements/Cargo.toml b/codex-rs/cloud-requirements/Cargo.toml new file mode 100644 index 0000000000..2bfde660bf --- /dev/null +++ b/codex-rs/cloud-requirements/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "codex-cloud-requirements" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +async-trait = { workspace = true } +codex-app-server-protocol = { workspace = true } +codex-backend-client = { workspace = true } +codex-core = { workspace = true } +codex-otel = { workspace = true } +codex-protocol = { workspace = true } +tokio = { workspace = true, features = ["sync", "time"] } +toml = { workspace = true } +tracing = { workspace = true } + +[dev-dependencies] +base64 = { workspace = true } +pretty_assertions = { workspace = true } +serde_json = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt", "test-util", "time"] } diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs new file mode 100644 index 0000000000..ccfa600319 --- /dev/null +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -0,0 +1,338 @@ +//! Cloud-hosted config requirements for Codex. +//! +//! This crate fetches `requirements.toml` data from the backend as an alternative to loading it +//! from the local filesystem. It only applies to Enterprise ChatGPT customers. +//! +//! Today, fetching is best-effort: on error or timeout, Codex continues without cloud requirements. +//! We expect to tighten this so that Enterprise ChatGPT customers must successfully fetch these +//! requirements before Codex will run. + +use async_trait::async_trait; +use codex_app_server_protocol::AuthMode; +use codex_backend_client::Client as BackendClient; +use codex_core::AuthManager; +use codex_core::auth::CodexAuth; +use codex_core::config_loader::CloudRequirementsLoader; +use codex_core::config_loader::ConfigRequirementsToml; +use codex_protocol::account::PlanType; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; +use tokio::time::timeout; + +/// This blocks codecs startup, so must be short. +const CLOUD_REQUIREMENTS_TIMEOUT: Duration = Duration::from_secs(5); + +#[async_trait] +trait RequirementsFetcher: Send + Sync { + /// Returns requirements as a TOML string. + /// + /// TODO(gt): For now, returns an Option. But when we want to make this fail-closed, return a + /// Result. + async fn fetch_requirements(&self, auth: &CodexAuth) -> Option; +} + +struct BackendRequirementsFetcher { + base_url: String, +} + +impl BackendRequirementsFetcher { + fn new(base_url: String) -> Self { + Self { base_url } + } +} + +#[async_trait] +impl RequirementsFetcher for BackendRequirementsFetcher { + async fn fetch_requirements(&self, auth: &CodexAuth) -> Option { + let client = BackendClient::from_auth(self.base_url.clone(), auth) + .inspect_err(|err| { + tracing::warn!( + error = %err, + "Failed to construct backend client for cloud requirements" + ); + }) + .ok()?; + + let response = client + .get_config_requirements_file() + .await + .inspect_err(|err| tracing::warn!(error = %err, "Failed to fetch cloud requirements")) + .ok()?; + + let Some(contents) = response.contents else { + tracing::warn!("Cloud requirements response missing contents"); + return None; + }; + + Some(contents) + } +} + +struct CloudRequirementsService { + auth_manager: Arc, + fetcher: Arc, + timeout: Duration, +} + +impl CloudRequirementsService { + fn new( + auth_manager: Arc, + fetcher: Arc, + timeout: Duration, + ) -> Self { + Self { + auth_manager, + fetcher, + timeout, + } + } + + async fn fetch_with_timeout(&self) -> Option { + let _timer = + codex_otel::start_global_timer("codex.cloud_requirements.fetch.duration_ms", &[]); + let started_at = Instant::now(); + let result = timeout(self.timeout, self.fetch()) + .await + .inspect_err(|_| { + tracing::warn!("Timed out waiting for cloud requirements; continuing without them"); + }) + .ok()?; + + match result.as_ref() { + Some(requirements) => { + tracing::info!( + elapsed_ms = started_at.elapsed().as_millis(), + requirements = ?requirements, + "Cloud requirements load completed" + ); + } + None => { + tracing::info!( + elapsed_ms = started_at.elapsed().as_millis(), + "Cloud requirements load completed (none)" + ); + } + } + + result + } + + async fn fetch(&self) -> Option { + let auth = self.auth_manager.auth().await?; + if !(auth.mode == AuthMode::ChatGPT + && auth.account_plan_type() == Some(PlanType::Enterprise)) + { + return None; + } + + let contents = self.fetcher.fetch_requirements(&auth).await?; + parse_cloud_requirements(&contents) + .inspect_err(|err| tracing::warn!(error = %err, "Failed to parse cloud requirements")) + .ok() + .flatten() + } +} + +pub fn cloud_requirements_loader( + auth_manager: Arc, + chatgpt_base_url: String, +) -> CloudRequirementsLoader { + let service = CloudRequirementsService::new( + auth_manager, + Arc::new(BackendRequirementsFetcher::new(chatgpt_base_url)), + CLOUD_REQUIREMENTS_TIMEOUT, + ); + let task = tokio::spawn(async move { service.fetch_with_timeout().await }); + CloudRequirementsLoader::new(async move { + task.await + .inspect_err(|err| tracing::warn!(error = %err, "Cloud requirements task failed")) + .ok() + .flatten() + }) +} + +fn parse_cloud_requirements( + contents: &str, +) -> Result, toml::de::Error> { + if contents.trim().is_empty() { + return Ok(None); + } + + let requirements: ConfigRequirementsToml = toml::from_str(contents)?; + if requirements.is_empty() { + Ok(None) + } else { + Ok(Some(requirements)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use base64::Engine; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use codex_core::auth::AuthCredentialsStoreMode; + use codex_protocol::protocol::AskForApproval; + use pretty_assertions::assert_eq; + use serde_json::json; + use std::future::pending; + use std::path::Path; + use tempfile::tempdir; + + fn write_auth_json(codex_home: &Path, value: serde_json::Value) -> std::io::Result<()> { + std::fs::write(codex_home.join("auth.json"), serde_json::to_string(&value)?)?; + Ok(()) + } + + fn auth_manager_with_api_key() -> Arc { + let tmp = tempdir().expect("tempdir"); + let auth_json = json!({ + "OPENAI_API_KEY": "sk-test-key", + "tokens": null, + "last_refresh": null, + }); + write_auth_json(tmp.path(), auth_json).expect("write auth"); + Arc::new(AuthManager::new( + tmp.path().to_path_buf(), + false, + AuthCredentialsStoreMode::File, + )) + } + + fn auth_manager_with_plan(plan_type: &str) -> Arc { + let tmp = tempdir().expect("tempdir"); + let header = json!({ "alg": "none", "typ": "JWT" }); + let auth_payload = json!({ + "chatgpt_plan_type": plan_type, + "chatgpt_user_id": "user-12345", + "user_id": "user-12345", + }); + let payload = json!({ + "email": "user@example.com", + "https://api.openai.com/auth": auth_payload, + }); + let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("header")); + let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).expect("payload")); + let signature_b64 = URL_SAFE_NO_PAD.encode(b"sig"); + let fake_jwt = format!("{header_b64}.{payload_b64}.{signature_b64}"); + + let auth_json = json!({ + "OPENAI_API_KEY": null, + "tokens": { + "id_token": fake_jwt, + "access_token": "test-access-token", + "refresh_token": "test-refresh-token", + }, + "last_refresh": null, + }); + write_auth_json(tmp.path(), auth_json).expect("write auth"); + Arc::new(AuthManager::new( + tmp.path().to_path_buf(), + false, + AuthCredentialsStoreMode::File, + )) + } + + fn parse_for_fetch(contents: Option<&str>) -> Option { + contents.and_then(|contents| parse_cloud_requirements(contents).ok().flatten()) + } + + struct StaticFetcher { + contents: Option, + } + + #[async_trait::async_trait] + impl RequirementsFetcher for StaticFetcher { + async fn fetch_requirements(&self, _auth: &CodexAuth) -> Option { + self.contents.clone() + } + } + + struct PendingFetcher; + + #[async_trait::async_trait] + impl RequirementsFetcher for PendingFetcher { + async fn fetch_requirements(&self, _auth: &CodexAuth) -> Option { + pending::<()>().await; + None + } + } + + #[tokio::test] + async fn fetch_cloud_requirements_skips_non_chatgpt_auth() { + let auth_manager = auth_manager_with_api_key(); + let service = CloudRequirementsService::new( + auth_manager, + Arc::new(StaticFetcher { contents: None }), + CLOUD_REQUIREMENTS_TIMEOUT, + ); + let result = service.fetch().await; + assert!(result.is_none()); + } + + #[tokio::test] + async fn fetch_cloud_requirements_skips_non_enterprise_plan() { + let auth_manager = auth_manager_with_plan("pro"); + let service = CloudRequirementsService::new( + auth_manager, + Arc::new(StaticFetcher { contents: None }), + CLOUD_REQUIREMENTS_TIMEOUT, + ); + let result = service.fetch().await; + assert!(result.is_none()); + } + + #[tokio::test] + async fn fetch_cloud_requirements_handles_missing_contents() { + let result = parse_for_fetch(None); + assert!(result.is_none()); + } + + #[tokio::test] + async fn fetch_cloud_requirements_handles_empty_contents() { + let result = parse_for_fetch(Some(" ")); + assert!(result.is_none()); + } + + #[tokio::test] + async fn fetch_cloud_requirements_handles_invalid_toml() { + let result = parse_for_fetch(Some("not = [")); + assert!(result.is_none()); + } + + #[tokio::test] + async fn fetch_cloud_requirements_ignores_empty_requirements() { + let result = parse_for_fetch(Some("# comment")); + assert!(result.is_none()); + } + + #[tokio::test] + async fn fetch_cloud_requirements_parses_valid_toml() { + let result = parse_for_fetch(Some("allowed_approval_policies = [\"never\"]")); + + assert_eq!( + result, + Some(ConfigRequirementsToml { + allowed_approval_policies: Some(vec![AskForApproval::Never]), + allowed_sandbox_modes: None, + mcp_servers: None, + }) + ); + } + + #[tokio::test(start_paused = true)] + async fn fetch_cloud_requirements_times_out() { + let auth_manager = auth_manager_with_plan("enterprise"); + let service = CloudRequirementsService::new( + auth_manager, + Arc::new(PendingFetcher), + CLOUD_REQUIREMENTS_TIMEOUT, + ); + let handle = tokio::spawn(async move { service.fetch_with_timeout().await }); + tokio::time::advance(CLOUD_REQUIREMENTS_TIMEOUT + Duration::from_millis(1)).await; + + let result = handle.await.expect("cloud requirements task"); + assert!(result.is_none()); + } +} diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index bc7dba6d71..fbd8999918 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -18,6 +18,7 @@ use crate::config::types::ShellEnvironmentPolicyToml; use crate::config::types::SkillsConfig; use crate::config::types::Tui; use crate::config::types::UriBasedFileOpener; +use crate::config_loader::CloudRequirementsLoader; use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigRequirements; use crate::config_loader::LoaderOverrides; @@ -366,6 +367,7 @@ pub struct ConfigBuilder { cli_overrides: Option>, harness_overrides: Option, loader_overrides: Option, + cloud_requirements: Option, fallback_cwd: Option, } @@ -390,6 +392,11 @@ impl ConfigBuilder { self } + pub fn cloud_requirements(mut self, cloud_requirements: CloudRequirementsLoader) -> Self { + self.cloud_requirements = Some(cloud_requirements); + self + } + pub fn fallback_cwd(mut self, fallback_cwd: Option) -> Self { self.fallback_cwd = fallback_cwd; self @@ -401,6 +408,7 @@ impl ConfigBuilder { cli_overrides, harness_overrides, loader_overrides, + cloud_requirements, fallback_cwd, } = self; let codex_home = codex_home.map_or_else(find_codex_home, std::io::Result::Ok)?; @@ -413,9 +421,14 @@ impl ConfigBuilder { None => AbsolutePathBuf::current_dir()?, }; harness_overrides.cwd = Some(cwd.to_path_buf()); - let config_layer_stack = - load_config_layers_state(&codex_home, Some(cwd), &cli_overrides, loader_overrides) - .await?; + let config_layer_stack = load_config_layers_state( + &codex_home, + Some(cwd), + &cli_overrides, + loader_overrides, + cloud_requirements, + ) + .await?; let merged_toml = config_layer_stack.effective_config(); // Note that each layer in ConfigLayerStack should have resolved @@ -511,6 +524,7 @@ pub async fn load_config_as_toml_with_cli_overrides( Some(cwd.clone()), &cli_overrides, LoaderOverrides::default(), + None, ) .await?; @@ -609,9 +623,14 @@ pub async fn load_global_mcp_servers( // There is no cwd/project context for this query, so this will not include // MCP servers defined in in-repo .codex/ folders. let cwd: Option = None; - let config_layer_stack = - load_config_layers_state(codex_home, cwd, &cli_overrides, LoaderOverrides::default()) - .await?; + let config_layer_stack = load_config_layers_state( + codex_home, + cwd, + &cli_overrides, + LoaderOverrides::default(), + None, + ) + .await?; let merged_toml = config_layer_stack.effective_config(); let Some(servers_value) = merged_toml.get("mcp_servers") else { return Ok(BTreeMap::new()); @@ -2612,7 +2631,8 @@ profile = "project" let cwd = AbsolutePathBuf::try_from(codex_home.path())?; let config_layer_stack = - load_config_layers_state(codex_home.path(), Some(cwd), &Vec::new(), overrides).await?; + load_config_layers_state(codex_home.path(), Some(cwd), &Vec::new(), overrides, None) + .await?; let cfg = deserialize_config_toml_with_base( config_layer_stack.effective_config(), codex_home.path(), @@ -2739,6 +2759,7 @@ profile = "project" Some(cwd), &[("model".to_string(), TomlValue::String("cli".to_string()))], overrides, + None, ) .await?; diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/core/src/config/service.rs index 961c40e02b..82583ee8a8 100644 --- a/codex-rs/core/src/config/service.rs +++ b/codex-rs/core/src/config/service.rs @@ -376,6 +376,7 @@ impl ConfigService { cwd, &self.cli_overrides, self.loader_overrides.clone(), + None, ) .await } diff --git a/codex-rs/core/src/config_loader/README.md b/codex-rs/core/src/config_loader/README.md index 67170644f5..04b72e4ca1 100644 --- a/codex-rs/core/src/config_loader/README.md +++ b/codex-rs/core/src/config_loader/README.md @@ -10,7 +10,7 @@ This module is the canonical place to **load and describe Codex configuration la Exported from `codex_core::config_loader`: -- `load_config_layers_state(codex_home, cwd_opt, cli_overrides, overrides) -> ConfigLayerStack` +- `load_config_layers_state(codex_home, cwd_opt, cli_overrides, overrides, cloud_requirements) -> ConfigLayerStack` - `ConfigLayerStack` - `effective_config() -> toml::Value` - `origins() -> HashMap` @@ -49,6 +49,7 @@ let layers = load_config_layers_state( Some(cwd), &cli_overrides, LoaderOverrides::default(), + None, ).await?; let effective = layers.effective_config(); diff --git a/codex-rs/core/src/config_loader/cloud_requirements.rs b/codex-rs/core/src/config_loader/cloud_requirements.rs new file mode 100644 index 0000000000..7c5e3a2947 --- /dev/null +++ b/codex-rs/core/src/config_loader/cloud_requirements.rs @@ -0,0 +1,56 @@ +use crate::config_loader::ConfigRequirementsToml; +use futures::future::BoxFuture; +use futures::future::FutureExt; +use futures::future::Shared; +use std::fmt; +use std::future::Future; + +#[derive(Clone)] +pub struct CloudRequirementsLoader { + // TODO(gt): This should return a Result once we can fail-closed. + fut: Shared>>, +} + +impl CloudRequirementsLoader { + pub fn new(fut: F) -> Self + where + F: Future> + Send + 'static, + { + Self { + fut: fut.boxed().shared(), + } + } + + pub async fn get(&self) -> Option { + self.fut.clone().await + } +} + +impl fmt::Debug for CloudRequirementsLoader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CloudRequirementsLoader").finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + #[tokio::test] + async fn shared_future_runs_once() { + let counter = Arc::new(AtomicUsize::new(0)); + let counter_clone = Arc::clone(&counter); + let loader = CloudRequirementsLoader::new(async move { + counter_clone.fetch_add(1, Ordering::SeqCst); + Some(ConfigRequirementsToml::default()) + }); + + let (first, second) = tokio::join!(loader.get(), loader.get()); + assert_eq!(first, second); + assert_eq!(counter.load(Ordering::SeqCst), 1); + } +} diff --git a/codex-rs/core/src/config_loader/config_requirements.rs b/codex-rs/core/src/config_loader/config_requirements.rs index a83398c711..2c220049cf 100644 --- a/codex-rs/core/src/config_loader/config_requirements.rs +++ b/codex-rs/core/src/config_loader/config_requirements.rs @@ -13,6 +13,7 @@ use crate::config::ConstraintError; pub enum RequirementSource { Unknown, MdmManagedPreferences { domain: String, key: String }, + CloudRequirements, SystemRequirementsToml { file: AbsolutePathBuf }, LegacyManagedConfigTomlFromFile { file: AbsolutePathBuf }, LegacyManagedConfigTomlFromMdm, @@ -25,6 +26,9 @@ impl fmt::Display for RequirementSource { RequirementSource::MdmManagedPreferences { domain, key } => { write!(f, "MDM {domain}:{key}") } + RequirementSource::CloudRequirements => { + write!(f, "cloud requirements") + } RequirementSource::SystemRequirementsToml { file } => { write!(f, "{}", file.as_path().display()) } @@ -448,6 +452,33 @@ mod tests { Ok(()) } + #[test] + fn constraint_error_includes_cloud_requirements_source() -> Result<()> { + let source: ConfigRequirementsToml = from_str( + r#" + allowed_approval_policies = ["on-request"] + "#, + )?; + + let source_location = RequirementSource::CloudRequirements; + + let mut target = ConfigRequirementsWithSources::default(); + target.merge_unset_fields(source_location.clone(), source); + let requirements = ConfigRequirements::try_from(target)?; + + assert_eq!( + requirements.approval_policy.can_set(&AskForApproval::Never), + Err(ConstraintError::InvalidValue { + field_name: "approval_policy", + candidate: "Never".into(), + allowed: "[OnRequest]".into(), + requirement_source: source_location, + }) + ); + + Ok(()) + } + #[test] fn deserialize_allowed_approval_policies() -> Result<()> { let toml_str = r#" diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index 5db10f2808..0dd704cab5 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -1,3 +1,4 @@ +mod cloud_requirements; mod config_requirements; mod diagnostics; mod fingerprint; @@ -30,6 +31,7 @@ use std::io; use std::path::Path; use toml::Value as TomlValue; +pub use cloud_requirements::CloudRequirementsLoader; pub use config_requirements::ConfigRequirements; pub use config_requirements::ConfigRequirementsToml; pub use config_requirements::McpServerIdentity; @@ -69,6 +71,7 @@ const DEFAULT_PROJECT_ROOT_MARKERS: &[&str] = &[".git"]; /// earlier layer cannot be overridden by a later layer: /// /// - admin: managed preferences (*) +/// - cloud: managed cloud requirements /// - system `/etc/codex/requirements.toml` /// /// For backwards compatibility, we also load from @@ -98,6 +101,7 @@ pub async fn load_config_layers_state( cwd: Option, cli_overrides: &[(String, TomlValue)], overrides: LoaderOverrides, + cloud_requirements: Option, // TODO(gt): Once exec and app-server are wired up, we can remove the option. ) -> io::Result { let mut config_requirements_toml = ConfigRequirementsWithSources::default(); @@ -110,6 +114,13 @@ pub async fn load_config_layers_state( ) .await?; + if let Some(loader) = cloud_requirements + && let Some(requirements) = loader.get().await + { + config_requirements_toml + .merge_unset_fields(RequirementSource::CloudRequirements, requirements); + } + // Honor /etc/codex/requirements.toml. if cfg!(unix) { load_requirements_toml( diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index 4b512c150f..c213c0b2ea 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -4,11 +4,15 @@ use crate::config::CONFIG_TOML_FILE; use crate::config::ConfigBuilder; use crate::config::ConfigOverrides; use crate::config::ConfigToml; +use crate::config::ConstraintError; use crate::config::ProjectConfig; +use crate::config_loader::CloudRequirementsLoader; use crate::config_loader::ConfigLayerEntry; use crate::config_loader::ConfigLoadError; use crate::config_loader::ConfigRequirements; +use crate::config_loader::ConfigRequirementsToml; use crate::config_loader::config_requirements::ConfigRequirementsWithSources; +use crate::config_loader::config_requirements::RequirementSource; use crate::config_loader::fingerprint::version_for_toml; use crate::config_loader::load_requirements_toml; use codex_protocol::config_types::TrustLevel; @@ -65,6 +69,7 @@ async fn returns_config_error_for_invalid_user_config_toml() { Some(cwd), &[] as &[(String, TomlValue)], LoaderOverrides::default(), + None, ) .await .expect_err("expected error"); @@ -94,6 +99,7 @@ async fn returns_config_error_for_invalid_managed_config_toml() { Some(cwd), &[] as &[(String, TomlValue)], overrides, + None, ) .await .expect_err("expected error"); @@ -182,6 +188,7 @@ extra = true Some(cwd), &[] as &[(String, TomlValue)], overrides, + None, ) .await .expect("load config"); @@ -218,6 +225,7 @@ async fn returns_empty_when_all_layers_missing() { Some(cwd), &[] as &[(String, TomlValue)], overrides, + None, ) .await .expect("load layers"); @@ -315,6 +323,7 @@ flag = false Some(cwd), &[] as &[(String, TomlValue)], overrides, + None, ) .await .expect("load config"); @@ -354,6 +363,7 @@ allowed_sandbox_modes = ["read-only"] ), ), }, + None, ) .await?; @@ -414,6 +424,7 @@ allowed_approval_policies = ["never"] ), ), }, + None, ) .await?; @@ -472,6 +483,91 @@ allowed_approval_policies = ["never", "on-request"] Ok(()) } +#[tokio::test(flavor = "current_thread")] +async fn cloud_requirements_are_not_overwritten_by_system_requirements() -> anyhow::Result<()> { + let tmp = tempdir()?; + let requirements_file = tmp.path().join("requirements.toml"); + tokio::fs::write( + &requirements_file, + r#" +allowed_approval_policies = ["on-request"] +"#, + ) + .await?; + + let mut config_requirements_toml = ConfigRequirementsWithSources::default(); + config_requirements_toml.merge_unset_fields( + RequirementSource::CloudRequirements, + ConfigRequirementsToml { + allowed_approval_policies: Some(vec![AskForApproval::Never]), + allowed_sandbox_modes: None, + mcp_servers: None, + }, + ); + load_requirements_toml(&mut config_requirements_toml, &requirements_file).await?; + + assert_eq!( + config_requirements_toml + .allowed_approval_policies + .as_ref() + .map(|sourced| sourced.value.clone()), + Some(vec![AskForApproval::Never]) + ); + assert_eq!( + config_requirements_toml + .allowed_approval_policies + .as_ref() + .map(|sourced| sourced.source.clone()), + Some(RequirementSource::CloudRequirements) + ); + + Ok(()) +} + +#[tokio::test] +async fn load_config_layers_includes_cloud_requirements() -> anyhow::Result<()> { + let tmp = tempdir()?; + let codex_home = tmp.path().join("home"); + tokio::fs::create_dir_all(&codex_home).await?; + let cwd = AbsolutePathBuf::from_absolute_path(tmp.path())?; + + let requirements = ConfigRequirementsToml { + allowed_approval_policies: Some(vec![AskForApproval::Never]), + allowed_sandbox_modes: None, + mcp_servers: None, + }; + let expected = requirements.clone(); + let cloud_requirements = CloudRequirementsLoader::new(async move { Some(requirements) }); + + let layers = load_config_layers_state( + &codex_home, + Some(cwd), + &[] as &[(String, TomlValue)], + LoaderOverrides::default(), + Some(cloud_requirements), + ) + .await?; + + assert_eq!( + layers.requirements_toml().allowed_approval_policies, + expected.allowed_approval_policies + ); + assert_eq!( + layers + .requirements() + .approval_policy + .can_set(&AskForApproval::OnRequest), + Err(ConstraintError::InvalidValue { + field_name: "approval_policy", + candidate: "OnRequest".into(), + allowed: "[Never]".into(), + requirement_source: RequirementSource::CloudRequirements, + }) + ); + + Ok(()) +} + #[tokio::test] async fn project_layers_prefer_closest_cwd() -> std::io::Result<()> { let tmp = tempdir()?; @@ -501,6 +597,7 @@ async fn project_layers_prefer_closest_cwd() -> std::io::Result<()> { Some(cwd), &[] as &[(String, TomlValue)], LoaderOverrides::default(), + None, ) .await?; @@ -632,6 +729,7 @@ async fn project_layer_is_added_when_dot_codex_exists_without_config_toml() -> s Some(cwd), &[] as &[(String, TomlValue)], LoaderOverrides::default(), + None, ) .await?; @@ -691,6 +789,7 @@ async fn project_layers_disabled_when_untrusted_or_unknown() -> std::io::Result< Some(cwd.clone()), &[] as &[(String, TomlValue)], LoaderOverrides::default(), + None, ) .await?; let project_layers_untrusted: Vec<_> = layers_untrusted @@ -728,6 +827,7 @@ async fn project_layers_disabled_when_untrusted_or_unknown() -> std::io::Result< Some(cwd), &[] as &[(String, TomlValue)], LoaderOverrides::default(), + None, ) .await?; let project_layers_unknown: Vec<_> = layers_unknown @@ -788,6 +888,7 @@ async fn invalid_project_config_ignored_when_untrusted_or_unknown() -> std::io:: Some(cwd.clone()), &[] as &[(String, TomlValue)], LoaderOverrides::default(), + None, ) .await?; let project_layers: Vec<_> = layers @@ -843,6 +944,7 @@ async fn cli_overrides_with_relative_paths_do_not_break_trust_check() -> std::io Some(cwd), &cli_overrides, LoaderOverrides::default(), + None, ) .await?; @@ -884,6 +986,7 @@ async fn project_root_markers_supports_alternate_markers() -> std::io::Result<() Some(cwd), &[] as &[(String, TomlValue)], LoaderOverrides::default(), + None, ) .await?; diff --git a/codex-rs/core/src/skills/manager.rs b/codex-rs/core/src/skills/manager.rs index 8aa6986882..f71ecfffa2 100644 --- a/codex-rs/core/src/skills/manager.rs +++ b/codex-rs/core/src/skills/manager.rs @@ -88,6 +88,7 @@ impl SkillsManager { Some(cwd_abs), &cli_overrides, LoaderOverrides::default(), + None, ) .await { diff --git a/codex-rs/exec-server/src/posix.rs b/codex-rs/exec-server/src/posix.rs index 12d0055cdd..3ec623330c 100644 --- a/codex-rs/exec-server/src/posix.rs +++ b/codex-rs/exec-server/src/posix.rs @@ -241,6 +241,7 @@ async fn load_exec_policy() -> anyhow::Result { cwd, &cli_overrides, overrides, + None, ) .await?; diff --git a/codex-rs/network-proxy/src/state.rs b/codex-rs/network-proxy/src/state.rs index 552455f510..b0c8fdfbcb 100644 --- a/codex-rs/network-proxy/src/state.rs +++ b/codex-rs/network-proxy/src/state.rs @@ -31,9 +31,10 @@ pub(crate) async fn build_config_state() -> Result { let codex_home = find_codex_home().context("failed to resolve CODEX_HOME")?; let cli_overrides = Vec::new(); let overrides = LoaderOverrides::default(); - let config_layer_stack = load_config_layers_state(&codex_home, None, &cli_overrides, overrides) - .await - .context("failed to load Codex config")?; + let config_layer_stack = + load_config_layers_state(&codex_home, None, &cli_overrides, overrides, None) + .await + .context("failed to load Codex config")?; let cfg_path = codex_home.join(CONFIG_TOML_FILE); diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 7f7fe51c5d..d859aa945e 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -31,6 +31,7 @@ codex-app-server-protocol = { workspace = true } codex-arg0 = { workspace = true } codex-backend-client = { workspace = true } codex-chatgpt = { workspace = true } +codex-cloud-requirements = { workspace = true } codex-common = { workspace = true, features = [ "cli", "elapsed", diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index c9f307dbe4..a8c6e2b88b 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -8,6 +8,7 @@ use app::App; pub use app::AppExitInfo; pub use app::ExitReason; use codex_app_server_protocol::AuthMode; +use codex_cloud_requirements::cloud_requirements_loader; use codex_common::oss::ensure_oss_provider_ready; use codex_common::oss::get_default_model_for_oss_provider; use codex_common::oss::ollama_chat_deprecation_notice; @@ -23,6 +24,7 @@ use codex_core::config::ConfigOverrides; use codex_core::config::find_codex_home; use codex_core::config::load_config_as_toml_with_cli_overrides; use codex_core::config::resolve_oss_provider; +use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::format_config_error_with_source; use codex_core::find_thread_path_by_id_str; @@ -206,6 +208,17 @@ pub async fn run_main( } }; + let cloud_auth_manager = AuthManager::shared( + codex_home.to_path_buf(), + false, + config_toml.cli_auth_credentials_store.unwrap_or_default(), + ); + let chatgpt_base_url = config_toml + .chatgpt_base_url + .clone() + .unwrap_or_else(|| "https://chatgpt.com/backend-api/".to_string()); + let cloud_requirements = cloud_requirements_loader(cloud_auth_manager, chatgpt_base_url); + let model_provider_override = if cli.oss { let resolved = resolve_oss_provider( cli.oss_provider.as_deref(), @@ -257,7 +270,12 @@ pub async fn run_main( ..Default::default() }; - let config = load_config_or_exit(cli_kv_overrides.clone(), overrides.clone()).await; + let config = load_config_or_exit( + cli_kv_overrides.clone(), + overrides.clone(), + cloud_requirements.clone(), + ) + .await; if let Some(warning) = add_dir_warning_message(&cli.add_dir, config.sandbox_policy.get()) { #[allow(clippy::print_stderr)] @@ -370,9 +388,16 @@ pub async fn run_main( .with(otel_tracing_layer) .try_init(); - run_ratatui_app(cli, config, overrides, cli_kv_overrides, feedback) - .await - .map_err(|err| std::io::Error::other(err.to_string())) + run_ratatui_app( + cli, + config, + overrides, + cli_kv_overrides, + cloud_requirements, + feedback, + ) + .await + .map_err(|err| std::io::Error::other(err.to_string())) } async fn run_ratatui_app( @@ -380,6 +405,7 @@ async fn run_ratatui_app( initial_config: Config, overrides: ConfigOverrides, cli_kv_overrides: Vec<(String, toml::Value)>, + cloud_requirements: CloudRequirementsLoader, feedback: codex_feedback::CodexFeedback, ) -> color_eyre::Result { color_eyre::install()?; @@ -465,7 +491,12 @@ async fn run_ratatui_app( .map(|d| d == TrustDirectorySelection::Trust) .unwrap_or(false) { - load_config_or_exit(cli_kv_overrides.clone(), overrides.clone()).await + load_config_or_exit( + cli_kv_overrides.clone(), + overrides.clone(), + cloud_requirements.clone(), + ) + .await } else { initial_config } @@ -633,6 +664,7 @@ async fn run_ratatui_app( load_config_or_exit_with_fallback_cwd( cli_kv_overrides.clone(), overrides.clone(), + cloud_requirements.clone(), fallback_cwd, ) .await @@ -816,19 +848,23 @@ fn get_login_status(config: &Config) -> LoginStatus { async fn load_config_or_exit( cli_kv_overrides: Vec<(String, toml::Value)>, overrides: ConfigOverrides, + cloud_requirements: CloudRequirementsLoader, ) -> Config { - load_config_or_exit_with_fallback_cwd(cli_kv_overrides, overrides, None).await + load_config_or_exit_with_fallback_cwd(cli_kv_overrides, overrides, cloud_requirements, None) + .await } async fn load_config_or_exit_with_fallback_cwd( cli_kv_overrides: Vec<(String, toml::Value)>, overrides: ConfigOverrides, + cloud_requirements: CloudRequirementsLoader, fallback_cwd: Option, ) -> Config { #[allow(clippy::print_stderr)] match ConfigBuilder::default() .cli_overrides(cli_kv_overrides) .harness_overrides(overrides) + .cloud_requirements(cloud_requirements) .fallback_cwd(fallback_cwd) .build() .await From 6cee538380eb9735c1dbb91ec33c7cf9d43cac00 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 13:50:33 +0100 Subject: [PATCH 100/116] explorer prompt (#10225) --- codex-rs/core/src/agent/role.rs | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/codex-rs/core/src/agent/role.rs b/codex-rs/core/src/agent/role.rs index 7a9dda005b..76e3a373ed 100644 --- a/codex-rs/core/src/agent/role.rs +++ b/codex-rs/core/src/agent/role.rs @@ -92,20 +92,16 @@ Rules: }, AgentRole::Explorer => AgentProfile { model: Some(EXPLORER_MODEL), - reasoning_effort: Some(ReasoningEffort::Low), - description: r#"Use for fast codebase understanding and information gathering. -`explorer` are extremely fast agents so use them as much as you can to speed up the resolution of the global task. -Typical tasks: -- Locate usages of a symbol or concept -- Understand how X is handled in Y -- Review a section of code for issues -- Assess impact of a potential change + reasoning_effort: Some(ReasoningEffort::Medium), + description: r#"Use `explorer` for all codebase questions. +Explorers are fast and authoritative. +Always prefer them over manual search or file reading. Rules: -- Be explicit in what you are looking for. A good usage of `explorer` would mean that don't need to read the same code after the explorer send you the result. -- **Always** prefer asking explorers rather than exploring the codebase yourself. -- Spawn multiple explorers in parallel when useful and wait for all results. -- You can ask the `explorer` to return file name, lines, entire code snippets, ... -- Reuse the same explorer when it is relevant. If later in your process you have more questions on some code an explorer already covered, reuse this same explorer to be more efficient. +- 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. +- Reuse existing explorers for related questions. "#, ..Default::default() }, From 09d25e91e96ac87e88171764fcd8e9da950ba7e4 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 14:18:31 +0100 Subject: [PATCH 101/116] fix: make sure the shell exists (#10222) --- codex-rs/core/src/shell.rs | 1 + codex-rs/core/tests/suite/view_image.rs | 24 +++++++++++++++++------- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/shell.rs b/codex-rs/core/src/shell.rs index c866afd3bd..6cde28d2f1 100644 --- a/codex-rs/core/src/shell.rs +++ b/codex-rs/core/src/shell.rs @@ -137,6 +137,7 @@ fn get_shell_path( let default_shell_path = get_user_shell_path(); if let Some(default_shell_path) = default_shell_path && detect_shell_type(&default_shell_path) == Some(shell_type) + && file_exists(&default_shell_path).is_some() { return Some(default_shell_path); } diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index 8c79190383..b72f66fce8 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -64,7 +64,9 @@ async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> { if let Some(parent) = abs_path.parent() { std::fs::create_dir_all(parent)?; } - let image = ImageBuffer::from_pixel(4096, 1024, Rgba([20u8, 40, 60, 255])); + let original_width = 2304; + let original_height = 864; + let image = ImageBuffer::from_pixel(original_width, original_height, Rgba([20u8, 40, 60, 255])); image.save(&abs_path)?; let response = sse(vec![ @@ -93,7 +95,13 @@ async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> { }) .await?; - wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; + wait_for_event_with_timeout( + &codex, + |event| matches!(event, EventMsg::TurnComplete(_)), + // Empirically, image attachment can be slow under Bazel/RBE. + Duration::from_secs(10), + ) + .await; let body = mock.single_request().body_json(); let image_message = @@ -124,8 +132,8 @@ async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> { let (width, height) = resized.dimensions(); assert!(width <= 2048); assert!(height <= 768); - assert!(width < 4096); - assert!(height < 1024); + assert!(width < original_width); + assert!(height < original_height); Ok(()) } @@ -148,7 +156,9 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { if let Some(parent) = abs_path.parent() { std::fs::create_dir_all(parent)?; } - let image = ImageBuffer::from_pixel(4096, 1024, Rgba([255u8, 0, 0, 255])); + let original_width = 2304; + let original_height = 864; + let image = ImageBuffer::from_pixel(original_width, original_height, Rgba([255u8, 0, 0, 255])); image.save(&abs_path)?; let call_id = "view-image-call"; @@ -261,8 +271,8 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { let (resized_width, resized_height) = resized.dimensions(); assert!(resized_width <= 2048); assert!(resized_height <= 768); - assert!(resized_width < 4096); - assert!(resized_height < 1024); + assert!(resized_width < original_width); + assert!(resized_height < original_height); Ok(()) } From 887bec0dee624bbe5f3e3f064a72fb86e563a5af Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 18:23:00 +0100 Subject: [PATCH 102/116] chore: do not clean the DB anymore (#10232) --- codex-rs/core/src/rollout/recorder.rs | 2 +- codex-rs/core/src/state_db.rs | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index 8157133165..501b46271f 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -428,7 +428,7 @@ impl RolloutRecorder { } }, Err(e) => { - warn!("failed to parse rollout line: {v:?}, error: {e}"); + warn!("failed to parse rollout line: {e}"); parse_errors = parse_errors.saturating_add(1); } } diff --git a/codex-rs/core/src/state_db.rs b/codex-rs/core/src/state_db.rs index 0804273bba..3e5beaa87e 100644 --- a/codex-rs/core/src/state_db.rs +++ b/codex-rs/core/src/state_db.rs @@ -33,12 +33,6 @@ pub(crate) async fn init_if_enabled( ) -> Option { let state_path = config.codex_home.join(STATE_DB_FILENAME); if !config.features.enabled(Feature::Sqlite) { - // We delete the file on best effort basis to maintain retro-compatibility in the future. - let wal_path = state_path.with_extension("sqlite-wal"); - let shm_path = state_path.with_extension("sqlite-shm"); - for path in [state_path.as_path(), wal_path.as_path(), shm_path.as_path()] { - tokio::fs::remove_file(path).await.ok(); - } return None; } let existed = tokio::fs::try_exists(&state_path).await.unwrap_or(false); From eff11f792b6bfae2dffdfa33c904b5732194e560 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 18:23:18 +0100 Subject: [PATCH 103/116] feat: improve logs client (#10229) --- codex-rs/state/src/bin/logs_client.rs | 144 ++++++++++++++++++-------- codex-rs/state/src/model/log.rs | 7 +- codex-rs/state/src/runtime.rs | 58 ++++++++--- 3 files changed, 148 insertions(+), 61 deletions(-) diff --git a/codex-rs/state/src/bin/logs_client.rs b/codex-rs/state/src/bin/logs_client.rs index 4389c29bc6..d1329a1a89 100644 --- a/codex-rs/state/src/bin/logs_client.rs +++ b/codex-rs/state/src/bin/logs_client.rs @@ -3,8 +3,6 @@ use std::time::Duration; use anyhow::Context; use chrono::DateTime; -use chrono::SecondsFormat; -use chrono::Utc; use clap::Parser; use codex_state::LogQuery; use codex_state::LogRow; @@ -37,17 +35,21 @@ struct Args { #[arg(long, value_name = "RFC3339|UNIX")] to: Option, - /// Substring match on module_path. - #[arg(long)] - module: Option, + /// Substring match on module_path. Repeat to include multiple substrings. + #[arg(long = "module")] + module: Vec, - /// Substring match on file path. - #[arg(long)] - file: Option, + /// Substring match on file path. Repeat to include multiple substrings. + #[arg(long = "file")] + file: Vec, - /// Match a specific thread id. + /// Match one or more thread ids. Repeat to include multiple threads. + #[arg(long = "thread-id")] + thread_id: Vec, + + /// Include logs that do not have a thread id. #[arg(long)] - thread_id: Option, + threadless: bool, /// Number of matching rows to show before tailing. #[arg(long, default_value_t = 200)] @@ -63,9 +65,10 @@ struct LogFilter { level_upper: Option, from_ts: Option, to_ts: Option, - module_like: Option, - file_like: Option, - thread_id: Option, + module_like: Vec, + file_like: Vec, + thread_ids: Vec, + include_threadless: bool, } #[tokio::main] @@ -126,14 +129,33 @@ fn build_filter(args: &Args) -> anyhow::Result { .context("failed to parse --to")?; let level_upper = args.level.as_ref().map(|level| level.to_ascii_uppercase()); + let module_like = args + .module + .iter() + .filter(|module| !module.is_empty()) + .cloned() + .collect::>(); + let file_like = args + .file + .iter() + .filter(|file| !file.is_empty()) + .cloned() + .collect::>(); + let thread_ids = args + .thread_id + .iter() + .filter(|thread_id| !thread_id.is_empty()) + .cloned() + .collect::>(); Ok(LogFilter { level_upper, from_ts, to_ts, - module_like: args.module.clone(), - file_like: args.file.clone(), - thread_id: args.thread_id.clone(), + module_like, + file_like, + thread_ids, + include_threadless: args.threadless, }) } @@ -211,7 +233,8 @@ fn to_log_query( to_ts: filter.to_ts, module_like: filter.module_like.clone(), file_like: filter.file_like.clone(), - thread_id: filter.thread_id.clone(), + thread_ids: filter.thread_ids.clone(), + include_threadless: filter.include_threadless, after_id, limit, descending, @@ -219,45 +242,82 @@ fn to_log_query( } fn format_row(row: &LogRow) -> String { - let timestamp = format_timestamp(row.ts, row.ts_nanos); + let timestamp = formatter::ts(row.ts, row.ts_nanos); let level = row.level.as_str(); let target = row.target.as_str(); let message = row.message.as_deref().unwrap_or(""); - let level_colored = color_level(level); + let level_colored = formatter::level(level); let timestamp_colored = timestamp.dimmed().to_string(); let thread_id = row.thread_id.as_deref().unwrap_or("-"); let thread_id_colored = thread_id.blue().dimmed().to_string(); let target_colored = target.dimmed().to_string(); - let message_colored = message.bold().to_string(); + let message_colored = heuristic_formatting(message); format!( "{timestamp_colored} {level_colored} [{thread_id_colored}] {target_colored} - {message_colored}" ) } -fn color_level(level: &str) -> String { - let padded = format!("{level:<5}"); - if level.eq_ignore_ascii_case("error") { - return padded.red().bold().to_string(); +fn heuristic_formatting(message: &str) -> String { + if matcher::apply_patch(message) { + formatter::apply_patch(message) + } else { + message.bold().to_string() } - if level.eq_ignore_ascii_case("warn") { - return padded.yellow().bold().to_string(); - } - if level.eq_ignore_ascii_case("info") { - return padded.green().bold().to_string(); - } - if level.eq_ignore_ascii_case("debug") { - return padded.blue().bold().to_string(); - } - if level.eq_ignore_ascii_case("trace") { - return padded.magenta().bold().to_string(); - } - padded.bold().to_string() } -fn format_timestamp(ts: i64, ts_nanos: i64) -> String { - let nanos = u32::try_from(ts_nanos).unwrap_or(0); - match DateTime::::from_timestamp(ts, nanos) { - Some(dt) => dt.to_rfc3339_opts(SecondsFormat::Millis, true), - None => format!("{ts}.{ts_nanos:09}Z"), +mod matcher { + pub(super) fn apply_patch(message: &str) -> bool { + message.starts_with("ToolCall: apply_patch") + } +} + +mod formatter { + use chrono::DateTime; + use chrono::SecondsFormat; + use chrono::Utc; + use owo_colors::OwoColorize; + + pub(super) fn apply_patch(message: &str) -> String { + message + .lines() + .map(|line| { + if line.starts_with('+') { + line.green().bold().to_string() + } else if line.starts_with('-') { + line.red().bold().to_string() + } else { + line.bold().to_string() + } + }) + .collect::>() + .join("\n") + } + + pub(super) fn ts(ts: i64, ts_nanos: i64) -> String { + let nanos = u32::try_from(ts_nanos).unwrap_or(0); + match DateTime::::from_timestamp(ts, nanos) { + Some(dt) => dt.to_rfc3339_opts(SecondsFormat::Millis, true), + None => format!("{ts}.{ts_nanos:09}Z"), + } + } + + pub(super) fn level(level: &str) -> String { + let padded = format!("{level:<5}"); + if level.eq_ignore_ascii_case("error") { + return padded.red().bold().to_string(); + } + if level.eq_ignore_ascii_case("warn") { + return padded.yellow().bold().to_string(); + } + if level.eq_ignore_ascii_case("info") { + return padded.green().bold().to_string(); + } + if level.eq_ignore_ascii_case("debug") { + return padded.blue().bold().to_string(); + } + if level.eq_ignore_ascii_case("trace") { + return padded.magenta().bold().to_string(); + } + padded.bold().to_string() } } diff --git a/codex-rs/state/src/model/log.rs b/codex-rs/state/src/model/log.rs index 5d774249dd..819abb5d22 100644 --- a/codex-rs/state/src/model/log.rs +++ b/codex-rs/state/src/model/log.rs @@ -32,9 +32,10 @@ pub struct LogQuery { pub level_upper: Option, pub from_ts: Option, pub to_ts: Option, - pub module_like: Option, - pub file_like: Option, - pub thread_id: Option, + pub module_like: Vec, + pub file_like: Vec, + pub thread_ids: Vec, + pub include_threadless: bool, pub after_id: Option, pub limit: Option, pub descending: bool, diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index e0805e5b65..39c79c32b9 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -457,28 +457,54 @@ fn push_log_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, query: &'a LogQu if let Some(to_ts) = query.to_ts { builder.push(" AND ts <= ").push_bind(to_ts); } - if let Some(module_like) = query.module_like.as_ref() { - builder - .push(" AND module_path LIKE '%' || ") - .push_bind(module_like.as_str()) - .push(" || '%'"); - } - if let Some(file_like) = query.file_like.as_ref() { - builder - .push(" AND file LIKE '%' || ") - .push_bind(file_like.as_str()) - .push(" || '%'"); - } - if let Some(thread_id) = query.thread_id.as_ref() { - builder - .push(" AND thread_id = ") - .push_bind(thread_id.as_str()); + push_like_filters(builder, "module_path", &query.module_like); + push_like_filters(builder, "file", &query.file_like); + let has_thread_filter = !query.thread_ids.is_empty() || query.include_threadless; + if has_thread_filter { + builder.push(" AND ("); + let mut needs_or = false; + for thread_id in &query.thread_ids { + if needs_or { + builder.push(" OR "); + } + builder.push("thread_id = ").push_bind(thread_id.as_str()); + needs_or = true; + } + if query.include_threadless { + if needs_or { + builder.push(" OR "); + } + builder.push("thread_id IS NULL"); + } + builder.push(")"); } if let Some(after_id) = query.after_id { builder.push(" AND id > ").push_bind(after_id); } } +fn push_like_filters<'a>( + builder: &mut QueryBuilder<'a, Sqlite>, + column: &str, + filters: &'a [String], +) { + if filters.is_empty() { + return; + } + builder.push(" AND ("); + for (idx, filter) in filters.iter().enumerate() { + if idx > 0 { + builder.push(" OR "); + } + builder + .push(column) + .push(" LIKE '%' || ") + .push_bind(filter.as_str()) + .push(" || '%'"); + } + builder.push(")"); +} + async fn open_sqlite(path: &Path) -> anyhow::Result { let options = SqliteConnectOptions::new() .filename(path) From 079f4952e0bdb147769849f2f7dcc06d4100bdf0 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 18:26:49 +0100 Subject: [PATCH 104/116] feat: heuristic coloring of logs (#10228) From 0212f4010e2b66eea296202da90778ce9d44babb Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 30 Jan 2026 18:32:10 +0100 Subject: [PATCH 105/116] nit: fix db with multiple metadata lines (#10237) --- codex-rs/core/src/rollout/recorder.rs | 2 +- codex-rs/state/src/extract.rs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index 501b46271f..265ff2bde2 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -434,7 +434,7 @@ impl RolloutRecorder { } } - info!( + tracing::debug!( "Resumed rollout with {} items, thread ID: {:?}, parse errors: {}", items.len(), thread_id, diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index 9c8ce21556..8d327a4d1a 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -30,6 +30,11 @@ pub fn apply_rollout_item( } fn apply_session_meta_from_item(metadata: &mut ThreadMetadata, meta_line: &SessionMetaLine) { + if metadata.id != meta_line.meta.id { + // Ignore session_meta lines that don't match the canonical thread ID, + // e.g., forked rollouts that embed the source session metadata. + return; + } metadata.id = meta_line.meta.id; metadata.source = enum_to_string(&meta_line.meta.source); if let Some(provider) = meta_line.meta.model_provider.as_deref() { From 377ab0c77cd8609637f2fa6d7c0230fa69ce3acc Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 30 Jan 2026 09:33:23 -0800 Subject: [PATCH 106/116] feat: refactor CodexAuth so invalid state cannot be represented (#10208) Previously, `CodexAuth` was defined as follows: https://github.com/openai/codex/blob/d550fbf41afc09d7d7b5ac813aea38de07b2a73f/codex-rs/core/src/auth.rs#L39-L46 But if you looked at its constructors, we had creation for `AuthMode::ApiKey` where `storage` was built using a nonsensical path (`PathBuf::new()`) and `auth_dot_json` was `None`: https://github.com/openai/codex/blob/d550fbf41afc09d7d7b5ac813aea38de07b2a73f/codex-rs/core/src/auth.rs#L212-L220 By comparison, when `AuthMode::ChatGPT` was used, `api_key` was always `None`: https://github.com/openai/codex/blob/d550fbf41afc09d7d7b5ac813aea38de07b2a73f/codex-rs/core/src/auth.rs#L665-L671 https://github.com/openai/codex/pull/10012 took things further because it introduced a new `ChatgptAuthTokens` variant to `AuthMode`, which is important in when invoking `account/login/start` via the app server, but most logic _internal_ to the app server should just reason about two `AuthMode` variants: `ApiKey` and `ChatGPT`. This PR tries to clean things up as follows: - `LoginAccountParams` and `AuthMode` in `codex-rs/app-server-protocol/` both continue to have the `ChatgptAuthTokens` variant, though it is used exclusively for the on-the-wire messaging. - `codex-rs/core/src/auth.rs` now has its own `AuthMode` enum, which only has two variants: `ApiKey` and `ChatGPT`. - `CodexAuth` has been changed from a struct to an enum. It is a disjoint union where each variant (`ApiKey`, `ChatGpt`, and `ChatGptAuthTokens`) have only the associated fields that make sense for that variant. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/10208). * #10224 * __->__ #10208 --- .../src/protocol/common.rs | 4 - .../app-server/src/codex_message_processor.rs | 39 +- codex-rs/cli/src/login.rs | 2 +- codex-rs/core/src/auth.rs | 340 ++++++++++++------ codex-rs/core/src/client.rs | 14 +- codex-rs/core/src/codex.rs | 2 +- codex-rs/core/src/model_provider_info.rs | 9 +- codex-rs/core/src/models_manager/manager.rs | 14 +- .../core/src/models_manager/model_presets.rs | 2 +- codex-rs/tui/src/app.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 13 +- codex-rs/tui/src/lib.rs | 2 +- codex-rs/tui/src/status/helpers.rs | 8 +- 13 files changed, 286 insertions(+), 165 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 2e8778bdc5..67736374ec 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -24,10 +24,6 @@ impl GitSha { } /// Authentication mode for OpenAI-backed providers. -/// -/// This is used internally to determine the base URL for generating responses, and to gate -/// ChatGPT-only behaviors like rate limits and available models (as opposed to API key-based -/// auth). #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)] #[serde(rename_all = "lowercase")] pub enum AuthMode { diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 3817bce3a1..c02f3c7368 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -133,6 +133,7 @@ use codex_app_server_protocol::build_turns_from_event_msgs; use codex_backend_client::Client as BackendClient; use codex_chatgpt::connectors; use codex_core::AuthManager; +use codex_core::CodexAuth; use codex_core::CodexThread; use codex_core::Cursor as RolloutCursor; use codex_core::InitialHistory; @@ -686,7 +687,11 @@ impl CodexMessageProcessor { .await; let payload = AuthStatusChangeNotification { - auth_method: self.auth_manager.auth_cached().map(|auth| auth.mode), + auth_method: self + .auth_manager + .auth_cached() + .as_ref() + .map(CodexAuth::api_auth_mode), }; self.outgoing .send_server_notification(ServerNotification::AuthStatusChange(payload)) @@ -716,7 +721,11 @@ impl CodexMessageProcessor { .await; let payload_v2 = AccountUpdatedNotification { - auth_mode: self.auth_manager.auth_cached().map(|auth| auth.mode), + auth_mode: self + .auth_manager + .auth_cached() + .as_ref() + .map(CodexAuth::api_auth_mode), }; self.outgoing .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) @@ -812,7 +821,10 @@ impl CodexMessageProcessor { auth_manager.reload(); // Notify clients with the actual current auth mode. - let current_auth_method = auth_manager.auth_cached().map(|a| a.mode); + let current_auth_method = auth_manager + .auth_cached() + .as_ref() + .map(CodexAuth::api_auth_mode); let payload = AuthStatusChangeNotification { auth_method: current_auth_method, }; @@ -902,7 +914,10 @@ impl CodexMessageProcessor { auth_manager.reload(); // Notify clients with the actual current auth mode. - let current_auth_method = auth_manager.auth_cached().map(|a| a.mode); + let current_auth_method = auth_manager + .auth_cached() + .as_ref() + .map(CodexAuth::api_auth_mode); let payload_v2 = AccountUpdatedNotification { auth_mode: current_auth_method, }; @@ -1106,7 +1121,11 @@ impl CodexMessageProcessor { } // Reflect the current auth method after logout (likely None). - Ok(self.auth_manager.auth_cached().map(|auth| auth.mode)) + Ok(self + .auth_manager + .auth_cached() + .as_ref() + .map(CodexAuth::api_auth_mode)) } async fn logout_v1(&mut self, request_id: RequestId) { @@ -1178,7 +1197,7 @@ impl CodexMessageProcessor { } else { match self.auth_manager.auth().await { Some(auth) => { - let auth_mode = auth.mode; + let auth_mode = auth.api_auth_mode(); let (reported_auth_method, token_opt) = match auth.get_token() { Ok(token) if !token.is_empty() => { let tok = if include_token { Some(token) } else { None }; @@ -1225,9 +1244,9 @@ impl CodexMessageProcessor { } let account = match self.auth_manager.auth_cached() { - Some(auth) => Some(match auth.mode { - AuthMode::ApiKey => Account::ApiKey {}, - AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens => { + Some(auth) => Some(match auth { + CodexAuth::ApiKey(_) => Account::ApiKey {}, + CodexAuth::ChatGpt(_) | CodexAuth::ChatGptAuthTokens(_) => { let email = auth.get_account_email(); let plan_type = auth.account_plan_type(); @@ -1286,7 +1305,7 @@ impl CodexMessageProcessor { }); }; - if !matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) { + if !auth.is_chatgpt_auth() { return Err(JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, message: "chatgpt authentication required to read rate limits".to_string(), diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index 0f4e4eb39f..cee002f339 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -225,7 +225,7 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! { let config = load_config_or_exit(cli_config_overrides).await; match CodexAuth::from_auth_storage(&config.codex_home, config.cli_auth_credentials_store_mode) { - Ok(Some(auth)) => match auth.mode { + Ok(Some(auth)) => match auth.api_auth_mode() { AuthMode::ApiKey => match auth.get_token() { Ok(api_key) => { eprintln!("Logged in using an API key - {}", safe_format_key(&api_key)); diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index d4520dc855..4bddbe3031 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -13,8 +13,9 @@ use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::Mutex; +use std::sync::RwLock; -use codex_app_server_protocol::AuthMode; +use codex_app_server_protocol::AuthMode as ApiAuthMode; use codex_protocol::config_types::ForcedLoginMethod; pub use crate::auth::storage::AuthCredentialsStoreMode; @@ -35,19 +36,50 @@ use codex_protocol::account::PlanType as AccountPlanType; use serde_json::Value; use thiserror::Error; -#[derive(Debug, Clone)] -pub struct CodexAuth { - pub mode: AuthMode, +/// Account type for the current user. +/// +/// This is used internally to determine the base URL for generating responses, +/// and to gate ChatGPT-only behaviors like rate limits and available models (as +/// opposed to API key-based auth). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AuthMode { + ApiKey, + ChatGPT, +} - pub(crate) api_key: Option, - pub(crate) auth_dot_json: Arc>>, +/// Authentication mechanism used by the current user. +#[derive(Debug, Clone)] +pub enum CodexAuth { + ApiKey(ApiKeyAuth), + ChatGpt(ChatGptAuth), + ChatGptAuthTokens(ChatGptAuthTokens), +} + +#[derive(Debug, Clone)] +pub struct ApiKeyAuth { + api_key: String, +} + +#[derive(Debug, Clone)] +pub struct ChatGptAuth { + state: ChatGptAuthState, storage: Arc, - pub(crate) client: CodexHttpClient, +} + +#[derive(Debug, Clone)] +pub struct ChatGptAuthTokens { + state: ChatGptAuthState, +} + +#[derive(Debug, Clone)] +struct ChatGptAuthState { + auth_dot_json: Arc>>, + client: CodexHttpClient, } impl PartialEq for CodexAuth { fn eq(&self, other: &Self) -> bool { - self.mode == other.mode + self.api_auth_mode() == other.api_auth_mode() } } @@ -114,14 +146,78 @@ impl From for std::io::Error { } impl CodexAuth { + fn from_auth_dot_json( + codex_home: &Path, + auth_dot_json: AuthDotJson, + auth_credentials_store_mode: AuthCredentialsStoreMode, + client: CodexHttpClient, + ) -> std::io::Result { + let auth_mode = auth_dot_json.resolved_mode(); + if auth_mode == ApiAuthMode::ApiKey { + let Some(api_key) = auth_dot_json.openai_api_key.as_deref() else { + return Err(std::io::Error::other("API key auth is missing a key.")); + }; + return Ok(CodexAuth::from_api_key_with_client(api_key, client)); + } + + let storage_mode = auth_dot_json.storage_mode(auth_credentials_store_mode); + let state = ChatGptAuthState { + auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), + client, + }; + + match auth_mode { + ApiAuthMode::ChatGPT => { + let storage = create_auth_storage(codex_home.to_path_buf(), storage_mode); + Ok(Self::ChatGpt(ChatGptAuth { state, storage })) + } + ApiAuthMode::ChatgptAuthTokens => { + Ok(Self::ChatGptAuthTokens(ChatGptAuthTokens { state })) + } + ApiAuthMode::ApiKey => unreachable!("api key mode is handled above"), + } + } + /// Loads the available auth information from auth storage. pub fn from_auth_storage( codex_home: &Path, auth_credentials_store_mode: AuthCredentialsStoreMode, - ) -> std::io::Result> { + ) -> std::io::Result> { load_auth(codex_home, false, auth_credentials_store_mode) } + pub fn internal_auth_mode(&self) -> AuthMode { + match self { + Self::ApiKey(_) => AuthMode::ApiKey, + Self::ChatGpt(_) | Self::ChatGptAuthTokens(_) => AuthMode::ChatGPT, + } + } + + pub fn api_auth_mode(&self) -> ApiAuthMode { + match self { + Self::ApiKey(_) => ApiAuthMode::ApiKey, + Self::ChatGpt(_) => ApiAuthMode::ChatGPT, + Self::ChatGptAuthTokens(_) => ApiAuthMode::ChatgptAuthTokens, + } + } + + pub fn is_chatgpt_auth(&self) -> bool { + self.internal_auth_mode() == AuthMode::ChatGPT + } + + pub fn is_external_chatgpt_tokens(&self) -> bool { + matches!(self, Self::ChatGptAuthTokens(_)) + } + + /// Returns `None` is `is_internal_auth_mode() != AuthMode::ApiKey`. + pub fn api_key(&self) -> Option<&str> { + match self { + Self::ApiKey(auth) => Some(auth.api_key.as_str()), + Self::ChatGpt(_) | Self::ChatGptAuthTokens(_) => None, + } + } + + /// Returns `Err` if `is_chatgpt_auth()` is false. pub fn get_token_data(&self) -> Result { let auth_dot_json: Option = self.get_current_auth_json(); match auth_dot_json { @@ -134,20 +230,23 @@ impl CodexAuth { } } + /// Returns the token string used for bearer authentication. pub fn get_token(&self) -> Result { - match self.mode { - AuthMode::ApiKey => Ok(self.api_key.clone().unwrap_or_default()), - AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens => { + match self { + Self::ApiKey(auth) => Ok(auth.api_key.clone()), + Self::ChatGpt(_) | Self::ChatGptAuthTokens(_) => { let access_token = self.get_token_data()?.access_token; Ok(access_token) } } } + /// Returns `None` if `is_chatgpt_auth()` is false. pub fn get_account_id(&self) -> Option { self.get_current_token_data().and_then(|t| t.account_id) } + /// Returns `None` if `is_chatgpt_auth()` is false. pub fn get_account_email(&self) -> Option { self.get_current_token_data().and_then(|t| t.id_token.email) } @@ -176,11 +275,18 @@ impl CodexAuth { }) } + /// Returns `None` if `is_chatgpt_auth()` is false. fn get_current_auth_json(&self) -> Option { + let state = match self { + Self::ChatGpt(auth) => &auth.state, + Self::ChatGptAuthTokens(auth) => &auth.state, + Self::ApiKey(_) => return None, + }; #[expect(clippy::unwrap_used)] - self.auth_dot_json.lock().unwrap().clone() + state.auth_dot_json.lock().unwrap().clone() } + /// Returns `None` if `is_chatgpt_auth()` is false. fn get_current_token_data(&self) -> Option { self.get_current_auth_json().and_then(|t| t.tokens) } @@ -188,7 +294,7 @@ impl CodexAuth { /// Consider this private to integration tests. pub fn create_dummy_chatgpt_auth_for_testing() -> Self { let auth_dot_json = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(ApiAuthMode::ChatGPT), openai_api_key: None, tokens: Some(TokenData { id_token: Default::default(), @@ -199,24 +305,19 @@ impl CodexAuth { last_refresh: Some(Utc::now()), }; - let auth_dot_json = Arc::new(Mutex::new(Some(auth_dot_json))); - Self { - api_key: None, - mode: AuthMode::ChatGPT, - storage: create_auth_storage(PathBuf::new(), AuthCredentialsStoreMode::File), - auth_dot_json, - client: crate::default_client::create_client(), - } + let client = crate::default_client::create_client(); + let state = ChatGptAuthState { + auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), + client, + }; + let storage = create_auth_storage(PathBuf::new(), AuthCredentialsStoreMode::File); + Self::ChatGpt(ChatGptAuth { state, storage }) } - fn from_api_key_with_client(api_key: &str, client: CodexHttpClient) -> Self { - Self { - api_key: Some(api_key.to_owned()), - mode: AuthMode::ApiKey, - storage: create_auth_storage(PathBuf::new(), AuthCredentialsStoreMode::File), - auth_dot_json: Arc::new(Mutex::new(None)), - client, - } + fn from_api_key_with_client(api_key: &str, _client: CodexHttpClient) -> Self { + Self::ApiKey(ApiKeyAuth { + api_key: api_key.to_owned(), + }) } pub fn from_api_key(api_key: &str) -> Self { @@ -224,6 +325,25 @@ impl CodexAuth { } } +impl ChatGptAuth { + fn current_auth_json(&self) -> Option { + #[expect(clippy::unwrap_used)] + self.state.auth_dot_json.lock().unwrap().clone() + } + + fn current_token_data(&self) -> Option { + self.current_auth_json().and_then(|auth| auth.tokens) + } + + fn storage(&self) -> &Arc { + &self.storage + } + + fn client(&self) -> &CodexHttpClient { + &self.state.client + } +} + pub const OPENAI_API_KEY_ENV_VAR: &str = "OPENAI_API_KEY"; pub const CODEX_API_KEY_ENV_VAR: &str = "CODEX_API_KEY"; @@ -258,7 +378,7 @@ pub fn login_with_api_key( auth_credentials_store_mode: AuthCredentialsStoreMode, ) -> std::io::Result<()> { let auth_dot_json = AuthDotJson { - auth_mode: Some(AuthMode::ApiKey), + auth_mode: Some(ApiAuthMode::ApiKey), openai_api_key: Some(api_key.to_string()), tokens: None, last_refresh: None, @@ -314,10 +434,10 @@ pub fn enforce_login_restrictions(config: &Config) -> std::io::Result<()> { }; if let Some(required_method) = config.forced_login_method { - let method_violation = match (required_method, auth.mode) { + let method_violation = match (required_method, auth.internal_auth_mode()) { (ForcedLoginMethod::Api, AuthMode::ApiKey) => None, - (ForcedLoginMethod::Chatgpt, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) => None, - (ForcedLoginMethod::Api, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) => Some( + (ForcedLoginMethod::Chatgpt, AuthMode::ChatGPT) => None, + (ForcedLoginMethod::Api, AuthMode::ChatGPT) => Some( "API key login is required, but ChatGPT is currently being used. Logging out." .to_string(), ), @@ -337,7 +457,7 @@ pub fn enforce_login_restrictions(config: &Config) -> std::io::Result<()> { } if let Some(expected_account_id) = config.forced_chatgpt_workspace_id.as_deref() { - if !matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) { + if !auth.is_chatgpt_auth() { return Ok(()); } @@ -607,7 +727,7 @@ impl AuthDotJson { }; Self { - auth_mode: Some(AuthMode::ChatgptAuthTokens), + auth_mode: Some(ApiAuthMode::ChatgptAuthTokens), openai_api_key: None, tokens: Some(tokens), last_refresh: Some(Utc::now()), @@ -623,21 +743,21 @@ impl AuthDotJson { Ok(Self::from_external_tokens(&external, id_token_info)) } - fn resolved_mode(&self) -> AuthMode { + fn resolved_mode(&self) -> ApiAuthMode { if let Some(mode) = self.auth_mode { return mode; } if self.openai_api_key.is_some() { - return AuthMode::ApiKey; + return ApiAuthMode::ApiKey; } - AuthMode::ChatGPT + ApiAuthMode::ChatGPT } fn storage_mode( &self, auth_credentials_store_mode: AuthCredentialsStoreMode, ) -> AuthCredentialsStoreMode { - if self.resolved_mode() == AuthMode::ChatgptAuthTokens { + if self.resolved_mode() == ApiAuthMode::ChatgptAuthTokens { AuthCredentialsStoreMode::Ephemeral } else { auth_credentials_store_mode @@ -645,35 +765,6 @@ impl AuthDotJson { } } -impl CodexAuth { - fn from_auth_dot_json( - codex_home: &Path, - auth_dot_json: AuthDotJson, - auth_credentials_store_mode: AuthCredentialsStoreMode, - client: CodexHttpClient, - ) -> std::io::Result { - let auth_mode = auth_dot_json.resolved_mode(); - if auth_mode == AuthMode::ApiKey { - let Some(api_key) = auth_dot_json.openai_api_key.as_deref() else { - return Err(std::io::Error::other("API key auth is missing a key.")); - }; - return Ok(CodexAuth::from_api_key_with_client(api_key, client)); - } - - let storage_mode = auth_dot_json.storage_mode(auth_credentials_store_mode); - let storage = create_auth_storage(codex_home.to_path_buf(), storage_mode); - Ok(Self { - api_key: None, - mode: auth_mode, - storage, - auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), - client, - }) - } -} - -use std::sync::RwLock; - /// Internal cached auth state. #[derive(Clone)] struct CachedAuth { @@ -685,7 +776,10 @@ struct CachedAuth { impl Debug for CachedAuth { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CachedAuth") - .field("auth_mode", &self.auth.as_ref().map(|auth| auth.mode)) + .field( + "auth_mode", + &self.auth.as_ref().map(CodexAuth::api_auth_mode), + ) .field( "external_refresher", &self.external_refresher.as_ref().map(|_| "present"), @@ -736,11 +830,13 @@ impl UnauthorizedRecovery { fn new(manager: Arc) -> Self { let cached_auth = manager.auth_cached(); let expected_account_id = cached_auth.as_ref().and_then(CodexAuth::get_account_id); - let mode = match cached_auth { - Some(auth) if auth.mode == AuthMode::ChatgptAuthTokens => { - UnauthorizedRecoveryMode::External - } - _ => UnauthorizedRecoveryMode::Managed, + let mode = if cached_auth + .as_ref() + .is_some_and(CodexAuth::is_external_chatgpt_tokens) + { + UnauthorizedRecoveryMode::External + } else { + UnauthorizedRecoveryMode::Managed }; let step = match mode { UnauthorizedRecoveryMode::Managed => UnauthorizedRecoveryStep::Reload, @@ -755,9 +851,12 @@ impl UnauthorizedRecovery { } pub fn has_next(&self) -> bool { - if !self.manager.auth_cached().is_some_and(|auth| { - matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) - }) { + if !self + .manager + .auth_cached() + .as_ref() + .is_some_and(CodexAuth::is_chatgpt_auth) + { return false; } @@ -996,7 +1095,8 @@ impl AuthManager { pub fn is_external_auth_active(&self) -> bool { self.auth_cached() - .is_some_and(|auth| auth.mode == AuthMode::ChatgptAuthTokens) + .as_ref() + .is_some_and(CodexAuth::is_external_chatgpt_tokens) } /// Convenience constructor returning an `Arc` wrapper. @@ -1026,18 +1126,25 @@ impl AuthManager { Some(auth) => auth, None => return Ok(()), }; - if auth.mode == AuthMode::ChatgptAuthTokens { - return self - .refresh_external_auth(ExternalAuthRefreshReason::Unauthorized) - .await; + match auth { + CodexAuth::ChatGptAuthTokens(_) => { + self.refresh_external_auth(ExternalAuthRefreshReason::Unauthorized) + .await + } + CodexAuth::ChatGpt(chatgpt_auth) => { + let token_data = chatgpt_auth.current_token_data().ok_or_else(|| { + RefreshTokenError::Transient(std::io::Error::other( + "Token data is not available.", + )) + })?; + self.refresh_tokens(&chatgpt_auth, token_data.refresh_token) + .await?; + // Reload to pick up persisted changes. + self.reload(); + Ok(()) + } + CodexAuth::ApiKey(_) => Ok(()), } - let token_data = auth.get_current_token_data().ok_or_else(|| { - RefreshTokenError::Transient(std::io::Error::other("Token data is not available.")) - })?; - self.refresh_tokens(&auth, token_data.refresh_token).await?; - // Reload to pick up persisted changes. - self.reload(); - Ok(()) } /// Log out by deleting the on‑disk auth.json (if present). Returns Ok(true) @@ -1051,16 +1158,23 @@ impl AuthManager { Ok(removed) } - pub fn get_auth_mode(&self) -> Option { - self.auth_cached().map(|a| a.mode) + pub fn get_auth_mode(&self) -> Option { + self.auth_cached().as_ref().map(CodexAuth::api_auth_mode) + } + + pub fn get_internal_auth_mode(&self) -> Option { + self.auth_cached() + .as_ref() + .map(CodexAuth::internal_auth_mode) } async fn refresh_if_stale(&self, auth: &CodexAuth) -> Result { - if auth.mode != AuthMode::ChatGPT { - return Ok(false); - } + let chatgpt_auth = match auth { + CodexAuth::ChatGpt(chatgpt_auth) => chatgpt_auth, + _ => return Ok(false), + }; - let auth_dot_json = match auth.get_current_auth_json() { + let auth_dot_json = match chatgpt_auth.current_auth_json() { Some(auth_dot_json) => auth_dot_json, None => return Ok(false), }; @@ -1075,7 +1189,8 @@ impl AuthManager { if last_refresh >= Utc::now() - chrono::Duration::days(TOKEN_REFRESH_INTERVAL) { return Ok(false); } - self.refresh_tokens(auth, tokens.refresh_token).await?; + self.refresh_tokens(chatgpt_auth, tokens.refresh_token) + .await?; self.reload(); Ok(true) } @@ -1135,13 +1250,13 @@ impl AuthManager { async fn refresh_tokens( &self, - auth: &CodexAuth, + auth: &ChatGptAuth, refresh_token: String, ) -> Result<(), RefreshTokenError> { - let refresh_response = try_refresh_token(refresh_token, &auth.client).await?; + let refresh_response = try_refresh_token(refresh_token, auth.client()).await?; update_tokens( - &auth.storage, + auth.storage(), refresh_response.id_token, refresh_response.access_token, refresh_response.refresh_token, @@ -1254,26 +1369,21 @@ mod tests { ) .expect("failed to write auth file"); - let CodexAuth { - api_key, - mode, - auth_dot_json, - storage: _, - .. - } = super::load_auth(codex_home.path(), false, AuthCredentialsStoreMode::File) + let auth = super::load_auth(codex_home.path(), false, AuthCredentialsStoreMode::File) .unwrap() .unwrap(); - assert_eq!(None, api_key); - assert_eq!(AuthMode::ChatGPT, mode); + assert_eq!(None, auth.api_key()); + assert_eq!(AuthMode::ChatGPT, auth.internal_auth_mode()); - let guard = auth_dot_json.lock().unwrap(); - let auth_dot_json = guard.as_ref().expect("AuthDotJson should exist"); + let auth_dot_json = auth + .get_current_auth_json() + .expect("AuthDotJson should exist"); let last_refresh = auth_dot_json .last_refresh .expect("last_refresh should be recorded"); assert_eq!( - &AuthDotJson { + AuthDotJson { auth_mode: None, openai_api_key: None, tokens: Some(TokenData { @@ -1308,8 +1418,8 @@ mod tests { let auth = super::load_auth(dir.path(), false, AuthCredentialsStoreMode::File) .unwrap() .unwrap(); - assert_eq!(auth.mode, AuthMode::ApiKey); - assert_eq!(auth.api_key, Some("sk-test-key".to_string())); + assert_eq!(auth.internal_auth_mode(), AuthMode::ApiKey); + assert_eq!(auth.api_key(), Some("sk-test-key")); assert!(auth.get_token_data().is_err()); } @@ -1318,7 +1428,7 @@ mod tests { fn logout_removes_auth_file() -> Result<(), std::io::Error> { let dir = tempdir()?; let auth_dot_json = AuthDotJson { - auth_mode: Some(AuthMode::ApiKey), + auth_mode: Some(ApiAuthMode::ApiKey), openai_api_key: Some("sk-test-key".to_string()), tokens: None, last_refresh: None, diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 0f05f58c47..f01c145e56 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -27,7 +27,6 @@ use codex_api::common::ResponsesWsRequest; use codex_api::create_text_param_for_request; use codex_api::error::ApiError; use codex_api::requests::responses::Compression; -use codex_app_server_protocol::AuthMode; use codex_otel::OtelManager; use codex_protocol::ThreadId; @@ -50,6 +49,7 @@ use tokio::sync::mpsc; use tracing::warn; use crate::AuthManager; +use crate::auth::CodexAuth; use crate::auth::RefreshTokenError; use crate::client_common::Prompt; use crate::client_common::ResponseEvent; @@ -220,7 +220,7 @@ impl ModelClient { let api_provider = self .state .provider - .to_api_provider(auth.as_ref().map(|a| a.mode))?; + .to_api_provider(auth.as_ref().map(CodexAuth::internal_auth_mode))?; let api_auth = auth_provider_from_auth(auth.clone(), &self.state.provider)?; let transport = ReqwestTransport::new(build_reqwest_client()); let request_telemetry = self.build_request_telemetry(); @@ -469,9 +469,7 @@ impl ModelClientSession { .config .features .enabled(Feature::EnableRequestCompression) - && auth.is_some_and(|auth| { - matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) - }) + && auth.is_some_and(CodexAuth::is_chatgpt_auth) && self.state.provider.is_openai() { Compression::Zstd @@ -509,7 +507,7 @@ impl ModelClientSession { let api_provider = self .state .provider - .to_api_provider(auth.as_ref().map(|a| a.mode))?; + .to_api_provider(auth.as_ref().map(CodexAuth::internal_auth_mode))?; let api_auth = auth_provider_from_auth(auth.clone(), &self.state.provider)?; let transport = ReqwestTransport::new(build_reqwest_client()); let (request_telemetry, sse_telemetry) = self.build_streaming_telemetry(); @@ -565,7 +563,7 @@ impl ModelClientSession { let api_provider = self .state .provider - .to_api_provider(auth.as_ref().map(|a| a.mode))?; + .to_api_provider(auth.as_ref().map(CodexAuth::internal_auth_mode))?; let api_auth = auth_provider_from_auth(auth.clone(), &self.state.provider)?; let transport = ReqwestTransport::new(build_reqwest_client()); let (request_telemetry, sse_telemetry) = self.build_streaming_telemetry(); @@ -611,7 +609,7 @@ impl ModelClientSession { let api_provider = self .state .provider - .to_api_provider(auth.as_ref().map(|a| a.mode))?; + .to_api_provider(auth.as_ref().map(CodexAuth::internal_auth_mode))?; let api_auth = auth_provider_from_auth(auth.clone(), &self.state.provider)?; let compression = self.responses_request_compression(auth.as_ref()); diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 7eefd04ec4..324f41a04e 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -838,7 +838,7 @@ impl Session { session_configuration.collaboration_mode.model(), auth.and_then(CodexAuth::get_account_id), auth.and_then(CodexAuth::get_account_email), - auth.map(|a| a.mode), + auth.map(CodexAuth::api_auth_mode), config.otel.log_user_prompt, terminal::user_agent(), session_configuration.session_source.clone(), diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index 0f3551480c..0f5a8643a7 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -5,10 +5,11 @@ //! 2. User-defined entries inside `~/.codex/config.toml` under the `model_providers` //! key. These override or extend the defaults at runtime. +use crate::auth::AuthMode; +use crate::error::EnvVarError; use codex_api::Provider as ApiProvider; use codex_api::WireApi as ApiWireApi; use codex_api::provider::RetryConfig as ApiRetryConfig; -use codex_app_server_protocol::AuthMode; use http::HeaderMap; use http::header::HeaderName; use http::header::HeaderValue; @@ -19,7 +20,6 @@ use std::collections::HashMap; use std::env::VarError; use std::time::Duration; -use crate::error::EnvVarError; const DEFAULT_STREAM_IDLE_TIMEOUT_MS: u64 = 300_000; const DEFAULT_STREAM_MAX_RETRIES: u64 = 5; const DEFAULT_REQUEST_MAX_RETRIES: u64 = 4; @@ -137,10 +137,7 @@ impl ModelProviderInfo { &self, auth_mode: Option, ) -> crate::error::Result { - let default_base_url = if matches!( - auth_mode, - Some(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) - ) { + let default_base_url = if matches!(auth_mode, Some(AuthMode::ChatGPT)) { "https://chatgpt.com/backend-api/codex" } else { "https://api.openai.com/v1" diff --git a/codex-rs/core/src/models_manager/manager.rs b/codex-rs/core/src/models_manager/manager.rs index c993032ea9..40f9c8ccdc 100644 --- a/codex-rs/core/src/models_manager/manager.rs +++ b/codex-rs/core/src/models_manager/manager.rs @@ -2,6 +2,7 @@ use super::cache::ModelsCacheManager; use crate::api_bridge::auth_provider_from_auth; use crate::api_bridge::map_api_error; use crate::auth::AuthManager; +use crate::auth::AuthMode; use crate::config::Config; use crate::default_client::build_reqwest_client; use crate::error::CodexErr; @@ -13,7 +14,6 @@ use crate::models_manager::model_info; use crate::models_manager::model_presets::builtin_model_presets; use codex_api::ModelsClient; use codex_api::ReqwestTransport; -use codex_app_server_protocol::AuthMode; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelPreset; @@ -61,7 +61,7 @@ impl ModelsManager { let cache_path = codex_home.join(MODEL_CACHE_FILE); let cache_manager = ModelsCacheManager::new(cache_path, DEFAULT_MODEL_CACHE_TTL); Self { - local_models: builtin_model_presets(auth_manager.get_auth_mode()), + local_models: builtin_model_presets(auth_manager.get_internal_auth_mode()), remote_models: RwLock::new(Self::load_remote_models_from_file().unwrap_or_default()), auth_manager, etag: RwLock::new(None), @@ -175,7 +175,7 @@ impl ModelsManager { refresh_strategy: RefreshStrategy, ) -> CoreResult<()> { if !config.features.enabled(Feature::RemoteModels) - || self.auth_manager.get_auth_mode() == Some(AuthMode::ApiKey) + || self.auth_manager.get_internal_auth_mode() == Some(AuthMode::ApiKey) { return Ok(()); } @@ -204,7 +204,7 @@ impl ModelsManager { let _timer = codex_otel::start_global_timer("codex.remote_models.fetch_update.duration_ms", &[]); let auth = self.auth_manager.auth().await; - let auth_mode = self.auth_manager.get_auth_mode(); + let auth_mode = self.auth_manager.get_internal_auth_mode(); let api_provider = self.provider.to_api_provider(auth_mode)?; let api_auth = auth_provider_from_auth(auth.clone(), &self.provider)?; let transport = ReqwestTransport::new(build_reqwest_client()); @@ -273,8 +273,8 @@ impl ModelsManager { let existing_presets = self.local_models.clone(); let mut merged_presets = ModelPreset::merge(remote_presets, existing_presets); let chatgpt_mode = matches!( - self.auth_manager.get_auth_mode(), - Some(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + self.auth_manager.get_internal_auth_mode(), + Some(AuthMode::ChatGPT) ); merged_presets = ModelPreset::filter_by_auth(merged_presets, chatgpt_mode); @@ -319,7 +319,7 @@ impl ModelsManager { let cache_path = codex_home.join(MODEL_CACHE_FILE); let cache_manager = ModelsCacheManager::new(cache_path, DEFAULT_MODEL_CACHE_TTL); Self { - local_models: builtin_model_presets(auth_manager.get_auth_mode()), + local_models: builtin_model_presets(auth_manager.get_internal_auth_mode()), remote_models: RwLock::new(Self::load_remote_models_from_file().unwrap_or_default()), auth_manager, etag: RwLock::new(None), diff --git a/codex-rs/core/src/models_manager/model_presets.rs b/codex-rs/core/src/models_manager/model_presets.rs index a8f4931f8d..f9105c6448 100644 --- a/codex-rs/core/src/models_manager/model_presets.rs +++ b/codex-rs/core/src/models_manager/model_presets.rs @@ -1,4 +1,4 @@ -use codex_app_server_protocol::AuthMode; +use crate::auth::AuthMode; use codex_protocol::openai_models::ModelPreset; use codex_protocol::openai_models::ModelUpgrade; use codex_protocol::openai_models::ReasoningEffort; diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 107e9f6ed6..c65ce4498d 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -984,7 +984,7 @@ impl App { model.as_str(), auth_ref.and_then(CodexAuth::get_account_id), auth_ref.and_then(CodexAuth::get_account_email), - auth_ref.map(|auth| auth.mode), + auth_ref.map(CodexAuth::api_auth_mode), config.otel.log_user_prompt, codex_core::terminal::user_agent(), SessionSource::Cli, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 8223c40ce0..491ea3add3 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -30,7 +30,6 @@ use std::time::Duration; use std::time::Instant; use crate::version::CODEX_CLI_VERSION; -use codex_app_server_protocol::AuthMode; use codex_backend_client::Client as BackendClient; use codex_chatgpt::connectors; use codex_core::config::Config; @@ -3584,10 +3583,12 @@ impl ChatWidget { fn prefetch_rate_limits(&mut self) { self.stop_rate_limit_poller(); - if !matches!( - self.auth_manager.auth_cached().map(|auth| auth.mode), - Some(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) - ) { + if !self + .auth_manager + .auth_cached() + .as_ref() + .is_some_and(CodexAuth::is_chatgpt_auth) + { return; } @@ -3600,7 +3601,7 @@ impl ChatWidget { loop { if let Some(auth) = auth_manager.auth().await - && matches!(auth.mode, AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + && auth.is_chatgpt_auth() && let Some(snapshot) = fetch_rate_limits(base_url.clone(), auth).await { app_event_tx.send(AppEvent::RateLimitSnapshotFetched(snapshot)); diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index a8c6e2b88b..1f34ed6049 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -833,7 +833,7 @@ fn get_login_status(config: &Config) -> LoginStatus { // to refresh the token. Block on it. let codex_home = config.codex_home.clone(); match CodexAuth::from_auth_storage(&codex_home, config.cli_auth_credentials_store_mode) { - Ok(Some(auth)) => LoginStatus::AuthMode(auth.mode), + Ok(Some(auth)) => LoginStatus::AuthMode(auth.api_auth_mode()), Ok(None) => LoginStatus::NotAuthenticated, Err(err) => { error!("Failed to read auth.json: {err}"); diff --git a/codex-rs/tui/src/status/helpers.rs b/codex-rs/tui/src/status/helpers.rs index 91f958a9cf..0a801227f5 100644 --- a/codex-rs/tui/src/status/helpers.rs +++ b/codex-rs/tui/src/status/helpers.rs @@ -2,8 +2,8 @@ use crate::exec_command::relativize_to_home; use crate::text_formatting; use chrono::DateTime; use chrono::Local; -use codex_app_server_protocol::AuthMode; use codex_core::AuthManager; +use codex_core::CodexAuth; use codex_core::config::Config; use codex_core::project_doc::discover_project_doc_paths; use codex_protocol::account::PlanType; @@ -90,15 +90,15 @@ pub(crate) fn compose_account_display( ) -> Option { let auth = auth_manager.auth_cached()?; - match auth.mode { - AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens => { + match auth { + CodexAuth::ChatGpt(_) | CodexAuth::ChatGptAuthTokens(_) => { let email = auth.get_account_email(); let plan = plan .map(|plan_type| title_case(format!("{plan_type:?}").as_str())) .or_else(|| Some("Unknown".to_string())); Some(StatusAccountDisplay::ChatGpt { email, plan }) } - AuthMode::ApiKey => Some(StatusAccountDisplay::ApiKey), + CodexAuth::ApiKey(_) => Some(StatusAccountDisplay::ApiKey), } } From dfafc546ab127aac45a16b73ae3d859203da66d6 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Fri, 30 Jan 2026 10:41:22 -0700 Subject: [PATCH 107/116] chore(feature) Experimental: Personality (#10212) ## Summary Let users start opting in to trying out personalities ## Testing - [x] existing tests pass --- codex-rs/core/src/features.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 961b7a56f6..97fa1022c4 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -560,7 +560,11 @@ pub const FEATURES: &[FeatureSpec] = &[ FeatureSpec { id: Feature::Personality, key: "personality", - stage: Stage::UnderDevelopment, + stage: Stage::Experimental { + name: "Personality", + menu_description: "Choose a communication style for Codex.", + announcement: "NEW: Pick a personality for Codex. Enable in /experimental!", + }, default_enabled: false, }, FeatureSpec { From 23db79fae2925ea74847d2341bd41f7a0e83344a Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Fri, 30 Jan 2026 10:41:37 -0700 Subject: [PATCH 108/116] chore(feature) Experimental: Smart Approvals (#10211) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Let's start getting feedback on this feature 😅 ## Testing - [x] existing tests pass --- codex-rs/core/src/features.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 97fa1022c4..934ab1c0ba 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -464,7 +464,11 @@ pub const FEATURES: &[FeatureSpec] = &[ FeatureSpec { id: Feature::RequestRule, key: "request_rule", - stage: Stage::UnderDevelopment, + stage: Stage::Experimental { + name: "Smart approvals", + menu_description: "Get smarter \"Don't ask again\" rule requests.", + announcement: "NEW: Try Smart approvals to get smarter \"Don't ask again\" requests. Enable in /experimental!", + }, default_enabled: false, }, FeatureSpec { From 5662eb8b75cd6aa5e1acbdbf93549f85dee510a1 Mon Sep 17 00:00:00 2001 From: gt-oai Date: Fri, 30 Jan 2026 18:04:09 +0000 Subject: [PATCH 109/116] Load exec policy rules from requirements (#10190) `requirements.toml` should be able to specify rules which always run. My intention here was that these rules could only ever be restrictive, which means the decision can be "prompt" or "forbidden" but never "allow". A requirement of "you must always allow this command" didn't make sense to me, but happy to be gaveled otherwise. Rules already applies the most restrictive decision, so we can safely merge these with rules found in other config folders. --- codex-rs/app-server/src/config_api.rs | 1 + codex-rs/cloud-requirements/src/lib.rs | 1 + codex-rs/core/src/config/constraint.rs | 6 + codex-rs/core/src/config/mod.rs | 1 + .../src/config_loader/config_requirements.rs | 98 +++++++ codex-rs/core/src/config_loader/mod.rs | 1 - .../config_loader/requirements_exec_policy.rs | 82 ++++-- codex-rs/core/src/config_loader/tests.rs | 266 ++++++++++++++---- codex-rs/core/src/exec_policy.rs | 13 +- 9 files changed, 398 insertions(+), 71 deletions(-) diff --git a/codex-rs/app-server/src/config_api.rs b/codex-rs/app-server/src/config_api.rs index 5c924d1819..9207668486 100644 --- a/codex-rs/app-server/src/config_api.rs +++ b/codex-rs/app-server/src/config_api.rs @@ -136,6 +136,7 @@ mod tests { CoreSandboxModeRequirement::ExternalSandbox, ]), mcp_servers: None, + rules: None, }; let mapped = map_requirements_toml_to_api(requirements); diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index ccfa600319..37faed081b 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -317,6 +317,7 @@ mod tests { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, mcp_servers: None, + rules: None, }) ); } diff --git a/codex-rs/core/src/config/constraint.rs b/codex-rs/core/src/config/constraint.rs index fa431a6eb2..23b6c57c74 100644 --- a/codex-rs/core/src/config/constraint.rs +++ b/codex-rs/core/src/config/constraint.rs @@ -18,6 +18,12 @@ pub enum ConstraintError { #[error("field `{field_name}` cannot be empty")] EmptyField { field_name: String }, + + #[error("invalid rules in requirements (set by {requirement_source}): {reason}")] + ExecPolicyParse { + requirement_source: RequirementSource, + reason: String, + }, } impl ConstraintError { diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index fbd8999918..2e1c853620 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1512,6 +1512,7 @@ impl Config { approval_policy: mut constrained_approval_policy, sandbox_policy: mut constrained_sandbox_policy, mcp_servers, + exec_policy: _, } = requirements; constrained_approval_policy diff --git a/codex-rs/core/src/config_loader/config_requirements.rs b/codex-rs/core/src/config_loader/config_requirements.rs index 2c220049cf..6b9184a539 100644 --- a/codex-rs/core/src/config_loader/config_requirements.rs +++ b/codex-rs/core/src/config_loader/config_requirements.rs @@ -6,6 +6,8 @@ use serde::Deserialize; use std::collections::BTreeMap; use std::fmt; +use super::requirements_exec_policy::RequirementsExecPolicy; +use super::requirements_exec_policy::RequirementsExecPolicyToml; use crate::config::Constrained; use crate::config::ConstraintError; @@ -49,6 +51,7 @@ pub struct ConfigRequirements { pub approval_policy: Constrained, pub sandbox_policy: Constrained, pub mcp_servers: Option>>, + pub(crate) exec_policy: Option>, } impl Default for ConfigRequirements { @@ -57,6 +60,7 @@ impl Default for ConfigRequirements { approval_policy: Constrained::allow_any_from_default(), sandbox_policy: Constrained::allow_any(SandboxPolicy::ReadOnly), mcp_servers: None, + exec_policy: None, } } } @@ -79,6 +83,7 @@ pub struct ConfigRequirementsToml { pub allowed_approval_policies: Option>, pub allowed_sandbox_modes: Option>, pub mcp_servers: Option>, + pub rules: Option, } /// Value paired with the requirement source it came from, for better error @@ -108,6 +113,7 @@ pub struct ConfigRequirementsWithSources { pub allowed_approval_policies: Option>>, pub allowed_sandbox_modes: Option>>, pub mcp_servers: Option>>, + pub rules: Option>, } impl ConfigRequirementsWithSources { @@ -139,6 +145,7 @@ impl ConfigRequirementsWithSources { allowed_approval_policies, allowed_sandbox_modes, mcp_servers, + rules, } ); } @@ -148,11 +155,13 @@ impl ConfigRequirementsWithSources { allowed_approval_policies, allowed_sandbox_modes, mcp_servers, + rules, } = self; ConfigRequirementsToml { allowed_approval_policies: allowed_approval_policies.map(|sourced| sourced.value), allowed_sandbox_modes: allowed_sandbox_modes.map(|sourced| sourced.value), mcp_servers: mcp_servers.map(|sourced| sourced.value), + rules: rules.map(|sourced| sourced.value), } } } @@ -189,6 +198,7 @@ impl ConfigRequirementsToml { self.allowed_approval_policies.is_none() && self.allowed_sandbox_modes.is_none() && self.mcp_servers.is_none() + && self.rules.is_none() } } @@ -200,6 +210,7 @@ impl TryFrom for ConfigRequirements { allowed_approval_policies, allowed_sandbox_modes, mcp_servers, + rules, } = toml; let approval_policy: Constrained = match allowed_approval_policies { @@ -274,10 +285,24 @@ impl TryFrom for ConfigRequirements { } None => Constrained::allow_any(default_sandbox_policy), }; + let exec_policy = match rules { + Some(Sourced { value, source }) => { + let policy = value.to_requirements_policy().map_err(|err| { + ConstraintError::ExecPolicyParse { + requirement_source: source.clone(), + reason: err.to_string(), + } + })?; + Some(Sourced::new(policy, source)) + } + None => None, + }; + Ok(ConfigRequirements { approval_policy, sandbox_policy, mcp_servers, + exec_policy, }) } } @@ -286,16 +311,24 @@ impl TryFrom for ConfigRequirements { mod tests { use super::*; use anyhow::Result; + use codex_execpolicy::Decision; + use codex_execpolicy::Evaluation; + use codex_execpolicy::RuleMatch; use codex_protocol::protocol::NetworkAccess; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use toml::from_str; + fn tokens(cmd: &[&str]) -> Vec { + cmd.iter().map(std::string::ToString::to_string).collect() + } + fn with_unknown_source(toml: ConfigRequirementsToml) -> ConfigRequirementsWithSources { let ConfigRequirementsToml { allowed_approval_policies, allowed_sandbox_modes, mcp_servers, + rules, } = toml; ConfigRequirementsWithSources { allowed_approval_policies: allowed_approval_policies @@ -303,6 +336,7 @@ mod tests { allowed_sandbox_modes: allowed_sandbox_modes .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)), } } @@ -323,6 +357,7 @@ mod tests { allowed_approval_policies: Some(allowed_approval_policies.clone()), allowed_sandbox_modes: Some(allowed_sandbox_modes.clone()), mcp_servers: None, + rules: None, }; target.merge_unset_fields(source.clone(), other); @@ -336,6 +371,7 @@ mod tests { )), allowed_sandbox_modes: Some(Sourced::new(allowed_sandbox_modes, source)), mcp_servers: None, + rules: None, } ); } @@ -364,6 +400,7 @@ mod tests { )), allowed_sandbox_modes: None, mcp_servers: None, + rules: None, } ); Ok(()) @@ -400,6 +437,7 @@ mod tests { )), allowed_sandbox_modes: None, mcp_servers: None, + rules: None, } ); Ok(()) @@ -626,4 +664,64 @@ mod tests { ); Ok(()) } + + #[test] + fn deserialize_exec_policy_requirements() -> Result<()> { + let toml_str = r#" + [rules] + prefix_rules = [ + { pattern = [{ token = "rm" }], decision = "forbidden" }, + ] + "#; + let config: ConfigRequirementsToml = from_str(toml_str)?; + let requirements: ConfigRequirements = with_unknown_source(config).try_into()?; + let policy = requirements.exec_policy.expect("exec policy").value; + + assert_eq!( + policy.as_ref().check(&tokens(&["rm", "-rf"]), &|_| { + panic!("rule should match so heuristic should not be called"); + }), + Evaluation { + decision: Decision::Forbidden, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: tokens(&["rm"]), + decision: Decision::Forbidden, + justification: None, + }], + } + ); + + Ok(()) + } + + #[test] + fn exec_policy_error_includes_requirement_source() -> Result<()> { + let toml_str = r#" + [rules] + prefix_rules = [ + { pattern = [{ token = "rm" }] }, + ] + "#; + let config: ConfigRequirementsToml = from_str(toml_str)?; + let requirements_toml_file = + AbsolutePathBuf::from_absolute_path("/etc/codex/requirements.toml")?; + let source_location = RequirementSource::SystemRequirementsToml { + file: requirements_toml_file, + }; + + let mut requirements_with_sources = ConfigRequirementsWithSources::default(); + requirements_with_sources.merge_unset_fields(source_location.clone(), config); + let err = ConfigRequirements::try_from(requirements_with_sources) + .expect_err("invalid exec policy"); + + assert_eq!( + err, + ConstraintError::ExecPolicyParse { + requirement_source: source_location, + reason: "rules prefix_rule at index 0 is missing a decision".to_string(), + } + ); + + Ok(()) + } } diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index 0dd704cab5..eba89fdb3d 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -7,7 +7,6 @@ mod layer_io; mod macos; mod merge; mod overrides; -#[cfg(test)] mod requirements_exec_policy; mod state; diff --git a/codex-rs/core/src/config_loader/requirements_exec_policy.rs b/codex-rs/core/src/config_loader/requirements_exec_policy.rs index cbc1d7531e..74546fc426 100644 --- a/codex-rs/core/src/config_loader/requirements_exec_policy.rs +++ b/codex-rs/core/src/config_loader/requirements_exec_policy.rs @@ -9,16 +9,43 @@ use serde::Deserialize; use std::sync::Arc; use thiserror::Error; -/// TOML types for expressing exec policy requirements. -/// -/// These types are kept separate from `ConfigRequirementsToml` and are -/// converted into `codex-execpolicy` rules. -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub struct RequirementsExecPolicyTomlRoot { - pub exec_policy: RequirementsExecPolicyToml, +#[derive(Debug, Clone)] +pub(crate) struct RequirementsExecPolicy { + policy: Policy, } -/// TOML representation of `[exec_policy]` within `requirements.toml`. +impl RequirementsExecPolicy { + pub fn new(policy: Policy) -> Self { + Self { policy } + } +} + +impl PartialEq for RequirementsExecPolicy { + fn eq(&self, other: &Self) -> bool { + policy_fingerprint(&self.policy) == policy_fingerprint(&other.policy) + } +} + +impl Eq for RequirementsExecPolicy {} + +impl AsRef for RequirementsExecPolicy { + fn as_ref(&self) -> &Policy { + &self.policy + } +} + +fn policy_fingerprint(policy: &Policy) -> Vec { + let mut entries = Vec::new(); + for (program, rules) in policy.rules().iter_all() { + for rule in rules { + entries.push(format!("{program}:{rule:?}")); + } + } + entries.sort(); + entries +} + +/// TOML representation of `[rules]` within `requirements.toml`. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct RequirementsExecPolicyToml { pub prefix_rules: Vec, @@ -65,14 +92,14 @@ impl RequirementsExecPolicyDecisionToml { #[derive(Debug, Error)] pub enum RequirementsExecPolicyParseError { - #[error("exec policy prefix_rules cannot be empty")] + #[error("rules prefix_rules cannot be empty")] EmptyPrefixRules, - #[error("exec policy prefix_rule at index {rule_index} has an empty pattern")] + #[error("rules prefix_rule at index {rule_index} has an empty pattern")] EmptyPattern { rule_index: usize }, #[error( - "exec policy prefix_rule at index {rule_index} has an invalid pattern token at index {token_index}: {reason}" + "rules prefix_rule at index {rule_index} has an invalid pattern token at index {token_index}: {reason}" )] InvalidPatternToken { rule_index: usize, @@ -80,12 +107,20 @@ pub enum RequirementsExecPolicyParseError { reason: String, }, - #[error("exec policy prefix_rule at index {rule_index} has an empty justification")] + #[error("rules prefix_rule at index {rule_index} has an empty justification")] EmptyJustification { rule_index: usize }, + + #[error("rules prefix_rule at index {rule_index} is missing a decision")] + MissingDecision { rule_index: usize }, + + #[error( + "rules prefix_rule at index {rule_index} has decision 'allow', which is not permitted in requirements.toml: Codex merges these rules with other config and uses the most restrictive result (use 'prompt' or 'forbidden')" + )] + AllowDecisionNotAllowed { rule_index: usize }, } impl RequirementsExecPolicyToml { - /// Convert requirements TOML exec policy rules into the internal `.rules` + /// Convert requirements TOML rules into the internal `.rules` /// representation used by `codex-execpolicy`. pub fn to_policy(&self) -> Result { if self.prefix_rules.is_empty() { @@ -112,10 +147,17 @@ impl RequirementsExecPolicyToml { .map(|(token_index, token)| parse_pattern_token(token, rule_index, token_index)) .collect::, _>>()?; - let decision = rule - .decision - .map(RequirementsExecPolicyDecisionToml::as_decision) - .unwrap_or(Decision::Allow); + let decision = match rule.decision { + Some(RequirementsExecPolicyDecisionToml::Allow) => { + return Err(RequirementsExecPolicyParseError::AllowDecisionNotAllowed { + rule_index, + }); + } + Some(decision) => decision.as_decision(), + None => { + return Err(RequirementsExecPolicyParseError::MissingDecision { rule_index }); + } + }; let justification = rule.justification.clone(); let (first_token, remaining_tokens) = pattern_tokens @@ -139,6 +181,12 @@ impl RequirementsExecPolicyToml { Ok(Policy::new(rules_by_program)) } + + pub(crate) fn to_requirements_policy( + &self, + ) -> Result { + self.to_policy().map(RequirementsExecPolicy::new) + } } fn parse_pattern_token( diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index c213c0b2ea..38d104fc19 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -502,6 +502,7 @@ allowed_approval_policies = ["on-request"] allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, mcp_servers: None, + rules: None, }, ); load_requirements_toml(&mut config_requirements_toml, &requirements_file).await?; @@ -535,6 +536,7 @@ async fn load_config_layers_includes_cloud_requirements() -> anyhow::Result<()> allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, mcp_servers: None, + rules: None, }; let expected = requirements.clone(); let cloud_requirements = CloudRequirementsLoader::new(async move { Some(requirements) }); @@ -1016,49 +1018,79 @@ async fn project_root_markers_supports_alternate_markers() -> std::io::Result<() } mod requirements_exec_policy_tests { + use super::super::config_requirements::ConfigRequirementsWithSources; use super::super::requirements_exec_policy::RequirementsExecPolicyDecisionToml; + use super::super::requirements_exec_policy::RequirementsExecPolicyParseError; use super::super::requirements_exec_policy::RequirementsExecPolicyPatternTokenToml; use super::super::requirements_exec_policy::RequirementsExecPolicyPrefixRuleToml; use super::super::requirements_exec_policy::RequirementsExecPolicyToml; - use super::super::requirements_exec_policy::RequirementsExecPolicyTomlRoot; + use crate::config_loader::ConfigLayerEntry; + use crate::config_loader::ConfigLayerStack; + use crate::config_loader::ConfigRequirements; + use crate::config_loader::ConfigRequirementsToml; + use crate::config_loader::RequirementSource; + use crate::exec_policy::load_exec_policy; + use codex_app_server_protocol::ConfigLayerSource; use codex_execpolicy::Decision; use codex_execpolicy::Evaluation; use codex_execpolicy::RuleMatch; + use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; + use std::path::Path; + use tempfile::tempdir; + use toml::Value as TomlValue; use toml::from_str; fn tokens(cmd: &[&str]) -> Vec { cmd.iter().map(std::string::ToString::to_string).collect() } - fn allow_all(_: &[String]) -> Decision { - Decision::Allow + fn panic_if_called(_: &[String]) -> Decision { + panic!("rule should match so heuristic should not be called"); + } + + fn config_stack_for_dot_codex_folder_with_requirements( + dot_codex_folder: &Path, + requirements: ConfigRequirements, + ) -> ConfigLayerStack { + let dot_codex_folder = AbsolutePathBuf::from_absolute_path(dot_codex_folder) + .expect("absolute dot_codex_folder"); + let layer = ConfigLayerEntry::new( + ConfigLayerSource::Project { dot_codex_folder }, + TomlValue::Table(Default::default()), + ); + ConfigLayerStack::new(vec![layer], requirements, ConfigRequirementsToml::default()) + .expect("ConfigLayerStack") + } + + fn requirements_from_toml(toml_str: &str) -> ConfigRequirements { + let config: ConfigRequirementsToml = from_str(toml_str).expect("parse requirements toml"); + let mut with_sources = ConfigRequirementsWithSources::default(); + with_sources.merge_unset_fields(RequirementSource::Unknown, config); + ConfigRequirements::try_from(with_sources).expect("requirements") } #[test] fn parses_single_prefix_rule_from_raw_toml() -> anyhow::Result<()> { let toml_str = r#" -[exec_policy] prefix_rules = [ { pattern = [{ token = "rm" }], decision = "forbidden" }, ] "#; - let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; + let parsed: RequirementsExecPolicyToml = from_str(toml_str)?; assert_eq!( parsed, - RequirementsExecPolicyTomlRoot { - exec_policy: RequirementsExecPolicyToml { - prefix_rules: vec![RequirementsExecPolicyPrefixRuleToml { - pattern: vec![RequirementsExecPolicyPatternTokenToml { - token: Some("rm".to_string()), - any_of: None, - }], - decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), - justification: None, + RequirementsExecPolicyToml { + prefix_rules: vec![RequirementsExecPolicyPrefixRuleToml { + pattern: vec![RequirementsExecPolicyPatternTokenToml { + token: Some("rm".to_string()), + any_of: None, }], - }, + decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), + justification: None, + }], } ); @@ -1068,44 +1100,41 @@ prefix_rules = [ #[test] fn parses_multiple_prefix_rules_from_raw_toml() -> anyhow::Result<()> { let toml_str = r#" -[exec_policy] prefix_rules = [ { pattern = [{ token = "rm" }], decision = "forbidden" }, { pattern = [{ token = "git" }, { any_of = ["push", "commit"] }], decision = "prompt", justification = "review changes before push or commit" }, ] "#; - let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; + let parsed: RequirementsExecPolicyToml = from_str(toml_str)?; assert_eq!( parsed, - RequirementsExecPolicyTomlRoot { - exec_policy: RequirementsExecPolicyToml { - prefix_rules: vec![ - RequirementsExecPolicyPrefixRuleToml { - pattern: vec![RequirementsExecPolicyPatternTokenToml { - token: Some("rm".to_string()), + RequirementsExecPolicyToml { + prefix_rules: vec![ + RequirementsExecPolicyPrefixRuleToml { + pattern: vec![RequirementsExecPolicyPatternTokenToml { + token: Some("rm".to_string()), + any_of: None, + }], + decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), + justification: None, + }, + RequirementsExecPolicyPrefixRuleToml { + pattern: vec![ + RequirementsExecPolicyPatternTokenToml { + token: Some("git".to_string()), any_of: None, - }], - decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), - justification: None, - }, - RequirementsExecPolicyPrefixRuleToml { - pattern: vec![ - RequirementsExecPolicyPatternTokenToml { - token: Some("git".to_string()), - any_of: None, - }, - RequirementsExecPolicyPatternTokenToml { - token: None, - any_of: Some(vec!["push".to_string(), "commit".to_string()]), - }, - ], - decision: Some(RequirementsExecPolicyDecisionToml::Prompt), - justification: Some("review changes before push or commit".to_string()), - }, - ], - }, + }, + RequirementsExecPolicyPatternTokenToml { + token: None, + any_of: Some(vec!["push".to_string(), "commit".to_string()]), + }, + ], + decision: Some(RequirementsExecPolicyDecisionToml::Prompt), + justification: Some("review changes before push or commit".to_string()), + }, + ], } ); @@ -1115,17 +1144,16 @@ prefix_rules = [ #[test] fn converts_rules_toml_into_internal_policy_representation() -> anyhow::Result<()> { let toml_str = r#" -[exec_policy] prefix_rules = [ { pattern = [{ token = "rm" }], decision = "forbidden" }, ] "#; - let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; - let policy = parsed.exec_policy.to_policy()?; + let parsed: RequirementsExecPolicyToml = from_str(toml_str)?; + let policy = parsed.to_policy()?; assert_eq!( - policy.check(&tokens(&["rm", "-rf", "/tmp"]), &allow_all), + policy.check(&tokens(&["rm", "-rf", "/tmp"]), &panic_if_called), Evaluation { decision: Decision::Forbidden, matched_rules: vec![RuleMatch::PrefixRuleMatch { @@ -1142,16 +1170,15 @@ prefix_rules = [ #[test] fn head_any_of_expands_into_multiple_program_rules() -> anyhow::Result<()> { let toml_str = r#" -[exec_policy] prefix_rules = [ { pattern = [{ any_of = ["git", "hg"] }, { token = "status" }], decision = "prompt" }, ] "#; - let parsed: RequirementsExecPolicyTomlRoot = from_str(toml_str)?; - let policy = parsed.exec_policy.to_policy()?; + let parsed: RequirementsExecPolicyToml = from_str(toml_str)?; + let policy = parsed.to_policy()?; assert_eq!( - policy.check(&tokens(&["git", "status"]), &allow_all), + policy.check(&tokens(&["git", "status"]), &panic_if_called), Evaluation { decision: Decision::Prompt, matched_rules: vec![RuleMatch::PrefixRuleMatch { @@ -1162,7 +1189,7 @@ prefix_rules = [ } ); assert_eq!( - policy.check(&tokens(&["hg", "status"]), &allow_all), + policy.check(&tokens(&["hg", "status"]), &panic_if_called), Evaluation { decision: Decision::Prompt, matched_rules: vec![RuleMatch::PrefixRuleMatch { @@ -1175,4 +1202,139 @@ prefix_rules = [ Ok(()) } + + #[test] + fn missing_decision_is_rejected() -> anyhow::Result<()> { + let toml_str = r#" +prefix_rules = [ + { pattern = [{ token = "rm" }] }, +] +"#; + + let parsed: RequirementsExecPolicyToml = from_str(toml_str)?; + let err = parsed.to_policy().expect_err("missing decision"); + + assert!(matches!( + err, + RequirementsExecPolicyParseError::MissingDecision { rule_index: 0 } + )); + Ok(()) + } + + #[test] + fn allow_decision_is_rejected() -> anyhow::Result<()> { + let toml_str = r#" +prefix_rules = [ + { pattern = [{ token = "rm" }], decision = "allow" }, +] +"#; + + let parsed: RequirementsExecPolicyToml = from_str(toml_str)?; + let err = parsed.to_policy().expect_err("allow decision not allowed"); + + assert!(matches!( + err, + RequirementsExecPolicyParseError::AllowDecisionNotAllowed { rule_index: 0 } + )); + Ok(()) + } + + #[test] + fn empty_prefix_rules_is_rejected() -> anyhow::Result<()> { + let toml_str = r#" +prefix_rules = [] +"#; + + let parsed: RequirementsExecPolicyToml = from_str(toml_str)?; + let err = parsed.to_policy().expect_err("empty prefix rules"); + + assert!(matches!( + err, + RequirementsExecPolicyParseError::EmptyPrefixRules + )); + Ok(()) + } + + #[tokio::test] + async fn loads_requirements_exec_policy_without_rules_files() -> anyhow::Result<()> { + let temp_dir = tempdir()?; + let requirements = requirements_from_toml( + r#" + [rules] + prefix_rules = [ + { pattern = [{ token = "rm" }], decision = "forbidden" }, + ] + "#, + ); + let config_stack = + config_stack_for_dot_codex_folder_with_requirements(temp_dir.path(), requirements); + + let policy = load_exec_policy(&config_stack).await?; + + assert_eq!( + policy.check_multiple([vec!["rm".to_string()]].iter(), &panic_if_called), + Evaluation { + decision: Decision::Forbidden, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: vec!["rm".to_string()], + decision: Decision::Forbidden, + justification: None, + }], + } + ); + + Ok(()) + } + + #[tokio::test] + async fn merges_requirements_exec_policy_with_file_rules() -> anyhow::Result<()> { + let temp_dir = tempdir()?; + let policy_dir = temp_dir.path().join("rules"); + std::fs::create_dir_all(&policy_dir)?; + std::fs::write( + policy_dir.join("deny.rules"), + r#"prefix_rule(pattern=["rm"], decision="forbidden")"#, + )?; + + let requirements = requirements_from_toml( + r#" + [rules] + prefix_rules = [ + { pattern = [{ token = "git" }, { token = "push" }], decision = "prompt" }, + ] + "#, + ); + let config_stack = + config_stack_for_dot_codex_folder_with_requirements(temp_dir.path(), requirements); + + let policy = load_exec_policy(&config_stack).await?; + + assert_eq!( + policy.check_multiple([vec!["rm".to_string()]].iter(), &panic_if_called), + Evaluation { + decision: Decision::Forbidden, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: vec!["rm".to_string()], + decision: Decision::Forbidden, + justification: None, + }], + } + ); + assert_eq!( + policy.check_multiple( + [vec!["git".to_string(), "push".to_string()]].iter(), + &panic_if_called + ), + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: vec!["git".to_string(), "push".to_string()], + decision: Decision::Prompt, + justification: None, + }], + } + ); + + Ok(()) + } } diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index 07a9ebceba..c0cb7f8fcf 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -280,7 +280,18 @@ pub async fn load_exec_policy(config_stack: &ConfigLayerStack) -> Result Date: Fri, 30 Jan 2026 10:14:46 -0800 Subject: [PATCH 110/116] plan mode: add TL;DR checkpoint and client behavior note (#10195) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Tightens Plan Mode to encourage exploration-first behavior and more back-and-forth alignment. - Adds a required TL;DR checkpoint before drafting the full plan. - Clarifies client behavior that can cause premature “Implement this plan?” prompts. ## What changed - Require at least one targeted non-mutating exploration pass before the first user question. - Insert a TL;DR checkpoint between Phase 2 (intent) and Phase 3 (implementation). - TL;DR checkpoint guidance: - Label: “Proposed Plan (TL;DR)” - Format: 3–5 bullets using `- ` - Options: exactly one option, “Approve” - `isOther: true`, with explicit guidance that “None of the above” is the edit path in the current UI. - Require the final plan to include a TL;DR consistent with the approved checkpoint. ## Why - In Plan Mode, any normal assistant message at turn completion is treated as plan content by the client. This can trigger premature “Implement this plan?” prompts. - The TL;DR checkpoint aligns on direction before Codex drafts a long, decision-complete plan. ## Testing - Manual: built the local CLI and verified the flow now explores first, presents a TL;DR checkpoint, and only drafts the full plan after approval. --------- Co-authored-by: Nick Baumann <@openai.com> --- codex-rs/core/templates/collaboration_mode/plan.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/codex-rs/core/templates/collaboration_mode/plan.md b/codex-rs/core/templates/collaboration_mode/plan.md index 4b5f450a50..cffbf16d36 100644 --- a/codex-rs/core/templates/collaboration_mode/plan.md +++ b/codex-rs/core/templates/collaboration_mode/plan.md @@ -37,6 +37,8 @@ When in doubt: if the action would reasonably be described as "doing the work" r Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged. +Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available. + Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration. ## PHASE 2 — Intent chat (what they actually want) @@ -97,6 +99,7 @@ Only output the final plan when it is decision complete and leaves no decisions The final plan must be plan-only and include: * A clear title +* A TL;DR section (3–5 bullets) * Exact file paths to change * Exact structures or shapes to introduce or modify * Exact function, method, type, and variable names and signatures From 40bf11bd52422c3a5bf39fe8daae8999949874be Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 30 Jan 2026 10:29:54 -0800 Subject: [PATCH 111/116] chore: fix the build breakage that came from a merge race (#10239) I think I needed to rebase on top of https://github.com/openai/codex/pull/10167 before merging https://github.com/openai/codex/pull/10208. --- codex-rs/Cargo.lock | 1 - codex-rs/cloud-requirements/Cargo.toml | 1 - codex-rs/cloud-requirements/src/lib.rs | 5 +---- 3 files changed, 1 insertion(+), 6 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 44f35f78ae..5cb338be1d 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1298,7 +1298,6 @@ version = "0.0.0" dependencies = [ "async-trait", "base64", - "codex-app-server-protocol", "codex-backend-client", "codex-core", "codex-otel", diff --git a/codex-rs/cloud-requirements/Cargo.toml b/codex-rs/cloud-requirements/Cargo.toml index 2bfde660bf..071c98b9b4 100644 --- a/codex-rs/cloud-requirements/Cargo.toml +++ b/codex-rs/cloud-requirements/Cargo.toml @@ -9,7 +9,6 @@ workspace = true [dependencies] async-trait = { workspace = true } -codex-app-server-protocol = { workspace = true } codex-backend-client = { workspace = true } codex-core = { workspace = true } codex-otel = { workspace = true } diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index 37faed081b..ed1bb051d5 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -8,7 +8,6 @@ //! requirements before Codex will run. use async_trait::async_trait; -use codex_app_server_protocol::AuthMode; use codex_backend_client::Client as BackendClient; use codex_core::AuthManager; use codex_core::auth::CodexAuth; @@ -120,9 +119,7 @@ impl CloudRequirementsService { async fn fetch(&self) -> Option { let auth = self.auth_manager.auth().await?; - if !(auth.mode == AuthMode::ChatGPT - && auth.account_plan_type() == Some(PlanType::Enterprise)) - { + if !(auth.is_chatgpt_auth() && auth.account_plan_type() == Some(PlanType::Enterprise)) { return None; } From ec4a2d07e411d11f4de13b4e09aa7386c914df6d Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Fri, 30 Jan 2026 10:59:30 -0800 Subject: [PATCH 112/116] Plan mode: stream proposed plans, emit plan items, and render in TUI (#9786) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Stream proposed plans in Plan Mode using `` tags parsed in core, emitting plan deltas plus a plan `ThreadItem`, while stripping tags from normal assistant output. - Persist plan items and rebuild them on resume so proposed plans show in thread history. - Wire plan items/deltas through app-server protocol v2 and render a dedicated proposed-plan view in the TUI, including the “Implement this plan?” prompt only when a plan item is present. ## Changes ### Core (`codex-rs/core`) - Added a generic, line-based tag parser that buffers each line until it can disprove a tag prefix; implements auto-close on `finish()` for unterminated tags. `codex-rs/core/src/tagged_block_parser.rs` - Refactored proposed plan parsing to wrap the generic parser. `codex-rs/core/src/proposed_plan_parser.rs` - In plan mode, stream assistant deltas as: - **Normal text** → `AgentMessageContentDelta` - **Plan text** → `PlanDelta` + `TurnItem::Plan` start/completion (`codex-rs/core/src/codex.rs`) - Final plan item content is derived from the completed assistant message (authoritative), not necessarily the concatenated deltas. - Strips `` blocks from assistant text in plan mode so tags don’t appear in normal messages. (`codex-rs/core/src/stream_events_utils.rs`) - Persist `ItemCompleted` events only for plan items for rollout replay. (`codex-rs/core/src/rollout/policy.rs`) - Guard `update_plan` tool in Plan Mode with a clear error message. (`codex-rs/core/src/tools/handlers/plan.rs`) - Updated Plan Mode prompt to: - keep `` out of non-final reasoning/preambles - require exact tag formatting - allow only one `` block per turn (`codex-rs/core/templates/collaboration_mode/plan.md`) ### Protocol / App-server protocol - Added `TurnItem::Plan` and `PlanDeltaEvent` to core protocol items. (`codex-rs/protocol/src/items.rs`, `codex-rs/protocol/src/protocol.rs`) - Added v2 `ThreadItem::Plan` and `PlanDeltaNotification` with EXPERIMENTAL markers and note that deltas may not match the final plan item. (`codex-rs/app-server-protocol/src/protocol/v2.rs`) - Added plan delta route in app-server protocol common mapping. (`codex-rs/app-server-protocol/src/protocol/common.rs`) - Rebuild plan items from persisted `ItemCompleted` events on resume. (`codex-rs/app-server-protocol/src/protocol/thread_history.rs`) ### App-server - Forward plan deltas to v2 clients and map core plan items to v2 plan items. (`codex-rs/app-server/src/bespoke_event_handling.rs`, `codex-rs/app-server/src/codex_message_processor.rs`) - Added v2 plan item tests. (`codex-rs/app-server/tests/suite/v2/plan_item.rs`) ### TUI - Added a dedicated proposed plan history cell with special background and padding, and moved “• Proposed Plan” outside the highlighted block. (`codex-rs/tui/src/history_cell.rs`, `codex-rs/tui/src/style.rs`) - Only show “Implement this plan?” when a plan item exists. (`codex-rs/tui/src/chatwidget.rs`, `codex-rs/tui/src/chatwidget/tests.rs`) Screenshot 2026-01-29 at 7 06 24 PM ### Docs / Misc - Updated protocol docs to mention plan deltas. (`codex-rs/docs/protocol_v1.md`) - Minor plumbing updates in exec/debug clients to tolerate plan deltas. (`codex-rs/debug-client/src/reader.rs`, `codex-rs/exec/...`) ## Tests - Added core integration tests: - Plan mode strips plan from agent messages. - Missing `` closes at end-of-message. (`codex-rs/core/tests/suite/items.rs`) - Added unit tests for generic tag parser (prefix buffering, non-tag lines, auto-close). (`codex-rs/core/src/tagged_block_parser.rs`) - Existing app-server plan item tests in v2. (`codex-rs/app-server/tests/suite/v2/plan_item.rs`) ## Notes / Behavior - Plan output no longer appears in standard assistant text in Plan Mode; it streams via `PlanDelta` and completes as a `TurnItem::Plan`. - The final plan item content is authoritative and may diverge from streamed deltas (documented as experimental). - Reasoning summaries are not filtered; prompt instructs the model not to include `` outside the final plan message. ## Codex Author `codex fork 019bec2d-b09d-7450-b292-d7bcdddcdbfb` --- .../src/protocol/common.rs | 2 + .../src/protocol/thread_history.rs | 15 + .../app-server-protocol/src/protocol/v2.rs | 21 + codex-rs/app-server/README.md | 5 + .../app-server/src/bespoke_event_handling.rs | 18 +- .../app-server/tests/common/mcp_process.rs | 4 + codex-rs/app-server/tests/suite/v2/mod.rs | 1 + .../app-server/tests/suite/v2/plan_item.rs | 257 ++++++++++ codex-rs/core/src/agent/control.rs | 2 + codex-rs/core/src/codex.rs | 461 +++++++++++++++++- codex-rs/core/src/compact.rs | 1 + codex-rs/core/src/compact_remote.rs | 1 + codex-rs/core/src/lib.rs | 2 + codex-rs/core/src/proposed_plan_parser.rs | 185 +++++++ codex-rs/core/src/rollout/policy.rs | 8 +- codex-rs/core/src/stream_events_utils.rs | 54 +- codex-rs/core/src/tagged_block_parser.rs | 314 ++++++++++++ codex-rs/core/src/tasks/user_shell.rs | 1 + codex-rs/core/src/tools/handlers/plan.rs | 6 + .../core/templates/collaboration_mode/plan.md | 26 +- codex-rs/core/tests/suite/items.rs | 267 ++++++++++ codex-rs/debug-client/src/reader.rs | 5 + codex-rs/docs/protocol_v1.md | 5 +- .../src/event_processor_with_human_output.rs | 18 +- .../src/event_processor_with_jsonl_output.rs | 14 +- .../tests/event_processor_with_json_output.rs | 2 + codex-rs/mcp-server/src/codex_tool_runner.rs | 3 + codex-rs/protocol/src/config_types.rs | 5 +- codex-rs/protocol/src/items.rs | 9 + codex-rs/protocol/src/plan_tool.rs | 1 + codex-rs/protocol/src/protocol.rs | 12 + codex-rs/tui/src/chatwidget.rs | 114 ++++- codex-rs/tui/src/chatwidget/tests.rs | 42 +- codex-rs/tui/src/history_cell.rs | 58 +++ codex-rs/tui/src/streaming/controller.rs | 103 ++++ codex-rs/tui/src/style.rs | 21 + 36 files changed, 2021 insertions(+), 42 deletions(-) create mode 100644 codex-rs/app-server/tests/suite/v2/plan_item.rs create mode 100644 codex-rs/core/src/proposed_plan_parser.rs create mode 100644 codex-rs/core/src/tagged_block_parser.rs diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 67736374ec..efcc651b33 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -609,6 +609,8 @@ server_notification_definitions! { /// This event is internal-only. Used by Codex Cloud. RawResponseItemCompleted => "rawResponseItem/completed" (v2::RawResponseItemCompletedNotification), AgentMessageDelta => "item/agentMessage/delta" (v2::AgentMessageDeltaNotification), + /// EXPERIMENTAL - proposed plan streaming deltas for plan items. + PlanDelta => "item/plan/delta" (v2::PlanDeltaNotification), CommandExecutionOutputDelta => "item/commandExecution/outputDelta" (v2::CommandExecutionOutputDeltaNotification), TerminalInteraction => "item/commandExecution/terminalInteraction" (v2::TerminalInteractionNotification), FileChangeOutputDelta => "item/fileChange/outputDelta" (v2::FileChangeOutputDeltaNotification), 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 e6c679b418..39efe47655 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -6,6 +6,7 @@ use crate::protocol::v2::UserInput; use codex_protocol::protocol::AgentReasoningEvent; use codex_protocol::protocol::AgentReasoningRawContentEvent; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ItemCompletedEvent; use codex_protocol::protocol::ThreadRolledBackEvent; use codex_protocol::protocol::TurnAbortedEvent; use codex_protocol::protocol::UserMessageEvent; @@ -55,6 +56,7 @@ impl ThreadHistoryBuilder { EventMsg::AgentReasoningRawContent(payload) => { self.handle_agent_reasoning_raw_content(payload) } + EventMsg::ItemCompleted(payload) => self.handle_item_completed(payload), EventMsg::TokenCount(_) => {} EventMsg::EnteredReviewMode(_) => {} EventMsg::ExitedReviewMode(_) => {} @@ -125,6 +127,19 @@ impl ThreadHistoryBuilder { }); } + fn handle_item_completed(&mut self, payload: &ItemCompletedEvent) { + if let codex_protocol::items::TurnItem::Plan(plan) = &payload.item { + if plan.text.is_empty() { + return; + } + let id = self.next_item_id(); + self.ensure_turn().items.push(ThreadItem::Plan { + id, + text: plan.text.clone(), + }); + } + } + fn handle_turn_aborted(&mut self, _payload: &TurnAbortedEvent) { let Some(turn) = self.current_turn.as_mut() else { return; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 8bea094487..8164eb5289 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2036,6 +2036,11 @@ pub enum ThreadItem { AgentMessage { id: String, text: String }, #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] + /// EXPERIMENTAL - proposed plan item content. The completed plan item is + /// authoritative and may not match the concatenation of `PlanDelta` text. + Plan { id: String, text: String }, + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] Reasoning { id: String, #[serde(default)] @@ -2140,6 +2145,10 @@ impl From for ThreadItem { .collect::(); ThreadItem::AgentMessage { id: agent.id, text } } + CoreTurnItem::Plan(plan) => ThreadItem::Plan { + id: plan.id, + text: plan.text, + }, CoreTurnItem::Reasoning(reasoning) => ThreadItem::Reasoning { id: reasoning.id, summary: reasoning.summary_text, @@ -2428,6 +2437,18 @@ pub struct AgentMessageDeltaNotification { pub delta: String, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +/// EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should +/// not assume concatenated deltas match the completed plan item content. +pub struct PlanDeltaNotification { + pub thread_id: String, + pub turn_id: String, + pub item_id: String, + pub delta: String, +} + #[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 3798d76027..76d1131a2e 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -444,6 +444,7 @@ Today both notifications carry an empty `items` array even when item events were - `userMessage` — `{id, content}` where `content` is a list of user inputs (`text`, `image`, or `localImage`). - `agentMessage` — `{id, text}` containing the accumulated agent reply. +- `plan` — `{id, text}` emitted for plan-mode turns; plan text can stream via `item/plan/delta` (experimental). - `reasoning` — `{id, summary, content}` where `summary` holds streamed reasoning summaries (applicable for most OpenAI models) and `content` holds raw reasoning blocks (applicable for e.g. open source models). - `commandExecution` — `{id, command, cwd, status, commandActions, aggregatedOutput?, exitCode?, durationMs?}` for sandboxed commands; `status` is `inProgress`, `completed`, `failed`, or `declined`. - `fileChange` — `{id, changes, status}` describing proposed edits; `changes` list `{path, kind, diff}` and `status` is `inProgress`, `completed`, `failed`, or `declined`. @@ -467,6 +468,10 @@ There are additional item-specific events: - `item/agentMessage/delta` — appends streamed text for the agent message; concatenate `delta` values for the same `itemId` in order to reconstruct the full reply. +#### plan + +- `item/plan/delta` — streams proposed plan content for plan items (experimental); concatenate `delta` values for the same plan `itemId`. These deltas correspond to the `` block. + #### reasoning - `item/reasoning/summaryTextDelta` — streams readable reasoning summaries; `summaryIndex` increments when a new summary section opens. diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index dd2628deb7..bf8fad3a9c 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::McpToolCallResult; use codex_app_server_protocol::McpToolCallStatus; 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; use codex_app_server_protocol::ReasoningSummaryTextDeltaNotification; @@ -118,6 +119,7 @@ pub(crate) async fn apply_bespoke_event_handling( msg, } = event; match msg { + EventMsg::TurnStarted(_) => {} EventMsg::TurnComplete(_ev) => { handle_turn_complete( conversation_id, @@ -593,14 +595,27 @@ pub(crate) async fn apply_bespoke_event_handling( .await; } EventMsg::AgentMessageContentDelta(event) => { + let codex_protocol::protocol::AgentMessageContentDeltaEvent { item_id, delta, .. } = + event; let notification = AgentMessageDeltaNotification { + thread_id: conversation_id.to_string(), + turn_id: event_turn_id.clone(), + item_id, + delta, + }; + outgoing + .send_server_notification(ServerNotification::AgentMessageDelta(notification)) + .await; + } + EventMsg::PlanDelta(event) => { + let notification = PlanDeltaNotification { thread_id: conversation_id.to_string(), turn_id: event_turn_id.clone(), item_id: event.item_id, delta: event.delta, }; outgoing - .send_server_notification(ServerNotification::AgentMessageDelta(notification)) + .send_server_notification(ServerNotification::PlanDelta(notification)) .await; } EventMsg::ContextCompacted(..) => { @@ -1160,6 +1175,7 @@ async fn handle_turn_plan_update( api_version: ApiVersion, outgoing: &OutgoingMessageSender, ) { + // `update_plan` is a todo/checklist tool; it is not related to plan-mode updates if let ApiVersion::V2 = api_version { let notification = TurnPlanUpdatedNotification { thread_id: conversation_id.to_string(), diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index 4eeab8f950..90cd7635a3 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -736,6 +736,10 @@ impl McpProcess { Ok(notification) } + pub async fn read_next_message(&mut self) -> anyhow::Result { + self.read_stream_until_message(|_| true).await + } + /// Clears any buffered messages so future reads only consider new stream items. /// /// We call this when e.g. we want to validate against the next turn and no longer care about diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index 8f54753bf6..b67c3e5c33 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -8,6 +8,7 @@ mod dynamic_tools; mod initialize; mod model_list; mod output_schema; +mod plan_item; mod rate_limits; mod request_user_input; mod review; diff --git a/codex-rs/app-server/tests/suite/v2/plan_item.rs b/codex-rs/app-server/tests/suite/v2/plan_item.rs new file mode 100644 index 0000000000..d138954ac4 --- /dev/null +++ b/codex-rs/app-server/tests/suite/v2/plan_item.rs @@ -0,0 +1,257 @@ +use anyhow::Result; +use anyhow::anyhow; +use app_test_support::McpProcess; +use app_test_support::create_mock_responses_server_sequence; +use app_test_support::to_response; +use codex_app_server_protocol::ItemCompletedNotification; +use codex_app_server_protocol::ItemStartedNotification; +use codex_app_server_protocol::JSONRPCMessage; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::PlanDeltaNotification; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadStartParams; +use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::TurnCompletedNotification; +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::features::FEATURES; +use codex_core::features::Feature; +use codex_protocol::config_types::CollaborationMode; +use codex_protocol::config_types::ModeKind; +use codex_protocol::config_types::Settings; +use core_test_support::responses; +use core_test_support::skip_if_no_network; +use pretty_assertions::assert_eq; +use std::collections::BTreeMap; +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 plan_mode_uses_proposed_plan_block_for_plan_item() -> Result<()> { + skip_if_no_network!(Ok(())); + + let plan_block = "\n# Final plan\n- first\n- second\n\n"; + let full_message = format!("Preface\n{plan_block}Postscript"); + let responses = vec![responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_message_item_added("msg-1", ""), + responses::ev_output_text_delta(&full_message), + responses::ev_assistant_message("msg-1", &full_message), + responses::ev_completed("resp-1"), + ])]; + let server = create_mock_responses_server_sequence(responses).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 turn = start_plan_mode_turn(&mut mcp).await?; + let (_, completed_items, plan_deltas, turn_completed) = + collect_turn_notifications(&mut mcp).await?; + + assert_eq!(turn_completed.turn.id, turn.id); + assert_eq!(turn_completed.turn.status, TurnStatus::Completed); + + let expected_plan = ThreadItem::Plan { + id: format!("{}-plan", turn.id), + text: "# Final plan\n- first\n- second\n".to_string(), + }; + let expected_plan_id = format!("{}-plan", turn.id); + let streamed_plan = plan_deltas + .iter() + .map(|delta| delta.delta.as_str()) + .collect::(); + assert_eq!(streamed_plan, "# Final plan\n- first\n- second\n"); + assert!( + plan_deltas + .iter() + .all(|delta| delta.item_id == expected_plan_id) + ); + let plan_items = completed_items + .iter() + .filter_map(|item| match item { + ThreadItem::Plan { .. } => Some(item.clone()), + _ => None, + }) + .collect::>(); + assert_eq!(plan_items, vec![expected_plan]); + assert!( + completed_items + .iter() + .any(|item| matches!(item, ThreadItem::AgentMessage { .. })), + "agent message items should still be emitted alongside the plan item" + ); + + Ok(()) +} + +#[tokio::test] +async fn plan_mode_without_proposed_plan_does_not_emit_plan_item() -> Result<()> { + skip_if_no_network!(Ok(())); + + let responses = vec![responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "Done"), + responses::ev_completed("resp-1"), + ])]; + let server = create_mock_responses_server_sequence(responses).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 _turn = start_plan_mode_turn(&mut mcp).await?; + let (_, completed_items, plan_deltas, _) = collect_turn_notifications(&mut mcp).await?; + + let has_plan_item = completed_items + .iter() + .any(|item| matches!(item, ThreadItem::Plan { .. })); + assert!(!has_plan_item); + assert!(plan_deltas.is_empty()); + + Ok(()) +} + +async fn start_plan_mode_turn(mcp: &mut McpProcess) -> Result { + let thread_req = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let thread = to_response::(thread_resp)?.thread; + + let collaboration_mode = CollaborationMode { + mode: ModeKind::Plan, + settings: Settings { + model: "mock-model".to_string(), + reasoning_effort: None, + developer_instructions: None, + }, + }; + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![V2UserInput::Text { + text: "Plan this".to_string(), + text_elements: Vec::new(), + }], + collaboration_mode: Some(collaboration_mode), + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + Ok(to_response::(turn_resp)?.turn) +} + +async fn collect_turn_notifications( + mcp: &mut McpProcess, +) -> Result<( + Vec, + Vec, + Vec, + TurnCompletedNotification, +)> { + let mut started_items = Vec::new(); + let mut completed_items = Vec::new(); + let mut plan_deltas = Vec::new(); + + loop { + let message = timeout(DEFAULT_READ_TIMEOUT, mcp.read_next_message()).await??; + let JSONRPCMessage::Notification(notification) = message else { + continue; + }; + match notification.method.as_str() { + "item/started" => { + let params = notification + .params + .ok_or_else(|| anyhow!("item/started notifications must include params"))?; + let payload: ItemStartedNotification = serde_json::from_value(params)?; + started_items.push(payload.item); + } + "item/completed" => { + let params = notification + .params + .ok_or_else(|| anyhow!("item/completed notifications must include params"))?; + let payload: ItemCompletedNotification = serde_json::from_value(params)?; + completed_items.push(payload.item); + } + "item/plan/delta" => { + let params = notification + .params + .ok_or_else(|| anyhow!("item/plan/delta notifications must include params"))?; + let payload: PlanDeltaNotification = serde_json::from_value(params)?; + plan_deltas.push(payload); + } + "turn/completed" => { + let params = notification + .params + .ok_or_else(|| anyhow!("turn/completed notifications must include params"))?; + let payload: TurnCompletedNotification = serde_json::from_value(params)?; + return Ok((started_items, completed_items, plan_deltas, payload)); + } + _ => {} + } + } +} + +fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { + let features = BTreeMap::from([ + (Feature::RemoteModels, false), + (Feature::CollaborationModes, true), + ]); + let feature_entries = features + .into_iter() + .map(|(feature, enabled)| { + let key = FEATURES + .iter() + .find(|spec| spec.id == feature) + .map(|spec| spec.key) + .unwrap_or_else(|| panic!("missing feature key for {feature:?}")); + format!("{key} = {enabled}") + }) + .collect::>() + .join("\n"); + 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" + +[features] +{feature_entries} + +[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/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 611c0d164c..151c6fa0fb 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -146,6 +146,7 @@ mod tests { use crate::config::Config; use crate::config::ConfigBuilder; use assert_matches::assert_matches; + use codex_protocol::config_types::ModeKind; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::TurnAbortReason; @@ -231,6 +232,7 @@ mod tests { async fn on_event_updates_status_from_task_started() { let status = agent_status_from_event(&EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, })); assert_eq!(status, Some(AgentStatus::Running)); } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 324f41a04e..30dd8d24fc 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -30,6 +30,7 @@ use crate::rollout::session_index; use crate::stream_events_utils::HandleOutputCtx; use crate::stream_events_utils::handle_non_tool_response_item; use crate::stream_events_utils::handle_output_item_done; +use crate::stream_events_utils::last_assistant_message_from_item; use crate::terminal; use crate::transport_manager::TransportManager; use crate::truncate::TruncationPolicy; @@ -44,6 +45,7 @@ use codex_protocol::config_types::Settings; use codex_protocol::config_types::WebSearchMode; use codex_protocol::dynamic_tools::DynamicToolResponse; use codex_protocol::dynamic_tools::DynamicToolSpec; +use codex_protocol::items::PlanItem; use codex_protocol::items::TurnItem; use codex_protocol::items::UserMessageItem; use codex_protocol::models::BaseInstructions; @@ -127,6 +129,9 @@ use crate::mentions::collect_explicit_app_paths; use crate::mentions::collect_tool_mentions_from_messages; use crate::model_provider_info::CHAT_WIRE_API_DEPRECATION_SUMMARY; use crate::project_doc::get_user_instructions; +use crate::proposed_plan_parser::ProposedPlanParser; +use crate::proposed_plan_parser::ProposedPlanSegment; +use crate::proposed_plan_parser::extract_proposed_plan_text; use crate::protocol::AgentMessageContentDeltaEvent; use crate::protocol::AgentReasoningSectionBreakEvent; use crate::protocol::ApplyPatchApprovalRequestEvent; @@ -139,6 +144,7 @@ use crate::protocol::EventMsg; use crate::protocol::ExecApprovalRequestEvent; use crate::protocol::McpServerRefreshConfig; use crate::protocol::Op; +use crate::protocol::PlanDeltaEvent; use crate::protocol::RateLimitSnapshot; use crate::protocol::ReasoningContentDeltaEvent; use crate::protocol::ReasoningRawContentDeltaEvent; @@ -482,6 +488,7 @@ pub(crate) struct TurnContext { pub(crate) developer_instructions: Option, pub(crate) compact_prompt: Option, pub(crate) user_instructions: Option, + pub(crate) collaboration_mode_kind: ModeKind, pub(crate) personality: Option, pub(crate) approval_policy: AskForApproval, pub(crate) sandbox_policy: SandboxPolicy, @@ -682,6 +689,7 @@ impl Session { developer_instructions: session_configuration.developer_instructions.clone(), compact_prompt: session_configuration.compact_prompt.clone(), user_instructions: session_configuration.user_instructions.clone(), + collaboration_mode_kind: session_configuration.collaboration_mode.mode, personality: session_configuration.personality, approval_policy: session_configuration.approval_policy.value(), sandbox_policy: session_configuration.sandbox_policy.get().clone(), @@ -3196,6 +3204,7 @@ async fn spawn_review_thread( developer_instructions: None, user_instructions: None, compact_prompt: parent_turn_context.compact_prompt.clone(), + collaboration_mode_kind: parent_turn_context.collaboration_mode_kind, personality: parent_turn_context.personality, approval_policy: parent_turn_context.approval_policy, sandbox_policy: parent_turn_context.sandbox_policy.clone(), @@ -3310,6 +3319,7 @@ pub(crate) async fn run_turn( let total_usage_tokens = sess.get_total_token_usage().await; let event = EventMsg::TurnStarted(TurnStartedEvent { model_context_window: turn_context.client.get_model_context_window(), + collaboration_mode_kind: turn_context.collaboration_mode_kind, }); sess.send_event(&turn_context, event).await; if total_usage_tokens >= auto_compact_limit { @@ -3759,6 +3769,381 @@ struct SamplingRequestResult { last_agent_message: Option, } +/// Ephemeral per-response state for streaming a single proposed plan. +/// This is intentionally not persisted or stored in session/state since it +/// only exists while a response is actively streaming. The final plan text +/// is extracted from the completed assistant message. +/// Tracks a single proposed plan item across a streaming response. +struct ProposedPlanItemState { + item_id: String, + started: bool, + completed: bool, +} + +/// Per-item plan parsers so we can buffer text while detecting `` +/// tags without ever mixing buffered lines across item ids. +struct PlanParsers { + assistant: HashMap, +} + +impl PlanParsers { + fn new() -> Self { + Self { + assistant: HashMap::new(), + } + } + + fn assistant_parser_mut(&mut self, item_id: &str) -> &mut ProposedPlanParser { + self.assistant + .entry(item_id.to_string()) + .or_insert_with(ProposedPlanParser::new) + } + + fn take_assistant_parser(&mut self, item_id: &str) -> Option { + self.assistant.remove(item_id) + } + + fn drain_assistant_parsers(&mut self) -> Vec<(String, ProposedPlanParser)> { + self.assistant.drain().collect() + } +} + +/// Aggregated state used only while streaming a plan-mode response. +/// Includes per-item parsers, deferred agent message bookkeeping, and the plan item lifecycle. +struct PlanModeStreamState { + /// Per-item parsers for assistant streams in plan mode. + plan_parsers: PlanParsers, + /// Agent message items started by the model but deferred until we see non-plan text. + pending_agent_message_items: HashMap, + /// Agent message items whose start notification has been emitted. + started_agent_message_items: HashSet, + /// Leading whitespace buffered until we see non-whitespace text for an item. + leading_whitespace_by_item: HashMap, + /// Tracks plan item lifecycle while streaming plan output. + plan_item_state: ProposedPlanItemState, +} + +impl PlanModeStreamState { + fn new(turn_id: &str) -> Self { + Self { + plan_parsers: PlanParsers::new(), + pending_agent_message_items: HashMap::new(), + started_agent_message_items: HashSet::new(), + leading_whitespace_by_item: HashMap::new(), + plan_item_state: ProposedPlanItemState::new(turn_id), + } + } +} + +impl ProposedPlanItemState { + fn new(turn_id: &str) -> Self { + Self { + item_id: format!("{turn_id}-plan"), + started: false, + completed: false, + } + } + + async fn start(&mut self, sess: &Session, turn_context: &TurnContext) { + if self.started || self.completed { + return; + } + self.started = true; + let item = TurnItem::Plan(PlanItem { + id: self.item_id.clone(), + text: String::new(), + }); + sess.emit_turn_item_started(turn_context, &item).await; + } + + async fn push_delta(&mut self, sess: &Session, turn_context: &TurnContext, delta: &str) { + if self.completed { + return; + } + if delta.is_empty() { + return; + } + let event = PlanDeltaEvent { + thread_id: sess.conversation_id.to_string(), + turn_id: turn_context.sub_id.clone(), + item_id: self.item_id.clone(), + delta: delta.to_string(), + }; + sess.send_event(turn_context, EventMsg::PlanDelta(event)) + .await; + } + + async fn complete_with_text( + &mut self, + sess: &Session, + turn_context: &TurnContext, + text: String, + ) { + if self.completed || !self.started { + return; + } + self.completed = true; + let item = TurnItem::Plan(PlanItem { + id: self.item_id.clone(), + text, + }); + sess.emit_turn_item_completed(turn_context, item).await; + } +} + +/// In plan mode we defer agent message starts until the parser emits non-plan +/// text. The parser buffers each line until it can rule out a tag prefix, so +/// plan-only outputs never show up as empty assistant messages. +async fn maybe_emit_pending_agent_message_start( + sess: &Session, + turn_context: &TurnContext, + state: &mut PlanModeStreamState, + item_id: &str, +) { + if state.started_agent_message_items.contains(item_id) { + return; + } + if let Some(item) = state.pending_agent_message_items.remove(item_id) { + sess.emit_turn_item_started(turn_context, &item).await; + state + .started_agent_message_items + .insert(item_id.to_string()); + } +} + +/// Agent messages are text-only today; concatenate all text entries. +fn agent_message_text(item: &codex_protocol::items::AgentMessageItem) -> String { + item.content + .iter() + .map(|entry| match entry { + codex_protocol::items::AgentMessageContent::Text { text } => text.as_str(), + }) + .collect() +} + +/// Split the stream into normal assistant text vs. proposed plan content. +/// Normal text becomes AgentMessage deltas; plan content becomes PlanDelta + +/// TurnItem::Plan. +async fn handle_plan_segments( + sess: &Session, + turn_context: &TurnContext, + state: &mut PlanModeStreamState, + item_id: &str, + segments: Vec, +) { + for segment in segments { + match segment { + ProposedPlanSegment::Normal(delta) => { + if delta.is_empty() { + continue; + } + let has_non_whitespace = delta.chars().any(|ch| !ch.is_whitespace()); + if !has_non_whitespace && !state.started_agent_message_items.contains(item_id) { + let entry = state + .leading_whitespace_by_item + .entry(item_id.to_string()) + .or_default(); + entry.push_str(&delta); + continue; + } + let delta = if !state.started_agent_message_items.contains(item_id) { + if let Some(prefix) = state.leading_whitespace_by_item.remove(item_id) { + format!("{prefix}{delta}") + } else { + delta + } + } else { + delta + }; + maybe_emit_pending_agent_message_start(sess, turn_context, state, item_id).await; + + let event = AgentMessageContentDeltaEvent { + thread_id: sess.conversation_id.to_string(), + turn_id: turn_context.sub_id.clone(), + item_id: item_id.to_string(), + delta, + }; + sess.send_event(turn_context, EventMsg::AgentMessageContentDelta(event)) + .await; + } + ProposedPlanSegment::ProposedPlanStart => { + if !state.plan_item_state.completed { + state.plan_item_state.start(sess, turn_context).await; + } + } + ProposedPlanSegment::ProposedPlanDelta(delta) => { + if !state.plan_item_state.completed { + if !state.plan_item_state.started { + state.plan_item_state.start(sess, turn_context).await; + } + state + .plan_item_state + .push_delta(sess, turn_context, &delta) + .await; + } + } + ProposedPlanSegment::ProposedPlanEnd => {} + } + } +} + +/// Flush any buffered proposed-plan segments when a specific assistant message ends. +async fn flush_proposed_plan_segments_for_item( + sess: &Session, + turn_context: &TurnContext, + state: &mut PlanModeStreamState, + item_id: &str, +) { + let Some(mut parser) = state.plan_parsers.take_assistant_parser(item_id) else { + return; + }; + let segments = parser.finish(); + if segments.is_empty() { + return; + } + handle_plan_segments(sess, turn_context, state, item_id, segments).await; +} + +/// Flush any remaining assistant plan parsers when the response completes. +async fn flush_proposed_plan_segments_all( + sess: &Session, + turn_context: &TurnContext, + state: &mut PlanModeStreamState, +) { + for (item_id, mut parser) in state.plan_parsers.drain_assistant_parsers() { + let segments = parser.finish(); + if segments.is_empty() { + continue; + } + handle_plan_segments(sess, turn_context, state, &item_id, segments).await; + } +} + +/// Emit completion for plan items by parsing the finalized assistant message. +async fn maybe_complete_plan_item_from_message( + sess: &Session, + turn_context: &TurnContext, + state: &mut PlanModeStreamState, + item: &ResponseItem, +) { + if let ResponseItem::Message { role, content, .. } = item + && role == "assistant" + { + let mut text = String::new(); + for entry in content { + if let ContentItem::OutputText { text: chunk } = entry { + text.push_str(chunk); + } + } + if let Some(plan_text) = extract_proposed_plan_text(&text) { + if !state.plan_item_state.started { + state.plan_item_state.start(sess, turn_context).await; + } + state + .plan_item_state + .complete_with_text(sess, turn_context, plan_text) + .await; + } + } +} + +/// Emit a completed agent message in plan mode, respecting deferred starts. +async fn emit_agent_message_in_plan_mode( + sess: &Session, + turn_context: &TurnContext, + agent_message: codex_protocol::items::AgentMessageItem, + state: &mut PlanModeStreamState, +) { + let agent_message_id = agent_message.id.clone(); + let text = agent_message_text(&agent_message); + if text.trim().is_empty() { + state.pending_agent_message_items.remove(&agent_message_id); + state.started_agent_message_items.remove(&agent_message_id); + return; + } + + maybe_emit_pending_agent_message_start(sess, turn_context, state, &agent_message_id).await; + + if !state + .started_agent_message_items + .contains(&agent_message_id) + { + let start_item = state + .pending_agent_message_items + .remove(&agent_message_id) + .unwrap_or_else(|| { + TurnItem::AgentMessage(codex_protocol::items::AgentMessageItem { + id: agent_message_id.clone(), + content: Vec::new(), + }) + }); + sess.emit_turn_item_started(turn_context, &start_item).await; + state + .started_agent_message_items + .insert(agent_message_id.clone()); + } + + sess.emit_turn_item_completed(turn_context, TurnItem::AgentMessage(agent_message)) + .await; + state.started_agent_message_items.remove(&agent_message_id); +} + +/// Emit completion for a plan-mode turn item, handling agent messages specially. +async fn emit_turn_item_in_plan_mode( + sess: &Session, + turn_context: &TurnContext, + turn_item: TurnItem, + previously_active_item: Option<&TurnItem>, + state: &mut PlanModeStreamState, +) { + match turn_item { + TurnItem::AgentMessage(agent_message) => { + emit_agent_message_in_plan_mode(sess, turn_context, agent_message, state).await; + } + _ => { + if previously_active_item.is_none() { + sess.emit_turn_item_started(turn_context, &turn_item).await; + } + sess.emit_turn_item_completed(turn_context, turn_item).await; + } + } +} + +/// Handle a completed assistant response item in plan mode, returning true if handled. +async fn handle_assistant_item_done_in_plan_mode( + sess: &Session, + turn_context: &TurnContext, + item: &ResponseItem, + state: &mut PlanModeStreamState, + previously_active_item: Option<&TurnItem>, + last_agent_message: &mut Option, +) -> bool { + if let ResponseItem::Message { role, .. } = item + && role == "assistant" + { + maybe_complete_plan_item_from_message(sess, turn_context, state, item).await; + + if let Some(turn_item) = handle_non_tool_response_item(item, true).await { + emit_turn_item_in_plan_mode( + sess, + turn_context, + turn_item, + previously_active_item, + state, + ) + .await; + } + + sess.record_conversation_items(turn_context, std::slice::from_ref(item)) + .await; + if let Some(agent_message) = last_assistant_message_from_item(item, true) { + *last_agent_message = Some(agent_message); + } + return true; + } + false +} + async fn drain_in_flight( in_flight: &mut FuturesOrdered>>, sess: Arc, @@ -3795,10 +4180,6 @@ async fn try_run_sampling_request( prompt: &Prompt, cancellation_token: CancellationToken, ) -> CodexResult { - // TODO: If we need to guarantee the persisted mode always matches the prompt used for this - // turn, capture it in TurnContext at creation time. Using SessionConfiguration here avoids - // duplicating model settings on TurnContext, but a later Op could update the session config - // before this write occurs. let collaboration_mode = sess.current_collaboration_mode().await; let rollout_item = RolloutItem::TurnContext(TurnContextItem { cwd: turn_context.cwd.clone(), @@ -3843,6 +4224,8 @@ async fn try_run_sampling_request( let mut last_agent_message: Option = None; let mut active_item: Option = None; let mut should_emit_turn_diff = false; + let plan_mode = turn_context.collaboration_mode_kind == ModeKind::Plan; + let mut plan_mode_state = plan_mode.then(|| PlanModeStreamState::new(&turn_context.sub_id)); let receiving_span = trace_span!("receiving_stream"); let outcome: CodexResult = loop { let handle_responses = trace_span!( @@ -3881,6 +4264,33 @@ async fn try_run_sampling_request( ResponseEvent::Created => {} ResponseEvent::OutputItemDone(item) => { let previously_active_item = active_item.take(); + if let Some(state) = plan_mode_state.as_mut() { + if let Some(previous) = previously_active_item.as_ref() { + let item_id = previous.id(); + if matches!(previous, TurnItem::AgentMessage(_)) { + flush_proposed_plan_segments_for_item( + &sess, + &turn_context, + state, + &item_id, + ) + .await; + } + } + if handle_assistant_item_done_in_plan_mode( + &sess, + &turn_context, + &item, + state, + previously_active_item.as_ref(), + &mut last_agent_message, + ) + .await + { + continue; + } + } + let mut ctx = HandleOutputCtx { sess: sess.clone(), turn_context: turn_context.clone(), @@ -3900,8 +4310,17 @@ async fn try_run_sampling_request( needs_follow_up |= output_result.needs_follow_up; } ResponseEvent::OutputItemAdded(item) => { - if let Some(turn_item) = handle_non_tool_response_item(&item).await { - sess.emit_turn_item_started(&turn_context, &turn_item).await; + if let Some(turn_item) = handle_non_tool_response_item(&item, plan_mode).await { + if let Some(state) = plan_mode_state.as_mut() + && matches!(turn_item, TurnItem::AgentMessage(_)) + { + let item_id = turn_item.id(); + state + .pending_agent_message_items + .insert(item_id, turn_item.clone()); + } else { + sess.emit_turn_item_started(&turn_context, &turn_item).await; + } active_item = Some(turn_item); } } @@ -3925,6 +4344,9 @@ async fn try_run_sampling_request( response_id: _, token_usage, } => { + if let Some(state) = plan_mode_state.as_mut() { + flush_proposed_plan_segments_all(&sess, &turn_context, state).await; + } sess.update_token_usage_info(&turn_context, token_usage.as_ref()) .await; should_emit_turn_diff = true; @@ -3940,14 +4362,25 @@ async fn try_run_sampling_request( // In review child threads, suppress assistant text deltas; the // UI will show a selection popup from the final ReviewOutput. if let Some(active) = active_item.as_ref() { - let event = AgentMessageContentDeltaEvent { - thread_id: sess.conversation_id.to_string(), - turn_id: turn_context.sub_id.clone(), - item_id: active.id(), - delta: delta.clone(), - }; - sess.send_event(&turn_context, EventMsg::AgentMessageContentDelta(event)) - .await; + let item_id = active.id(); + if let Some(state) = plan_mode_state.as_mut() + && matches!(active, TurnItem::AgentMessage(_)) + { + let segments = state + .plan_parsers + .assistant_parser_mut(&item_id) + .parse(&delta); + handle_plan_segments(&sess, &turn_context, state, &item_id, segments).await; + } else { + let event = AgentMessageContentDeltaEvent { + thread_id: sess.conversation_id.to_string(), + turn_id: turn_context.sub_id.clone(), + item_id, + delta, + }; + sess.send_event(&turn_context, EventMsg::AgentMessageContentDelta(event)) + .await; + } } else { error_or_panic("OutputTextDelta without active item".to_string()); } diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index b233618eea..af9aacc769 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -61,6 +61,7 @@ pub(crate) async fn run_compact_task( ) { let start_event = EventMsg::TurnStarted(TurnStartedEvent { model_context_window: turn_context.client.get_model_context_window(), + collaboration_mode_kind: turn_context.collaboration_mode_kind, }); sess.send_event(&turn_context, start_event).await; run_compact_task_inner(sess.clone(), turn_context, input).await; diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index 35c157acfc..b45a2769dc 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -22,6 +22,7 @@ pub(crate) async fn run_inline_remote_auto_compact_task( pub(crate) async fn run_remote_compact_task(sess: Arc, turn_context: Arc) { let start_event = EventMsg::TurnStarted(TurnStartedEvent { model_context_window: turn_context.client.get_model_context_window(), + collaboration_mode_kind: turn_context.collaboration_mode_kind, }); sess.send_event(&turn_context, start_event).await; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 63bba76507..ba47838e1f 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -49,9 +49,11 @@ mod model_provider_info; pub mod parse_command; pub mod path_utils; pub mod powershell; +mod proposed_plan_parser; pub mod sandboxing; mod session_prefix; mod stream_events_utils; +mod tagged_block_parser; mod text_encoding; pub mod token_data; mod truncate; diff --git a/codex-rs/core/src/proposed_plan_parser.rs b/codex-rs/core/src/proposed_plan_parser.rs new file mode 100644 index 0000000000..44be264f29 --- /dev/null +++ b/codex-rs/core/src/proposed_plan_parser.rs @@ -0,0 +1,185 @@ +use crate::tagged_block_parser::TagSpec; +use crate::tagged_block_parser::TaggedLineParser; +use crate::tagged_block_parser::TaggedLineSegment; + +const OPEN_TAG: &str = ""; +const CLOSE_TAG: &str = ""; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PlanTag { + ProposedPlan, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ProposedPlanSegment { + Normal(String), + ProposedPlanStart, + ProposedPlanDelta(String), + ProposedPlanEnd, +} + +/// Parser for `` blocks emitted in plan mode. +/// +/// This is a thin wrapper around the generic line-based tag parser. It maps +/// tag-aware segments into plan-specific segments for downstream consumers. +#[derive(Debug)] +pub(crate) struct ProposedPlanParser { + parser: TaggedLineParser, +} + +impl ProposedPlanParser { + pub(crate) fn new() -> Self { + Self { + parser: TaggedLineParser::new(vec![TagSpec { + open: OPEN_TAG, + close: CLOSE_TAG, + tag: PlanTag::ProposedPlan, + }]), + } + } + + pub(crate) fn parse(&mut self, delta: &str) -> Vec { + self.parser + .parse(delta) + .into_iter() + .map(map_plan_segment) + .collect() + } + + pub(crate) fn finish(&mut self) -> Vec { + self.parser + .finish() + .into_iter() + .map(map_plan_segment) + .collect() + } +} + +fn map_plan_segment(segment: TaggedLineSegment) -> ProposedPlanSegment { + match segment { + TaggedLineSegment::Normal(text) => ProposedPlanSegment::Normal(text), + TaggedLineSegment::TagStart(PlanTag::ProposedPlan) => { + ProposedPlanSegment::ProposedPlanStart + } + TaggedLineSegment::TagDelta(PlanTag::ProposedPlan, text) => { + ProposedPlanSegment::ProposedPlanDelta(text) + } + TaggedLineSegment::TagEnd(PlanTag::ProposedPlan) => ProposedPlanSegment::ProposedPlanEnd, + } +} + +pub(crate) fn strip_proposed_plan_blocks(text: &str) -> String { + let mut parser = ProposedPlanParser::new(); + let mut out = String::new(); + for segment in parser.parse(text).into_iter().chain(parser.finish()) { + if let ProposedPlanSegment::Normal(delta) = segment { + out.push_str(&delta); + } + } + out +} + +pub(crate) fn extract_proposed_plan_text(text: &str) -> Option { + let mut parser = ProposedPlanParser::new(); + let mut plan_text = String::new(); + let mut saw_plan_block = false; + for segment in parser.parse(text).into_iter().chain(parser.finish()) { + match segment { + ProposedPlanSegment::ProposedPlanStart => { + saw_plan_block = true; + plan_text.clear(); + } + ProposedPlanSegment::ProposedPlanDelta(delta) => { + plan_text.push_str(&delta); + } + ProposedPlanSegment::ProposedPlanEnd | ProposedPlanSegment::Normal(_) => {} + } + } + saw_plan_block.then_some(plan_text) +} + +#[cfg(test)] +mod tests { + use super::ProposedPlanParser; + use super::ProposedPlanSegment; + use super::strip_proposed_plan_blocks; + use pretty_assertions::assert_eq; + + #[test] + fn streams_proposed_plan_segments() { + let mut parser = ProposedPlanParser::new(); + let mut segments = Vec::new(); + + for chunk in [ + "Intro text\n\n- step 1\n", + "\nOutro", + ] { + segments.extend(parser.parse(chunk)); + } + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![ + ProposedPlanSegment::Normal("Intro text\n".to_string()), + ProposedPlanSegment::ProposedPlanStart, + ProposedPlanSegment::ProposedPlanDelta("- step 1\n".to_string()), + ProposedPlanSegment::ProposedPlanEnd, + ProposedPlanSegment::Normal("Outro".to_string()), + ] + ); + } + + #[test] + fn preserves_non_tag_lines() { + let mut parser = ProposedPlanParser::new(); + let mut segments = parser.parse(" extra\n"); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![ProposedPlanSegment::Normal( + " extra\n".to_string() + )] + ); + } + + #[test] + fn closes_unterminated_plan_block_on_finish() { + let mut parser = ProposedPlanParser::new(); + let mut segments = parser.parse("\n- step 1\n"); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![ + ProposedPlanSegment::ProposedPlanStart, + ProposedPlanSegment::ProposedPlanDelta("- step 1\n".to_string()), + ProposedPlanSegment::ProposedPlanEnd, + ] + ); + } + + #[test] + fn closes_tag_line_without_trailing_newline() { + let mut parser = ProposedPlanParser::new(); + let mut segments = parser.parse("\n- step 1\n"); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![ + ProposedPlanSegment::ProposedPlanStart, + ProposedPlanSegment::ProposedPlanDelta("- step 1\n".to_string()), + ProposedPlanSegment::ProposedPlanEnd, + ] + ); + } + + #[test] + fn strips_proposed_plan_blocks_from_text() { + let text = "before\n\n- step\n\nafter"; + assert_eq!(strip_proposed_plan_blocks(text), "before\nafter"); + } +} diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 6de60ae05c..5796bd1961 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -48,6 +48,12 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::ThreadRolledBack(_) | EventMsg::UndoCompleted(_) | EventMsg::TurnAborted(_) => true, + EventMsg::ItemCompleted(event) => { + // Plan items are derived from streaming tags and are not part of the + // raw ResponseItem history, so we persist their completion to replay + // them on resume without bloating rollouts with every item lifecycle. + matches!(event.item, codex_protocol::items::TurnItem::Plan(_)) + } EventMsg::Error(_) | EventMsg::Warning(_) | EventMsg::TurnStarted(_) @@ -89,8 +95,8 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::ViewImageToolCall(_) | EventMsg::DeprecationNotice(_) | EventMsg::ItemStarted(_) - | EventMsg::ItemCompleted(_) | EventMsg::AgentMessageContentDelta(_) + | EventMsg::PlanDelta(_) | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) | EventMsg::SkillsUpdateAvailable diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index 930ce5afd6..91f7efdb01 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -1,6 +1,7 @@ use std::pin::Pin; use std::sync::Arc; +use codex_protocol::config_types::ModeKind; use codex_protocol::items::TurnItem; use tokio_util::sync::CancellationToken; @@ -10,6 +11,7 @@ use crate::error::CodexErr; use crate::error::Result; use crate::function_tool::FunctionCallError; use crate::parse_turn_item; +use crate::proposed_plan_parser::strip_proposed_plan_blocks; use crate::tools::parallel::ToolCallRuntime; use crate::tools::router::ToolRouter; use codex_protocol::models::FunctionCallOutputPayload; @@ -46,6 +48,7 @@ pub(crate) async fn handle_output_item_done( previously_active_item: Option, ) -> Result { let mut output = OutputItemResult::default(); + let plan_mode = ctx.turn_context.collaboration_mode_kind == ModeKind::Plan; match ToolRouter::build_tool_call(ctx.sess.as_ref(), item.clone()).await { // The model emitted a tool call; log it, persist the item immediately, and queue the tool execution. @@ -74,7 +77,7 @@ pub(crate) async fn handle_output_item_done( } // No tool call: convert messages/reasoning into turn items and mark them as complete. Ok(None) => { - if let Some(turn_item) = handle_non_tool_response_item(&item).await { + if let Some(turn_item) = handle_non_tool_response_item(&item, plan_mode).await { if previously_active_item.is_none() { ctx.sess .emit_turn_item_started(&ctx.turn_context, &turn_item) @@ -89,7 +92,7 @@ pub(crate) async fn handle_output_item_done( ctx.sess .record_conversation_items(&ctx.turn_context, std::slice::from_ref(&item)) .await; - let last_agent_message = last_assistant_message_from_item(&item); + let last_agent_message = last_assistant_message_from_item(&item, plan_mode); output.last_agent_message = last_agent_message; } @@ -155,13 +158,31 @@ pub(crate) async fn handle_output_item_done( Ok(output) } -pub(crate) async fn handle_non_tool_response_item(item: &ResponseItem) -> Option { +pub(crate) async fn handle_non_tool_response_item( + item: &ResponseItem, + plan_mode: bool, +) -> Option { debug!(?item, "Output item"); match item { ResponseItem::Message { .. } | ResponseItem::Reasoning { .. } - | ResponseItem::WebSearchCall { .. } => parse_turn_item(item), + | ResponseItem::WebSearchCall { .. } => { + let mut turn_item = parse_turn_item(item)?; + if plan_mode && let TurnItem::AgentMessage(agent_message) = &mut turn_item { + let combined = agent_message + .content + .iter() + .map(|entry| match entry { + codex_protocol::items::AgentMessageContent::Text { text } => text.as_str(), + }) + .collect::(); + let stripped = strip_proposed_plan_blocks(&combined); + agent_message.content = + vec![codex_protocol::items::AgentMessageContent::Text { text: stripped }]; + } + Some(turn_item) + } ResponseItem::FunctionCallOutput { .. } | ResponseItem::CustomToolCallOutput { .. } => { debug!("unexpected tool output from stream"); None @@ -170,14 +191,29 @@ pub(crate) async fn handle_non_tool_response_item(item: &ResponseItem) -> Option } } -pub(crate) fn last_assistant_message_from_item(item: &ResponseItem) -> Option { +pub(crate) fn last_assistant_message_from_item( + item: &ResponseItem, + plan_mode: bool, +) -> Option { if let ResponseItem::Message { role, content, .. } = item && role == "assistant" { - return content.iter().rev().find_map(|ci| match ci { - codex_protocol::models::ContentItem::OutputText { text } => Some(text.clone()), - _ => None, - }); + let combined = content + .iter() + .filter_map(|ci| match ci { + codex_protocol::models::ContentItem::OutputText { text } => Some(text.as_str()), + _ => None, + }) + .collect::(); + if combined.is_empty() { + return None; + } + return if plan_mode { + let stripped = strip_proposed_plan_blocks(&combined); + (!stripped.trim().is_empty()).then_some(stripped) + } else { + Some(combined) + }; } None } diff --git a/codex-rs/core/src/tagged_block_parser.rs b/codex-rs/core/src/tagged_block_parser.rs new file mode 100644 index 0000000000..46ec012c30 --- /dev/null +++ b/codex-rs/core/src/tagged_block_parser.rs @@ -0,0 +1,314 @@ +//! Line-based tag block parsing for streamed text. +//! +//! The parser buffers each line until it can disprove that the line is a tag, +//! which is required for tags that must appear alone on a line. For example, +//! Proposed Plan output uses `` and `` tags +//! on their own lines so clients can stream plan content separately. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct TagSpec { + pub(crate) open: &'static str, + pub(crate) close: &'static str, + pub(crate) tag: T, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum TaggedLineSegment { + Normal(String), + TagStart(T), + TagDelta(T, String), + TagEnd(T), +} + +/// Stateful line parser that splits input into normal text vs tag blocks. +/// +/// How it works: +/// - While reading a line, we buffer characters until the line either finishes +/// (`\n`) or stops matching any tag prefix (after `trim_start`). +/// - If it stops matching a tag prefix, the buffered line is immediately +/// emitted as text and we continue in "plain text" mode until the next +/// newline. +/// - When a full line is available, we compare it to the open/close tags; tag +/// lines emit TagStart/TagEnd, otherwise the line is emitted as text. +/// - `finish()` flushes any buffered line and auto-closes an unterminated tag, +/// which keeps streaming resilient to missing closing tags. +#[derive(Debug, Default)] +pub(crate) struct TaggedLineParser +where + T: Copy + Eq, +{ + specs: Vec>, + active_tag: Option, + detect_tag: bool, + line_buffer: String, +} + +impl TaggedLineParser +where + T: Copy + Eq, +{ + pub(crate) fn new(specs: Vec>) -> Self { + Self { + specs, + active_tag: None, + detect_tag: true, + line_buffer: String::new(), + } + } + + /// Parse a streamed delta into line-aware segments. + pub(crate) fn parse(&mut self, delta: &str) -> Vec> { + let mut segments = Vec::new(); + let mut run = String::new(); + + for ch in delta.chars() { + if self.detect_tag { + if !run.is_empty() { + self.push_text(std::mem::take(&mut run), &mut segments); + } + self.line_buffer.push(ch); + if ch == '\n' { + self.finish_line(&mut segments); + continue; + } + let slug = self.line_buffer.trim_start(); + if slug.is_empty() || self.is_tag_prefix(slug) { + continue; + } + // This line cannot be a tag line, so flush it immediately. + let buffered = std::mem::take(&mut self.line_buffer); + self.detect_tag = false; + self.push_text(buffered, &mut segments); + continue; + } + + run.push(ch); + if ch == '\n' { + self.push_text(std::mem::take(&mut run), &mut segments); + self.detect_tag = true; + } + } + + if !run.is_empty() { + self.push_text(run, &mut segments); + } + + segments + } + + /// Flush any buffered text and close an unterminated tag block. + pub(crate) fn finish(&mut self) -> Vec> { + let mut segments = Vec::new(); + if !self.line_buffer.is_empty() { + let buffered = std::mem::take(&mut self.line_buffer); + let without_newline = buffered.strip_suffix('\n').unwrap_or(&buffered); + let slug = without_newline.trim_start().trim_end(); + + if let Some(tag) = self.match_open(slug) + && self.active_tag.is_none() + { + push_segment(&mut segments, TaggedLineSegment::TagStart(tag)); + self.active_tag = Some(tag); + } else if let Some(tag) = self.match_close(slug) + && self.active_tag == Some(tag) + { + push_segment(&mut segments, TaggedLineSegment::TagEnd(tag)); + self.active_tag = None; + } else { + // The buffered line never proved to be a tag line. + self.push_text(buffered, &mut segments); + } + } + if let Some(tag) = self.active_tag.take() { + push_segment(&mut segments, TaggedLineSegment::TagEnd(tag)); + } + self.detect_tag = true; + segments + } + + fn finish_line(&mut self, segments: &mut Vec>) { + let line = std::mem::take(&mut self.line_buffer); + let without_newline = line.strip_suffix('\n').unwrap_or(&line); + let slug = without_newline.trim_start().trim_end(); + + if let Some(tag) = self.match_open(slug) + && self.active_tag.is_none() + { + push_segment(segments, TaggedLineSegment::TagStart(tag)); + self.active_tag = Some(tag); + self.detect_tag = true; + return; + } + + if let Some(tag) = self.match_close(slug) + && self.active_tag == Some(tag) + { + push_segment(segments, TaggedLineSegment::TagEnd(tag)); + self.active_tag = None; + self.detect_tag = true; + return; + } + + self.detect_tag = true; + self.push_text(line, segments); + } + + fn push_text(&self, text: String, segments: &mut Vec>) { + if let Some(tag) = self.active_tag { + push_segment(segments, TaggedLineSegment::TagDelta(tag, text)); + } else { + push_segment(segments, TaggedLineSegment::Normal(text)); + } + } + + fn is_tag_prefix(&self, slug: &str) -> bool { + let slug = slug.trim_end(); + self.specs + .iter() + .any(|spec| spec.open.starts_with(slug) || spec.close.starts_with(slug)) + } + + fn match_open(&self, slug: &str) -> Option { + self.specs + .iter() + .find(|spec| spec.open == slug) + .map(|spec| spec.tag) + } + + fn match_close(&self, slug: &str) -> Option { + self.specs + .iter() + .find(|spec| spec.close == slug) + .map(|spec| spec.tag) + } +} + +fn push_segment(segments: &mut Vec>, segment: TaggedLineSegment) +where + T: Copy + Eq, +{ + match segment { + TaggedLineSegment::Normal(delta) => { + if delta.is_empty() { + return; + } + if let Some(TaggedLineSegment::Normal(existing)) = segments.last_mut() { + existing.push_str(&delta); + return; + } + segments.push(TaggedLineSegment::Normal(delta)); + } + TaggedLineSegment::TagDelta(tag, delta) => { + if delta.is_empty() { + return; + } + if let Some(TaggedLineSegment::TagDelta(existing_tag, existing)) = segments.last_mut() + && *existing_tag == tag + { + existing.push_str(&delta); + return; + } + segments.push(TaggedLineSegment::TagDelta(tag, delta)); + } + TaggedLineSegment::TagStart(tag) => { + segments.push(TaggedLineSegment::TagStart(tag)); + } + TaggedLineSegment::TagEnd(tag) => { + segments.push(TaggedLineSegment::TagEnd(tag)); + } + } +} + +#[cfg(test)] +mod tests { + use super::TagSpec; + use super::TaggedLineParser; + use super::TaggedLineSegment; + use pretty_assertions::assert_eq; + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum Tag { + Block, + } + + fn parser() -> TaggedLineParser { + TaggedLineParser::new(vec![TagSpec { + open: "", + close: "", + tag: Tag::Block, + }]) + } + + #[test] + fn buffers_prefix_until_tag_is_decided() { + let mut parser = parser(); + let mut segments = parser.parse("\nline\n\n")); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![ + TaggedLineSegment::TagStart(Tag::Block), + TaggedLineSegment::TagDelta(Tag::Block, "line\n".to_string()), + TaggedLineSegment::TagEnd(Tag::Block), + ] + ); + } + + #[test] + fn rejects_tag_lines_with_extra_text() { + let mut parser = parser(); + let mut segments = parser.parse(" extra\n"); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![TaggedLineSegment::Normal(" extra\n".to_string())] + ); + } + + #[test] + fn closes_unterminated_tag_on_finish() { + let mut parser = parser(); + let mut segments = parser.parse("\nline\n"); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![ + TaggedLineSegment::TagStart(Tag::Block), + TaggedLineSegment::TagDelta(Tag::Block, "line\n".to_string()), + TaggedLineSegment::TagEnd(Tag::Block), + ] + ); + } + + #[test] + fn accepts_tags_with_trailing_whitespace() { + let mut parser = parser(); + let mut segments = parser.parse(" \nline\n \n"); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![ + TaggedLineSegment::TagStart(Tag::Block), + TaggedLineSegment::TagDelta(Tag::Block, "line\n".to_string()), + TaggedLineSegment::TagEnd(Tag::Block), + ] + ); + } + + #[test] + fn passes_through_plain_text() { + let mut parser = parser(); + let mut segments = parser.parse("plain text\n"); + segments.extend(parser.finish()); + + assert_eq!( + segments, + vec![TaggedLineSegment::Normal("plain text\n".to_string())] + ); + } +} diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 4305417a35..177d122554 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -67,6 +67,7 @@ impl SessionTask for UserShellCommandTask { let event = EventMsg::TurnStarted(TurnStartedEvent { model_context_window: turn_context.client.get_model_context_window(), + collaboration_mode_kind: turn_context.collaboration_mode_kind, }); let session = session.clone_session(); session.send_event(turn_context.as_ref(), event).await; diff --git a/codex-rs/core/src/tools/handlers/plan.rs b/codex-rs/core/src/tools/handlers/plan.rs index 073319bf1c..79e332a77e 100644 --- a/codex-rs/core/src/tools/handlers/plan.rs +++ b/codex-rs/core/src/tools/handlers/plan.rs @@ -10,6 +10,7 @@ use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; use crate::tools::spec::JsonSchema; use async_trait::async_trait; +use codex_protocol::config_types::ModeKind; use codex_protocol::plan_tool::UpdatePlanArgs; use codex_protocol::protocol::EventMsg; use std::collections::BTreeMap; @@ -103,6 +104,11 @@ pub(crate) async fn handle_update_plan( arguments: String, _call_id: String, ) -> Result { + if turn_context.collaboration_mode_kind == ModeKind::Plan { + return Err(FunctionCallError::RespondToModel( + "update_plan is a TODO/checklist tool and is not allowed in Plan mode".to_string(), + )); + } let args = parse_update_plan_arguments(&arguments)?; session .send_event(turn_context, EventMsg::PlanUpdate(args)) diff --git a/codex-rs/core/templates/collaboration_mode/plan.md b/codex-rs/core/templates/collaboration_mode/plan.md index cffbf16d36..395b6c368b 100644 --- a/codex-rs/core/templates/collaboration_mode/plan.md +++ b/codex-rs/core/templates/collaboration_mode/plan.md @@ -8,6 +8,12 @@ You are in **Plan Mode** until a developer message explicitly ends it. Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it. +## Plan Mode vs update_plan tool + +Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a `` block. + +Separately, `update_plan` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use `update_plan` in Plan mode, it will return an error. + ## Execution vs. mutation in Plan Mode You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions. @@ -96,6 +102,22 @@ Use the `request_user_input` tool only for decisions that materially change the Only output the final plan when it is decision complete and leaves no decisions to the implementer. +When you present the official plan, wrap it in a `` block so the client can render it specially: + +1) The opening tag must be on its own line. +2) Start the plan content on the next line (no text on the same line as the tag). +3) The closing tag must be on its own line. +4) Use Markdown inside the block. +5) Keep the tags exactly as `` and `` (do not translate or rename them), even if the plan content is in another language. + +Example: + + +# Plan title +- Step 1 +- Step 2 + + The final plan must be plan-only and include: * A clear title @@ -106,6 +128,6 @@ The final plan must be plan-only and include: * Test cases * Explicit assumptions and defaults chosen where needed -Do not ask "should I proceed?" in the final output. +Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. -Only produce the final answer when you are presenting the complete spec. +Only produce at most one `` block per turn, and only when you are presenting a complete spec. diff --git a/codex-rs/core/tests/suite/items.rs b/codex-rs/core/tests/suite/items.rs index 08ac598388..7ef73dce94 100644 --- a/codex-rs/core/tests/suite/items.rs +++ b/codex-rs/core/tests/suite/items.rs @@ -5,6 +5,10 @@ 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::user_input::ByteRange; @@ -27,6 +31,7 @@ use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; @@ -327,6 +332,268 @@ async fn agent_message_content_delta_has_item_metadata() -> anyhow::Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_mode_emits_plan_item_from_proposed_plan_block() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let TestCodex { + codex, + session_configured, + .. + } = test_codex().build(&server).await?; + + let plan_block = "\n- Step 1\n- Step 2\n\n"; + let full_message = format!("Intro\n{plan_block}Outro"); + let stream = sse(vec![ + ev_response_created("resp-1"), + ev_message_item_added("msg-1", ""), + ev_output_text_delta(&full_message), + ev_assistant_message("msg-1", &full_message), + ev_completed("resp-1"), + ]); + mount_sse_once(&server, stream).await; + + let collaboration_mode = CollaborationMode { + mode: ModeKind::Plan, + settings: Settings { + model: session_configured.model.clone(), + reasoning_effort: None, + developer_instructions: None, + }, + }; + + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "please plan".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: std::env::current_dir()?, + approval_policy: codex_core::protocol::AskForApproval::Never, + sandbox_policy: codex_core::protocol::SandboxPolicy::DangerFullAccess, + model: session_configured.model.clone(), + effort: None, + summary: codex_protocol::config_types::ReasoningSummary::Auto, + collaboration_mode: Some(collaboration_mode), + personality: None, + }) + .await?; + + let plan_delta = wait_for_event_match(&codex, |ev| match ev { + EventMsg::PlanDelta(event) => Some(event.clone()), + _ => None, + }) + .await; + + let plan_completed = wait_for_event_match(&codex, |ev| match ev { + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::Plan(item), + .. + }) => Some(item.clone()), + _ => None, + }) + .await; + + assert_eq!( + plan_delta.thread_id, + session_configured.session_id.to_string() + ); + assert_eq!(plan_delta.delta, "- Step 1\n- Step 2\n"); + assert_eq!(plan_completed.text, "- Step 1\n- Step 2\n"); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_mode_strips_plan_from_agent_messages() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let TestCodex { + codex, + session_configured, + .. + } = test_codex().build(&server).await?; + + let plan_block = "\n- Step 1\n- Step 2\n\n"; + let full_message = format!("Intro\n{plan_block}Outro"); + let stream = sse(vec![ + ev_response_created("resp-1"), + ev_message_item_added("msg-1", ""), + ev_output_text_delta(&full_message), + ev_assistant_message("msg-1", &full_message), + ev_completed("resp-1"), + ]); + mount_sse_once(&server, stream).await; + + let collaboration_mode = CollaborationMode { + mode: ModeKind::Plan, + settings: Settings { + model: session_configured.model.clone(), + reasoning_effort: None, + developer_instructions: None, + }, + }; + + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "please plan".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: std::env::current_dir()?, + approval_policy: codex_core::protocol::AskForApproval::Never, + sandbox_policy: codex_core::protocol::SandboxPolicy::DangerFullAccess, + model: session_configured.model.clone(), + effort: None, + summary: codex_protocol::config_types::ReasoningSummary::Auto, + collaboration_mode: Some(collaboration_mode), + personality: None, + }) + .await?; + + let mut agent_deltas = Vec::new(); + let mut plan_delta = None; + let mut agent_item = None; + let mut plan_item = None; + + while plan_delta.is_none() || agent_item.is_none() || plan_item.is_none() { + let ev = wait_for_event(&codex, |_| true).await; + match ev { + EventMsg::AgentMessageContentDelta(event) => { + agent_deltas.push(event.delta); + } + EventMsg::PlanDelta(event) => { + plan_delta = Some(event.delta); + } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::AgentMessage(item), + .. + }) => { + agent_item = Some(item); + } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::Plan(item), + .. + }) => { + plan_item = Some(item); + } + _ => {} + } + } + + let agent_text = agent_deltas.concat(); + assert_eq!(agent_text, "Intro\nOutro"); + assert_eq!(plan_delta.unwrap(), "- Step 1\n- Step 2\n"); + assert_eq!(plan_item.unwrap().text, "- Step 1\n- Step 2\n"); + let agent_text_from_item: String = agent_item + .unwrap() + .content + .iter() + .map(|entry| match entry { + AgentMessageContent::Text { text } => text.as_str(), + }) + .collect(); + assert_eq!(agent_text_from_item, "Intro\nOutro"); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_mode_handles_missing_plan_close_tag() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let TestCodex { + codex, + session_configured, + .. + } = test_codex().build(&server).await?; + + let full_message = "Intro\n\n- Step 1\n"; + let stream = sse(vec![ + ev_response_created("resp-1"), + ev_message_item_added("msg-1", ""), + ev_output_text_delta(full_message), + ev_assistant_message("msg-1", full_message), + ev_completed("resp-1"), + ]); + mount_sse_once(&server, stream).await; + + let collaboration_mode = CollaborationMode { + mode: ModeKind::Plan, + settings: Settings { + model: session_configured.model.clone(), + reasoning_effort: None, + developer_instructions: None, + }, + }; + + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "please plan".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: std::env::current_dir()?, + approval_policy: codex_core::protocol::AskForApproval::Never, + sandbox_policy: codex_core::protocol::SandboxPolicy::DangerFullAccess, + model: session_configured.model.clone(), + effort: None, + summary: codex_protocol::config_types::ReasoningSummary::Auto, + collaboration_mode: Some(collaboration_mode), + personality: None, + }) + .await?; + + let mut plan_delta = None; + let mut plan_item = None; + let mut agent_item = None; + + while plan_delta.is_none() || plan_item.is_none() || agent_item.is_none() { + let ev = wait_for_event(&codex, |_| true).await; + match ev { + EventMsg::PlanDelta(event) => { + plan_delta = Some(event.delta); + } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::Plan(item), + .. + }) => { + plan_item = Some(item); + } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::AgentMessage(item), + .. + }) => { + agent_item = Some(item); + } + _ => {} + } + } + + assert_eq!(plan_delta.unwrap(), "- Step 1\n"); + assert_eq!(plan_item.unwrap().text, "- Step 1\n"); + let agent_text_from_item: String = agent_item + .unwrap() + .content + .iter() + .map(|entry| match entry { + AgentMessageContent::Text { text } => text.as_str(), + }) + .collect(); + assert_eq!(agent_text_from_item, "Intro\n"); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn reasoning_content_delta_has_item_metadata() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/debug-client/src/reader.rs b/codex-rs/debug-client/src/reader.rs index 92161638ff..48841f699d 100644 --- a/codex-rs/debug-client/src/reader.rs +++ b/codex-rs/debug-client/src/reader.rs @@ -229,6 +229,11 @@ fn emit_filtered_item(item: ThreadItem, thread_id: &str, output: &Output) -> any let label = output.format_label("assistant", LabelColor::Assistant); output.server_line(&format!("{thread_label} {label}: {text}"))?; } + ThreadItem::Plan { text, .. } => { + let label = output.format_label("assistant", LabelColor::Assistant); + output.server_line(&format!("{thread_label} {label}: plan"))?; + write_multiline(output, &thread_label, &format!("{label}:"), &text)?; + } ThreadItem::CommandExecution { command, status, diff --git a/codex-rs/docs/protocol_v1.md b/codex-rs/docs/protocol_v1.md index 74b5546012..8f68ecc9a6 100644 --- a/codex-rs/docs/protocol_v1.md +++ b/codex-rs/docs/protocol_v1.md @@ -74,8 +74,11 @@ For complete documentation of the `Op` and `EventMsg` variants, refer to [protoc - `Op::UserTurn` and `Op::OverrideTurnContext` accept an optional `personality` override that updates the model’s communication style - `EventMsg` - `EventMsg::AgentMessage` – Messages from the `Model` + - `EventMsg::AgentMessageContentDelta` – Streaming assistant text + - `EventMsg::PlanDelta` – Streaming proposed plan text when the model emits a `` block in plan mode - `EventMsg::ExecApprovalRequest` – Request approval from user to execute a command - - `EventMsg::RequestUserInput` – Request user input for a tool call (questions must include options; the client always adds a free-form choice) + - `EventMsg::RequestUserInput` – Request user input for a tool call (questions can include options plus `isOther` to add a free-form choice) + - `EventMsg::TurnStarted` – Turn start metadata including `model_context_window` and `collaboration_mode_kind` - `EventMsg::TurnComplete` – A turn completed successfully - `EventMsg::Error` – A turn stopped with an error - `EventMsg::Warning` – A non-fatal warning that the client should surface to the user 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 e11e1fcadb..8469dc42ed 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -20,6 +20,7 @@ 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; @@ -33,6 +34,7 @@ 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 owo_colors::OwoColorize; use owo_colors::Style; @@ -73,6 +75,7 @@ pub(crate) struct EventProcessorWithHumanOutput { last_message_path: Option, last_total_token_usage: Option, final_message: Option, + last_proposed_plan: Option, } impl EventProcessorWithHumanOutput { @@ -99,6 +102,7 @@ impl EventProcessorWithHumanOutput { last_message_path, last_total_token_usage: None, final_message: None, + last_proposed_plan: None, } } else { Self { @@ -116,6 +120,7 @@ impl EventProcessorWithHumanOutput { last_message_path, last_total_token_usage: None, final_message: None, + last_proposed_plan: None, } } } @@ -260,12 +265,14 @@ impl EventProcessor for EventProcessorWithHumanOutput { ); } EventMsg::TurnComplete(TurnCompleteEvent { last_agent_message }) => { - let last_message = last_agent_message.as_deref(); + let last_message = last_agent_message + .as_deref() + .or(self.last_proposed_plan.as_deref()); if let Some(output_file) = self.last_message_path.as_deref() { handle_last_message(last_message, output_file); } - self.final_message = last_agent_message; + self.final_message = last_agent_message.or_else(|| self.last_proposed_plan.clone()); return CodexStatus::InitiateShutdown; } @@ -297,6 +304,12 @@ impl EventProcessor for EventProcessorWithHumanOutput { message, ); } + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::Plan(item), + .. + }) => { + self.last_proposed_plan = Some(item.text); + } EventMsg::ExecCommandBegin(ExecCommandBeginEvent { command, cwd, .. }) => { eprint!( "{}\n{} in {}", @@ -769,6 +782,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { | EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) | EventMsg::AgentMessageContentDelta(_) + | EventMsg::PlanDelta(_) | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) | EventMsg::SkillsUpdateAvailable 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 687df574d6..823fa7b810 100644 --- a/codex-rs/exec/src/event_processor_with_jsonl_output.rs +++ b/codex-rs/exec/src/event_processor_with_jsonl_output.rs @@ -58,6 +58,7 @@ use tracing::warn; pub struct EventProcessorWithJsonOutput { last_message_path: Option, + last_proposed_plan: Option, next_event_id: AtomicU64, // Tracks running commands by call_id, including the associated item id. running_commands: HashMap, @@ -102,6 +103,7 @@ impl EventProcessorWithJsonOutput { pub fn new(last_message_path: Option) -> Self { Self { last_message_path, + last_proposed_plan: None, next_event_id: AtomicU64::new(0), running_commands: HashMap::new(), running_patch_applies: HashMap::new(), @@ -119,6 +121,13 @@ impl EventProcessorWithJsonOutput { protocol::EventMsg::SessionConfigured(ev) => self.handle_session_configured(ev), protocol::EventMsg::ThreadNameUpdated(_) => Vec::new(), protocol::EventMsg::AgentMessage(ev) => self.handle_agent_message(ev), + protocol::EventMsg::ItemCompleted(protocol::ItemCompletedEvent { + item: codex_protocol::items::TurnItem::Plan(item), + .. + }) => { + self.last_proposed_plan = Some(item.text.clone()); + Vec::new() + } protocol::EventMsg::AgentReasoning(ev) => self.handle_reasoning_event(ev), protocol::EventMsg::ExecCommandBegin(ev) => self.handle_exec_command_begin(ev), protocol::EventMsg::ExecCommandEnd(ev) => self.handle_exec_command_end(ev), @@ -855,7 +864,10 @@ impl EventProcessor for EventProcessorWithJsonOutput { last_agent_message, }) => { if let Some(output_file) = self.last_message_path.as_deref() { - handle_last_message(last_agent_message.as_deref(), output_file); + let last_message = last_agent_message + .as_deref() + .or(self.last_proposed_plan.as_deref()); + handle_last_message(last_message, output_file); } CodexStatus::InitiateShutdown } 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 dc5f220fd3..e405195e7e 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -55,6 +55,7 @@ use codex_exec::exec_events::TurnStartedEvent; use codex_exec::exec_events::Usage; use codex_exec::exec_events::WebSearchItem; use codex_protocol::ThreadId; +use codex_protocol::config_types::ModeKind; use codex_protocol::models::WebSearchAction; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; @@ -117,6 +118,7 @@ fn task_started_produces_turn_started_event() { "t1", EventMsg::TurnStarted(codex_core::protocol::TurnStartedEvent { model_context_window: Some(32_000), + collaboration_mode_kind: ModeKind::Custom, }), )); diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index c96bc60706..1dbdbc767b 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -252,6 +252,9 @@ async fn run_codex_tool_session_inner( .await; continue; } + EventMsg::PlanDelta(_) => { + continue; + } EventMsg::Error(err_event) => { // Always respond in tools/call's expected shape, and include conversationId so the client can resume. let result = create_call_tool_result_with_thread_id( diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs index 86d39d6d4a..db2964c40c 100644 --- a/codex-rs/protocol/src/config_types.rs +++ b/codex-rs/protocol/src/config_types.rs @@ -166,10 +166,13 @@ pub enum AltScreenMode { } /// Initial collaboration mode to use when the TUI starts. -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, JsonSchema, TS)] +#[derive( + Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, JsonSchema, TS, Default, +)] #[serde(rename_all = "snake_case")] pub enum ModeKind { Plan, + #[default] Code, PairProgramming, Execute, diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index e7c916a61d..9a387a9d22 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -20,6 +20,7 @@ use ts_rs::TS; pub enum TurnItem { UserMessage(UserMessageItem), AgentMessage(AgentMessageItem), + Plan(PlanItem), Reasoning(ReasoningItem), WebSearch(WebSearchItem), ContextCompaction(ContextCompactionItem), @@ -44,6 +45,12 @@ pub struct AgentMessageItem { pub content: Vec, } +#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] +pub struct PlanItem { + pub id: String, + pub text: String, +} + #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ReasoningItem { pub id: String, @@ -218,6 +225,7 @@ impl TurnItem { match self { TurnItem::UserMessage(item) => item.id.clone(), TurnItem::AgentMessage(item) => item.id.clone(), + TurnItem::Plan(item) => item.id.clone(), TurnItem::Reasoning(item) => item.id.clone(), TurnItem::WebSearch(item) => item.id.clone(), TurnItem::ContextCompaction(item) => item.id.clone(), @@ -228,6 +236,7 @@ impl TurnItem { match self { TurnItem::UserMessage(item) => vec![item.as_legacy_event()], TurnItem::AgentMessage(item) => item.as_legacy_events(), + TurnItem::Plan(_) => Vec::new(), TurnItem::WebSearch(item) => vec![item.as_legacy_event()], TurnItem::Reasoning(item) => item.as_legacy_events(show_raw_agent_reasoning), TurnItem::ContextCompaction(item) => vec![item.as_legacy_event()], diff --git a/codex-rs/protocol/src/plan_tool.rs b/codex-rs/protocol/src/plan_tool.rs index a9038eb03b..affb4c1896 100644 --- a/codex-rs/protocol/src/plan_tool.rs +++ b/codex-rs/protocol/src/plan_tool.rs @@ -22,6 +22,7 @@ pub struct PlanItemArg { #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)] #[serde(deny_unknown_fields)] pub struct UpdatePlanArgs { + /// Arguments for the `update_plan` todo/checklist tool (not plan mode). #[serde(default)] pub explanation: Option, pub plan: Vec, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index fbaf4f4457..929d7d73c7 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -14,6 +14,7 @@ use std::time::Duration; use crate::ThreadId; use crate::approvals::ElicitationRequestEvent; use crate::config_types::CollaborationMode; +use crate::config_types::ModeKind; use crate::config_types::Personality; use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; use crate::config_types::WindowsSandboxLevel; @@ -838,6 +839,7 @@ pub enum EventMsg { ItemCompleted(ItemCompletedEvent), AgentMessageContentDelta(AgentMessageContentDeltaEvent), + PlanDelta(PlanDeltaEvent), ReasoningContentDelta(ReasoningContentDeltaEvent), ReasoningRawContentDelta(ReasoningRawContentDeltaEvent), @@ -1017,6 +1019,14 @@ impl HasLegacyEvent for AgentMessageContentDeltaEvent { } } +#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] +pub struct PlanDeltaEvent { + pub thread_id: String, + pub turn_id: String, + pub item_id: String, + pub delta: String, +} + #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ReasoningContentDeltaEvent { pub thread_id: String, @@ -1107,6 +1117,8 @@ pub struct TurnCompleteEvent { pub struct TurnStartedEvent { // TODO(aibrahim): make this not optional pub model_context_window: Option, + #[serde(default)] + pub collaboration_mode_kind: ModeKind, } #[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq, JsonSchema, TS)] diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 491ea3add3..7793f0a39c 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -196,6 +196,7 @@ mod skills; use self::skills::collect_tool_mentions; use self::skills::find_app_mentions; use self::skills::find_skill_mentions_with_tool_mentions; +use crate::streaming::controller::PlanStreamController; use crate::streaming::controller::StreamController; use chrono::Local; @@ -485,6 +486,8 @@ pub(crate) struct ChatWidget { rate_limit_poller: Option>, // Stream lifecycle controller stream_controller: Option, + // Stream lifecycle controller for proposed plan output. + plan_stream_controller: Option, running_commands: HashMap, suppressed_exec_calls: HashSet, skills_all: Vec, @@ -553,6 +556,12 @@ 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. + saw_plan_item_this_turn: bool, + // Incremental buffer for streamed plan content. + plan_delta_buffer: String, + // True while a plan item is streaming. + plan_item_active: bool, // Status-indicator elapsed seconds captured at the last emitted final-message separator. // // This lets the separator show per-chunk work time (since the previous separator) rather than @@ -896,7 +905,7 @@ impl ChatWidget { 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() { + if self.stream_controller.is_none() && !message.is_empty() { self.handle_streaming_delta(message); } self.flush_answer_stream_with_separator(); @@ -908,6 +917,56 @@ impl ChatWidget { self.handle_streaming_delta(delta); } + fn on_plan_delta(&mut self, delta: String) { + if self.active_mode_kind() != ModeKind::Plan { + return; + } + if !self.plan_item_active { + self.plan_item_active = true; + self.plan_delta_buffer.clear(); + } + self.plan_delta_buffer.push_str(&delta); + // Before streaming plan content, flush any active exec cell group. + self.flush_unified_exec_wait_streak(); + self.flush_active_cell(); + + if self.plan_stream_controller.is_none() { + self.plan_stream_controller = Some(PlanStreamController::new( + self.last_rendered_width.get().map(|w| w.saturating_sub(4)), + )); + } + if let Some(controller) = self.plan_stream_controller.as_mut() + && controller.push(&delta) + { + self.app_event_tx.send(AppEvent::StartCommitAnimation); + } + self.request_redraw(); + } + + fn on_plan_item_completed(&mut self, text: String) { + let streamed_plan = self.plan_delta_buffer.trim().to_string(); + let plan_text = if text.trim().is_empty() { + streamed_plan + } else { + text + }; + self.plan_delta_buffer.clear(); + self.plan_item_active = false; + self.saw_plan_item_this_turn = true; + if let Some(mut controller) = self.plan_stream_controller.take() + && let Some(cell) = controller.finalize() + { + self.add_boxed_history(cell); + // TODO: Replace streamed output with the final plan item text if plan streaming is + // removed or if we need to reconcile mismatches between streamed and final content. + return; + } + if plan_text.is_empty() { + return; + } + self.add_to_history(history_cell::new_proposed_plan(plan_text)); + } + fn on_agent_reasoning_delta(&mut self, delta: String) { // For reasoning deltas, do not stream to history. Accumulate the // current reasoning block and extract the first bold element @@ -954,6 +1013,10 @@ impl ChatWidget { fn on_task_started(&mut self) { self.agent_turn_running = true; self.saw_plan_update_this_turn = false; + self.saw_plan_item_this_turn = false; + self.plan_delta_buffer.clear(); + self.plan_item_active = false; + self.plan_stream_controller = None; self.bottom_pane.clear_quit_shortcut_hint(); self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; @@ -969,6 +1032,11 @@ impl ChatWidget { fn on_task_complete(&mut self, last_agent_message: Option, from_replay: bool) { // If a stream is currently active, finalize it. self.flush_answer_stream_with_separator(); + if let Some(mut controller) = self.plan_stream_controller.take() + && let Some(cell) = controller.finalize() + { + self.add_boxed_history(cell); + } self.flush_unified_exec_wait_streak(); // Mark task stopped and request redraw now that all content is in history. self.agent_turn_running = false; @@ -981,7 +1049,7 @@ impl ChatWidget { self.request_redraw(); if !from_replay && self.queued_user_messages.is_empty() { - self.maybe_prompt_plan_implementation(last_agent_message.as_deref()); + self.maybe_prompt_plan_implementation(); } // If there is a queued user message, send exactly one now to begin the next turn. self.maybe_send_next_queued_input(); @@ -993,7 +1061,7 @@ impl ChatWidget { self.maybe_show_pending_rate_limit_prompt(); } - fn maybe_prompt_plan_implementation(&mut self, last_agent_message: Option<&str>) { + fn maybe_prompt_plan_implementation(&mut self) { if !self.collaboration_modes_enabled() { return; } @@ -1003,8 +1071,7 @@ impl ChatWidget { if self.active_mode_kind() != ModeKind::Plan { return; } - let has_message = last_agent_message.is_some_and(|message| !message.trim().is_empty()); - if !has_message && !self.saw_plan_update_this_turn { + if !self.saw_plan_item_this_turn { return; } if !self.bottom_pane.no_modal_or_popup_active() { @@ -1749,15 +1816,28 @@ impl ChatWidget { /// Periodic tick to commit at most one queued line to history with a small delay, /// animating the output. pub(crate) fn on_commit_tick(&mut self) { + let mut has_controller = false; + let mut all_idle = true; if let Some(controller) = self.stream_controller.as_mut() { + has_controller = true; let (cell, is_idle) = controller.on_commit_tick(); if let Some(cell) = cell { self.bottom_pane.hide_status_indicator(); self.add_boxed_history(cell); } - if is_idle { - self.app_event_tx.send(AppEvent::StopCommitAnimation); + all_idle &= is_idle; + } + if let Some(controller) = self.plan_stream_controller.as_mut() { + has_controller = true; + let (cell, is_idle) = controller.on_commit_tick(); + if let Some(cell) = cell { + self.bottom_pane.hide_status_indicator(); + self.add_boxed_history(cell); } + all_idle &= is_idle; + } + if has_controller && all_idle { + self.app_event_tx.send(AppEvent::StopCommitAnimation); } } @@ -2160,6 +2240,7 @@ impl ChatWidget { rate_limit_switch_prompt: RateLimitSwitchPromptState::default(), rate_limit_poller: None, stream_controller: None, + plan_stream_controller: None, running_commands: HashMap::new(), suppressed_exec_calls: HashSet::new(), last_unified_wait: None, @@ -2188,6 +2269,9 @@ impl ChatWidget { needs_final_message_separator: false, had_work_activity: false, saw_plan_update_this_turn: false, + saw_plan_item_this_turn: false, + plan_delta_buffer: String::new(), + plan_item_active: false, last_separator_elapsed_secs: None, last_rendered_width: std::cell::Cell::new(None), feedback, @@ -2301,6 +2385,7 @@ impl ChatWidget { rate_limit_switch_prompt: RateLimitSwitchPromptState::default(), rate_limit_poller: None, stream_controller: None, + plan_stream_controller: None, running_commands: HashMap::new(), suppressed_exec_calls: HashSet::new(), last_unified_wait: None, @@ -2319,6 +2404,9 @@ impl ChatWidget { thread_name: None, forked_from: None, saw_plan_update_this_turn: false, + saw_plan_item_this_turn: false, + plan_delta_buffer: String::new(), + plan_item_active: false, queued_user_messages: VecDeque::new(), show_welcome_banner: is_first_run, suppress_session_configured_redraw: false, @@ -2431,6 +2519,7 @@ impl ChatWidget { rate_limit_switch_prompt: RateLimitSwitchPromptState::default(), rate_limit_poller: None, stream_controller: None, + plan_stream_controller: None, running_commands: HashMap::new(), suppressed_exec_calls: HashSet::new(), last_unified_wait: None, @@ -2459,6 +2548,9 @@ impl ChatWidget { needs_final_message_separator: false, had_work_activity: false, saw_plan_update_this_turn: false, + saw_plan_item_this_turn: false, + plan_delta_buffer: String::new(), + plan_item_active: false, last_separator_elapsed_secs: None, last_rendered_width: std::cell::Cell::new(None), feedback, @@ -3219,6 +3311,7 @@ impl ChatWidget { match msg { EventMsg::AgentMessageDelta(_) + | EventMsg::PlanDelta(_) | EventMsg::AgentReasoningDelta(_) | EventMsg::TerminalInteraction(_) | EventMsg::ExecCommandOutputDelta(_) => {} @@ -3234,6 +3327,7 @@ impl ChatWidget { EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta }) => { self.on_agent_message_delta(delta) } + EventMsg::PlanDelta(event) => self.on_plan_delta(event.delta), EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { delta }) | EventMsg::AgentReasoningRawContentDelta(AgentReasoningRawContentDeltaEvent { delta, @@ -3357,11 +3451,15 @@ impl ChatWidget { EventMsg::ThreadRolledBack(_) => {} EventMsg::RawResponseItem(_) | EventMsg::ItemStarted(_) - | EventMsg::ItemCompleted(_) | EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) | EventMsg::DynamicToolCallRequest(_) => {} + EventMsg::ItemCompleted(event) => { + if let codex_protocol::items::TurnItem::Plan(plan_item) = event.item { + self.on_plan_item_completed(plan_item.text); + } + } } } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 331afdf90a..d24504578c 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -809,6 +809,7 @@ async fn make_chatwidget_manual( rate_limit_switch_prompt: RateLimitSwitchPromptState::default(), rate_limit_poller: None, stream_controller: None, + plan_stream_controller: None, running_commands: HashMap::new(), suppressed_exec_calls: HashSet::new(), skills_all: Vec::new(), @@ -840,6 +841,9 @@ async fn make_chatwidget_manual( needs_final_message_separator: false, had_work_activity: false, saw_plan_update_this_turn: false, + saw_plan_item_this_turn: false, + plan_delta_buffer: String::new(), + plan_item_active: false, last_separator_elapsed_secs: None, last_rendered_width: std::cell::Cell::new(None), feedback: codex_feedback::CodexFeedback::new(), @@ -1277,7 +1281,7 @@ async fn plan_implementation_popup_skips_when_messages_queued() { } #[tokio::test] -async fn plan_implementation_popup_shows_on_plan_update_without_message() { +async fn plan_implementation_popup_skips_without_proposed_plan() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await; chat.set_feature_enabled(Feature::CollaborationModes, true); let plan_mask = @@ -1295,10 +1299,31 @@ async fn plan_implementation_popup_shows_on_plan_update_without_message() { }); chat.on_task_complete(None, false); + let popup = render_bottom_popup(&chat, 80); + assert!( + !popup.contains(PLAN_IMPLEMENTATION_TITLE), + "expected no plan popup without proposed plan output, got {popup:?}" + ); +} + +#[tokio::test] +async fn plan_implementation_popup_shows_after_proposed_plan_output() { + let (mut chat, _rx, _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.on_task_started(); + chat.on_plan_delta("- Step 1\n- Step 2\n".to_string()); + chat.on_plan_item_completed("- Step 1\n- Step 2\n".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 plan update, got {popup:?}" + "expected plan popup after proposed plan output, got {popup:?}" ); } @@ -1957,6 +1982,7 @@ async fn unified_exec_wait_after_final_agent_message_snapshot() { id: "turn-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); @@ -1991,6 +2017,7 @@ async fn unified_exec_wait_before_streamed_agent_message_snapshot() { id: "turn-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); @@ -2779,6 +2806,7 @@ async fn interrupted_turn_error_message_snapshot() { id: "task-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); @@ -3793,6 +3821,7 @@ async fn interrupt_clears_unified_exec_wait_streak_snapshot() { id: "turn-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); @@ -3866,6 +3895,7 @@ async fn ui_snapshots_small_heights_task_running() { id: "task-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); chat.handle_codex_event(Event { @@ -3897,6 +3927,7 @@ async fn status_widget_and_approval_modal_snapshot() { id: "task-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); // Provide a deterministic header for the status line. @@ -3949,6 +3980,7 @@ async fn status_widget_active_snapshot() { id: "task-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); // Provide a deterministic header via a bold reasoning chunk. @@ -3998,6 +4030,7 @@ async fn mcp_startup_complete_does_not_clear_running_task() { id: "task-1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); @@ -4554,6 +4587,7 @@ async fn stream_recovery_restores_previous_status_header() { id: "task".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); drain_insert_history(&mut rx); @@ -4591,6 +4625,7 @@ async fn multiple_agent_messages_in_single_turn_emit_multiple_headers() { id: "s1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); @@ -4785,6 +4820,7 @@ async fn chatwidget_exec_and_status_layout_vt100_snapshot() { id: "t1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); chat.handle_codex_event(Event { @@ -4832,6 +4868,7 @@ async fn chatwidget_markdown_code_blocks_vt100_snapshot() { id: "t1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); // Build a vt100 visual from the history insertions only (no UI overlay) @@ -4921,6 +4958,7 @@ async fn chatwidget_tall() { id: "t1".into(), msg: EventMsg::TurnStarted(TurnStartedEvent { model_context_window: None, + collaboration_mode_kind: ModeKind::Custom, }), }); for i in 0..30 { diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 1f19c929a2..aadfb318f8 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -25,6 +25,7 @@ use crate::render::line_utils::line_to_static; use crate::render::line_utils::prefix_lines; use crate::render::line_utils::push_owned_lines; use crate::render::renderable::Renderable; +use crate::style::proposed_plan_style; use crate::style::user_message_style; use crate::text_formatting::format_and_truncate_tool_result; use crate::text_formatting::truncate_text; @@ -1768,6 +1769,63 @@ pub(crate) fn new_plan_update(update: UpdatePlanArgs) -> PlanUpdateCell { PlanUpdateCell { explanation, plan } } +pub(crate) fn new_proposed_plan(plan_markdown: String) -> ProposedPlanCell { + ProposedPlanCell { plan_markdown } +} + +pub(crate) fn new_proposed_plan_stream( + lines: Vec>, + is_stream_continuation: bool, +) -> ProposedPlanStreamCell { + ProposedPlanStreamCell { + lines, + is_stream_continuation, + } +} + +#[derive(Debug)] +pub(crate) struct ProposedPlanCell { + plan_markdown: String, +} + +#[derive(Debug)] +pub(crate) struct ProposedPlanStreamCell { + lines: Vec>, + is_stream_continuation: bool, +} + +impl HistoryCell for ProposedPlanCell { + fn display_lines(&self, width: u16) -> Vec> { + let mut lines: Vec> = Vec::new(); + lines.push(vec!["• ".dim(), "Proposed Plan".bold()].into()); + lines.push(Line::from(" ")); + + let mut plan_lines: Vec> = vec![Line::from(" ")]; + let plan_style = proposed_plan_style(); + let wrap_width = width.saturating_sub(4).max(1) as usize; + let mut body: Vec> = Vec::new(); + append_markdown(&self.plan_markdown, Some(wrap_width), &mut body); + if body.is_empty() { + body.push(Line::from("(empty)".dim().italic())); + } + plan_lines.extend(prefix_lines(body, " ".into(), " ".into())); + plan_lines.push(Line::from(" ")); + + lines.extend(plan_lines.into_iter().map(|line| line.style(plan_style))); + lines + } +} + +impl HistoryCell for ProposedPlanStreamCell { + fn display_lines(&self, _width: u16) -> Vec> { + self.lines.clone() + } + + fn is_stream_continuation(&self) -> bool { + self.is_stream_continuation + } +} + #[derive(Debug)] pub(crate) struct PlanUpdateCell { explanation: Option, diff --git a/codex-rs/tui/src/streaming/controller.rs b/codex-rs/tui/src/streaming/controller.rs index e73ebd41e6..462962e980 100644 --- a/codex-rs/tui/src/streaming/controller.rs +++ b/codex-rs/tui/src/streaming/controller.rs @@ -1,5 +1,8 @@ use crate::history_cell::HistoryCell; use crate::history_cell::{self}; +use crate::render::line_utils::prefix_lines; +use crate::style::proposed_plan_style; +use ratatui::prelude::Stylize; use ratatui::text::Line; use super::StreamState; @@ -80,6 +83,106 @@ impl StreamController { } } +/// Controller that streams proposed plan markdown into a styled plan block. +pub(crate) struct PlanStreamController { + state: StreamState, + header_emitted: bool, + top_padding_emitted: bool, +} + +impl PlanStreamController { + pub(crate) fn new(width: Option) -> Self { + Self { + state: StreamState::new(width), + header_emitted: false, + top_padding_emitted: false, + } + } + + /// Push a delta; if it contains a newline, commit completed lines and start animation. + pub(crate) fn push(&mut self, delta: &str) -> bool { + let state = &mut self.state; + if !delta.is_empty() { + state.has_seen_delta = true; + } + state.collector.push_delta(delta); + if delta.contains('\n') { + let newly_completed = state.collector.commit_complete_lines(); + if !newly_completed.is_empty() { + state.enqueue(newly_completed); + return true; + } + } + false + } + + /// Finalize the active stream. Drain and emit now. + pub(crate) fn finalize(&mut self) -> Option> { + let remaining = { + let state = &mut self.state; + state.collector.finalize_and_drain() + }; + let mut out_lines = Vec::new(); + { + let state = &mut self.state; + if !remaining.is_empty() { + state.enqueue(remaining); + } + let step = state.drain_all(); + out_lines.extend(step); + } + + self.state.clear(); + self.emit(out_lines, true) + } + + /// Step animation: commit at most one queued line and handle end-of-drain cleanup. + pub(crate) fn on_commit_tick(&mut self) -> (Option>, bool) { + let step = self.state.step(); + (self.emit(step, false), self.state.is_idle()) + } + + fn emit( + &mut self, + lines: Vec>, + include_bottom_padding: bool, + ) -> Option> { + if lines.is_empty() && !include_bottom_padding { + return None; + } + + let mut out_lines: Vec> = Vec::new(); + let is_stream_continuation = self.header_emitted; + if !self.header_emitted { + out_lines.push(vec!["• ".dim(), "Proposed Plan".bold()].into()); + out_lines.push(Line::from(" ")); + self.header_emitted = true; + } + + let mut plan_lines: Vec> = Vec::new(); + if !self.top_padding_emitted { + plan_lines.push(Line::from(" ")); + self.top_padding_emitted = true; + } + plan_lines.extend(lines); + if include_bottom_padding { + plan_lines.push(Line::from(" ")); + } + + let plan_style = proposed_plan_style(); + let plan_lines = prefix_lines(plan_lines, " ".into(), " ".into()) + .into_iter() + .map(|line| line.style(plan_style)) + .collect::>(); + out_lines.extend(plan_lines); + + Some(Box::new(history_cell::new_proposed_plan_stream( + out_lines, + is_stream_continuation, + ))) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/codex-rs/tui/src/style.rs b/codex-rs/tui/src/style.rs index 26a71bd897..2b4ab4c4d3 100644 --- a/codex-rs/tui/src/style.rs +++ b/codex-rs/tui/src/style.rs @@ -9,6 +9,10 @@ pub fn user_message_style() -> Style { user_message_style_for(default_bg()) } +pub fn proposed_plan_style() -> Style { + proposed_plan_style_for(default_bg()) +} + /// Returns the style for a user-authored message using the provided terminal background. pub fn user_message_style_for(terminal_bg: Option<(u8, u8, u8)>) -> Style { match terminal_bg { @@ -17,6 +21,13 @@ pub fn user_message_style_for(terminal_bg: Option<(u8, u8, u8)>) -> Style { } } +pub fn proposed_plan_style_for(terminal_bg: Option<(u8, u8, u8)>) -> Style { + match terminal_bg { + Some(bg) => Style::default().bg(proposed_plan_bg(bg)), + None => Style::default(), + } +} + #[allow(clippy::disallowed_methods)] pub fn user_message_bg(terminal_bg: (u8, u8, u8)) -> Color { let (top, alpha) = if is_light(terminal_bg) { @@ -26,3 +37,13 @@ pub fn user_message_bg(terminal_bg: (u8, u8, u8)) -> Color { }; best_color(blend(top, terminal_bg, alpha)) } + +#[allow(clippy::disallowed_methods)] +pub fn proposed_plan_bg(terminal_bg: (u8, u8, u8)) -> Color { + let (top, alpha) = if is_light(terminal_bg) { + ((0, 110, 150), 0.08) + } else { + ((80, 170, 220), 0.2) + }; + best_color(blend(top, terminal_bg, alpha)) +} From 2d10aa68598591bf6e4eb2261cfe534852dd8d9a Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Fri, 30 Jan 2026 11:15:21 -0800 Subject: [PATCH 113/116] Tui: hide Code mode footer label (#10063) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Title Hide Code mode footer label/cycle hint; add Plan footer-collapse snapshots Summary - Keep Code mode internal naming but suppress the footer mode label + cycle hint when Code is active. - Only show the cycle hint when a non‑Code mode indicator is present. - Add Plan-mode footer collapse snapshot coverage (empty + queued, across widths) and update existing footer collapse snapshots for the new Code behavior. Notes - The test run currently fails in codex-cloud-requirements on origin/main due to a stale auth.mode field; no fix is included in this PR to keep the diff minimal. Codex author `codex resume 019c0296-cfd4-7193-9b0a-6949048e4546` --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 118 ++++++++++++++++-- codex-rs/tui/src/bottom_pane/footer.rs | 9 +- ...er__tests__footer_collapse_empty_full.snap | 2 +- ...ollapse_empty_mode_cycle_with_context.snap | 2 +- ...apse_empty_mode_cycle_without_context.snap | 2 +- ...ests__footer_collapse_empty_mode_only.snap | 2 +- ...ests__footer_collapse_plan_empty_full.snap | 13 ++ ...se_plan_empty_mode_cycle_with_context.snap | 13 ++ ...plan_empty_mode_cycle_without_context.snap | 13 ++ ..._footer_collapse_plan_empty_mode_only.snap | 13 ++ ...ests__footer_collapse_plan_queue_full.snap | 13 ++ ...se_plan_queue_message_without_context.snap | 13 ++ ..._footer_collapse_plan_queue_mode_only.snap | 13 ++ ...ollapse_plan_queue_short_with_context.snap | 13 ++ ...apse_plan_queue_short_without_context.snap | 13 ++ ...er__tests__footer_collapse_queue_full.snap | 2 +- ...ollapse_queue_message_without_context.snap | 2 +- ...ests__footer_collapse_queue_mode_only.snap | 2 +- ...ter_collapse_queue_short_with_context.snap | 2 +- ..._collapse_queue_short_without_context.snap | 2 +- codex-rs/tui/src/chatwidget.rs | 2 +- 21 files changed, 237 insertions(+), 27 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_full.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_with_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_without_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_only.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_full.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_message_without_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_mode_only.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_with_context.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_without_context.snap diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 7c8b7585ac..1d3cf942fb 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -2873,7 +2873,8 @@ impl ChatComposer { } ActivePopup::None => { let footer_props = self.footer_props(); - let show_cycle_hint = !footer_props.is_task_running; + let show_cycle_hint = + !footer_props.is_task_running && self.collaboration_mode_indicator.is_some(); let show_shortcuts_hint = match footer_props.mode { FooterMode::ComposerEmpty => !self.is_in_paste_burst(), FooterMode::QuitShortcutReminder @@ -3353,23 +3354,23 @@ mod tests { fn setup_collab_footer( composer: &mut ChatComposer, context_percent: i64, - indicator: CollaborationModeIndicator, + indicator: Option, ) { composer.set_collaboration_modes_enabled(true); - composer.set_collaboration_mode_indicator(Some(indicator)); + composer.set_collaboration_mode_indicator(indicator); composer.set_context_window(Some(context_percent), None); } - // Empty textarea, agent idle: shortcuts hint can show, and cycle hint is available. + // Empty textarea, agent idle: shortcuts hint can show, and cycle hint is hidden. snapshot_composer_state_with_width("footer_collapse_empty_full", 120, true, |composer| { - setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 100, None); }); snapshot_composer_state_with_width( "footer_collapse_empty_mode_cycle_with_context", 60, true, |composer| { - setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 100, None); }, ); snapshot_composer_state_with_width( @@ -3377,7 +3378,7 @@ mod tests { 44, true, |composer| { - setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 100, None); }, ); snapshot_composer_state_with_width( @@ -3385,13 +3386,47 @@ mod tests { 26, true, |composer| { - setup_collab_footer(composer, 100, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 100, None); + }, + ); + + // Empty textarea, plan mode idle: shortcuts hint and cycle hint are available. + snapshot_composer_state_with_width( + "footer_collapse_plan_empty_full", + 120, + true, + |composer| { + setup_collab_footer(composer, 100, Some(CollaborationModeIndicator::Plan)); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_plan_empty_mode_cycle_with_context", + 60, + true, + |composer| { + setup_collab_footer(composer, 100, Some(CollaborationModeIndicator::Plan)); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_plan_empty_mode_cycle_without_context", + 44, + true, + |composer| { + setup_collab_footer(composer, 100, Some(CollaborationModeIndicator::Plan)); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_plan_empty_mode_only", + 26, + true, + |composer| { + setup_collab_footer(composer, 100, Some(CollaborationModeIndicator::Plan)); }, ); // Textarea has content, agent running, steer enabled: queue hint is shown. snapshot_composer_state_with_width("footer_collapse_queue_full", 120, true, |composer| { - setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 98, None); composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); @@ -3401,7 +3436,7 @@ mod tests { 50, true, |composer| { - setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 98, None); composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); @@ -3412,7 +3447,7 @@ mod tests { 40, true, |composer| { - setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 98, None); composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); @@ -3423,7 +3458,7 @@ mod tests { 30, true, |composer| { - setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 98, None); composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); @@ -3434,7 +3469,64 @@ mod tests { 20, true, |composer| { - setup_collab_footer(composer, 98, CollaborationModeIndicator::Code); + setup_collab_footer(composer, 98, None); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + + // Textarea has content, plan mode active, agent running, steer enabled: queue hint + mode. + snapshot_composer_state_with_width( + "footer_collapse_plan_queue_full", + 120, + true, + |composer| { + setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_plan_queue_short_with_context", + 50, + true, + |composer| { + setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_plan_queue_message_without_context", + 40, + true, + |composer| { + setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_plan_queue_short_without_context", + 30, + true, + |composer| { + setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); + composer.set_steer_enabled(true); + composer.set_task_running(true); + composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); + }, + ); + snapshot_composer_state_with_width( + "footer_collapse_plan_queue_mode_only", + 20, + true, + |composer| { + setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); diff --git a/codex-rs/tui/src/bottom_pane/footer.rs b/codex-rs/tui/src/bottom_pane/footer.rs index 1ded8ce319..c297b9e362 100644 --- a/codex-rs/tui/src/bottom_pane/footer.rs +++ b/codex-rs/tui/src/bottom_pane/footer.rs @@ -73,12 +73,12 @@ pub(crate) struct FooterProps { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum CollaborationModeIndicator { Plan, - Code, PairProgramming, Execute, } const MODE_CYCLE_HINT: &str = "shift+tab to cycle"; +const FOOTER_CONTEXT_GAP_COLS: u16 = 1; impl CollaborationModeIndicator { fn label(self, show_cycle_hint: bool) -> String { @@ -89,7 +89,6 @@ impl CollaborationModeIndicator { }; match self { CollaborationModeIndicator::Plan => format!("Plan mode{suffix}"), - CollaborationModeIndicator::Code => format!("Code mode{suffix}"), CollaborationModeIndicator::PairProgramming => { format!("Pair Programming mode{suffix}") } @@ -101,7 +100,6 @@ impl CollaborationModeIndicator { let label = self.label(show_cycle_hint); match self { CollaborationModeIndicator::Plan => Span::from(label).magenta(), - CollaborationModeIndicator::Code => Span::from(label).dim(), CollaborationModeIndicator::PairProgramming => Span::from(label).cyan(), CollaborationModeIndicator::Execute => Span::from(label).dim(), } @@ -475,7 +473,10 @@ pub(crate) fn can_show_left_with_context(area: Rect, left_width: u16, context_wi let Some(context_x) = right_aligned_x(area, context_width) else { return true; }; - let left_extent = FOOTER_INDENT_COLS as u16 + left_width; + if left_width == 0 { + return true; + } + let left_extent = FOOTER_INDENT_COLS as u16 + left_width + FOOTER_CONTEXT_GAP_COLS; left_extent <= context_x.saturating_sub(area.x) } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap index 90a7b12e4a..4324d806e2 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_full.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" ? for shortcuts · Code mode (shift+tab to cycle) 100% context left " +" ? for shortcuts 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap index cfc93be1e6..ecaeb58149 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_with_context.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" Code mode (shift+tab to cycle) 100% context left " +" ? for shortcuts 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap index 9901a8fbbf..118ac25291 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_cycle_without_context.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" Code mode (shift+tab to cycle) " +" ? for shortcuts 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap index 98c7c33889..9c95004785 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_empty_mode_only.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" Code mode " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_full.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_full.snap new file mode 100644 index 0000000000..f39aefad64 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_full.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anything " +" " +" " +" " +" " +" " +" " +" ? for shortcuts · Plan mode (shift+tab to cycle) 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_with_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_with_context.snap new file mode 100644 index 0000000000..347ba31648 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_with_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anything " +" " +" " +" " +" " +" " +" " +" Plan mode (shift+tab to cycle) 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_without_context.snap new file mode 100644 index 0000000000..006e2a1773 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_cycle_without_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anything " +" " +" " +" " +" " +" " +" " +" Plan mode (shift+tab to cycle) " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_only.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_only.snap new file mode 100644 index 0000000000..bea268c57e --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_empty_mode_only.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Ask Codex to do anythin " +" " +" " +" " +" " +" " +" " +" Plan mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_full.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_full.snap new file mode 100644 index 0000000000..5f0f353822 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_full.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue message · Plan mode 98% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_message_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_message_without_context.snap new file mode 100644 index 0000000000..017e3eb2aa --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_message_without_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue message · Plan mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_mode_only.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_mode_only.snap new file mode 100644 index 0000000000..35a94ac73a --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_mode_only.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" Plan mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_with_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_with_context.snap new file mode 100644 index 0000000000..77f38dc4e7 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_with_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue · Plan mode 98% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_without_context.snap new file mode 100644 index 0000000000..91f917e987 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_plan_queue_short_without_context.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› Test " +" " +" " +" " +" " +" " +" " +" tab to queue · Plan mode " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap index cfb47fa9d7..1057803326 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_full.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" tab to queue message · Code mode 98% context left " +" tab to queue message 98% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap index 0a91488b58..4f44c0424e 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_message_without_context.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" tab to queue message · Code mode " +" tab to queue 98% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap index 9adcc6e059..e2d1d2e282 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_mode_only.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" Code mode " +" tab to queue " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap index 0910602616..b7128fd415 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_with_context.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" tab to queue · Code mode 98% context left " +" tab to queue message 98% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap index 993dc34035..3df7f74328 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_collapse_queue_short_without_context.snap @@ -10,4 +10,4 @@ expression: terminal.backend() " " " " " " -" tab to queue · Code mode " +" tab to queue message " diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 7793f0a39c..b0c8c7cf33 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -5313,7 +5313,7 @@ impl ChatWidget { } match self.active_mode_kind() { ModeKind::Plan => Some(CollaborationModeIndicator::Plan), - ModeKind::Code => Some(CollaborationModeIndicator::Code), + ModeKind::Code => None, ModeKind::PairProgramming => Some(CollaborationModeIndicator::PairProgramming), ModeKind::Execute => Some(CollaborationModeIndicator::Execute), ModeKind::Custom => None, From e6d913af2dc5ace19c06d5ae6a35c34cff996a1c Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 30 Jan 2026 11:18:39 -0800 Subject: [PATCH 114/116] chore: rename ChatGpt -> Chatgpt in type names (#10244) When using ChatGPT in names of types, we should be consistent, so this renames some types with `ChatGpt` in the name to `Chatgpt`. From https://rust-lang.github.io/api-guidelines/naming.html: > In `UpperCamelCase`, acronyms and contractions of compound words count as one word: use `Uuid` rather than `UUID`, `Usize` rather than `USize` or `Stdin` rather than `StdIn`. In `snake_case`, acronyms and contractions are lower-cased: `is_xid_start`. This PR updates existing uses of `ChatGpt` and changes them to `Chatgpt`. Though in all cases where it could affect the wire format, I visually inspected that we don't change anything there. That said, this _will_ change the codegen because it will affect the spelling of type names. For example, this renames `AuthMode::ChatGPT` to `AuthMode::Chatgpt` in `app-server-protocol`, but the wire format is still `"chatgpt"`. This PR also updates a number of types in `codex-rs/core/src/auth.rs`. --- .../src/protocol/common.rs | 2 +- .../app-server/src/codex_message_processor.rs | 2 +- .../app-server/tests/common/auth_fixtures.rs | 2 +- codex-rs/cli/src/login.rs | 2 +- codex-rs/core/src/auth.rs | 66 +++++++++---------- codex-rs/core/src/auth/storage.rs | 2 +- codex-rs/core/src/codex.rs | 2 +- codex-rs/core/src/model_provider_info.rs | 2 +- codex-rs/core/src/models_manager/manager.rs | 2 +- codex-rs/core/tests/responses_headers.rs | 4 +- codex-rs/core/tests/suite/auth_refresh.rs | 18 ++--- codex-rs/login/src/server.rs | 2 +- codex-rs/tui/src/onboarding/auth.rs | 2 +- codex-rs/tui/src/status/helpers.rs | 2 +- 14 files changed, 55 insertions(+), 55 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index efcc651b33..eb59480b58 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -30,7 +30,7 @@ pub enum AuthMode { /// OpenAI API key provided by the caller and stored by Codex. ApiKey, /// ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex). - ChatGPT, + Chatgpt, /// [UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. /// /// ChatGPT auth tokens are supplied by an external host app and are only diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index c02f3c7368..78f670c049 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1246,7 +1246,7 @@ impl CodexMessageProcessor { let account = match self.auth_manager.auth_cached() { Some(auth) => Some(match auth { CodexAuth::ApiKey(_) => Account::ApiKey {}, - CodexAuth::ChatGpt(_) | CodexAuth::ChatGptAuthTokens(_) => { + CodexAuth::Chatgpt(_) | CodexAuth::ChatgptAuthTokens(_) => { let email = auth.get_account_email(); let plan_type = auth.account_plan_type(); diff --git a/codex-rs/app-server/tests/common/auth_fixtures.rs b/codex-rs/app-server/tests/common/auth_fixtures.rs index b78d5b105d..e689e41838 100644 --- a/codex-rs/app-server/tests/common/auth_fixtures.rs +++ b/codex-rs/app-server/tests/common/auth_fixtures.rs @@ -159,7 +159,7 @@ pub fn write_chatgpt_auth( let last_refresh = fixture.last_refresh.unwrap_or_else(|| Some(Utc::now())); let auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(tokens), last_refresh, diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index cee002f339..01a830acb2 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -236,7 +236,7 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! { std::process::exit(1); } }, - AuthMode::ChatGPT => { + AuthMode::Chatgpt => { eprintln!("Logged in using ChatGPT"); std::process::exit(0); } diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index 4bddbe3031..fb4114a7c2 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -44,15 +44,15 @@ use thiserror::Error; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AuthMode { ApiKey, - ChatGPT, + Chatgpt, } /// Authentication mechanism used by the current user. #[derive(Debug, Clone)] pub enum CodexAuth { ApiKey(ApiKeyAuth), - ChatGpt(ChatGptAuth), - ChatGptAuthTokens(ChatGptAuthTokens), + Chatgpt(ChatgptAuth), + ChatgptAuthTokens(ChatgptAuthTokens), } #[derive(Debug, Clone)] @@ -61,18 +61,18 @@ pub struct ApiKeyAuth { } #[derive(Debug, Clone)] -pub struct ChatGptAuth { - state: ChatGptAuthState, +pub struct ChatgptAuth { + state: ChatgptAuthState, storage: Arc, } #[derive(Debug, Clone)] -pub struct ChatGptAuthTokens { - state: ChatGptAuthState, +pub struct ChatgptAuthTokens { + state: ChatgptAuthState, } #[derive(Debug, Clone)] -struct ChatGptAuthState { +struct ChatgptAuthState { auth_dot_json: Arc>>, client: CodexHttpClient, } @@ -161,18 +161,18 @@ impl CodexAuth { } let storage_mode = auth_dot_json.storage_mode(auth_credentials_store_mode); - let state = ChatGptAuthState { + let state = ChatgptAuthState { auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), client, }; match auth_mode { - ApiAuthMode::ChatGPT => { + ApiAuthMode::Chatgpt => { let storage = create_auth_storage(codex_home.to_path_buf(), storage_mode); - Ok(Self::ChatGpt(ChatGptAuth { state, storage })) + Ok(Self::Chatgpt(ChatgptAuth { state, storage })) } ApiAuthMode::ChatgptAuthTokens => { - Ok(Self::ChatGptAuthTokens(ChatGptAuthTokens { state })) + Ok(Self::ChatgptAuthTokens(ChatgptAuthTokens { state })) } ApiAuthMode::ApiKey => unreachable!("api key mode is handled above"), } @@ -189,31 +189,31 @@ impl CodexAuth { pub fn internal_auth_mode(&self) -> AuthMode { match self { Self::ApiKey(_) => AuthMode::ApiKey, - Self::ChatGpt(_) | Self::ChatGptAuthTokens(_) => AuthMode::ChatGPT, + Self::Chatgpt(_) | Self::ChatgptAuthTokens(_) => AuthMode::Chatgpt, } } pub fn api_auth_mode(&self) -> ApiAuthMode { match self { Self::ApiKey(_) => ApiAuthMode::ApiKey, - Self::ChatGpt(_) => ApiAuthMode::ChatGPT, - Self::ChatGptAuthTokens(_) => ApiAuthMode::ChatgptAuthTokens, + Self::Chatgpt(_) => ApiAuthMode::Chatgpt, + Self::ChatgptAuthTokens(_) => ApiAuthMode::ChatgptAuthTokens, } } pub fn is_chatgpt_auth(&self) -> bool { - self.internal_auth_mode() == AuthMode::ChatGPT + self.internal_auth_mode() == AuthMode::Chatgpt } pub fn is_external_chatgpt_tokens(&self) -> bool { - matches!(self, Self::ChatGptAuthTokens(_)) + matches!(self, Self::ChatgptAuthTokens(_)) } /// Returns `None` is `is_internal_auth_mode() != AuthMode::ApiKey`. pub fn api_key(&self) -> Option<&str> { match self { Self::ApiKey(auth) => Some(auth.api_key.as_str()), - Self::ChatGpt(_) | Self::ChatGptAuthTokens(_) => None, + Self::Chatgpt(_) | Self::ChatgptAuthTokens(_) => None, } } @@ -234,7 +234,7 @@ impl CodexAuth { pub fn get_token(&self) -> Result { match self { Self::ApiKey(auth) => Ok(auth.api_key.clone()), - Self::ChatGpt(_) | Self::ChatGptAuthTokens(_) => { + Self::Chatgpt(_) | Self::ChatgptAuthTokens(_) => { let access_token = self.get_token_data()?.access_token; Ok(access_token) } @@ -278,8 +278,8 @@ impl CodexAuth { /// Returns `None` if `is_chatgpt_auth()` is false. fn get_current_auth_json(&self) -> Option { let state = match self { - Self::ChatGpt(auth) => &auth.state, - Self::ChatGptAuthTokens(auth) => &auth.state, + Self::Chatgpt(auth) => &auth.state, + Self::ChatgptAuthTokens(auth) => &auth.state, Self::ApiKey(_) => return None, }; #[expect(clippy::unwrap_used)] @@ -294,7 +294,7 @@ impl CodexAuth { /// Consider this private to integration tests. pub fn create_dummy_chatgpt_auth_for_testing() -> Self { let auth_dot_json = AuthDotJson { - auth_mode: Some(ApiAuthMode::ChatGPT), + auth_mode: Some(ApiAuthMode::Chatgpt), openai_api_key: None, tokens: Some(TokenData { id_token: Default::default(), @@ -306,12 +306,12 @@ impl CodexAuth { }; let client = crate::default_client::create_client(); - let state = ChatGptAuthState { + let state = ChatgptAuthState { auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), client, }; let storage = create_auth_storage(PathBuf::new(), AuthCredentialsStoreMode::File); - Self::ChatGpt(ChatGptAuth { state, storage }) + Self::Chatgpt(ChatgptAuth { state, storage }) } fn from_api_key_with_client(api_key: &str, _client: CodexHttpClient) -> Self { @@ -325,7 +325,7 @@ impl CodexAuth { } } -impl ChatGptAuth { +impl ChatgptAuth { fn current_auth_json(&self) -> Option { #[expect(clippy::unwrap_used)] self.state.auth_dot_json.lock().unwrap().clone() @@ -436,8 +436,8 @@ pub fn enforce_login_restrictions(config: &Config) -> std::io::Result<()> { if let Some(required_method) = config.forced_login_method { let method_violation = match (required_method, auth.internal_auth_mode()) { (ForcedLoginMethod::Api, AuthMode::ApiKey) => None, - (ForcedLoginMethod::Chatgpt, AuthMode::ChatGPT) => None, - (ForcedLoginMethod::Api, AuthMode::ChatGPT) => Some( + (ForcedLoginMethod::Chatgpt, AuthMode::Chatgpt) => None, + (ForcedLoginMethod::Api, AuthMode::Chatgpt) => Some( "API key login is required, but ChatGPT is currently being used. Logging out." .to_string(), ), @@ -750,7 +750,7 @@ impl AuthDotJson { if self.openai_api_key.is_some() { return ApiAuthMode::ApiKey; } - ApiAuthMode::ChatGPT + ApiAuthMode::Chatgpt } fn storage_mode( @@ -1127,11 +1127,11 @@ impl AuthManager { None => return Ok(()), }; match auth { - CodexAuth::ChatGptAuthTokens(_) => { + CodexAuth::ChatgptAuthTokens(_) => { self.refresh_external_auth(ExternalAuthRefreshReason::Unauthorized) .await } - CodexAuth::ChatGpt(chatgpt_auth) => { + CodexAuth::Chatgpt(chatgpt_auth) => { let token_data = chatgpt_auth.current_token_data().ok_or_else(|| { RefreshTokenError::Transient(std::io::Error::other( "Token data is not available.", @@ -1170,7 +1170,7 @@ impl AuthManager { async fn refresh_if_stale(&self, auth: &CodexAuth) -> Result { let chatgpt_auth = match auth { - CodexAuth::ChatGpt(chatgpt_auth) => chatgpt_auth, + CodexAuth::Chatgpt(chatgpt_auth) => chatgpt_auth, _ => return Ok(false), }; @@ -1250,7 +1250,7 @@ impl AuthManager { async fn refresh_tokens( &self, - auth: &ChatGptAuth, + auth: &ChatgptAuth, refresh_token: String, ) -> Result<(), RefreshTokenError> { let refresh_response = try_refresh_token(refresh_token, auth.client()).await?; @@ -1373,7 +1373,7 @@ mod tests { .unwrap() .unwrap(); assert_eq!(None, auth.api_key()); - assert_eq!(AuthMode::ChatGPT, auth.internal_auth_mode()); + assert_eq!(AuthMode::Chatgpt, auth.internal_auth_mode()); let auth_dot_json = auth .get_current_auth_json() diff --git a/codex-rs/core/src/auth/storage.rs b/codex-rs/core/src/auth/storage.rs index b4f4bb8e7e..1ac1b2ee18 100644 --- a/codex-rs/core/src/auth/storage.rs +++ b/codex-rs/core/src/auth/storage.rs @@ -565,7 +565,7 @@ mod tests { let auth_file = get_auth_file(codex_home.path()); std::fs::write(&auth_file, "stale")?; let auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(TokenData { id_token: Default::default(), diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 30dd8d24fc..5a1ce90dd9 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -5271,7 +5271,7 @@ mod tests { model_info.slug.as_str(), None, Some("test@test.com".to_string()), - Some(AuthMode::ChatGPT), + Some(AuthMode::Chatgpt), false, "test".to_string(), session_source, diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index 0f5a8643a7..56ff76d7f6 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -137,7 +137,7 @@ impl ModelProviderInfo { &self, auth_mode: Option, ) -> crate::error::Result { - let default_base_url = if matches!(auth_mode, Some(AuthMode::ChatGPT)) { + let default_base_url = if matches!(auth_mode, Some(AuthMode::Chatgpt)) { "https://chatgpt.com/backend-api/codex" } else { "https://api.openai.com/v1" diff --git a/codex-rs/core/src/models_manager/manager.rs b/codex-rs/core/src/models_manager/manager.rs index 40f9c8ccdc..936e40d1bc 100644 --- a/codex-rs/core/src/models_manager/manager.rs +++ b/codex-rs/core/src/models_manager/manager.rs @@ -274,7 +274,7 @@ impl ModelsManager { let mut merged_presets = ModelPreset::merge(remote_presets, existing_presets); let chatgpt_mode = matches!( self.auth_manager.get_internal_auth_mode(), - Some(AuthMode::ChatGPT) + Some(AuthMode::Chatgpt) ); merged_presets = ModelPreset::filter_by_auth(merged_presets, chatgpt_mode); diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index b2c64818cc..86d6e8ce61 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -71,7 +71,7 @@ async fn responses_stream_includes_subagent_header_on_review() { let config = Arc::new(config); let conversation_id = ThreadId::new(); - let auth_mode = AuthMode::ChatGPT; + let auth_mode = AuthMode::Chatgpt; let session_source = SessionSource::SubAgent(SubAgentSource::Review); let model_info = ModelsManager::construct_model_info_offline(model.as_str(), &config); let otel_manager = OtelManager::new( @@ -169,7 +169,7 @@ async fn responses_stream_includes_subagent_header_on_other() { let config = Arc::new(config); let conversation_id = ThreadId::new(); - let auth_mode = AuthMode::ChatGPT; + let auth_mode = AuthMode::Chatgpt; let session_source = SessionSource::SubAgent(SubAgentSource::Other("my-task".to_string())); let model_info = ModelsManager::construct_model_info_offline(model.as_str(), &config); diff --git a/codex-rs/core/tests/suite/auth_refresh.rs b/codex-rs/core/tests/suite/auth_refresh.rs index 4ef3b82eec..a6be08f23c 100644 --- a/codex-rs/core/tests/suite/auth_refresh.rs +++ b/codex-rs/core/tests/suite/auth_refresh.rs @@ -51,7 +51,7 @@ async fn refresh_token_succeeds_updates_storage() -> Result<()> { let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -113,7 +113,7 @@ async fn returns_fresh_tokens_as_is() -> Result<()> { let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -159,7 +159,7 @@ async fn refreshes_token_when_last_refresh_is_stale() -> Result<()> { let stale_refresh = Utc::now() - Duration::days(9); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(stale_refresh), @@ -218,7 +218,7 @@ async fn refresh_token_returns_permanent_error_for_expired_refresh_token() -> Re let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -268,7 +268,7 @@ async fn refresh_token_returns_transient_error_on_server_failure() -> Result<()> let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -320,7 +320,7 @@ async fn unauthorized_recovery_reloads_then_refreshes_tokens() -> Result<()> { let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -329,7 +329,7 @@ async fn unauthorized_recovery_reloads_then_refreshes_tokens() -> Result<()> { let disk_tokens = build_tokens("disk-access-token", "disk-refresh-token"); let disk_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(disk_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -412,7 +412,7 @@ async fn unauthorized_recovery_skips_reload_on_account_mismatch() -> Result<()> let initial_last_refresh = Utc::now() - Duration::days(1); let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); let initial_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(initial_tokens.clone()), last_refresh: Some(initial_last_refresh), @@ -427,7 +427,7 @@ async fn unauthorized_recovery_skips_reload_on_account_mismatch() -> Result<()> ..disk_tokens.clone() }; let disk_auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: None, tokens: Some(disk_tokens), last_refresh: Some(initial_last_refresh), diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 5272c84eaa..e571d9b824 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -560,7 +560,7 @@ pub(crate) async fn persist_tokens_async( tokens.account_id = Some(acc.to_string()); } let auth = AuthDotJson { - auth_mode: Some(AuthMode::ChatGPT), + auth_mode: Some(AuthMode::Chatgpt), openai_api_key: api_key, tokens: Some(tokens), last_refresh: Some(Utc::now()), diff --git a/codex-rs/tui/src/onboarding/auth.rs b/codex-rs/tui/src/onboarding/auth.rs index daf64f36d8..7378b6628e 100644 --- a/codex-rs/tui/src/onboarding/auth.rs +++ b/codex-rs/tui/src/onboarding/auth.rs @@ -663,7 +663,7 @@ impl AuthModeWidget { fn handle_existing_chatgpt_login(&mut self) -> bool { if matches!( self.login_status, - LoginStatus::AuthMode(AuthMode::ChatGPT | AuthMode::ChatgptAuthTokens) + LoginStatus::AuthMode(AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens) ) { *self.sign_in_state.write().unwrap() = SignInState::ChatGptSuccess; self.request_frame.schedule_frame(); diff --git a/codex-rs/tui/src/status/helpers.rs b/codex-rs/tui/src/status/helpers.rs index 0a801227f5..bc4cbb9c16 100644 --- a/codex-rs/tui/src/status/helpers.rs +++ b/codex-rs/tui/src/status/helpers.rs @@ -91,7 +91,7 @@ pub(crate) fn compose_account_display( let auth = auth_manager.auth_cached()?; match auth { - CodexAuth::ChatGpt(_) | CodexAuth::ChatGptAuthTokens(_) => { + CodexAuth::Chatgpt(_) | CodexAuth::ChatgptAuthTokens(_) => { let email = auth.get_account_email(); let plan = plan .map(|plan_type| title_case(format!("{plan_type:?}").as_str())) From 9b29a48a09893cfdea7d7ea056918a9a011ccc01 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 30 Jan 2026 11:48:03 -0800 Subject: [PATCH 115/116] Plan mode prompt (#10238) # 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. --- .../core/templates/collaboration_mode/plan.md | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/codex-rs/core/templates/collaboration_mode/plan.md b/codex-rs/core/templates/collaboration_mode/plan.md index 395b6c368b..2ae72aba43 100644 --- a/codex-rs/core/templates/collaboration_mode/plan.md +++ b/codex-rs/core/templates/collaboration_mode/plan.md @@ -60,18 +60,14 @@ Do not ask questions that can be answered from the repo or system (for example, Every assistant turn MUST be exactly one of: A) a `request_user_input` tool call (questions/options only), OR -B) a non-final status update with no questions and no plan content, OR C) the final output: a titled, plan-only document. Rules: * No questions in free text (only via `request_user_input`). * Never mix a `request_user_input` call with plan content. -* Status updates must not include questions or plan content. * Internal tool/repo exploration is allowed privately before A, B, or C. -Status updates should be frequent during exploration. Provide 1-2 sentence updates that summarize discoveries, assumption changes, or why you are changing direction. Use Parallel tools for exploration. - ## Ask a lot, but never ask trivia You SHOULD ask many questions, but each question must: @@ -113,19 +109,15 @@ When you present the official plan, wrap it in a `` block so the Example: -# Plan title -- Step 1 -- Step 2 +plan content -The final plan must be plan-only and include: +plan content should be human and agent digestible. The final plan must be plan-only and include: * A clear title -* A TL;DR section (3–5 bullets) -* Exact file paths to change -* Exact structures or shapes to introduce or modify -* Exact function, method, type, and variable names and signatures -* Test cases +* tldr section. don't necessary call it tldr. +* Important changes or additions of signatures, structs, types. +* Test cases and scenarios * Explicit assumptions and defaults chosen where needed Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. From 2457bb3c404e4c092eef52ff9b2538b01623a17d Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Fri, 30 Jan 2026 11:57:13 -0800 Subject: [PATCH 116/116] Fix deploy (#10251) Fix https://github.com/openai/codex/actions/runs/21527697445/job/62035898666 --- codex-rs/tui/src/app.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index c65ce4498d..7ed9d0b035 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1154,6 +1154,7 @@ impl App { return Ok(AppExitInfo { token_usage: app.token_usage(), thread_id: app.chat_widget.thread_id(), + thread_name: app.chat_widget.thread_name(), update_action: app.pending_update_action, exit_reason, });