Skip to content

fix: expose codex apply_patch for local models (#9114) - #9121

Merged
mahiatlinux merged 17 commits into
unslothai:mainfrom
Biotrioo:fix/issue-9114
Aug 30, 2026
Merged

mahiatlinux merged 17 commits into
unslothai:mainfrom
Biotrioo:fix/issue-9114

Conversation

@Biotrioo

Copy link
Copy Markdown
Contributor

Summary

Fixes #9114 by exposing Codex's native apply_patch tool for Unsloth-served local models.

Root cause

The generated Codex model catalog set apply_patch_tool_type to None, so Codex did not register the native editing tool.

Validation

  • Direct syntax and catalog contract checks passed.
  • git diff --check passed.
  • The focused pytest could not run in the available runtime because pytest is not installed.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6b1441135b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth_cli/commands/start.py Outdated
"support_verbosity": False,
"default_verbosity": None,
"apply_patch_tool_type": None,
"apply_patch_tool_type": "function",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate the unsupported function apply-patch variant

Codex 0.144.0-alpha.4, which _codex_supports_model_catalog() accepts as newer than 0.110.0, rejects the generated catalog before launching with unknown variant 'function', expected 'freeform'. Consequently, users on this supported Codex version cannot start any Unsloth Codex session after the catalog is regenerated; use the recognized freeform value or raise the version gate to the first Codex release that accepts function.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. The catalog now emits freeform, and focused compatibility tests execute the native tool through Codex 0.147.0, 0.148.0, and 0.151.0.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the catalog in unsloth_cli/commands/start.py still emits apply_patch_tool_type as None, so local models launched through unsloth codex never get the native editing tool, and the one-line flip plus the assertion in unsloth_cli/tests/test_start.py is the right fix. Could you drop the unrelated reformatting in the three test files so this stays to the catalog change?

@mahiatlinux

Copy link
Copy Markdown
Contributor

unsloth_cli/commands/start.py:2483: "function" is not an accepted apply_patch_tool_type, and Codex refuses to start

ApplyPatchToolType lost its Function variant in openai/codex rust-v0.131.0. At rust-v0.147.0, the version in #9114, and on every release since, codex-rs/protocol/src/openai_models.rs reads:

#[serde(rename_all = "snake_case")]
pub enum ApplyPatchToolType {
    Freeform,
}

The field is Option<ApplyPatchToolType> with no serde(other) and no alias, and load_catalog_json in codex-rs/core/src/config/mod.rs propagates the serde error out of config load. An unrecognised value is not skipped per model, it fails the whole file.

codex-cli 0.147.0 run against the model-catalog.json that write_codex_config writes:

Error: failed to parse model_catalog_json path `$CODEX_HOME/model-catalog.json` as JSON:
unknown variant `function`, expected `freeform` at line 28 column 5

Exit before the TUI opens. unsloth codex goes from "apply_patch missing from the tool list" to "will not launch", for everyone, not just the reporter. There is no override: the literal is hardcoded and _codex_supports_model_catalog() passes for every Codex at or above 0.110.0 plus every machine with no Codex on PATH, so --no-launch recipes and the subagent child home at start.py:2535 get the same catalog.

_CODEX_MODEL_CATALOG_MIN_VERSION = (0, 110, 0) at start.py:2439 admits 0.110.0 upward. "function" parses only on 0.110.x through 0.130.x. "freeform" parses across the whole gated range and is the value every entry in Codex's own models-manager/models.json carries.

Write "apply_patch_tool_type": "freeform",.

studio/backend/routes/inference.py:17441: the freeform tool is dropped before it reaches the model, so the corrected value still does not close #9114

With "freeform" the catalog parses and Codex registers the tool. Captured POST /v1/responses from codex-cli 0.147.0 against a catalog generated by write_codex_config:

apply_patch_tool_type tools in the request
null (main today) exec_command, write_stdin, update_plan, request_user_input, view_image, ... no apply_patch
"freeform" same list plus apply_patch, as {"type": "custom", "format": {"type": "grammar", "syntax": "lark", ...}}
"function" (this PR) no request, config load dies first

unsloth codex points Codex at Studio's /v1/responses (start.py writes wire_api = "responses" against the Studio base URL). That endpoint converts to a ChatCompletionRequest through _build_chat_request on both paths (inference.py:17980 non-streaming, inference.py:18138 streaming), and _translate_responses_tools_to_chat forwards function tools only:

if tool.get("type") != "function":
    continue

models/inference.py:2352-2360 documents the same: other tool types "are accepted for SDK compatibility but ignored on the llama-server passthrough". Nothing under studio/ handles apply_patch or the patch envelope.

llama-server drops it a second time even if Studio forwarded it. tools/server/server-chat.cpp:261-263 in ggml-org/llama.cpp:

if (type != "function") {
    SRV_WRN("unsupported Responses tool type '%s' skipped\n", type.c_str());

So the Lark grammar is never read, the tool never enters the templated prompt, and the model's actual tool list, which is what #9114 is about, is unchanged.

Closing #9114 needs the translator to carry the freeform tool through, or a deliberate decision to keep local models on the shell-intercept path. A catalog constant cannot do it at any value.

unsloth_cli/codex_fallback_prompt.md:132: the only patching instruction the model gets describes a call no tool in the request accepts

Line 132, pinned as base_instructions at start.py:2478:

- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {"command":["apply_patch","*** Begin Patch\n...*** End Patch"]}

The file is delivered verbatim as the request's instructions (20750 bytes, byte-identical to the vendored file). The tools that arrive alongside it, captured from codex-cli 0.147.0 on this catalog, take these parameters:

exec_command       cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms
write_stdin        chars, max_output_tokens, session_id, yield_time_ms
update_plan        explanation, plan
request_user_input questions
view_image         path

None accepts command; the shell tool here is exec_command, which takes cmd. So on main today the model's one patching instruction describes a call it cannot make, which is a plausible driver of the symptom in #9114, "the system prompt mentions it, but it's not in my actual tool list", and it is independent of the catalog value.

Setting the field does not resolve it, it adds a contradiction. The description Codex sends with the freeform tool is:

The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.

The model would receive both strings. This is not vendor drift: the file matches models-manager/prompt.md at 0.144.0 and 0.147.0, and upstream pairs that prompt with apply_patch_tool_type: None in its own unknown-model fallback (models-manager/src/model_info.rs). The prompt upstream pairs with freeform, carried by gpt-5.2 in models-manager/models.json, replaces the JSON example with that same sentence.

start.py:2436 states the intent to keep this metadata aligned with Codex's unknown-model fallback. The prompt and the tool type are one pair upstream, so both have to move together. start.py:219 already ships tool-call healing because small GGUFs emit malformed calls; handing one contradictory instructions about a grammar-constrained format makes that worse.

unsloth_cli/tests/test_start.py:857: the test pins the value Codex rejects

assert catalog["models"][0]["apply_patch_tool_type"] == "function"

The assertion restates the literal written at start.py:2483, with no reference to Codex's schema, so it passes on a catalog Codex cannot load. Nothing else in the suite checks the catalog against Codex's types: the codex tests in this file mock _codex_supports_model_catalog and never invoke a real binary. That is the gap that let an invalid value through.

Point it at "freeform", and assert against the set of values Codex accepts rather than a bare literal, since upstream has already narrowed this field once. A check that the generated catalog actually parses with the installed Codex would catch the whole class.

@mahiatlinux
mahiatlinux self-requested a review August 19, 2026 09:46

@mahiatlinux mahiatlinux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review posted as a comment above.

@mahiatlinux

Copy link
Copy Markdown
Contributor

Reviewed and extended this beyond the catalog literal. The original issue is real, but the original fix was incomplete and used a value that current Codex rejects.

Before and after

Before this PR, write_codex_config() generated apply_patch_tool_type: null. Codex therefore omitted apply_patch from /v1/responses, even though the fallback prompt mentioned it. This reproduces #9114.

The PR originally changed the value to "function". Codex 0.131.0 and newer reject that catalog at startup with unknown variant 'function', expected 'freeform'. Changing only the value to "freeform" makes Codex send a native custom grammar tool, but Studio and llama.cpp previously dropped every non-function Responses tool before the local model saw it.

The final implementation now:

  • emits Codex's supported "freeform" catalog value
  • preserves Codex's Lark patch grammar and adds a valid patch example for small local models
  • translates only the validated native apply_patch custom tool to llama.cpp's function-tool shape
  • converts the model result back to a native Responses custom_tool_call, including streaming
  • preserves custom_tool_call and custom_tool_call_output on later turns
  • leaves unsupported custom tools ignored, matching the old local-server behavior
  • translates a forced custom tool_choice only when the matching validated tool exists
  • enables Codex's apply_patch_freeform line-ending preservation from 0.148.0, the release where the feature was added

End-to-end verification

I ran Codex 0.151.0 against an actual Unsloth Studio server using unsloth/gemma-4-E2B-it-GGUF, gemma-4-E2B-it-UD-Q4_K_XL.gguf, on CPU. Codex received a native custom apply_patch tool, the local model selected it, Codex executed it, and Studio received custom_tool_call_output on the next Responses request. This was execution through Codex, not a catalog-only assertion.

Successful operations covered create, modify, two hunks in one file, delete, nested paths, spaces in paths, Unicode names and content, LF, and CRLF. Missing-context and malformed patches failed without changing the target. A workspace-write attempt outside the working tree did not create the sentinel. Existing exec_command remained present and executed successfully.

The first real Gemma attempt produced an invalid hunk and Codex rejected it. That exposed the missing patch-format guidance and led to the grammar-preserving function bridge plus valid example. A Qwen2.5 Coder 3B Q8 run imitated tool text instead of making a structured call, which is model behavior rather than a transport failure.

Compatibility and tests

  • Codex 0.147.0: freeform catalog parses and native patch execution works
  • Codex 0.148.0 and 0.151.0: native patch execution works and CRLF preservation is enabled
  • catalog null: no native apply_patch, matching the old behavior
  • catalog "function": startup rejection reproduced
  • normal Responses function tools keep their existing schemas and output
  • non-Codex custom tools and unsupported built-ins remain ignored
  • existing local model serving and non-Codex request paths are unchanged
  • 671 focused local tests pass, with ruff and git diff --check

Final-head focused CI:

Full fork CI for the exact final source HEAD: results. It completed with 38 passes and 4 expected skips. Seven checks reproduced failures already present on current main: stale backend source-inspection assertions plus missing Python 3.13 torchaudio, disabled-MCP Playwright state, Gemma 270M nondeterminism on macOS, stale MLX/Gemma Core tests across all three dependency matrices, and four unrelated repo CPU tests. No failure exercised or implicated this PR's changed paths.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-30T00:35:43.931191Z 3aefa95 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 3aefa95707

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

Copy link
Copy Markdown
Contributor

All reviewed and fixed, LGTM. full fork CI results

@mahiatlinux mahiatlinux changed the title fix: expose Codex apply_patch for local models (#9114) fix: expose codex apply_patch for local models (#9114) Aug 30, 2026
@mahiatlinux
mahiatlinux merged commit a540272 into unslothai:main Aug 30, 2026
42 of 50 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] apply_patch tool not exposed when launching Codex via unsloth codex .

3 participants