Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Kenshia540272b6c44
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 658c851ea47..b9efa173906 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2832,6 +2832,27 @@ class ResponsesFunctionCallOutputInputItem(BaseModel):
status: Optional[Literal["in_progress", "completed", "incomplete"]] = None
+class ResponsesCustomToolCallInputItem(BaseModel):
+ """A prior assistant custom_tool_call replayed by a Responses client."""
+
+ type: Literal["custom_tool_call"]
+ id: Optional[str] = None
+ call_id: str
+ name: str
+ input: str = Field(..., description = "Raw freeform input the model produced.")
+ status: Optional[Literal["in_progress", "completed", "incomplete"]] = None
+
+
+class ResponsesCustomToolCallOutputInputItem(BaseModel):
+ """A client result for a prior custom_tool_call."""
+
+ type: Literal["custom_tool_call_output"]
+ id: Optional[str] = None
+ call_id: str
+ output: Union[str, list]
+ status: Optional[Literal["in_progress", "completed", "incomplete"]] = None
+
+
class ResponsesUnknownInputItem(BaseModel):
"""Catch-all for unmodelled Responses input item types.
@@ -2861,6 +2882,10 @@ def _responses_input_item_discriminator(v: Any) -> str:
return "function_call"
if t == "function_call_output":
return "function_call_output"
+ if t == "custom_tool_call":
+ return "custom_tool_call"
+ if t == "custom_tool_call_output":
+ return "custom_tool_call_output"
if r is not None or t == "message":
return "message"
return "unknown"
@@ -2871,6 +2896,8 @@ ResponsesInputItem = Annotated[
Annotated[ResponsesInputMessage, Tag("message")],
Annotated[ResponsesFunctionCallInputItem, Tag("function_call")],
Annotated[ResponsesFunctionCallOutputInputItem, Tag("function_call_output")],
+ Annotated[ResponsesCustomToolCallInputItem, Tag("custom_tool_call")],
+ Annotated[ResponsesCustomToolCallOutputInputItem, Tag("custom_tool_call_output")],
Annotated[ResponsesUnknownInputItem, Tag("unknown")],
],
Discriminator(_responses_input_item_discriminator),
@@ -2907,12 +2934,12 @@ class ResponsesRequest(BaseModel):
# OpenAI function-calling fields, forwarded via the Chat Completions
# pass-through. Plain list so built-in tool shapes round-trip without
- # validation errors; the translator forwards only ``type=="function"`` entries.
+ # validation errors; the translator forwards functions and Codex apply_patch.
tools: Optional[list[dict]] = Field(
None,
description = (
- "Responses-shape function tool definitions. Entries with "
- '`type="function"` are translated to the Chat Completions nested '
+ "Responses-shape tool definitions. Function tools and Codex's "
+ "custom `apply_patch` are translated to the Chat Completions nested "
"shape before being forwarded to llama-server; other tool types "
"(built-in web_search, file_search, mcp, ...) are accepted for SDK "
"compatibility but ignored on the llama-server passthrough."
@@ -2991,10 +3018,22 @@ class ResponsesOutputFunctionCall(BaseModel):
status: Literal["completed", "in_progress", "incomplete"] = "completed"
+class ResponsesOutputCustomToolCall(BaseModel):
+ """A freeform custom-tool call returned by the Responses API."""
+
+ type: Literal["custom_tool_call"] = "custom_tool_call"
+ id: str = Field(default_factory = lambda: f"ctc_{uuid.uuid4().hex[:12]}")
+ call_id: str
+ name: str
+ input: str
+ status: Literal["completed", "in_progress", "incomplete"] = "completed"
+
+
ResponsesOutputItem = Union[
ResponsesOutputMessage,
ResponsesOutputReasoning,
ResponsesOutputFunctionCall,
+ ResponsesOutputCustomToolCall,
]
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 197ebb90750..3289e5a330f 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2758,11 +2758,14 @@ from models.inference import (
ResponsesUnknownInputItem,
ResponsesFunctionCallInputItem,
ResponsesFunctionCallOutputInputItem,
+ ResponsesCustomToolCallInputItem,
+ ResponsesCustomToolCallOutputInputItem,
ResponsesOutputTextContent,
ResponsesOutputMessage,
ResponsesOutputReasoning,
ResponsesOutputReasoningContent,
ResponsesOutputFunctionCall,
+ ResponsesOutputCustomToolCall,
ResponsesUsage,
ResponsesResponse,
AnthropicMessagesRequest,
@@ -24562,8 +24565,44 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get
# =====================================================================
+_RESPONSES_CUSTOM_APPLY_PATCH = "apply_patch"
+
+
+def _is_responses_apply_patch_tool(tool: Any) -> bool:
+ if not isinstance(tool, dict):
+ return False
+ format_spec = tool.get("format")
+ return (
+ tool.get("type") == "custom"
+ and tool.get("name") == _RESPONSES_CUSTOM_APPLY_PATCH
+ and isinstance(format_spec, dict)
+ and format_spec.get("type") == "grammar"
+ and format_spec.get("syntax") == "lark"
+ and isinstance(format_spec.get("definition"), str)
+ )
+
+
+def _responses_custom_tool_names(tools: Optional[list[dict]]) -> set[str]:
+ return {tool["name"] for tool in tools or [] if _is_responses_apply_patch_tool(tool)}
+
+
+def _responses_apply_patch_description(tool: dict) -> str:
+ description = (
+ "Edit files by passing one complete patch in the input field. "
+ "Every added content line must start with +. Example:\n"
+ "*** Begin Patch\n"
+ "*** Add File: path/to/file.txt\n"
+ "+first line\n"
+ "*** End Patch"
+ )
+ format_spec = tool.get("format")
+ if isinstance(format_spec, dict) and isinstance(format_spec.get("definition"), str):
+ description += "\n\nThe input must match this Lark grammar:\n" + format_spec["definition"]
+ return description
+
+
def _translate_responses_tools_to_chat(tools: Optional[list[dict]]) -> Optional[list[dict]]:
- """Translate Responses-shape function tools to the Chat Completions nested shape.
+ """Translate supported Responses tools to the Chat Completions function shape.
Responses uses a flat shape per tool entry::
@@ -24576,10 +24615,9 @@ def _translate_responses_tools_to_chat(tools: Optional[list[dict]]) -> Optional[
"function": {"name": "...", "description": "...",
"parameters": {...}, "strict": true}}
- Only ``type=="function"`` entries are forwarded. Built-in Responses tools
- (``web_search``, ``file_search``, ``mcp``, ...) are dropped: llama-server
- doesn't implement them server-side, so keeping them would produce an opaque
- upstream 400.
+ Codex's freeform ``apply_patch`` custom tool becomes a string-input function
+ for local chat templates. Other custom and built-in Responses tools are
+ dropped because llama-server cannot execute them server-side.
"""
if not tools:
return None
@@ -24587,6 +24625,29 @@ def _translate_responses_tools_to_chat(tools: Optional[list[dict]]) -> Optional[
for tool in tools:
if not isinstance(tool, dict):
continue
+ if _is_responses_apply_patch_tool(tool):
+ out.append(
+ {
+ "type": "function",
+ "function": {
+ "name": _RESPONSES_CUSTOM_APPLY_PATCH,
+ "description": _responses_apply_patch_description(tool),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "input": {
+ "type": "string",
+ "description": "A complete patch matching the tool grammar.",
+ }
+ },
+ "required": ["input"],
+ "additionalProperties": False,
+ },
+ "strict": False,
+ },
+ }
+ )
+ continue
if tool.get("type") != "function":
continue
fn: dict = {}
@@ -24602,7 +24663,9 @@ def _translate_responses_tools_to_chat(tools: Optional[list[dict]]) -> Optional[
return out or None
-def _translate_responses_tool_choice_to_chat(tool_choice: Any) -> Any:
+def _translate_responses_tool_choice_to_chat(
+ tool_choice: Any, custom_tool_names: Optional[set[str]] = None
+) -> Any:
"""Translate a Responses-shape ``tool_choice`` to the Chat Completions shape.
String values (``"auto"``/``"none"``/``"required"``) pass through unchanged.
@@ -24617,10 +24680,14 @@ def _translate_responses_tool_choice_to_chat(tool_choice: Any) -> Any:
return tool_choice
if (
isinstance(tool_choice, dict)
- and tool_choice.get("type") == "function"
+ and tool_choice.get("type") in ("function", "custom")
and "name" in tool_choice
and "function" not in tool_choice
):
+ if tool_choice.get("type") == "custom":
+ custom_tool_names = custom_tool_names or set()
+ if tool_choice["name"] not in custom_tool_names:
+ return tool_choice
return {"type": "function", "function": {"name": tool_choice["name"]}}
return tool_choice
@@ -24875,7 +24942,7 @@ def _responses_reasoning_output_item(reasoning_text: str, item_id: Optional[str]
def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
"""Convert a ResponsesRequest's ``input`` into a Chat-format ``ChatMessage`` list.
- Handles the three input item shapes allowed by the Responses API:
+ Handles the supported input item shapes from the Responses API:
- ``ResponsesInputMessage`` -- regular chat messages (text or multimodal).
- ``ResponsesFunctionCallInputItem`` -- a prior assistant tool call
@@ -24884,6 +24951,8 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
- ``ResponsesFunctionCallOutputInputItem`` -- a tool result the client is
returning. Becomes a ``role="tool"`` message with ``tool_call_id`` set to
the originating ``call_id`` so llama-server can reconcile call with result.
+ - ``ResponsesCustomToolCallInputItem`` and its output counterpart -- the
+ freeform call is wrapped in the local ``input`` function argument.
System / developer content is collected from ``instructions`` *and* any
``role="system"`` / ``role="developer"`` entries in ``input``, then merged
@@ -24912,6 +24981,13 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
messages.append(ChatMessage(role = "user", content = payload.input))
return _with_system(messages)
+ custom_tool_names = _responses_custom_tool_names(payload.tools)
+ custom_tool_call_ids = {
+ item.call_id
+ for item in payload.input
+ if isinstance(item, ResponsesCustomToolCallInputItem) and item.name in custom_tool_names
+ }
+
for item in payload.input:
if isinstance(item, ResponsesFunctionCallInputItem):
messages.append(
@@ -24945,6 +25021,39 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
)
continue
+ if isinstance(item, ResponsesCustomToolCallInputItem):
+ if item.call_id not in custom_tool_call_ids:
+ continue
+ messages.append(
+ ChatMessage(
+ role = "assistant",
+ content = None,
+ tool_calls = [
+ {
+ "id": item.call_id,
+ "type": "function",
+ "function": {
+ "name": item.name,
+ "arguments": json.dumps({"input": item.input}, ensure_ascii = False),
+ },
+ }
+ ],
+ )
+ )
+ continue
+
+ if isinstance(item, ResponsesCustomToolCallOutputInputItem):
+ if item.call_id not in custom_tool_call_ids:
+ continue
+ messages.append(
+ ChatMessage(
+ role = "tool",
+ tool_call_id = item.call_id,
+ content = _responses_tool_output_content(item.output),
+ )
+ )
+ continue
+
if isinstance(item, ResponsesUnknownInputItem):
# Reasoning items and other unmodelled top-level Responses item
# types are silently dropped -- llama-server-backed GGUFs can't
@@ -25044,7 +25153,9 @@ def _build_chat_request(
if chat_tools is not None:
chat_kwargs["tools"] = chat_tools
- chat_tool_choice = _translate_responses_tool_choice_to_chat(payload.tool_choice)
+ chat_tool_choice = _translate_responses_tool_choice_to_chat(
+ payload.tool_choice, _responses_custom_tool_names(payload.tools)
+ )
if chat_tool_choice is not None:
chat_kwargs["tool_choice"] = chat_tool_choice
if payload.parallel_tool_calls is not None:
@@ -25095,23 +25206,50 @@ def _build_chat_request(
return ChatCompletionRequest(**chat_kwargs)
-def _chat_tool_calls_to_responses_output(tool_calls: list[dict]) -> list[dict]:
- """Map Chat Completions ``tool_calls`` into Responses ``function_call`` output items.
+def _responses_custom_tool_input(arguments: Any) -> str:
+ if not isinstance(arguments, str):
+ return ""
+ try:
+ parsed = json.loads(arguments)
+ except json.JSONDecodeError:
+ return arguments
+ if isinstance(parsed, dict) and isinstance(parsed.get("input"), str):
+ return parsed["input"]
+ return arguments
+
+
+def _chat_tool_calls_to_responses_output(
+ tool_calls: list[dict], custom_tool_names: Optional[set[str]] = None
+) -> list[dict]:
+ """Map local function calls back into their Responses output item types.
The Chat Completions id (``call_xxx``) is the shared correlation key across
turns in the Responses API -- stored as ``call_id`` on the output item and
- echoed back by the client as ``function_call_output.call_id`` next turn.
+ echoed back by the client in the tool output on the next turn.
"""
+ custom_tool_names = custom_tool_names or set()
items: list[dict] = []
for tc in tool_calls:
if tc.get("type") != "function":
continue
fn = tc.get("function") or {}
+ name = fn.get("name", "")
+ arguments = fn.get("arguments", "") or ""
+ if name in custom_tool_names:
+ items.append(
+ ResponsesOutputCustomToolCall(
+ call_id = tc.get("id", ""),
+ name = name,
+ input = _responses_custom_tool_input(arguments),
+ status = "completed",
+ ).model_dump()
+ )
+ continue
items.append(
ResponsesOutputFunctionCall(
call_id = tc.get("id", ""),
- name = fn.get("name", ""),
- arguments = fn.get("arguments", "") or "",
+ name = name,
+ arguments = arguments,
status = "completed",
).model_dump()
)
@@ -25209,7 +25347,11 @@ async def _responses_non_streaming(
content = [ResponsesOutputTextContent(text = text)],
).model_dump()
)
- output_items.extend(_chat_tool_calls_to_responses_output(tool_calls))
+ output_items.extend(
+ _chat_tool_calls_to_responses_output(
+ tool_calls, _responses_custom_tool_names(payload.tools)
+ )
+ )
response = ResponsesResponse(
id = resp_id,
@@ -25275,10 +25417,9 @@ async def _responses_stream(
Output items are allocated as upstream deltas appear. Reasoning/text deltas
open top-level ``reasoning`` / ``message`` items; each tool call from
``delta.tool_calls[]`` is promoted to its own top-level ``function_call``
- item (one per distinct ``tool_calls[].index``) and relayed as
- ``response.function_call_arguments.delta`` / ``.done`` events so clients
- (Codex, OpenAI Python SDK) can reconstruct the call incrementally and reply
- with a ``function_call_output`` item next turn.
+ item (one per distinct ``tool_calls[].index``). Regular functions relay
+ argument deltas. Codex's bridged ``apply_patch`` call is buffered and
+ restored to one native ``custom_tool_call`` item with raw patch input.
"""
from core.inference.llama_keepwarm import mark_response_failed
@@ -25286,6 +25427,7 @@ async def _responses_stream(
created_at = int(time.time())
chat_req = _build_chat_request(payload, messages, stream = True)
+ custom_tool_names = _responses_custom_tool_names(payload.tools)
llama_backend = get_llama_cpp_backend()
if not llama_backend.is_loaded:
@@ -25475,7 +25617,8 @@ async def _responses_stream(
if fn.get("name") and not st["name"]:
st["name"] = fn["name"]
- if not st["opened"] and st["call_id"] and st["name"]:
+ is_custom_tool = st["name"] in custom_tool_names
+ if not is_custom_tool and not st["opened"] and st["call_id"] and st["name"]:
item_added = {
"type": "response.output_item.added",
"output_index": st["output_index"],
@@ -25492,8 +25635,9 @@ async def _responses_stream(
st["opened"] = True
arg_delta = fn.get("arguments") or ""
- if arg_delta and st["opened"]:
+ if arg_delta:
st["arguments"] += arg_delta
+ if arg_delta and st["opened"]:
args_delta_event = {
"type": "response.function_call_arguments.delta",
"item_id": st["item_id"],
@@ -25501,11 +25645,6 @@ async def _responses_stream(
"delta": arg_delta,
}
events.append(_sse("response.function_call_arguments.delta", args_delta_event))
- elif arg_delta:
- # Buffer args until we can open the item (some models
- # send id/name in the same chunk as the first arg delta;
- # if not, stash).
- st["arguments"] += arg_delta
return events
def _claim_output_index() -> int:
@@ -25724,17 +25863,27 @@ async def _responses_stream(
)
)
for st in tool_call_state.values():
+ if st["name"] in custom_tool_names:
+ item = {
+ "type": "custom_tool_call",
+ "status": "completed",
+ "call_id": st["call_id"],
+ "name": st["name"],
+ "input": _responses_custom_tool_input(st["arguments"]),
+ }
+ else:
+ item = {
+ "type": "function_call",
+ "id": st["item_id"],
+ "status": "completed",
+ "call_id": st["call_id"],
+ "name": st["name"],
+ "arguments": st["arguments"],
+ }
indexed_items.append(
(
st["output_index"],
- {
- "type": "function_call",
- "id": st["item_id"],
- "status": "completed",
- "call_id": st["call_id"],
- "name": st["name"],
- "arguments": st["arguments"],
- },
+ item,
)
)
return [item for _, item in sorted(indexed_items, key = lambda pair: pair[0])]
@@ -26166,6 +26315,25 @@ async def _responses_stream(
)
continue
+ if st["name"] in custom_tool_names:
+ if not st["call_id"]:
+ st["call_id"] = f"call_{uuid.uuid4().hex[:12]}"
+ custom_input = _responses_custom_tool_input(st["arguments"])
+ item_done = {
+ "type": "response.output_item.done",
+ "output_index": st["output_index"],
+ "item": {
+ "type": "custom_tool_call",
+ "status": "completed",
+ "call_id": st["call_id"],
+ "name": st["name"],
+ "input": custom_input,
+ },
+ }
+ api_monitor.append_reply(monitor_id, _monitor_call_text(st["name"], custom_input))
+ yield _sse("response.output_item.done", item_done)
+ continue
+
# If id/name never arrived (malformed upstream), synthesise so the
# client still sees a coherent frame sequence.
if not st["opened"]:
diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.py
index ea434e98551..68aa0c356a4 100644
--- a/studio/backend/tests/test_responses_tool_passthrough.py
+++ b/studio/backend/tests/test_responses_tool_passthrough.py
@@ -43,11 +43,14 @@ from pydantic import ValidationError
from core.inference.api_monitor import ApiMonitor
from models.inference import (
ChatMessage,
+ ResponsesCustomToolCallInputItem,
+ ResponsesCustomToolCallOutputInputItem,
ResponsesFunctionCallInputItem,
ResponsesFunctionCallOutputInputItem,
ResponsesFunctionTool,
ResponsesInputMessage,
ResponsesOutputFunctionCall,
+ ResponsesOutputCustomToolCall,
ResponsesOutputMessage,
ResponsesOutputReasoning,
ResponsesOutputTextContent,
@@ -66,6 +69,7 @@ from routes.inference import (
_extract_response_format,
_extract_responses_reasoning,
_normalise_responses_input,
+ _responses_custom_tool_input,
_responses_tool_output_content,
_responses_non_streaming,
_responses_stream,
@@ -74,6 +78,18 @@ from routes.inference import (
)
+def _codex_apply_patch_tool():
+ return {
+ "type": "custom",
+ "name": "apply_patch",
+ "format": {
+ "type": "grammar",
+ "syntax": "lark",
+ "definition": 'start: "*** Begin Patch" LF hunk+ "*** End Patch" LF?',
+ },
+ }
+
+
# =====================================================================
# Request model — tools / tool_choice / parallel_tool_calls
# =====================================================================
@@ -185,6 +201,26 @@ class TestResponsesMultiTurnInput:
)
assert isinstance(item.output, list)
+ def test_custom_tool_call_items(self):
+ req = ResponsesRequest(
+ input = [
+ {
+ "type": "custom_tool_call",
+ "call_id": "call_patch",
+ "name": "apply_patch",
+ "input": "*** Begin Patch\n*** End Patch",
+ },
+ {
+ "type": "custom_tool_call_output",
+ "call_id": "call_patch",
+ "output": "Done!",
+ },
+ ]
+ )
+
+ assert isinstance(req.input[0], ResponsesCustomToolCallInputItem)
+ assert isinstance(req.input[1], ResponsesCustomToolCallOutputInputItem)
+
# =====================================================================
# Translators — tools, tool_choice
@@ -230,6 +266,66 @@ class TestToolsTranslation:
assert len(out) == 1
assert out[0]["function"]["name"] == "search"
+ def test_codex_apply_patch_custom_tool_becomes_a_local_function(self):
+ grammar = (
+ 'start: "*** Begin Patch" LF add_hunk "*** End Patch" LF?\n'
+ 'add_hunk: "*** Add File: " filename LF add_line+\n'
+ 'add_line: "+" /(.*)/ LF'
+ )
+ out = _translate_responses_tools_to_chat(
+ [
+ {
+ "type": "custom",
+ "name": "apply_patch",
+ "description": "freeform",
+ "format": {"type": "grammar", "syntax": "lark", "definition": grammar},
+ }
+ ]
+ )
+
+ assert out == [
+ {
+ "type": "function",
+ "function": {
+ "name": "apply_patch",
+ "description": (
+ "Edit files by passing one complete patch in the input field. "
+ "Every added content line must start with +. Example:\n"
+ "*** Begin Patch\n"
+ "*** Add File: path/to/file.txt\n"
+ "+first line\n"
+ "*** End Patch\n\n"
+ "The input must match this Lark grammar:\n" + grammar
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "input": {
+ "type": "string",
+ "description": "A complete patch matching the tool grammar.",
+ }
+ },
+ "required": ["input"],
+ "additionalProperties": False,
+ },
+ "strict": False,
+ },
+ }
+ ]
+
+ def test_unrelated_custom_tools_stay_unsupported(self):
+ assert (
+ _translate_responses_tools_to_chat(
+ [{"type": "custom", "name": "code_exec", "description": "raw input"}]
+ )
+ is None
+ )
+
+ def test_apply_patch_without_the_codex_grammar_stays_unsupported(self):
+ assert (
+ _translate_responses_tools_to_chat([{"type": "custom", "name": "apply_patch"}]) is None
+ )
+
def test_empty_returns_none(self):
assert _translate_responses_tools_to_chat(None) is None
assert _translate_responses_tools_to_chat([]) is None
@@ -263,6 +359,19 @@ class TestToolChoiceTranslation:
{"type": "function", "name": "get_weather"}
) == {"type": "function", "function": {"name": "get_weather"}}
+ def test_forced_apply_patch_custom_tool_converted(self):
+ assert _translate_responses_tool_choice_to_chat(
+ {"type": "custom", "name": "apply_patch"}, {"apply_patch"}
+ ) == {"type": "function", "function": {"name": "apply_patch"}}
+
+ def test_forced_apply_patch_without_valid_catalog_passes_through(self):
+ choice = {"type": "custom", "name": "apply_patch"}
+ assert _translate_responses_tool_choice_to_chat(choice, set()) is choice
+
+ def test_unrelated_custom_tool_choice_passes_through(self):
+ choice = {"type": "custom", "name": "code_exec"}
+ assert _translate_responses_tool_choice_to_chat(choice) is choice
+
def test_already_chat_nested_shape_passes_through(self):
"""A client sending the Chat Completions nested shape isn't
double-wrapped."""
@@ -439,6 +548,67 @@ class TestNormaliseResponsesInputWithTools:
assert msgs[2].tool_call_id == "call_1"
assert msgs[2].content == '{"temp": 20}'
+ def test_custom_tool_call_round_trip_maps_to_local_function(self):
+ patch = "*** Begin Patch\n*** Add File: café.txt\n+héllo\n*** End Patch"
+ payload = ResponsesRequest(
+ input = [
+ {
+ "type": "custom_tool_call",
+ "call_id": "call_patch",
+ "name": "apply_patch",
+ "input": patch,
+ },
+ {
+ "type": "custom_tool_call_output",
+ "call_id": "call_patch",
+ "output": "Done!",
+ },
+ ],
+ tools = [_codex_apply_patch_tool()],
+ )
+
+ messages = _normalise_responses_input(payload)
+
+ assert len(messages) == 2
+ assert messages[0].role == "assistant"
+ call = messages[0].tool_calls[0]
+ assert call["id"] == "call_patch"
+ assert call["function"]["name"] == "apply_patch"
+ assert json.loads(call["function"]["arguments"]) == {"input": patch}
+ assert messages[1].role == "tool"
+ assert messages[1].tool_call_id == "call_patch"
+ assert messages[1].content == "Done!"
+
+ def test_unrelated_custom_tool_replay_stays_ignored(self):
+ payload = ResponsesRequest(
+ input = [
+ {
+ "type": "custom_tool_call",
+ "call_id": "call_code",
+ "name": "code_exec",
+ "input": "print('hidden')",
+ },
+ {
+ "type": "custom_tool_call_output",
+ "call_id": "call_code",
+ "output": "hidden output",
+ },
+ ],
+ tools = [
+ {
+ "type": "custom",
+ "name": "code_exec",
+ "format": {
+ "type": "grammar",
+ "syntax": "lark",
+ "definition": "start: /.+/",
+ },
+ }
+ ],
+ )
+
+ assert _normalise_responses_input(payload) == []
+
def test_instructions_plus_developer_message_are_merged(self):
"""Codex CLI sends `instructions` (system prompt) AND a developer
message in `input`. Strict chat templates (harmony / gpt-oss,
@@ -785,6 +955,51 @@ class TestChatToolCallsToResponsesOutput:
)
assert items[0]["arguments"] == ""
+ def test_apply_patch_function_is_restored_to_a_custom_tool_call(self):
+ patch = "*** Begin Patch\n*** Add File: café.txt\n+héllo\n*** End Patch"
+ items = _chat_tool_calls_to_responses_output(
+ [
+ {
+ "id": "call_patch",
+ "type": "function",
+ "function": {
+ "name": "apply_patch",
+ "arguments": json.dumps({"input": patch}),
+ },
+ }
+ ],
+ {"apply_patch"},
+ )
+
+ assert items[0]["type"] == "custom_tool_call"
+ assert items[0]["call_id"] == "call_patch"
+ assert items[0]["name"] == "apply_patch"
+ assert items[0]["input"] == patch
+
+ def test_regular_function_named_apply_patch_stays_a_function_call(self):
+ items = _chat_tool_calls_to_responses_output(
+ [
+ {
+ "id": "call_patch",
+ "type": "function",
+ "function": {"name": "apply_patch", "arguments": '{"path":"x"}'},
+ }
+ ]
+ )
+
+ assert items[0]["type"] == "function_call"
+
+ @pytest.mark.parametrize(
+ ("arguments", "expected"),
+ [
+ ('{"input":"patch"', '{"input":"patch"'),
+ ('{"other":"value"}', '{"other":"value"}'),
+ (None, ""),
+ ],
+ )
+ def test_malformed_custom_arguments_are_not_hidden(self, arguments, expected):
+ assert _responses_custom_tool_input(arguments) == expected
+
# =====================================================================
# Non-streaming Responses adapter
@@ -804,7 +1019,11 @@ class TestResponsesNonStreamingAdapter:
):
import routes.inference as inf_mod
- async def fake_chat_completions(chat_req, request):
+ async def fake_chat_completions(
+ chat_req,
+ request,
+ current_subject = None,
+ ):
return JSONResponse(
content = {
"model": "test-model",
@@ -842,6 +1061,34 @@ class TestResponsesNonStreamingAdapter:
assert "<think>" not in body["output"][1]["content"][0]["text"]
assert "</think>" not in body["output"][1]["content"][0]["text"]
+ def test_apply_patch_function_becomes_a_custom_tool_call(self, monkeypatch):
+ patch = "*** Begin Patch\n*** Add File: nested/a.txt\n+ok\n*** End Patch"
+ payload = ResponsesRequest(
+ input = "edit the file",
+ tools = [_codex_apply_patch_tool()],
+ )
+ body = self._run_with_message(
+ monkeypatch,
+ {
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_patch",
+ "type": "function",
+ "function": {
+ "name": "apply_patch",
+ "arguments": json.dumps({"input": patch}),
+ },
+ }
+ ],
+ },
+ payload = payload,
+ )
+
+ assert len(body["output"]) == 1
+ assert body["output"][0]["type"] == "custom_tool_call"
+ assert body["output"][0]["input"] == patch
+
def test_unclosed_think_block_extracts_as_reasoning(self):
reasoning, visible = _extract_responses_reasoning(
"<think>partial plan",
@@ -855,7 +1102,11 @@ class TestResponsesNonStreamingAdapter:
import routes.inference as inf_mod
import routes.inference as inf_mod
- async def fake_chat_completions(chat_req, request):
+ async def fake_chat_completions(
+ chat_req,
+ request,
+ current_subject = None,
+ ):
assert request.state.skip_api_monitor is True
return JSONResponse(
content = {
@@ -911,7 +1162,11 @@ class TestResponsesNonStreamingAdapter:
usage = {"prompt_tokens": 11, "completion_tokens": 50, "total_tokens": 61}
- async def fake_chat_completions(chat_req, request):
+ async def fake_chat_completions(
+ chat_req,
+ request,
+ current_subject = None,
+ ):
assert request.state.skip_api_monitor is True
# monitor_id is None here: this call's own row is the suppressed one.
if observations is not None:
@@ -1030,7 +1285,11 @@ class TestResponsesNonStreamingAdapter:
def test_monitor_records_tool_only_reply(self, monkeypatch):
import routes.inference as inf_mod
- async def fake_chat_completions(chat_req, request):
+ async def fake_chat_completions(
+ chat_req,
+ request,
+ current_subject = None,
+ ):
assert request.state.skip_api_monitor is True
return JSONResponse(
content = {
@@ -1085,7 +1344,11 @@ class TestResponsesNonStreamingAdapter:
def test_cancelled_chat_completion_finalizes_monitor(self, monkeypatch):
import routes.inference as inf_mod
- async def fake_chat_completions(chat_req, request):
+ async def fake_chat_completions(
+ chat_req,
+ request,
+ current_subject = None,
+ ):
assert request.state.skip_api_monitor is True
raise asyncio.CancelledError()
@@ -1841,6 +2104,115 @@ class TestResponsesStreamAdapter:
"message",
]
+ def test_apply_patch_stream_is_restored_to_one_custom_tool_call(self, monkeypatch):
+ patch = "*** Begin Patch\n*** Add File: nested/café.txt\n+héllo\n*** End Patch"
+ arguments = json.dumps({"input": patch}, ensure_ascii = False)
+ split = len(arguments) // 2
+ chunks = [
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_patch",
+ "type": "function",
+ "function": {
+ "name": "apply_patch",
+ "arguments": arguments[:split],
+ },
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {"arguments": arguments[split:]},
+ }
+ ]
+ }
+ }
+ ]
+ },
+ ]
+ self._install_stream_mock(monkeypatch, chunks)
+ payload = ResponsesRequest(
+ input = "edit",
+ stream = True,
+ tools = [_codex_apply_patch_tool()],
+ )
+
+ async def run():
+ response = await _responses_stream(
+ payload, [ChatMessage(role = "user", content = "edit")], self._Request()
+ )
+ return await self._collect(response)
+
+ lines = asyncio.run(run())
+
+ assert self._payloads(lines, "response.function_call_arguments.delta") == []
+ assert self._payloads(lines, "response.function_call_arguments.done") == []
+ done = self._payloads(lines, "response.output_item.done")
+ assert len(done) == 1
+ assert done[0]["item"] == {
+ "type": "custom_tool_call",
+ "status": "completed",
+ "call_id": "call_patch",
+ "name": "apply_patch",
+ "input": patch,
+ }
+ completed = self._payloads(lines, "response.completed")[0]
+ assert completed["response"]["output"] == [done[0]["item"]]
+
+ def test_regular_apply_patch_function_stream_stays_a_function_call(self, monkeypatch):
+ chunks = [
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_patch",
+ "type": "function",
+ "function": {
+ "name": "apply_patch",
+ "arguments": '{"path":"x"}',
+ },
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+ self._install_stream_mock(monkeypatch, chunks)
+ payload = ResponsesRequest(
+ input = "edit",
+ stream = True,
+ tools = [{"type": "function", "name": "apply_patch"}],
+ )
+
+ async def run():
+ response = await _responses_stream(
+ payload, [ChatMessage(role = "user", content = "edit")], self._Request()
+ )
+ return await self._collect(response)
+
+ lines = asyncio.run(run())
+
+ done = self._payloads(lines, "response.output_item.done")
+ assert done[0]["item"]["type"] == "function_call"
+ assert self._payloads(lines, "response.function_call_arguments.done")
+
def test_requests_usage_and_caps_parallel_tool_calls(self, monkeypatch):
import routes.inference as inf_mod
@@ -1970,6 +2342,17 @@ class TestResponsesOutputFunctionCall:
assert d["status"] == "completed"
assert d["id"].startswith("fc_")
+ def test_custom_tool_call_construction(self):
+ call = ResponsesOutputCustomToolCall(
+ call_id = "call_patch",
+ name = "apply_patch",
+ input = "*** Begin Patch\n*** End Patch",
+ ).model_dump()
+
+ assert call["type"] == "custom_tool_call"
+ assert call["id"].startswith("ctc_")
+ assert call["status"] == "completed"
+
def test_response_with_tool_call_output(self):
resp = ResponsesResponse(
model = "test",
diff --git a/unsloth_cli/codex_fallback_prompt.md b/unsloth_cli/codex_fallback_prompt.md
index 5d5fd6c9f8e..1ddd96a5386 100644
--- a/unsloth_cli/codex_fallback_prompt.md
+++ b/unsloth_cli/codex_fallback_prompt.md
@@ -129,7 +129,7 @@ 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`): {"command":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
+- Use the `apply_patch` tool to edit files. Send one complete `*** Begin Patch` / `*** End Patch` patch per call.
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:
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index dea34e944e8..bbcd90a2f56 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -2588,13 +2588,10 @@ def _merge_codex_config(existing: str, base: str) -> str:
# Apache-2.0 prompt is copied from openai/codex rust-v0.144.0 models-manager/prompt.md.
_CODEX_FALLBACK_PROMPT = Path(__file__).parent.parent / "codex_fallback_prompt.md"
_CODEX_MODEL_CATALOG_MIN_VERSION = (0, 110, 0)
+_CODEX_PATCH_LINE_ENDINGS_MIN_VERSION = (0, 148, 0)
-def _codex_supports_model_catalog() -> bool:
- executable = _which_with_install_dirs("codex")
- if executable is None:
- # A --no-launch recipe may be copied to another machine; assume a current Codex.
- return True
+def _codex_executable_version(executable: str) -> Optional[tuple[int, int, int]]:
try:
output = subprocess.check_output(
[executable, "--version"],
@@ -2604,11 +2601,27 @@ def _codex_supports_model_catalog() -> bool:
env = _probe_env(),
)
except Exception:
- return False
+ return None
match = re.search(r"(\d+)\.(\d+)\.(\d+)", output)
- return bool(match) and tuple(int(part) for part in match.groups()) >= (
- _CODEX_MODEL_CATALOG_MIN_VERSION
- )
+ return tuple(int(part) for part in match.groups()) if match else None
+
+
+def _codex_supports_model_catalog() -> bool:
+ executable = _which_with_install_dirs("codex")
+ if executable is None:
+ # A --no-launch recipe may be copied to another machine; assume a current Codex.
+ return True
+ version = _codex_executable_version(executable)
+ return version is not None and version >= _CODEX_MODEL_CATALOG_MIN_VERSION
+
+
+def _codex_supports_patch_line_endings() -> bool:
+ executable = _which_with_install_dirs("codex")
+ if executable is None:
+ # A normal launch installs Codex after this check; no-launch may run elsewhere.
+ return True
+ version = _codex_executable_version(executable)
+ return version is not None and version >= _CODEX_PATCH_LINE_ENDINGS_MIN_VERSION
def _codex_model_catalog(model: dict) -> dict:
@@ -2631,7 +2644,7 @@ def _codex_model_catalog(model: dict) -> dict:
"supports_reasoning_summary_parameter": False,
"support_verbosity": False,
"default_verbosity": None,
- "apply_patch_tool_type": None,
+ "apply_patch_tool_type": "freeform",
"truncation_policy": {"mode": "bytes", "limit": 10_000},
"supports_parallel_tool_calls": False,
"experimental_supported_tools": [],
@@ -2659,6 +2672,11 @@ def write_codex_config(base: str, model: dict, home: Path) -> None:
f'model_provider = "{_CODEX_PROFILE}"\n'
f"model = {json.dumps(model['id'])}\n"
)
+ if _codex_supports_patch_line_endings():
+ profile_text += (
+ "suppress_unstable_features_warning = true\n"
+ "features.apply_patch_preserve_line_endings = true\n"
+ )
if _codex_supports_model_catalog() and _CODEX_FALLBACK_PROMPT.is_file():
catalog = home / "model-catalog.json"
catalog_text = json.dumps(_codex_model_catalog(model), indent = 2) + "\n"
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index cf98db8975b..3a6dcb65c9a 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -926,12 +926,15 @@ def test_merge_codex_config_keeps_user_oss_provider():
def test_write_codex_config_profile(tmp_path, monkeypatch):
monkeypatch.setattr(start, "_codex_supports_model_catalog", lambda: True)
+ monkeypatch.setattr(start, "_codex_supports_patch_line_endings", lambda: True)
start.write_codex_config(BASE, MODEL, tmp_path)
profile = _parse_toml((tmp_path / "unsloth_api.config.toml").read_text())
assert profile["oss_provider"] == "unsloth_api"
assert profile["model_provider"] == "unsloth_api"
assert profile["model"] == MODEL["id"]
assert profile["model_context_window"] == 131072
+ assert profile["features"]["apply_patch_preserve_line_endings"] is True
+ assert profile["suppress_unstable_features_warning"] is True
catalog_path = Path(profile["model_catalog_json"])
assert catalog_path == Path("model-catalog.json")
@@ -941,10 +944,12 @@ def test_write_codex_config_profile(tmp_path, monkeypatch):
assert catalog["models"][0]["max_context_window"] == 131072
assert catalog["models"][0]["supports_reasoning_summary_parameter"] is False
assert catalog["models"][0]["supports_parallel_tool_calls"] is False
+ assert catalog["models"][0]["apply_patch_tool_type"] == "freeform"
assert catalog["models"][0]["base_instructions"] == start._CODEX_FALLBACK_PROMPT.read_text(
encoding = "utf-8"
)
+ assert '{"command"' not in catalog["models"][0]["base_instructions"]
config = _parse_toml((tmp_path / "config.toml").read_text())
assert config["model_providers"]["unsloth_api"]["env_key"] == "UNSLOTH_STUDIO_AUTH_TOKEN"
@@ -970,6 +975,27 @@ def test_codex_model_catalog_version_gate(monkeypatch, version, expected):
assert start._codex_supports_model_catalog() is expected
+ ("version", "expected"),
+ [
+ ("codex-cli 0.147.0", False),
+ ("codex-cli 0.148.0", True),
+ ("codex-cli 0.150.0", True),
+ ("codex-cli 0.151.0", True),
+ ("codex-cli 1.0.0", True),
+ ],
+)
+def test_codex_patch_line_endings_version_gate(monkeypatch, version, expected):
+ monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/codex")
+ monkeypatch.setattr(start.subprocess, "check_output", lambda *args, **kwargs: version)
+ assert start._codex_supports_patch_line_endings() is expected
+
+
+def test_codex_patch_line_endings_assumes_current_when_not_installed(monkeypatch):
+ monkeypatch.setattr(start, "_which_with_install_dirs", lambda _: None)
+ assert start._codex_supports_patch_line_endings() is True
+
+
def test_write_codex_config_omits_catalog_for_old_codex(tmp_path, monkeypatch):
monkeypatch.setattr(start, "_codex_supports_model_catalog", lambda: False)
start.write_codex_config(BASE, MODEL, tmp_path)