From 238ce7dfad3916c325d9919a829ecd5ce60ef43a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 11 Dec 2025 09:04:08 -0800 Subject: [PATCH 01/77] feat: robin (#7882) image --------- Co-authored-by: Dylan Hurd --- .../app-server/tests/suite/v2/model_list.rs | 12 +- codex-rs/core/gpt_5_2_prompt.md | 370 ++++++++++++++++++ .../core/src/openai_models/model_family.rs | 5 +- .../core/src/openai_models/model_presets.rs | 8 +- codex-rs/core/tests/suite/list_models.rs | 16 +- ...twidget__tests__model_selection_popup.snap | 3 +- ...twidget__tests__model_selection_popup.snap | 3 +- 7 files changed, 397 insertions(+), 20 deletions(-) create mode 100644 codex-rs/core/gpt_5_2_prompt.md diff --git a/codex-rs/app-server/tests/suite/v2/model_list.rs b/codex-rs/app-server/tests/suite/v2/model_list.rs index e8d3d16058..eb9d0c32c1 100644 --- a/codex-rs/app-server/tests/suite/v2/model_list.rs +++ b/codex-rs/app-server/tests/suite/v2/model_list.rs @@ -117,10 +117,12 @@ async fn list_models_returns_all_models_with_large_limit() -> Result<()> { is_default: false, }, Model { - id: "robin".to_string(), - model: "robin".to_string(), - display_name: "robin".to_string(), - description: "Robin".to_string(), + id: "gpt-5.2".to_string(), + model: "gpt-5.2".to_string(), + display_name: "gpt-5.2".to_string(), + description: + "Latest frontier model with improvements across knowledge, reasoning and coding" + .to_string(), supported_reasoning_efforts: vec![ ReasoningEffortOption { reasoning_effort: ReasoningEffort::Low, @@ -274,7 +276,7 @@ async fn list_models_pagination_works() -> Result<()> { } = to_response::(fourth_response)?; assert_eq!(fourth_items.len(), 1); - assert_eq!(fourth_items[0].id, "robin"); + assert_eq!(fourth_items[0].id, "gpt-5.2"); let fifth_cursor = fourth_cursor.ok_or_else(|| anyhow!("cursor for fifth page"))?; let fifth_request = mcp diff --git a/codex-rs/core/gpt_5_2_prompt.md b/codex-rs/core/gpt_5_2_prompt.md new file mode 100644 index 0000000000..fdb1e3d5d3 --- /dev/null +++ b/codex-rs/core/gpt_5_2_prompt.md @@ -0,0 +1,370 @@ +You are GPT-5.2 running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful. + +Your capabilities: + +- Receive user prompts and other context provided by the harness, such as files in the workspace. +- Communicate with the user by streaming thinking & responses, and by making & updating plans. +- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section. + +Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI). + +# How you work + +## Personality + +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. + +## AGENTS.md spec +- Repos often contain AGENTS.md files. These files can appear anywhere within the repository. +- These files are a way for humans to give you (the agent) instructions or tips for working within the container. +- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code. +- Instructions in AGENTS.md files: + - The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it. + - For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file. + - Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise. + - More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions. + - Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions. +- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable. + +## Autonomy and Persistence +Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you. + +Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself. + +## Responsiveness + +### User Updates Spec +You'll work for stretches with tool calls — it's critical to keep the user updated as you work. + +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 + +Tone: +- Friendly, confident, senior-engineer energy. Positive, collaborative, humble; fix mistakes quickly. + +Content: +- Before the first tool call, 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. + +**Examples:** + +- “I’ve explored the repo; now checking the API route definitions.” +- “Next, I’ll patch the config and update the related tests.” +- “I’m about to scaffold the CLI commands and helper functions.” +- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.” +- “Config’s looking tidy. Next up is patching helpers to keep things in sync.” +- “Finished poking at the DB gateway. I will now chase down error handling.” +- “Alright, build pipeline order is interesting. Checking how it reports failures.” +- “Spotted a clever caching util; now hunting where it gets used.” + +## Planning + +You have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go. + +Note that plans are not for padding out simple work with filler steps or stating the obvious. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately. + +Do not repeat the full contents of the plan after an `update_plan` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step. + +Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. Sometimes, you may need to change plans in the middle of a task: call `update_plan` with the updated plan and make sure to provide an `explanation` of the rationale when doing so. + +Maintain statuses in the tool: exactly one item in_progress at a time; mark items complete when done; post timely status transitions. Do not jump an item from pending to completed: always set it to in_progress first. Do not batch-complete multiple items after the fact. Finish with all items completed or explicitly canceled/deferred before ending the turn. Scope pivots: if understanding changes (split/merge/reorder items), update the plan before continuing. Do not let the plan go stale while coding. + +Use a plan when: + +- The task is non-trivial and will require multiple actions over a long time horizon. +- There are logical phases or dependencies where sequencing matters. +- The work has ambiguity that benefits from outlining high-level goals. +- You want intermediate checkpoints for feedback and validation. +- When the user asked you to do more than one thing in a single prompt +- The user has asked you to use the plan tool (aka "TODOs") +- You generate additional steps while working, and plan to do them before yielding to the user + +### Examples + +**High-quality plans** + +Example 1: + +1. Add CLI entry with file args +2. Parse Markdown via CommonMark library +3. Apply semantic HTML template +4. Handle code blocks, images, links +5. Add error handling for invalid files + +Example 2: + +1. Define CSS variables for colors +2. Add toggle with localStorage state +3. Refactor components to use variables +4. Verify all views for readability +5. Add smooth theme-change transition + +Example 3: + +1. Set up Node.js + WebSocket server +2. Add join/leave broadcast events +3. Implement messaging with timestamps +4. Add usernames + mention highlighting +5. Persist messages in lightweight DB +6. Add typing indicators + unread count + +**Low-quality plans** + +Example 1: + +1. Create CLI tool +2. Add Markdown parser +3. Convert to HTML + +Example 2: + +1. Add dark mode toggle +2. Save preference +3. Make styles look good + +Example 3: + +1. Create single-file HTML game +2. Run quick sanity check +3. Summarize usage instructions + +If you need to write a plan, only write high quality plans, not low quality ones. + +## Task execution + +You are a coding agent. You must keep going until the query or task is completely resolved, before ending your turn and yielding back to the user. Persist until the task is fully handled end-to-end within the current turn whenever feasible and persevere even when function calls fail. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer. + +You MUST adhere to the following criteria when solving queries: + +- Working on the repo(s) in the current environment is allowed, even if they are proprietary. +- Analyzing code for vulnerabilities is allowed. +- Showing user code and tool call details is allowed. +- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`). This is a FREEFORM tool, so do not wrap the patch in JSON. + +If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines: + +- Fix the problem at the root cause rather than applying surface-level patches, when possible. +- Avoid unneeded complexity in your solution. +- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.) +- Update documentation as necessary. +- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task. +- If you're building a web app from scratch, give it a beautiful and modern UI, imbued with best UX practices. +- Use `git log` and `git blame` to search the history of the codebase if additional context is required. +- NEVER add copyright or license headers unless specifically requested. +- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc. +- Do not `git commit` your changes or create new git branches unless explicitly requested. +- Do not add inline comments within code unless explicitly requested. +- Do not use one-letter variable names unless explicitly requested. +- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor. + +## Codex CLI harness, sandboxing, and approvals + +The Codex CLI harness supports several different configurations for sandboxing and escalation approvals that the user can choose from. + +Filesystem sandboxing defines which files can be read or written. The options for `sandbox_mode` are: +- **read-only**: The sandbox only permits reading files. +- **workspace-write**: The sandbox permits reading files, and editing files in `cwd` and `writable_roots`. Editing files in other directories requires approval. +- **danger-full-access**: No filesystem sandboxing - all commands are permitted. + +Network sandboxing defines whether network can be accessed without approval. Options for `network_access` are: +- **restricted**: Requires approval +- **enabled**: No approval needed + +Approvals are your mechanism to get user consent to run shell commands without the sandbox. Possible configuration options for `approval_policy` are +- **untrusted**: The harness will escalate most commands for user approval, apart from a limited allowlist of safe "read" commands. +- **on-failure**: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox. +- **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. (Note that this mode is not always available. If it is, you'll see parameters for escalating in the tool definition.) +- **never**: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is paired with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding. + +When you are running with `approval_policy == on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval: +- 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. +- You are running sandboxed and need to run a command that requires network access (e.g. installing packages) +- 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. +- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for +- (for all of these, you should weigh alternative paths that do not require approval) + +When `sandbox_mode` is set to read-only, you'll need to request approval for any command that isn't a read. + +You will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing enabled, and approval on-failure. + +Although they introduce friction to the user because your work is paused until the user responds, you should leverage them when necessary to accomplish important work. 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 unless it is set to "never", in which case never ask for approvals. + +When requesting approval to execute a command that will require escalated privileges: + - Provide the `sandbox_permissions` parameter with the value `"require_escalated"` + - Include a short, 1 sentence explanation for why you need escalated permissions in the justification parameter + +## Validating your work + +If the codebase has tests, or the ability to build or run tests, consider using them to verify changes once your work is complete. + +When testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests. + +Similarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one. + +For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.) + +Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance: + +- When running in non-interactive approval modes like **never** or **on-failure**, you can proactively run tests, lint and do whatever you need to ensure you've completed the task. If you are unable to run tests, you must still do your utmost best to complete the task. +- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first. +- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task. + +## Ambition vs. precision + +For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation. + +If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature. + +You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified. + +## Sharing progress updates + +For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next. + +Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why. + +The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along. + +## Presenting your work and final message + +Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges. + +You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation. + +The user is working on the same computer as you, and has access to your work. As such there's no need to show the contents of files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path. + +If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly. + +Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding. + +### Final answer structure and style guidelines + +You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value. + +**Section Headers** + +- Use only when they improve clarity — they are not mandatory for every answer. +- Choose descriptive names that fit the content +- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**` +- Leave no blank line before the first bullet under a header. +- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer. + +**Bullets** + +- Use `-` followed by a space for every bullet. +- Merge related points when possible; avoid a bullet for every trivial detail. +- Keep bullets to one line unless breaking for clarity is unavoidable. +- Group into short lists (4–6 bullets) ordered by importance. +- Use consistent keyword phrasing and formatting across sections. + +**Monospace** + +- Wrap all commands, file paths, env vars, code identifiers, and code samples in backticks (`` `...` ``). +- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command. +- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``). + +**File References** +When referencing files in your response, make sure to include the relevant start line and 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 + +**Structure** + +- Place related bullets together; don’t mix unrelated concepts in the same section. +- Order sections from general → specific → supporting info. +- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it. +- Match structure to complexity: + - Multi-part or detailed results → use clear headers and grouped bullets. + - Simple results → minimal headers, possibly just a short list or paragraph. + +**Tone** + +- Keep the voice collaborative and natural, like a coding partner handing off work. +- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition +- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”). +- Keep descriptions self-contained; don’t refer to “above” or “below”. +- Use parallel structure in lists for consistency. + +**Verbosity** +- Final answer compactness rules (enforced): + - Tiny/small single-file change (≤ ~10 lines): 2–5 sentences or ≤3 bullets. No headings. 0–1 short snippet (≤3 lines) only if essential. + - Medium change (single area or a few files): ≤6 bullets or 6–10 sentences. At most 1–2 short snippets total (≤8 lines each). + - Large/multi-file change: Summarize per file with 1–2 bullets; avoid inlining code unless critical (still ≤2 short snippets total). + - Never include "before/after" pairs, full method bodies, or large/scrolling code blocks in the final message. Prefer referencing file/symbol names instead. + +**Don’t** + +- Don’t use literal words “bold” or “monospace” in the content. +- Don’t nest bullets or create deep hierarchies. +- Don’t output ANSI escape codes directly — the CLI renderer applies them. +- Don’t cram unrelated keywords into a single bullet; split for clarity. +- Don’t let keyword lists run long — wrap or reformat for scanability. + +Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable. + +For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting. + +# Tool Guidelines + +## Shell commands + +When using the shell, you must adhere to the following guidelines: + +- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.) +- Do not use python scripts to attempt to output larger chunks of a file. Command line output will be truncated after 10 kilobytes, regardless of the command used. +- Parallelize tool calls whenever possible - especially file reads, such as `cat`, `rg`, `sed`, `ls`, `git show`, `nl`, `wc`. Use `multi_tool_use.parallel` to parallelize tool calls and only this. + +## apply_patch + +Use the `apply_patch` tool to edit files. Your patch language is a stripped‑down, file‑oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high‑level envelope: + +*** Begin Patch +[ one or more file sections ] +*** End Patch + +Within that envelope, you get a sequence of file operations. +You MUST include a header to specify the action you are taking. +Each operation starts with one of three headers: + +*** Add File: - create a new file. Every following line is a + line (the initial contents). +*** Delete File: - remove an existing file. Nothing follows. +*** Update File: - patch an existing file in place (optionally with a rename). + +Example patch: + +``` +*** Begin Patch +*** Add File: hello.txt ++Hello world +*** Update File: src/app.py +*** Move to: src/main.py +@@ def greet(): +-print("Hi") ++print("Hello, world!") +*** Delete File: obsolete.txt +*** End Patch +``` + +It is important to remember: + +- You must include a header with your intended action (Add/Delete/Update) +- You must prefix new lines with `+` even when creating a new file + +## `update_plan` + +A tool named `update_plan` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task. + +To create a new plan, call `update_plan` with a short list of 1‑sentence steps (no more than 5-7 words each) with a `status` for each step (`pending`, `in_progress`, or `completed`). + +When steps have been completed, use `update_plan` to mark each finished step as `completed` and the next step you are working on as `in_progress`. There should always be exactly one `in_progress` step until everything is done. You can mark multiple items as complete in a single `update_plan` call. + +If all steps are complete, ensure you call `update_plan` to mark all steps as `completed`. diff --git a/codex-rs/core/src/openai_models/model_family.rs b/codex-rs/core/src/openai_models/model_family.rs index 87ea6a4fcb..07911b8c83 100644 --- a/codex-rs/core/src/openai_models/model_family.rs +++ b/codex-rs/core/src/openai_models/model_family.rs @@ -14,6 +14,7 @@ const BASE_INSTRUCTIONS: &str = include_str!("../../prompt.md"); const GPT_5_CODEX_INSTRUCTIONS: &str = include_str!("../../gpt_5_codex_prompt.md"); const GPT_5_1_INSTRUCTIONS: &str = include_str!("../../gpt_5_1_prompt.md"); +const GPT_5_2_INSTRUCTIONS: &str = include_str!("../../gpt_5_2_prompt.md"); const GPT_5_1_CODEX_MAX_INSTRUCTIONS: &str = include_str!("../../gpt-5.1-codex-max_prompt.md"); pub(crate) const CONTEXT_WINDOW_272K: i64 = 272_000; @@ -284,14 +285,14 @@ pub fn find_family_for_model(slug: &str) -> ModelFamily { truncation_policy: TruncationPolicy::Tokens(10_000), context_window: Some(CONTEXT_WINDOW_272K), ) - } else if slug.starts_with("robin") { + } else if slug.starts_with("gpt-5.2") { model_family!( slug, slug, supports_reasoning_summaries: true, apply_patch_tool_type: Some(ApplyPatchToolType::Freeform), support_verbosity: true, default_verbosity: Some(Verbosity::Low), - base_instructions: GPT_5_1_INSTRUCTIONS.to_string(), + base_instructions: GPT_5_2_INSTRUCTIONS.to_string(), default_reasoning_effort: Some(ReasoningEffort::Medium), truncation_policy: TruncationPolicy::Bytes(10_000), shell_type: ConfigShellToolType::ShellCommand, diff --git a/codex-rs/core/src/openai_models/model_presets.rs b/codex-rs/core/src/openai_models/model_presets.rs index b279a33fc7..42a5557f40 100644 --- a/codex-rs/core/src/openai_models/model_presets.rs +++ b/codex-rs/core/src/openai_models/model_presets.rs @@ -94,10 +94,10 @@ static PRESETS: Lazy> = Lazy::new(|| { show_in_picker: true, }, ModelPreset { - id: "robin".to_string(), - model: "robin".to_string(), - display_name: "robin".to_string(), - description: "Robin".to_string(), + id: "gpt-5.2".to_string(), + model: "gpt-5.2".to_string(), + display_name: "gpt-5.2".to_string(), + description: "Latest frontier model with improvements across knowledge, reasoning and coding".to_string(), default_reasoning_effort: ReasoningEffort::Medium, supported_reasoning_efforts: vec![ ReasoningEffortPreset { diff --git a/codex-rs/core/tests/suite/list_models.rs b/codex-rs/core/tests/suite/list_models.rs index 268115bb5f..9cfd9b267f 100644 --- a/codex-rs/core/tests/suite/list_models.rs +++ b/codex-rs/core/tests/suite/list_models.rs @@ -46,7 +46,7 @@ fn expected_models_for_api_key() -> Vec { gpt_5_1_codex_max(), gpt_5_1_codex(), gpt_5_1_codex_mini(), - robin(), + gpt_5_2(), gpt_5_1(), ] } @@ -56,7 +56,7 @@ fn expected_models_for_chatgpt() -> Vec { gpt_5_1_codex_max(), gpt_5_1_codex(), gpt_5_1_codex_mini(), - robin(), + gpt_5_2(), gpt_5_1(), ] } @@ -142,12 +142,14 @@ fn gpt_5_1_codex_mini() -> ModelPreset { } } -fn robin() -> ModelPreset { +fn gpt_5_2() -> ModelPreset { ModelPreset { - id: "robin".to_string(), - model: "robin".to_string(), - display_name: "robin".to_string(), - description: "Robin".to_string(), + id: "gpt-5.2".to_string(), + model: "gpt-5.2".to_string(), + display_name: "gpt-5.2".to_string(), + description: + "Latest frontier model with improvements across knowledge, reasoning and coding" + .to_string(), default_reasoning_effort: ReasoningEffort::Medium, supported_reasoning_efforts: vec![ effort( diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap index b4c76500ca..eb67d0ea96 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap @@ -10,7 +10,8 @@ expression: popup 2. gpt-5.1-codex Optimized for codex. 3. gpt-5.1-codex-mini Optimized for codex. Cheaper, faster, but less capable. - 4. robin Robin + 4. gpt-5.2 Latest frontier model with improvements + across knowledge, reasoning and coding 5. gpt-5.1 Broad world knowledge with strong general reasoning. diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_selection_popup.snap index b0482e7ec9..1858383b4a 100644 --- a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_selection_popup.snap +++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_selection_popup.snap @@ -10,7 +10,8 @@ expression: popup 2. gpt-5.1-codex Optimized for codex. 3. gpt-5.1-codex-mini Optimized for codex. Cheaper, faster, but less capable. - 4. robin Robin + 4. gpt-5.2 Latest frontier model with improvements across + knowledge, reasoning and coding 5. gpt-5.1 Broad world knowledge with strong general reasoning. Press enter to select reasoning effort, or esc to dismiss. From bb8fdb20dc24e7650dfb4551173c1b87a3a20a29 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 11 Dec 2025 09:11:42 -0800 Subject: [PATCH 02/77] Revert "Only show Worked for after the final assistant message" (#7884) Reverts openai/codex#7854 --- codex-rs/tui/src/bottom_pane/mod.rs | 1 - codex-rs/tui/src/chatwidget.rs | 27 ++++++------------- ...t_markdown_code_blocks_vt100_snapshot.snap | 3 +-- codex-rs/tui/src/chatwidget/tests.rs | 1 - codex-rs/tui/src/status_indicator_widget.rs | 5 +++- 5 files changed, 13 insertions(+), 24 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index c0d6007324..8516687284 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -136,7 +136,6 @@ impl BottomPane { self.request_redraw(); } - #[cfg(test)] pub fn status_widget(&self) -> Option<&StatusIndicatorWidget> { self.status.as_ref() } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index d7a451e825..82f00f9cac 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -4,7 +4,6 @@ use std::collections::VecDeque; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; -use std::time::Instant; use codex_app_server_protocol::AuthMode; use codex_backend_client::Client as BackendClient; @@ -334,8 +333,6 @@ pub(crate) struct ChatWidget { feedback: codex_feedback::CodexFeedback, // Current session rollout path (if known) current_rollout_path: Option, - // Current task start time - task_started_at: Option, } struct UserMessage { @@ -521,20 +518,17 @@ impl ChatWidget { self.set_status_header(String::from("Working")); self.full_reasoning_buffer.clear(); self.reasoning_buffer.clear(); - self.task_started_at = Some(Instant::now()); self.request_redraw(); } fn on_task_complete(&mut self, last_agent_message: Option) { // If a stream is currently active, finalize it. self.flush_answer_stream_with_separator(); - self.add_final_message_separator(); // Mark task stopped and request redraw now that all content is in history. self.bottom_pane.set_task_running(false); self.running_commands.clear(); self.suppressed_exec_calls.clear(); self.last_unified_wait = None; - self.task_started_at = None; self.request_redraw(); // If there is a queued user message, send exactly one now to begin the next turn. @@ -670,7 +664,6 @@ impl ChatWidget { self.suppressed_exec_calls.clear(); self.last_unified_wait = None; self.stream_controller = None; - self.task_started_at = None; self.maybe_show_pending_rate_limit_prompt(); } pub(crate) fn get_model_family(&self) -> ModelFamily { @@ -1014,6 +1007,14 @@ impl ChatWidget { self.flush_active_cell(); if self.stream_controller.is_none() { + if self.needs_final_message_separator { + let elapsed_seconds = self + .bottom_pane + .status_widget() + .map(super::status_indicator_widget::StatusIndicatorWidget::elapsed_seconds); + self.add_to_history(history_cell::FinalMessageSeparator::new(elapsed_seconds)); + self.needs_final_message_separator = false; + } self.stream_controller = Some(StreamController::new( self.last_rendered_width.get().map(|w| w.saturating_sub(2)), )); @@ -1026,16 +1027,6 @@ impl ChatWidget { self.request_redraw(); } - fn add_final_message_separator(&mut self) { - if self.needs_final_message_separator { - let elapsed_seconds = self - .task_started_at - .map(|start_time| start_time.elapsed().as_secs()); - self.add_to_history(history_cell::FinalMessageSeparator::new(elapsed_seconds)); - self.needs_final_message_separator = false; - } - } - pub(crate) fn handle_exec_end_now(&mut self, ev: ExecCommandEndEvent) { let running = self.running_commands.remove(&ev.call_id); if self.suppressed_exec_calls.remove(&ev.call_id) { @@ -1339,7 +1330,6 @@ impl ChatWidget { last_rendered_width: std::cell::Cell::new(None), feedback, current_rollout_path: None, - task_started_at: None, }; widget.prefetch_rate_limits(); @@ -1425,7 +1415,6 @@ impl ChatWidget { last_rendered_width: std::cell::Cell::new(None), feedback, current_rollout_path: None, - task_started_at: None, }; widget.prefetch_rate_limits(); diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap index 8f9b559276..1ed73b5fa5 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap @@ -1,6 +1,6 @@ --- source: tui/src/chatwidget/tests.rs -expression: term.backend().vt100().screen().contents() +expression: visual --- • -- Indented code block (4 spaces) SELECT * @@ -16,4 +16,3 @@ expression: term.backend().vt100().screen().contents() "path": "C:\\Program Files\\App", "regex": "^foo.*(bar)?$" } -─ Worked for 0s ──────────────────────────────────────────────────────────────── diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index f03346ee52..bd85a9edc8 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -442,7 +442,6 @@ fn make_chatwidget_manual( last_rendered_width: std::cell::Cell::new(None), feedback: codex_feedback::CodexFeedback::new(), current_rollout_path: None, - task_started_at: None, }; (widget, rx, op_rx) } diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index e850c32fe6..642b9ca2b7 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -125,10 +125,13 @@ impl StatusIndicatorWidget { elapsed } - #[cfg(test)] fn elapsed_seconds_at(&self, now: Instant) -> u64 { self.elapsed_duration_at(now).as_secs() } + + pub fn elapsed_seconds(&self) -> u64 { + self.elapsed_seconds_at(Instant::now()) + } } impl Renderable for StatusIndicatorWidget { From 703bf12b36ce327787004ce111c5d6b9bea33318 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Thu, 11 Dec 2025 09:57:59 -0800 Subject: [PATCH 03/77] fix: dont quit on 'q' in onboarding ApiKeyEntry state (#7869) ### What Don't treat `q` as a special quit character on the API key paste page in the onboarding flow. This addresses #7413, where pasting API keys with `q` would cause codex to quit on Windows. ### Test Plan Tested on Windows and MacOS. --- .../tui/src/onboarding/onboarding_screen.rs | 60 ++++++++++++------- 1 file changed, 37 insertions(+), 23 deletions(-) diff --git a/codex-rs/tui/src/onboarding/onboarding_screen.rs b/codex-rs/tui/src/onboarding/onboarding_screen.rs index 47c7811a3b..14999b2229 100644 --- a/codex-rs/tui/src/onboarding/onboarding_screen.rs +++ b/codex-rs/tui/src/onboarding/onboarding_screen.rs @@ -195,11 +195,24 @@ impl OnboardingScreen { pub fn should_exit(&self) -> bool { self.should_exit } + + fn is_api_key_entry_active(&self) -> bool { + self.steps.iter().any(|step| { + if let Step::Auth(widget) = step { + return widget + .sign_in_state + .read() + .is_ok_and(|g| matches!(&*g, SignInState::ApiKeyEntry(_))); + } + false + }) + } } impl KeyboardHandler for OnboardingScreen { fn handle_key_event(&mut self, key_event: KeyEvent) { - match key_event { + let is_api_key_entry_active = self.is_api_key_entry_active(); + let should_quit = match key_event { KeyEvent { code: KeyCode::Char('d'), modifiers: crossterm::event::KeyModifiers::CONTROL, @@ -211,32 +224,33 @@ impl KeyboardHandler for OnboardingScreen { modifiers: crossterm::event::KeyModifiers::CONTROL, kind: KeyEventKind::Press, .. - } - | KeyEvent { + } => true, + KeyEvent { code: KeyCode::Char('q'), kind: KeyEventKind::Press, .. - } => { - if self.is_auth_in_progress() { - // If the user cancels the auth menu, exit the app rather than - // leave the user at a prompt in an unauthed state. - self.should_exit = true; - } - self.is_done = true; - } - _ => { - if let Some(Step::Welcome(widget)) = self - .steps - .iter_mut() - .find(|step| matches!(step, Step::Welcome(_))) - { - widget.handle_key_event(key_event); - } - if let Some(active_step) = self.current_steps_mut().into_iter().last() { - active_step.handle_key_event(key_event); - } - } + } => !is_api_key_entry_active, + _ => false, }; + if should_quit { + if self.is_auth_in_progress() { + // If the user cancels the auth menu, exit the app rather than + // leave the user at a prompt in an unauthed state. + self.should_exit = true; + } + self.is_done = true; + } else { + if let Some(Step::Welcome(widget)) = self + .steps + .iter_mut() + .find(|step| matches!(step, Step::Welcome(_))) + { + widget.handle_key_event(key_event); + } + if let Some(active_step) = self.current_steps_mut().into_iter().last() { + active_step.handle_key_event(key_event); + } + } self.request_frame.schedule_frame(); } From 8c4c6a19e09f295592a77558bdf6b150707bac16 Mon Sep 17 00:00:00 2001 From: Tyler Anton Date: Thu, 11 Dec 2025 10:43:50 -0800 Subject: [PATCH 04/77] fix: drop stale filedescriptor output hash for nix (#7865) Fixes: #7863 - Remove the `filedescriptor-0.8.3` entry from `codex-rs/default.nix` output hashes because the crate now comes from crates.io. --- codex-rs/default.nix | 1 - 1 file changed, 1 deletion(-) diff --git a/codex-rs/default.nix b/codex-rs/default.nix index 819ca7aad2..26971f1846 100644 --- a/codex-rs/default.nix +++ b/codex-rs/default.nix @@ -22,7 +22,6 @@ rustPlatform.buildRustPackage (_: { cargoLock.outputHashes = { "ratatui-0.29.0" = "sha256-HBvT5c8GsiCxMffNjJGLmHnvG77A6cqEL+1ARurBXho="; "crossterm-0.28.1" = "sha256-6qCtfSMuXACKFb9ATID39XyFDIEMFDmbx6SSmNe+728="; - "filedescriptor-0.8.3" = "sha256-aIbzfHYjPDzWSZrgbauezGzg6lm3frhyBbU01gTQpaE="; }; meta = with lib; { From 0af7e4a195237220e49f576f13c2adf7a04a8bc6 Mon Sep 17 00:00:00 2001 From: Anton Panasenko Date: Thu, 11 Dec 2025 11:59:40 -0800 Subject: [PATCH 05/77] fix: omit reasoning summary when ReasoningSummary::None (#7845) ``` { "error": { "message": "Invalid value: 'none'. Supported values are: 'concise', 'detailed', and 'auto'.", "type": "invalid_request_error", "param": "reasoning.summary", "code": "invalid_value" } } ``` --- codex-rs/core/src/client.rs | 6 ++- codex-rs/core/tests/suite/client.rs | 76 +++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 72c23a3ea4..9659b10909 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -206,7 +206,11 @@ impl ModelClient { let reasoning = if model_family.supports_reasoning_summaries { Some(Reasoning { effort: self.effort.or(model_family.default_reasoning_effort), - summary: Some(self.summary), + summary: if self.summary == ReasoningSummaryConfig::None { + None + } else { + Some(self.summary) + }, }) } else { None diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index faa9801f86..4d47c9f214 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -22,6 +22,7 @@ use codex_core::protocol::Op; use codex_core::protocol::SessionSource; use codex_otel::otel_event_manager::OtelEventManager; use codex_protocol::ConversationId; +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Verbosity; use codex_protocol::models::ReasoningItemContent; use codex_protocol::models::ReasoningItemReasoningSummary; @@ -823,6 +824,81 @@ async fn includes_default_reasoning_effort_in_request_when_defined_by_model_fami Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn configured_reasoning_summary_is_sent() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + let server = MockServer::start().await; + + let resp_mock = mount_sse_once(&server, sse_completed("resp1")).await; + let TestCodex { codex, .. } = test_codex() + .with_config(|config| { + config.model_reasoning_summary = ReasoningSummary::Concise; + }) + .build(&server) + .await?; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "hello".into(), + }], + }) + .await + .unwrap(); + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; + + let request = resp_mock.single_request(); + let request_body = request.body_json(); + + pretty_assertions::assert_eq!( + request_body + .get("reasoning") + .and_then(|reasoning| reasoning.get("summary")) + .and_then(|value| value.as_str()), + Some("concise") + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn reasoning_summary_is_omitted_when_disabled() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + let server = MockServer::start().await; + + let resp_mock = mount_sse_once(&server, sse_completed("resp1")).await; + let TestCodex { codex, .. } = test_codex() + .with_config(|config| { + config.model_reasoning_summary = ReasoningSummary::None; + }) + .build(&server) + .await?; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "hello".into(), + }], + }) + .await + .unwrap(); + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; + + let request = resp_mock.single_request(); + let request_body = request.body_json(); + + pretty_assertions::assert_eq!( + request_body + .get("reasoning") + .and_then(|reasoning| reasoning.get("summary")), + None + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_default_verbosity_in_request() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); From b9fb3b81e58869dd7d502380261c958c82ec4ec2 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 11 Dec 2025 13:30:56 -0800 Subject: [PATCH 06/77] Chore: limit find family visability (#7891) a little bit more code quality of life --- codex-rs/core/src/client_common.rs | 8 +- codex-rs/core/src/config/mod.rs | 13 +++ .../core/src/openai_models/model_family.rs | 8 +- .../core/src/openai_models/models_manager.rs | 9 +- codex-rs/core/src/tools/spec.rs | 88 +++++++++++-------- 5 files changed, 80 insertions(+), 46 deletions(-) diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index f6152e55d7..4a3bc8de23 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -252,13 +252,15 @@ impl Stream for ResponseStream { #[cfg(test)] mod tests { - use crate::openai_models::model_family::find_family_for_model; use codex_api::ResponsesApiRequest; use codex_api::common::OpenAiVerbosity; use codex_api::common::TextControls; use codex_api::create_text_param_for_request; use pretty_assertions::assert_eq; + use crate::config::test_config; + use crate::openai_models::models_manager::ModelsManager; + use super::*; struct InstructionsTestCase { @@ -309,7 +311,9 @@ mod tests { }, ]; for test_case in test_cases { - let model_family = find_family_for_model(test_case.slug); + let config = test_config(); + let model_family = + ModelsManager::construct_model_family_offline(test_case.slug, &config); let expected = if test_case.expects_apply_patch_instructions { format!( "{}\n{}", diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index e0e6985a39..6a95a860f2 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -50,6 +50,8 @@ use std::collections::HashMap; use std::io::ErrorKind; use std::path::Path; use std::path::PathBuf; +#[cfg(test)] +use tempfile::tempdir; use crate::config::profile::ConfigProfile; use toml::Value as TomlValue; @@ -68,6 +70,17 @@ pub(crate) const PROJECT_DOC_MAX_BYTES: usize = 32 * 1024; // 32 KiB pub const CONFIG_TOML_FILE: &str = "config.toml"; +#[cfg(test)] +pub(crate) fn test_config() -> Config { + let codex_home = tempdir().expect("create temp dir"); + Config::load_from_base_config_with_overrides( + ConfigToml::default(), + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + ) + .expect("load default test config") +} + /// Application configuration loaded from disk and merged with overrides. #[derive(Debug, Clone, PartialEq)] pub struct Config { diff --git a/codex-rs/core/src/openai_models/model_family.rs b/codex-rs/core/src/openai_models/model_family.rs index 07911b8c83..1d6181c6d9 100644 --- a/codex-rs/core/src/openai_models/model_family.rs +++ b/codex-rs/core/src/openai_models/model_family.rs @@ -157,10 +157,9 @@ macro_rules! model_family { }}; } -// todo(aibrahim): remove this function -/// Returns a `ModelFamily` for the given model slug, or `None` if the slug -/// does not match any known model family. -pub fn find_family_for_model(slug: &str) -> ModelFamily { +/// Internal offline helper for `ModelsManager` that returns a `ModelFamily` for the given +/// model slug. +pub(in crate::openai_models) fn find_family_for_model(slug: &str) -> ModelFamily { if slug.starts_with("o3") { model_family!( slug, "o3", @@ -329,6 +328,7 @@ pub fn find_family_for_model(slug: &str) -> ModelFamily { } fn derive_default_model_family(model: &str) -> ModelFamily { + tracing::warn!("Unknown model {model} is used. This will degrade the performance of Codex."); ModelFamily { slug: model.to_string(), family: model.to_string(), diff --git a/codex-rs/core/src/openai_models/models_manager.rs b/codex-rs/core/src/openai_models/models_manager.rs index de9aa0f7c8..823293b8b7 100644 --- a/codex-rs/core/src/openai_models/models_manager.rs +++ b/codex-rs/core/src/openai_models/models_manager.rs @@ -24,7 +24,6 @@ use crate::error::Result as CoreResult; use crate::features::Feature; use crate::model_provider_info::ModelProviderInfo; use crate::openai_models::model_family::ModelFamily; -use crate::openai_models::model_family::find_family_for_model; use crate::openai_models::model_presets::builtin_model_presets; const MODEL_CACHE_FILE: &str = "models_cache.json"; @@ -117,9 +116,13 @@ impl ModelsManager { .map(|models| models.clone()) } + fn find_family_for_model(slug: &str) -> ModelFamily { + super::model_family::find_family_for_model(slug) + } + /// Look up the requested model family while applying remote metadata overrides. pub async fn construct_model_family(&self, model: &str, config: &Config) -> ModelFamily { - find_family_for_model(model) + Self::find_family_for_model(model) .with_config_overrides(config) .with_remote_overrides(self.remote_models.read().await.clone()) } @@ -154,7 +157,7 @@ impl ModelsManager { #[cfg(any(test, feature = "test-support"))] /// Offline helper that builds a `ModelFamily` without consulting remote state. pub fn construct_model_family_offline(model: &str, config: &Config) -> ModelFamily { - find_family_for_model(model).with_config_overrides(config) + Self::find_family_for_model(model).with_config_overrides(config) } /// Replace the cached remote models and rebuild the derived presets list. diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 4f1782d458..11061d4d35 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -1121,7 +1121,8 @@ pub(crate) fn build_specs( #[cfg(test)] mod tests { use crate::client_common::tools::FreeformTool; - use crate::openai_models::model_family::find_family_for_model; + use crate::config::test_config; + use crate::openai_models::models_manager::ModelsManager; use crate::tools::registry::ConfiguredToolSpec; use mcp_types::ToolInputSchema; use pretty_assertions::assert_eq; @@ -1216,7 +1217,8 @@ mod tests { #[test] fn test_full_toolset_specs_for_gpt5_codex_unified_exec_web_search() { - let model_family = find_family_for_model("gpt-5-codex"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); features.enable(Feature::WebSearchRequest); @@ -1274,13 +1276,14 @@ mod tests { } } - fn assert_model_tools(model_family: &str, features: &Features, expected_tools: &[&str]) { - let model_family = find_family_for_model(model_family); - let config = ToolsConfig::new(&ToolsConfigParams { + fn assert_model_tools(model_slug: &str, features: &Features, expected_tools: &[&str]) { + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline(model_slug, &config); + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features, }); - let (tools, _) = build_specs(&config, Some(HashMap::new())).build(); + let (tools, _) = build_specs(&tools_config, Some(HashMap::new())).build(); let tool_names = tools.iter().map(|t| t.spec.name()).collect::>(); assert_eq!(&tool_names, &expected_tools,); } @@ -1467,19 +1470,20 @@ mod tests { #[test] fn test_build_specs_default_shell_present() { - let model_family = find_family_for_model("o3"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("o3", &config); let mut features = Features::with_defaults(); features.enable(Feature::WebSearchRequest); features.enable(Feature::UnifiedExec); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); - let (tools, _) = build_specs(&config, Some(HashMap::new())).build(); + let (tools, _) = build_specs(&tools_config, Some(HashMap::new())).build(); // Only check the shell variant and a couple of core tools. let mut subset = vec!["exec_command", "write_stdin", "update_plan"]; - if let Some(shell_tool) = shell_tool_name(&config) { + if let Some(shell_tool) = shell_tool_name(&tools_config) { subset.push(shell_tool); } assert_contains_tool_names(&tools, &subset); @@ -1488,15 +1492,16 @@ mod tests { #[test] #[ignore] fn test_parallel_support_flags() { - let model_family = find_family_for_model("gpt-5-codex"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.disable(Feature::ViewImageTool); features.enable(Feature::UnifiedExec); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); - let (tools, _) = build_specs(&config, None).build(); + let (tools, _) = build_specs(&tools_config, None).build(); assert!(!find_tool(&tools, "exec_command").supports_parallel_tool_calls); assert!(!find_tool(&tools, "write_stdin").supports_parallel_tool_calls); @@ -1507,14 +1512,16 @@ mod tests { #[test] fn test_test_model_family_includes_sync_tool() { - let model_family = find_family_for_model("test-gpt-5-codex"); + let config = test_config(); + let model_family = + ModelsManager::construct_model_family_offline("test-gpt-5-codex", &config); let mut features = Features::with_defaults(); features.disable(Feature::ViewImageTool); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); - let (tools, _) = build_specs(&config, None).build(); + let (tools, _) = build_specs(&tools_config, None).build(); assert!( tools @@ -1536,16 +1543,17 @@ mod tests { #[test] fn test_build_specs_mcp_tools_converted() { - let model_family = find_family_for_model("o3"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("o3", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); features.enable(Feature::WebSearchRequest); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); let (tools, _) = build_specs( - &config, + &tools_config, Some(HashMap::from([( "test_server/do_something_cool".to_string(), mcp_types::Tool { @@ -1630,10 +1638,11 @@ mod tests { #[test] fn test_build_specs_mcp_tools_sorted_by_name() { - let model_family = find_family_for_model("o3"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("o3", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); @@ -1687,7 +1696,7 @@ mod tests { ), ]); - let (tools, _) = build_specs(&config, Some(tools_map)).build(); + let (tools, _) = build_specs(&tools_config, Some(tools_map)).build(); // Only assert that the MCP tools themselves are sorted by fully-qualified name. let mcp_names: Vec<_> = tools @@ -1705,17 +1714,18 @@ mod tests { #[test] fn test_mcp_tool_property_missing_type_defaults_to_string() { - let model_family = find_family_for_model("gpt-5-codex"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); features.enable(Feature::WebSearchRequest); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); let (tools, _) = build_specs( - &config, + &tools_config, Some(HashMap::from([( "dash/search".to_string(), mcp_types::Tool { @@ -1761,17 +1771,18 @@ mod tests { #[test] fn test_mcp_tool_integer_normalized_to_number() { - let model_family = find_family_for_model("gpt-5-codex"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); features.enable(Feature::WebSearchRequest); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); let (tools, _) = build_specs( - &config, + &tools_config, Some(HashMap::from([( "dash/paginate".to_string(), mcp_types::Tool { @@ -1813,18 +1824,19 @@ mod tests { #[test] fn test_mcp_tool_array_without_items_gets_default_string_items() { - let model_family = find_family_for_model("gpt-5-codex"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); features.enable(Feature::WebSearchRequest); features.enable(Feature::ApplyPatchFreeform); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); let (tools, _) = build_specs( - &config, + &tools_config, Some(HashMap::from([( "dash/tags".to_string(), mcp_types::Tool { @@ -1869,17 +1881,18 @@ mod tests { #[test] fn test_mcp_tool_anyof_defaults_to_string() { - let model_family = find_family_for_model("gpt-5-codex"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); features.enable(Feature::WebSearchRequest); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); let (tools, _) = build_specs( - &config, + &tools_config, Some(HashMap::from([( "dash/value".to_string(), mcp_types::Tool { @@ -1980,16 +1993,17 @@ Examples of valid command strings: #[test] fn test_get_openai_tools_mcp_tools_with_additional_properties_schema() { - let model_family = find_family_for_model("gpt-5-codex"); + let config = test_config(); + let model_family = ModelsManager::construct_model_family_offline("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); features.enable(Feature::WebSearchRequest); - let config = ToolsConfig::new(&ToolsConfigParams { + let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, features: &features, }); let (tools, _) = build_specs( - &config, + &tools_config, Some(HashMap::from([( "test_server/do_something_cool".to_string(), mcp_types::Tool { From c4f3f566a5777a1aab86446bacc973f308b6a92e Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 11 Dec 2025 13:40:48 -0800 Subject: [PATCH 07/77] remove release script (#7885) --- codex-rs/scripts/create_github_release | 411 ------------------------- docs/contributing.md | 19 -- docs/release_management.md | 45 --- 3 files changed, 475 deletions(-) delete mode 100755 codex-rs/scripts/create_github_release delete mode 100644 docs/release_management.md diff --git a/codex-rs/scripts/create_github_release b/codex-rs/scripts/create_github_release deleted file mode 100755 index fffd987bc1..0000000000 --- a/codex-rs/scripts/create_github_release +++ /dev/null @@ -1,411 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import base64 -import json -import re -import subprocess -import sys - - -REPO = "openai/codex" -BRANCH_REF = "heads/main" -CARGO_TOML_PATH = "codex-rs/Cargo.toml" - - -def parse_args(argv: list[str]) -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Publish a tagged Codex release.") - parser.add_argument( - "-n", - "--dry-run", - action="store_true", - help="Print the version that would be used and exit before making changes.", - ) - parser.add_argument( - "--promote-alpha", - metavar="VERSION", - help="Promote an existing alpha tag (e.g., 0.56.0-alpha.5) by using its merge-base with main as the base commit.", - ) - - group = parser.add_mutually_exclusive_group() - group.add_argument( - "--publish-alpha", - action="store_true", - help="Publish the next alpha release for the upcoming minor version.", - ) - group.add_argument( - "--publish-release", - action="store_true", - help="Publish the next stable release by bumping the minor version.", - ) - parser.add_argument( - "--emergency-version-override", - help="Publish a specific version because tag was created for the previous release but it never succeeded. Value should be semver, e.g., `0.43.0-alpha.9`.", - ) - - args = parser.parse_args(argv[1:]) - if not ( - args.publish_alpha - or args.publish_release - or args.emergency_version_override - or args.promote_alpha - ): - parser.error( - "Must specify --publish-alpha, --publish-release, --promote-alpha, or --emergency-version-override." - ) - return args - - -def main(argv: list[str]) -> int: - args = parse_args(argv) - - ensure_release_not_in_progress() - - # Strip the leading "v" if present. - promote_alpha = args.promote_alpha - if promote_alpha and promote_alpha.startswith("v"): - promote_alpha = promote_alpha[1:] - - try: - if promote_alpha: - version = derive_release_version_from_alpha(promote_alpha) - elif args.emergency_version_override: - version = args.emergency_version_override - else: - version = determine_version(args) - print(f"Publishing version {version}") - if promote_alpha: - base_commit = get_promote_alpha_base_commit(promote_alpha) - if args.dry_run: - print( - f"Would publish version {version} using base commit {base_commit} derived from rust-v{promote_alpha}." - ) - return 0 - elif args.dry_run: - return 0 - - if not promote_alpha: - print("Fetching branch head...") - base_commit = get_branch_head() - print(f"Base commit: {base_commit}") - print("Fetching commit tree...") - base_tree = get_commit_tree(base_commit) - print(f"Base tree: {base_tree}") - print("Fetching Cargo.toml...") - current_contents = fetch_file_contents(base_commit) - print("Updating version...") - updated_contents = replace_version(current_contents, version) - print("Creating blob...") - blob_sha = create_blob(updated_contents) - print(f"Blob SHA: {blob_sha}") - print("Creating tree...") - tree_sha = create_tree(base_tree, blob_sha) - print(f"Tree SHA: {tree_sha}") - print("Creating commit...") - commit_sha = create_commit(version, tree_sha, base_commit) - print(f"Commit SHA: {commit_sha}") - print("Creating tag...") - tag_sha = create_tag(version, commit_sha) - print(f"Tag SHA: {tag_sha}") - print("Creating tag ref...") - create_tag_ref(version, tag_sha) - print("Done.") - except ReleaseError as error: - print(f"ERROR: {error}", file=sys.stderr) - return 1 - return 0 - - -class ReleaseError(RuntimeError): - pass - - -def run_gh_api(endpoint: str, *, method: str = "GET", payload: dict | None = None) -> dict: - print(f"Running gh api {method} {endpoint}") - command = [ - "gh", - "api", - endpoint, - "--method", - method, - "-H", - "Accept: application/vnd.github+json", - ] - json_payload = None - if payload is not None: - json_payload = json.dumps(payload) - print(f"Payload: {json_payload}") - command.extend(["-H", "Content-Type: application/json", "--input", "-"]) - result = subprocess.run(command, text=True, capture_output=True, input=json_payload) - if result.returncode != 0: - message = result.stderr.strip() or result.stdout.strip() or "gh api call failed" - raise ReleaseError(message) - try: - return json.loads(result.stdout or "{}") - except json.JSONDecodeError as error: - raise ReleaseError("Failed to parse response from gh api.") from error - - -def ensure_release_not_in_progress() -> None: - """Fail fast if a release workflow is already running or queued.""" - - statuses = ("in_progress", "queued") - runs: list[dict] = [] - for status in statuses: - response = run_gh_api( - f"/repos/{REPO}/actions/workflows/rust-release.yml/runs?per_page=50&status={status}" - ) - runs.extend(response.get("workflow_runs", [])) - - active_runs = [run for run in runs if run.get("status") in statuses] - if not active_runs: - return - - seen_ids: set[int] = set() - urls: list[str] = [] - for run in active_runs: - run_id = run.get("id") - if run_id in seen_ids: - continue - seen_ids.add(run_id) - urls.append(run.get("html_url", str(run_id))) - - raise ReleaseError( - "Release workflow already running or queued; wait or cancel it before publishing: " - + ", ".join(urls) - ) - - -def get_branch_head() -> str: - response = run_gh_api(f"/repos/{REPO}/git/refs/{BRANCH_REF}") - try: - return response["object"]["sha"] - except KeyError as error: - raise ReleaseError("Unable to determine branch head.") from error - - -def get_promote_alpha_base_commit(alpha_version: str) -> str: - tag_name = f"rust-v{alpha_version}" - tag_commit_sha = get_tag_commit_sha(tag_name) - return get_merge_base_with_main(tag_commit_sha) - - -def get_tag_commit_sha(tag_name: str) -> str: - response = run_gh_api(f"/repos/{REPO}/git/refs/tags/{tag_name}") - try: - sha = response["object"]["sha"] - obj_type = response["object"]["type"] - except KeyError as error: - raise ReleaseError(f"Unable to resolve tag {tag_name}.") from error - while obj_type == "tag": - tag_response = run_gh_api(f"/repos/{REPO}/git/tags/{sha}") - try: - sha = tag_response["object"]["sha"] - obj_type = tag_response["object"]["type"] - except KeyError as error: - raise ReleaseError(f"Unable to resolve annotated tag {tag_name}.") from error - if obj_type != "commit": - raise ReleaseError(f"Tag {tag_name} does not reference a commit.") - return sha - - -def get_merge_base_with_main(commit_sha: str) -> str: - response = run_gh_api(f"/repos/{REPO}/compare/main...{commit_sha}") - try: - return response["merge_base_commit"]["sha"] - except KeyError as error: - raise ReleaseError("Unable to determine merge base with main.") from error - - -def get_commit_tree(commit_sha: str) -> str: - response = run_gh_api(f"/repos/{REPO}/git/commits/{commit_sha}") - try: - return response["tree"]["sha"] - except KeyError as error: - raise ReleaseError("Commit response missing tree SHA.") from error - - -def fetch_file_contents(ref_sha: str) -> str: - response = run_gh_api(f"/repos/{REPO}/contents/{CARGO_TOML_PATH}?ref={ref_sha}") - try: - encoded_content = response["content"].replace("\n", "") - encoding = response.get("encoding", "") - except KeyError as error: - raise ReleaseError("Failed to fetch Cargo.toml contents.") from error - - if encoding != "base64": - raise ReleaseError(f"Unexpected Cargo.toml encoding: {encoding}") - - try: - return base64.b64decode(encoded_content).decode("utf-8") - except (ValueError, UnicodeDecodeError) as error: - raise ReleaseError("Failed to decode Cargo.toml contents.") from error - - -def replace_version(contents: str, version: str) -> str: - updated, matches = re.subn( - r'^version = "[^"]+"', f'version = "{version}"', contents, count=1, flags=re.MULTILINE - ) - if matches != 1: - raise ReleaseError("Unable to update version in Cargo.toml.") - return updated - - -def create_blob(content: str) -> str: - response = run_gh_api( - f"/repos/{REPO}/git/blobs", - method="POST", - payload={"content": content, "encoding": "utf-8"}, - ) - try: - return response["sha"] - except KeyError as error: - raise ReleaseError("Blob creation response missing SHA.") from error - - -def create_tree(base_tree_sha: str, blob_sha: str) -> str: - response = run_gh_api( - f"/repos/{REPO}/git/trees", - method="POST", - payload={ - "base_tree": base_tree_sha, - "tree": [ - { - "path": CARGO_TOML_PATH, - "mode": "100644", - "type": "blob", - "sha": blob_sha, - } - ], - }, - ) - try: - return response["sha"] - except KeyError as error: - raise ReleaseError("Tree creation response missing SHA.") from error - - -def create_commit(version: str, tree_sha: str, parent_sha: str) -> str: - response = run_gh_api( - f"/repos/{REPO}/git/commits", - method="POST", - payload={ - "message": f"Release {version}", - "tree": tree_sha, - "parents": [parent_sha], - }, - ) - try: - return response["sha"] - except KeyError as error: - raise ReleaseError("Commit creation response missing SHA.") from error - - -def create_tag(version: str, commit_sha: str) -> str: - tag_name = f"rust-v{version}" - response = run_gh_api( - f"/repos/{REPO}/git/tags", - method="POST", - payload={ - "tag": tag_name, - "message": f"Release {version}", - "object": commit_sha, - "type": "commit", - }, - ) - try: - return response["sha"] - except KeyError as error: - raise ReleaseError("Tag creation response missing SHA.") from error - - -def create_tag_ref(version: str, tag_sha: str) -> None: - tag_ref = f"refs/tags/rust-v{version}" - run_gh_api( - f"/repos/{REPO}/git/refs", - method="POST", - payload={"ref": tag_ref, "sha": tag_sha}, - ) - - -def determine_version(args: argparse.Namespace) -> str: - latest_version = get_latest_release_version() - # When determining the next version after the current release, - # we should always increment the minor version, but reset the - # patch to zero. In practice, `patch` should only be non-zero if - # --emergency-version-override was used. - major, minor, _patch = parse_semver(latest_version) - next_minor_version = format_version(major, minor + 1, 0) - - if args.publish_release: - return next_minor_version - - alpha_prefix = f"{next_minor_version}-alpha." - releases = list_releases() - highest_alpha = 0 - found_alpha = False - for release in releases: - tag = release.get("tag_name", "") - candidate = strip_tag_prefix(tag) - if candidate and candidate.startswith(alpha_prefix): - suffix = candidate[len(alpha_prefix) :] - try: - alpha_number = int(suffix) - except ValueError: - continue - highest_alpha = max(highest_alpha, alpha_number) - found_alpha = True - - if found_alpha: - return f"{alpha_prefix}{highest_alpha + 1}" - return f"{alpha_prefix}1" - - -def get_latest_release_version() -> str: - response = run_gh_api(f"/repos/{REPO}/releases/latest") - tag = response.get("tag_name") - version = strip_tag_prefix(tag) - if not version: - raise ReleaseError("Latest release tag has unexpected format.") - return version - - -def list_releases() -> list[dict]: - response = run_gh_api(f"/repos/{REPO}/releases?per_page=100") - if not isinstance(response, list): - raise ReleaseError("Unexpected response when listing releases.") - return response - - -def strip_tag_prefix(tag: str | None) -> str | None: - if not tag: - return None - prefix = "rust-v" - if not tag.startswith(prefix): - return None - return tag[len(prefix) :] - - -def parse_semver(version: str) -> tuple[int, int, int]: - parts = version.split(".") - if len(parts) != 3: - raise ReleaseError(f"Unexpected version format: {version}") - try: - return int(parts[0]), int(parts[1]), int(parts[2]) - except ValueError as error: - raise ReleaseError(f"Version components must be integers: {version}") from error - - -def format_version(major: int, minor: int, patch: int) -> str: - return f"{major}.{minor}.{patch}" - - -def derive_release_version_from_alpha(alpha_version: str) -> str: - match = re.match(r"^(\d+)\.(\d+)\.(\d+)-alpha\.(\d+)$", alpha_version) - if match is None: - raise ReleaseError(f"Unexpected alpha version format: {alpha_version}") - return f"{match.group(1)}.{match.group(2)}.{match.group(3)}" - - -if __name__ == "__main__": - sys.exit(main(sys.argv)) diff --git a/docs/contributing.md b/docs/contributing.md index 983d64e6dc..ec188631d1 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -71,25 +71,6 @@ No special Git commands, email attachments, or commit footers required. The **DCO check** blocks merges until every commit in the PR carries the footer (with squash this is just the one). -### Releasing `codex` - -_For admins only._ - -Make sure you are on `main` and have no local changes. Then run: - -```shell -VERSION=0.2.0 # Can also be 0.2.0-alpha.1 or any valid Rust version. -./codex-rs/scripts/create_github_release.sh "$VERSION" -``` - -This will make a local commit on top of `main` with `version` set to `$VERSION` in `codex-rs/Cargo.toml` (note that on `main`, we leave the version as `version = "0.0.0"`). - -This will push the commit using the tag `rust-v${VERSION}`, which in turn kicks off [the release workflow](../.github/workflows/rust-release.yml). This will create a new GitHub Release named `$VERSION`. - -If everything looks good in the generated GitHub Release, uncheck the **pre-release** box so it is the latest release. - -Create a PR to update [`Cask/c/codex.rb`](https://github.com/Homebrew/homebrew-cask/blob/main/Formula/c/codex.rb) on Homebrew. - ### Security & responsible AI Have you discovered a vulnerability or have concerns about model output? Please e-mail **security@openai.com** and we will respond promptly. diff --git a/docs/release_management.md b/docs/release_management.md deleted file mode 100644 index 05148b1c93..0000000000 --- a/docs/release_management.md +++ /dev/null @@ -1,45 +0,0 @@ -# Release Management - -Currently, we made Codex binaries available in three places: - -- GitHub Releases https://github.com/openai/codex/releases/ -- `@openai/codex` on npm: https://www.npmjs.com/package/@openai/codex -- `codex` on Homebrew: https://formulae.brew.sh/cask/codex - -# Cutting a Release - -Run the `codex-rs/scripts/create_github_release` script in the repository to publish a new release. The script will choose the appropriate version number depending on the type of release you are creating. - -To cut a new alpha release from `main` (feel free to cut alphas liberally): - -``` -./codex-rs/scripts/create_github_release --publish-alpha -``` - -To cut a new _public_ release from `main` (which requires more caution), run: - -``` -./codex-rs/scripts/create_github_release --publish-release -``` - -TIP: Add the `--dry-run` flag to report the next version number for the respective release and exit. - -Running the publishing script will kick off a GitHub Action to build the release, so go to https://github.com/openai/codex/actions/workflows/rust-release.yml to find the corresponding workflow. (Note: we should automate finding the workflow URL with `gh`.) - -When the workflow finishes, the GitHub Release is "done," but you still have to consider npm and Homebrew. - -## Publishing to npm - -The GitHub Action is responsible for publishing to npm. - -## Publishing to Homebrew - -For Homebrew, we ship Codex as a cask. Homebrew's automation system checks our GitHub repo every few hours for a new release and will open a PR to update the cask with the latest binary. - -Inevitably, you just have to refresh this page periodically to see if the release has been picked up by their automation system: - -https://github.com/Homebrew/homebrew-cask/pulls?q=%3Apr+codex - -For reference, our Homebrew cask lives at: - -https://github.com/Homebrew/homebrew-cask/blob/main/Casks/c/codex.rb From 3e81ed4b918680519c620cc103c865b7be41bbfe Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Thu, 11 Dec 2025 13:51:27 -0800 Subject: [PATCH 08/77] Elevated Sandbox 3 (#7809) dedicated sandbox command runner exe. --- codex-rs/windows-sandbox-rs/Cargo.toml | 4 + .../src/bin/command_runner.rs | 12 + .../src/command_runner_win.rs | 225 ++++++++++++++++++ codex-rs/windows-sandbox-rs/src/lib.rs | 16 ++ 4 files changed, 257 insertions(+) create mode 100644 codex-rs/windows-sandbox-rs/src/bin/command_runner.rs create mode 100644 codex-rs/windows-sandbox-rs/src/command_runner_win.rs diff --git a/codex-rs/windows-sandbox-rs/Cargo.toml b/codex-rs/windows-sandbox-rs/Cargo.toml index ac290101cc..4e75421601 100644 --- a/codex-rs/windows-sandbox-rs/Cargo.toml +++ b/codex-rs/windows-sandbox-rs/Cargo.toml @@ -13,6 +13,10 @@ path = "src/lib.rs" name = "codex-windows-sandbox-setup" path = "src/bin/setup_main.rs" +[[bin]] +name = "codex-command-runner" +path = "src/bin/command_runner.rs" + [dependencies] anyhow = "1.0" base64 = { workspace = true } diff --git a/codex-rs/windows-sandbox-rs/src/bin/command_runner.rs b/codex-rs/windows-sandbox-rs/src/bin/command_runner.rs new file mode 100644 index 0000000000..e84a153549 --- /dev/null +++ b/codex-rs/windows-sandbox-rs/src/bin/command_runner.rs @@ -0,0 +1,12 @@ +#[path = "../command_runner_win.rs"] +mod win; + +#[cfg(target_os = "windows")] +fn main() -> anyhow::Result<()> { + win::main() +} + +#[cfg(not(target_os = "windows"))] +fn main() { + panic!("codex-command-runner is Windows-only"); +} diff --git a/codex-rs/windows-sandbox-rs/src/command_runner_win.rs b/codex-rs/windows-sandbox-rs/src/command_runner_win.rs new file mode 100644 index 0000000000..806a8777da --- /dev/null +++ b/codex-rs/windows-sandbox-rs/src/command_runner_win.rs @@ -0,0 +1,225 @@ +#![cfg(target_os = "windows")] + +use anyhow::Context; +use anyhow::Result; +use codex_windows_sandbox::allow_null_device; +use codex_windows_sandbox::convert_string_sid_to_sid; +use codex_windows_sandbox::create_process_as_user; +use codex_windows_sandbox::create_readonly_token_with_cap_from; +use codex_windows_sandbox::create_workspace_write_token_with_cap_from; +use codex_windows_sandbox::get_current_token_for_restriction; +use codex_windows_sandbox::log_note; +use codex_windows_sandbox::parse_policy; +use codex_windows_sandbox::to_wide; +use codex_windows_sandbox::SandboxPolicy; +use serde::Deserialize; +use std::collections::HashMap; +use std::ffi::c_void; +use std::path::PathBuf; +use windows_sys::Win32::Foundation::CloseHandle; +use windows_sys::Win32::Foundation::GetLastError; +use windows_sys::Win32::Foundation::HANDLE; +use windows_sys::Win32::Storage::FileSystem::CreateFileW; +use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ; +use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE; +use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING; +use windows_sys::Win32::System::JobObjects::AssignProcessToJobObject; +use windows_sys::Win32::System::JobObjects::CreateJobObjectW; +use windows_sys::Win32::System::JobObjects::JobObjectExtendedLimitInformation; +use windows_sys::Win32::System::JobObjects::SetInformationJobObject; +use windows_sys::Win32::System::JobObjects::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; +use windows_sys::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; +use windows_sys::Win32::System::Threading::TerminateProcess; +use windows_sys::Win32::System::Threading::WaitForSingleObject; +use windows_sys::Win32::System::Threading::INFINITE; + +#[derive(Debug, Deserialize)] +struct RunnerRequest { + policy_json_or_preset: String, + // Writable location for logs (sandbox user's .codex). + codex_home: PathBuf, + // Real user's CODEX_HOME for shared data (caps, config). + real_codex_home: PathBuf, + cap_sid: String, + command: Vec, + cwd: PathBuf, + env_map: HashMap, + timeout_ms: Option, + stdin_pipe: String, + stdout_pipe: String, + stderr_pipe: String, +} + +const WAIT_TIMEOUT: u32 = 0x0000_0102; + +unsafe fn create_job_kill_on_close() -> Result { + let h = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()); + if h == 0 { + return Err(anyhow::anyhow!("CreateJobObjectW failed")); + } + let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed(); + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let ok = SetInformationJobObject( + h, + JobObjectExtendedLimitInformation, + &mut limits as *mut _ as *mut _, + std::mem::size_of::() as u32, + ); + if ok == 0 { + return Err(anyhow::anyhow!("SetInformationJobObject failed")); + } + Ok(h) +} + +pub fn main() -> Result<()> { + let mut input = String::new(); + let mut args = std::env::args().skip(1); + if let Some(first) = args.next() { + if let Some(rest) = first.strip_prefix("--request-file=") { + let req_path = PathBuf::from(rest); + input = std::fs::read_to_string(&req_path).context("read request file")?; + } + } + if input.is_empty() { + anyhow::bail!("runner: no request-file provided"); + } + let req: RunnerRequest = serde_json::from_str(&input).context("parse runner request json")?; + let log_dir = Some(req.codex_home.as_path()); + log_note( + &format!( + "runner start cwd={} cmd={:?} real_codex_home={}", + req.cwd.display(), + req.command, + req.real_codex_home.display() + ), + Some(&req.codex_home), + ); + + let policy = parse_policy(&req.policy_json_or_preset).context("parse policy_json_or_preset")?; + let psid_cap: *mut c_void = unsafe { convert_string_sid_to_sid(&req.cap_sid).unwrap() }; + + // Create restricted token from current process token. + let base = unsafe { get_current_token_for_restriction()? }; + let token_res: Result<(HANDLE, *mut c_void)> = unsafe { + match &policy { + SandboxPolicy::ReadOnly => create_readonly_token_with_cap_from(base, psid_cap), + SandboxPolicy::WorkspaceWrite { .. } => { + create_workspace_write_token_with_cap_from(base, psid_cap) + } + SandboxPolicy::DangerFullAccess => unreachable!(), + } + }; + let (h_token, psid_to_use) = token_res?; + unsafe { + CloseHandle(base); + } + unsafe { + allow_null_device(psid_to_use); + } + + // Open named pipes for stdio. + let open_pipe = |name: &str, access: u32| -> Result { + let path = to_wide(name); + let handle = unsafe { + CreateFileW( + path.as_ptr(), + access, + 0, + std::ptr::null_mut(), + OPEN_EXISTING, + 0, + 0, + ) + }; + if handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE { + let err = unsafe { GetLastError() }; + log_note( + &format!("CreateFileW failed for pipe {name}: {err}"), + Some(&req.codex_home), + ); + return Err(anyhow::anyhow!("CreateFileW failed for pipe {name}: {err}")); + } + Ok(handle) + }; + let h_stdin = open_pipe(&req.stdin_pipe, FILE_GENERIC_READ)?; + let h_stdout = open_pipe(&req.stdout_pipe, FILE_GENERIC_WRITE)?; + let h_stderr = open_pipe(&req.stderr_pipe, FILE_GENERIC_WRITE)?; + + // Build command and env, spawn with CreateProcessAsUserW. + let spawn_result = unsafe { + create_process_as_user( + h_token, + &req.command, + &req.cwd, + &req.env_map, + Some(&req.codex_home), + Some((h_stdin, h_stdout, h_stderr)), + ) + }; + let (proc_info, _si) = match spawn_result { + Ok(v) => v, + Err(e) => { + log_note(&format!("runner: spawn failed: {e:?}"), log_dir); + unsafe { + CloseHandle(h_stdin); + CloseHandle(h_stdout); + CloseHandle(h_stderr); + CloseHandle(h_token); + } + return Err(e); + } + }; + + // Optional job kill on close. + let h_job = unsafe { create_job_kill_on_close().ok() }; + if let Some(job) = h_job { + unsafe { + let _ = AssignProcessToJobObject(job, proc_info.hProcess); + } + } + + // Wait for process. + let wait_res = unsafe { + WaitForSingleObject( + proc_info.hProcess, + req.timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE), + ) + }; + let timed_out = wait_res == WAIT_TIMEOUT; + + let exit_code: i32; + unsafe { + if timed_out { + let _ = TerminateProcess(proc_info.hProcess, 1); + exit_code = 128 + 64; + } else { + let mut raw_exit: u32 = 1; + windows_sys::Win32::System::Threading::GetExitCodeProcess( + proc_info.hProcess, + &mut raw_exit, + ); + exit_code = raw_exit as i32; + } + if proc_info.hThread != 0 { + CloseHandle(proc_info.hThread); + } + if proc_info.hProcess != 0 { + CloseHandle(proc_info.hProcess); + } + CloseHandle(h_stdin); + CloseHandle(h_stdout); + CloseHandle(h_stderr); + CloseHandle(h_token); + if let Some(job) = h_job { + CloseHandle(job); + } + } + if exit_code != 0 { + eprintln!("runner child exited with code {}", exit_code); + } + log_note( + &format!("runner exit pid={} code={}", proc_info.hProcess, exit_code), + log_dir, + ); + std::process::exit(exit_code); +} diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index 56b59e387c..c4367e6124 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -12,6 +12,8 @@ windows_modules!( #[path = "setup_orchestrator.rs"] mod setup; +#[cfg(target_os = "windows")] +pub use acl::allow_null_device; #[cfg(target_os = "windows")] pub use acl::ensure_allow_write_aces; #[cfg(target_os = "windows")] @@ -33,6 +35,12 @@ pub use logging::log_note; #[cfg(target_os = "windows")] pub use logging::LOG_FILE_NAME; #[cfg(target_os = "windows")] +pub use policy::parse_policy; +#[cfg(target_os = "windows")] +pub use policy::SandboxPolicy; +#[cfg(target_os = "windows")] +pub use process::create_process_as_user; +#[cfg(target_os = "windows")] pub use setup::run_elevated_setup; #[cfg(target_os = "windows")] pub use setup::run_setup_refresh; @@ -43,11 +51,19 @@ pub use setup::SETUP_VERSION; #[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; +#[cfg(target_os = "windows")] +pub use token::create_workspace_write_token_with_cap_from; +#[cfg(target_os = "windows")] +pub use token::get_current_token_for_restriction; +#[cfg(target_os = "windows")] pub use windows_impl::run_windows_sandbox_capture; #[cfg(target_os = "windows")] pub use windows_impl::CaptureResult; #[cfg(target_os = "windows")] pub use winutil::string_from_sid_bytes; +#[cfg(target_os = "windows")] +pub use winutil::to_wide; #[cfg(not(target_os = "windows"))] pub use stub::apply_world_writable_scan_and_denies; From b7fa7ca8e9ac678e48e41e48984334d435df64f2 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 11 Dec 2025 14:06:07 -0800 Subject: [PATCH 09/77] Update Model Info (#7853) --- .../app-server/tests/common/models_cache.rs | 11 ++ codex-rs/codex-api/src/endpoint/models.rs | 10 ++ .../codex-api/tests/models_integration.rs | 11 ++ codex-rs/core/src/config/mod.rs | 2 +- codex-rs/core/src/config/types.rs | 8 -- .../core/src/openai_models/model_family.rs | 130 +++++++++++++++++- .../core/src/openai_models/models_manager.rs | 13 +- .../core/src/tools/handlers/apply_patch.rs | 9 -- codex-rs/core/src/tools/spec.rs | 2 +- codex-rs/core/src/truncate.rs | 11 ++ codex-rs/core/tests/responses_headers.rs | 2 +- codex-rs/core/tests/suite/remote_models.rs | 20 +++ codex-rs/protocol/src/openai_models.rs | 66 +++++++-- codex-rs/tui/src/history_cell.rs | 2 +- codex-rs/tui2/src/history_cell.rs | 2 +- 15 files changed, 259 insertions(+), 40 deletions(-) diff --git a/codex-rs/app-server/tests/common/models_cache.rs b/codex-rs/app-server/tests/common/models_cache.rs index 8306e34394..f1ff8c5a31 100644 --- a/codex-rs/app-server/tests/common/models_cache.rs +++ b/codex-rs/app-server/tests/common/models_cache.rs @@ -6,6 +6,8 @@ use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelPreset; use codex_protocol::openai_models::ModelVisibility; +use codex_protocol::openai_models::ReasoningSummaryFormat; +use codex_protocol::openai_models::TruncationPolicyConfig; use serde_json::json; use std::path::Path; @@ -28,6 +30,15 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo { priority, upgrade: preset.upgrade.as_ref().map(|u| u.id.clone()), base_instructions: 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: None, + reasoning_summary_format: ReasoningSummaryFormat::None, + experimental_supported_tools: Vec::new(), } } diff --git a/codex-rs/codex-api/src/endpoint/models.rs b/codex-rs/codex-api/src/endpoint/models.rs index 5de08432f0..b15f07fca2 100644 --- a/codex-rs/codex-api/src/endpoint/models.rs +++ b/codex-rs/codex-api/src/endpoint/models.rs @@ -219,6 +219,16 @@ mod tests { "supported_in_api": true, "priority": 1, "upgrade": null, + "base_instructions": null, + "supports_reasoning_summaries": false, + "support_verbosity": false, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": {"mode": "bytes", "limit": 10_000}, + "supports_parallel_tool_calls": false, + "context_window": null, + "reasoning_summary_format": "none", + "experimental_supported_tools": [], })) .unwrap(), ], diff --git a/codex-rs/codex-api/tests/models_integration.rs b/codex-rs/codex-api/tests/models_integration.rs index 20eb64d5cd..93baffd356 100644 --- a/codex-rs/codex-api/tests/models_integration.rs +++ b/codex-rs/codex-api/tests/models_integration.rs @@ -11,6 +11,8 @@ use codex_protocol::openai_models::ModelVisibility; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; +use codex_protocol::openai_models::ReasoningSummaryFormat; +use codex_protocol::openai_models::TruncationPolicyConfig; use http::HeaderMap; use http::Method; use wiremock::Mock; @@ -78,6 +80,15 @@ async fn models_client_hits_models_endpoint() { priority: 1, upgrade: None, base_instructions: 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: None, + reasoning_summary_format: ReasoningSummaryFormat::None, + experimental_supported_tools: Vec::new(), }], etag: String::new(), }; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 6a95a860f2..4c1a073c57 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -7,7 +7,6 @@ use crate::config::types::Notifications; use crate::config::types::OtelConfig; use crate::config::types::OtelConfigToml; use crate::config::types::OtelExporterKind; -use crate::config::types::ReasoningSummaryFormat; use crate::config::types::SandboxWorkspaceWrite; use crate::config::types::ShellEnvironmentPolicy; use crate::config::types::ShellEnvironmentPolicyToml; @@ -39,6 +38,7 @@ use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::TrustLevel; use codex_protocol::config_types::Verbosity; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::openai_models::ReasoningSummaryFormat; use codex_rmcp_client::OAuthCredentialsStoreMode; use codex_utils_absolute_path::AbsolutePathBufGuard; use dirs::home_dir; diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index 6648e288a5..ca16b7a560 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -522,14 +522,6 @@ impl From for ShellEnvironmentPolicy { } } -#[derive(Deserialize, Debug, Clone, PartialEq, Eq, Default, Hash)] -#[serde(rename_all = "kebab-case")] -pub enum ReasoningSummaryFormat { - #[default] - None, - Experimental, -} - #[cfg(test)] mod tests { use super::*; diff --git a/codex-rs/core/src/openai_models/model_family.rs b/codex-rs/core/src/openai_models/model_family.rs index 1d6181c6d9..4e3375c580 100644 --- a/codex-rs/core/src/openai_models/model_family.rs +++ b/codex-rs/core/src/openai_models/model_family.rs @@ -1,12 +1,12 @@ 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::ReasoningEffort; +use codex_protocol::openai_models::ReasoningSummaryFormat; use crate::config::Config; -use crate::config::types::ReasoningSummaryFormat; -use crate::tools::handlers::apply_patch::ApplyPatchToolType; use crate::truncate::TruncationPolicy; -use codex_protocol::openai_models::ConfigShellToolType; /// The `instructions` field in the payload sent to a model should always start /// with this content. @@ -101,14 +101,53 @@ impl ModelFamily { pub fn with_remote_overrides(mut self, remote_models: Vec) -> Self { for model in remote_models { if model.slug == self.slug { - self.default_reasoning_effort = Some(model.default_reasoning_level); - self.shell_type = model.shell_type; - self.base_instructions = model.base_instructions.unwrap_or(self.base_instructions); + self.apply_remote_overrides(model); } } self } + fn apply_remote_overrides(&mut self, model: ModelInfo) { + let ModelInfo { + slug: _, + display_name: _, + description: _, + default_reasoning_level, + supported_reasoning_levels: _, + shell_type, + visibility: _, + minimal_client_version: _, + supported_in_api: _, + priority: _, + upgrade: _, + base_instructions, + supports_reasoning_summaries, + support_verbosity, + default_verbosity, + apply_patch_tool_type, + truncation_policy, + supports_parallel_tool_calls, + context_window, + reasoning_summary_format, + experimental_supported_tools, + } = model; + + self.default_reasoning_effort = Some(default_reasoning_level); + self.shell_type = shell_type; + if let Some(base) = base_instructions { + self.base_instructions = base; + } + self.supports_reasoning_summaries = supports_reasoning_summaries; + self.support_verbosity = support_verbosity; + self.default_verbosity = default_verbosity; + self.apply_patch_tool_type = apply_patch_tool_type; + self.truncation_policy = truncation_policy.into(); + self.supports_parallel_tool_calls = supports_parallel_tool_calls; + self.context_window = context_window; + self.reasoning_summary_format = reasoning_summary_format; + self.experimental_supported_tools = experimental_supported_tools; + } + pub fn auto_compact_token_limit(&self) -> Option { self.auto_compact_token_limit .or(self.context_window.map(Self::default_auto_compact_limit)) @@ -356,6 +395,7 @@ mod tests { use codex_protocol::openai_models::ClientVersion; use codex_protocol::openai_models::ModelVisibility; use codex_protocol::openai_models::ReasoningEffortPreset; + use codex_protocol::openai_models::TruncationPolicyConfig; fn remote(slug: &str, effort: ReasoningEffort, shell: ConfigShellToolType) -> ModelInfo { ModelInfo { @@ -374,6 +414,15 @@ mod tests { priority: 1, upgrade: None, base_instructions: 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: None, + reasoning_summary_format: ReasoningSummaryFormat::None, + experimental_supported_tools: Vec::new(), } } @@ -422,4 +471,73 @@ mod tests { ); assert_eq!(updated.shell_type, family.shell_type); } + + #[test] + fn remote_overrides_apply_extended_metadata() { + let family = model_family!( + "gpt-5.1", + "gpt-5.1", + supports_reasoning_summaries: false, + support_verbosity: false, + default_verbosity: None, + apply_patch_tool_type: Some(ApplyPatchToolType::Function), + supports_parallel_tool_calls: false, + experimental_supported_tools: vec!["local".to_string()], + truncation_policy: TruncationPolicy::Bytes(10_000), + context_window: Some(100), + reasoning_summary_format: ReasoningSummaryFormat::None, + ); + + let updated = family.with_remote_overrides(vec![ModelInfo { + slug: "gpt-5.1".to_string(), + display_name: "gpt-5.1".to_string(), + description: Some("desc".to_string()), + default_reasoning_level: ReasoningEffort::High, + supported_reasoning_levels: vec![ReasoningEffortPreset { + effort: ReasoningEffort::High, + description: "High".to_string(), + }], + shell_type: ConfigShellToolType::ShellCommand, + visibility: ModelVisibility::List, + minimal_client_version: ClientVersion(0, 1, 0), + supported_in_api: true, + priority: 10, + upgrade: None, + base_instructions: Some("Remote instructions".to_string()), + supports_reasoning_summaries: true, + support_verbosity: true, + default_verbosity: Some(Verbosity::High), + apply_patch_tool_type: Some(ApplyPatchToolType::Freeform), + truncation_policy: TruncationPolicyConfig::tokens(2_000), + supports_parallel_tool_calls: true, + context_window: Some(400_000), + reasoning_summary_format: ReasoningSummaryFormat::Experimental, + experimental_supported_tools: vec!["alpha".to_string(), "beta".to_string()], + }]); + + assert_eq!( + updated.default_reasoning_effort, + Some(ReasoningEffort::High) + ); + assert!(updated.supports_reasoning_summaries); + assert!(updated.support_verbosity); + assert_eq!(updated.default_verbosity, Some(Verbosity::High)); + assert_eq!(updated.shell_type, ConfigShellToolType::ShellCommand); + assert_eq!( + updated.apply_patch_tool_type, + Some(ApplyPatchToolType::Freeform) + ); + assert_eq!(updated.truncation_policy, TruncationPolicy::Tokens(2_000)); + assert!(updated.supports_parallel_tool_calls); + assert_eq!(updated.context_window, Some(400_000)); + assert_eq!( + updated.reasoning_summary_format, + ReasoningSummaryFormat::Experimental + ); + assert_eq!( + updated.experimental_supported_tools, + vec!["alpha".to_string(), "beta".to_string()] + ); + assert_eq!(updated.base_instructions, "Remote instructions"); + } } diff --git a/codex-rs/core/src/openai_models/models_manager.rs b/codex-rs/core/src/openai_models/models_manager.rs index 823293b8b7..b383079f44 100644 --- a/codex-rs/core/src/openai_models/models_manager.rs +++ b/codex-rs/core/src/openai_models/models_manager.rs @@ -206,7 +206,7 @@ impl ModelsManager { /// Convert remote model metadata into picker-ready presets, marking defaults. async fn build_available_models(&self) { let mut available_models = self.remote_models.read().await.clone(); - available_models.sort_by(|a, b| b.priority.cmp(&a.priority)); + available_models.sort_by(|a, b| a.priority.cmp(&b.priority)); let mut model_presets: Vec = available_models .into_iter() .map(Into::into) @@ -279,6 +279,15 @@ mod tests { "priority": priority, "upgrade": null, "base_instructions": null, + "supports_reasoning_summaries": false, + "support_verbosity": false, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": {"mode": "bytes", "limit": 10_000}, + "supports_parallel_tool_calls": false, + "context_window": null, + "reasoning_summary_format": "none", + "experimental_supported_tools": [], })) .expect("valid model") } @@ -306,7 +315,7 @@ mod tests { let server = MockServer::start().await; let remote_models = vec![ remote_model("priority-low", "Low", 1), - remote_model("priority-high", "High", 10), + remote_model("priority-high", "High", 0), ]; let models_mock = mount_models_once( &server, diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 5b8a04b388..14a481f4ea 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -26,8 +26,6 @@ use crate::tools::sandboxing::ToolCtx; use crate::tools::spec::ApplyPatchToolArgs; use crate::tools::spec::JsonSchema; use async_trait::async_trait; -use serde::Deserialize; -use serde::Serialize; pub struct ApplyPatchHandler; @@ -161,13 +159,6 @@ impl ToolHandler for ApplyPatchHandler { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[serde(rename_all = "snake_case")] -pub enum ApplyPatchToolType { - Freeform, - Function, -} - #[allow(clippy::too_many_arguments)] pub(crate) async fn intercept_apply_patch( command: &[String], diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 11061d4d35..ea445e8789 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -4,10 +4,10 @@ use crate::features::Feature; use crate::features::Features; use crate::openai_models::model_family::ModelFamily; use crate::tools::handlers::PLAN_TOOL; -use crate::tools::handlers::apply_patch::ApplyPatchToolType; use crate::tools::handlers::apply_patch::create_apply_patch_freeform_tool; use crate::tools::handlers::apply_patch::create_apply_patch_json_tool; use crate::tools::registry::ToolRegistryBuilder; +use codex_protocol::openai_models::ApplyPatchToolType; use codex_protocol::openai_models::ConfigShellToolType; use serde::Deserialize; use serde::Serialize; diff --git a/codex-rs/core/src/truncate.rs b/codex-rs/core/src/truncate.rs index 1c710ba108..9f0672363e 100644 --- a/codex-rs/core/src/truncate.rs +++ b/codex-rs/core/src/truncate.rs @@ -4,6 +4,8 @@ use crate::config::Config; use codex_protocol::models::FunctionCallOutputContentItem; +use codex_protocol::openai_models::TruncationMode; +use codex_protocol::openai_models::TruncationPolicyConfig; const APPROX_BYTES_PER_TOKEN: usize = 4; @@ -13,6 +15,15 @@ pub enum TruncationPolicy { Tokens(usize), } +impl From for TruncationPolicy { + fn from(config: TruncationPolicyConfig) -> Self { + match config.mode { + TruncationMode::Bytes => Self::Bytes(config.limit as usize), + TruncationMode::Tokens => Self::Tokens(config.limit as usize), + } + } +} + impl TruncationPolicy { /// Scale the underlying budget by `multiplier`, rounding up to avoid under-budgeting. pub fn mul(self, multiplier: f64) -> Self { diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 934c327a6c..0288050205 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -10,11 +10,11 @@ use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::ResponseItem; use codex_core::WireApi; -use codex_core::config::types::ReasoningSummaryFormat; use codex_core::openai_models::models_manager::ModelsManager; use codex_otel::otel_event_manager::OtelEventManager; use codex_protocol::ConversationId; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::openai_models::ReasoningSummaryFormat; use codex_protocol::protocol::SessionSource; use core_test_support::load_default_config_for_test; use core_test_support::responses; diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index 707ab6fa45..bf01196c78 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -25,6 +25,8 @@ use codex_protocol::openai_models::ModelVisibility; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::ReasoningEffortPreset; +use codex_protocol::openai_models::ReasoningSummaryFormat; +use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::user_input::UserInput; use core_test_support::load_default_config_for_test; use core_test_support::responses::ev_assistant_message; @@ -75,6 +77,15 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { priority: 1, upgrade: None, base_instructions: 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: None, + reasoning_summary_format: ReasoningSummaryFormat::None, + experimental_supported_tools: Vec::new(), }; let models_mock = mount_models_once( @@ -206,6 +217,15 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { priority: 1, upgrade: None, base_instructions: Some(remote_base.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: None, + reasoning_summary_format: ReasoningSummaryFormat::None, + experimental_supported_tools: Vec::new(), }; mount_models_once( &server, diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs index c5500f1cc5..5afaad15c5 100644 --- a/codex-rs/protocol/src/openai_models.rs +++ b/codex-rs/protocol/src/openai_models.rs @@ -8,6 +8,8 @@ use strum_macros::Display; use strum_macros::EnumIter; use ts_rs::TS; +use crate::config_types::Verbosity; + /// See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning #[derive( Debug, @@ -112,6 +114,51 @@ pub enum ConfigShellToolType { ShellCommand, } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, TS, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ApplyPatchToolType { + Freeform, + Function, +} + +#[derive(Deserialize, Debug, Clone, PartialEq, Eq, Default, Hash, TS, JsonSchema, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ReasoningSummaryFormat { + #[default] + None, + Experimental, +} + +/// Server-provided truncation policy metadata for a model. +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum TruncationMode { + Bytes, + Tokens, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] +pub struct TruncationPolicyConfig { + pub mode: TruncationMode, + pub limit: i64, +} + +impl TruncationPolicyConfig { + pub const fn bytes(limit: i64) -> Self { + Self { + mode: TruncationMode::Bytes, + limit, + } + } + + pub const fn tokens(limit: i64) -> Self { + Self { + mode: TruncationMode::Tokens, + limit, + } + } +} + /// Semantic version triple encoded as an array in JSON (e.g. [0, 62, 0]). #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] pub struct ClientVersion(pub i32, pub i32, pub i32); @@ -121,22 +168,25 @@ pub struct ClientVersion(pub i32, pub i32, pub i32); pub struct ModelInfo { pub slug: String, pub display_name: String, - #[serde(default)] pub description: Option, pub default_reasoning_level: ReasoningEffort, pub supported_reasoning_levels: Vec, pub shell_type: ConfigShellToolType, - #[serde(default = "default_visibility")] pub visibility: ModelVisibility, pub minimal_client_version: ClientVersion, - #[serde(default)] pub supported_in_api: bool, - #[serde(default)] pub priority: i32, - #[serde(default)] pub upgrade: Option, - #[serde(default)] pub base_instructions: Option, + pub supports_reasoning_summaries: bool, + pub support_verbosity: bool, + pub default_verbosity: Option, + pub apply_patch_tool_type: Option, + pub truncation_policy: TruncationPolicyConfig, + pub supports_parallel_tool_calls: bool, + pub context_window: Option, + pub reasoning_summary_format: ReasoningSummaryFormat, + pub experimental_supported_tools: Vec, } /// Response wrapper for `/models`. @@ -147,10 +197,6 @@ pub struct ModelsResponse { pub etag: String, } -fn default_visibility() -> ModelVisibility { - ModelVisibility::None -} - // convert ModelInfo to ModelPreset impl From for ModelPreset { fn from(info: ModelInfo) -> Self { diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 4147067366..dffe7eba2e 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -26,12 +26,12 @@ use base64::Engine; use codex_common::format_env_display::format_env_display; use codex_core::config::Config; use codex_core::config::types::McpServerTransportConfig; -use codex_core::config::types::ReasoningSummaryFormat; use codex_core::protocol::FileChange; use codex_core::protocol::McpAuthStatus; use codex_core::protocol::McpInvocation; use codex_core::protocol::SessionConfiguredEvent; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; +use codex_protocol::openai_models::ReasoningSummaryFormat; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; use codex_protocol::plan_tool::UpdatePlanArgs; diff --git a/codex-rs/tui2/src/history_cell.rs b/codex-rs/tui2/src/history_cell.rs index 4147067366..dffe7eba2e 100644 --- a/codex-rs/tui2/src/history_cell.rs +++ b/codex-rs/tui2/src/history_cell.rs @@ -26,12 +26,12 @@ use base64::Engine; use codex_common::format_env_display::format_env_display; use codex_core::config::Config; use codex_core::config::types::McpServerTransportConfig; -use codex_core::config::types::ReasoningSummaryFormat; use codex_core::protocol::FileChange; use codex_core::protocol::McpAuthStatus; use codex_core::protocol::McpInvocation; use codex_core::protocol::SessionConfiguredEvent; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; +use codex_protocol::openai_models::ReasoningSummaryFormat; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; use codex_protocol::plan_tool::UpdatePlanArgs; From bacbe871c8493023a813654b9ef70ef5b874caa2 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 11 Dec 2025 14:43:55 -0800 Subject: [PATCH 10/77] Update RMCP client config guidance (#7895) ## Summary - update CLI OAuth guidance to reference `features.rmcp_client` instead of the deprecated experimental flag - keep login/logout help text consistent with the new feature flag ## Testing - `cargo test -p codex-cli` ------ [Codex Task](https://chatgpt.com/codex/tasks/task_i_693b3e0bf27c832cb66d585847a552ab) --- codex-rs/cli/src/mcp_cmd.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 93f22e705c..bfeedb1f78 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -53,11 +53,11 @@ pub enum McpSubcommand { Remove(RemoveArgs), /// [experimental] Authenticate with a configured MCP server via OAuth. - /// Requires experimental_use_rmcp_client = true in config.toml. + /// Requires features.rmcp_client = true in config.toml. Login(LoginArgs), /// [experimental] Remove stored OAuth credentials for a server. - /// Requires experimental_use_rmcp_client = true in config.toml. + /// Requires features.rmcp_client = true in config.toml. Logout(LogoutArgs), } @@ -285,7 +285,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re Ok(true) => { if !config.features.enabled(Feature::RmcpClient) { println!( - "MCP server supports login. Add `experimental_use_rmcp_client = true` \ + "MCP server supports login. Add `features.rmcp_client = true` \ to your config.toml and run `codex mcp login {name}` to login." ); } else { From e0d7ac51d30df4fb937b18fa8df680304093afd0 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 11 Dec 2025 14:46:00 -0800 Subject: [PATCH 11/77] fix: policy/*.codexpolicy -> rules/*.rules (#7888) We decided that `*.rules` is a more fitting (and concise) file extension than `*.codexpolicy`, so we are changing the file extension for the "execpolicy" effort. We are also changing the subfolder of `$CODEX_HOME` from `policy` to `rules` to match. This PR updates the in-repo docs and we will update the public docs once the next CLI release goes out. Locally, I created `~/.codex/rules/default.rules` with the following contents: ``` prefix_rule(pattern=["gh", "pr", "view"]) ``` And then I asked Codex to run: ``` gh pr view 7888 --json title,body,comments ``` and it was able to! --- codex-rs/cli/tests/execpolicy.rs | 9 +++-- codex-rs/core/src/exec_policy.rs | 36 +++++++++---------- codex-rs/core/tests/suite/approvals.rs | 2 +- codex-rs/core/tests/suite/exec_policy.rs | 2 +- codex-rs/exec-server/tests/common/lib.rs | 4 +-- .../exec-server/tests/suite/list_tools.rs | 4 +-- codex-rs/execpolicy/README.md | 8 ++--- codex-rs/execpolicy/src/amend.rs | 9 +++-- codex-rs/execpolicy/src/execpolicycheck.rs | 8 ++--- codex-rs/execpolicy/tests/basic.rs | 16 ++++----- docs/execpolicy.md | 14 ++++---- 11 files changed, 58 insertions(+), 54 deletions(-) diff --git a/codex-rs/cli/tests/execpolicy.rs b/codex-rs/cli/tests/execpolicy.rs index 4610b95874..241a873d59 100644 --- a/codex-rs/cli/tests/execpolicy.rs +++ b/codex-rs/cli/tests/execpolicy.rs @@ -8,7 +8,12 @@ use tempfile::TempDir; #[test] fn execpolicy_check_matches_expected_json() -> Result<(), Box> { let codex_home = TempDir::new()?; - let policy_path = codex_home.path().join("policy.codexpolicy"); + let policy_path = codex_home.path().join("rules").join("policy.rules"); + fs::create_dir_all( + policy_path + .parent() + .expect("policy path should have a parent"), + )?; fs::write( &policy_path, r#" @@ -24,7 +29,7 @@ prefix_rule( .args([ "execpolicy", "check", - "--policy", + "--rules", policy_path .to_str() .expect("policy path should be valid UTF-8"), diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index 6de2967c76..8917610ffc 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -30,9 +30,9 @@ const FORBIDDEN_REASON: &str = "execpolicy forbids this command"; const PROMPT_CONFLICT_REASON: &str = "execpolicy requires approval for this command, but AskForApproval is set to Never"; const PROMPT_REASON: &str = "execpolicy requires approval for this command"; -const POLICY_DIR_NAME: &str = "policy"; -const POLICY_EXTENSION: &str = "codexpolicy"; -const DEFAULT_POLICY_FILE: &str = "default.codexpolicy"; +const RULES_DIR_NAME: &str = "rules"; +const RULE_EXTENSION: &str = "rules"; +const DEFAULT_POLICY_FILE: &str = "default.rules"; fn is_policy_match(rule_match: &RuleMatch) -> bool { match rule_match { @@ -92,7 +92,7 @@ pub(crate) async fn load_exec_policy_for_features( } pub async fn load_exec_policy(codex_home: &Path) -> Result { - let policy_dir = codex_home.join(POLICY_DIR_NAME); + let policy_dir = codex_home.join(RULES_DIR_NAME); let policy_paths = collect_policy_files(&policy_dir).await?; let mut parser = PolicyParser::new(); @@ -124,7 +124,7 @@ pub async fn load_exec_policy(codex_home: &Path) -> Result PathBuf { - codex_home.join(POLICY_DIR_NAME).join(DEFAULT_POLICY_FILE) + codex_home.join(RULES_DIR_NAME).join(DEFAULT_POLICY_FILE) } pub(crate) async fn append_execpolicy_amendment_and_update( @@ -304,7 +304,7 @@ async fn collect_policy_files(dir: &Path) -> Result, ExecPolicyErro if path .extension() .and_then(|ext| ext.to_str()) - .is_some_and(|ext| ext == POLICY_EXTENSION) + .is_some_and(|ext| ext == RULE_EXTENSION) && file_type.is_file() { policy_paths.push(path); @@ -349,14 +349,14 @@ mod tests { }, policy.check_multiple(commands.iter(), &|_| Decision::Allow) ); - assert!(!temp_dir.path().join(POLICY_DIR_NAME).exists()); + assert!(!temp_dir.path().join(RULES_DIR_NAME).exists()); } #[tokio::test] async fn collect_policy_files_returns_empty_when_dir_missing() { let temp_dir = tempdir().expect("create temp dir"); - let policy_dir = temp_dir.path().join(POLICY_DIR_NAME); + let policy_dir = temp_dir.path().join(RULES_DIR_NAME); let files = collect_policy_files(&policy_dir) .await .expect("collect policy files"); @@ -367,10 +367,10 @@ mod tests { #[tokio::test] async fn loads_policies_from_policy_subdirectory() { let temp_dir = tempdir().expect("create temp dir"); - let policy_dir = temp_dir.path().join(POLICY_DIR_NAME); + let policy_dir = temp_dir.path().join(RULES_DIR_NAME); fs::create_dir_all(&policy_dir).expect("create policy dir"); fs::write( - policy_dir.join("deny.codexpolicy"), + policy_dir.join("deny.rules"), r#"prefix_rule(pattern=["rm"], decision="forbidden")"#, ) .expect("write policy file"); @@ -395,7 +395,7 @@ mod tests { async fn ignores_policies_outside_policy_dir() { let temp_dir = tempdir().expect("create temp dir"); fs::write( - temp_dir.path().join("root.codexpolicy"), + temp_dir.path().join("root.rules"), r#"prefix_rule(pattern=["ls"], decision="prompt")"#, ) .expect("write policy file"); @@ -423,7 +423,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") "#; let mut parser = PolicyParser::new(); parser - .parse("test.codexpolicy", policy_src) + .parse("test.rules", policy_src) .expect("parse policy"); let policy = Arc::new(RwLock::new(parser.build())); @@ -456,7 +456,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") let policy_src = r#"prefix_rule(pattern=["rm"], decision="prompt")"#; let mut parser = PolicyParser::new(); parser - .parse("test.codexpolicy", policy_src) + .parse("test.rules", policy_src) .expect("parse policy"); let policy = Arc::new(RwLock::new(parser.build())); let command = vec!["rm".to_string()]; @@ -485,7 +485,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") let policy_src = r#"prefix_rule(pattern=["rm"], decision="prompt")"#; let mut parser = PolicyParser::new(); parser - .parse("test.codexpolicy", policy_src) + .parse("test.rules", policy_src) .expect("parse policy"); let policy = Arc::new(RwLock::new(parser.build())); let command = vec!["rm".to_string()]; @@ -537,7 +537,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") let policy_src = r#"prefix_rule(pattern=["apple"], decision="allow")"#; let mut parser = PolicyParser::new(); parser - .parse("test.codexpolicy", policy_src) + .parse("test.rules", policy_src) .expect("parse policy"); let policy = Arc::new(RwLock::new(parser.build())); let command = vec![ @@ -668,7 +668,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") let policy_src = r#"prefix_rule(pattern=["rm"], decision="prompt")"#; let mut parser = PolicyParser::new(); parser - .parse("test.codexpolicy", policy_src) + .parse("test.rules", policy_src) .expect("parse policy"); let policy = Arc::new(RwLock::new(parser.build())); let command = vec!["rm".to_string()]; @@ -726,7 +726,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") let policy_src = r#"prefix_rule(pattern=["cat"], decision="allow")"#; let mut parser = PolicyParser::new(); parser - .parse("test.codexpolicy", policy_src) + .parse("test.rules", policy_src) .expect("parse policy"); let policy = Arc::new(RwLock::new(parser.build())); @@ -783,7 +783,7 @@ prefix_rule(pattern=["rm"], decision="forbidden") let policy_src = r#"prefix_rule(pattern=["echo"], decision="allow")"#; let mut parser = PolicyParser::new(); parser - .parse("test.codexpolicy", policy_src) + .parse("test.rules", policy_src) .expect("parse policy"); let policy = Arc::new(RwLock::new(parser.build())); let command = vec!["echo".to_string(), "safe".to_string()]; diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 10a510af42..d1b1a515df 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -1633,7 +1633,7 @@ async fn approving_execpolicy_amendment_persists_policy_and_skips_future_prompts .await?; wait_for_completion(&test).await; - let policy_path = test.home.path().join("policy").join("default.codexpolicy"); + let policy_path = test.home.path().join("rules").join("default.rules"); let policy_contents = fs::read_to_string(&policy_path)?; assert!( policy_contents diff --git a/codex-rs/core/tests/suite/exec_policy.rs b/codex-rs/core/tests/suite/exec_policy.rs index b65b2994ee..470478ad75 100644 --- a/codex-rs/core/tests/suite/exec_policy.rs +++ b/codex-rs/core/tests/suite/exec_policy.rs @@ -27,7 +27,7 @@ async fn execpolicy_blocks_shell_invocation() -> Result<()> { } let mut builder = test_codex().with_config(|config| { - let policy_path = config.codex_home.join("policy").join("policy.codexpolicy"); + let policy_path = config.codex_home.join("rules").join("policy.rules"); fs::create_dir_all( policy_path .parent() diff --git a/codex-rs/exec-server/tests/common/lib.rs b/codex-rs/exec-server/tests/common/lib.rs index 0c29528220..f4a70f5b1f 100644 --- a/codex-rs/exec-server/tests/common/lib.rs +++ b/codex-rs/exec-server/tests/common/lib.rs @@ -72,9 +72,9 @@ pub async fn write_default_execpolicy

(policy: &str, codex_home: P) -> anyhow: where P: AsRef, { - let policy_dir = codex_home.as_ref().join("policy"); + let policy_dir = codex_home.as_ref().join("rules"); tokio::fs::create_dir_all(&policy_dir).await?; - tokio::fs::write(policy_dir.join("default.codexpolicy"), policy).await?; + tokio::fs::write(policy_dir.join("default.rules"), policy).await?; Ok(()) } diff --git a/codex-rs/exec-server/tests/suite/list_tools.rs b/codex-rs/exec-server/tests/suite/list_tools.rs index 2f3d412df7..4a28dec5b3 100644 --- a/codex-rs/exec-server/tests/suite/list_tools.rs +++ b/codex-rs/exec-server/tests/suite/list_tools.rs @@ -16,10 +16,10 @@ use tempfile::TempDir; #[tokio::test(flavor = "current_thread")] async fn list_tools() -> Result<()> { let codex_home = TempDir::new()?; - let policy_dir = codex_home.path().join("policy"); + let policy_dir = codex_home.path().join("rules"); fs::create_dir_all(&policy_dir)?; fs::write( - policy_dir.join("default.codexpolicy"), + policy_dir.join("default.rules"), r#"prefix_rule(pattern=["ls"], decision="prompt")"#, )?; let dotslash_cache_temp_dir = TempDir::new()?; diff --git a/codex-rs/execpolicy/README.md b/codex-rs/execpolicy/README.md index 1ddb67252f..288a46dcbc 100644 --- a/codex-rs/execpolicy/README.md +++ b/codex-rs/execpolicy/README.md @@ -20,14 +20,14 @@ prefix_rule( ``` ## CLI -- From the Codex CLI, run `codex execpolicy check` subcommand with one or more policy files (for example `src/default.codexpolicy`) to check a command: +- From the Codex CLI, run `codex execpolicy check` subcommand with one or more policy files (for example `src/default.rules`) to check a command: ```bash -codex execpolicy check --policy path/to/policy.codexpolicy git status +codex execpolicy check --rules path/to/policy.rules git status ``` -- Pass multiple `--policy` flags to merge rules, evaluated in the order provided, and use `--pretty` for formatted JSON. +- Pass multiple `--rules` flags to merge rules, evaluated in the order provided, and use `--pretty` for formatted JSON. - You can also run the standalone dev binary directly during development: ```bash -cargo run -p codex-execpolicy -- check --policy path/to/policy.codexpolicy git status +cargo run -p codex-execpolicy -- check --rules path/to/policy.rules git status ``` - Example outcomes: - Match: `{"matchedRules":[{...}],"decision":"allow"}` diff --git a/codex-rs/execpolicy/src/amend.rs b/codex-rs/execpolicy/src/amend.rs index 36a02cebf9..9114d3a64f 100644 --- a/codex-rs/execpolicy/src/amend.rs +++ b/codex-rs/execpolicy/src/amend.rs @@ -154,7 +154,7 @@ mod tests { #[test] fn appends_rule_and_creates_directories() { let tmp = tempdir().expect("create temp dir"); - let policy_path = tmp.path().join("policy").join("default.codexpolicy"); + let policy_path = tmp.path().join("rules").join("default.rules"); blocking_append_allow_prefix_rule( &policy_path, @@ -162,8 +162,7 @@ mod tests { ) .expect("append rule"); - let contents = - std::fs::read_to_string(&policy_path).expect("default.codexpolicy should exist"); + let contents = std::fs::read_to_string(&policy_path).expect("default.rules should exist"); assert_eq!( contents, r#"prefix_rule(pattern=["echo", "Hello, world!"], decision="allow") @@ -174,7 +173,7 @@ mod tests { #[test] fn appends_rule_without_duplicate_newline() { let tmp = tempdir().expect("create temp dir"); - let policy_path = tmp.path().join("policy").join("default.codexpolicy"); + let policy_path = tmp.path().join("rules").join("default.rules"); std::fs::create_dir_all(policy_path.parent().unwrap()).expect("create policy dir"); std::fs::write( &policy_path, @@ -201,7 +200,7 @@ prefix_rule(pattern=["echo", "Hello, world!"], decision="allow") #[test] fn inserts_newline_when_missing_before_append() { let tmp = tempdir().expect("create temp dir"); - let policy_path = tmp.path().join("policy").join("default.codexpolicy"); + let policy_path = tmp.path().join("rules").join("default.rules"); std::fs::create_dir_all(policy_path.parent().unwrap()).expect("create policy dir"); std::fs::write( &policy_path, diff --git a/codex-rs/execpolicy/src/execpolicycheck.rs b/codex-rs/execpolicy/src/execpolicycheck.rs index 939ed8590b..f191f4b12e 100644 --- a/codex-rs/execpolicy/src/execpolicycheck.rs +++ b/codex-rs/execpolicy/src/execpolicycheck.rs @@ -14,9 +14,9 @@ use crate::RuleMatch; /// Arguments for evaluating a command against one or more execpolicy files. #[derive(Debug, Parser, Clone)] pub struct ExecPolicyCheckCommand { - /// Paths to execpolicy files to evaluate (repeatable). - #[arg(short = 'p', long = "policy", value_name = "PATH", required = true)] - pub policies: Vec, + /// Paths to execpolicy rule files to evaluate (repeatable). + #[arg(short = 'r', long = "rules", value_name = "PATH", required = true)] + pub rules: Vec, /// Pretty-print the JSON output. #[arg(long)] @@ -35,7 +35,7 @@ pub struct ExecPolicyCheckCommand { impl ExecPolicyCheckCommand { /// Load the policies for this command, evaluate the command, and render JSON output. pub fn run(&self) -> Result<()> { - let policy = load_policies(&self.policies)?; + let policy = load_policies(&self.rules)?; let matched_rules = policy.matches_for_command(&self.command, None); let json = format_matches_json(&matched_rules, self.pretty)?; diff --git a/codex-rs/execpolicy/tests/basic.rs b/codex-rs/execpolicy/tests/basic.rs index 3ea33604ae..7ae5e6e213 100644 --- a/codex-rs/execpolicy/tests/basic.rs +++ b/codex-rs/execpolicy/tests/basic.rs @@ -54,7 +54,7 @@ prefix_rule( ) "#; let mut parser = PolicyParser::new(); - parser.parse("test.codexpolicy", policy_src)?; + parser.parse("test.rules", policy_src)?; let policy = parser.build(); let cmd = tokens(&["git", "status"]); let evaluation = policy.check(&cmd, &allow_all); @@ -129,8 +129,8 @@ prefix_rule( ) "#; let mut parser = PolicyParser::new(); - parser.parse("first.codexpolicy", first_policy)?; - parser.parse("second.codexpolicy", second_policy)?; + parser.parse("first.rules", first_policy)?; + parser.parse("second.rules", second_policy)?; let policy = parser.build(); let git_rules = rule_snapshots(policy.rules().get_vec("git").context("missing git rules")?); @@ -194,7 +194,7 @@ prefix_rule( ) "#; let mut parser = PolicyParser::new(); - parser.parse("test.codexpolicy", policy_src)?; + parser.parse("test.rules", policy_src)?; let policy = parser.build(); let bash_rules = rule_snapshots( @@ -259,7 +259,7 @@ prefix_rule( ) "#; let mut parser = PolicyParser::new(); - parser.parse("test.codexpolicy", policy_src)?; + parser.parse("test.rules", policy_src)?; let policy = parser.build(); let rules = rule_snapshots(policy.rules().get_vec("npm").context("missing npm rules")?); @@ -323,7 +323,7 @@ prefix_rule( ) "#; let mut parser = PolicyParser::new(); - parser.parse("test.codexpolicy", policy_src)?; + parser.parse("test.rules", policy_src)?; let policy = parser.build(); let match_eval = policy.check(&tokens(&["git", "status"]), &allow_all); assert_eq!( @@ -367,7 +367,7 @@ prefix_rule( ) "#; let mut parser = PolicyParser::new(); - parser.parse("test.codexpolicy", policy_src)?; + parser.parse("test.rules", policy_src)?; let policy = parser.build(); let commit = policy.check(&tokens(&["git", "commit", "-m", "hi"]), &allow_all); @@ -403,7 +403,7 @@ prefix_rule( ) "#; let mut parser = PolicyParser::new(); - parser.parse("test.codexpolicy", policy_src)?; + parser.parse("test.rules", policy_src)?; let policy = parser.build(); let commands = vec![ diff --git a/docs/execpolicy.md b/docs/execpolicy.md index e60e1cec6c..ecc79f33d2 100644 --- a/docs/execpolicy.md +++ b/docs/execpolicy.md @@ -1,6 +1,6 @@ # Execpolicy quickstart -Codex can enforce your own rules-based execution policy before it runs shell commands. Policies live in `.codexpolicy` files under `~/.codex/policy`. +Codex can enforce your own rules-based execution policy before it runs shell commands. Policies live in `.rules` files under `~/.codex/rules`. ## How to create and edit rules @@ -12,12 +12,12 @@ Codex CLI will present the option to whitelist commands when a command causes a Whitelisted commands will no longer require your permission to run in current and subsequent sessions. -Under the hood, when you approve and whitelist a command, codex will edit `~/.codex/policy/default.codexpolicy`. +Under the hood, when you approve and whitelist a command, codex will edit `~/.codex/rules/default.rules`. -### Editing `.codexpolicy` files +### Editing `.rules` files -1. Create a policy directory: `mkdir -p ~/.codex/policy`. -2. Add one or more `.codexpolicy` files in that folder. Codex automatically loads every `.codexpolicy` file in there on startup. +1. Create a policy directory: `mkdir -p ~/.codex/rules`. +2. Add one or more `.rules` files in that folder. Codex automatically loads every `.rules` file in there on startup. 3. Write `prefix_rule` entries to describe the commands you want to allow, prompt, or block: ```starlark @@ -40,10 +40,10 @@ In this example rule, if Codex wants to run commands with the prefix `git push` Use the `codex execpolicy check` subcommand to preview decisions before you save a rule (see the [`codex-execpolicy` README](../codex-rs/execpolicy/README.md) for syntax details): ```shell -codex execpolicy check --policy ~/.codex/policy/default.codexpolicy git push origin main +codex execpolicy check --rules ~/.codex/rules/default.rules git push origin main ``` -Pass multiple `--policy` flags to test how several files combine, and use `--pretty` for formatted JSON output. See the [`codex-rs/execpolicy` README](../codex-rs/execpolicy/README.md) for a more detailed walkthrough of the available syntax. +Pass multiple `--rules` flags to test how several files combine, and use `--pretty` for formatted JSON output. See the [`codex-rs/execpolicy` README](../codex-rs/execpolicy/README.md) for a more detailed walkthrough of the available syntax. Example output when a rule matches: From 36610d975a3e92252178f5e1cb3adab60c593d4e Mon Sep 17 00:00:00 2001 From: dank-openai Date: Thu, 11 Dec 2025 15:09:00 -0800 Subject: [PATCH 12/77] Fix toasts on Windows under WSL 2 (#7137) Before this: no notifications or toasts when using Codex CLI in WSL 2. After this: I get toasts from Codex --- codex-rs/README.md | 2 +- codex-rs/cli/src/wsl_paths.rs | 21 +-- codex-rs/core/src/env.rs | 19 +++ codex-rs/core/src/lib.rs | 1 + codex-rs/tui/src/lib.rs | 1 + codex-rs/tui/src/notifications/mod.rs | 139 ++++++++++++++++++ codex-rs/tui/src/notifications/osc9.rs | 37 +++++ .../tui/src/notifications/windows_toast.rs | 128 ++++++++++++++++ codex-rs/tui/src/tui.rs | 73 +++++---- docs/config.md | 2 + 10 files changed, 376 insertions(+), 47 deletions(-) create mode 100644 codex-rs/core/src/env.rs create mode 100644 codex-rs/tui/src/notifications/mod.rs create mode 100644 codex-rs/tui/src/notifications/osc9.rs create mode 100644 codex-rs/tui/src/notifications/windows_toast.rs diff --git a/codex-rs/README.md b/codex-rs/README.md index 385b4c62e5..a3d1b82fb8 100644 --- a/codex-rs/README.md +++ b/codex-rs/README.md @@ -46,7 +46,7 @@ Use `codex mcp` to add/list/get/remove MCP server launchers defined in `config.t ### Notifications -You can enable notifications by configuring a script that is run whenever the agent finishes a turn. The [notify documentation](../docs/config.md#notify) includes a detailed example that explains how to get desktop notifications via [terminal-notifier](https://github.com/julienXX/terminal-notifier) on macOS. +You can enable notifications by configuring a script that is run whenever the agent finishes a turn. The [notify documentation](../docs/config.md#notify) includes a detailed example that explains how to get desktop notifications via [terminal-notifier](https://github.com/julienXX/terminal-notifier) on macOS. When Codex detects that it is running under WSL 2 inside Windows Terminal (`WT_SESSION` is set), the TUI automatically falls back to native Windows toast notifications so approval prompts and completed turns surface even though Windows Terminal does not implement OSC 9. ### `codex exec` to run Codex programmatically/non-interactively diff --git a/codex-rs/cli/src/wsl_paths.rs b/codex-rs/cli/src/wsl_paths.rs index 56ce8668cf..b6ceb2e0bc 100644 --- a/codex-rs/cli/src/wsl_paths.rs +++ b/codex-rs/cli/src/wsl_paths.rs @@ -1,24 +1,7 @@ use std::ffi::OsStr; -/// WSL-specific path helpers used by the updater logic. -/// -/// See https://github.com/openai/codex/issues/6086. -pub fn is_wsl() -> bool { - #[cfg(target_os = "linux")] - { - if std::env::var_os("WSL_DISTRO_NAME").is_some() { - return true; - } - match std::fs::read_to_string("/proc/version") { - Ok(version) => version.to_lowercase().contains("microsoft"), - Err(_) => false, - } - } - #[cfg(not(target_os = "linux"))] - { - false - } -} +/// Returns true if the current process is running under WSL. +pub use codex_core::env::is_wsl; /// Convert a Windows absolute path (`C:\foo\bar` or `C:/foo/bar`) to a WSL mount path (`/mnt/c/foo/bar`). /// Returns `None` if the input does not look like a Windows drive path. diff --git a/codex-rs/core/src/env.rs b/codex-rs/core/src/env.rs new file mode 100644 index 0000000000..5370c0ffd8 --- /dev/null +++ b/codex-rs/core/src/env.rs @@ -0,0 +1,19 @@ +//! Functions for environment detection that need to be shared across crates. + +/// Returns true if the current process is running under Windows Subsystem for Linux. +pub fn is_wsl() -> bool { + #[cfg(target_os = "linux")] + { + if std::env::var_os("WSL_DISTRO_NAME").is_some() { + return true; + } + match std::fs::read_to_string("/proc/version") { + Ok(version) => version.to_lowercase().contains("microsoft"), + Err(_) => false, + } + } + #[cfg(not(target_os = "linux"))] + { + false + } +} diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index cd0ff497ab..f69e7b8fb1 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -21,6 +21,7 @@ pub mod config; pub mod config_loader; mod context_manager; pub mod custom_prompts; +pub mod env; mod environment_context; pub mod error; pub mod exec; diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 71a47d1198..36883b8664 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -58,6 +58,7 @@ mod markdown; mod markdown_render; mod markdown_stream; mod model_migration; +mod notifications; pub mod onboarding; mod oss_selection; mod pager_overlay; diff --git a/codex-rs/tui/src/notifications/mod.rs b/codex-rs/tui/src/notifications/mod.rs new file mode 100644 index 0000000000..33a591dfdb --- /dev/null +++ b/codex-rs/tui/src/notifications/mod.rs @@ -0,0 +1,139 @@ +mod osc9; +mod windows_toast; + +use std::env; +use std::io; + +use codex_core::env::is_wsl; +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), +} + +impl DesktopNotificationBackend { + pub fn osc9() -> Self { + Self::Osc9(Osc9Backend) + } + + pub fn windows_toast() -> Self { + Self::WindowsToast(WindowsToastBackend::default()) + } + + pub fn kind(&self) -> NotificationBackendKind { + match self { + DesktopNotificationBackend::Osc9(_) => NotificationBackendKind::Osc9, + DesktopNotificationBackend::WindowsToast(_) => NotificationBackendKind::WindowsToast, + } + } + + pub fn notify(&mut self, message: &str) -> io::Result<()> { + match self { + DesktopNotificationBackend::Osc9(backend) => backend.notify(message), + DesktopNotificationBackend::WindowsToast(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() + } +} + +fn should_use_windows_toasts() -> bool { + is_wsl() && env::var_os("WT_SESSION").is_some() +} + +#[cfg(test)] +mod tests { + use super::NotificationBackendKind; + use super::detect_backend; + use serial_test::serial; + use std::ffi::OsString; + + struct EnvVarGuard { + key: &'static str, + original: Option, + } + + impl EnvVarGuard { + fn set(key: &'static str, value: &str) -> Self { + let original = std::env::var_os(key); + unsafe { + std::env::set_var(key, value); + } + Self { key, original } + } + + fn remove(key: &'static str) -> Self { + let original = std::env::var_os(key); + unsafe { + std::env::remove_var(key); + } + Self { key, original } + } + } + + impl Drop for EnvVarGuard { + fn drop(&mut self) { + unsafe { + match &self.original { + Some(value) => std::env::set_var(self.key, value), + None => std::env::remove_var(self.key), + } + } + } + } + + #[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); + } + + #[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); + } + + #[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); + } +} diff --git a/codex-rs/tui/src/notifications/osc9.rs b/codex-rs/tui/src/notifications/osc9.rs new file mode 100644 index 0000000000..fd3a8ad96d --- /dev/null +++ b/codex-rs/tui/src/notifications/osc9.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 Osc9Backend; + +impl Osc9Backend { + pub fn notify(&mut self, message: &str) -> io::Result<()> { + execute!(stdout(), PostNotification(message.to_string())) + } +} + +/// Command that emits an OSC 9 desktop notification with a message. +#[derive(Debug, Clone)] +pub struct PostNotification(pub String); + +impl Command for PostNotification { + fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result { + write!(f, "\x1b]9;{}\x07", self.0) + } + + #[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/windows_toast.rs b/codex-rs/tui/src/notifications/windows_toast.rs new file mode 100644 index 0000000000..9917e62c37 --- /dev/null +++ b/codex-rs/tui/src/notifications/windows_toast.rs @@ -0,0 +1,128 @@ +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 5502b83356..36f6cc2cb5 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -39,6 +39,9 @@ use tokio_stream::Stream; 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; #[cfg(unix)] use crate::tui::job_control::SUSPEND_KEY; #[cfg(unix)] @@ -173,6 +176,7 @@ pub struct Tui { // True when terminal/tab is focused; updated internally from crossterm events terminal_focused: Arc, enhanced_keys_supported: bool, + notification_backend: Option, } impl Tui { @@ -198,6 +202,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()), } } @@ -212,11 +217,47 @@ impl Tui { /// Emit a desktop notification now if the terminal is unfocused. /// Returns true if a notification was posted. pub fn notify(&mut self, message: impl AsRef) -> bool { - if !self.terminal_focused.load(Ordering::Relaxed) { - let _ = execute!(stdout(), PostNotification(message.as_ref().to_string())); - true - } else { - false + if self.terminal_focused.load(Ordering::Relaxed) { + return false; + } + + let Some(backend) = self.notification_backend.as_mut() else { + return false; + }; + + 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 + } + }, } } @@ -417,25 +458,3 @@ impl Tui { Ok(None) } } - -/// Command that emits an OSC 9 desktop notification with a message. -#[derive(Debug, Clone)] -pub struct PostNotification(pub String); - -impl Command for PostNotification { - fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result { - write!(f, "\x1b]9;{}\x07", self.0) - } - - #[cfg(windows)] - fn execute_winapi(&self) -> 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/docs/config.md b/docs/config.md index 8b131cd63a..2ac775528f 100644 --- a/docs/config.md +++ b/docs/config.md @@ -745,6 +745,8 @@ notify = ["python3", "/Users/mbolin/.codex/notify.py"] > [!NOTE] > Use `notify` for automation and integrations: Codex invokes your external program with a single JSON argument for each event, independent of the TUI. If you only want lightweight desktop notifications while using the TUI, prefer `tui.notifications`, which uses terminal escape codes and requires no external program. You can enable both; `tui.notifications` covers in‑TUI alerts (e.g., approval prompts), while `notify` is best for system‑level hooks or custom notifiers. Currently, `notify` emits only `agent-turn-complete`, whereas `tui.notifications` supports `agent-turn-complete` and `approval-requested` with optional filtering. +When Codex detects WSL 2 inside Windows Terminal (the session exports `WT_SESSION`), `tui.notifications` automatically switches to a Windows toast backend by spawning `powershell.exe`. This ensures both approval prompts and completed turns trigger native toasts even though Windows Terminal ignores OSC 9 escape sequences. Terminals that advertise OSC 9 support (iTerm2, WezTerm, kitty, etc.) continue to use the existing escape-sequence backend, and the `notify` hook remains unchanged. + ### hide_agent_reasoning Codex intermittently emits "reasoning" events that show the model's internal "thinking" before it produces a final answer. Some users may find these events distracting, especially in CI logs or minimal terminal output. From 43e6e75317bf3c31e9fcffcce533a56ad01495cb Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Thu, 11 Dec 2025 17:24:43 -0600 Subject: [PATCH 13/77] Added deprecation notice for "chat" wire_api (#7897) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR adds a deprecation notice that appears once per invocation of codex (not per conversation) when a conversation is started using a custom model provider configured with the "chat" wire_api. We have [announced](https://github.com/openai/codex/discussions/7782) that this feature is deprecated and will be removed in early Feb 2026, so we want to notify users of this fact. The deprecation notice was added in a way that works with the non-interactive "codex exec", the TUI, and with the extension. Screen shots of each are below. image Screenshot 2025-12-11 at 2 22 29 PM Screenshot 2025-12-11 at 2 21 26 PM --- codex-rs/core/src/codex.rs | 30 ++++++++++++++++++++++++ codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/model_provider_info.rs | 1 + 3 files changed, 32 insertions(+) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index e23e03298d..c546bb583e 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -2,7 +2,9 @@ use std::collections::HashMap; use std::fmt::Debug; use std::path::PathBuf; use std::sync::Arc; +use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; use crate::AuthManager; use crate::SandboxState; @@ -65,6 +67,7 @@ use tracing::info; use tracing::warn; use crate::ModelProviderInfo; +use crate::WireApi; use crate::client::ModelClient; use crate::client_common::Prompt; use crate::client_common::ResponseEvent; @@ -80,6 +83,7 @@ use crate::exec::StreamOutput; use crate::exec_policy::ExecPolicyUpdateError; use crate::mcp::auth::compute_auth_statuses; use crate::mcp_connection_manager::McpConnectionManager; +use crate::model_provider_info::CHAT_WIRE_API_DEPRECATION_SUMMARY; use crate::project_doc::get_user_instructions; use crate::protocol::AgentMessageContentDeltaEvent; use crate::protocol::AgentReasoningSectionBreakEvent; @@ -167,6 +171,31 @@ pub struct CodexSpawnOk { pub(crate) const INITIAL_SUBMIT_ID: &str = ""; pub(crate) const SUBMISSION_CHANNEL_CAPACITY: usize = 64; +static CHAT_WIRE_API_DEPRECATION_EMITTED: AtomicBool = AtomicBool::new(false); + +fn maybe_push_chat_wire_api_deprecation( + config: &Config, + post_session_configured_events: &mut Vec, +) { + if config.model_provider.wire_api != WireApi::Chat { + return; + } + + if CHAT_WIRE_API_DEPRECATION_EMITTED + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .is_err() + { + return; + } + + post_session_configured_events.push(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::DeprecationNotice(DeprecationNoticeEvent { + summary: CHAT_WIRE_API_DEPRECATION_SUMMARY.to_string(), + details: None, + }), + }); +} impl Codex { /// Spawn a new [`Codex`] and initialize the session. @@ -584,6 +613,7 @@ impl Session { msg: EventMsg::DeprecationNotice(DeprecationNoticeEvent { summary, details }), }); } + maybe_push_chat_wire_api_deprecation(&config, &mut post_session_configured_events); // todo(aibrahim): why are we passing model here while it can change? let otel_event_manager = OtelEventManager::new( diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index f69e7b8fb1..11b49c78c4 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -49,6 +49,7 @@ pub mod token_data; mod truncate; mod unified_exec; mod user_instructions; +pub use model_provider_info::CHAT_WIRE_API_DEPRECATION_SUMMARY; pub use model_provider_info::DEFAULT_LMSTUDIO_PORT; pub use model_provider_info::DEFAULT_OLLAMA_PORT; pub use model_provider_info::LMSTUDIO_OSS_PROVIDER_ID; diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index aa86501014..22f0d99984 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -26,6 +26,7 @@ const DEFAULT_REQUEST_MAX_RETRIES: u64 = 4; const MAX_STREAM_MAX_RETRIES: u64 = 100; /// Hard cap for user-configured `request_max_retries`. const MAX_REQUEST_MAX_RETRIES: u64 = 100; +pub const CHAT_WIRE_API_DEPRECATION_SUMMARY: &str = r#"Support for the "chat" wire API is deprecated and will soon be removed. Update your model provider definition in config.toml to use wire_api = "responses"."#; /// Wire protocol that the provider speaks. Most third-party services only /// implement the classic OpenAI Chat Completions JSON schema, whereas OpenAI From 95f7d37ec68bb54cc6bae29566dca8103b788699 Mon Sep 17 00:00:00 2001 From: Victor Vannara Date: Thu, 11 Dec 2025 16:38:52 -0800 Subject: [PATCH 14/77] Fix misleading 'maximize' high effort description on xhigh models (#7874) ## Notes - switch misleading High reasoning effort descriptions from "Maximizes reasoning depth" to "Higher reasoning depth" across models with xhigh reasoning. Affects GPT-5.1 Codex Max and Robin - refresh model list fixtures and chatwidget snapshots to match new copy ## Revision - R2: Change 'Higher' to 'Greater' - R1: Initial ## Testing image image --- codex-rs/app-server/tests/suite/v2/model_list.rs | 4 ++-- codex-rs/core/src/openai_models/model_presets.rs | 4 ++-- codex-rs/core/tests/suite/list_models.rs | 4 ++-- ...i__chatwidget__tests__model_reasoning_selection_popup.snap | 2 +- ...s__model_reasoning_selection_popup_extra_high_warning.snap | 2 +- codex-rs/tui/src/chatwidget/tests.rs | 2 +- ...2__chatwidget__tests__model_reasoning_selection_popup.snap | 2 +- ...s__model_reasoning_selection_popup_extra_high_warning.snap | 2 +- ...i__chatwidget__tests__model_reasoning_selection_popup.snap | 2 +- ...s__model_reasoning_selection_popup_extra_high_warning.snap | 2 +- 10 files changed, 13 insertions(+), 13 deletions(-) diff --git a/codex-rs/app-server/tests/suite/v2/model_list.rs b/codex-rs/app-server/tests/suite/v2/model_list.rs index eb9d0c32c1..b406eda3f4 100644 --- a/codex-rs/app-server/tests/suite/v2/model_list.rs +++ b/codex-rs/app-server/tests/suite/v2/model_list.rs @@ -64,7 +64,7 @@ async fn list_models_returns_all_models_with_large_limit() -> Result<()> { }, ReasoningEffortOption { reasoning_effort: ReasoningEffort::High, - description: "Maximizes reasoning depth for complex problems".to_string(), + description: "Greater reasoning depth for complex problems".to_string(), }, ReasoningEffortOption { reasoning_effort: ReasoningEffort::XHigh, @@ -138,7 +138,7 @@ async fn list_models_returns_all_models_with_large_limit() -> Result<()> { }, ReasoningEffortOption { reasoning_effort: ReasoningEffort::High, - description: "Maximizes reasoning depth for complex or ambiguous problems" + description: "Greater reasoning depth for complex or ambiguous problems" .to_string(), }, ReasoningEffortOption { diff --git a/codex-rs/core/src/openai_models/model_presets.rs b/codex-rs/core/src/openai_models/model_presets.rs index 42a5557f40..cf635e8dac 100644 --- a/codex-rs/core/src/openai_models/model_presets.rs +++ b/codex-rs/core/src/openai_models/model_presets.rs @@ -28,7 +28,7 @@ static PRESETS: Lazy> = Lazy::new(|| { }, ReasoningEffortPreset { effort: ReasoningEffort::High, - description: "Maximizes reasoning depth for complex problems".to_string(), + description: "Greater reasoning depth for complex problems".to_string(), }, ReasoningEffortPreset { effort: ReasoningEffort::XHigh, @@ -110,7 +110,7 @@ static PRESETS: Lazy> = Lazy::new(|| { }, ReasoningEffortPreset { effort: ReasoningEffort::High, - description: "Maximizes reasoning depth for complex or ambiguous problems".to_string(), + description: "Greater reasoning depth for complex or ambiguous problems".to_string(), }, ReasoningEffortPreset { effort: ReasoningEffort::XHigh, diff --git a/codex-rs/core/tests/suite/list_models.rs b/codex-rs/core/tests/suite/list_models.rs index 9cfd9b267f..b62fdfe9ac 100644 --- a/codex-rs/core/tests/suite/list_models.rs +++ b/codex-rs/core/tests/suite/list_models.rs @@ -79,7 +79,7 @@ fn gpt_5_1_codex_max() -> ModelPreset { ), effort( ReasoningEffort::High, - "Maximizes reasoning depth for complex problems", + "Greater reasoning depth for complex problems", ), effort( ReasoningEffort::XHigh, @@ -162,7 +162,7 @@ fn gpt_5_2() -> ModelPreset { ), effort( ReasoningEffort::High, - "Maximizes reasoning depth for complex or ambiguous problems", + "Greater reasoning depth for complex or ambiguous problems", ), effort( ReasoningEffort::XHigh, diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap index b4b89736a9..a4a86a41ba 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap @@ -6,7 +6,7 @@ expression: popup 1. Low Fast responses with lighter reasoning 2. Medium (default) Balances speed and reasoning depth for everyday tasks -› 3. High (current) Maximizes reasoning depth for complex problems +› 3. High (current) Greater reasoning depth for complex problems 4. Extra high Extra high reasoning depth for complex problems Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap index c5332ff590..3eb172c101 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap @@ -8,7 +8,7 @@ expression: popup 1. Low Fast responses with lighter reasoning 2. Medium (default) Balances speed and reasoning depth for everyday tasks - 3. High Maximizes reasoning depth for complex problems + 3. High Greater reasoning depth for complex problems › 4. Extra high (current) Extra high reasoning depth for complex problems ⚠ Extra high reasoning effort can quickly consume Plus plan rate limits. diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index bd85a9edc8..65f6708c91 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -1930,7 +1930,7 @@ fn single_reasoning_option_skips_selection() { let single_effort = vec![ReasoningEffortPreset { effort: ReasoningEffortConfig::High, - description: "Maximizes reasoning depth for complex or ambiguous problems".to_string(), + description: "Greater reasoning depth for complex or ambiguous problems".to_string(), }]; let preset = ModelPreset { id: "model-with-single-reasoning".to_string(), diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup.snap index cbf5f0fb52..86c748d597 100644 --- a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup.snap +++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup.snap @@ -6,7 +6,7 @@ expression: popup 1. Low Fast responses with lighter reasoning 2. Medium (default) Balances speed and reasoning depth for everyday tasks -› 3. High (current) Maximizes reasoning depth for complex problems +› 3. High (current) Greater reasoning depth for complex problems 4. Extra high Extra high reasoning depth for complex problems Press enter to confirm or esc to go back diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap index ed6c6fee19..4d1d62d935 100644 --- a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap +++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap @@ -7,7 +7,7 @@ expression: popup 1. Low Fast responses with lighter reasoning 2. Medium (default) Balances speed and reasoning depth for everyday tasks - 3. High Maximizes reasoning depth for complex problems + 3. High Greater reasoning depth for complex problems › 4. Extra high (current) Extra high reasoning depth for complex problems ⚠ Extra high reasoning effort can quickly consume Plus plan rate limits. diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap index b4b89736a9..a4a86a41ba 100644 --- a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap +++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap @@ -6,7 +6,7 @@ expression: popup 1. Low Fast responses with lighter reasoning 2. Medium (default) Balances speed and reasoning depth for everyday tasks -› 3. High (current) Maximizes reasoning depth for complex problems +› 3. High (current) Greater reasoning depth for complex problems 4. Extra high Extra high reasoning depth for complex problems Press enter to confirm or esc to go back diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap index c5332ff590..3eb172c101 100644 --- a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap +++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap @@ -8,7 +8,7 @@ expression: popup 1. Low Fast responses with lighter reasoning 2. Medium (default) Balances speed and reasoning depth for everyday tasks - 3. High Maximizes reasoning depth for complex problems + 3. High Greater reasoning depth for complex problems › 4. Extra high (current) Extra high reasoning depth for complex problems ⚠ Extra high reasoning effort can quickly consume Plus plan rate limits. From c787e9d0c08fd5aad08509b109816211762d9a50 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 11 Dec 2025 16:41:04 -0800 Subject: [PATCH 15/77] Make migration screen dynamic (#7896) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. --- codex-rs/core/src/config/edit.rs | 47 +++ codex-rs/core/src/config/types.rs | 4 + codex-rs/tui/src/app.rs | 194 +++++----- codex-rs/tui/src/app_event.rs | 3 +- codex-rs/tui/src/model_migration.rs | 339 ++++++++++-------- ...ration__tests__model_migration_prompt.snap | 15 +- ...ts__model_migration_prompt_gpt5_codex.snap | 12 +- ...odel_migration_prompt_gpt5_codex_mini.snap | 11 +- ...s__model_migration_prompt_gpt5_family.snap | 10 +- 9 files changed, 359 insertions(+), 276 deletions(-) diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 37c2aba6ef..89c33079c0 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -32,6 +32,8 @@ pub enum ConfigEdit { SetWindowsWslSetupAcknowledged(bool), /// Toggle the model migration prompt acknowledgement flag. SetNoticeHideModelMigrationPrompt(String, bool), + /// Record that a migration prompt was shown for an old->new model mapping. + RecordModelMigrationSeen { from: String, to: String }, /// Replace the entire `[mcp_servers]` table. ReplaceMcpServers(BTreeMap), /// Set trust_level under `[projects.""]`, @@ -263,6 +265,11 @@ impl ConfigDocument { value(*acknowledged), )) } + ConfigEdit::RecordModelMigrationSeen { from, to } => Ok(self.write_value( + Scope::Global, + &[Notice::TABLE_KEY, "model_migrations", from.as_str()], + value(to.clone()), + )), ConfigEdit::SetWindowsWslSetupAcknowledged(acknowledged) => Ok(self.write_value( Scope::Global, &["windows_wsl_setup_acknowledged"], @@ -522,6 +529,14 @@ impl ConfigEditsBuilder { self } + pub fn record_model_migration_seen(mut self, from: &str, to: &str) -> Self { + self.edits.push(ConfigEdit::RecordModelMigrationSeen { + from: from.to_string(), + to: to.to_string(), + }); + self + } + pub fn set_windows_wsl_setup_acknowledged(mut self, acknowledged: bool) -> Self { self.edits .push(ConfigEdit::SetWindowsWslSetupAcknowledged(acknowledged)); @@ -897,6 +912,38 @@ existing = "value" assert_eq!(contents, expected); } + #[test] + fn blocking_record_model_migration_seen_preserves_table() { + let tmp = tempdir().expect("tmpdir"); + let codex_home = tmp.path(); + std::fs::write( + codex_home.join(CONFIG_TOML_FILE), + r#"[notice] +existing = "value" +"#, + ) + .expect("seed"); + apply_blocking( + codex_home, + None, + &[ConfigEdit::RecordModelMigrationSeen { + from: "gpt-5".to_string(), + to: "gpt-5.1".to_string(), + }], + ) + .expect("persist"); + + let contents = + std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config"); + let expected = r#"[notice] +existing = "value" + +[notice.model_migrations] +gpt-5 = "gpt-5.1" +"#; + assert_eq!(contents, expected); + } + #[test] fn blocking_replace_mcp_servers_round_trips() { let tmp = tempdir().expect("tmpdir"); diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index ca16b7a560..d54bdbc100 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -4,6 +4,7 @@ // definitions that do not contain business logic. use codex_utils_absolute_path::AbsolutePathBuf; +use std::collections::BTreeMap; use std::collections::HashMap; use std::path::PathBuf; use std::time::Duration; @@ -396,6 +397,9 @@ pub struct Notice { /// Tracks whether the user has seen the gpt-5.1-codex-max migration prompt #[serde(rename = "hide_gpt-5.1-codex-max_migration_prompt")] pub hide_gpt_5_1_codex_max_migration_prompt: Option, + /// Tracks acknowledged model migrations as old->new model slug mappings. + #[serde(default)] + pub model_migrations: BTreeMap, } impl Notice { diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index a12393c91a..5397a2eaec 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -8,7 +8,7 @@ use crate::exec_command::strip_bash_lc_and_escape; use crate::file_search::FileSearchManager; use crate::history_cell::HistoryCell; use crate::model_migration::ModelMigrationOutcome; -use crate::model_migration::migration_copy_for_config; +use crate::model_migration::migration_copy_for_models; use crate::model_migration::run_model_migration_prompt; use crate::pager_overlay::Overlay; use crate::render::highlight::highlight_bash_to_lines; @@ -20,7 +20,6 @@ use crate::tui; use crate::tui::TuiEvent; use crate::update_action::UpdateAction; use codex_ansi_escape::ansi_escape_line; -use codex_app_server_protocol::AuthMode; use codex_core::AuthManager; use codex_core::ConversationManager; use codex_core::config::Config; @@ -50,6 +49,7 @@ use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::widgets::Paragraph; use ratatui::widgets::Wrap; +use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -62,9 +62,6 @@ use tokio::sync::mpsc::unbounded_channel; #[cfg(not(debug_assertions))] use crate::history_cell::UpdateAvailableHistoryCell; -const GPT_5_1_MIGRATION_AUTH_MODES: [AuthMode; 2] = [AuthMode::ChatGPT, AuthMode::ApiKey]; -const GPT_5_1_CODEX_MIGRATION_AUTH_MODES: [AuthMode; 2] = [AuthMode::ChatGPT, AuthMode::ApiKey]; - #[derive(Debug, Clone)] pub struct AppExitInfo { pub token_usage: TokenUsage, @@ -109,26 +106,46 @@ struct SessionSummary { fn should_show_model_migration_prompt( current_model: &str, target_model: &str, - hide_prompt_flag: Option, - available_models: Vec, + seen_migrations: &BTreeMap, + available_models: &[ModelPreset], ) -> bool { - if target_model == current_model || hide_prompt_flag.unwrap_or(false) { + if target_model == current_model { return false; } - available_models + if let Some(seen_target) = seen_migrations.get(current_model) + && seen_target == target_model + { + return false; + } + + if available_models .iter() - .filter(|preset| preset.upgrade.is_some()) - .any(|preset| preset.model == current_model) + .any(|preset| preset.model == current_model && preset.upgrade.is_some()) + { + return true; + } + + if available_models + .iter() + .any(|preset| preset.upgrade.as_ref().map(|u| u.id.as_str()) == Some(target_model)) + { + return true; + } + + false } -fn migration_prompt_hidden(config: &Config, migration_config_key: &str) -> Option { +fn migration_prompt_hidden(config: &Config, migration_config_key: &str) -> bool { match migration_config_key { - HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG => { - config.notices.hide_gpt_5_1_codex_max_migration_prompt + HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG => config + .notices + .hide_gpt_5_1_codex_max_migration_prompt + .unwrap_or(false), + HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG => { + config.notices.hide_gpt5_1_migration_prompt.unwrap_or(false) } - HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG => config.notices.hide_gpt5_1_migration_prompt, - _ => None, + _ => false, } } @@ -137,7 +154,6 @@ async fn handle_model_migration_prompt_if_needed( config: &mut Config, model: &str, app_event_tx: &AppEventSender, - auth_mode: Option, models_manager: Arc, ) -> Option { let available_models = models_manager.list_models(config).await; @@ -152,26 +168,52 @@ async fn handle_model_migration_prompt_if_needed( migration_config_key, }) = upgrade { - if !migration_prompt_allows_auth_mode(auth_mode, migration_config_key.as_str()) { + if migration_prompt_hidden(config, migration_config_key.as_str()) { return None; } let target_model = target_model.to_string(); - let hide_prompt_flag = migration_prompt_hidden(config, migration_config_key.as_str()); if !should_show_model_migration_prompt( model, &target_model, - hide_prompt_flag, - available_models.clone(), + &config.notices.model_migrations, + &available_models, ) { return None; } - let prompt_copy = migration_copy_for_config(migration_config_key.as_str()); + let current_preset = available_models.iter().find(|preset| preset.model == model); + let target_preset = available_models + .iter() + .find(|preset| preset.model == target_model); + let target_display_name = target_preset + .map(|preset| preset.display_name.clone()) + .unwrap_or_else(|| target_model.clone()); + let heading_label = if target_display_name == model { + target_model.clone() + } else { + target_display_name.clone() + }; + let target_description = target_preset.and_then(|preset| { + if preset.description.is_empty() { + None + } else { + Some(preset.description.clone()) + } + }); + let can_opt_out = current_preset.is_some(); + let prompt_copy = migration_copy_for_models( + model, + &target_model, + heading_label, + target_description, + can_opt_out, + ); match run_model_migration_prompt(tui, prompt_copy).await { ModelMigrationOutcome::Accepted => { app_event_tx.send(AppEvent::PersistModelMigrationPromptAcknowledged { - migration_config: migration_config_key.to_string(), + from_model: model.to_string(), + to_model: target_model.clone(), }); config.model = Some(target_model.clone()); @@ -197,7 +239,8 @@ async fn handle_model_migration_prompt_if_needed( } ModelMigrationOutcome::Rejected => { app_event_tx.send(AppEvent::PersistModelMigrationPromptAcknowledged { - migration_config: migration_config_key.to_string(), + from_model: model.to_string(), + to_model: target_model.clone(), }); } ModelMigrationOutcome::Exit => { @@ -276,7 +319,6 @@ impl App { let (app_event_tx, mut app_event_rx) = unbounded_channel(); let app_event_tx = AppEventSender::new(app_event_tx); - let auth_mode = auth_manager.auth().map(|auth| auth.mode); let conversation_manager = Arc::new(ConversationManager::new( auth_manager.clone(), SessionSource::Cli, @@ -290,7 +332,6 @@ impl App { &mut config, model.as_str(), &app_event_tx, - auth_mode, conversation_manager.get_models_manager(), ) .await; @@ -948,13 +989,19 @@ impl App { )); } } - AppEvent::PersistModelMigrationPromptAcknowledged { migration_config } => { + AppEvent::PersistModelMigrationPromptAcknowledged { + from_model, + to_model, + } => { if let Err(err) = ConfigEditsBuilder::new(&self.config.codex_home) - .set_hide_model_migration_prompt(&migration_config, true) + .record_model_migration_seen(from_model.as_str(), to_model.as_str()) .apply() .await { - tracing::error!(error = %err, "failed to persist model migration prompt acknowledgement"); + tracing::error!( + error = %err, + "failed to persist model migration prompt acknowledgement" + ); self.chat_widget.add_error_message(format!( "Failed to save model migration prompt preference: {err}" )); @@ -1128,28 +1175,6 @@ impl App { } } -fn migration_prompt_allowed_auth_modes(migration_config_key: &str) -> Option<&'static [AuthMode]> { - match migration_config_key { - HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG => Some(&GPT_5_1_MIGRATION_AUTH_MODES), - HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG => Some(&GPT_5_1_CODEX_MIGRATION_AUTH_MODES), - _ => None, - } -} - -fn migration_prompt_allows_auth_mode( - auth_mode: Option, - migration_config_key: &str, -) -> bool { - if let Some(allowed_modes) = migration_prompt_allowed_auth_modes(migration_config_key) { - match auth_mode { - None => true, - Some(mode) => allowed_modes.contains(&mode), - } - } else { - auth_mode != Some(AuthMode::ApiKey) - } -} - #[cfg(test)] mod tests { use super::*; @@ -1259,51 +1284,54 @@ mod tests { #[test] fn model_migration_prompt_only_shows_for_deprecated_models() { + let seen = BTreeMap::new(); assert!(should_show_model_migration_prompt( "gpt-5", "gpt-5.1", - None, - all_model_presets() + &seen, + &all_model_presets() )); assert!(should_show_model_migration_prompt( "gpt-5-codex", "gpt-5.1-codex", - None, - all_model_presets() + &seen, + &all_model_presets() )); assert!(should_show_model_migration_prompt( "gpt-5-codex-mini", "gpt-5.1-codex-mini", - None, - all_model_presets() + &seen, + &all_model_presets() )); assert!(should_show_model_migration_prompt( "gpt-5.1-codex", "gpt-5.1-codex-max", - None, - all_model_presets() + &seen, + &all_model_presets() )); assert!(!should_show_model_migration_prompt( "gpt-5.1-codex", "gpt-5.1-codex", - None, - all_model_presets() + &seen, + &all_model_presets() )); } #[test] fn model_migration_prompt_respects_hide_flag_and_self_target() { + let mut seen = BTreeMap::new(); + seen.insert("gpt-5".to_string(), "gpt-5.1".to_string()); assert!(!should_show_model_migration_prompt( "gpt-5", "gpt-5.1", - Some(true), - all_model_presets() + &seen, + &all_model_presets() )); assert!(!should_show_model_migration_prompt( "gpt-5.1", "gpt-5.1", - None, - all_model_presets() + &seen, + &all_model_presets() )); } @@ -1457,40 +1485,4 @@ mod tests { Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string()) ); } - - #[test] - fn gpt5_migration_allows_api_key_and_chatgpt() { - assert!(migration_prompt_allows_auth_mode( - Some(AuthMode::ApiKey), - HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG, - )); - assert!(migration_prompt_allows_auth_mode( - Some(AuthMode::ChatGPT), - HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG, - )); - } - - #[test] - fn gpt_5_1_codex_max_migration_limits_to_chatgpt() { - assert!(migration_prompt_allows_auth_mode( - Some(AuthMode::ChatGPT), - HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG, - )); - assert!(migration_prompt_allows_auth_mode( - Some(AuthMode::ApiKey), - HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG, - )); - } - - #[test] - fn other_migrations_block_api_key() { - assert!(!migration_prompt_allows_auth_mode( - Some(AuthMode::ApiKey), - "unknown" - )); - assert!(migration_prompt_allows_auth_mode( - Some(AuthMode::ChatGPT), - "unknown" - )); - } } diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index c92dab4b3a..adb9c1308e 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -139,7 +139,8 @@ pub(crate) enum AppEvent { /// Persist the acknowledgement flag for the model migration prompt. PersistModelMigrationPromptAcknowledged { - migration_config: String, + from_model: String, + to_model: String, }, /// Skip the next world-writable scan (one-shot) after a user-confirmed continue. diff --git a/codex-rs/tui/src/model_migration.rs b/codex-rs/tui/src/model_migration.rs index cbce1f1bb0..fa59b8fcc9 100644 --- a/codex-rs/tui/src/model_migration.rs +++ b/codex-rs/tui/src/model_migration.rs @@ -7,8 +7,6 @@ use crate::selection_list::selection_option_row; use crate::tui::FrameRequester; use crate::tui::Tui; use crate::tui::TuiEvent; -use codex_core::openai_models::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG; -use codex_core::openai_models::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; @@ -57,11 +55,44 @@ impl MigrationMenuOption { } } -pub(crate) fn migration_copy_for_config(migration_config_key: &str) -> ModelMigrationCopy { - match migration_config_key { - HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG => gpt5_migration_copy(), - HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG => gpt_5_1_codex_max_migration_copy(), - _ => gpt_5_1_codex_max_migration_copy(), +pub(crate) fn migration_copy_for_models( + current_model: &str, + target_model: &str, + target_display_name: String, + target_description: Option, + can_opt_out: bool, +) -> ModelMigrationCopy { + let heading_text = Span::from(format!("Try {target_display_name}")).bold(); + let description_line = target_description + .filter(|desc| !desc.is_empty()) + .map(Line::from) + .unwrap_or_else(|| { + Line::from(format!( + "{target_display_name} is recommended for better performance and reliability." + )) + }); + + let mut content = vec![ + Line::from(format!( + "We recommend switching from {current_model} to {target_model}." + )), + Line::from(""), + description_line, + Line::from(""), + ]; + + if can_opt_out { + content.push(Line::from(format!( + "You can continue using {current_model} if you prefer." + ))); + } else { + content.push(Line::from("Press enter to continue".dim())); + } + + ModelMigrationCopy { + heading: vec![heading_text], + content, + can_opt_out, } } @@ -69,26 +100,7 @@ pub(crate) async fn run_model_migration_prompt( tui: &mut Tui, copy: ModelMigrationCopy, ) -> ModelMigrationOutcome { - // Render the prompt on the terminal's alternate screen so exiting or cancelling - // does not leave a large blank region in the normal scrollback. This does not - // change the prompt's appearance – only where it is drawn. - struct AltScreenGuard<'a> { - tui: &'a mut Tui, - } - impl<'a> AltScreenGuard<'a> { - fn enter(tui: &'a mut Tui) -> Self { - let _ = tui.enter_alt_screen(); - Self { tui } - } - } - impl Drop for AltScreenGuard<'_> { - fn drop(&mut self) { - let _ = self.tui.leave_alt_screen(); - } - } - let alt = AltScreenGuard::enter(tui); - let mut screen = ModelMigrationScreen::new(alt.tui.frame_requester(), copy); let _ = alt.tui.draw(u16::MAX, |frame| { @@ -178,39 +190,15 @@ impl ModelMigrationScreen { return; } - if key_event.modifiers.contains(KeyModifiers::CONTROL) - && matches!(key_event.code, KeyCode::Char('c') | KeyCode::Char('d')) - { + if is_ctrl_exit_combo(key_event) { self.exit(); return; } - if !self.copy.can_opt_out { - if matches!(key_event.code, KeyCode::Esc | KeyCode::Enter) { - self.accept(); - } - return; - } - - match key_event.code { - KeyCode::Up | KeyCode::Char('k') => { - self.highlight_option(MigrationMenuOption::TryNewModel); - } - KeyCode::Down | KeyCode::Char('j') => { - self.highlight_option(MigrationMenuOption::UseExistingModel); - } - KeyCode::Char('1') => { - self.highlight_option(MigrationMenuOption::TryNewModel); - self.accept(); - } - KeyCode::Char('2') => { - self.highlight_option(MigrationMenuOption::UseExistingModel); - self.reject(); - } - KeyCode::Enter | KeyCode::Esc => { - self.confirm_selection(); - } - _ => {} + if self.copy.can_opt_out { + self.handle_menu_key(key_event.code); + } else if matches!(key_event.code, KeyCode::Esc | KeyCode::Enter) { + self.accept(); } } @@ -228,110 +216,125 @@ impl WidgetRef for &ModelMigrationScreen { Clear.render(area, buf); let mut column = ColumnRenderable::new(); - column.push(""); - let mut heading = vec![Span::raw("> ")]; - heading.extend(self.copy.heading.clone()); - column.push(Line::from(heading)); + column.push(self.heading_line()); column.push(Line::from("")); - - for (idx, line) in self.copy.content.iter().enumerate() { - if idx != 0 { - column.push(Line::from("")); - } - - column.push( - Paragraph::new(line.clone()) - .wrap(Wrap { trim: false }) - .inset(Insets::tlbr(0, 2, 0, 0)), - ); - } - + self.render_content(&mut column); if self.copy.can_opt_out { - column.push(Line::from("")); - column.push( - Paragraph::new("Choose how you'd like Codex to proceed.") - .wrap(Wrap { trim: false }) - .inset(Insets::tlbr(0, 2, 0, 0)), - ); - column.push(Line::from("")); - - for (idx, option) in MigrationMenuOption::all().into_iter().enumerate() { - column.push(selection_option_row( - idx, - option.label().to_string(), - self.highlighted_option == option, - )); - } - - column.push(Line::from("")); - column.push( - Line::from(vec![ - "Use ".dim(), - key_hint::plain(KeyCode::Up).into(), - "/".dim(), - key_hint::plain(KeyCode::Down).into(), - " to move, press ".dim(), - key_hint::plain(KeyCode::Enter).into(), - " to confirm".dim(), - ]) - .inset(Insets::tlbr(0, 2, 0, 0)), - ); + self.render_menu(&mut column); } column.render(area, buf); } } -fn gpt_5_1_codex_max_migration_copy() -> ModelMigrationCopy { - ModelMigrationCopy { - heading: vec!["Codex just got an upgrade. Introducing gpt-5.1-codex-max".bold()], - content: vec![ - Line::from( - "Codex is now powered by gpt-5.1-codex-max, our latest frontier agentic coding model. It is smarter and faster than its predecessors and capable of long-running project-scale work.", - ), +impl ModelMigrationScreen { + fn handle_menu_key(&mut self, code: KeyCode) { + match code { + KeyCode::Up | KeyCode::Char('k') => { + self.highlight_option(MigrationMenuOption::TryNewModel); + } + KeyCode::Down | KeyCode::Char('j') => { + self.highlight_option(MigrationMenuOption::UseExistingModel); + } + KeyCode::Char('1') => { + self.highlight_option(MigrationMenuOption::TryNewModel); + self.accept(); + } + KeyCode::Char('2') => { + self.highlight_option(MigrationMenuOption::UseExistingModel); + self.reject(); + } + KeyCode::Enter | KeyCode::Esc => self.confirm_selection(), + _ => {} + } + } + + fn heading_line(&self) -> Line<'static> { + let mut heading = vec![Span::raw("> ")]; + heading.extend(self.copy.heading.iter().cloned()); + Line::from(heading) + } + + fn render_content(&self, column: &mut ColumnRenderable) { + self.render_lines(&self.copy.content, column); + } + + fn render_lines(&self, lines: &[Line<'static>], column: &mut ColumnRenderable) { + for line in lines { + column.push( + Paragraph::new(line.clone()) + .wrap(Wrap { trim: false }) + .inset(Insets::tlbr(0, 2, 0, 0)), + ); + } + } + + fn render_menu(&self, column: &mut ColumnRenderable) { + column.push(Line::from("")); + column.push( + Paragraph::new("Choose how you'd like Codex to proceed.") + .wrap(Wrap { trim: false }) + .inset(Insets::tlbr(0, 2, 0, 0)), + ); + column.push(Line::from("")); + + for (idx, option) in MigrationMenuOption::all().into_iter().enumerate() { + column.push(selection_option_row( + idx, + option.label().to_string(), + self.highlighted_option == option, + )); + } + + column.push(Line::from("")); + column.push( Line::from(vec![ - "Learn more at ".into(), - "https://openai.com/index/gpt-5-1-codex-max/" - .cyan() - .underlined(), - ".".into(), - ]), - ], - can_opt_out: true, + "Use ".dim(), + key_hint::plain(KeyCode::Up).into(), + "/".dim(), + key_hint::plain(KeyCode::Down).into(), + " to move, press ".dim(), + key_hint::plain(KeyCode::Enter).into(), + " to confirm".dim(), + ]) + .inset(Insets::tlbr(0, 2, 0, 0)), + ); } } -fn gpt5_migration_copy() -> ModelMigrationCopy { - ModelMigrationCopy { - heading: vec!["Introducing our gpt-5.1 models".bold()], - content: vec![ - Line::from( - "We've upgraded our family of models supported in Codex to gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.", - ), - Line::from( - "You can continue using legacy models by specifying them directly with the -m option or in your config.toml.", - ), - Line::from(vec![ - "Learn more at ".into(), - "https://openai.com/index/gpt-5-1/".cyan().underlined(), - ".".into(), - ]), - Line::from(vec!["Press enter to continue".dim()]), - ], - can_opt_out: false, +// Render the prompt on the terminal's alternate screen so exiting or cancelling +// does not leave a large blank region in the normal scrollback. This does not +// change the prompt's appearance – only where it is drawn. +struct AltScreenGuard<'a> { + tui: &'a mut Tui, +} + +impl<'a> AltScreenGuard<'a> { + fn enter(tui: &'a mut Tui) -> Self { + let _ = tui.enter_alt_screen(); + Self { tui } } } +impl Drop for AltScreenGuard<'_> { + fn drop(&mut self) { + let _ = self.tui.leave_alt_screen(); + } +} + +fn is_ctrl_exit_combo(key_event: KeyEvent) -> bool { + key_event.modifiers.contains(KeyModifiers::CONTROL) + && matches!(key_event.code, KeyCode::Char('c') | KeyCode::Char('d')) +} + #[cfg(test)] mod tests { use super::ModelMigrationScreen; - use super::gpt_5_1_codex_max_migration_copy; - use super::migration_copy_for_config; + use super::migration_copy_for_models; use crate::custom_terminal::Terminal; use crate::test_backend::VT100Backend; use crate::tui::FrameRequester; - use codex_core::openai_models::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use insta::assert_snapshot; @@ -340,14 +343,20 @@ mod tests { #[test] fn prompt_snapshot() { let width: u16 = 60; - let height: u16 = 20; + let height: u16 = 28; let backend = VT100Backend::new(width, height); let mut terminal = Terminal::with_options(backend).expect("terminal"); terminal.set_viewport_area(Rect::new(0, 0, width, height)); let screen = ModelMigrationScreen::new( FrameRequester::test_dummy(), - gpt_5_1_codex_max_migration_copy(), + migration_copy_for_models( + "gpt-5.1-codex-mini", + "gpt-5.1-codex-max", + "gpt-5.1-codex-max".to_string(), + Some("Latest Codex-optimized flagship for deep and fast reasoning.".to_string()), + true, + ), ); { @@ -361,13 +370,19 @@ mod tests { #[test] fn prompt_snapshot_gpt5_family() { - let backend = VT100Backend::new(65, 12); + let backend = VT100Backend::new(65, 22); let mut terminal = Terminal::with_options(backend).expect("terminal"); - terminal.set_viewport_area(Rect::new(0, 0, 65, 12)); + terminal.set_viewport_area(Rect::new(0, 0, 65, 22)); let screen = ModelMigrationScreen::new( FrameRequester::test_dummy(), - migration_copy_for_config(HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG), + migration_copy_for_models( + "gpt-5", + "gpt-5.1", + "gpt-5.1".to_string(), + Some("Broad world knowledge with strong general reasoning.".to_string()), + false, + ), ); { let mut frame = terminal.get_frame(); @@ -379,13 +394,19 @@ mod tests { #[test] fn prompt_snapshot_gpt5_codex() { - let backend = VT100Backend::new(60, 12); + let backend = VT100Backend::new(60, 22); let mut terminal = Terminal::with_options(backend).expect("terminal"); - terminal.set_viewport_area(Rect::new(0, 0, 60, 12)); + terminal.set_viewport_area(Rect::new(0, 0, 60, 22)); let screen = ModelMigrationScreen::new( FrameRequester::test_dummy(), - migration_copy_for_config(HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG), + migration_copy_for_models( + "gpt-5-codex", + "gpt-5.1-codex-max", + "gpt-5.1-codex-max".to_string(), + Some("Latest Codex-optimized flagship for deep and fast reasoning.".to_string()), + false, + ), ); { let mut frame = terminal.get_frame(); @@ -397,13 +418,19 @@ mod tests { #[test] fn prompt_snapshot_gpt5_codex_mini() { - let backend = VT100Backend::new(60, 12); + let backend = VT100Backend::new(60, 22); let mut terminal = Terminal::with_options(backend).expect("terminal"); - terminal.set_viewport_area(Rect::new(0, 0, 60, 12)); + terminal.set_viewport_area(Rect::new(0, 0, 60, 22)); let screen = ModelMigrationScreen::new( FrameRequester::test_dummy(), - migration_copy_for_config(HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG), + migration_copy_for_models( + "gpt-5-codex-mini", + "gpt-5.1-codex-mini", + "gpt-5.1-codex-mini".to_string(), + Some("Optimized for codex. Cheaper, faster, but less capable.".to_string()), + false, + ), ); { let mut frame = terminal.get_frame(); @@ -417,7 +444,13 @@ mod tests { fn escape_key_accepts_prompt() { let mut screen = ModelMigrationScreen::new( FrameRequester::test_dummy(), - gpt_5_1_codex_max_migration_copy(), + migration_copy_for_models( + "gpt-old", + "gpt-new", + "gpt-new".to_string(), + Some("Latest recommended model for better performance.".to_string()), + true, + ), ); // Simulate pressing Escape @@ -437,7 +470,13 @@ mod tests { fn selecting_use_existing_model_rejects_upgrade() { let mut screen = ModelMigrationScreen::new( FrameRequester::test_dummy(), - gpt_5_1_codex_max_migration_copy(), + migration_copy_for_models( + "gpt-old", + "gpt-new", + "gpt-new".to_string(), + Some("Latest recommended model for better performance.".to_string()), + true, + ), ); screen.handle_key(KeyEvent::new( diff --git a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt.snap b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt.snap index 1f95142169..f5fa4e4739 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt.snap @@ -1,15 +1,18 @@ --- source: tui/src/model_migration.rs +assertion_line: 368 expression: terminal.backend() --- -> Codex just got an upgrade. Introducing gpt-5.1-codex-max - Codex is now powered by gpt-5.1-codex-max, our latest - frontier agentic coding model. It is smarter and faster - than its predecessors and capable of long-running - project-scale work. +> Try gpt-5.1-codex-max - Learn more at https://openai.com/index/gpt-5-1-codex-max/. + We recommend switching from gpt-5.1-codex-mini to + gpt-5.1-codex-max. + + Latest Codex-optimized flagship for deep and fast + reasoning. + + You can continue using gpt-5.1-codex-mini if you prefer. Choose how you'd like Codex to proceed. diff --git a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex.snap b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex.snap index 52718e5793..00eb75e0a5 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex.snap @@ -1,15 +1,15 @@ --- source: tui/src/model_migration.rs +assertion_line: 416 expression: terminal.backend() --- -> Introducing our gpt-5.1 models - We've upgraded our family of models supported in Codex to - gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini. +> Try gpt-5.1-codex-max - You can continue using legacy models by specifying them - directly with the -m option or in your config.toml. + We recommend switching from gpt-5-codex to + gpt-5.1-codex-max. - Learn more at https://openai.com/index/gpt-5-1/. + Latest Codex-optimized flagship for deep and fast + reasoning. Press enter to continue diff --git a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap index 52718e5793..e8d3ed3b41 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap @@ -1,15 +1,14 @@ --- source: tui/src/model_migration.rs +assertion_line: 440 expression: terminal.backend() --- -> Introducing our gpt-5.1 models - We've upgraded our family of models supported in Codex to - gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini. +> Try gpt-5.1-codex-mini - You can continue using legacy models by specifying them - directly with the -m option or in your config.toml. + We recommend switching from gpt-5-codex-mini to + gpt-5.1-codex-mini. - Learn more at https://openai.com/index/gpt-5-1/. + Optimized for codex. Cheaper, faster, but less capable. Press enter to continue diff --git a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_family.snap b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_family.snap index 52718e5793..dba2430db7 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_family.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_family.snap @@ -1,15 +1,13 @@ --- source: tui/src/model_migration.rs +assertion_line: 392 expression: terminal.backend() --- -> Introducing our gpt-5.1 models - We've upgraded our family of models supported in Codex to - gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini. +> Try gpt-5.1 - You can continue using legacy models by specifying them - directly with the -m option or in your config.toml. + We recommend switching from gpt-5 to gpt-5.1. - Learn more at https://openai.com/index/gpt-5-1/. + Broad world knowledge with strong general reasoning. Press enter to continue From 9e91e49edbd1715a5a4c155d0837f97d0f6276a7 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Thu, 11 Dec 2025 17:58:35 -0800 Subject: [PATCH 16/77] Revert "fix(apply-patch): preserve CRLF line endings on Windows" (#7903) Reverts openai/codex#7515 --- codex-rs/apply-patch/src/lib.rs | 161 +------------------ codex-rs/core/tests/suite/apply_patch_cli.rs | 91 ----------- 2 files changed, 8 insertions(+), 244 deletions(-) diff --git a/codex-rs/apply-patch/src/lib.rs b/codex-rs/apply-patch/src/lib.rs index fe4fe584dc..645f396845 100644 --- a/codex-rs/apply-patch/src/lib.rs +++ b/codex-rs/apply-patch/src/lib.rs @@ -699,7 +699,13 @@ fn derive_new_contents_from_chunks( } }; - let original_lines: Vec = build_lines_from_contents(&original_contents); + let mut original_lines: Vec = original_contents.split('\n').map(String::from).collect(); + + // Drop the trailing empty element that results from the final newline so + // that line counts match the behaviour of standard `diff`. + if original_lines.last().is_some_and(String::is_empty) { + original_lines.pop(); + } let replacements = compute_replacements(&original_lines, path, chunks)?; let new_lines = apply_replacements(original_lines, &replacements); @@ -707,67 +713,13 @@ fn derive_new_contents_from_chunks( if !new_lines.last().is_some_and(String::is_empty) { new_lines.push(String::new()); } - let new_contents = build_contents_from_lines(&original_contents, &new_lines); + let new_contents = new_lines.join("\n"); Ok(AppliedPatch { original_contents, new_contents, }) } -// TODO(dylan-hurd-oai): I think we can migrate to just use `contents.lines()` -// across all platforms. -fn build_lines_from_contents(contents: &str) -> Vec { - if cfg!(windows) { - contents.lines().map(String::from).collect() - } else { - let mut lines: Vec = contents.split('\n').map(String::from).collect(); - - // Drop the trailing empty element that results from the final newline so - // that line counts match the behaviour of standard `diff`. - if lines.last().is_some_and(String::is_empty) { - lines.pop(); - } - - lines - } -} - -fn build_contents_from_lines(original_contents: &str, lines: &[String]) -> String { - if cfg!(windows) { - // for now, only compute this if we're on Windows. - let uses_crlf = contents_uses_crlf(original_contents); - if uses_crlf { - lines.join("\r\n") - } else { - lines.join("\n") - } - } else { - lines.join("\n") - } -} - -/// Detects whether the source file uses Windows CRLF line endings consistently. -/// We only consider a file CRLF-formatted if every newline is part of a -/// CRLF sequence. This avoids rewriting an LF-formatted file that merely -/// contains embedded sequences of "\r\n". -/// -/// Returns `true` if the file uses CRLF line endings, `false` otherwise. -fn contents_uses_crlf(contents: &str) -> bool { - let bytes = contents.as_bytes(); - let mut n_newlines = 0usize; - let mut n_crlf = 0usize; - for i in 0..bytes.len() { - if bytes[i] == b'\n' { - n_newlines += 1; - if i > 0 && bytes[i - 1] == b'\r' { - n_crlf += 1; - } - } - } - - n_newlines > 0 && n_crlf == n_newlines -} - /// Compute a list of replacements needed to transform `original_lines` into the /// new lines, given the patch `chunks`. Each replacement is returned as /// `(start_index, old_len, new_lines)`. @@ -1414,72 +1366,6 @@ PATCH"#, assert_eq!(contents, "a\nB\nc\nd\nE\nf\ng\n"); } - /// Ensure CRLF line endings are preserved for updated files on Windows‑style inputs. - #[cfg(windows)] - #[test] - fn test_preserve_crlf_line_endings_on_update() { - let dir = tempdir().unwrap(); - let path = dir.path().join("crlf.txt"); - - // Original file uses CRLF (\r\n) endings. - std::fs::write(&path, b"a\r\nb\r\nc\r\n").unwrap(); - - // Replace `b` -> `B` and append `d`. - let patch = wrap_patch(&format!( - r#"*** Update File: {} -@@ - a --b -+B -@@ - c -+d -*** End of File"#, - path.display() - )); - - let mut stdout = Vec::new(); - let mut stderr = Vec::new(); - apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); - - let out = std::fs::read(&path).unwrap(); - // Expect all CRLF endings; count occurrences of CRLF and ensure there are 4 lines. - let content = String::from_utf8_lossy(&out); - assert!(content.contains("\r\n")); - // No bare LF occurrences immediately preceding a non-CR: the text should not contain "a\nb". - assert!(!content.contains("a\nb")); - // Validate exact content sequence with CRLF delimiters. - assert_eq!(content, "a\r\nB\r\nc\r\nd\r\n"); - } - - /// Ensure CRLF inputs with embedded carriage returns in the content are preserved. - #[cfg(windows)] - #[test] - fn test_preserve_crlf_embedded_carriage_returns_on_append() { - let dir = tempdir().unwrap(); - let path = dir.path().join("crlf_cr_content.txt"); - - // Original file: first line has a literal '\r' in the content before the CRLF terminator. - std::fs::write(&path, b"foo\r\r\nbar\r\n").unwrap(); - - // Append a new line without modifying existing ones. - let patch = wrap_patch(&format!( - r#"*** Update File: {} -@@ -+BAZ -*** End of File"#, - path.display() - )); - - let mut stdout = Vec::new(); - let mut stderr = Vec::new(); - apply_patch(&patch, &mut stdout, &mut stderr).unwrap(); - - let out = std::fs::read(&path).unwrap(); - // CRLF endings must be preserved and the extra CR in "foo\r\r" must not be collapsed. - assert_eq!(out.as_slice(), b"foo\r\r\nbar\r\nBAZ\r\n"); - } - #[test] fn test_pure_addition_chunk_followed_by_removal() { let dir = tempdir().unwrap(); @@ -1665,37 +1551,6 @@ PATCH"#, assert_eq!(expected, diff); } - /// For LF-only inputs with a trailing newline ensure that the helper used - /// on Windows-style builds drops the synthetic trailing empty element so - /// replacements behave like standard `diff` line numbering. - #[test] - fn test_derive_new_contents_lf_trailing_newline() { - let dir = tempdir().unwrap(); - let path = dir.path().join("lf_trailing_newline.txt"); - fs::write(&path, "foo\nbar\n").unwrap(); - - let patch = wrap_patch(&format!( - r#"*** Update File: {} -@@ - foo --bar -+BAR -"#, - path.display() - )); - - let patch = parse_patch(&patch).unwrap(); - let chunks = match patch.hunks.as_slice() { - [Hunk::UpdateFile { chunks, .. }] => chunks, - _ => panic!("Expected a single UpdateFile hunk"), - }; - - let AppliedPatch { new_contents, .. } = - derive_new_contents_from_chunks(&path, chunks).unwrap(); - - assert_eq!(new_contents, "foo\nBAR\n"); - } - #[test] fn test_unified_diff_insert_at_eof() { // Insert a new line at end‑of‑file. diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index 70c8aa4fa4..880e74d959 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -1250,94 +1250,3 @@ async fn apply_patch_change_context_disambiguates_target( assert_eq!(contents, "fn a\nx=10\ny=2\nfn b\nx=11\ny=20\n"); Ok(()) } - -/// Ensure that applying a patch can update a CRLF file with unicode characters. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[test_case(ApplyPatchModelOutput::Freeform)] -#[test_case(ApplyPatchModelOutput::Function)] -#[test_case(ApplyPatchModelOutput::Shell)] -#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] -#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)] -async fn apply_patch_cli_updates_unicode_characters( - model_output: ApplyPatchModelOutput, -) -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("unicode.txt"); - fs::write(&target, "first ⚠️\nsecond ❌\nthird 🔥\n")?; - - let patch = format!( - r#"*** Begin Patch -*** Update File: {} -@@ - first ⚠️ --second ❌ -+SECOND ✅ -@@ - third 🔥 -+FOURTH -*** End of File -*** End Patch"#, - target.display() - ); - let call_id = "apply-unicode-update"; - mount_apply_patch(&harness, call_id, patch.as_str(), "ok", model_output).await; - - harness - .submit("update unicode characters via apply_patch CLI") - .await?; - - let file_contents = fs::read(&target)?; - let content = String::from_utf8_lossy(&file_contents); - assert_eq!(content, "first ⚠️\nSECOND ✅\nthird 🔥\nFOURTH\n"); - Ok(()) -} - -/// Ensure that applying a patch via the CLI preserves CRLF line endings for -/// Windows-style inputs even when updating the file contents. -#[cfg(windows)] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[test_case(ApplyPatchModelOutput::Freeform)] -#[test_case(ApplyPatchModelOutput::Function)] -#[test_case(ApplyPatchModelOutput::Shell)] -#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] -#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)] -async fn apply_patch_cli_updates_crlf_file_preserves_line_endings( - model_output: ApplyPatchModelOutput, -) -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("crlf.txt"); - fs::write(&target, b"first\r\nsecond\r\nthird\r\n")?; - - let patch = format!( - r#"*** Begin Patch -*** Update File: {} -@@ - first --second -+SECOND -@@ - third -+FOURTH -*** End of File -*** End Patch"#, - target.display() - ); - let call_id = "apply-crlf-update"; - mount_apply_patch(&harness, call_id, patch.as_str(), "ok", model_output).await; - - harness - .submit("update crlf file via apply_patch CLI") - .await?; - - let file_contents = fs::read(&target)?; - let content = String::from_utf8_lossy(&file_contents); - assert!(content.contains("\r\n")); - assert_eq!(content, "first\r\nSECOND\r\nthird\r\nFOURTH\r\n"); - Ok(()) -} From 163a7e317e562aacb7b02fadc288b10fca4e4abd Mon Sep 17 00:00:00 2001 From: Shijie Rao Date: Thu, 11 Dec 2025 18:56:55 -0800 Subject: [PATCH 17/77] feat: use latest disk value for mcp servers status (#7907) ### Summary Instead of stale in memory config value for listing mcp server statuses, we pull the latest disk value. --- codex-rs/app-server/src/codex_message_processor.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index c62734f24e..9f4227b2df 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -2079,12 +2079,19 @@ impl CodexMessageProcessor { } async fn list_mcp_servers(&self, request_id: RequestId, params: ListMcpServersParams) { - let snapshot = collect_mcp_snapshot(self.config.as_ref()).await; + let config = match self.load_latest_config().await { + Ok(config) => config, + Err(error) => { + self.outgoing.send_error(request_id, error).await; + return; + } + }; + + let snapshot = collect_mcp_snapshot(&config).await; let tools_by_server = group_tools_by_server(&snapshot.tools); - let mut server_names: Vec = self - .config + let mut server_names: Vec = config .mcp_servers .keys() .cloned() From 190fa9e1048dd231bd1598db2ca1d11a440e199b Mon Sep 17 00:00:00 2001 From: Victor Vannara Date: Thu, 11 Dec 2025 21:18:47 -0800 Subject: [PATCH 18/77] docs: clarify xhigh reasoning effort on gpt-5.2 (#7911) ## Changes - Update config docs and example config comments to state that "xhigh" is supported on gpt-5.2 as well as gpt-5.1-codex-max - Adjust the FAQ model-support section to reflect broader xhigh availability --- docs/config.md | 2 +- docs/example-config.md | 2 +- docs/faq.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/config.md b/docs/config.md index 2ac775528f..ca4ba015e9 100644 --- a/docs/config.md +++ b/docs/config.md @@ -195,7 +195,7 @@ If the selected model is known to support reasoning (for example: `o3`, `o4-mini - `"low"` - `"medium"` (default) - `"high"` -- `"xhigh"` (available only on `gpt-5.1-codex-max`) +- `"xhigh"` (available on `gpt-5.1-codex-max` and `gpt-5.2`) Note: to minimize reasoning, choose `"minimal"`. diff --git a/docs/example-config.md b/docs/example-config.md index 2345274e1b..f1d36cd453 100644 --- a/docs/example-config.md +++ b/docs/example-config.md @@ -37,7 +37,7 @@ model_provider = "openai" # Reasoning & Verbosity (Responses API capable models) ################################################################################ -# Reasoning effort: minimal | low | medium | high | xhigh (default: medium; xhigh only on gpt-5.1-codex-max) +# Reasoning effort: minimal | low | medium | high | xhigh (default: medium; xhigh on gpt-5.1-codex-max and gpt-5.2) model_reasoning_effort = "medium" # Reasoning summary: auto | concise | detailed | none (default: auto) diff --git a/docs/faq.md b/docs/faq.md index 37b9ef39d8..93776b957a 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -8,7 +8,7 @@ In 2021, OpenAI released Codex, an AI system designed to generate code from natu ### Which models are supported? -We recommend using Codex with GPT-5.1 Codex Max, our best coding model. The default reasoning level is medium, and you can upgrade to high or xhigh (Codex Max only) for complex tasks with the `/model` command. +We recommend using Codex with GPT-5.1 Codex Max, our best coding model. The default reasoning level is medium, and you can upgrade to high or xhigh (where supported, e.g. `gpt-5.1-codex-max` and `gpt-5.2`) for complex tasks with the `/model` command. You can also use older models by using API-based auth and launching codex with the `--model` flag. From 4312cae0055d8b318bb4cb83f6e855dc335873b4 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 11 Dec 2025 22:07:54 -0800 Subject: [PATCH 19/77] feat: introduce utilities for locating pwsh.exe and powershell.exe (#7893) I am trying to tighten up some of our logic around PowerShell over in https://github.com/openai/codex/pull/7607 and it would be helpful to be more precise about `pwsh.exe` versus `powershell.exe`, as they do not accept the exact same input language. To that end, this PR introduces utilities for detecting each on the system. I think we also want to update `get_user_shell_path()` to return PowerShell instead of `None` on Windows, but we'll consider that in a separate PR since it may require more testing. --- codex-rs/core/src/powershell.rs | 90 +++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/codex-rs/core/src/powershell.rs b/codex-rs/core/src/powershell.rs index 844866262e..8ce540dac3 100644 --- a/codex-rs/core/src/powershell.rs +++ b/codex-rs/core/src/powershell.rs @@ -1,5 +1,8 @@ use std::path::PathBuf; +#[cfg(windows)] +use codex_utils_absolute_path::AbsolutePathBuf; + use crate::shell::ShellType; use crate::shell::detect_shell_type; @@ -40,6 +43,93 @@ pub fn extract_powershell_command(command: &[String]) -> Option<(&str, &str)> { None } +/// This function attempts to find a valid PowerShell executable on the system. +/// It first tries to find pwsh.exe, and if that fails, it tries to find +/// powershell.exe. +#[cfg(windows)] +#[allow(dead_code)] +pub(crate) fn try_find_powershellish_executable_blocking() -> Option { + if let Some(pwsh_path) = try_find_pwsh_executable_blocking() { + Some(pwsh_path) + } else { + try_find_powershell_executable_blocking() + } +} + +/// This function attempts to find a powershell.exe executable on the system. +#[cfg(windows)] +pub(crate) fn try_find_powershell_executable_blocking() -> Option { + try_find_powershellish_executable_in_path(&["powershell.exe"]) +} + +/// This function attempts to find a pwsh.exe executable on the system. +/// Note that pwsh.exe and powershell.exe are different executables: +/// +/// - pwsh.exe is the cross-platform PowerShell Core (v6+) executable +/// - powershell.exe is the Windows PowerShell (v5.1 and earlier) executable +/// +/// Further, while powershell.exe is included by default on Windows systems, +/// pwsh.exe must be installed separately by the user. And even when the user +/// has installed pwsh.exe, it may not be available in the system PATH, in which +/// case we attempt to locate it via other means. +#[cfg(windows)] +pub(crate) fn try_find_pwsh_executable_blocking() -> Option { + if let Some(ps_home) = std::process::Command::new("cmd") + .args(["/C", "pwsh", "-NoProfile", "-Command", "$PSHOME"]) + .output() + .ok() + .and_then(|out| { + if !out.status.success() { + return None; + } + let stdout = String::from_utf8_lossy(&out.stdout); + let trimmed = stdout.trim(); + (!trimmed.is_empty()).then(|| trimmed.to_string()) + }) + { + let candidate = AbsolutePathBuf::resolve_path_against_base("pwsh.exe", &ps_home); + + if let Ok(candidate_abs_path) = candidate + && is_powershellish_executable_available(candidate_abs_path.as_path()) + { + return Some(candidate_abs_path); + } + } + + try_find_powershellish_executable_in_path(&["pwsh.exe"]) +} + +#[cfg(windows)] +fn try_find_powershellish_executable_in_path(candidates: &[&str]) -> Option { + for candidate in candidates { + let Ok(resolved_path) = which::which(candidate) else { + continue; + }; + + if !is_powershellish_executable_available(&resolved_path) { + continue; + } + + let Ok(abs_path) = AbsolutePathBuf::from_absolute_path(resolved_path) else { + continue; + }; + + return Some(abs_path); + } + + None +} + +#[cfg(windows)] +fn is_powershellish_executable_available(powershell_or_pwsh_exe: &std::path::Path) -> bool { + // This test works for both powershell.exe and pwsh.exe. + std::process::Command::new(powershell_or_pwsh_exe) + .args(["-NoLogo", "-NoProfile", "-Command", "Write-Output ok"]) + .output() + .map(|output| output.status.success()) + .unwrap_or(false) +} + #[cfg(test)] mod tests { use super::extract_powershell_command; From 60479a9674c5dd6d7aa433201a8da28463015523 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Fri, 12 Dec 2025 00:28:59 -0600 Subject: [PATCH 20/77] Make skill name and description limit based on characters not byte counts (#7915) This PR changes the length validation for SKILL.md `name` and `description` fields so they use character counts rather than byte counts. Aligned character limits to other harnesses. This addresses #7730. --- codex-rs/core/src/skills/loader.rs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index c014af3147..f3ed7f0239 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -22,8 +22,8 @@ struct SkillFrontmatter { const SKILLS_FILENAME: &str = "SKILL.md"; const SKILLS_DIR_NAME: &str = "skills"; const REPO_ROOT_CONFIG_DIR_NAME: &str = ".codex"; -const MAX_NAME_LEN: usize = 100; -const MAX_DESCRIPTION_LEN: usize = 500; +const MAX_NAME_LEN: usize = 64; +const MAX_DESCRIPTION_LEN: usize = 1024; #[derive(Debug)] enum SkillParseError { @@ -171,7 +171,7 @@ fn validate_field( if value.is_empty() { return Err(SkillParseError::MissingField(field_name)); } - if value.len() > max_len { + if value.chars().count() > max_len { return Err(SkillParseError::InvalidField { field: field_name, reason: format!("exceeds maximum length of {max_len} characters"), @@ -295,12 +295,22 @@ mod tests { #[test] fn enforces_length_limits() { let codex_home = tempfile::tempdir().expect("tempdir"); - let long_desc = "a".repeat(MAX_DESCRIPTION_LEN + 1); - write_skill(&codex_home, "too-long", "toolong", &long_desc); + let max_desc = "\u{1F4A1}".repeat(MAX_DESCRIPTION_LEN); + write_skill(&codex_home, "max-len", "max-len", &max_desc); let cfg = make_config(&codex_home); let outcome = load_skills(&cfg); - assert_eq!(outcome.skills.len(), 0); + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!(outcome.skills.len(), 1); + + let too_long_desc = "\u{1F4A1}".repeat(MAX_DESCRIPTION_LEN + 1); + write_skill(&codex_home, "too-long", "too-long", &too_long_desc); + let outcome = load_skills(&cfg); + assert_eq!(outcome.skills.len(), 1); assert_eq!(outcome.errors.len(), 1); assert!( outcome.errors[0].message.contains("invalid description"), From 9287be762ef45e4405859685e959f67e73d6336c Mon Sep 17 00:00:00 2001 From: Victor Vannara Date: Thu, 11 Dec 2025 22:30:56 -0800 Subject: [PATCH 21/77] fix(tui): show xhigh reasoning warning for gpt-5.2 (#7910) ## Notes - Extend reasoning-effort popup warning eligibility to gpt-5.2* models for the Extra High (xhigh) option. ## Revisions - R2: Remove unnecessary tests and snapshots - R1: initial ## Testing - `just fix`, `cargo test -p codex-tui`, and `cargo test -p codex-tui2` - Manual testing **Before**: image **After** (consistent with GPT 5.1 Codex Max): image image --- codex-rs/tui/src/chatwidget.rs | 3 ++- codex-rs/tui2/src/chatwidget.rs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 82f00f9cac..e3f95a612e 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -2395,7 +2395,8 @@ impl ChatWidget { format!("⚠ {effort_label} reasoning effort can quickly consume Plus plan rate limits.") }); let warn_for_model = preset.model.starts_with("gpt-5.1-codex") - || preset.model.starts_with("gpt-5.1-codex-max"); + || preset.model.starts_with("gpt-5.1-codex-max") + || preset.model.starts_with("gpt-5.2"); struct EffortChoice { stored: Option, diff --git a/codex-rs/tui2/src/chatwidget.rs b/codex-rs/tui2/src/chatwidget.rs index ea29c00d93..320f5b54d8 100644 --- a/codex-rs/tui2/src/chatwidget.rs +++ b/codex-rs/tui2/src/chatwidget.rs @@ -2379,7 +2379,8 @@ impl ChatWidget { format!("⚠ {effort_label} reasoning effort can quickly consume Plus plan rate limits.") }); let warn_for_model = preset.model.starts_with("gpt-5.1-codex") - || preset.model.starts_with("gpt-5.1-codex-max"); + || preset.model.starts_with("gpt-5.1-codex-max") + || preset.model.starts_with("gpt-5.2"); struct EffortChoice { stored: Option, From 49bf49c2faf9daef0a1834c02d648d5c25ca09f0 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 12 Dec 2025 10:48:25 +0000 Subject: [PATCH 22/77] feat: more safe commands (#7728) --- .../src/command_safety/is_safe_command.rs | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/command_safety/is_safe_command.rs b/codex-rs/core/src/command_safety/is_safe_command.rs index 5e7a7034d8..01a52026e2 100644 --- a/codex-rs/core/src/command_safety/is_safe_command.rs +++ b/codex-rs/core/src/command_safety/is_safe_command.rs @@ -47,24 +47,47 @@ fn is_safe_to_call_with_exec(command: &[String]) -> bool { .file_name() .and_then(|osstr| osstr.to_str()) { + Some(cmd) if cfg!(target_os = "linux") && matches!(cmd, "numfmt" | "tac") => true, + #[rustfmt::skip] Some( "cat" | "cd" | + "cut" | "echo" | + "expr" | "false" | "grep" | "head" | + "id" | "ls" | "nl" | + "paste" | "pwd" | + "rev" | + "seq" | + "stat" | "tail" | + "tr" | "true" | + "uname" | + "uniq" | "wc" | - "which") => { + "which" | + "whoami") => { true }, + Some("base64") => { + const UNSAFE_BASE64_OPTIONS: &[&str] = &["-o", "--output"]; + + !command.iter().skip(1).any(|arg| { + UNSAFE_BASE64_OPTIONS.contains(&arg.as_str()) + || arg.starts_with("--output=") + || (arg.starts_with("-o") && arg != "-o") + }) + } + Some("find") => { // Certain options to `find` can delete files, write to files, or // execute arbitrary commands, so we cannot auto-approve the @@ -184,6 +207,7 @@ mod tests { fn known_safe_examples() { assert!(is_safe_to_call_with_exec(&vec_str(&["ls"]))); assert!(is_safe_to_call_with_exec(&vec_str(&["git", "status"]))); + assert!(is_safe_to_call_with_exec(&vec_str(&["base64"]))); assert!(is_safe_to_call_with_exec(&vec_str(&[ "sed", "-n", "1,5p", "file.txt" ]))); @@ -197,6 +221,14 @@ mod tests { assert!(is_safe_to_call_with_exec(&vec_str(&[ "find", ".", "-name", "file.txt" ]))); + + if cfg!(target_os = "linux") { + assert!(is_safe_to_call_with_exec(&vec_str(&["numfmt", "1000"]))); + assert!(is_safe_to_call_with_exec(&vec_str(&["tac", "Cargo.toml"]))); + } else { + assert!(!is_safe_to_call_with_exec(&vec_str(&["numfmt", "1000"]))); + assert!(!is_safe_to_call_with_exec(&vec_str(&["tac", "Cargo.toml"]))); + } } #[test] @@ -233,6 +265,21 @@ mod tests { } } + #[test] + fn base64_output_options_are_unsafe() { + for args in [ + vec_str(&["base64", "-o", "out.bin"]), + vec_str(&["base64", "--output", "out.bin"]), + vec_str(&["base64", "--output=out.bin"]), + vec_str(&["base64", "-ob64.txt"]), + ] { + assert!( + !is_safe_to_call_with_exec(&args), + "expected {args:?} to be considered unsafe due to output option" + ); + } + } + #[test] fn ripgrep_rules() { // Safe ripgrep invocations – none of the unsafe flags are present. From b99ce883fefe242f4d9a87099538a8facc7f8061 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 12 Dec 2025 10:50:50 +0000 Subject: [PATCH 23/77] fix: break tui (#7876) Prevent TUI to loop for ever if one of the RX it's listing on get closed --- codex-rs/tui/src/tui.rs | 61 ++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 25 deletions(-) diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 36f6cc2cb5..f9566da908 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -277,33 +277,42 @@ impl Tui { let event_stream = async_stream::stream! { loop { select! { - Some(Ok(event)) = crossterm_events.next() => { - match event { - Event::Key(key_event) => { - #[cfg(unix)] - if SUSPEND_KEY.is_press(key_event) { - let _ = suspend_context.suspend(&alt_screen_active); - // We continue here after resume. - yield TuiEvent::Draw; - continue; + event_result = crossterm_events.next() => { + match event_result { + Some(Ok(event)) => { + match event { + Event::Key(key_event) => { + #[cfg(unix)] + if SUSPEND_KEY.is_press(key_event) { + let _ = suspend_context.suspend(&alt_screen_active); + // We continue here after resume. + yield TuiEvent::Draw; + continue; + } + yield TuiEvent::Key(key_event); + } + Event::Resize(_, _) => { + yield TuiEvent::Draw; + } + Event::Paste(pasted) => { + yield TuiEvent::Paste(pasted); + } + Event::FocusGained => { + terminal_focused.store(true, Ordering::Relaxed); + crate::terminal_palette::requery_default_colors(); + yield TuiEvent::Draw; + } + Event::FocusLost => { + terminal_focused.store(false, Ordering::Relaxed); + } + _ => {} } - yield TuiEvent::Key(key_event); } - Event::Resize(_, _) => { - yield TuiEvent::Draw; + Some(Err(_)) | None => { + // Exit the loop in case of broken pipe as we will never + // recover from it + break; } - Event::Paste(pasted) => { - yield TuiEvent::Paste(pasted); - } - Event::FocusGained => { - terminal_focused.store(true, Ordering::Relaxed); - crate::terminal_palette::requery_default_colors(); - yield TuiEvent::Draw; - } - Event::FocusLost => { - terminal_focused.store(false, Ordering::Relaxed); - } - _ => {} } } result = draw_rx.recv() => { @@ -316,7 +325,9 @@ impl Tui { yield TuiEvent::Draw; } Err(tokio::sync::broadcast::error::RecvError::Closed) => { - // Sender dropped; stop emitting draws from this source. + // Sender dropped. This stream likely outlived its owning `Tui`; + // exit to avoid spinning on a permanently-closed receiver. + break; } } } From f152b16ed9ead49541bd12d976b590cdbd2938e5 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 12 Dec 2025 11:40:54 +0000 Subject: [PATCH 24/77] fix: race on rx subscription (#7921) Fix race where the PTY was sending first chunk before the subscription to the broadcast --- codex-rs/utils/pty/src/lib.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/codex-rs/utils/pty/src/lib.rs b/codex-rs/utils/pty/src/lib.rs index cd98107ca0..38e86bd2a6 100644 --- a/codex-rs/utils/pty/src/lib.rs +++ b/codex-rs/utils/pty/src/lib.rs @@ -54,6 +54,7 @@ impl ExecCommandSession { pub fn new( writer_tx: mpsc::Sender>, output_tx: broadcast::Sender>, + initial_output_rx: broadcast::Receiver>, killer: Box, reader_handle: JoinHandle<()>, writer_handle: JoinHandle<()>, @@ -62,7 +63,6 @@ impl ExecCommandSession { exit_code: Arc>>, pair: PtyPairWrapper, ) -> (Self, broadcast::Receiver>) { - let initial_output_rx = output_tx.subscribe(); ( Self { writer_tx, @@ -177,6 +177,8 @@ pub async fn spawn_pty_process( let (writer_tx, mut writer_rx) = mpsc::channel::>(128); let (output_tx, _) = broadcast::channel::>(256); + // Subscribe before starting the reader thread. + let initial_output_rx = output_tx.subscribe(); let mut reader = pair.master.try_clone_reader()?; let output_tx_clone = output_tx.clone(); @@ -242,6 +244,7 @@ pub async fn spawn_pty_process( let (session, output_rx) = ExecCommandSession::new( writer_tx, output_tx, + initial_output_rx, killer, reader_handle, writer_handle, From 9429e8b21963e38b8de66400e1fcf412e993feb5 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Fri, 12 Dec 2025 09:50:09 -0800 Subject: [PATCH 25/77] chore(gpt-5.2) prompt update (#7934) ## Summary Updates --- codex-rs/core/gpt_5_2_prompt.md | 37 +-------------------------------- 1 file changed, 1 insertion(+), 36 deletions(-) diff --git a/codex-rs/core/gpt_5_2_prompt.md b/codex-rs/core/gpt_5_2_prompt.md index fdb1e3d5d3..99a3f49bbe 100644 --- a/codex-rs/core/gpt_5_2_prompt.md +++ b/codex-rs/core/gpt_5_2_prompt.md @@ -33,33 +33,6 @@ Unless the user explicitly asks for a plan, asks a question about the code, is b ## Responsiveness -### User Updates Spec -You'll work for stretches with tool calls — it's critical to keep the user updated as you work. - -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 - -Tone: -- Friendly, confident, senior-engineer energy. Positive, collaborative, humble; fix mistakes quickly. - -Content: -- Before the first tool call, 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. - -**Examples:** - -- “I’ve explored the repo; now checking the API route definitions.” -- “Next, I’ll patch the config and update the related tests.” -- “I’m about to scaffold the CLI commands and helper functions.” -- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.” -- “Config’s looking tidy. Next up is patching helpers to keep things in sync.” -- “Finished poking at the DB gateway. I will now chase down error handling.” -- “Alright, build pipeline order is interesting. Checking how it reports failures.” -- “Spotted a clever caching util; now hunting where it gets used.” - ## Planning You have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go. @@ -221,15 +194,7 @@ If you're operating in an existing codebase, you should make sure you do exactly You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified. -## Sharing progress updates - -For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next. - -Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why. - -The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along. - -## Presenting your work and final message +## Presenting your work Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges. From b3ddd50eeeb7ab35fd873f015dae5e0c1db35b01 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Fri, 12 Dec 2025 10:05:02 -0800 Subject: [PATCH 26/77] Remote compact for API-key users (#7835) --- codex-rs/codex-api/src/requests/chat.rs | 4 +- codex-rs/core/src/codex.rs | 5 +- codex-rs/core/src/compact.rs | 14 ++-- codex-rs/core/src/context_manager/history.rs | 6 +- codex-rs/core/src/model_provider_info.rs | 8 +- codex-rs/core/src/rollout/policy.rs | 2 +- codex-rs/core/src/tasks/compact.rs | 5 +- codex-rs/core/tests/suite/compact.rs | 80 +++++++++---------- codex-rs/core/tests/suite/compact_remote.rs | 46 +++++++---- .../core/tests/suite/compact_resume_fork.rs | 1 + codex-rs/protocol/src/models.rs | 8 +- 11 files changed, 101 insertions(+), 78 deletions(-) diff --git a/codex-rs/codex-api/src/requests/chat.rs b/codex-rs/codex-api/src/requests/chat.rs index c1ba89f37a..d5ac188efc 100644 --- a/codex-rs/codex-api/src/requests/chat.rs +++ b/codex-rs/codex-api/src/requests/chat.rs @@ -74,7 +74,7 @@ impl<'a> ChatRequestBuilder<'a> { ResponseItem::CustomToolCallOutput { .. } => {} ResponseItem::WebSearchCall { .. } => {} ResponseItem::GhostSnapshot { .. } => {} - ResponseItem::CompactionSummary { .. } => {} + ResponseItem::Compaction { .. } => {} } } @@ -303,7 +303,7 @@ impl<'a> ChatRequestBuilder<'a> { ResponseItem::Reasoning { .. } | ResponseItem::WebSearchCall { .. } | ResponseItem::Other - | ResponseItem::CompactionSummary { .. } => { + | ResponseItem::Compaction { .. } => { continue; } } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index c546bb583e..04603152b8 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -2175,7 +2175,10 @@ pub(crate) async fn run_task( // as long as compaction works well in getting us way below the token limit, we shouldn't worry about being in an infinite loop. if token_limit_reached { - if should_use_remote_compact_task(&sess) { + if should_use_remote_compact_task( + sess.as_ref(), + &turn_context.client.get_provider(), + ) { run_inline_remote_auto_compact_task(sess.clone(), turn_context.clone()) .await; } else { diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index 7ce325a75a..1a90b7b223 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use crate::ModelProviderInfo; use crate::Prompt; use crate::client_common::ResponseEvent; use crate::codex::Session; @@ -18,7 +19,6 @@ use crate::truncate::TruncationPolicy; use crate::truncate::approx_token_count; use crate::truncate::truncate_text; use crate::util::backoff; -use codex_app_server_protocol::AuthMode; use codex_protocol::items::TurnItem; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; @@ -32,13 +32,11 @@ pub const SUMMARIZATION_PROMPT: &str = include_str!("../templates/compact/prompt pub const SUMMARY_PREFIX: &str = include_str!("../templates/compact/summary_prefix.md"); const COMPACT_USER_MESSAGE_MAX_TOKENS: usize = 20_000; -pub(crate) fn should_use_remote_compact_task(session: &Session) -> bool { - session - .services - .auth_manager - .auth() - .is_some_and(|auth| auth.mode == AuthMode::ChatGPT) - && session.enabled(Feature::RemoteCompaction) +pub(crate) fn should_use_remote_compact_task( + session: &Session, + provider: &ModelProviderInfo, +) -> bool { + provider.is_openai() && session.enabled(Feature::RemoteCompaction) } pub(crate) async fn run_inline_auto_compact_task( diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 9b75c836ab..c18ad7df8e 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -92,7 +92,7 @@ impl ContextManager { encrypted_content: Some(content), .. } - | ResponseItem::CompactionSummary { + | ResponseItem::Compaction { encrypted_content: content, } => estimate_reasoning_length(content.len()) as i64, item => { @@ -258,7 +258,7 @@ impl ContextManager { | ResponseItem::FunctionCall { .. } | ResponseItem::WebSearchCall { .. } | ResponseItem::CustomToolCall { .. } - | ResponseItem::CompactionSummary { .. } + | ResponseItem::Compaction { .. } | ResponseItem::GhostSnapshot { .. } | ResponseItem::Other => item.clone(), } @@ -277,7 +277,7 @@ fn is_api_message(message: &ResponseItem) -> bool { | ResponseItem::LocalShellCall { .. } | ResponseItem::Reasoning { .. } | ResponseItem::WebSearchCall { .. } - | ResponseItem::CompactionSummary { .. } => true, + | ResponseItem::Compaction { .. } => true, ResponseItem::GhostSnapshot { .. } => false, ResponseItem::Other => false, } diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index 22f0d99984..9617392237 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -28,6 +28,8 @@ const MAX_STREAM_MAX_RETRIES: u64 = 100; const MAX_REQUEST_MAX_RETRIES: u64 = 100; pub const CHAT_WIRE_API_DEPRECATION_SUMMARY: &str = r#"Support for the "chat" wire API is deprecated and will soon be removed. Update your model provider definition in config.toml to use wire_api = "responses"."#; +const OPENAI_PROVIDER_NAME: &str = "OpenAI"; + /// Wire protocol that the provider speaks. Most third-party services only /// implement the classic OpenAI Chat Completions JSON schema, whereas OpenAI /// itself (and a handful of others) additionally expose the more modern @@ -210,7 +212,7 @@ impl ModelProviderInfo { } pub fn create_openai_provider() -> ModelProviderInfo { ModelProviderInfo { - name: "OpenAI".into(), + name: OPENAI_PROVIDER_NAME.into(), // Allow users to override the default OpenAI endpoint by // exporting `OPENAI_BASE_URL`. This is useful when pointing // Codex at a proxy, mock server, or Azure-style deployment @@ -247,6 +249,10 @@ impl ModelProviderInfo { requires_openai_auth: true, } } + + pub fn is_openai(&self) -> bool { + self.name == OPENAI_PROVIDER_NAME + } } pub const DEFAULT_LMSTUDIO_PORT: u16 = 1234; diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index fc6e4b9afd..47f051df4f 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -28,7 +28,7 @@ pub(crate) fn should_persist_response_item(item: &ResponseItem) -> bool { | ResponseItem::CustomToolCallOutput { .. } | ResponseItem::WebSearchCall { .. } | ResponseItem::GhostSnapshot { .. } - | ResponseItem::CompactionSummary { .. } => true, + | ResponseItem::Compaction { .. } => true, ResponseItem::Other => false, } } diff --git a/codex-rs/core/src/tasks/compact.rs b/codex-rs/core/src/tasks/compact.rs index 293116c167..a2a268fbb3 100644 --- a/codex-rs/core/src/tasks/compact.rs +++ b/codex-rs/core/src/tasks/compact.rs @@ -25,7 +25,10 @@ impl SessionTask for CompactTask { _cancellation_token: CancellationToken, ) -> Option { let session = session.clone_session(); - if crate::compact::should_use_remote_compact_task(&session) { + if crate::compact::should_use_remote_compact_task( + session.as_ref(), + &ctx.client.get_provider(), + ) { crate::compact_remote::run_remote_compact_task(session, ctx).await } else { crate::compact::run_compact_task(session, ctx, input).await diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index 521a76845a..bffb601eb3 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -38,6 +38,7 @@ use core_test_support::responses::sse_failed; use core_test_support::responses::start_mock_server; use pretty_assertions::assert_eq; use serde_json::json; +use wiremock::MockServer; // --- Test helpers ----------------------------------------------------------- pub(super) const FIRST_REPLY: &str = "FIRST_REPLY"; @@ -100,6 +101,13 @@ fn json_fragment(text: &str) -> String { .to_string() } +fn non_openai_model_provider(server: &MockServer) -> ModelProviderInfo { + let mut provider = built_in_model_providers()["openai"].clone(); + provider.name = "OpenAI (test)".into(); + provider.base_url = Some(format!("{}/v1", server.uri())); + provider +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn summarize_context_three_requests_and_instructions() { skip_if_no_network!(); @@ -127,10 +135,7 @@ async fn summarize_context_three_requests_and_instructions() { let request_log = mount_sse_sequence(&server, vec![sse1, sse2, sse3]).await; // Build config pointing to the mock server and spawn Codex. - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); config.model_provider = model_provider; @@ -324,10 +329,7 @@ async fn manual_compact_uses_custom_prompt() { let custom_prompt = "Use this compact prompt instead"; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); config.model_provider = model_provider; @@ -407,10 +409,7 @@ async fn manual_compact_emits_api_and_local_token_usage_events() { ]); mount_sse_once(&server, sse_compact).await; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); config.model_provider = model_provider; @@ -467,7 +466,11 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { let server = start_mock_server().await; + let non_openai_provider_name = non_openai_model_provider(&server).name; let codex = test_codex() + .with_config(move |config| { + config.model_provider.name = non_openai_provider_name; + }) .build(&server) .await .expect("build codex") @@ -1050,10 +1053,7 @@ async fn auto_compact_runs_after_token_limit_hit() { }; mount_sse_once_match(&server, fourth_matcher, sse4).await; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); @@ -1299,10 +1299,7 @@ async fn auto_compact_persists_rollout_entries() { }; mount_sse_once_match(&server, third_matcher, sse3).await; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); @@ -1403,10 +1400,7 @@ async fn manual_compact_retries_after_context_window_error() { ) .await; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); @@ -1539,10 +1533,7 @@ async fn manual_compact_twice_preserves_latest_user_messages() { ) .await; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); @@ -1743,10 +1734,7 @@ async fn auto_compact_allows_multiple_attempts_when_interleaved_with_other_turn_ mount_sse_sequence(&server, vec![sse1, sse2, sse3, sse4, sse5, sse6]).await; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); @@ -1856,10 +1844,7 @@ async fn auto_compact_triggers_after_function_call_over_95_percent_usage() { // We don't assert on the post-compact request, so no need to keep its mock. mount_sse_once(&server, post_auto_compact_turn).await; - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; + let model_provider = non_openai_model_provider(&server); let home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&home); @@ -1961,13 +1946,18 @@ async fn auto_compact_counts_encrypted_reasoning_before_last_user() { ) .await; - let compacted_history = vec![codex_protocol::models::ResponseItem::Message { - id: None, - role: "assistant".to_string(), - content: vec![codex_protocol::models::ContentItem::OutputText { - text: "REMOTE_COMPACT_SUMMARY".to_string(), - }], - }]; + let compacted_history = vec![ + codex_protocol::models::ResponseItem::Message { + id: None, + role: "assistant".to_string(), + content: vec![codex_protocol::models::ContentItem::OutputText { + text: "REMOTE_COMPACT_SUMMARY".to_string(), + }], + }, + codex_protocol::models::ResponseItem::Compaction { + encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(), + }, + ]; let compact_mock = mount_compact_json_once(&server, serde_json::json!({ "output": compacted_history })).await; @@ -2028,4 +2018,8 @@ async fn auto_compact_counts_encrypted_reasoning_before_last_user() { resume_body.contains("REMOTE_COMPACT_SUMMARY") || resume_body.contains(FINAL_REPLY), "resume request should follow remote compact and use compacted history" ); + assert!( + resume_body.contains("ENCRYPTED_COMPACTION_SUMMARY"), + "resume request should include compaction summary item" + ); } diff --git a/codex-rs/core/tests/suite/compact_remote.rs b/codex-rs/core/tests/suite/compact_remote.rs index 49fd5791c8..34e44419b4 100644 --- a/codex-rs/core/tests/suite/compact_remote.rs +++ b/codex-rs/core/tests/suite/compact_remote.rs @@ -51,13 +51,18 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> { ) .await; - let compacted_history = vec![ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "REMOTE_COMPACTED_SUMMARY".to_string(), - }], - }]; + let compacted_history = vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "REMOTE_COMPACTED_SUMMARY".to_string(), + }], + }, + 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() }), @@ -120,6 +125,10 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> { follow_up_body.contains("REMOTE_COMPACTED_SUMMARY"), "expected follow-up request to use compacted history" ); + assert!( + follow_up_body.contains("ENCRYPTED_COMPACTION_SUMMARY"), + "expected follow-up request to include compaction summary item" + ); assert!( !follow_up_body.contains("FIRST_REMOTE_REPLY"), "expected follow-up request to drop pre-compaction assistant messages" @@ -159,13 +168,18 @@ async fn remote_compact_runs_automatically() -> Result<()> { ) .await; - let compacted_history = vec![ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "REMOTE_COMPACTED_SUMMARY".to_string(), - }], - }]; + let compacted_history = vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "REMOTE_COMPACTED_SUMMARY".to_string(), + }], + }, + 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() }), @@ -190,6 +204,7 @@ async fn remote_compact_runs_automatically() -> Result<()> { assert_eq!(compact_mock.requests().len(), 1); let follow_up_body = responses_mock.single_request().body_json().to_string(); assert!(follow_up_body.contains("REMOTE_COMPACTED_SUMMARY")); + assert!(follow_up_body.contains("ENCRYPTED_COMPACTION_SUMMARY")); Ok(()) } @@ -226,6 +241,9 @@ async fn remote_compact_persists_replacement_history_in_rollout() -> Result<()> text: "COMPACTED_USER_SUMMARY".to_string(), }], }, + ResponseItem::Compaction { + encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(), + }, ResponseItem::Message { id: None, role: "assistant".to_string(), diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index 5d3d9e4b8a..188e38da18 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -857,6 +857,7 @@ async fn start_test_conversation( model: Option<&str>, ) -> (TempDir, Config, ConversationManager, Arc) { let model_provider = ModelProviderInfo { + name: "Non-OpenAI Model provider".into(), base_url: Some(format!("{}/v1", server.uri())), ..built_in_model_providers()["openai"].clone() }; diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 5c609c3c46..722e915615 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -150,8 +150,8 @@ pub enum ResponseItem { GhostSnapshot { ghost_commit: GhostCommit, }, - #[serde(alias = "compaction")] - CompactionSummary { + #[serde(alias = "compaction_summary")] + Compaction { encrypted_content: String, }, #[serde(other)] @@ -671,13 +671,13 @@ mod tests { #[test] fn deserializes_compaction_alias() -> Result<()> { - let json = r#"{"type":"compaction","encrypted_content":"abc"}"#; + let json = r#"{"type":"compaction_summary","encrypted_content":"abc"}"#; let item: ResponseItem = serde_json::from_str(json)?; assert_eq!( item, - ResponseItem::CompactionSummary { + ResponseItem::Compaction { encrypted_content: "abc".into(), } ); From 149696d9595fafad912ae0b3abd42688b7453750 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 12 Dec 2025 10:59:39 -0800 Subject: [PATCH 27/77] chores: models manager (#7937) --- codex-rs/app-server/tests/common/Cargo.toml | 2 +- codex-rs/core/src/error.rs | 1 - codex-rs/core/src/openai_models/model_family.rs | 6 +++--- codex-rs/core/src/openai_models/model_presets.rs | 4 ++-- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/codex-rs/app-server/tests/common/Cargo.toml b/codex-rs/app-server/tests/common/Cargo.toml index 380f70d9b1..67ceeae4f4 100644 --- a/codex-rs/app-server/tests/common/Cargo.toml +++ b/codex-rs/app-server/tests/common/Cargo.toml @@ -13,7 +13,7 @@ assert_cmd = { workspace = true } base64 = { workspace = true } chrono = { workspace = true } codex-app-server-protocol = { workspace = true } -codex-core = { workspace = true } +codex-core = { workspace = true, features = ["test-support"] } codex-protocol = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index c7e0c2bde2..e8fa91d26e 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -58,7 +58,6 @@ pub enum SandboxErr { #[derive(Error, Debug)] pub enum CodexErr { - // todo(aibrahim): git rid of this error carrying the dangling artifacts #[error("turn aborted. Something went wrong? Hit `/feedback` to report the issue.")] TurnAborted, diff --git a/codex-rs/core/src/openai_models/model_family.rs b/codex-rs/core/src/openai_models/model_family.rs index 4e3375c580..e486c7d911 100644 --- a/codex-rs/core/src/openai_models/model_family.rs +++ b/codex-rs/core/src/openai_models/model_family.rs @@ -83,7 +83,7 @@ pub struct ModelFamily { } impl ModelFamily { - pub fn with_config_overrides(mut self, config: &Config) -> Self { + pub(super) fn with_config_overrides(mut self, config: &Config) -> Self { if let Some(supports_reasoning_summaries) = config.model_supports_reasoning_summaries { self.supports_reasoning_summaries = supports_reasoning_summaries; } @@ -98,7 +98,7 @@ impl ModelFamily { } self } - pub fn with_remote_overrides(mut self, remote_models: Vec) -> Self { + pub(super) fn with_remote_overrides(mut self, remote_models: Vec) -> Self { for model in remote_models { if model.slug == self.slug { self.apply_remote_overrides(model); @@ -198,7 +198,7 @@ macro_rules! model_family { /// Internal offline helper for `ModelsManager` that returns a `ModelFamily` for the given /// model slug. -pub(in crate::openai_models) fn find_family_for_model(slug: &str) -> ModelFamily { +pub(super) fn find_family_for_model(slug: &str) -> ModelFamily { if slug.starts_with("o3") { model_family!( slug, "o3", diff --git a/codex-rs/core/src/openai_models/model_presets.rs b/codex-rs/core/src/openai_models/model_presets.rs index cf635e8dac..d11e5af309 100644 --- a/codex-rs/core/src/openai_models/model_presets.rs +++ b/codex-rs/core/src/openai_models/model_presets.rs @@ -237,7 +237,7 @@ static PRESETS: Lazy> = Lazy::new(|| { ] }); -pub(crate) fn builtin_model_presets(_auth_mode: Option) -> Vec { +pub(super) fn builtin_model_presets(_auth_mode: Option) -> Vec { PRESETS .iter() .filter(|preset| preset.show_in_picker) @@ -245,7 +245,7 @@ pub(crate) fn builtin_model_presets(_auth_mode: Option) -> Vec &'static Vec { &PRESETS } From 92098d36e8490cad66eade1ce56d10917f7eb7a3 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 12 Dec 2025 20:01:24 +0000 Subject: [PATCH 28/77] feat: clean config loading and config api (#7924) Check the README of the `config_loader` for details --- codex-rs/Cargo.lock | 2 - codex-rs/app-server/Cargo.toml | 2 - .../app-server/src/codex_message_processor.rs | 25 +- codex-rs/app-server/src/config_api.rs | 1096 +---------------- codex-rs/core/src/config/mod.rs | 84 +- codex-rs/core/src/config/service.rs | 935 ++++++++++++++ codex-rs/core/src/config_loader/README.md | 64 + .../core/src/config_loader/fingerprint.rs | 67 + codex-rs/core/src/config_loader/layer_io.rs | 100 ++ codex-rs/core/src/config_loader/merge.rs | 18 + codex-rs/core/src/config_loader/mod.rs | 361 +----- codex-rs/core/src/config_loader/overrides.rs | 55 + codex-rs/core/src/config_loader/state.rs | 128 ++ codex-rs/core/src/config_loader/tests.rs | 138 +++ 14 files changed, 1592 insertions(+), 1483 deletions(-) create mode 100644 codex-rs/core/src/config/service.rs create mode 100644 codex-rs/core/src/config_loader/README.md create mode 100644 codex-rs/core/src/config_loader/fingerprint.rs create mode 100644 codex-rs/core/src/config_loader/layer_io.rs create mode 100644 codex-rs/core/src/config_loader/merge.rs create mode 100644 codex-rs/core/src/config_loader/overrides.rs create mode 100644 codex-rs/core/src/config_loader/state.rs create mode 100644 codex-rs/core/src/config_loader/tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 24eb0e4bab..ec5911a4bd 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -846,12 +846,10 @@ dependencies = [ "serde", "serde_json", "serial_test", - "sha2", "shlex", "tempfile", "tokio", "toml 0.9.5", - "toml_edit", "tracing", "tracing-subscriber", "uuid", diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 948facdea6..cb3f51bb82 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -31,11 +31,9 @@ codex-utils-json-to-toml = { workspace = true } chrono = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } -sha2 = { workspace = true } mcp-types = { workspace = true } tempfile = { workspace = true } toml = { workspace = true } -toml_edit = { workspace = true } tokio = { workspace = true, features = [ "io-std", "macros", diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 9f4227b2df..53fabd22e4 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -117,10 +117,9 @@ use codex_core::auth::CLIENT_ID; use codex_core::auth::login_with_api_key; use codex_core::config::Config; use codex_core::config::ConfigOverrides; -use codex_core::config::ConfigToml; +use codex_core::config::ConfigService; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::types::McpServerTransportConfig; -use codex_core::config_loader::load_config_as_toml; use codex_core::default_client::get_codex_user_agent; use codex_core::exec::ExecParams; use codex_core::exec_env::create_env; @@ -1108,12 +1107,13 @@ impl CodexMessageProcessor { } async fn get_user_saved_config(&self, request_id: RequestId) { - let toml_value = match load_config_as_toml(&self.config.codex_home).await { - Ok(val) => val, + let service = ConfigService::new(self.config.codex_home.clone(), Vec::new()); + let user_saved_config: UserSavedConfig = match service.load_user_saved_config().await { + Ok(config) => config, Err(err) => { let error = JSONRPCErrorError { code: INTERNAL_ERROR_CODE, - message: format!("failed to load config.toml: {err}"), + message: err.to_string(), data: None, }; self.outgoing.send_error(request_id, error).await; @@ -1121,21 +1121,6 @@ impl CodexMessageProcessor { } }; - let cfg: ConfigToml = match toml_value.try_into() { - Ok(cfg) => cfg, - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to parse config.toml: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let user_saved_config: UserSavedConfig = cfg.into(); - let response = GetUserSavedConfigResponse { config: user_saved_config, }; diff --git a/codex-rs/app-server/src/config_api.rs b/codex-rs/app-server/src/config_api.rs index c1eaf62d26..98e0f108e9 100644 --- a/codex-rs/app-server/src/config_api.rs +++ b/codex-rs/app-server/src/config_api.rs @@ -1,66 +1,27 @@ use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; -use codex_app_server_protocol::Config; use codex_app_server_protocol::ConfigBatchWriteParams; -use codex_app_server_protocol::ConfigLayer; -use codex_app_server_protocol::ConfigLayerMetadata; -use codex_app_server_protocol::ConfigLayerName; use codex_app_server_protocol::ConfigReadParams; use codex_app_server_protocol::ConfigReadResponse; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::ConfigWriteErrorCode; use codex_app_server_protocol::ConfigWriteResponse; use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::MergeStrategy; -use codex_app_server_protocol::OverriddenMetadata; -use codex_app_server_protocol::WriteStatus; -use codex_core::config::ConfigToml; -use codex_core::config::edit::ConfigEdit; -use codex_core::config::edit::ConfigEditsBuilder; -use codex_core::config_loader::LoadedConfigLayers; -use codex_core::config_loader::LoaderOverrides; -use codex_core::config_loader::load_config_layers_with_overrides; -use codex_core::config_loader::merge_toml_values; -use serde_json::Value as JsonValue; +use codex_core::config::ConfigService; +use codex_core::config::ConfigServiceError; use serde_json::json; -use sha2::Digest; -use sha2::Sha256; -use std::collections::HashMap; -use std::path::Path; use std::path::PathBuf; use toml::Value as TomlValue; -use toml_edit::Item as TomlItem; - -const SESSION_FLAGS_SOURCE: &str = "--config"; -const MDM_SOURCE: &str = "com.openai.codex/config_toml_base64"; -const CONFIG_FILE_NAME: &str = "config.toml"; #[derive(Clone)] pub(crate) struct ConfigApi { - codex_home: PathBuf, - cli_overrides: Vec<(String, TomlValue)>, - loader_overrides: LoaderOverrides, + service: ConfigService, } impl ConfigApi { pub(crate) fn new(codex_home: PathBuf, cli_overrides: Vec<(String, TomlValue)>) -> Self { Self { - codex_home, - cli_overrides, - loader_overrides: LoaderOverrides::default(), - } - } - - #[cfg(test)] - fn with_overrides( - codex_home: PathBuf, - cli_overrides: Vec<(String, TomlValue)>, - loader_overrides: LoaderOverrides, - ) -> Self { - Self { - codex_home, - cli_overrides, - loader_overrides, + service: ConfigService::new(codex_home, cli_overrides), } } @@ -68,696 +29,32 @@ impl ConfigApi { &self, params: ConfigReadParams, ) -> Result { - let layers = self - .load_layers_state() - .await - .map_err(|err| internal_error("failed to read configuration layers", err))?; - - let effective = layers.effective_config(); - validate_config(&effective).map_err(|err| internal_error("invalid configuration", err))?; - - let config: Config = serde_json::from_value(to_json_value(&effective)) - .map_err(|err| internal_error("failed to deserialize configuration", err))?; - let response = ConfigReadResponse { - config, - origins: layers.origins(), - layers: params.include_layers.then(|| layers.layers_high_to_low()), - }; - - Ok(response) + self.service.read(params).await.map_err(map_error) } pub(crate) async fn write_value( &self, params: ConfigValueWriteParams, ) -> Result { - let edits = vec![(params.key_path, params.value, params.merge_strategy)]; - self.apply_edits(params.file_path, params.expected_version, edits) - .await + self.service.write_value(params).await.map_err(map_error) } pub(crate) async fn batch_write( &self, params: ConfigBatchWriteParams, ) -> Result { - let edits = params - .edits - .into_iter() - .map(|edit| (edit.key_path, edit.value, edit.merge_strategy)) - .collect(); - - self.apply_edits(params.file_path, params.expected_version, edits) - .await - } - - async fn apply_edits( - &self, - file_path: Option, - expected_version: Option, - edits: Vec<(String, JsonValue, MergeStrategy)>, - ) -> Result { - let allowed_path = self.codex_home.join(CONFIG_FILE_NAME); - let provided_path = file_path - .as_ref() - .map(PathBuf::from) - .unwrap_or_else(|| allowed_path.clone()); - - if !paths_match(&allowed_path, &provided_path) { - return Err(config_write_error( - ConfigWriteErrorCode::ConfigLayerReadonly, - "Only writes to the user config are allowed", - )); - } - - let layers = self - .load_layers_state() - .await - .map_err(|err| internal_error("failed to load configuration", err))?; - - if let Some(expected) = expected_version.as_deref() - && expected != layers.user.version - { - return Err(config_write_error( - ConfigWriteErrorCode::ConfigVersionConflict, - "Configuration was modified since last read. Fetch latest version and retry.", - )); - } - - let mut user_config = layers.user.config.clone(); - let mut parsed_segments = Vec::new(); - let mut config_edits = Vec::new(); - - for (key_path, value, strategy) in edits.into_iter() { - let segments = parse_key_path(&key_path).map_err(|message| { - config_write_error(ConfigWriteErrorCode::ConfigValidationError, message) - })?; - let original_value = value_at_path(&user_config, &segments).cloned(); - let parsed_value = parse_value(value).map_err(|message| { - config_write_error(ConfigWriteErrorCode::ConfigValidationError, message) - })?; - - apply_merge(&mut user_config, &segments, parsed_value.as_ref(), strategy).map_err( - |err| match err { - MergeError::PathNotFound => config_write_error( - ConfigWriteErrorCode::ConfigPathNotFound, - "Path not found", - ), - MergeError::Validation(message) => { - config_write_error(ConfigWriteErrorCode::ConfigValidationError, message) - } - }, - )?; - - let updated_value = value_at_path(&user_config, &segments).cloned(); - if original_value != updated_value { - let edit = match updated_value { - Some(value) => ConfigEdit::SetPath { - segments: segments.clone(), - value: toml_value_to_item(&value) - .map_err(|err| internal_error("failed to build config edits", err))?, - }, - None => ConfigEdit::ClearPath { - segments: segments.clone(), - }, - }; - config_edits.push(edit); - } - - parsed_segments.push(segments); - } - - validate_config(&user_config).map_err(|err| { - config_write_error( - ConfigWriteErrorCode::ConfigValidationError, - format!("Invalid configuration: {err}"), - ) - })?; - - let updated_layers = layers.with_user_config(user_config.clone()); - let effective = updated_layers.effective_config(); - validate_config(&effective).map_err(|err| { - config_write_error( - ConfigWriteErrorCode::ConfigValidationError, - format!("Invalid configuration: {err}"), - ) - })?; - - if !config_edits.is_empty() { - ConfigEditsBuilder::new(&self.codex_home) - .with_edits(config_edits) - .apply() - .await - .map_err(|err| internal_error("failed to persist config.toml", err))?; - } - - let overridden = first_overridden_edit(&updated_layers, &effective, &parsed_segments); - let status = overridden - .as_ref() - .map(|_| WriteStatus::OkOverridden) - .unwrap_or(WriteStatus::Ok); - - let file_path = provided_path - .canonicalize() - .unwrap_or(provided_path.clone()) - .display() - .to_string(); - - Ok(ConfigWriteResponse { - status, - version: updated_layers.user.version.clone(), - file_path, - overridden_metadata: overridden, - }) - } - - async fn load_layers_state(&self) -> std::io::Result { - let LoadedConfigLayers { - base, - managed_config, - managed_preferences, - } = load_config_layers_with_overrides(&self.codex_home, self.loader_overrides.clone()) - .await?; - - let user = LayerState::new( - ConfigLayerName::User, - self.codex_home.join(CONFIG_FILE_NAME), - base, - ); - - let session_flags = LayerState::new( - ConfigLayerName::SessionFlags, - PathBuf::from(SESSION_FLAGS_SOURCE), - { - let mut root = TomlValue::Table(toml::map::Map::new()); - for (path, value) in self.cli_overrides.iter() { - apply_override(&mut root, path, value.clone()); - } - root - }, - ); - - let system = managed_config.map(|cfg| { - LayerState::new( - ConfigLayerName::System, - system_config_path(&self.codex_home), - cfg, - ) - }); - - let mdm = managed_preferences - .map(|cfg| LayerState::new(ConfigLayerName::Mdm, PathBuf::from(MDM_SOURCE), cfg)); - - Ok(LayersState { - user, - session_flags, - system, - mdm, - }) + self.service.batch_write(params).await.map_err(map_error) } } -fn parse_value(value: JsonValue) -> Result, String> { - if value.is_null() { - return Ok(None); +fn map_error(err: ConfigServiceError) -> JSONRPCErrorError { + if let Some(code) = err.write_error_code() { + return config_write_error(code, err.to_string()); } - serde_json::from_value::(value) - .map(Some) - .map_err(|err| format!("invalid value: {err}")) -} - -fn parse_key_path(path: &str) -> Result, String> { - if path.trim().is_empty() { - return Err("keyPath must not be empty".to_string()); - } - Ok(path - .split('.') - .map(std::string::ToString::to_string) - .collect()) -} - -fn apply_override(target: &mut TomlValue, path: &str, value: TomlValue) { - use toml::value::Table; - - let segments: Vec<&str> = path.split('.').collect(); - let mut current = target; - - for (idx, segment) in segments.iter().enumerate() { - let is_last = idx == segments.len() - 1; - - if is_last { - match current { - TomlValue::Table(table) => { - table.insert(segment.to_string(), value); - } - _ => { - let mut table = Table::new(); - table.insert(segment.to_string(), value); - *current = TomlValue::Table(table); - } - } - return; - } - - match current { - TomlValue::Table(table) => { - current = table - .entry((*segment).to_string()) - .or_insert_with(|| TomlValue::Table(Table::new())); - } - _ => { - *current = TomlValue::Table(Table::new()); - if let TomlValue::Table(tbl) = current { - current = tbl - .entry((*segment).to_string()) - .or_insert_with(|| TomlValue::Table(Table::new())); - } - } - } - } -} - -#[derive(Debug)] -enum MergeError { - PathNotFound, - Validation(String), -} - -fn apply_merge( - root: &mut TomlValue, - segments: &[String], - value: Option<&TomlValue>, - strategy: MergeStrategy, -) -> Result { - let Some(value) = value else { - return clear_path(root, segments); - }; - - let Some((last, parents)) = segments.split_last() else { - return Err(MergeError::Validation( - "keyPath must not be empty".to_string(), - )); - }; - - let mut current = root; - - for segment in parents { - match current { - TomlValue::Table(table) => { - current = table - .entry(segment.clone()) - .or_insert_with(|| TomlValue::Table(toml::map::Map::new())); - } - _ => { - *current = TomlValue::Table(toml::map::Map::new()); - if let TomlValue::Table(table) = current { - current = table - .entry(segment.clone()) - .or_insert_with(|| TomlValue::Table(toml::map::Map::new())); - } - } - } - } - - let table = current.as_table_mut().ok_or_else(|| { - MergeError::Validation("cannot set value on non-table parent".to_string()) - })?; - - if matches!(strategy, MergeStrategy::Upsert) - && let Some(existing) = table.get_mut(last) - && matches!(existing, TomlValue::Table(_)) - && matches!(value, TomlValue::Table(_)) - { - merge_toml_values(existing, value); - return Ok(true); - } - - let changed = table - .get(last) - .map(|existing| Some(existing) != Some(value)) - .unwrap_or(true); - table.insert(last.clone(), value.clone()); - Ok(changed) -} - -fn clear_path(root: &mut TomlValue, segments: &[String]) -> Result { - let Some((last, parents)) = segments.split_last() else { - return Err(MergeError::Validation( - "keyPath must not be empty".to_string(), - )); - }; - - let mut current = root; - for segment in parents { - match current { - TomlValue::Table(table) => { - current = table.get_mut(segment).ok_or(MergeError::PathNotFound)?; - } - _ => return Err(MergeError::PathNotFound), - } - } - - let Some(parent) = current.as_table_mut() else { - return Err(MergeError::PathNotFound); - }; - - Ok(parent.remove(last).is_some()) -} - -fn toml_value_to_item(value: &TomlValue) -> anyhow::Result { - match value { - TomlValue::Table(table) => { - let mut table_item = toml_edit::Table::new(); - table_item.set_implicit(false); - for (key, val) in table { - table_item.insert(key, toml_value_to_item(val)?); - } - Ok(TomlItem::Table(table_item)) - } - other => Ok(TomlItem::Value(toml_value_to_value(other)?)), - } -} - -fn toml_value_to_value(value: &TomlValue) -> anyhow::Result { - match value { - TomlValue::String(val) => Ok(toml_edit::Value::from(val.clone())), - TomlValue::Integer(val) => Ok(toml_edit::Value::from(*val)), - TomlValue::Float(val) => Ok(toml_edit::Value::from(*val)), - TomlValue::Boolean(val) => Ok(toml_edit::Value::from(*val)), - TomlValue::Datetime(val) => Ok(toml_edit::Value::from(*val)), - TomlValue::Array(items) => { - let mut array = toml_edit::Array::new(); - for item in items { - array.push(toml_value_to_value(item)?); - } - Ok(toml_edit::Value::Array(array)) - } - TomlValue::Table(table) => { - let mut inline = toml_edit::InlineTable::new(); - for (key, val) in table { - inline.insert(key, toml_value_to_value(val)?); - } - Ok(toml_edit::Value::InlineTable(inline)) - } - } -} - -#[derive(Clone)] -struct LayerState { - name: ConfigLayerName, - source: PathBuf, - config: TomlValue, - version: String, -} - -impl LayerState { - fn new(name: ConfigLayerName, source: PathBuf, config: TomlValue) -> Self { - let version = version_for_toml(&config); - Self { - name, - source, - config, - version, - } - } - - fn metadata(&self) -> ConfigLayerMetadata { - ConfigLayerMetadata { - name: self.name.clone(), - source: self.source.display().to_string(), - version: self.version.clone(), - } - } - - fn as_layer(&self) -> ConfigLayer { - ConfigLayer { - name: self.name.clone(), - source: self.source.display().to_string(), - version: self.version.clone(), - config: to_json_value(&self.config), - } - } -} - -#[derive(Clone)] -struct LayersState { - user: LayerState, - session_flags: LayerState, - system: Option, - mdm: Option, -} - -impl LayersState { - fn with_user_config(self, user_config: TomlValue) -> Self { - Self { - user: LayerState::new(self.user.name, self.user.source, user_config), - session_flags: self.session_flags, - system: self.system, - mdm: self.mdm, - } - } - - fn effective_config(&self) -> TomlValue { - let mut merged = self.user.config.clone(); - merge_toml_values(&mut merged, &self.session_flags.config); - if let Some(system) = &self.system { - merge_toml_values(&mut merged, &system.config); - } - if let Some(mdm) = &self.mdm { - merge_toml_values(&mut merged, &mdm.config); - } - merged - } - - fn origins(&self) -> HashMap { - let mut origins = HashMap::new(); - let mut path = Vec::new(); - - record_origins( - &self.user.config, - &self.user.metadata(), - &mut path, - &mut origins, - ); - record_origins( - &self.session_flags.config, - &self.session_flags.metadata(), - &mut path, - &mut origins, - ); - if let Some(system) = &self.system { - record_origins(&system.config, &system.metadata(), &mut path, &mut origins); - } - if let Some(mdm) = &self.mdm { - record_origins(&mdm.config, &mdm.metadata(), &mut path, &mut origins); - } - - origins - } - - fn layers_high_to_low(&self) -> Vec { - let mut layers = Vec::new(); - if let Some(mdm) = &self.mdm { - layers.push(mdm.as_layer()); - } - if let Some(system) = &self.system { - layers.push(system.as_layer()); - } - layers.push(self.session_flags.as_layer()); - layers.push(self.user.as_layer()); - layers - } -} - -fn record_origins( - value: &TomlValue, - meta: &ConfigLayerMetadata, - path: &mut Vec, - origins: &mut HashMap, -) { - match value { - TomlValue::Table(table) => { - for (key, val) in table { - path.push(key.clone()); - record_origins(val, meta, path, origins); - path.pop(); - } - } - TomlValue::Array(items) => { - for (idx, item) in items.iter().enumerate() { - path.push(idx.to_string()); - record_origins(item, meta, path, origins); - path.pop(); - } - } - _ => { - if !path.is_empty() { - origins.insert(path.join("."), meta.clone()); - } - } - } -} - -fn to_json_value(value: &TomlValue) -> JsonValue { - serde_json::to_value(value).unwrap_or(JsonValue::Null) -} - -fn validate_config(value: &TomlValue) -> Result<(), toml::de::Error> { - let _: ConfigToml = value.clone().try_into()?; - Ok(()) -} - -fn version_for_toml(value: &TomlValue) -> String { - let json = to_json_value(value); - let canonical = canonical_json(&json); - let serialized = serde_json::to_vec(&canonical).unwrap_or_default(); - let mut hasher = Sha256::new(); - hasher.update(serialized); - let hash = hasher.finalize(); - let hex = hash - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); - format!("sha256:{hex}") -} - -fn canonical_json(value: &JsonValue) -> JsonValue { - match value { - JsonValue::Object(map) => { - let mut sorted = serde_json::Map::new(); - let mut keys = map.keys().cloned().collect::>(); - keys.sort(); - for key in keys { - if let Some(val) = map.get(&key) { - sorted.insert(key, canonical_json(val)); - } - } - JsonValue::Object(sorted) - } - JsonValue::Array(items) => JsonValue::Array(items.iter().map(canonical_json).collect()), - other => other.clone(), - } -} - -fn paths_match(expected: &Path, provided: &Path) -> bool { - if let (Ok(expanded_expected), Ok(expanded_provided)) = - (expected.canonicalize(), provided.canonicalize()) - { - return expanded_expected == expanded_provided; - } - - expected == provided -} - -fn value_at_path<'a>(root: &'a TomlValue, segments: &[String]) -> Option<&'a TomlValue> { - let mut current = root; - for segment in segments { - match current { - TomlValue::Table(table) => { - current = table.get(segment)?; - } - TomlValue::Array(items) => { - let idx: usize = segment.parse().ok()?; - current = items.get(idx)?; - } - _ => return None, - } - } - Some(current) -} - -fn override_message(layer: &ConfigLayerName) -> String { - match layer { - ConfigLayerName::Mdm => "Overridden by managed policy (mdm)".to_string(), - ConfigLayerName::System => "Overridden by managed config (system)".to_string(), - ConfigLayerName::SessionFlags => "Overridden by session flags".to_string(), - ConfigLayerName::User => "Overridden by user config".to_string(), - } -} - -fn compute_override_metadata( - layers: &LayersState, - effective: &TomlValue, - segments: &[String], -) -> Option { - let user_value = value_at_path(&layers.user.config, segments); - let effective_value = value_at_path(effective, segments); - - if user_value.is_some() && user_value == effective_value { - return None; - } - - if user_value.is_none() && effective_value.is_none() { - return None; - } - - let effective_layer = find_effective_layer(layers, segments); - let overriding_layer = effective_layer.unwrap_or_else(|| layers.user.metadata()); - let message = override_message(&overriding_layer.name); - - Some(OverriddenMetadata { - message, - overriding_layer, - effective_value: effective_value - .map(to_json_value) - .unwrap_or(JsonValue::Null), - }) -} - -fn first_overridden_edit( - layers: &LayersState, - effective: &TomlValue, - edits: &[Vec], -) -> Option { - for segments in edits { - if let Some(meta) = compute_override_metadata(layers, effective, segments) { - return Some(meta); - } - } - None -} - -fn find_effective_layer(layers: &LayersState, segments: &[String]) -> Option { - let check = - |state: &LayerState| value_at_path(&state.config, segments).map(|_| state.metadata()); - - if let Some(mdm) = &layers.mdm - && let Some(meta) = check(mdm) - { - return Some(meta); - } - if let Some(system) = &layers.system - && let Some(meta) = check(system) - { - return Some(meta); - } - if let Some(meta) = check(&layers.session_flags) { - return Some(meta); - } - check(&layers.user) -} - -fn system_config_path(codex_home: &Path) -> PathBuf { - if let Ok(path) = std::env::var("CODEX_MANAGED_CONFIG_PATH") { - return PathBuf::from(path); - } - - #[cfg(unix)] - { - let _ = codex_home; - PathBuf::from("/etc/codex/managed_config.toml") - } - - #[cfg(not(unix))] - { - codex_home.join("managed_config.toml") - } -} - -fn internal_error(context: &str, err: E) -> JSONRPCErrorError { JSONRPCErrorError { code: INTERNAL_ERROR_CODE, - message: format!("{context}: {err}"), + message: err.to_string(), data: None, } } @@ -771,374 +68,3 @@ fn config_write_error(code: ConfigWriteErrorCode, message: impl Into) -> })), } } - -#[cfg(test)] -mod tests { - use super::*; - use anyhow::Result; - use codex_app_server_protocol::AskForApproval; - use pretty_assertions::assert_eq; - use tempfile::tempdir; - - #[test] - fn toml_value_to_item_handles_nested_config_tables() { - let config = r#" -[mcp_servers.docs] -command = "docs-server" - -[mcp_servers.docs.http_headers] -X-Doc = "42" -"#; - - let value: TomlValue = toml::from_str(config).expect("parse config example"); - let item = toml_value_to_item(&value).expect("convert to toml_edit item"); - - let root = item.as_table().expect("root table"); - assert!(!root.is_implicit(), "root table should be explicit"); - - let mcp_servers = root - .get("mcp_servers") - .and_then(TomlItem::as_table) - .expect("mcp_servers table"); - assert!( - !mcp_servers.is_implicit(), - "mcp_servers table should be explicit" - ); - - let docs = mcp_servers - .get("docs") - .and_then(TomlItem::as_table) - .expect("docs table"); - assert_eq!( - docs.get("command") - .and_then(TomlItem::as_value) - .and_then(toml_edit::Value::as_str), - Some("docs-server") - ); - - let http_headers = docs - .get("http_headers") - .and_then(TomlItem::as_table) - .expect("http_headers table"); - assert_eq!( - http_headers - .get("X-Doc") - .and_then(TomlItem::as_value) - .and_then(toml_edit::Value::as_str), - Some("42") - ); - } - - #[tokio::test] - async fn write_value_preserves_comments_and_order() -> Result<()> { - let tmp = tempdir().expect("tempdir"); - let original = r#"# Codex user configuration -model = "gpt-5" -approval_policy = "on-request" - -[notice] -# Preserve this comment -hide_full_access_warning = true - -[features] -unified_exec = true -"#; - std::fs::write(tmp.path().join(CONFIG_FILE_NAME), original)?; - - let api = ConfigApi::new(tmp.path().to_path_buf(), vec![]); - api.write_value(ConfigValueWriteParams { - file_path: Some(tmp.path().join(CONFIG_FILE_NAME).display().to_string()), - key_path: "features.remote_compaction".to_string(), - value: json!(true), - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await - .expect("write succeeds"); - - let updated = - std::fs::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).expect("read config"); - let expected = r#"# Codex user configuration -model = "gpt-5" -approval_policy = "on-request" - -[notice] -# Preserve this comment -hide_full_access_warning = true - -[features] -unified_exec = true -remote_compaction = true -"#; - assert_eq!(updated, expected); - Ok(()) - } - - #[tokio::test] - async fn read_includes_origins_and_layers() { - let tmp = tempdir().expect("tempdir"); - std::fs::write(tmp.path().join(CONFIG_FILE_NAME), "model = \"user\"").unwrap(); - - let managed_path = tmp.path().join("managed_config.toml"); - std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); - - let api = ConfigApi::with_overrides( - tmp.path().to_path_buf(), - vec![], - LoaderOverrides { - managed_config_path: Some(managed_path), - #[cfg(target_os = "macos")] - managed_preferences_base64: None, - }, - ); - - let response = api - .read(ConfigReadParams { - include_layers: true, - }) - .await - .expect("response"); - - assert_eq!(response.config.approval_policy, Some(AskForApproval::Never)); - - assert_eq!( - response - .origins - .get("approval_policy") - .expect("origin") - .name, - ConfigLayerName::System - ); - let layers = response.layers.expect("layers present"); - assert_eq!(layers.first().unwrap().name, ConfigLayerName::System); - assert_eq!(layers.get(1).unwrap().name, ConfigLayerName::SessionFlags); - assert_eq!(layers.last().unwrap().name, ConfigLayerName::User); - } - - #[tokio::test] - async fn write_value_reports_override() { - let tmp = tempdir().expect("tempdir"); - std::fs::write( - tmp.path().join(CONFIG_FILE_NAME), - "approval_policy = \"on-request\"", - ) - .unwrap(); - - let managed_path = tmp.path().join("managed_config.toml"); - std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); - - let api = ConfigApi::with_overrides( - tmp.path().to_path_buf(), - vec![], - LoaderOverrides { - managed_config_path: Some(managed_path), - #[cfg(target_os = "macos")] - managed_preferences_base64: None, - }, - ); - - let result = api - .write_value(ConfigValueWriteParams { - file_path: Some(tmp.path().join(CONFIG_FILE_NAME).display().to_string()), - key_path: "approval_policy".to_string(), - value: json!("never"), - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await - .expect("result"); - - let read_after = api - .read(ConfigReadParams { - include_layers: true, - }) - .await - .expect("read"); - assert_eq!( - read_after.config.approval_policy, - Some(AskForApproval::Never) - ); - assert_eq!( - read_after - .origins - .get("approval_policy") - .expect("origin") - .name, - ConfigLayerName::System - ); - assert_eq!(result.status, WriteStatus::Ok); - assert!(result.overridden_metadata.is_none()); - } - - #[tokio::test] - async fn version_conflict_rejected() { - let tmp = tempdir().expect("tempdir"); - std::fs::write(tmp.path().join(CONFIG_FILE_NAME), "model = \"user\"").unwrap(); - - let api = ConfigApi::new(tmp.path().to_path_buf(), vec![]); - let error = api - .write_value(ConfigValueWriteParams { - file_path: Some(tmp.path().join(CONFIG_FILE_NAME).display().to_string()), - key_path: "model".to_string(), - value: json!("gpt-5"), - merge_strategy: MergeStrategy::Replace, - expected_version: Some("sha256:bogus".to_string()), - }) - .await - .expect_err("should fail"); - - assert_eq!(error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - error - .data - .as_ref() - .and_then(|d| d.get("config_write_error_code")) - .and_then(serde_json::Value::as_str), - Some("configVersionConflict") - ); - } - - #[tokio::test] - async fn write_value_defaults_to_user_config_path() { - let tmp = tempdir().expect("tempdir"); - std::fs::write(tmp.path().join(CONFIG_FILE_NAME), "").unwrap(); - - let api = ConfigApi::new(tmp.path().to_path_buf(), vec![]); - api.write_value(ConfigValueWriteParams { - file_path: None, - key_path: "model".to_string(), - value: json!("gpt-new"), - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await - .expect("write succeeds"); - - let contents = - std::fs::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).expect("read config"); - assert!( - contents.contains("model = \"gpt-new\""), - "config.toml should be updated even when file_path is omitted" - ); - } - - #[tokio::test] - async fn invalid_user_value_rejected_even_if_overridden_by_managed() { - let tmp = tempdir().expect("tempdir"); - std::fs::write(tmp.path().join(CONFIG_FILE_NAME), "model = \"user\"").unwrap(); - - let managed_path = tmp.path().join("managed_config.toml"); - std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); - - let api = ConfigApi::with_overrides( - tmp.path().to_path_buf(), - vec![], - LoaderOverrides { - managed_config_path: Some(managed_path), - #[cfg(target_os = "macos")] - managed_preferences_base64: None, - }, - ); - - let error = api - .write_value(ConfigValueWriteParams { - file_path: Some(tmp.path().join(CONFIG_FILE_NAME).display().to_string()), - key_path: "approval_policy".to_string(), - value: json!("bogus"), - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await - .expect_err("should fail validation"); - - assert_eq!(error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - error - .data - .as_ref() - .and_then(|d| d.get("config_write_error_code")) - .and_then(serde_json::Value::as_str), - Some("configValidationError") - ); - - let contents = - std::fs::read_to_string(tmp.path().join(CONFIG_FILE_NAME)).expect("read config"); - assert_eq!(contents.trim(), "model = \"user\""); - } - - #[tokio::test] - async fn read_reports_managed_overrides_user_and_session_flags() { - let tmp = tempdir().expect("tempdir"); - std::fs::write(tmp.path().join(CONFIG_FILE_NAME), "model = \"user\"").unwrap(); - - let managed_path = tmp.path().join("managed_config.toml"); - std::fs::write(&managed_path, "model = \"system\"").unwrap(); - - let cli_overrides = vec![( - "model".to_string(), - TomlValue::String("session".to_string()), - )]; - - let api = ConfigApi::with_overrides( - tmp.path().to_path_buf(), - cli_overrides, - LoaderOverrides { - managed_config_path: Some(managed_path), - #[cfg(target_os = "macos")] - managed_preferences_base64: None, - }, - ); - - let response = api - .read(ConfigReadParams { - include_layers: true, - }) - .await - .expect("response"); - - assert_eq!(response.config.model.as_deref(), Some("system")); - assert_eq!( - response.origins.get("model").expect("origin").name, - ConfigLayerName::System - ); - let layers = response.layers.expect("layers"); - assert_eq!(layers.first().unwrap().name, ConfigLayerName::System); - assert_eq!(layers.get(1).unwrap().name, ConfigLayerName::SessionFlags); - assert_eq!(layers.get(2).unwrap().name, ConfigLayerName::User); - } - - #[tokio::test] - async fn write_value_reports_managed_override() { - let tmp = tempdir().expect("tempdir"); - std::fs::write(tmp.path().join(CONFIG_FILE_NAME), "").unwrap(); - - let managed_path = tmp.path().join("managed_config.toml"); - std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); - - let api = ConfigApi::with_overrides( - tmp.path().to_path_buf(), - vec![], - LoaderOverrides { - managed_config_path: Some(managed_path), - #[cfg(target_os = "macos")] - managed_preferences_base64: None, - }, - ); - - let result = api - .write_value(ConfigValueWriteParams { - file_path: Some(tmp.path().join(CONFIG_FILE_NAME).display().to_string()), - key_path: "approval_policy".to_string(), - value: json!("on-request"), - merge_strategy: MergeStrategy::Replace, - expected_version: None, - }) - .await - .expect("result"); - - assert_eq!(result.status, WriteStatus::OkOverridden); - let overridden = result.overridden_metadata.expect("overridden metadata"); - assert_eq!(overridden.overriding_layer.name, ConfigLayerName::System); - assert_eq!(overridden.effective_value, json!("never")); - } -} diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 4c1a073c57..584708156b 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -12,10 +12,7 @@ use crate::config::types::ShellEnvironmentPolicy; use crate::config::types::ShellEnvironmentPolicyToml; use crate::config::types::Tui; use crate::config::types::UriBasedFileOpener; -use crate::config_loader::LoadedConfigLayers; -use crate::config_loader::load_config_as_toml; -use crate::config_loader::load_config_layers_with_overrides; -use crate::config_loader::merge_toml_values; +use crate::config_loader::load_config_layers_state; use crate::features::Feature; use crate::features::FeatureOverrides; use crate::features::Features; @@ -59,8 +56,12 @@ use toml_edit::DocumentMut; pub mod edit; pub mod profile; +pub mod service; pub mod types; +pub use service::ConfigService; +pub use service::ConfigServiceError; + const OPENAI_DEFAULT_REVIEW_MODEL: &str = "gpt-5.1-codex-max"; /// Maximum number of bytes of the documentation that will be embedded. Larger @@ -342,29 +343,8 @@ async fn load_resolved_config( cli_overrides: Vec<(String, TomlValue)>, overrides: crate::config_loader::LoaderOverrides, ) -> std::io::Result { - let layers = load_config_layers_with_overrides(codex_home, overrides).await?; - Ok(apply_overlays(layers, cli_overrides)) -} - -fn apply_overlays( - layers: LoadedConfigLayers, - cli_overrides: Vec<(String, TomlValue)>, -) -> TomlValue { - let LoadedConfigLayers { - mut base, - managed_config, - managed_preferences, - } = layers; - - for (path, value) in cli_overrides.into_iter() { - apply_toml_override(&mut base, &path, value); - } - - for overlay in [managed_config, managed_preferences].into_iter().flatten() { - merge_toml_values(&mut base, &overlay); - } - - base + let layers = load_config_layers_state(codex_home, &cli_overrides, overrides).await?; + Ok(layers.effective_config()) } fn deserialize_config_toml_with_base( @@ -382,7 +362,12 @@ fn deserialize_config_toml_with_base( pub async fn load_global_mcp_servers( codex_home: &Path, ) -> std::io::Result> { - let root_value = load_config_as_toml(codex_home).await?; + let root_value = load_resolved_config( + codex_home, + Vec::new(), + crate::config_loader::LoaderOverrides::default(), + ) + .await?; let Some(servers_value) = root_value.get("mcp_servers") else { return Ok(BTreeMap::new()); }; @@ -541,49 +526,6 @@ pub fn set_default_oss_provider(codex_home: &Path, provider: &str) -> std::io::R Ok(()) } -/// Apply a single dotted-path override onto a TOML value. -fn apply_toml_override(root: &mut TomlValue, path: &str, value: TomlValue) { - use toml::value::Table; - - let segments: Vec<&str> = path.split('.').collect(); - let mut current = root; - - for (idx, segment) in segments.iter().enumerate() { - let is_last = idx == segments.len() - 1; - - if is_last { - match current { - TomlValue::Table(table) => { - table.insert(segment.to_string(), value); - } - _ => { - let mut table = Table::new(); - table.insert(segment.to_string(), value); - *current = TomlValue::Table(table); - } - } - return; - } - - // Traverse or create intermediate object. - match current { - TomlValue::Table(table) => { - current = table - .entry(segment.to_string()) - .or_insert_with(|| TomlValue::Table(Table::new())); - } - _ => { - *current = TomlValue::Table(Table::new()); - if let TomlValue::Table(tbl) = current { - current = tbl - .entry(segment.to_string()) - .or_insert_with(|| TomlValue::Table(Table::new())); - } - } - } - } -} - /// Base config deserialized from ~/.codex/config.toml. #[derive(Deserialize, Debug, Clone, Default, PartialEq)] pub struct ConfigToml { diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/core/src/config/service.rs new file mode 100644 index 0000000000..6f9d0e4d60 --- /dev/null +++ b/codex-rs/core/src/config/service.rs @@ -0,0 +1,935 @@ +use super::CONFIG_TOML_FILE; +use super::ConfigToml; +use crate::config::edit::ConfigEdit; +use crate::config::edit::ConfigEditsBuilder; +use crate::config_loader::ConfigLayerEntry; +use crate::config_loader::ConfigLayerStack; +use crate::config_loader::LoaderOverrides; +use crate::config_loader::load_config_layers_state; +use crate::config_loader::merge_toml_values; +use codex_app_server_protocol::Config as ApiConfig; +use codex_app_server_protocol::ConfigBatchWriteParams; +use codex_app_server_protocol::ConfigLayerMetadata; +use codex_app_server_protocol::ConfigLayerName; +use codex_app_server_protocol::ConfigReadParams; +use codex_app_server_protocol::ConfigReadResponse; +use codex_app_server_protocol::ConfigValueWriteParams; +use codex_app_server_protocol::ConfigWriteErrorCode; +use codex_app_server_protocol::ConfigWriteResponse; +use codex_app_server_protocol::MergeStrategy; +use codex_app_server_protocol::OverriddenMetadata; +use codex_app_server_protocol::WriteStatus; +use serde_json::Value as JsonValue; +use std::path::Path; +use std::path::PathBuf; +use thiserror::Error; +use toml::Value as TomlValue; +use toml_edit::Item as TomlItem; + +#[derive(Debug, Error)] +pub enum ConfigServiceError { + #[error("{message}")] + Write { + code: ConfigWriteErrorCode, + message: String, + }, + + #[error("{context}: {source}")] + Io { + context: &'static str, + #[source] + source: std::io::Error, + }, + + #[error("{context}: {source}")] + Json { + context: &'static str, + #[source] + source: serde_json::Error, + }, + + #[error("{context}: {source}")] + Toml { + context: &'static str, + #[source] + source: toml::de::Error, + }, + + #[error("{context}: {source}")] + Anyhow { + context: &'static str, + #[source] + source: anyhow::Error, + }, +} + +impl ConfigServiceError { + fn write(code: ConfigWriteErrorCode, message: impl Into) -> Self { + Self::Write { + code, + message: message.into(), + } + } + + fn io(context: &'static str, source: std::io::Error) -> Self { + Self::Io { context, source } + } + + fn json(context: &'static str, source: serde_json::Error) -> Self { + Self::Json { context, source } + } + + fn toml(context: &'static str, source: toml::de::Error) -> Self { + Self::Toml { context, source } + } + + fn anyhow(context: &'static str, source: anyhow::Error) -> Self { + Self::Anyhow { context, source } + } + + pub fn write_error_code(&self) -> Option { + match self { + Self::Write { code, .. } => Some(code.clone()), + _ => None, + } + } +} + +#[derive(Clone)] +pub struct ConfigService { + codex_home: PathBuf, + cli_overrides: Vec<(String, TomlValue)>, + loader_overrides: LoaderOverrides, +} + +impl ConfigService { + pub fn new(codex_home: PathBuf, cli_overrides: Vec<(String, TomlValue)>) -> Self { + Self { + codex_home, + cli_overrides, + loader_overrides: LoaderOverrides::default(), + } + } + + #[cfg(test)] + fn with_overrides( + codex_home: PathBuf, + cli_overrides: Vec<(String, TomlValue)>, + loader_overrides: LoaderOverrides, + ) -> Self { + Self { + codex_home, + cli_overrides, + loader_overrides, + } + } + + pub async fn read( + &self, + params: ConfigReadParams, + ) -> Result { + let layers = self + .load_layers_state() + .await + .map_err(|err| ConfigServiceError::io("failed to read configuration layers", err))?; + + let effective = layers.effective_config(); + validate_config(&effective) + .map_err(|err| ConfigServiceError::toml("invalid configuration", err))?; + + let json_value = serde_json::to_value(&effective) + .map_err(|err| ConfigServiceError::json("failed to serialize configuration", err))?; + let config: ApiConfig = serde_json::from_value(json_value) + .map_err(|err| ConfigServiceError::json("failed to deserialize configuration", err))?; + + Ok(ConfigReadResponse { + config, + origins: layers.origins(), + layers: params.include_layers.then(|| layers.layers_high_to_low()), + }) + } + + pub async fn write_value( + &self, + params: ConfigValueWriteParams, + ) -> Result { + let edits = vec![(params.key_path, params.value, params.merge_strategy)]; + self.apply_edits(params.file_path, params.expected_version, edits) + .await + } + + pub async fn batch_write( + &self, + params: ConfigBatchWriteParams, + ) -> Result { + let edits = params + .edits + .into_iter() + .map(|edit| (edit.key_path, edit.value, edit.merge_strategy)) + .collect(); + + self.apply_edits(params.file_path, params.expected_version, edits) + .await + } + + pub async fn load_user_saved_config( + &self, + ) -> Result { + let layers = self + .load_layers_state() + .await + .map_err(|err| ConfigServiceError::io("failed to load configuration", err))?; + + let toml_value = layers.effective_config(); + let cfg: ConfigToml = toml_value + .try_into() + .map_err(|err| ConfigServiceError::toml("failed to parse config.toml", err))?; + Ok(cfg.into()) + } + + async fn apply_edits( + &self, + file_path: Option, + expected_version: Option, + edits: Vec<(String, JsonValue, MergeStrategy)>, + ) -> Result { + let allowed_path = self.codex_home.join(CONFIG_TOML_FILE); + let provided_path = file_path + .as_ref() + .map(PathBuf::from) + .unwrap_or_else(|| allowed_path.clone()); + + if !paths_match(&allowed_path, &provided_path) { + return Err(ConfigServiceError::write( + ConfigWriteErrorCode::ConfigLayerReadonly, + "Only writes to the user config are allowed", + )); + } + + let layers = self + .load_layers_state() + .await + .map_err(|err| ConfigServiceError::io("failed to load configuration", err))?; + + if let Some(expected) = expected_version.as_deref() + && expected != layers.user.version + { + return Err(ConfigServiceError::write( + ConfigWriteErrorCode::ConfigVersionConflict, + "Configuration was modified since last read. Fetch latest version and retry.", + )); + } + + let mut user_config = layers.user.config.clone(); + let mut parsed_segments = Vec::new(); + let mut config_edits = Vec::new(); + + for (key_path, value, strategy) in edits.into_iter() { + let segments = parse_key_path(&key_path).map_err(|message| { + ConfigServiceError::write(ConfigWriteErrorCode::ConfigValidationError, message) + })?; + let original_value = value_at_path(&user_config, &segments).cloned(); + let parsed_value = parse_value(value).map_err(|message| { + ConfigServiceError::write(ConfigWriteErrorCode::ConfigValidationError, message) + })?; + + apply_merge(&mut user_config, &segments, parsed_value.as_ref(), strategy).map_err( + |err| match err { + MergeError::PathNotFound => ConfigServiceError::write( + ConfigWriteErrorCode::ConfigPathNotFound, + "Path not found", + ), + MergeError::Validation(message) => ConfigServiceError::write( + ConfigWriteErrorCode::ConfigValidationError, + message, + ), + }, + )?; + + let updated_value = value_at_path(&user_config, &segments).cloned(); + if original_value != updated_value { + let edit = match updated_value { + Some(value) => ConfigEdit::SetPath { + segments: segments.clone(), + value: toml_value_to_item(&value).map_err(|err| { + ConfigServiceError::anyhow("failed to build config edits", err) + })?, + }, + None => ConfigEdit::ClearPath { + segments: segments.clone(), + }, + }; + config_edits.push(edit); + } + + parsed_segments.push(segments); + } + + validate_config(&user_config).map_err(|err| { + ConfigServiceError::write( + ConfigWriteErrorCode::ConfigValidationError, + format!("Invalid configuration: {err}"), + ) + })?; + + let updated_layers = layers.with_user_config(user_config.clone()); + let effective = updated_layers.effective_config(); + validate_config(&effective).map_err(|err| { + ConfigServiceError::write( + ConfigWriteErrorCode::ConfigValidationError, + format!("Invalid configuration: {err}"), + ) + })?; + + if !config_edits.is_empty() { + ConfigEditsBuilder::new(&self.codex_home) + .with_edits(config_edits) + .apply() + .await + .map_err(|err| ConfigServiceError::anyhow("failed to persist config.toml", err))?; + } + + let overridden = first_overridden_edit(&updated_layers, &effective, &parsed_segments); + let status = overridden + .as_ref() + .map(|_| WriteStatus::OkOverridden) + .unwrap_or(WriteStatus::Ok); + + let file_path = provided_path + .canonicalize() + .unwrap_or(provided_path.clone()) + .display() + .to_string(); + + Ok(ConfigWriteResponse { + status, + version: updated_layers.user.version.clone(), + file_path, + overridden_metadata: overridden, + }) + } + + async fn load_layers_state(&self) -> std::io::Result { + load_config_layers_state( + &self.codex_home, + &self.cli_overrides, + self.loader_overrides.clone(), + ) + .await + } +} + +fn parse_value(value: JsonValue) -> Result, String> { + if value.is_null() { + return Ok(None); + } + + serde_json::from_value::(value) + .map(Some) + .map_err(|err| format!("invalid value: {err}")) +} + +fn parse_key_path(path: &str) -> Result, String> { + if path.trim().is_empty() { + return Err("keyPath must not be empty".to_string()); + } + Ok(path + .split('.') + .map(std::string::ToString::to_string) + .collect()) +} + +#[derive(Debug)] +enum MergeError { + PathNotFound, + Validation(String), +} + +fn apply_merge( + root: &mut TomlValue, + segments: &[String], + value: Option<&TomlValue>, + strategy: MergeStrategy, +) -> Result { + let Some(value) = value else { + return clear_path(root, segments); + }; + + let Some((last, parents)) = segments.split_last() else { + return Err(MergeError::Validation( + "keyPath must not be empty".to_string(), + )); + }; + + let mut current = root; + + for segment in parents { + match current { + TomlValue::Table(table) => { + current = table + .entry(segment.clone()) + .or_insert_with(|| TomlValue::Table(toml::map::Map::new())); + } + _ => { + *current = TomlValue::Table(toml::map::Map::new()); + if let TomlValue::Table(table) = current { + current = table + .entry(segment.clone()) + .or_insert_with(|| TomlValue::Table(toml::map::Map::new())); + } + } + } + } + + let table = current.as_table_mut().ok_or_else(|| { + MergeError::Validation("cannot set value on non-table parent".to_string()) + })?; + + if matches!(strategy, MergeStrategy::Upsert) + && let Some(existing) = table.get_mut(last) + && matches!(existing, TomlValue::Table(_)) + && matches!(value, TomlValue::Table(_)) + { + merge_toml_values(existing, value); + return Ok(true); + } + + let changed = table + .get(last) + .map(|existing| Some(existing) != Some(value)) + .unwrap_or(true); + table.insert(last.clone(), value.clone()); + Ok(changed) +} + +fn clear_path(root: &mut TomlValue, segments: &[String]) -> Result { + let Some((last, parents)) = segments.split_last() else { + return Err(MergeError::Validation( + "keyPath must not be empty".to_string(), + )); + }; + + let mut current = root; + for segment in parents { + match current { + TomlValue::Table(table) => { + current = table.get_mut(segment).ok_or(MergeError::PathNotFound)?; + } + _ => return Err(MergeError::PathNotFound), + } + } + + let Some(parent) = current.as_table_mut() else { + return Err(MergeError::PathNotFound); + }; + + Ok(parent.remove(last).is_some()) +} + +fn toml_value_to_item(value: &TomlValue) -> anyhow::Result { + match value { + TomlValue::Table(table) => { + let mut table_item = toml_edit::Table::new(); + table_item.set_implicit(false); + for (key, val) in table { + table_item.insert(key, toml_value_to_item(val)?); + } + Ok(TomlItem::Table(table_item)) + } + other => Ok(TomlItem::Value(toml_value_to_value(other)?)), + } +} + +fn toml_value_to_value(value: &TomlValue) -> anyhow::Result { + match value { + TomlValue::String(val) => Ok(toml_edit::Value::from(val.clone())), + TomlValue::Integer(val) => Ok(toml_edit::Value::from(*val)), + TomlValue::Float(val) => Ok(toml_edit::Value::from(*val)), + TomlValue::Boolean(val) => Ok(toml_edit::Value::from(*val)), + TomlValue::Datetime(val) => Ok(toml_edit::Value::from(*val)), + TomlValue::Array(items) => { + let mut array = toml_edit::Array::new(); + for item in items { + array.push(toml_value_to_value(item)?); + } + Ok(toml_edit::Value::Array(array)) + } + TomlValue::Table(table) => { + let mut inline = toml_edit::InlineTable::new(); + for (key, val) in table { + inline.insert(key, toml_value_to_value(val)?); + } + Ok(toml_edit::Value::InlineTable(inline)) + } + } +} + +fn validate_config(value: &TomlValue) -> Result<(), toml::de::Error> { + let _: ConfigToml = value.clone().try_into()?; + Ok(()) +} + +fn paths_match(expected: &Path, provided: &Path) -> bool { + if let (Ok(expanded_expected), Ok(expanded_provided)) = + (expected.canonicalize(), provided.canonicalize()) + { + return expanded_expected == expanded_provided; + } + + expected == provided +} + +fn value_at_path<'a>(root: &'a TomlValue, segments: &[String]) -> Option<&'a TomlValue> { + let mut current = root; + for segment in segments { + match current { + TomlValue::Table(table) => { + current = table.get(segment)?; + } + TomlValue::Array(items) => { + let idx = segment.parse::().ok()?; + let idx = usize::try_from(idx).ok()?; + current = items.get(idx)?; + } + _ => return None, + } + } + Some(current) +} + +fn override_message(layer: &ConfigLayerName) -> String { + match layer { + ConfigLayerName::Mdm => "Overridden by managed policy (mdm)".to_string(), + ConfigLayerName::System => "Overridden by managed config (system)".to_string(), + ConfigLayerName::SessionFlags => "Overridden by session flags".to_string(), + ConfigLayerName::User => "Overridden by user config".to_string(), + } +} + +fn compute_override_metadata( + layers: &ConfigLayerStack, + effective: &TomlValue, + segments: &[String], +) -> Option { + let user_value = value_at_path(&layers.user.config, segments); + let effective_value = value_at_path(effective, segments); + + if user_value.is_some() && user_value == effective_value { + return None; + } + + if user_value.is_none() && effective_value.is_none() { + return None; + } + + let effective_layer = find_effective_layer(layers, segments); + let overriding_layer = effective_layer.unwrap_or_else(|| layers.user.metadata()); + let message = override_message(&overriding_layer.name); + + Some(OverriddenMetadata { + message, + overriding_layer, + effective_value: effective_value + .and_then(|value| serde_json::to_value(value).ok()) + .unwrap_or(JsonValue::Null), + }) +} + +fn first_overridden_edit( + layers: &ConfigLayerStack, + effective: &TomlValue, + edits: &[Vec], +) -> Option { + for segments in edits { + if let Some(meta) = compute_override_metadata(layers, effective, segments) { + return Some(meta); + } + } + None +} + +fn find_effective_layer( + layers: &ConfigLayerStack, + segments: &[String], +) -> Option { + let check = + |state: &ConfigLayerEntry| value_at_path(&state.config, segments).map(|_| state.metadata()); + + if let Some(mdm) = &layers.mdm + && let Some(meta) = check(mdm) + { + return Some(meta); + } + if let Some(system) = &layers.system + && let Some(meta) = check(system) + { + return Some(meta); + } + if let Some(meta) = check(&layers.session_flags) { + return Some(meta); + } + check(&layers.user) +} + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::Result; + use codex_app_server_protocol::AskForApproval; + use pretty_assertions::assert_eq; + use tempfile::tempdir; + + #[test] + fn toml_value_to_item_handles_nested_config_tables() { + let config = r#" +[mcp_servers.docs] +command = "docs-server" + +[mcp_servers.docs.http_headers] +X-Doc = "42" +"#; + + let value: TomlValue = toml::from_str(config).expect("parse config example"); + let item = toml_value_to_item(&value).expect("convert to toml_edit item"); + + let root = item.as_table().expect("root table"); + assert!(!root.is_implicit(), "root table should be explicit"); + + let mcp_servers = root + .get("mcp_servers") + .and_then(TomlItem::as_table) + .expect("mcp_servers table"); + assert!( + !mcp_servers.is_implicit(), + "mcp_servers table should be explicit" + ); + + let docs = mcp_servers + .get("docs") + .and_then(TomlItem::as_table) + .expect("docs table"); + assert_eq!( + docs.get("command") + .and_then(TomlItem::as_value) + .and_then(toml_edit::Value::as_str), + Some("docs-server") + ); + + let http_headers = docs + .get("http_headers") + .and_then(TomlItem::as_table) + .expect("http_headers table"); + assert_eq!( + http_headers + .get("X-Doc") + .and_then(TomlItem::as_value) + .and_then(toml_edit::Value::as_str), + Some("42") + ); + } + + #[tokio::test] + async fn write_value_preserves_comments_and_order() -> Result<()> { + let tmp = tempdir().expect("tempdir"); + let original = r#"# Codex user configuration +model = "gpt-5" +approval_policy = "on-request" + +[notice] +# Preserve this comment +hide_full_access_warning = true + +[features] +unified_exec = true +"#; + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), original)?; + + let service = ConfigService::new(tmp.path().to_path_buf(), vec![]); + service + .write_value(ConfigValueWriteParams { + file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), + key_path: "features.remote_compaction".to_string(), + value: serde_json::json!(true), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect("write succeeds"); + + let updated = + std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).expect("read config"); + let expected = r#"# Codex user configuration +model = "gpt-5" +approval_policy = "on-request" + +[notice] +# Preserve this comment +hide_full_access_warning = true + +[features] +unified_exec = true +remote_compaction = true +"#; + assert_eq!(updated, expected); + Ok(()) + } + + #[tokio::test] + async fn read_includes_origins_and_layers() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "model = \"user\"").unwrap(); + + let managed_path = tmp.path().join("managed_config.toml"); + std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); + + let service = ConfigService::with_overrides( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides { + managed_config_path: Some(managed_path), + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + }, + ); + + let response = service + .read(ConfigReadParams { + include_layers: true, + }) + .await + .expect("response"); + + assert_eq!(response.config.approval_policy, Some(AskForApproval::Never)); + + assert_eq!( + response + .origins + .get("approval_policy") + .expect("origin") + .name, + ConfigLayerName::System + ); + let layers = response.layers.expect("layers present"); + assert_eq!(layers.first().unwrap().name, ConfigLayerName::System); + assert_eq!(layers.get(1).unwrap().name, ConfigLayerName::SessionFlags); + assert_eq!(layers.last().unwrap().name, ConfigLayerName::User); + } + + #[tokio::test] + async fn write_value_reports_override() { + let tmp = tempdir().expect("tempdir"); + std::fs::write( + tmp.path().join(CONFIG_TOML_FILE), + "approval_policy = \"on-request\"", + ) + .unwrap(); + + let managed_path = tmp.path().join("managed_config.toml"); + std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); + + let service = ConfigService::with_overrides( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides { + managed_config_path: Some(managed_path), + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + }, + ); + + let result = service + .write_value(ConfigValueWriteParams { + file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), + key_path: "approval_policy".to_string(), + value: serde_json::json!("never"), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect("result"); + + let read_after = service + .read(ConfigReadParams { + include_layers: true, + }) + .await + .expect("read"); + assert_eq!( + read_after.config.approval_policy, + Some(AskForApproval::Never) + ); + assert_eq!( + read_after + .origins + .get("approval_policy") + .expect("origin") + .name, + ConfigLayerName::System + ); + assert_eq!(result.status, WriteStatus::Ok); + assert!(result.overridden_metadata.is_none()); + } + + #[tokio::test] + async fn version_conflict_rejected() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "model = \"user\"").unwrap(); + + let service = ConfigService::new(tmp.path().to_path_buf(), vec![]); + let error = service + .write_value(ConfigValueWriteParams { + file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), + key_path: "model".to_string(), + value: serde_json::json!("gpt-5"), + merge_strategy: MergeStrategy::Replace, + expected_version: Some("sha256:bogus".to_string()), + }) + .await + .expect_err("should fail"); + + assert_eq!( + error.write_error_code(), + Some(ConfigWriteErrorCode::ConfigVersionConflict) + ); + } + + #[tokio::test] + async fn write_value_defaults_to_user_config_path() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); + + let service = ConfigService::new(tmp.path().to_path_buf(), vec![]); + service + .write_value(ConfigValueWriteParams { + file_path: None, + key_path: "model".to_string(), + value: serde_json::json!("gpt-new"), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect("write succeeds"); + + let contents = + std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).expect("read config"); + assert!( + contents.contains("model = \"gpt-new\""), + "config.toml should be updated even when file_path is omitted" + ); + } + + #[tokio::test] + async fn invalid_user_value_rejected_even_if_overridden_by_managed() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "model = \"user\"").unwrap(); + + let managed_path = tmp.path().join("managed_config.toml"); + std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); + + let service = ConfigService::with_overrides( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides { + managed_config_path: Some(managed_path), + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + }, + ); + + let error = service + .write_value(ConfigValueWriteParams { + file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), + key_path: "approval_policy".to_string(), + value: serde_json::json!("bogus"), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect_err("should fail validation"); + + assert_eq!( + error.write_error_code(), + Some(ConfigWriteErrorCode::ConfigValidationError) + ); + + let contents = + std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).expect("read config"); + assert_eq!(contents.trim(), "model = \"user\""); + } + + #[tokio::test] + async fn read_reports_managed_overrides_user_and_session_flags() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "model = \"user\"").unwrap(); + + let managed_path = tmp.path().join("managed_config.toml"); + std::fs::write(&managed_path, "model = \"system\"").unwrap(); + + let cli_overrides = vec![( + "model".to_string(), + TomlValue::String("session".to_string()), + )]; + + let service = ConfigService::with_overrides( + tmp.path().to_path_buf(), + cli_overrides, + LoaderOverrides { + managed_config_path: Some(managed_path), + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + }, + ); + + let response = service + .read(ConfigReadParams { + include_layers: true, + }) + .await + .expect("response"); + + assert_eq!(response.config.model.as_deref(), Some("system")); + assert_eq!( + response.origins.get("model").expect("origin").name, + ConfigLayerName::System + ); + let layers = response.layers.expect("layers"); + assert_eq!(layers.first().unwrap().name, ConfigLayerName::System); + assert_eq!(layers.get(1).unwrap().name, ConfigLayerName::SessionFlags); + assert_eq!(layers.get(2).unwrap().name, ConfigLayerName::User); + } + + #[tokio::test] + async fn write_value_reports_managed_override() { + let tmp = tempdir().expect("tempdir"); + std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); + + let managed_path = tmp.path().join("managed_config.toml"); + std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); + + let service = ConfigService::with_overrides( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides { + managed_config_path: Some(managed_path), + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + }, + ); + + let result = service + .write_value(ConfigValueWriteParams { + file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), + key_path: "approval_policy".to_string(), + value: serde_json::json!("on-request"), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect("result"); + + assert_eq!(result.status, WriteStatus::OkOverridden); + let overridden = result.overridden_metadata.expect("overridden metadata"); + assert_eq!(overridden.overriding_layer.name, ConfigLayerName::System); + assert_eq!(overridden.effective_value, serde_json::json!("never")); + } +} diff --git a/codex-rs/core/src/config_loader/README.md b/codex-rs/core/src/config_loader/README.md new file mode 100644 index 0000000000..da427c4544 --- /dev/null +++ b/codex-rs/core/src/config_loader/README.md @@ -0,0 +1,64 @@ +# `codex-core` config loader + +This module is the canonical place to **load and describe Codex configuration layers** (user config, CLI/session overrides, managed config, and MDM-managed preferences) and to produce: + +- An **effective merged** TOML config. +- **Per-key origins** metadata (which layer “wins” for a given key). +- **Per-layer versions** (stable fingerprints) used for optimistic concurrency / conflict detection. + +## Public surface + +Exported from `codex_core::config_loader`: + +- `load_config_layers_state(codex_home, cli_overrides, overrides) -> ConfigLayerStack` +- `ConfigLayerStack` + - `effective_config() -> toml::Value` + - `origins() -> HashMap` + - `layers_high_to_low() -> Vec` + - `with_user_config(user_config) -> ConfigLayerStack` +- `ConfigLayerEntry` (one layer’s `{name, source, config, version}`) +- `LoaderOverrides` (test/override hooks for managed config sources) +- `merge_toml_values(base, overlay)` (public helper used elsewhere) + +## Layering model + +Precedence is **top overrides bottom**: + +1. **MDM** managed preferences (macOS only) +2. **System** managed config (e.g. `managed_config.toml`) +3. **Session flags** (CLI overrides, applied as dotted-path TOML writes) +4. **User** config (`config.toml`) + +This is what `ConfigLayerStack::effective_config()` implements. + +## Typical usage + +Most callers want the effective config plus metadata: + +```rust +use codex_core::config_loader::{load_config_layers_state, LoaderOverrides}; +use toml::Value as TomlValue; + +let cli_overrides: Vec<(String, TomlValue)> = Vec::new(); +let layers = load_config_layers_state( + &codex_home, + &cli_overrides, + LoaderOverrides::default(), +).await?; + +let effective = layers.effective_config(); +let origins = layers.origins(); +let layers_for_ui = layers.layers_high_to_low(); +``` + +## Internal layout + +Implementation is split by concern: + +- `state.rs`: public types (`ConfigLayerEntry`, `ConfigLayerStack`) + merge/origins convenience methods. +- `layer_io.rs`: reading `config.toml`, managed config, and managed preferences inputs. +- `overrides.rs`: CLI dotted-path overrides → TOML “session flags” layer. +- `merge.rs`: recursive TOML merge. +- `fingerprint.rs`: stable per-layer hashing and per-key origins traversal. +- `macos.rs`: managed preferences integration (macOS only). + diff --git a/codex-rs/core/src/config_loader/fingerprint.rs b/codex-rs/core/src/config_loader/fingerprint.rs new file mode 100644 index 0000000000..c072134fde --- /dev/null +++ b/codex-rs/core/src/config_loader/fingerprint.rs @@ -0,0 +1,67 @@ +use codex_app_server_protocol::ConfigLayerMetadata; +use serde_json::Value as JsonValue; +use sha2::Digest; +use sha2::Sha256; +use std::collections::HashMap; +use toml::Value as TomlValue; + +pub(super) fn record_origins( + value: &TomlValue, + meta: &ConfigLayerMetadata, + path: &mut Vec, + origins: &mut HashMap, +) { + match value { + TomlValue::Table(table) => { + for (key, val) in table { + path.push(key.clone()); + record_origins(val, meta, path, origins); + path.pop(); + } + } + TomlValue::Array(items) => { + for (idx, item) in (0_i32..).zip(items.iter()) { + path.push(idx.to_string()); + record_origins(item, meta, path, origins); + path.pop(); + } + } + _ => { + if !path.is_empty() { + origins.insert(path.join("."), meta.clone()); + } + } + } +} + +pub(super) fn version_for_toml(value: &TomlValue) -> String { + let json = serde_json::to_value(value).unwrap_or(JsonValue::Null); + let canonical = canonical_json(&json); + let serialized = serde_json::to_vec(&canonical).unwrap_or_default(); + let mut hasher = Sha256::new(); + hasher.update(serialized); + let hash = hasher.finalize(); + let hex = hash + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + format!("sha256:{hex}") +} + +fn canonical_json(value: &JsonValue) -> JsonValue { + match value { + JsonValue::Object(map) => { + let mut sorted = serde_json::Map::new(); + let mut keys = map.keys().cloned().collect::>(); + keys.sort(); + for key in keys { + if let Some(val) = map.get(&key) { + sorted.insert(key, canonical_json(val)); + } + } + JsonValue::Object(sorted) + } + JsonValue::Array(items) => JsonValue::Array(items.iter().map(canonical_json).collect()), + other => other.clone(), + } +} diff --git a/codex-rs/core/src/config_loader/layer_io.rs b/codex-rs/core/src/config_loader/layer_io.rs new file mode 100644 index 0000000000..1e9052f216 --- /dev/null +++ b/codex-rs/core/src/config_loader/layer_io.rs @@ -0,0 +1,100 @@ +use super::LoaderOverrides; +use super::macos::load_managed_admin_config_layer; +use super::overrides::default_empty_table; +use crate::config::CONFIG_TOML_FILE; +use std::io; +use std::path::Path; +use std::path::PathBuf; +use tokio::fs; +use toml::Value as TomlValue; + +#[cfg(unix)] +const CODEX_MANAGED_CONFIG_SYSTEM_PATH: &str = "/etc/codex/managed_config.toml"; + +#[derive(Debug, Clone)] +pub(super) struct LoadedConfigLayers { + pub base: TomlValue, + pub managed_config: Option, + pub managed_preferences: Option, +} + +pub(super) async fn load_config_layers_internal( + codex_home: &Path, + overrides: LoaderOverrides, +) -> io::Result { + #[cfg(target_os = "macos")] + let LoaderOverrides { + managed_config_path, + managed_preferences_base64, + } = overrides; + + #[cfg(not(target_os = "macos"))] + let LoaderOverrides { + managed_config_path, + } = overrides; + + let managed_config_path = + managed_config_path.unwrap_or_else(|| managed_config_default_path(codex_home)); + + let user_config_path = codex_home.join(CONFIG_TOML_FILE); + let user_config = read_config_from_path(&user_config_path, true).await?; + let managed_config = read_config_from_path(&managed_config_path, false).await?; + + #[cfg(target_os = "macos")] + let managed_preferences = + load_managed_admin_config_layer(managed_preferences_base64.as_deref()).await?; + + #[cfg(not(target_os = "macos"))] + let managed_preferences = load_managed_admin_config_layer(None).await?; + + Ok(LoadedConfigLayers { + base: user_config.unwrap_or_else(default_empty_table), + managed_config, + managed_preferences, + }) +} + +pub(super) async fn read_config_from_path( + path: &Path, + log_missing_as_info: bool, +) -> io::Result> { + match fs::read_to_string(path).await { + Ok(contents) => match toml::from_str::(&contents) { + Ok(value) => Ok(Some(value)), + Err(err) => { + tracing::error!("Failed to parse {}: {err}", path.display()); + Err(io::Error::new(io::ErrorKind::InvalidData, err)) + } + }, + Err(err) if err.kind() == io::ErrorKind::NotFound => { + if log_missing_as_info { + tracing::info!("{} not found, using defaults", path.display()); + } else { + tracing::debug!("{} not found", path.display()); + } + Ok(None) + } + Err(err) => { + tracing::error!("Failed to read {}: {err}", path.display()); + Err(err) + } + } +} + +/// Return the default managed config path (honoring `CODEX_MANAGED_CONFIG_PATH`). +pub(super) fn managed_config_default_path(codex_home: &Path) -> PathBuf { + if let Ok(path) = std::env::var("CODEX_MANAGED_CONFIG_PATH") { + return PathBuf::from(path); + } + + #[cfg(unix)] + { + let _ = codex_home; + PathBuf::from(CODEX_MANAGED_CONFIG_SYSTEM_PATH) + } + + #[cfg(not(unix))] + { + codex_home.join("managed_config.toml") + } +} diff --git a/codex-rs/core/src/config_loader/merge.rs b/codex-rs/core/src/config_loader/merge.rs new file mode 100644 index 0000000000..eacbbcb788 --- /dev/null +++ b/codex-rs/core/src/config_loader/merge.rs @@ -0,0 +1,18 @@ +use toml::Value as TomlValue; + +/// Merge config `overlay` into `base`, giving `overlay` precedence. +pub fn merge_toml_values(base: &mut TomlValue, overlay: &TomlValue) { + if let TomlValue::Table(overlay_table) = overlay + && let TomlValue::Table(base_table) = base + { + for (key, value) in overlay_table { + if let Some(existing) = base_table.get_mut(key) { + merge_toml_values(existing, value); + } else { + base_table.insert(key.clone(), value.clone()); + } + } + } else { + *base = overlay.clone(); + } +} diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index 4cd541d3e5..c7c522008d 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -1,319 +1,74 @@ +mod fingerprint; +mod layer_io; mod macos; +mod merge; +mod overrides; +mod state; + +#[cfg(test)] +mod tests; use crate::config::CONFIG_TOML_FILE; -use macos::load_managed_admin_config_layer; +use codex_app_server_protocol::ConfigLayerName; use std::io; use std::path::Path; use std::path::PathBuf; -use tokio::fs; use toml::Value as TomlValue; -#[cfg(unix)] -const CODEX_MANAGED_CONFIG_SYSTEM_PATH: &str = "/etc/codex/managed_config.toml"; +pub use merge::merge_toml_values; +pub use state::ConfigLayerEntry; +pub use state::ConfigLayerStack; +pub use state::LoaderOverrides; -#[derive(Debug, Clone)] -pub struct LoadedConfigLayers { - pub base: TomlValue, - pub managed_config: Option, - pub managed_preferences: Option, -} +const SESSION_FLAGS_SOURCE: &str = "--config"; +const MDM_SOURCE: &str = "com.openai.codex/config_toml_base64"; -#[derive(Debug, Default, Clone)] -pub struct LoaderOverrides { - pub managed_config_path: Option, - #[cfg(target_os = "macos")] - pub managed_preferences_base64: Option, -} - -// Configuration layering pipeline (top overrides bottom): -// -// +-------------------------+ -// | Managed preferences (*) | -// +-------------------------+ -// ^ -// | -// +-------------------------+ -// | managed_config.toml | -// +-------------------------+ -// ^ -// | -// +-------------------------+ -// | config.toml (base) | -// +-------------------------+ -// -// (*) Only available on macOS via managed device profiles. - -pub async fn load_config_as_toml(codex_home: &Path) -> io::Result { - load_config_as_toml_with_overrides(codex_home, LoaderOverrides::default()).await -} - -pub async fn load_config_layers(codex_home: &Path) -> io::Result { - load_config_layers_with_overrides(codex_home, LoaderOverrides::default()).await -} - -fn default_empty_table() -> TomlValue { - TomlValue::Table(Default::default()) -} - -pub async fn load_config_layers_with_overrides( +/// Configuration layering pipeline (top overrides bottom): +/// +/// +-------------------------+ +/// | Managed preferences (*) | +/// +-------------------------+ +/// ^ +/// | +/// +-------------------------+ +/// | managed_config.toml | +/// +-------------------------+ +/// ^ +/// | +/// +-------------------------+ +/// | config.toml (base) | +/// +-------------------------+ +/// +/// (*) Only available on macOS via managed device profiles. +pub async fn load_config_layers_state( codex_home: &Path, + cli_overrides: &[(String, TomlValue)], overrides: LoaderOverrides, -) -> io::Result { - load_config_layers_internal(codex_home, overrides).await -} +) -> io::Result { + let managed_config_path = overrides + .managed_config_path + .clone() + .unwrap_or_else(|| layer_io::managed_config_default_path(codex_home)); -async fn load_config_as_toml_with_overrides( - codex_home: &Path, - overrides: LoaderOverrides, -) -> io::Result { - let layers = load_config_layers_internal(codex_home, overrides).await?; - Ok(apply_managed_layers(layers)) -} + let layers = layer_io::load_config_layers_internal(codex_home, overrides).await?; + let cli_overrides = overrides::build_cli_overrides_layer(cli_overrides); -async fn load_config_layers_internal( - codex_home: &Path, - overrides: LoaderOverrides, -) -> io::Result { - #[cfg(target_os = "macos")] - let LoaderOverrides { - managed_config_path, - managed_preferences_base64, - } = overrides; - - #[cfg(not(target_os = "macos"))] - let LoaderOverrides { - managed_config_path, - } = overrides; - - let managed_config_path = - managed_config_path.unwrap_or_else(|| managed_config_default_path(codex_home)); - - let user_config_path = codex_home.join(CONFIG_TOML_FILE); - let user_config = read_config_from_path(&user_config_path, true).await?; - let managed_config = read_config_from_path(&managed_config_path, false).await?; - - #[cfg(target_os = "macos")] - let managed_preferences = - load_managed_admin_config_layer(managed_preferences_base64.as_deref()).await?; - - #[cfg(not(target_os = "macos"))] - let managed_preferences = load_managed_admin_config_layer(None).await?; - - Ok(LoadedConfigLayers { - base: user_config.unwrap_or_else(default_empty_table), - managed_config, - managed_preferences, + Ok(ConfigLayerStack { + user: ConfigLayerEntry::new( + ConfigLayerName::User, + codex_home.join(CONFIG_TOML_FILE), + layers.base, + ), + session_flags: ConfigLayerEntry::new( + ConfigLayerName::SessionFlags, + PathBuf::from(SESSION_FLAGS_SOURCE), + cli_overrides, + ), + system: layers.managed_config.map(|cfg| { + ConfigLayerEntry::new(ConfigLayerName::System, managed_config_path.clone(), cfg) + }), + mdm: layers + .managed_preferences + .map(|cfg| ConfigLayerEntry::new(ConfigLayerName::Mdm, PathBuf::from(MDM_SOURCE), cfg)), }) } - -async fn read_config_from_path( - path: &Path, - log_missing_as_info: bool, -) -> io::Result> { - match fs::read_to_string(path).await { - Ok(contents) => match toml::from_str::(&contents) { - Ok(value) => Ok(Some(value)), - Err(err) => { - tracing::error!("Failed to parse {}: {err}", path.display()); - Err(io::Error::new(io::ErrorKind::InvalidData, err)) - } - }, - Err(err) if err.kind() == io::ErrorKind::NotFound => { - if log_missing_as_info { - tracing::info!("{} not found, using defaults", path.display()); - } else { - tracing::debug!("{} not found", path.display()); - } - Ok(None) - } - Err(err) => { - tracing::error!("Failed to read {}: {err}", path.display()); - Err(err) - } - } -} - -/// Merge config `overlay` into `base`, giving `overlay` precedence. -pub fn merge_toml_values(base: &mut TomlValue, overlay: &TomlValue) { - if let TomlValue::Table(overlay_table) = overlay - && let TomlValue::Table(base_table) = base - { - for (key, value) in overlay_table { - if let Some(existing) = base_table.get_mut(key) { - merge_toml_values(existing, value); - } else { - base_table.insert(key.clone(), value.clone()); - } - } - } else { - *base = overlay.clone(); - } -} - -fn managed_config_default_path(codex_home: &Path) -> PathBuf { - if let Ok(path) = std::env::var("CODEX_MANAGED_CONFIG_PATH") { - return PathBuf::from(path); - } - - #[cfg(unix)] - { - let _ = codex_home; - PathBuf::from(CODEX_MANAGED_CONFIG_SYSTEM_PATH) - } - - #[cfg(not(unix))] - { - codex_home.join("managed_config.toml") - } -} - -fn apply_managed_layers(layers: LoadedConfigLayers) -> TomlValue { - let LoadedConfigLayers { - mut base, - managed_config, - managed_preferences, - } = layers; - - for overlay in [managed_config, managed_preferences].into_iter().flatten() { - merge_toml_values(&mut base, &overlay); - } - - base -} - -#[cfg(test)] -mod tests { - use super::*; - use tempfile::tempdir; - - #[tokio::test] - async fn merges_managed_config_layer_on_top() { - let tmp = tempdir().expect("tempdir"); - let managed_path = tmp.path().join("managed_config.toml"); - - std::fs::write( - tmp.path().join(CONFIG_TOML_FILE), - r#"foo = 1 - -[nested] -value = "base" -"#, - ) - .expect("write base"); - std::fs::write( - &managed_path, - r#"foo = 2 - -[nested] -value = "managed_config" -extra = true -"#, - ) - .expect("write managed config"); - - let overrides = LoaderOverrides { - managed_config_path: Some(managed_path), - #[cfg(target_os = "macos")] - managed_preferences_base64: None, - }; - - let loaded = load_config_as_toml_with_overrides(tmp.path(), overrides) - .await - .expect("load config"); - let table = loaded.as_table().expect("top-level table expected"); - - assert_eq!(table.get("foo"), Some(&TomlValue::Integer(2))); - let nested = table - .get("nested") - .and_then(|v| v.as_table()) - .expect("nested"); - assert_eq!( - nested.get("value"), - Some(&TomlValue::String("managed_config".to_string())) - ); - assert_eq!(nested.get("extra"), Some(&TomlValue::Boolean(true))); - } - - #[tokio::test] - async fn returns_empty_when_all_layers_missing() { - let tmp = tempdir().expect("tempdir"); - let managed_path = tmp.path().join("managed_config.toml"); - let overrides = LoaderOverrides { - managed_config_path: Some(managed_path), - #[cfg(target_os = "macos")] - managed_preferences_base64: None, - }; - - let layers = load_config_layers_with_overrides(tmp.path(), overrides) - .await - .expect("load layers"); - let base_table = layers.base.as_table().expect("base table expected"); - assert!( - base_table.is_empty(), - "expected empty base layer when configs missing" - ); - assert!( - layers.managed_config.is_none(), - "managed config layer should be absent when file missing" - ); - - #[cfg(not(target_os = "macos"))] - { - let loaded = load_config_as_toml(tmp.path()).await.expect("load config"); - let table = loaded.as_table().expect("top-level table expected"); - assert!( - table.is_empty(), - "expected empty table when configs missing" - ); - } - } - - #[cfg(target_os = "macos")] - #[tokio::test] - async fn managed_preferences_take_highest_precedence() { - use base64::Engine; - - let managed_payload = r#" -[nested] -value = "managed" -flag = false -"#; - let encoded = base64::prelude::BASE64_STANDARD.encode(managed_payload.as_bytes()); - let tmp = tempdir().expect("tempdir"); - let managed_path = tmp.path().join("managed_config.toml"); - - std::fs::write( - tmp.path().join(CONFIG_TOML_FILE), - r#"[nested] -value = "base" -"#, - ) - .expect("write base"); - std::fs::write( - &managed_path, - r#"[nested] -value = "managed_config" -flag = true -"#, - ) - .expect("write managed config"); - - let overrides = LoaderOverrides { - managed_config_path: Some(managed_path), - managed_preferences_base64: Some(encoded), - }; - - let loaded = load_config_as_toml_with_overrides(tmp.path(), overrides) - .await - .expect("load config"); - let nested = loaded - .get("nested") - .and_then(|v| v.as_table()) - .expect("nested table"); - assert_eq!( - nested.get("value"), - Some(&TomlValue::String("managed".to_string())) - ); - assert_eq!(nested.get("flag"), Some(&TomlValue::Boolean(false))); - } -} diff --git a/codex-rs/core/src/config_loader/overrides.rs b/codex-rs/core/src/config_loader/overrides.rs new file mode 100644 index 0000000000..e2ae6375a2 --- /dev/null +++ b/codex-rs/core/src/config_loader/overrides.rs @@ -0,0 +1,55 @@ +use toml::Value as TomlValue; + +pub(super) fn default_empty_table() -> TomlValue { + TomlValue::Table(Default::default()) +} + +pub(super) fn build_cli_overrides_layer(cli_overrides: &[(String, TomlValue)]) -> TomlValue { + let mut root = default_empty_table(); + for (path, value) in cli_overrides { + apply_toml_override(&mut root, path, value.clone()); + } + root +} + +/// Apply a single dotted-path override onto a TOML value. +fn apply_toml_override(root: &mut TomlValue, path: &str, value: TomlValue) { + use toml::value::Table; + + let mut current = root; + let mut segments_iter = path.split('.').peekable(); + + while let Some(segment) = segments_iter.next() { + let is_last = segments_iter.peek().is_none(); + + if is_last { + match current { + TomlValue::Table(table) => { + table.insert(segment.to_string(), value); + } + _ => { + let mut table = Table::new(); + table.insert(segment.to_string(), value); + *current = TomlValue::Table(table); + } + } + return; + } + + match current { + TomlValue::Table(table) => { + current = table + .entry(segment.to_string()) + .or_insert_with(|| TomlValue::Table(Table::new())); + } + _ => { + *current = TomlValue::Table(Table::new()); + if let TomlValue::Table(tbl) = current { + current = tbl + .entry(segment.to_string()) + .or_insert_with(|| TomlValue::Table(Table::new())); + } + } + } + } +} diff --git a/codex-rs/core/src/config_loader/state.rs b/codex-rs/core/src/config_loader/state.rs new file mode 100644 index 0000000000..e23cc243ce --- /dev/null +++ b/codex-rs/core/src/config_loader/state.rs @@ -0,0 +1,128 @@ +use super::fingerprint::record_origins; +use super::fingerprint::version_for_toml; +use super::merge::merge_toml_values; +use codex_app_server_protocol::ConfigLayer; +use codex_app_server_protocol::ConfigLayerMetadata; +use codex_app_server_protocol::ConfigLayerName; +use serde_json::Value as JsonValue; +use std::collections::HashMap; +use std::path::PathBuf; +use toml::Value as TomlValue; + +#[derive(Debug, Default, Clone)] +pub struct LoaderOverrides { + pub managed_config_path: Option, + #[cfg(target_os = "macos")] + pub managed_preferences_base64: Option, +} + +#[derive(Debug, Clone)] +pub struct ConfigLayerEntry { + pub name: ConfigLayerName, + pub source: PathBuf, + pub config: TomlValue, + pub version: String, +} + +impl ConfigLayerEntry { + pub fn new(name: ConfigLayerName, source: PathBuf, config: TomlValue) -> Self { + let version = version_for_toml(&config); + Self { + name, + source, + config, + version, + } + } + + pub fn metadata(&self) -> ConfigLayerMetadata { + ConfigLayerMetadata { + name: self.name.clone(), + source: self.source.display().to_string(), + version: self.version.clone(), + } + } + + pub fn as_layer(&self) -> ConfigLayer { + ConfigLayer { + name: self.name.clone(), + source: self.source.display().to_string(), + version: self.version.clone(), + config: serde_json::to_value(&self.config).unwrap_or(JsonValue::Null), + } + } +} + +#[derive(Debug, Clone)] +pub struct ConfigLayerStack { + pub user: ConfigLayerEntry, + pub session_flags: ConfigLayerEntry, + pub system: Option, + pub mdm: Option, +} + +impl ConfigLayerStack { + pub fn with_user_config(&self, user_config: TomlValue) -> Self { + Self { + user: ConfigLayerEntry::new( + self.user.name.clone(), + self.user.source.clone(), + user_config, + ), + session_flags: self.session_flags.clone(), + system: self.system.clone(), + mdm: self.mdm.clone(), + } + } + + pub fn effective_config(&self) -> TomlValue { + let mut merged = self.user.config.clone(); + merge_toml_values(&mut merged, &self.session_flags.config); + if let Some(system) = &self.system { + merge_toml_values(&mut merged, &system.config); + } + if let Some(mdm) = &self.mdm { + merge_toml_values(&mut merged, &mdm.config); + } + merged + } + + pub fn origins(&self) -> HashMap { + let mut origins = HashMap::new(); + let mut path = Vec::new(); + + record_origins( + &self.user.config, + &self.user.metadata(), + &mut path, + &mut origins, + ); + record_origins( + &self.session_flags.config, + &self.session_flags.metadata(), + &mut path, + &mut origins, + ); + if let Some(system) = &self.system { + record_origins(&system.config, &system.metadata(), &mut path, &mut origins); + } + if let Some(mdm) = &self.mdm { + record_origins(&mdm.config, &mdm.metadata(), &mut path, &mut origins); + } + + origins + } + + pub fn layers_high_to_low(&self) -> Vec { + let mut layers = Vec::new(); + if let Some(mdm) = &self.mdm { + layers.push(mdm.as_layer()); + } + if let Some(system) = &self.system { + layers.push(system.as_layer()); + } + layers.push(self.session_flags.as_layer()); + layers.push(self.user.as_layer()); + layers + } +} diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs new file mode 100644 index 0000000000..121ef736dc --- /dev/null +++ b/codex-rs/core/src/config_loader/tests.rs @@ -0,0 +1,138 @@ +use super::LoaderOverrides; +use super::load_config_layers_state; +use crate::config::CONFIG_TOML_FILE; +use tempfile::tempdir; +use toml::Value as TomlValue; + +#[tokio::test] +async fn merges_managed_config_layer_on_top() { + let tmp = tempdir().expect("tempdir"); + let managed_path = tmp.path().join("managed_config.toml"); + + std::fs::write( + tmp.path().join(CONFIG_TOML_FILE), + r#"foo = 1 + +[nested] +value = "base" +"#, + ) + .expect("write base"); + std::fs::write( + &managed_path, + r#"foo = 2 + +[nested] +value = "managed_config" +extra = true +"#, + ) + .expect("write managed config"); + + let overrides = LoaderOverrides { + managed_config_path: Some(managed_path), + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + }; + + let state = load_config_layers_state(tmp.path(), &[] as &[(String, TomlValue)], overrides) + .await + .expect("load config"); + let loaded = state.effective_config(); + let table = loaded.as_table().expect("top-level table expected"); + + assert_eq!(table.get("foo"), Some(&TomlValue::Integer(2))); + let nested = table + .get("nested") + .and_then(|v| v.as_table()) + .expect("nested"); + assert_eq!( + nested.get("value"), + Some(&TomlValue::String("managed_config".to_string())) + ); + assert_eq!(nested.get("extra"), Some(&TomlValue::Boolean(true))); +} + +#[tokio::test] +async fn returns_empty_when_all_layers_missing() { + let tmp = tempdir().expect("tempdir"); + let managed_path = tmp.path().join("managed_config.toml"); + let overrides = LoaderOverrides { + managed_config_path: Some(managed_path), + #[cfg(target_os = "macos")] + managed_preferences_base64: None, + }; + + let layers = load_config_layers_state(tmp.path(), &[] as &[(String, TomlValue)], overrides) + .await + .expect("load layers"); + let base_table = layers.user.config.as_table().expect("base table expected"); + assert!( + base_table.is_empty(), + "expected empty base layer when configs missing" + ); + assert!( + layers.system.is_none(), + "managed config layer should be absent when file missing" + ); + + #[cfg(not(target_os = "macos"))] + { + let effective = layers.effective_config(); + let table = effective.as_table().expect("top-level table expected"); + assert!( + table.is_empty(), + "expected empty table when configs missing" + ); + } +} + +#[cfg(target_os = "macos")] +#[tokio::test] +async fn managed_preferences_take_highest_precedence() { + use base64::Engine; + + let managed_payload = r#" +[nested] +value = "managed" +flag = false +"#; + let encoded = base64::prelude::BASE64_STANDARD.encode(managed_payload.as_bytes()); + let tmp = tempdir().expect("tempdir"); + let managed_path = tmp.path().join("managed_config.toml"); + + std::fs::write( + tmp.path().join(CONFIG_TOML_FILE), + r#"[nested] +value = "base" +"#, + ) + .expect("write base"); + std::fs::write( + &managed_path, + r#"[nested] +value = "managed_config" +flag = true +"#, + ) + .expect("write managed config"); + + let overrides = LoaderOverrides { + managed_config_path: Some(managed_path), + managed_preferences_base64: Some(encoded), + }; + + let state = load_config_layers_state(tmp.path(), &[] as &[(String, TomlValue)], overrides) + .await + .expect("load config"); + let loaded = state.effective_config(); + let nested = loaded + .get("nested") + .and_then(|v| v.as_table()) + .expect("nested table"); + assert_eq!( + nested.get("value"), + Some(&TomlValue::String("managed".to_string())) + ); + assert_eq!(nested.get("flag"), Some(&TomlValue::Boolean(false))); +} From 570eb5fe7884ae73a684944a1c17077a6d7845fd Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Fri, 12 Dec 2025 12:21:53 -0800 Subject: [PATCH 29/77] chore(prompt) Remove truncation details (#7941) Fixes #7867 and #7906 ## Summary Update truncation details. --- codex-rs/core/gpt_5_1_prompt.md | 2 +- codex-rs/core/gpt_5_2_prompt.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/gpt_5_1_prompt.md b/codex-rs/core/gpt_5_1_prompt.md index 3201ffeb68..a4492c6acb 100644 --- a/codex-rs/core/gpt_5_1_prompt.md +++ b/codex-rs/core/gpt_5_1_prompt.md @@ -319,7 +319,7 @@ For casual greetings, acknowledgements, or other one-off conversational messages When using the shell, you must adhere to the following guidelines: - When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.) -- Read files in chunks with a max chunk size of 250 lines. Do not use python scripts to attempt to output larger chunks of a file. Command line output will be truncated after 10 kilobytes or 256 lines of output, regardless of the command used. +- Do not use python scripts to attempt to output larger chunks of a file. ## apply_patch diff --git a/codex-rs/core/gpt_5_2_prompt.md b/codex-rs/core/gpt_5_2_prompt.md index 99a3f49bbe..cfbb220849 100644 --- a/codex-rs/core/gpt_5_2_prompt.md +++ b/codex-rs/core/gpt_5_2_prompt.md @@ -285,7 +285,7 @@ For casual greetings, acknowledgements, or other one-off conversational messages When using the shell, you must adhere to the following guidelines: - When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.) -- Do not use python scripts to attempt to output larger chunks of a file. Command line output will be truncated after 10 kilobytes, regardless of the command used. +- Do not use python scripts to attempt to output larger chunks of a file. - Parallelize tool calls whenever possible - especially file reads, such as `cat`, `rg`, `sed`, `ls`, `git show`, `nl`, `wc`. Use `multi_tool_use.parallel` to parallelize tool calls and only this. ## apply_patch From 677732ff6541fad141823698f7e85920f036b2e1 Mon Sep 17 00:00:00 2001 From: iceweasel-oai Date: Fri, 12 Dec 2025 12:30:38 -0800 Subject: [PATCH 30/77] Elevated Sandbox 4 (#7889) --- codex-rs/Cargo.lock | 31 +- codex-rs/cli/src/debug_sandbox.rs | 34 +- codex-rs/core/src/config/mod.rs | 7 +- codex-rs/core/src/exec.rs | 33 +- codex-rs/core/src/features.rs | 8 + codex-rs/core/src/safety.rs | 22 + .../windows-sandbox-rs/src/elevated_impl.rs | 588 ++++++++++++++++++ codex-rs/windows-sandbox-rs/src/lib.rs | 67 +- codex-rs/windows-sandbox-rs/src/process.rs | 35 +- codex-rs/windows-sandbox-rs/src/winutil.rs | 42 ++ 10 files changed, 739 insertions(+), 128 deletions(-) create mode 100644 codex-rs/windows-sandbox-rs/src/elevated_impl.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index ec5911a4bd..1979b1fdaa 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1253,7 +1253,7 @@ dependencies = [ "allocative", "anyhow", "clap", - "derive_more 2.1.0", + "derive_more 2.0.1", "env_logger", "log", "multimap", @@ -1545,7 +1545,7 @@ dependencies = [ "codex-windows-sandbox", "color-eyre", "crossterm", - "derive_more 2.1.0", + "derive_more 2.0.1", "diffy", "dirs", "dunce", @@ -1614,7 +1614,7 @@ dependencies = [ "codex-windows-sandbox", "color-eyre", "crossterm", - "derive_more 2.1.0", + "derive_more 2.0.1", "diffy", "dirs", "dunce", @@ -1835,9 +1835,9 @@ dependencies = [ [[package]] name = "convert_case" -version = "0.10.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +checksum = "bb402b8d4c85569410425650ce3eddc7d698ed96d39a73f941b08fb63082f1e7" dependencies = [ "unicode-segmentation", ] @@ -2176,11 +2176,11 @@ dependencies = [ [[package]] name = "derive_more" -version = "2.1.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10b768e943bed7bf2cab53df09f4bc34bfd217cdb57d971e769874c9a6710618" +checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" dependencies = [ - "derive_more-impl 2.1.0", + "derive_more-impl 2.0.1", ] [[package]] @@ -2198,14 +2198,13 @@ dependencies = [ [[package]] name = "derive_more-impl" -version = "2.1.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d286bfdaf75e988b4a78e013ecd79c581e06399ab53fbacd2d916c2f904f30b" +checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ - "convert_case 0.10.0", + "convert_case 0.7.1", "proc-macro2", "quote", - "rustc_version", "syn 2.0.104", "unicode-xid", ] @@ -6989,9 +6988,9 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "ts-rs" -version = "11.1.0" +version = "11.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4994acea2522cd2b3b85c1d9529a55991e3ad5e25cdcd3de9d505972c4379424" +checksum = "6ef1b7a6d914a34127ed8e1fa927eb7088903787bcded4fa3eef8f85ee1568be" dependencies = [ "serde_json", "thiserror 2.0.17", @@ -7001,9 +7000,9 @@ dependencies = [ [[package]] name = "ts-rs-macros" -version = "11.1.0" +version = "11.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6ff59666c9cbaec3533964505d39154dc4e0a56151fdea30a09ed0301f62e2" +checksum = "e9d4ed7b4c18cc150a6a0a1e9ea1ecfa688791220781af6e119f9599a8502a0a" dependencies = [ "proc-macro2", "quote", diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 26fecd55c6..c298a3511a 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -136,7 +136,9 @@ async fn run_command_under_sandbox( if let SandboxType::Windows = sandbox_type { #[cfg(target_os = "windows")] { + use codex_core::features::Feature; use codex_windows_sandbox::run_windows_sandbox_capture; + use codex_windows_sandbox::run_windows_sandbox_capture_elevated; let policy_str = serde_json::to_string(&config.sandbox_policy)?; @@ -145,18 +147,32 @@ 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); // Preflight audit is invoked elsewhere at the appropriate times. let res = tokio::task::spawn_blocking(move || { - run_windows_sandbox_capture( - policy_str.as_str(), - &sandbox_cwd, - base_dir.as_path(), - command_vec, - &cwd_clone, - env_map, - None, - ) + if use_elevated { + run_windows_sandbox_capture_elevated( + policy_str.as_str(), + &sandbox_cwd, + base_dir.as_path(), + command_vec, + &cwd_clone, + env_map, + None, + ) + } else { + run_windows_sandbox_capture( + policy_str.as_str(), + &sandbox_cwd, + base_dir.as_path(), + command_vec, + &cwd_clone, + env_map, + None, + ) + } }) .await; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 584708156b..a6febb55c5 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -956,7 +956,12 @@ impl Config { let features = Features::from_config(&cfg, &config_profile, feature_overrides); #[cfg(target_os = "windows")] { - crate::safety::set_windows_sandbox_enabled(features.enabled(Feature::WindowsSandbox)); + // 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 = { diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 596f325059..da113ae42d 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -220,7 +220,9 @@ 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_windows_sandbox::run_windows_sandbox_capture; + use codex_windows_sandbox::run_windows_sandbox_capture_elevated; let ExecParams { command, @@ -244,16 +246,29 @@ async fn exec_windows_sandbox( "windows sandbox: failed to resolve codex_home: {err}" ))) })?; + let use_elevated = is_windows_elevated_sandbox_enabled(); let spawn_res = tokio::task::spawn_blocking(move || { - run_windows_sandbox_capture( - policy_str.as_str(), - &sandbox_cwd, - codex_home.as_ref(), - command, - &cwd, - env, - timeout_ms, - ) + if use_elevated { + run_windows_sandbox_capture_elevated( + policy_str.as_str(), + &sandbox_cwd, + codex_home.as_ref(), + command, + &cwd, + env, + timeout_ms, + ) + } else { + run_windows_sandbox_capture( + policy_str.as_str(), + &sandbox_cwd, + codex_home.as_ref(), + command, + &cwd, + env, + timeout_ms, + ) + } }) .await; diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index a011884fc4..20f405bf28 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -50,6 +50,8 @@ pub enum Feature { ExecPolicy, /// Enable Windows sandbox (restricted token) on Windows. WindowsSandbox, + /// Use the elevated Windows sandbox pipeline (setup + runner). + WindowsSandboxElevated, /// Remote compaction enabled (only for ChatGPT auth) RemoteCompaction, /// Refresh remote models and emit AppReady once the list is available. @@ -327,6 +329,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Experimental, default_enabled: false, }, + FeatureSpec { + id: Feature::WindowsSandboxElevated, + key: "enable_elevated_windows_sandbox", + stage: Stage::Experimental, + default_enabled: false, + }, FeatureSpec { id: Feature::RemoteCompaction, key: "remote_compaction", diff --git a/codex-rs/core/src/safety.rs b/codex-rs/core/src/safety.rs index e82e107453..8ab120ca60 100644 --- a/codex-rs/core/src/safety.rs +++ b/codex-rs/core/src/safety.rs @@ -18,6 +18,8 @@ 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) { @@ -28,6 +30,26 @@ pub fn set_windows_sandbox_enabled(enabled: bool) { #[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 +} + #[derive(Debug, PartialEq)] pub enum SafetyCheck { AutoApprove { diff --git a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs new file mode 100644 index 0000000000..b72ee75974 --- /dev/null +++ b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs @@ -0,0 +1,588 @@ +mod windows_impl { + use crate::acl::allow_null_device; + use crate::allow::compute_allow_paths; + use crate::allow::AllowDenyPaths; + use crate::cap::cap_sid_file; + use crate::cap::load_or_create_cap_sids; + use crate::env::ensure_non_interactive_pager; + use crate::env::inherit_path_env; + use crate::env::normalize_null_device_env; + use crate::identity::require_logon_sandbox_creds; + use crate::logging::debug_log; + use crate::logging::log_failure; + use crate::logging::log_note; + use crate::logging::log_start; + use crate::logging::log_success; + use crate::policy::parse_policy; + use crate::policy::SandboxPolicy; + use crate::token::convert_string_sid_to_sid; + use crate::winutil::format_last_error; + use crate::winutil::quote_windows_arg; + use crate::winutil::to_wide; + use anyhow::Result; + use rand::rngs::SmallRng; + use rand::Rng; + use rand::SeedableRng; + use std::collections::HashMap; + use std::ffi::c_void; + use std::fs; + use std::io; + use std::path::Path; + use std::path::PathBuf; + use std::ptr; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::Foundation::GetLastError; + use windows_sys::Win32::Foundation::HANDLE; + use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW; + use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR; + use windows_sys::Win32::Security::SECURITY_ATTRIBUTES; + use windows_sys::Win32::System::Diagnostics::Debug::SetErrorMode; + use windows_sys::Win32::System::Pipes::ConnectNamedPipe; + use windows_sys::Win32::System::Pipes::CreateNamedPipeW; + // PIPE_ACCESS_DUPLEX is 0x00000003; not exposed in windows-sys 0.52, so use the value directly. + const PIPE_ACCESS_DUPLEX: u32 = 0x0000_0003; + use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE; + use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE; + use windows_sys::Win32::System::Pipes::PIPE_WAIT; + use windows_sys::Win32::System::Threading::CreateProcessWithLogonW; + use windows_sys::Win32::System::Threading::GetExitCodeProcess; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + use windows_sys::Win32::System::Threading::INFINITE; + use windows_sys::Win32::System::Threading::LOGON_WITH_PROFILE; + use windows_sys::Win32::System::Threading::PROCESS_INFORMATION; + use windows_sys::Win32::System::Threading::STARTUPINFOW; + + /// Ensures the parent directory of a path exists before writing to it. + fn ensure_dir(p: &Path) -> Result<()> { + if let Some(d) = p.parent() { + std::fs::create_dir_all(d)?; + } + Ok(()) + } + + /// Walks upward from `start` to locate the git worktree root, following gitfile redirects. + fn find_git_root(start: &Path) -> Option { + let mut cur = dunce::canonicalize(start).ok()?; + loop { + let marker = cur.join(".git"); + if marker.is_dir() { + return Some(cur); + } + if marker.is_file() { + if let Ok(txt) = std::fs::read_to_string(&marker) { + if let Some(rest) = txt.trim().strip_prefix("gitdir:") { + let gitdir = rest.trim(); + let resolved = if Path::new(gitdir).is_absolute() { + PathBuf::from(gitdir) + } else { + cur.join(gitdir) + }; + return resolved.parent().map(|p| p.to_path_buf()).or(Some(cur)); + } + } + return Some(cur); + } + let parent = cur.parent()?; + if parent == cur { + return None; + } + cur = parent.to_path_buf(); + } + } + + /// Creates the sandbox user's Codex home directory if it does not already exist. + fn ensure_codex_home_exists(p: &Path) -> Result<()> { + std::fs::create_dir_all(p)?; + Ok(()) + } + + /// Adds a git safe.directory entry to the environment when running inside a repository. + /// git will not otherwise allow the Sandbox user to run git commands on the repo directory + /// which is owned by the primary user. + fn inject_git_safe_directory( + env_map: &mut HashMap, + cwd: &Path, + logs_base_dir: Option<&Path>, + ) { + if let Some(git_root) = find_git_root(cwd) { + let mut cfg_count: usize = env_map + .get("GIT_CONFIG_COUNT") + .and_then(|v| v.parse::().ok()) + .unwrap_or(0); + let git_path = git_root.to_string_lossy().replace("\\\\", "/"); + env_map.insert( + format!("GIT_CONFIG_KEY_{cfg_count}"), + "safe.directory".to_string(), + ); + env_map.insert(format!("GIT_CONFIG_VALUE_{cfg_count}"), git_path); + cfg_count += 1; + env_map.insert("GIT_CONFIG_COUNT".to_string(), cfg_count.to_string()); + log_note( + &format!("injected git safe.directory for {}", git_root.display()), + logs_base_dir, + ); + } + } + + /// Locates `codex-command-runner.exe` next to the current binary. + fn find_runner_exe() -> PathBuf { + if let Ok(exe) = std::env::current_exe() { + if let Some(dir) = exe.parent() { + let candidate = dir.join("codex-command-runner.exe"); + if candidate.exists() { + return candidate; + } + } + } + PathBuf::from("codex-command-runner.exe") + } + + /// Generates a unique named-pipe path used to communicate with the runner process. + fn pipe_name(suffix: &str) -> String { + let mut rng = SmallRng::from_entropy(); + format!(r"\\.\pipe\codex-runner-{:x}-{}", rng.gen::(), suffix) + } + + /// Creates a named pipe with permissive ACLs so the sandbox user can connect. + fn create_named_pipe(name: &str, access: u32) -> io::Result { + // Allow sandbox users to connect by granting Everyone full access on the pipe. + let sddl = to_wide("D:(A;;GA;;;WD)"); + let mut sd: PSECURITY_DESCRIPTOR = ptr::null_mut(); + let ok = unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl.as_ptr(), + 1, // SDDL_REVISION_1 + &mut sd, + ptr::null_mut(), + ) + }; + if ok == 0 { + return Err(io::Error::from_raw_os_error(unsafe { + GetLastError() as i32 + })); + } + let mut sa = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: sd, + bInheritHandle: 0, + }; + let wide = to_wide(name); + let h = unsafe { + CreateNamedPipeW( + wide.as_ptr(), + access, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + 1, + 65536, + 65536, + 0, + &mut sa as *mut SECURITY_ATTRIBUTES, + ) + }; + if h == 0 || h == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE { + return Err(io::Error::from_raw_os_error(unsafe { + GetLastError() as i32 + })); + } + Ok(h) + } + + /// Waits for a client connection on the named pipe, tolerating an existing connection. + fn connect_pipe(h: HANDLE) -> io::Result<()> { + let ok = unsafe { ConnectNamedPipe(h, ptr::null_mut()) }; + if ok == 0 { + let err = unsafe { GetLastError() }; + const ERROR_PIPE_CONNECTED: u32 = 535; + if err != ERROR_PIPE_CONNECTED { + return Err(io::Error::from_raw_os_error(err as i32)); + } + } + Ok(()) + } + + pub use crate::windows_impl::CaptureResult; + + #[derive(serde::Serialize)] + struct RunnerPayload { + policy_json_or_preset: String, + sandbox_policy_cwd: PathBuf, + // Writable log dir for sandbox user (.codex in sandbox profile). + codex_home: PathBuf, + // Real user's CODEX_HOME for shared data (caps, config). + real_codex_home: PathBuf, + cap_sid: String, + request_file: Option, + command: Vec, + cwd: PathBuf, + env_map: HashMap, + timeout_ms: Option, + stdin_pipe: String, + stdout_pipe: String, + stderr_pipe: String, + } + + /// Launches the command runner under the sandbox user and captures its output. + pub fn run_windows_sandbox_capture( + policy_json_or_preset: &str, + sandbox_policy_cwd: &Path, + codex_home: &Path, + command: Vec, + cwd: &Path, + mut env_map: HashMap, + timeout_ms: Option, + ) -> Result { + let policy = parse_policy(policy_json_or_preset)?; + normalize_null_device_env(&mut env_map); + ensure_non_interactive_pager(&mut env_map); + inherit_path_env(&mut env_map); + inject_git_safe_directory(&mut env_map, cwd, None); + let current_dir = cwd.to_path_buf(); + // Use a temp-based log dir that the sandbox user can write. + let sandbox_base = codex_home.join(".sandbox"); + ensure_codex_home_exists(&sandbox_base)?; + + let logs_base_dir: Option<&Path> = Some(sandbox_base.as_path()); + log_start(&command, logs_base_dir); + let sandbox_creds = + require_logon_sandbox_creds(&policy, sandbox_policy_cwd, cwd, &env_map, codex_home)?; + log_note("cli creds ready", logs_base_dir); + let cap_sid_path = cap_sid_file(codex_home); + + // Build capability SID for ACL grants. + let (psid_to_use, cap_sid_str) = match &policy { + SandboxPolicy::ReadOnly => { + let caps = load_or_create_cap_sids(codex_home); + ensure_dir(&cap_sid_path)?; + fs::write(&cap_sid_path, serde_json::to_string(&caps)?)?; + ( + unsafe { convert_string_sid_to_sid(&caps.readonly).unwrap() }, + caps.readonly.clone(), + ) + } + SandboxPolicy::WorkspaceWrite { .. } => { + let caps = load_or_create_cap_sids(codex_home); + ensure_dir(&cap_sid_path)?; + fs::write(&cap_sid_path, serde_json::to_string(&caps)?)?; + ( + unsafe { convert_string_sid_to_sid(&caps.workspace).unwrap() }, + caps.workspace.clone(), + ) + } + SandboxPolicy::DangerFullAccess => { + anyhow::bail!("DangerFullAccess is not supported for sandboxing") + } + }; + + let AllowDenyPaths { allow, deny } = + compute_allow_paths(&policy, sandbox_policy_cwd, ¤t_dir, &env_map); + // Deny/allow ACEs are now applied during setup; avoid per-command churn. + log_note( + &format!( + "cli skipping per-command ACL grants (allow_count={} deny_count={})", + allow.len(), + deny.len() + ), + logs_base_dir, + ); + unsafe { + allow_null_device(psid_to_use); + } + + // Prepare named pipes for runner. + let stdin_name = pipe_name("stdin"); + let stdout_name = pipe_name("stdout"); + let stderr_name = pipe_name("stderr"); + let h_stdin_pipe = create_named_pipe( + &stdin_name, + PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + )?; + let h_stdout_pipe = create_named_pipe( + &stdout_name, + PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + )?; + let h_stderr_pipe = create_named_pipe( + &stderr_name, + PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, + )?; + log_note( + &format!( + "cli pipes created stdin={} stdout={} stderr={}", + stdin_name, stdout_name, stderr_name + ), + logs_base_dir, + ); + + // Launch runner as sandbox user via CreateProcessWithLogonW. + let runner_exe = find_runner_exe(); + let runner_cmdline = runner_exe + .to_str() + .map(|s| s.to_string()) + .unwrap_or_else(|| "codex-command-runner.exe".to_string()); + // Write request to a file under the sandbox base dir for the runner to read. + // TODO(iceweasel) - use a different mechanism for invoking the runner. + let base_tmp = sandbox_base.join("requests"); + std::fs::create_dir_all(&base_tmp)?; + let mut rng = SmallRng::from_entropy(); + let req_file = base_tmp.join(format!("request-{:x}.json", rng.gen::())); + let payload = RunnerPayload { + policy_json_or_preset: policy_json_or_preset.to_string(), + sandbox_policy_cwd: sandbox_policy_cwd.to_path_buf(), + codex_home: sandbox_base.clone(), + real_codex_home: codex_home.to_path_buf(), + cap_sid: cap_sid_str.clone(), + request_file: Some(req_file.clone()), + command: command.clone(), + cwd: cwd.to_path_buf(), + env_map: env_map.clone(), + timeout_ms, + stdin_pipe: stdin_name.clone(), + stdout_pipe: stdout_name.clone(), + stderr_pipe: stderr_name.clone(), + }; + let payload_json = serde_json::to_string(&payload)?; + if let Err(e) = fs::write(&req_file, &payload_json) { + log_note( + &format!("error writing request file {}: {}", req_file.display(), e), + logs_base_dir, + ); + return Err(e.into()); + } + log_note( + &format!("cli request file written path={}", req_file.display()), + logs_base_dir, + ); + let runner_full_cmd = format!( + "{} {}", + quote_windows_arg(&runner_cmdline), + quote_windows_arg(&format!("--request-file={}", req_file.display())) + ); + let mut cmdline_vec: Vec = to_wide(&runner_full_cmd); + let exe_w: Vec = to_wide(&runner_cmdline); + let cwd_w: Vec = to_wide(cwd); + log_note( + &format!("cli prep done request_file={}", req_file.display()), + logs_base_dir, + ); + log_note( + &format!("cli about to launch runner cmd={}", runner_full_cmd), + logs_base_dir, + ); + + // Minimal CPWL launch: inherit env, no desktop override, no handle inheritance. + let env_block: Option> = None; + let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() }; + si.cb = std::mem::size_of::() as u32; + let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; + let user_w = to_wide(&sandbox_creds.username); + let domain_w = to_wide("."); + let password_w = to_wide(&sandbox_creds.password); + // Suppress WER/UI popups from the runner process so we can collect exit codes. + let _ = unsafe { SetErrorMode(0x0001 | 0x0002) }; // SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX + + // Ensure command line buffer is mutable and includes the exe as argv[0]. + let spawn_res = unsafe { + CreateProcessWithLogonW( + user_w.as_ptr(), + domain_w.as_ptr(), + password_w.as_ptr(), + LOGON_WITH_PROFILE, + exe_w.as_ptr(), + cmdline_vec.as_mut_ptr(), + windows_sys::Win32::System::Threading::CREATE_NO_WINDOW + | windows_sys::Win32::System::Threading::CREATE_UNICODE_ENVIRONMENT, + env_block + .as_ref() + .map(|b| b.as_ptr() as *const c_void) + .unwrap_or(ptr::null()), + cwd_w.as_ptr(), + &si, + &mut pi, + ) + }; + if spawn_res == 0 { + let err = unsafe { GetLastError() } as i32; + let dbg = format!( + "CreateProcessWithLogonW failed: {} ({}) | cwd={} | cmd={} | req_file={} | env=inherit | si_flags={}", + err, + format_last_error(err), + cwd.display(), + runner_full_cmd, + req_file.display(), + si.dwFlags, + ); + debug_log(&dbg, logs_base_dir); + log_note(&dbg, logs_base_dir); + return Err(anyhow::anyhow!("CreateProcessWithLogonW failed: {}", err)); + } + log_note( + &format!("cli runner launched pid={}", pi.hProcess), + logs_base_dir, + ); + + // Pipes are no longer passed as std handles; no stdin payload is sent. + connect_pipe(h_stdin_pipe)?; + connect_pipe(h_stdout_pipe)?; + connect_pipe(h_stderr_pipe)?; + unsafe { + CloseHandle(h_stdin_pipe); + } + + // Read stdout/stderr. + let (tx_out, rx_out) = std::sync::mpsc::channel::>(); + let (tx_err, rx_err) = std::sync::mpsc::channel::>(); + let t_out = std::thread::spawn(move || { + let mut buf = Vec::new(); + let mut tmp = [0u8; 8192]; + loop { + let mut read_bytes: u32 = 0; + let ok = unsafe { + windows_sys::Win32::Storage::FileSystem::ReadFile( + h_stdout_pipe, + tmp.as_mut_ptr(), + tmp.len() as u32, + &mut read_bytes, + std::ptr::null_mut(), + ) + }; + if ok == 0 || read_bytes == 0 { + break; + } + buf.extend_from_slice(&tmp[..read_bytes as usize]); + } + let _ = tx_out.send(buf); + }); + let t_err = std::thread::spawn(move || { + let mut buf = Vec::new(); + let mut tmp = [0u8; 8192]; + loop { + let mut read_bytes: u32 = 0; + let ok = unsafe { + windows_sys::Win32::Storage::FileSystem::ReadFile( + h_stderr_pipe, + tmp.as_mut_ptr(), + tmp.len() as u32, + &mut read_bytes, + std::ptr::null_mut(), + ) + }; + if ok == 0 || read_bytes == 0 { + break; + } + buf.extend_from_slice(&tmp[..read_bytes as usize]); + } + let _ = tx_err.send(buf); + }); + + let timeout = timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE); + let res = unsafe { WaitForSingleObject(pi.hProcess, timeout) }; + let timed_out = res == 0x0000_0102; + let mut exit_code_u32: u32 = 1; + if !timed_out { + unsafe { + GetExitCodeProcess(pi.hProcess, &mut exit_code_u32); + } + } else { + unsafe { + windows_sys::Win32::System::Threading::TerminateProcess(pi.hProcess, 1); + } + } + + unsafe { + if pi.hThread != 0 { + CloseHandle(pi.hThread); + } + if pi.hProcess != 0 { + CloseHandle(pi.hProcess); + } + CloseHandle(h_stdout_pipe); + CloseHandle(h_stderr_pipe); + } + let _ = t_out.join(); + let _ = t_err.join(); + let stdout = rx_out.recv().unwrap_or_default(); + let stderr = rx_err.recv().unwrap_or_default(); + let exit_code = if timed_out { + 128 + 64 + } else { + exit_code_u32 as i32 + }; + + if exit_code == 0 { + log_success(&command, logs_base_dir); + } else { + log_failure(&command, &format!("exit code {}", exit_code), logs_base_dir); + } + + Ok(CaptureResult { + exit_code, + stdout, + stderr, + timed_out, + }) + } + + #[cfg(test)] + mod tests { + use crate::policy::SandboxPolicy; + + fn workspace_policy(network_access: bool) -> SandboxPolicy { + SandboxPolicy::WorkspaceWrite { + writable_roots: Vec::new(), + network_access, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + } + } + + #[test] + fn applies_network_block_when_access_is_disabled() { + assert!(!workspace_policy(false).has_full_network_access()); + } + + #[test] + fn skips_network_block_when_access_is_allowed() { + assert!(workspace_policy(true).has_full_network_access()); + } + + #[test] + fn applies_network_block_for_read_only() { + assert!(!SandboxPolicy::ReadOnly.has_full_network_access()); + } + } +} + +#[cfg(target_os = "windows")] +pub use windows_impl::run_windows_sandbox_capture; + +#[cfg(not(target_os = "windows"))] +mod stub { + use anyhow::bail; + use anyhow::Result; + use codex_protocol::protocol::SandboxPolicy; + use std::collections::HashMap; + use std::path::Path; + + #[derive(Debug, Default)] + pub struct CaptureResult { + pub exit_code: i32, + pub stdout: Vec, + pub stderr: Vec, + pub timed_out: bool, + } + + /// Stub implementation for non-Windows targets; sandboxing only works on Windows. + pub fn run_windows_sandbox_capture( + _policy_json_or_preset: &str, + _sandbox_policy_cwd: &Path, + _codex_home: &Path, + _command: Vec, + _cwd: &Path, + _env_map: HashMap, + _timeout_ms: Option, + ) -> Result { + bail!("Windows sandbox is only available on Windows") + } +} + +#[cfg(not(target_os = "windows"))] +pub use stub::run_windows_sandbox_capture; diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index c4367e6124..1bcfa12074 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -12,6 +12,9 @@ windows_modules!( #[path = "setup_orchestrator.rs"] mod setup; +#[cfg(target_os = "windows")] +mod elevated_impl; + #[cfg(target_os = "windows")] pub use acl::allow_null_device; #[cfg(target_os = "windows")] @@ -29,6 +32,8 @@ pub use dpapi::protect as dpapi_protect; #[cfg(target_os = "windows")] pub use dpapi::unprotect as dpapi_unprotect; #[cfg(target_os = "windows")] +pub use elevated_impl::run_windows_sandbox_capture as run_windows_sandbox_capture_elevated; +#[cfg(target_os = "windows")] pub use identity::require_logon_sandbox_creds; #[cfg(target_os = "windows")] pub use logging::log_note; @@ -91,8 +96,10 @@ mod windows_impl { use super::logging::log_success; use super::policy::parse_policy; use super::policy::SandboxPolicy; + use super::process::make_env_block; use super::token::convert_string_sid_to_sid; use super::winutil::format_last_error; + use super::winutil::quote_windows_arg; use super::winutil::to_wide; use anyhow::Result; use std::collections::HashMap; @@ -135,66 +142,6 @@ mod windows_impl { Ok(()) } - fn make_env_block(env: &HashMap) -> Vec { - let mut items: Vec<(String, String)> = - env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); - items.sort_by(|a, b| { - a.0.to_uppercase() - .cmp(&b.0.to_uppercase()) - .then(a.0.cmp(&b.0)) - }); - let mut w: Vec = Vec::new(); - for (k, v) in items { - let mut s = to_wide(format!("{}={}", k, v)); - s.pop(); - w.extend_from_slice(&s); - w.push(0); - } - w.push(0); - w - } - - // Quote a single Windows command-line argument following the rules used by - // CommandLineToArgvW/CRT so that spaces, quotes, and backslashes are preserved. - // Reference behavior matches Rust std::process::Command on Windows. - fn quote_windows_arg(arg: &str) -> String { - let needs_quotes = arg.is_empty() - || arg - .chars() - .any(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '"')); - if !needs_quotes { - return arg.to_string(); - } - - let mut quoted = String::with_capacity(arg.len() + 2); - quoted.push('"'); - let mut backslashes = 0; - for ch in arg.chars() { - match ch { - '\\' => { - backslashes += 1; - } - '"' => { - quoted.push_str(&"\\".repeat(backslashes * 2 + 1)); - quoted.push('"'); - backslashes = 0; - } - _ => { - if backslashes > 0 { - quoted.push_str(&"\\".repeat(backslashes)); - backslashes = 0; - } - quoted.push(ch); - } - } - } - if backslashes > 0 { - quoted.push_str(&"\\".repeat(backslashes * 2)); - } - quoted.push('"'); - quoted - } - unsafe fn setup_stdio_pipes() -> io::Result { let mut in_r: HANDLE = 0; let mut in_w: HANDLE = 0; diff --git a/codex-rs/windows-sandbox-rs/src/process.rs b/codex-rs/windows-sandbox-rs/src/process.rs index 978dcfe60a..786fe416a4 100644 --- a/codex-rs/windows-sandbox-rs/src/process.rs +++ b/codex-rs/windows-sandbox-rs/src/process.rs @@ -1,5 +1,6 @@ use crate::logging; use crate::winutil::format_last_error; +use crate::winutil::quote_windows_arg; use crate::winutil::to_wide; use anyhow::anyhow; use anyhow::Result; @@ -50,38 +51,6 @@ pub fn make_env_block(env: &HashMap) -> Vec { w } -#[allow(dead_code)] -fn quote_arg(a: &str) -> String { - let needs_quote = a.is_empty() || a.chars().any(|ch| ch.is_whitespace() || ch == '"'); - if !needs_quote { - return a.to_string(); - } - let mut out = String::from("\""); - let mut bs: usize = 0; - for ch in a.chars() { - if (ch as u32) == 92 { - bs += 1; - continue; - } - if ch == '"' { - out.push_str(&"\\".repeat(bs * 2 + 1)); - out.push('"'); - bs = 0; - continue; - } - if bs > 0 { - out.push_str(&"\\".repeat(bs * 2)); - bs = 0; - } - out.push(ch); - } - if bs > 0 { - out.push_str(&"\\".repeat(bs * 2)); - } - out.push('"'); - out -} - #[allow(dead_code)] unsafe fn ensure_inheritable_stdio(si: &mut STARTUPINFOW) -> Result<()> { for kind in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] { @@ -114,7 +83,7 @@ pub unsafe fn create_process_as_user( ) -> Result<(PROCESS_INFORMATION, STARTUPINFOW)> { let cmdline_str = argv .iter() - .map(|a| quote_arg(a)) + .map(|a| quote_windows_arg(a)) .collect::>() .join(" "); let mut cmdline: Vec = to_wide(&cmdline_str); diff --git a/codex-rs/windows-sandbox-rs/src/winutil.rs b/codex-rs/windows-sandbox-rs/src/winutil.rs index a819561261..02f7a8cce3 100644 --- a/codex-rs/windows-sandbox-rs/src/winutil.rs +++ b/codex-rs/windows-sandbox-rs/src/winutil.rs @@ -14,6 +14,48 @@ pub fn to_wide>(s: S) -> Vec { v } +/// Quote a single Windows command-line argument following the rules used by +/// CommandLineToArgvW/CRT so that spaces, quotes, and backslashes are preserved. +/// Reference behavior matches Rust std::process::Command on Windows. +#[cfg(target_os = "windows")] +pub fn quote_windows_arg(arg: &str) -> String { + let needs_quotes = arg.is_empty() + || arg + .chars() + .any(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '"')); + if !needs_quotes { + return arg.to_string(); + } + + let mut quoted = String::with_capacity(arg.len() + 2); + quoted.push('"'); + let mut backslashes = 0; + for ch in arg.chars() { + match ch { + '\\' => { + backslashes += 1; + } + '"' => { + quoted.push_str(&"\\".repeat(backslashes * 2 + 1)); + quoted.push('"'); + backslashes = 0; + } + _ => { + if backslashes > 0 { + quoted.push_str(&"\\".repeat(backslashes)); + backslashes = 0; + } + quoted.push(ch); + } + } + } + if backslashes > 0 { + quoted.push_str(&"\\".repeat(backslashes * 2)); + } + quoted.push('"'); + quoted +} + // Produce a readable description for a Win32 error code. pub fn format_last_error(err: i32) -> String { unsafe { From 26d0d822a2fcff0975f6ca244632671993e3cfa1 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Fri, 12 Dec 2025 12:50:49 -0800 Subject: [PATCH 31/77] chore(prompt) Update base prompt (#7943) ## Summary Update base prompt --- codex-rs/core/prompt.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/prompt.md b/codex-rs/core/prompt.md index e4590c386d..d8bebc371b 100644 --- a/codex-rs/core/prompt.md +++ b/codex-rs/core/prompt.md @@ -297,7 +297,7 @@ For casual greetings, acknowledgements, or other one-off conversational messages When using the shell, you must adhere to the following guidelines: - When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.) -- Read files in chunks with a max chunk size of 250 lines. Do not use python scripts to attempt to output larger chunks of a file. Command line output will be truncated after 10 kilobytes or 256 lines of output, regardless of the command used. +- Do not use python scripts to attempt to output larger chunks of a file. ## `update_plan` From 9009490357fc3843c14cab1c3e0132acc70487ed Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 12 Dec 2025 13:06:49 -0800 Subject: [PATCH 32/77] fix: use PowerShell to parse PowerShell (#7607) Previous to this PR, we used a hand-rolled PowerShell parser in `windows_safe_commands.rs` to take a `&str` of PowerShell script see if it is equivalent to a list of `execvp(3)` invocations, and if so, we then test each using `is_safe_powershell_command()` to determine if the overall command is safe: https://github.com/openai/codex/blob/6e6338aa876bb4258abe25b02ac6417b8ea9dff0/codex-rs/core/src/command_safety/windows_safe_commands.rs#L89-L98 Unfortunately, our PowerShell parser did not recognize `@(...)` as a special construct, so it was treated as an ordinary token. This meant that the following would erroneously be considered "safe:" ```powershell ls @(calc.exe) ``` The fix introduced in this PR is to do something comparable what we do for Bash/Zsh, which is to use a "proper" parser to derive the list of `execvp(3)` calls. For Bash/Zsh, we rely on https://crates.io/crates/tree-sitter-bash, but there does not appear to be a crate of comparable quality for parsing PowerShell statically (https://github.com/airbus-cert/tree-sitter-powershell/ is the best thing I found). Instead, in this PR, we use a PowerShell script to parse the input PowerShell program to produce the AST. --- .../src/command_safety/powershell_parser.ps1 | 201 +++++++++ .../command_safety/windows_safe_commands.rs | 388 +++++++++++++----- codex-rs/core/src/powershell.rs | 10 +- codex-rs/core/src/tools/handlers/shell.rs | 25 +- 4 files changed, 501 insertions(+), 123 deletions(-) create mode 100644 codex-rs/core/src/command_safety/powershell_parser.ps1 diff --git a/codex-rs/core/src/command_safety/powershell_parser.ps1 b/codex-rs/core/src/command_safety/powershell_parser.ps1 new file mode 100644 index 0000000000..af71cb7f34 --- /dev/null +++ b/codex-rs/core/src/command_safety/powershell_parser.ps1 @@ -0,0 +1,201 @@ +$ErrorActionPreference = 'Stop' + +$payload = $env:CODEX_POWERSHELL_PAYLOAD +if ([string]::IsNullOrEmpty($payload)) { + Write-Output '{"status":"parse_failed"}' + exit 0 +} + +try { + $source = + [System.Text.Encoding]::Unicode.GetString( + [System.Convert]::FromBase64String($payload) + ) +} catch { + Write-Output '{"status":"parse_failed"}' + exit 0 +} + +$tokens = $null +$errors = $null + +$ast = $null +try { + $ast = [System.Management.Automation.Language.Parser]::ParseInput( + $source, + [ref]$tokens, + [ref]$errors + ) +} catch { + Write-Output '{"status":"parse_failed"}' + exit 0 +} + +if ($errors.Count -gt 0) { + Write-Output '{"status":"parse_errors"}' + exit 0 +} + +function Convert-CommandElement { + param($element) + + if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) { + return @($element.Value) + } + + if ($element -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) { + if ($element.NestedExpressions.Count -gt 0) { + return $null + } + return @($element.Value) + } + + if ($element -is [System.Management.Automation.Language.ConstantExpressionAst]) { + return @($element.Value.ToString()) + } + + if ($element -is [System.Management.Automation.Language.CommandParameterAst]) { + if ($element.Argument -eq $null) { + return @('-' + $element.ParameterName) + } + + if ($element.Argument -is [System.Management.Automation.Language.StringConstantExpressionAst]) { + return @('-' + $element.ParameterName, $element.Argument.Value) + } + + if ($element.Argument -is [System.Management.Automation.Language.ConstantExpressionAst]) { + return @('-' + $element.ParameterName, $element.Argument.Value.ToString()) + } + + return $null + } + + return $null +} + +function Convert-PipelineElement { + param($element) + + if ($element -is [System.Management.Automation.Language.CommandAst]) { + if ($element.Redirections.Count -gt 0) { + return $null + } + + if ( + $element.InvocationOperator -ne $null -and + $element.InvocationOperator -ne [System.Management.Automation.Language.TokenKind]::Unknown + ) { + return $null + } + + $parts = @() + foreach ($commandElement in $element.CommandElements) { + $converted = Convert-CommandElement $commandElement + if ($converted -eq $null) { + return $null + } + $parts += $converted + } + return $parts + } + + if ($element -is [System.Management.Automation.Language.CommandExpressionAst]) { + if ($element.Redirections.Count -gt 0) { + return $null + } + + if ($element.Expression -is [System.Management.Automation.Language.ParenExpressionAst]) { + $innerPipeline = $element.Expression.Pipeline + if ($innerPipeline -and $innerPipeline.PipelineElements.Count -eq 1) { + return Convert-PipelineElement $innerPipeline.PipelineElements[0] + } + } + + return $null + } + + return $null +} + +function Add-CommandsFromPipelineAst { + param($pipeline, $commands) + + if ($pipeline.PipelineElements.Count -eq 0) { + return $false + } + + foreach ($element in $pipeline.PipelineElements) { + $words = Convert-PipelineElement $element + if ($words -eq $null -or $words.Count -eq 0) { + return $false + } + $null = $commands.Add($words) + } + + return $true +} + +function Add-CommandsFromPipelineChain { + param($chain, $commands) + + if (-not (Add-CommandsFromPipelineBase $chain.LhsPipelineChain $commands)) { + return $false + } + + if (-not (Add-CommandsFromPipelineAst $chain.RhsPipeline $commands)) { + return $false + } + + return $true +} + +function Add-CommandsFromPipelineBase { + param($pipeline, $commands) + + if ($pipeline -is [System.Management.Automation.Language.PipelineAst]) { + return Add-CommandsFromPipelineAst $pipeline $commands + } + + if ($pipeline -is [System.Management.Automation.Language.PipelineChainAst]) { + return Add-CommandsFromPipelineChain $pipeline $commands + } + + return $false +} + +$commands = [System.Collections.ArrayList]::new() + +foreach ($statement in $ast.EndBlock.Statements) { + if (-not (Add-CommandsFromPipelineBase $statement $commands)) { + $commands = $null + break + } +} + +if ($commands -ne $null) { + $normalized = [System.Collections.ArrayList]::new() + foreach ($cmd in $commands) { + if ($cmd -is [string]) { + $null = $normalized.Add(@($cmd)) + continue + } + + if ($cmd -is [System.Array] -or $cmd -is [System.Collections.IEnumerable]) { + $null = $normalized.Add(@($cmd)) + continue + } + + $normalized = $null + break + } + + $commands = $normalized +} + +$result = if ($commands -eq $null) { + @{ status = 'unsupported' } +} else { + @{ status = 'ok'; commands = $commands } +} + +,$result | ConvertTo-Json -Depth 3 diff --git a/codex-rs/core/src/command_safety/windows_safe_commands.rs b/codex-rs/core/src/command_safety/windows_safe_commands.rs index a1d3b297f9..ac479a4d2c 100644 --- a/codex-rs/core/src/command_safety/windows_safe_commands.rs +++ b/codex-rs/core/src/command_safety/windows_safe_commands.rs @@ -1,30 +1,38 @@ -use shlex::split as shlex_split; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; +use serde::Deserialize; use std::path::Path; +use std::process::Command; +use std::sync::LazyLock; + +const POWERSHELL_PARSER_SCRIPT: &str = include_str!("powershell_parser.ps1"); /// On Windows, we conservatively allow only clearly read-only PowerShell invocations /// that match a small safelist. Anything else (including direct CMD commands) is unsafe. pub fn is_safe_command_windows(command: &[String]) -> bool { if let Some(commands) = try_parse_powershell_command_sequence(command) { - return commands + commands .iter() - .all(|cmd| is_safe_powershell_command(cmd.as_slice())); + .all(|cmd| is_safe_powershell_command(cmd.as_slice())) + } else { + // Only PowerShell invocations are allowed on Windows for now; anything else is unsafe. + false } - // Only PowerShell invocations are allowed on Windows for now; anything else is unsafe. - false } /// Returns each command sequence if the invocation starts with a PowerShell binary. /// For example, the tokens from `pwsh Get-ChildItem | Measure-Object` become two sequences. fn try_parse_powershell_command_sequence(command: &[String]) -> Option>> { let (exe, rest) = command.split_first()?; - if !is_powershell_executable(exe) { - return None; + if is_powershell_executable(exe) { + parse_powershell_invocation(exe, rest) + } else { + None } - parse_powershell_invocation(rest) } /// Parses a PowerShell invocation into discrete command vectors, rejecting unsafe patterns. -fn parse_powershell_invocation(args: &[String]) -> Option>> { +fn parse_powershell_invocation(executable: &str, args: &[String]) -> Option>> { if args.is_empty() { // Examples rejected here: "pwsh" and "powershell.exe" with no additional arguments. return None; @@ -42,7 +50,7 @@ fn parse_powershell_invocation(args: &[String]) -> Option>> { // Examples rejected here: "pwsh -Command foo bar" and "powershell -c ls extra". return None; } - return parse_powershell_script(script); + return parse_powershell_script(executable, script); } _ if lower.starts_with("-command:") || lower.starts_with("/command:") => { if idx + 1 != args.len() { @@ -51,7 +59,7 @@ fn parse_powershell_invocation(args: &[String]) -> Option>> { return None; } let script = arg.split_once(':')?.1; - return parse_powershell_script(script); + return parse_powershell_script(executable, script); } // Benign, no-arg flags we tolerate. @@ -77,7 +85,8 @@ fn parse_powershell_invocation(args: &[String]) -> Option>> { // This happens if powershell is invoked without -Command, e.g. // ["pwsh", "-NoLogo", "git", "-c", "core.pager=cat", "status"] _ => { - return split_into_commands(args[idx..].to_vec()); + let script = join_arguments_as_script(&args[idx..]); + return parse_powershell_script(executable, &script); } } } @@ -88,46 +97,14 @@ fn parse_powershell_invocation(args: &[String]) -> Option>> { /// Tokenizes an inline PowerShell script and delegates to the command splitter. /// Examples of when this is called: pwsh.exe -Command '