Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Fix custom tool IDs when switching Codex providers (#1831)
Ali Khokharb89d3e188761
diff --git a/pyproject.toml b/pyproject.tomlindex a0e7b255..68e19dd7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.2.39"+version = "6.2.40"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/src/free_claude_code/core/openai_responses/ids.py b/src/free_claude_code/core/openai_responses/ids.pyindex 0ef53f00..12ebd222 100644--- a/src/free_claude_code/core/openai_responses/ids.py+++ b/src/free_claude_code/core/openai_responses/ids.py@@ -1,6 +1,19 @@"""Identifier helpers for OpenAI Responses payloads."""import uuid+from typing import Literal+++def tool_item_id_prefix(kind: Literal["function", "custom"]) -> str:+ return "ctc_" if kind == "custom" else "fc_"+++def tool_item_id_for_kind(item_id: str, *, kind: Literal["function", "custom"]) -> str:+ """Retag only a known opposite prefix, preserving the opaque suffix."""+ opposite = tool_item_id_prefix("function" if kind == "custom" else "custom")+ if item_id.startswith(opposite):+ return tool_item_id_prefix(kind) + item_id[len(opposite) :]+ return item_iddef new_response_id() -> str:diff --git a/src/free_claude_code/core/openai_responses/messages_stream.py b/src/free_claude_code/core/openai_responses/messages_stream.pyindex 161e1705..d06b86de 100644--- a/src/free_claude_code/core/openai_responses/messages_stream.py+++ b/src/free_claude_code/core/openai_responses/messages_stream.py@@ -18,7 +18,12 @@ from free_claude_code.core.history_replay import (from free_claude_code.core.json_types import JsonObject, JsonValuefrom .errors import ResponsesConversionError, openai_error_from_failure-from .ids import new_message_item_id, new_reasoning_item_id, new_response_id+from .ids import (+ new_message_item_id,+ new_reasoning_item_id,+ new_response_id,+ tool_item_id_prefix,+)from .items import message_item, reasoning_itemfrom .models import OpenAIResponsesRequestfrom .streaming.blocks import ReasoningBlockState, TextBlockState, ToolBlockState@@ -296,7 +301,7 @@ class AnthropicToResponsesStream:tool = ToolBlockState(index,slot,- f"fc_{uuid.uuid4().hex}",+ f"{tool_item_id_prefix(identity.kind)}{uuid.uuid4().hex}",call_id,identity.kind,identity.name,diff --git a/src/free_claude_code/core/openai_responses/native.py b/src/free_claude_code/core/openai_responses/native.pyindex 2829ec3f..39e0f0a4 100644--- a/src/free_claude_code/core/openai_responses/native.py+++ b/src/free_claude_code/core/openai_responses/native.py@@ -11,6 +11,7 @@ from free_claude_code.core.reasoning import ReasoningPolicyfrom .errors import openai_error_from_failurefrom .events import format_response_sse_event+from .ids import tool_item_id_for_kindfrom .models import OpenAIResponsesRequestfrom .reasoning import responses_reasoning_config, responses_reasoning_policy@@ -31,6 +32,20 @@ def build_native_responses_request(JsonObject,request.model_dump(mode="json", exclude_none=True),)+ if isinstance(items := body.get("input"), list):+ for item in items:+ if not isinstance(item, dict) or item.get("type") not in (+ "function_call",+ "custom_tool_call",+ ):+ continue+ item_id = item.get("id")+ if isinstance(item_id, str) and item_id != tool_item_id_for_kind(+ item_id,+ kind="custom" if item["type"] == "custom_tool_call" else "function",+ ):+ # Full calls replay by call_id; incompatible item IDs are optional.+ del item["id"]body["model"] = modelbody["stream"] = Truebody["store"] = Falsediff --git a/src/free_claude_code/core/openai_responses/tool_adaptation.py b/src/free_claude_code/core/openai_responses/tool_adaptation.pyindex 351d0988..b6e9f8b6 100644--- a/src/free_claude_code/core/openai_responses/tool_adaptation.py+++ b/src/free_claude_code/core/openai_responses/tool_adaptation.py@@ -12,6 +12,7 @@ import simplejsonfrom free_claude_code.core.json_types import JsonObject, JsonValuefrom .errors import ResponsesConversionError+from .ids import tool_item_id_for_kindfrom .models import OpenAIResponsesRequestfrom .tool_search import (ClientSearchHistory,@@ -505,6 +506,8 @@ class ResponsesToolAdapter:}if identity.namespace is not None:item["namespace"] = identity.namespace+ if isinstance(item_id := item.get("id"), str):+ item["id"] = tool_item_id_for_kind(item_id, kind="custom")return itemdef restore_tools(@@ -696,7 +699,7 @@ class ResponsesToolEventAdapter:and original_item.get("type") == "function_call"and item.get("type") == "custom_tool_call"):- if isinstance(item_id := item.get("id"), str):+ if isinstance(item_id := original_item.get("id"), str):self._custom_items.add(item_id)if event_type == "response.output_item.added":item["input"] = ""diff --git a/tests/core/openai_responses/test_native.py b/tests/core/openai_responses/test_native.pyindex d7666b29..7a5fe1bf 100644--- a/tests/core/openai_responses/test_native.py+++ b/tests/core/openai_responses/test_native.py@@ -1,8 +1,10 @@import json+from copy import deepcopyimport pytestfrom free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.json_types import JsonObject, JsonValuefrom free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.openai_responses.native import (NativeResponsesRelay,@@ -102,6 +104,81 @@ def test_native_request_preserves_complete_multimodal_input_tree() -> None:assert body["input"] == input_tree+def test_native_request_recovers_mistyped_tool_ids_without_mutating_history() -> None:+ custom: JsonObject = {+ "type": "custom_tool_call",+ "name": "edit",+ "call_id": "call_edit",+ "input": "patch",+ "provider_extension": {"id": "fc_nested"},+ }+ function: JsonObject = {+ "type": "function_call",+ "name": "lookup",+ "call_id": "call_lookup",+ "arguments": "{}",+ }+ remaining: list[JsonValue] = [+ {**custom, "id": "ctc_shared", "call_id": "call_other"},+ {"type": "custom_tool_call_output", "call_id": "call_edit", "output": "done"},+ {"type": "function_call_output", "call_id": "call_lookup", "output": "found"},+ {"type": "item_reference", "id": "fc_shared"},+ ]+ request = OpenAIResponsesRequest(+ model="example",+ input=[+ {**custom, "id": "fc_shared"},+ {**function, "id": "ctc_lookup"},+ *remaining,+ ],+ metadata={"id": "fc_metadata"},+ )+ original = deepcopy(request.model_dump())+ body = build_native_responses_request(+ request, model="example", reasoning=ReasoningPolicy()+ )+ assert body["input"] == [custom, function, *remaining]+ assert body["metadata"] == {"id": "fc_metadata"}+ assert request.model_dump() == original+ assert (+ build_native_responses_request(+ OpenAIResponsesRequest.model_validate(body),+ model="example",+ reasoning=ReasoningPolicy(),+ )+ == body+ )+++ "item",+ [+ {"type": "custom_tool_call", "id": "ctc_valid"},+ {"type": "function_call", "id": "fc_valid"},+ {"type": "custom_tool_call"},+ {"type": "function_call"},+ {"type": "custom_tool_call", "id": "opaque"},+ {"type": "function_call", "id": "opaque"},+ {"type": "custom_tool_call", "id": None},+ {"type": "function_call", "id": 42},+ {"type": "custom_tool_call_output", "id": "fc_result"},+ {"type": "function_call_output", "id": "ctc_result"},+ {"type": "message", "id": "ctc_message"},+ {"type": "reasoning", "id": "fc_reasoning"},+ {"type": "item_reference", "id": "fc_reference"},+ {"type": "tool_search_call", "id": "fc_search"},+ ],+)+def test_native_request_preserves_ids_outside_known_call_mismatches(+ item: JsonObject,+) -> None:+ request = OpenAIResponsesRequest(model="example", input=[item])+ body = build_native_responses_request(+ request, model="example", reasoning=ReasoningPolicy()+ )+ assert body["input"] == [item]++def test_native_request_preserves_reasoning_when_fcc_did_not_override_it() -> None:request = OpenAIResponsesRequest.model_validate({diff --git a/tests/core/openai_responses/test_responses_from_messages_stream.py b/tests/core/openai_responses/test_responses_from_messages_stream.pyindex 23b8fa50..8dda1910 100644--- a/tests/core/openai_responses/test_responses_from_messages_stream.py+++ b/tests/core/openai_responses/test_responses_from_messages_stream.py@@ -249,6 +249,19 @@ def test_parallel_tools_preserve_call_ids_namespace_and_emit_arguments_once() ->assert output[0]["name"] == "lookup" and output[0]["arguments"] == '{"q":"ok"}'assert output[1]["call_id"] == "call-b" and output[1]["input"] == "pwd"assert output[0]["id"] != output[0]["call_id"]+ for index, prefix in ((0, "fc_"), (1, "ctc_")):+ item_id = output[index]["id"]+ assert isinstance(item_id, str) and item_id.startswith(prefix)+ coordinates = [event for event in events if event.get("output_index") == index]+ assert [+ cast(JsonObject, event["item"])["id"]+ for event in coordinates+ if "item" in event+ ] == [item_id, item_id]+ assert [event["item_id"] for event in coordinates if "item_id" in event] == [+ item_id,+ item_id,+ ]assert [event["delta"]for event in eventsdiff --git a/tests/core/openai_responses/test_tool_adaptation.py b/tests/core/openai_responses/test_tool_adaptation.pyindex 2deb2217..a155b951 100644--- a/tests/core/openai_responses/test_tool_adaptation.py+++ b/tests/core/openai_responses/test_tool_adaptation.py@@ -133,6 +133,7 @@ def test_hosted_discovery_restores_definitions_and_replays_flat_names(assert public[1]["name"] == "lookup"assert public[1]["namespace"] == "crm"assert public[1]["type"] == ("custom_tool_call" if custom else "function_call")+ assert public[1]["id"] == ("ctc_lookup" if custom else "fc_lookup")assert replay[0]["type"] == "tool_search_output"assert replay[0]["tools"] == [wire_definition]assert replay[1]["name"] == "crm__lookup"@@ -283,6 +284,58 @@ def test_image_only_web_search_is_not_silently_replaced_with_text_search() -> No_adapter(request)[email protected]("status", ["completed", "incomplete", "failed"])[email protected]("namespaced", [False, True])+def test_terminal_snapshot_restores_custom_item_id_without_prior_events(+ status: str, namespaced: bool+) -> None:+ tool: JsonObject = {"type": "custom", "name": "edit"}+ adapter = ResponsesToolAdapter(+ OpenAIResponsesRequest(+ model="example",+ input="edit",+ tools=[{"type": "namespace", "name": "editor", "tools": [tool]}]+ if namespaced+ else [tool],+ ),+ ResponsesToolPolicy(custom_tools_as_functions=True, flatten_namespaces=True),+ )+ item: JsonObject = {+ "type": "function_call",+ "id": "fc_snapshot",+ "call_id": "call_snapshot",+ "name": "editor__edit" if namespaced else "edit",+ "arguments": '{"input":"patch"}',+ "status": "completed" if status == "completed" else "incomplete",+ "provider_extension": {"id": "fc_untouched"},+ }+ payload: JsonObject = {+ "type": f"response.{status}",+ "response": {+ "id": "resp_snapshot",+ "model": "example",+ "status": status,+ "output": [item],+ },+ }+ original = deepcopy(payload)+ events = parse_sse_text(+ "".join(_presenter(adapter).feed(f"response.{status}", payload))+ )+ restored = events[0].data["response"]["output"][0]+ assert restored == {+ "type": "custom_tool_call",+ "id": "ctc_snapshot",+ "call_id": "call_snapshot",+ "name": "edit",+ "input": "patch",+ "status": item["status"],+ "provider_extension": {"id": "fc_untouched"},+ **({"namespace": "editor"} if namespaced else {}),+ }+ assert payload == original++def test_custom_and_function_names_cannot_collide_after_conversion() -> None:request = OpenAIResponsesRequest(model="example",@@ -552,7 +605,7 @@ def test_separate_attempts_do_not_share_custom_item_ids_or_sequences() -> None:"sequence_number": 100,"item": {"type": "function_call",- "id": "reused",+ "id": "fc_reused","name": "edit","call_id": "first","arguments": "",@@ -560,7 +613,7 @@ def test_separate_attempts_do_not_share_custom_item_ids_or_sequences() -> None:},))- ordinary: JsonObject = {"sequence_number": 0, "item_id": "reused", "delta": "{}"}+ ordinary: JsonObject = {"sequence_number": 0, "item_id": "fc_reused", "delta": "{}"}result = list(second.feed("response.function_call_arguments.delta", ordinary))assert result == [(diff --git a/tests/providers/test_openai_chat_stream_output.py b/tests/providers/test_openai_chat_stream_output.pyindex 32a89cb7..91da63a2 100644--- a/tests/providers/test_openai_chat_stream_output.py+++ b/tests/providers/test_openai_chat_stream_output.py@@ -348,9 +348,26 @@ def test_responses_chat_output_preserves_custom_tool_free_form_input() -> None:final = _object_dict(events[-1][1]["response"])final_output = final["output"]assert isinstance(final_output, list)+ item_id = _object_dict(final_output[0])["id"]+ assert isinstance(item_id, str) and item_id.startswith("ctc_")+ assert [kind for kind, _ in events] == [+ "response.created",+ "response.output_item.added",+ "response.custom_tool_call_input.delta",+ "response.custom_tool_call_input.done",+ "response.output_item.done",+ "response.completed",+ ]+ assert [event["item_id"] for _, event in events if "item_id" in event] == [+ item_id,+ item_id,+ ]+ assert [+ _object_dict(event["item"])["id"] for _, event in events if "item" in event+ ] == [item_id, item_id]assert final_output == [{- "id": _object_dict(final_output[0])["id"],+ "id": item_id,"type": "custom_tool_call","status": "completed","call_id": "call_patch",diff --git a/tests/providers/test_openai_responses_transport.py b/tests/providers/test_openai_responses_transport.pyindex ca4c4e29..cb9a45ae 100644--- a/tests/providers/test_openai_responses_transport.py+++ b/tests/providers/test_openai_responses_transport.py@@ -10,6 +10,7 @@ import pytestfrom openai import AsyncOpenAIfrom free_claude_code.application.errors import InvalidRequestError+from free_claude_code.core.anthropic import ReasoningReplayModefrom free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.anthropic.stream_contracts import (assert_anthropic_stream_contract,@@ -21,8 +22,13 @@ from free_claude_code.core.failures import ExecutionFailure, FailureKindfrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,ResponsesToolPolicy,+ build_responses_chat_request,)from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy+from free_claude_code.providers.openai_chat.stream_output import (+ ChatStreamUsage,+ ResponsesChatStreamOutput,+)from free_claude_code.providers.openai_responses import OpenAIResponsesTransportfrom tests.providers.support import REASONING_ON, immediate_admission@@ -337,7 +343,7 @@ async def test_concurrent_requests_do_not_share_tool_identities() -> None:body = json.loads(request.content)call = {"type": "function_call",- "id": "same_item",+ "id": "fc_same_item","call_id": "same_call","name": "edit","arguments": '{"input":"patch"}',@@ -358,17 +364,24 @@ async def test_concurrent_requests_do_not_share_tool_identities() -> None:{"type": "response.function_call_arguments.delta","sequence_number": 1,- "item_id": "same_item",+ "item_id": "fc_same_item","output_index": 0,"delta": call["arguments"],},{- "type": "response.output_item.done",+ "type": "response.function_call_arguments.done","sequence_number": 2,+ "item_id": "fc_same_item",+ "output_index": 0,+ "arguments": call["arguments"],+ },+ {+ "type": "response.output_item.done",+ "sequence_number": 3,"output_index": 0,"item": call,},- {"type": "response.completed", "sequence_number": 3, "response": response},+ {"type": "response.completed", "sequence_number": 4, "response": response},)return httpx2.Response(200,@@ -401,8 +414,29 @@ async def test_concurrent_requests_do_not_share_tool_identities() -> None:]assert custom_events[-1].data["response"]["output"][0]["type"] == "custom_tool_call"assert function_events[-1].data["response"]["output"][0]["type"] == "function_call"+ for events, item_id in (+ (custom_events, "ctc_same_item"),+ (function_events, "fc_same_item"),+ ):+ assert events[-1].data["response"]["output"][0]["id"] == item_id+ assert [+ event.data["item"]["id"] for event in events if "item" in event.data+ ] == [+ item_id,+ item_id,+ ]+ assert [+ event.data["item_id"] for event in events if "item_id" in event.data+ ] == [+ item_id,+ item_id,+ ]assert not any(- event.event == "response.function_call_arguments.delta"+ event.event+ in {+ "response.function_call_arguments.delta",+ "response.function_call_arguments.done",+ }for event in custom_events)assert any(@@ -411,6 +445,100 @@ async def test_concurrent_requests_do_not_share_tool_identities() -> None:)+ ("legacy", "adapt_custom", "expected_type", "keep_id"),+ [+ (False, False, "custom_tool_call", True),+ (True, False, "custom_tool_call", False),+ (False, True, "function_call", False),+ (True, True, "function_call", True),+ ],+)+async def test_chat_custom_history_replays_with_native_wire_compatible_ids(+ legacy: bool, adapt_custom: bool, expected_type: str, keep_id: bool+) -> None:+ request = OpenAIResponsesRequest(+ model="example", input="edit", tools=[{"type": "custom", "name": "edit"}]+ )+ prepared = build_responses_chat_request(+ request, reasoning_replay=ReasoningReplayMode.DISABLED+ )+ writer = ResponsesChatStreamOutput(prepared.tool_adapter, input_tokens=1)+ frames = writer.start_events()+ frames.append(writer.start_tool_block(0, "call_edit", "edit"))+ frames.append(writer.emit_tool_delta(0, '{"input":"patch"}'))+ frames.extend(+ writer.finish_success(+ stop_reason="tool_calls",+ usage=ChatStreamUsage(input_tokens=3, output_tokens=2),+ )+ )+ item = parse_sse_text("".join(frames))[-1].data["response"]["output"][0]+ if legacy:+ item["id"] = "fc_legacy"+ continuation = OpenAIResponsesRequest(+ model="example",+ tools=request.tools,+ input=[+ item,+ {+ "type": "custom_tool_call_output",+ "call_id": "call_edit",+ "output": "done",+ },+ ],+ )+ original = continuation.model_dump()+ captured: list[dict[str, object]] = []++ def handler(request: httpx2.Request) -> httpx2.Response:+ captured.append(json.loads(request.content))+ return httpx2.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ text=_sse(_completed_event()),+ )++ client = _client(handler)+ try:+ await _collect_native(+ _transport(+ client,+ tool_policy=ResponsesToolPolicy(custom_tools_as_functions=adapt_custom),+ ),+ continuation,+ )+ finally:+ await client.close()+ assert len(captured) == 1+ history = captured[0]["input"]+ assert isinstance(history, list)+ call, result = history+ assert call["type"] == expected_type+ assert call["call_id"] == "call_edit"+ assert call["name"] == "edit"+ if keep_id:+ assert call["id"] == item["id"]+ else:+ assert "id" not in call+ if adapt_custom:+ assert json.loads(call["arguments"]) == {"input": "patch"}+ assert result == {+ "type": "function_call_output",+ "call_id": "call_edit",+ "output": "done",+ }+ else:+ assert call["input"] == "patch"+ assert result == {+ "type": "custom_tool_call_output",+ "call_id": "call_edit",+ "output": "done",+ }+ assert continuation.model_dump() == original++@pytest.mark.asyncioasync def test_native_responses_preserves_request_and_upstream_event_identity() -> None:captured: list[dict[str, object]] = []diff --git a/uv.lock b/uv.lockindex 48014ecf..ea892b77 100644--- a/uv.lock+++ b/uv.lock@@ -599,7 +599,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.2.39"+version = "6.2.40"source = { editable = "." }dependencies = [{ name = "aiohttp" },