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
Keep tool names portable across OpenAI transports (#1309)
Ali Khokharefaa27243d76
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex a12ffa8d..08ff569c 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -688,6 +688,15 @@ client-specific recovery phrase.Providers call the OpenAI request policy for Anthropic-to-OpenAI conversion,reasoning replay selection, `extra_body`, and chat-completion field normalization.+The SDK-free `OpenAIToolNameCodec` in+[core/anthropic/](src/free_claude_code/core/anthropic/) owns reversible+translation from client tool identities to OpenAI's portable function-name+grammar. OpenAI Chat and upstream Responses adapters apply that codec only to+their explicit declaration, forced-choice, and replay fields, then restore the+original identity before Anthropic tool state or schema validation. Valid names+remain unchanged, while deterministic aliases keep retries, replay, and+append-only prompt prefixes stable. This is target-protocol conversion, never a+provider or model capability switch.Specialized provider packages remain only for true upstream quirks such asGemini thought signatures, NIM tool-schema aliases, retry downgrades, and NVCFdeployment-failure classification, or DeepSeek attachment/tool/thinking@@ -733,7 +742,9 @@ request schemas, and converts it into ordinary OpenAI tool-call deltas beforethe shared stream runner can commit visible text. Native structured tool-calldeltas remain authoritative when both forms appear; incomplete or invalidnative markup is a retryable upstream protocol failure rather than user-visible-assistant text.+assistant text. NIM argument-property aliases remain keyed by the original tool+identity: shared OpenAI output restores the tool name first, then NIM restores+arguments and validates the original schema.### Reasoning Ownership@@ -969,6 +980,11 @@ tools with a single string `input` field, and restores `custom_tool_call`,Responses edge. Text or grammar format metadata is preserved as model guidance;FCC does not validate custom-tool grammars.+Client-facing Responses tool identity mapping is distinct from upstream wire+portability. Namespaces and custom-tool identities are restored at the public+Responses edge; the OpenAI tool-name codec operates beneath that mapping only+while the canonical Anthropic request crosses an OpenAI upstream transport.+Responses reasoning is handled as lossless protocol conversion before providerpolicy. The adapter preserves `reasoning.effort` in Anthropic `output_config`;the application reasoning boundary then interprets `none` as off and preservesdiff --git a/pyproject.toml b/pyproject.tomlindex 5e7f5caf..9f11d048 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "4.16.0"+version = "4.16.1"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/anthropic/__init__.py b/src/free_claude_code/core/anthropic/__init__.pyindex 03e22421..88b17b30 100644--- a/src/free_claude_code/core/anthropic/__init__.py+++ b/src/free_claude_code/core/anthropic/__init__.py@@ -35,6 +35,7 @@ from .models import (Tool,Usage,)+from .openai_tool_names import OpenAIToolNameCodecfrom .request_serialization import dump_messages_request, serialize_tool_result_contentfrom .request_snapshot import anthropic_request_snapshotfrom .sse_aggregation import aggregate_anthropic_sse_to_message@@ -70,6 +71,7 @@ __all__ = ["MessagesRequest","MessagesResponse","OpenAIConversionError",+ "OpenAIToolNameCodec","ReasoningReplayMode","StreamBlockLedger","SystemContent",diff --git a/src/free_claude_code/core/anthropic/openai_tool_names.py b/src/free_claude_code/core/anthropic/openai_tool_names.pynew file mode 100644index 00000000..9f1a2e5c--- /dev/null+++ b/src/free_claude_code/core/anthropic/openai_tool_names.py@@ -0,0 +1,124 @@+"""Reversible tool names for Anthropic-to-OpenAI protocol conversion."""++import hashlib+import re+from collections.abc import Iterable+from dataclasses import dataclass++from .content import get_block_attr, get_block_type+from .models import MessagesRequest++OPENAI_TOOL_NAME_MAX_LENGTH = 64+_ALIAS_DIGEST_LENGTH = 16+_PORTABLE_TOOL_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")+_INVALID_TOOL_NAME_CHARACTERS = re.compile(r"[^A-Za-z0-9_-]+")+++@dataclass(frozen=True, slots=True)+class OpenAIToolNameCodec:+ """Map non-portable client tool names to deterministic OpenAI aliases."""++ _original_to_alias: dict[str, str]+ _alias_to_original: dict[str, str]+ _unchanged_names: frozenset[str]++ @classmethod+ def from_request(cls, request: MessagesRequest) -> OpenAIToolNameCodec:+ """Build the codec from every tool identity carried by one request."""+ return cls.from_names(_request_tool_names(request))++ @classmethod+ def from_names(cls, names: Iterable[str]) -> OpenAIToolNameCodec:+ """Build order-independent aliases for the supplied non-empty names."""+ unique_names = {name for name in names if name}+ portable_names = {+ name for name in unique_names if _PORTABLE_TOOL_NAME.fullmatch(name)+ }+ reserved = set(portable_names)+ original_to_alias: dict[str, str] = {}+ alias_to_original: dict[str, str] = {}++ for name in sorted(unique_names - portable_names):+ alias = _unique_alias(name, reserved)+ reserved.add(alias)+ original_to_alias[name] = alias+ alias_to_original[alias] = name++ return cls(+ original_to_alias,+ alias_to_original,+ frozenset(portable_names),+ )++ @property+ def has_aliases(self) -> bool:+ """Return whether this request needs any tool-name translation."""+ return bool(self._original_to_alias)++ def encode(self, name: str) -> str:+ """Return the OpenAI wire name for one client name."""+ return self._original_to_alias.get(name, name)++ def decode(self, name: str) -> str:+ """Return the original client name for one known wire alias."""+ return self._alias_to_original.get(name, name)++ def is_alias(self, value: str) -> bool:+ """Return whether value is one complete alias generated for this request."""+ return value in self._alias_to_original++ def is_unchanged_name(self, value: str) -> bool:+ """Return whether value is one complete name sent upstream unchanged."""+ return value in self._unchanged_names++ def is_alias_prefix(self, value: str) -> bool:+ """Return whether value is an incomplete prefix of a generated alias."""+ return bool(value) and any(+ alias != value and alias.startswith(value)+ for alias in self._alias_to_original+ )+++def _request_tool_names(request: MessagesRequest) -> Iterable[str]:+ for tool in request.tools or ():+ yield tool.name++ tool_choice = request.tool_choice+ if isinstance(tool_choice, dict):+ choice_type = tool_choice.get("type")+ if choice_type == "tool":+ name = tool_choice.get("name")+ if isinstance(name, str):+ yield name+ elif choice_type == "function":+ function = tool_choice.get("function")+ if isinstance(function, dict):+ name = function.get("name")+ if isinstance(name, str):+ yield name++ for message in request.messages:+ if message.role != "assistant" or not isinstance(message.content, list):+ continue+ for block in message.content:+ if get_block_type(block) != "tool_use":+ continue+ name = get_block_attr(block, "name")+ if isinstance(name, str):+ yield name+++def _unique_alias(name: str, reserved: set[str]) -> str:+ readable = _INVALID_TOOL_NAME_CHARACTERS.sub("_", name).strip("_-") or "tool"+ max_readable_length = OPENAI_TOOL_NAME_MAX_LENGTH - _ALIAS_DIGEST_LENGTH - 1+ readable = readable[:max_readable_length].rstrip("_-") or "tool"+ attempt = 0+ while True:+ digest_input = name if attempt == 0 else f"{name}\0{attempt}"+ digest = hashlib.sha256(digest_input.encode("utf-8")).hexdigest()[+ :_ALIAS_DIGEST_LENGTH+ ]+ alias = f"{readable}_{digest}"+ if alias not in reserved:+ return alias+ attempt += 1diff --git a/src/free_claude_code/core/openai_responses/provider_input.py b/src/free_claude_code/core/openai_responses/provider_input.pyindex 88344969..9375b187 100644--- a/src/free_claude_code/core/openai_responses/provider_input.py+++ b/src/free_claude_code/core/openai_responses/provider_input.py@@ -5,6 +5,7 @@ from typing import Anyfrom free_claude_code.core.anthropic.content import get_block_attr, get_block_typefrom free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.anthropic.openai_tool_names import OpenAIToolNameCodecfrom free_claude_code.core.anthropic.request_serialization import (serialize_tool_result_content,)@@ -21,6 +22,7 @@ def build_responses_provider_request("""Build a stateless Responses request without silently dropping fields."""_validate_supported_request(request)+ tool_names = OpenAIToolNameCodec.from_request(request)instructions = _system_text(request)input_items: list[dict[str, Any]] = []for message in request.messages:@@ -33,6 +35,7 @@ def build_responses_provider_request(_assistant_items(message.content,reasoning_content=message.reasoning_content,+ tool_names=tool_names,))else:@@ -64,7 +67,7 @@ def build_responses_provider_request(body["tools"] = [{"type": "function",- "name": tool.name,+ "name": tool_names.encode(tool.name),"description": tool.description,"parameters": tool.input_schema or {"type": "object", "properties": {}},"strict": False,@@ -72,7 +75,7 @@ def build_responses_provider_request(for tool in request.tools]if request.tool_choice is not None:- body["tool_choice"] = _tool_choice(request.tool_choice)+ body["tool_choice"] = _tool_choice(request.tool_choice, tool_names=tool_names)if reasoning_config := _reasoning_config(reasoning):body["reasoning"] = reasoning_configreturn body@@ -124,6 +127,7 @@ def _assistant_items(content: Any,*,reasoning_content: str | None,+ tool_names: OpenAIToolNameCodec,) -> list[dict[str, Any]]:if isinstance(content, str):items = [_assistant_message([{"type": "output_text", "text": content}])]@@ -172,7 +176,7 @@ def _assistant_items({"type": "function_call","call_id": str(get_block_attr(block, "id", "")),- "name": str(get_block_attr(block, "name", "")),+ "name": tool_names.encode(str(get_block_attr(block, "name", ""))),"arguments": json.dumps(get_block_attr(block, "input", {}),ensure_ascii=False,@@ -292,7 +296,11 @@ def _user_message(content: list[dict[str, Any]]) -> dict[str, Any]:return {"type": "message", "role": "user", "content": content}-def _tool_choice(choice: dict[str, Any]) -> str | dict[str, str]:+def _tool_choice(+ choice: dict[str, Any],+ *,+ tool_names: OpenAIToolNameCodec,+) -> str | dict[str, str]:choice_type = choice.get("type")if choice_type in {"auto", "none"}:return str(choice_type)@@ -302,7 +310,7 @@ def _tool_choice(choice: dict[str, Any]) -> str | dict[str, str]:name = choice.get("name")if not isinstance(name, str) or not name:raise ResponsesConversionError("Forced tool choice requires a tool name.")- return {"type": "function", "name": name}+ return {"type": "function", "name": tool_names.encode(name)}raise ResponsesConversionError(f"Unsupported tool_choice type {choice_type!r}.")diff --git a/src/free_claude_code/core/openai_responses/provider_stream.py b/src/free_claude_code/core/openai_responses/provider_stream.pyindex a270f437..ae5cce43 100644--- a/src/free_claude_code/core/openai_responses/provider_stream.py+++ b/src/free_claude_code/core/openai_responses/provider_stream.py@@ -3,6 +3,7 @@from dataclasses import dataclassfrom typing import Any+from free_claude_code.core.anthropic.openai_tool_names import OpenAIToolNameCodecfrom free_claude_code.core.anthropic.streaming import AnthropicStreamLedger@@ -35,6 +36,7 @@ class ResponsesProviderStream:model: str,input_tokens: int,log_raw_events: bool = False,+ tool_names: OpenAIToolNameCodec | None = None,) -> None:self.ledger = AnthropicStreamLedger(message_id,@@ -44,6 +46,7 @@ class ResponsesProviderStream:)self.completed = Falseself.generated_output = False+ self._tool_names = tool_names or OpenAIToolNameCodec.from_names(())self._tools: dict[str, _ToolState] = {}self._encrypted_reasoning: dict[str, str] = {}@@ -85,7 +88,7 @@ class ResponsesProviderStream:self._tools[item_id] = _ToolState(tool_index=len(self._tools),call_id=_string(item.get("call_id")) or item_id,- name=_string(item.get("name")),+ name=self._tool_names.decode(_string(item.get("name"))),)if item.get("type") == "reasoning" and item_id:encrypted = item.get("encrypted_content")@@ -144,11 +147,11 @@ class ResponsesProviderStream:state = _ToolState(tool_index=len(self._tools),call_id=_string(item.get("call_id")) or item_id,- name=_string(item.get("name")),+ name=self._tool_names.decode(_string(item.get("name"))),)self._tools[item_id] = stateif not state.name:- state.name = _string(item.get("name"))+ state.name = self._tool_names.decode(_string(item.get("name")))events = list(self.ledger.close_content_blocks())events.extend(self._ensure_tool_started(state))arguments = item.get("arguments")diff --git a/src/free_claude_code/providers/openai_chat/provider.py b/src/free_claude_code/providers/openai_chat/provider.pyindex 27c4ab70..66c2725f 100644--- a/src/free_claude_code/providers/openai_chat/provider.py+++ b/src/free_claude_code/providers/openai_chat/provider.py@@ -15,6 +15,7 @@ from free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.core.anthropic import (ContentType,HeuristicToolParser,+ OpenAIToolNameCodec,ThinkTagParser,)from free_claude_code.core.anthropic.models import MessagesRequest@@ -361,6 +362,7 @@ class _OpenAIChatStreamRunner:request.model if response_model is None else response_model)self._reasoning = reasoning+ self._tool_names = OpenAIToolNameCodec.from_request(request)self._message_id = f"msg_{uuid.uuid4()}"self._tool_calls = OpenAIToolCallAssembler(record_extra_content=provider._record_tool_call_extra_content@@ -408,6 +410,7 @@ class _OpenAIChatStreamRunner:usage_info = Nonetool_argument_aliases: dict[str, dict[str, str]] = {}tool_argument_alias_buffers: dict[int, str] = {}+ tool_name_buffers: dict[int, str] = {}while True:structured_reasoning = (@@ -505,7 +508,9 @@ class _OpenAIChatStreamRunner:for tool_use in detected_tools:for event in iter_heuristic_tool_use_sse(- ledger, tool_use+ ledger,+ tool_use,+ tool_names=self._tool_names,):for out_event in hold_event(event):yield out_event@@ -528,6 +533,8 @@ class _OpenAIChatStreamRunner:for event in self._tool_calls.process_tool_call(tool_call_info,ledger,+ tool_names=self._tool_names,+ tool_name_buffers=tool_name_buffers,tool_argument_aliases=tool_argument_aliases,tool_argument_alias_buffers=tool_argument_alias_buffers,):@@ -538,6 +545,13 @@ class _OpenAIChatStreamRunner:raise TruncatedProviderStreamError("Provider stream ended without finish_reason.")+ if any(+ not self._tool_names.is_unchanged_name(name)+ for name in tool_name_buffers.values()+ ):+ raise TruncatedProviderStreamError(+ "Provider stream ended with an incomplete tool name."+ )breakexcept asyncio.CancelledError, GeneratorExit:@@ -584,6 +598,7 @@ class _OpenAIChatStreamRunner:usage_info = Nonetool_argument_aliases = {}tool_argument_alias_buffers = {}+ tool_name_buffers = {}continueif decision.action == RecoveryFailureAction.MIDSTREAM_RECOVERY:@@ -683,10 +698,24 @@ class _OpenAIChatStreamRunner:yield eventfor tool_use in heuristic_parser.flush():- for event in iter_heuristic_tool_use_sse(ledger, tool_use):+ for event in iter_heuristic_tool_use_sse(+ ledger,+ tool_use,+ tool_names=self._tool_names,+ ):for out_event in hold_event(event):yield out_event+ for event in self._tool_calls.flush_tool_name_buffers(+ ledger,+ tool_names=self._tool_names,+ tool_name_buffers=tool_name_buffers,+ tool_argument_aliases=tool_argument_aliases,+ tool_argument_alias_buffers=tool_argument_alias_buffers,+ ):+ for out_event in hold_event(event):+ yield out_event+has_emitted_tool = ledger.has_emitted_tool_block()has_content_blocks = (ledger.blocks.text_index != -1@@ -803,6 +832,7 @@ class _OpenAIChatStreamRunner:completed_tool_calls = tool_calls.completed_calls(self._request,+ tool_names=self._tool_names,tool_argument_aliases=self._provider._tool_argument_aliases(accepted_body),diff --git a/src/free_claude_code/providers/openai_chat/request_policy.py b/src/free_claude_code/providers/openai_chat/request_policy.pyindex d81e0c58..2d15a395 100644--- a/src/free_claude_code/providers/openai_chat/request_policy.py+++ b/src/free_claude_code/providers/openai_chat/request_policy.py@@ -8,7 +8,11 @@ from typing import Any, Literalfrom loguru import loggerfrom free_claude_code.application.errors import InvalidRequestError-from free_claude_code.core.anthropic import ReasoningReplayMode, build_base_request_body+from free_claude_code.core.anthropic import (+ OpenAIToolNameCodec,+ ReasoningReplayMode,+ build_base_request_body,+)from free_claude_code.core.anthropic.conversion import OpenAIConversionErrorfrom free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.reasoning import ReasoningPolicy@@ -77,6 +81,8 @@ def build_openai_chat_request_body(for postprocess in postprocessors:postprocess(body, request_data, reasoning)+ _encode_openai_tool_names(body, OpenAIToolNameCodec.from_request(request_data))+logger.debug("{}_REQUEST: conversion done model={} msgs={} tools={}",policy.provider_name,@@ -87,6 +93,59 @@ def build_openai_chat_request_body(return body+def _encode_openai_tool_names(body: dict[str, Any], codec: OpenAIToolNameCodec) -> None:+ """Encode only canonical OpenAI Chat tool-name locations."""+ if not codec.has_aliases:+ return++ tools = body.get("tools")+ if isinstance(tools, list):+ for tool in tools:+ if not isinstance(tool, dict):+ continue+ function = tool.get("function")+ if not isinstance(function, dict):+ continue+ name = function.get("name")+ if isinstance(name, str):+ function["name"] = codec.encode(name)++ messages = body.get("messages")+ if isinstance(messages, list):+ for message in messages:+ if not isinstance(message, dict):+ continue+ tool_calls = message.get("tool_calls")+ if not isinstance(tool_calls, list):+ continue+ for tool_call in tool_calls:+ if not isinstance(tool_call, dict):+ continue+ function = tool_call.get("function")+ if not isinstance(function, dict):+ continue+ name = function.get("name")+ if isinstance(name, str):+ function["name"] = codec.encode(name)++ tool_choice = body.get("tool_choice")+ if not isinstance(tool_choice, dict):+ return+ function = tool_choice.get("function")+ if not isinstance(function, dict):+ return+ name = function.get("name")+ if not isinstance(name, str):+ return+ encoded = codec.encode(name)+ if encoded == name:+ return+ body["tool_choice"] = {+ **tool_choice,+ "function": {**function, "name": encoded},+ }++def _apply_common_openai_chat_policy(body: dict[str, Any], policy: OpenAIChatRequestPolicy) -> None:diff --git a/src/free_claude_code/providers/openai_chat/tool_calls.py b/src/free_claude_code/providers/openai_chat/tool_calls.pyindex 562a94ee..58a8025d 100644--- a/src/free_claude_code/providers/openai_chat/tool_calls.py+++ b/src/free_claude_code/providers/openai_chat/tool_calls.py@@ -6,6 +6,7 @@ from collections.abc import Callable, Iteratorfrom dataclasses import dataclass, fieldfrom typing import Any+from free_claude_code.core.anthropic import OpenAIToolNameCodecfrom free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.anthropic.streaming import (AnthropicStreamLedger,@@ -62,6 +63,7 @@ class OpenAIToolCallCollector:self,request: MessagesRequest,*,+ tool_names: OpenAIToolNameCodec | None = None,tool_argument_aliases: dict[str, dict[str, str]] | None = None,) -> tuple[dict[str, Any], ...] | None:"""Return complete schema-valid calls, or None when output is incomplete."""@@ -69,7 +71,8 @@ class OpenAIToolCallCollector:completed: list[dict[str, Any]] = []for index in sorted(self._calls):state = self._calls[index]- name = state.name.strip()+ wire_name = state.name.strip()+ name = tool_names.decode(wire_name) if tool_names is not None else wire_nameif not name or name not in schemas:return Nonearguments = "".join(state.argument_parts)@@ -101,9 +104,17 @@ class OpenAIToolCallCollector:def iter_heuristic_tool_use_sse(- ledger: AnthropicStreamLedger, tool_use: dict[str, Any]+ ledger: AnthropicStreamLedger,+ tool_use: dict[str, Any],+ *,+ tool_names: OpenAIToolNameCodec | None = None,) -> Iterator[str]:"""Emit SSE for one heuristic tool_use block."""+ name = tool_use.get("name")+ if tool_names is not None and isinstance(name, str):+ decoded_name = tool_names.decode(name)+ if decoded_name != name:+ tool_use = {**tool_use, "name": decoded_name}if tool_use.get("name") == "Task" and isinstance(tool_use.get("input"), dict):task_input = tool_use["input"]if task_input.get("run_in_background") is not False:@@ -187,6 +198,8 @@ class OpenAIToolCallAssembler:tc: dict[str, Any],ledger: AnthropicStreamLedger,*,+ tool_names: OpenAIToolNameCodec | None = None,+ tool_name_buffers: dict[int, str] | None = None,tool_argument_aliases: dict[str, dict[str, str]] | None = None,tool_argument_alias_buffers: dict[int, str] | None = None,) -> Iterator[str]:@@ -212,8 +225,15 @@ class OpenAIToolCallAssembler:if extra_content:ledger.blocks.set_tool_extra_content(tc_index, extra_content)- if incoming_name is not None:- ledger.blocks.register_tool_name(tc_index, incoming_name)+ if isinstance(incoming_name, str) and incoming_name:+ resolved_name = _decode_streamed_tool_name(+ incoming_name,+ tool_index=tc_index,+ tool_names=tool_names,+ buffers=tool_name_buffers,+ )+ if resolved_name is not None:+ ledger.blocks.register_tool_name(tc_index, resolved_name)state = ledger.blocks.tool_states.get(tc_index)resolved_id = (state.tool_id if state and state.tool_id else None) or tc.get(@@ -271,6 +291,29 @@ class OpenAIToolCallAssembler:for tool_index, out in ledger.blocks.flush_task_arg_buffers():yield ledger.emit_tool_delta(tool_index, out)+ def flush_tool_name_buffers(+ self,+ ledger: AnthropicStreamLedger,+ *,+ tool_names: OpenAIToolNameCodec,+ tool_name_buffers: dict[int, str],+ tool_argument_aliases: dict[str, dict[str, str]],+ tool_argument_alias_buffers: dict[int, str],+ ) -> Iterator[str]:+ """Resolve names held only because they also prefix a generated alias."""+ for tool_index, name in list(tool_name_buffers.items()):+ tool_name_buffers.pop(tool_index, None)+ yield from self.process_tool_call(+ {+ "index": tool_index,+ "function": {"name": name, "arguments": ""},+ },+ ledger,+ tool_names=tool_names,+ tool_argument_aliases=tool_argument_aliases,+ tool_argument_alias_buffers=tool_argument_alias_buffers,+ )+def flush_tool_argument_alias_buffers(self,ledger: AnthropicStreamLedger,@@ -381,3 +424,26 @@ def _merge_tool_name(existing: str, incoming: str) -> str:if existing.startswith(incoming):return existingreturn "".join((existing, incoming))+++def _decode_streamed_tool_name(+ incoming: str,+ *,+ tool_index: int,+ tool_names: OpenAIToolNameCodec | None,+ buffers: dict[int, str] | None,+) -> str | None:+ if tool_names is None or not tool_names.has_aliases:+ return incoming+ if buffers is None:+ return tool_names.decode(incoming)++ combined = _merge_tool_name(buffers.get(tool_index, ""), incoming)+ if tool_names.is_alias(combined):+ buffers.pop(tool_index, None)+ return tool_names.decode(combined)+ if tool_names.is_alias_prefix(combined):+ buffers[tool_index] = combined+ return None+ buffers.pop(tool_index, None)+ return tool_names.decode(combined)diff --git a/src/free_claude_code/providers/openai_codex/provider.py b/src/free_claude_code/providers/openai_codex/provider.pyindex fac450da..1c44b1ad 100644--- a/src/free_claude_code/providers/openai_codex/provider.py+++ b/src/free_claude_code/providers/openai_codex/provider.py@@ -12,6 +12,7 @@ import httpxfrom free_claude_code.application.errors import InvalidRequestErrorfrom free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.anthropic.openai_tool_names import OpenAIToolNameCodecfrom free_claude_code.core.diagnostics import (ERROR_DETAIL_DISPLAY_CAP_BYTES,attach_upstream_error_body,@@ -134,12 +135,14 @@ class OpenAICodexProvider(BaseProvider):) -> AsyncIterator[str]:"""Stream Responses output in Anthropic Messages format."""+ tool_names = OpenAIToolNameCodec.from_request(request)body = self._build_body(request, reasoning=reasoning)return self._run_stream(body,input_tokens=input_tokens,request_id=request_id,response_model=response_model or request.model,+ tool_names=tool_names,)@staticmethod@@ -160,6 +163,7 @@ class OpenAICodexProvider(BaseProvider):input_tokens: int,request_id: str | None,response_model: str,+ tool_names: OpenAIToolNameCodec,) -> AsyncIterator[str]:retry_session = self._admission.new_retry_session(request_id=request_id)recovery = RecoveryController()@@ -184,6 +188,7 @@ class OpenAICodexProvider(BaseProvider):model=response_model,input_tokens=input_tokens,log_raw_events=self._config.log_raw_sse_events,+ tool_names=tool_names,)for event in stream.start():for held in recovery.push(event):diff --git a/tests/core/anthropic/test_openai_tool_names.py b/tests/core/anthropic/test_openai_tool_names.pynew file mode 100644index 00000000..908aae01--- /dev/null+++ b/tests/core/anthropic/test_openai_tool_names.py@@ -0,0 +1,159 @@+import re++from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.anthropic.openai_tool_names import OpenAIToolNameCodec++_PORTABLE_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")+++def _request(*names: str) -> MessagesRequest:+ return MessagesRequest.model_validate(+ {+ "model": "test-model",+ "messages": [{"role": "user", "content": "hello"}],+ "tools": [+ {+ "name": name,+ "description": "test",+ "input_schema": {"type": "object"},+ }+ for name in names+ ],+ }+ )+++def test_portable_names_at_boundaries_remain_unchanged() -> None:+ names = ("x", "A" * 64, "read_file-2")+ codec = OpenAIToolNameCodec.from_request(_request(*names))++ assert codec.has_aliases is False+ assert [codec.encode(name) for name in names] == list(names)+ assert [codec.decode(name) for name in names] == list(names)+ assert all(codec.is_unchanged_name(name) for name in names)+++def test_long_and_invalid_names_round_trip_through_portable_aliases() -> None:+ names = (+ "x" * 65,+ "mcp__server__" + "tool" * 23,+ "mcp.server/tool name",+ "工具名称",+ )+ codec = OpenAIToolNameCodec.from_request(_request(*names))++ assert codec.has_aliases is True+ for name in names:+ alias = codec.encode(name)+ assert alias != name+ assert _PORTABLE_NAME.fullmatch(alias)+ assert codec.decode(alias) == name+++def test_reported_102_character_name_becomes_portable() -> None:+ name = "mcp__issue_1307__" + "x" * 85+ assert len(name) == 102++ alias = OpenAIToolNameCodec.from_request(_request(name)).encode(name)++ assert len(alias) <= 64+ assert _PORTABLE_NAME.fullmatch(alias)+++def test_aliases_are_unique_for_names_with_the_same_long_prefix() -> None:+ common = "mcp__one_very_long_server_namespace__" + "x" * 50+ names = (f"{common}_first", f"{common}_second")+ codec = OpenAIToolNameCodec.from_request(_request(*names))++ assert codec.encode(names[0]) != codec.encode(names[1])+++def test_aliases_are_order_independent() -> None:+ names = (+ "mcp__server_a__" + "x" * 70,+ "mcp__server_b__" + "y" * 70,+ "normal_tool",+ )+ forward = OpenAIToolNameCodec.from_request(_request(*names))+ reverse = OpenAIToolNameCodec.from_request(_request(*reversed(names)))++ assert {name: forward.encode(name) for name in names} == {+ name: reverse.encode(name) for name in names+ }+++def test_alias_does_not_shadow_an_existing_portable_name() -> None:+ long_name = "mcp__collision_candidate__" + "x" * 70+ first = OpenAIToolNameCodec.from_request(_request(long_name))+ first_alias = first.encode(long_name)++ codec = OpenAIToolNameCodec.from_request(_request(long_name, first_alias))++ assert codec.encode(first_alias) == first_alias+ assert codec.encode(long_name) != first_alias+ assert codec.decode(codec.encode(long_name)) == long_name+++def test_codec_collects_forced_choice_and_history_names_without_mutation() -> None:+ declared = "safe_tool"+ forced = "mcp__forced__" + "f" * 70+ historical = "mcp__historical__" + "h" * 70+ request = MessagesRequest.model_validate(+ {+ "model": "test-model",+ "messages": [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "call_1",+ "name": historical,+ "input": {},+ }+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "call_1",+ "content": "done",+ }+ ],+ },+ ],+ "tools": [{"name": declared, "input_schema": {"type": "object"}}],+ "tool_choice": {"type": "tool", "name": forced},+ }+ )+ snapshot = request.model_dump()++ codec = OpenAIToolNameCodec.from_request(request)++ assert codec.encode(declared) == declared+ assert codec.decode(codec.encode(forced)) == forced+ assert codec.decode(codec.encode(historical)) == historical+ assert request.model_dump() == snapshot+++def test_only_generated_aliases_are_decoded_and_prefixes_are_detected() -> None:+ name = "mcp__fragmented__" + "x" * 70+ codec = OpenAIToolNameCodec.from_request(_request(name))+ alias = codec.encode(name)++ assert codec.is_alias(alias) is True+ assert codec.is_alias(alias[:20]) is False+ assert codec.is_unchanged_name(alias) is False+ assert codec.is_alias_prefix(alias[:20]) is True+ assert codec.is_alias_prefix(alias) is False+ assert codec.is_alias_prefix("unrelated") is False+ assert codec.decode("unknown_tool") == "unknown_tool"+++def test_empty_name_retains_existing_invalid_identity() -> None:+ codec = OpenAIToolNameCodec.from_request(_request(""))++ assert codec.encode("") == ""+ assert codec.decode("") == ""diff --git a/tests/core/openai_responses/test_provider_input.py b/tests/core/openai_responses/test_provider_input.pyindex c6204b6e..29dd56fe 100644--- a/tests/core/openai_responses/test_provider_input.py+++ b/tests/core/openai_responses/test_provider_input.py@@ -107,6 +107,66 @@ def test_build_responses_provider_request_preserves_multiturn_protocol() -> None}+def test_responses_provider_request_uses_one_portable_tool_alias() -> None:+ original = "mcp__responses_provider__" + "x" * 70+ request = MessagesRequest.model_validate(+ {+ "model": "gpt-test",+ "messages": [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "call_1",+ "name": original,+ "input": {"q": "value"},+ }+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "call_1",+ "content": "done",+ }+ ],+ },+ ],+ "tools": [+ {+ "name": original,+ "description": "Long tool",+ "input_schema": {"type": "object"},+ },+ {"name": "safe_tool", "input_schema": {"type": "object"}},+ ],+ "tool_choice": {"type": "tool", "name": original},+ }+ )+ snapshot = request.model_dump()++ body = build_responses_provider_request(+ request,+ reasoning=ReasoningPolicy.provider_default(),+ )++ alias = body["tools"][0]["name"]+ assert alias != original+ assert len(alias) <= 64+ assert body["tools"][1]["name"] == "safe_tool"+ assert body["tool_choice"] == {"type": "function", "name": alias}+ function_call = next(+ item for item in body["input"] if item["type"] == "function_call"+ )+ assert function_call["name"] == alias+ assert function_call["call_id"] == "call_1"+ assert function_call["arguments"] == '{"q":"value"}'+ assert request.model_dump() == snapshot++def test_responses_round_trip_preserves_encrypted_reasoning_and_tool_ids() -> None:adapter = OpenAIResponsesAdapter()ingress = OpenAIResponsesRequest.model_validate(diff --git a/tests/core/openai_responses/test_provider_stream.py b/tests/core/openai_responses/test_provider_stream.pyindex d1318b5b..21c5ae05 100644--- a/tests/core/openai_responses/test_provider_stream.py+++ b/tests/core/openai_responses/test_provider_stream.py@@ -1,5 +1,6 @@import pytest+from free_claude_code.core.anthropic.openai_tool_names import OpenAIToolNameCodecfrom free_claude_code.core.anthropic.stream_contracts import (assert_anthropic_stream_contract,parse_sse_text,@@ -151,3 +152,68 @@ def test_responses_provider_stream_surfaces_failed_event() -> None:)assert exc_info.value.code == "server_error"+++def test_responses_provider_stream_restores_added_and_done_only_tool_names() -> None:+ originals = (+ "mcp__responses_added__" + "x" * 70,+ "mcp__responses_done__" + "y" * 70,+ )+ codec = OpenAIToolNameCodec.from_names(originals)+ stream = ResponsesProviderStream(+ message_id="msg_test",+ model="gpt-test",+ input_tokens=0,+ tool_names=codec,+ )+ output = stream.start()+ output.extend(+ stream.feed(+ "response.output_item.added",+ {+ "item": {+ "type": "function_call",+ "id": "fc_added",+ "call_id": "call_added",+ "name": codec.encode(originals[0]),+ }+ },+ )+ )+ output.extend(+ stream.feed(+ "response.output_item.done",+ {+ "item": {+ "type": "function_call",+ "id": "fc_added",+ "call_id": "call_added",+ "name": codec.encode(originals[0]),+ "arguments": "{}",+ }+ },+ )+ )+ output.extend(+ stream.feed(+ "response.output_item.done",+ {+ "item": {+ "type": "function_call",+ "id": "fc_done",+ "call_id": "call_done",+ "name": codec.encode(originals[1]),+ "arguments": "{}",+ }+ },+ )+ )++ event_text = "".join(output)+ starts = [+ event.data["content_block"]+ for event in parse_sse_text(event_text)+ if event.event == "content_block_start"+ ]+ assert [start["name"] for start in starts] == list(originals)+ assert all(codec.encode(name) not in event_text for name in originals)diff --git a/tests/providers/test_nvidia_nim_request.py b/tests/providers/test_nvidia_nim_request.pyindex c45ec4b6..fb794bb1 100644--- a/tests/providers/test_nvidia_nim_request.py+++ b/tests/providers/test_nvidia_nim_request.py@@ -1,5 +1,6 @@"""Tests for NVIDIA NIM request policy helpers."""+import refrom copy import deepcopyfrom typing import Any@@ -254,6 +255,41 @@ class TestBuildRequestBody:assert "_fcc_arg_type" in parameters["required"]assert tool_schema == original_schema+ def test_reported_long_tool_name_uses_generic_alias_after_nim_repairs(self, req):+ """Issue #1307's 52nd tool is portable without losing NIM arg aliases."""+ long_name = "mcp__issue_1307__" + "x" * 85+ assert len(long_name) == 102+ tools = [+ Tool(name=f"tool_{index}", input_schema={"type": "object"})+ for index in range(51)+ ]+ tools.append(+ Tool(+ name=long_name,+ input_schema={+ "type": "object",+ "properties": {"type": {"type": "string"}},+ "required": ["type"],+ },+ )+ )+ req.tools = tools+ snapshot = req.model_dump()++ body = build_request_body(req, NimSettings(), reasoning=REASONING_OFF)++ wire_name = body["tools"][51]["function"]["name"]+ assert wire_name != long_name+ assert re.fullmatch(r"[A-Za-z0-9_-]{1,64}", wire_name)+ assert body[NIM_TOOL_ARGUMENT_ALIASES_KEY] == {+ long_name: {"_fcc_arg_type": "type"}+ }+ assert (+ NIM_TOOL_ARGUMENT_ALIASES_KEY+ not in body_without_nim_tool_argument_aliases(body)+ )+ assert req.model_dump() == snapshot+def test_safe_tool_schema_does_not_add_alias_metadata(self, req):tool_schema = {"type": "object",diff --git a/tests/providers/test_openai_chat_tool_names.py b/tests/providers/test_openai_chat_tool_names.pynew file mode 100644index 00000000..5c4956fc--- /dev/null+++ b/tests/providers/test_openai_chat_tool_names.py@@ -0,0 +1,150 @@+from copy import deepcopy+from typing import Any++from free_claude_code.core.anthropic import ReasoningReplayMode+from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.providers.openai_chat.request_policy import (+ OpenAIChatRequestPolicy,+ build_openai_chat_request_body,+)++_POLICY = OpenAIChatRequestPolicy(+ provider_name="TEST",+ reasoning_replay=ReasoningReplayMode.THINK_TAGS,+)+++def _request(name: str, *, continued: bool = False) -> MessagesRequest:+ messages: list[dict] = [+ {"role": "user", "content": "Use the tool"},+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "call_1",+ "name": name,+ "input": {"value": "x"},+ }+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "call_1",+ "content": "done",+ }+ ],+ },+ ]+ if continued:+ messages.append({"role": "user", "content": "Continue"})+ return MessagesRequest.model_validate(+ {+ "model": "test-model",+ "messages": messages,+ "tools": [+ {+ "name": name,+ "description": "Long tool",+ "input_schema": {+ "type": "object",+ "properties": {"value": {"type": "string"}},+ },+ },+ {+ "name": "safe_tool",+ "description": "Safe tool",+ "input_schema": {"type": "object"},+ },+ ],+ "tool_choice": {"type": "tool", "name": name},+ }+ )+++def _body(request: MessagesRequest, *, postprocessors=()) -> dict[str, Any]:+ return build_openai_chat_request_body(+ request,+ reasoning=ReasoningPolicy.provider_default(),+ policy=_POLICY,+ postprocessors=postprocessors,+ )+++def test_chat_request_uses_one_alias_in_definition_choice_and_history() -> None:+ original = "mcp__long_server__" + "x" * 90+ request = _request(original)+ snapshot = request.model_dump()++ body = _body(request)++ tools = body["tools"]+ assert isinstance(tools, list)+ alias = tools[0]["function"]["name"]+ assert alias != original+ assert len(alias) <= 64+ assert tools[1]["function"]["name"] == "safe_tool"+ assert body["tool_choice"] == {+ "type": "function",+ "function": {"name": alias},+ }+ messages = body["messages"]+ assert isinstance(messages, list)+ assistant = next(message for message in messages if message["role"] == "assistant")+ assert assistant["tool_calls"][0]["function"] == {+ "name": alias,+ "arguments": '{"value": "x"}',+ }+ assert assistant["tool_calls"][0]["id"] == "call_1"+ assert request.model_dump() == snapshot+++def test_chat_name_encoding_runs_after_provider_postprocessors() -> None:+ original = "mcp__postprocessor_order__" + "x" * 80+ request = _request(original)+ observed: list[str] = []++ def observe_names(body, _request, _reasoning) -> None:+ observed.append(body["tools"][0]["function"]["name"])++ body = _body(request, postprocessors=(observe_names,))++ assert observed == [original]+ assert body["tools"][0]["function"]["name"] != original+++def test_chat_aliases_remain_stable_for_append_only_requests() -> None:+ original = "mcp__cache_stable__" + "x" * 90++ prefix_body = _body(_request(original))+ continued_body = _body(_request(original, continued=True))++ assert continued_body["tools"] == prefix_body["tools"]+ assert continued_body["tool_choice"] == prefix_body["tool_choice"]+ prefix_messages = prefix_body["messages"]+ assert continued_body["messages"][: len(prefix_messages)] == prefix_messages+++def test_chat_encoding_does_not_rewrite_unrelated_name_fields() -> None:+ original = "mcp__canonical_name_only__" + "x" * 80+ request = _request(original)+ request.extra_body = {"metadata": {"name": original}}+ policy = OpenAIChatRequestPolicy(+ provider_name="TEST",+ reasoning_replay=ReasoningReplayMode.THINK_TAGS,+ include_extra_body=True,+ )+ snapshot = deepcopy(request.extra_body)++ body = build_openai_chat_request_body(+ request,+ reasoning=ReasoningPolicy.provider_default(),+ policy=policy,+ )++ assert body["extra_body"] == snapshot+ assert body["tools"][0]["function"]["name"] != originaldiff --git a/tests/providers/test_openai_codex_provider.py b/tests/providers/test_openai_codex_provider.pyindex 97168410..2e9bc168 100644--- a/tests/providers/test_openai_codex_provider.py+++ b/tests/providers/test_openai_codex_provider.py@@ -172,6 +172,100 @@ async def test_provider_uses_subscription_headers_and_visible_model_catalog() ->await client.aclose()+async def test_provider_round_trips_portable_tool_name_alias() -> None:+ original = "mcp__codex_provider__" + "x" * 70+ request = MessagesRequest.model_validate(+ {+ "model": "gpt-test",+ "messages": [{"role": "user", "content": "use the tool"}],+ "tools": [+ {+ "name": original,+ "description": "Long tool",+ "input_schema": {"type": "object"},+ }+ ],+ "tool_choice": {"type": "tool", "name": original},+ }+ )+ payloads: list[dict[str, Any]] = []++ def handler(http_request: httpx.Request) -> httpx.Response:+ payload = json.loads(http_request.content)+ payloads.append(payload)+ alias = payload["tools"][0]["name"]+ body = _sse(+ (+ "response.output_item.added",+ {+ "type": "response.output_item.added",+ "item": {+ "type": "function_call",+ "id": "fc_1",+ "call_id": "call_1",+ "name": alias,+ },+ },+ ),+ (+ "response.output_item.done",+ {+ "type": "response.output_item.done",+ "item": {+ "type": "function_call",+ "id": "fc_1",+ "call_id": "call_1",+ "name": alias,+ "arguments": "{}",+ },+ },+ ),+ (+ "response.completed",+ {+ "type": "response.completed",+ "response": {+ "id": "resp_1",+ "usage": {"input_tokens": 3, "output_tokens": 2},+ },+ },+ ),+ )+ return httpx.Response(+ 200,+ text=body,+ headers={"content-type": "text/event-stream"},+ request=http_request,+ )++ client = httpx.AsyncClient(+ base_url="https://chatgpt.com/backend-api/codex/",+ transport=httpx.MockTransport(handler),+ )+ provider = OpenAICodexProvider(+ _config(), auth=_FakeAuth(), admission=_admission(), client=client+ )++ body = await _collect(provider.stream_response(request))++ payload = payloads[0]+ alias = payload["tools"][0]["name"]+ assert alias != original+ assert len(alias) <= 64+ assert payload["tool_choice"] == {"type": "function", "name": alias}+ events = parse_sse_text(body)+ assert_anthropic_stream_contract(events)+ tool_start = next(+ event.data["content_block"]+ for event in events+ if event.event == "content_block_start"+ )+ assert tool_start["name"] == original+ assert alias not in body+ await client.aclose()++@pytest.mark.asyncioasync def test_early_truncated_attempt_is_retried_without_duplicate_output() -> None:attempts = 0diff --git a/tests/providers/test_streaming_errors.py b/tests/providers/test_streaming_errors.pyindex 0434bd7b..23240a9a 100644--- a/tests/providers/test_streaming_errors.py+++ b/tests/providers/test_streaming_errors.py@@ -9,6 +9,7 @@ import openaiimport pytestfrom free_claude_code.config.nim import NimSettings+from free_claude_code.core.anthropic import OpenAIToolNameCodecfrom free_claude_code.core.anthropic.stream_contracts import (parse_sse_text,)@@ -27,6 +28,7 @@ from free_claude_code.providers.openai_chat.provider import ()from free_claude_code.providers.openai_chat.tool_calls import (OpenAIToolCallAssembler,+ OpenAIToolCallCollector,has_committed_sse_output,iter_heuristic_tool_use_sse,)@@ -768,6 +770,66 @@ class TestStreamingExceptionHandling:assert parsed[0].event == "message_start"assert parsed[-1].event == "message_stop"+ @pytest.mark.asyncio+ async def test_precommit_retry_discards_abandoned_tool_name_fragment(self):+ """A retried alias fragment cannot prefix or duplicate the successful call."""+ provider = _make_provider()+ original = "mcp__retry_tool_name__" + "x" * 70+ request = _make_request(+ tools=[{"name": original, "input_schema": {"type": "object"}}]+ )+ alias = OpenAIToolNameCodec.from_request(request).encode(original)+ first_stream = AsyncStreamMock(+ [+ _make_tool_calls_chunk(+ name=alias[:20],+ arguments="",+ tool_id="call_abandoned",+ ),+ _make_chunk(finish_reason="tool_calls"),+ ]+ )+ second_stream = AsyncStreamMock(+ [+ _make_tool_calls_chunk(+ name=alias,+ arguments="{}",+ tool_id="call_success",+ ),+ _make_chunk(finish_reason="tool_calls"),+ ]+ )++ with patch.object(+ provider._client.chat.completions,+ "create",+ new_callable=AsyncMock,+ side_effect=[first_stream, second_stream],+ ) as create:+ events = await _collect_stream(provider, request)++ event_text = "".join(events)+ parsed = parse_sse_text(event_text)+ tool_starts = [+ event.data["content_block"]+ for event in parsed+ if event.event == "content_block_start"+ and event.data.get("content_block", {}).get("type") == "tool_use"+ ]+ assert create.await_count == 2+ assert tool_starts == [+ {+ "type": "tool_use",+ "id": "call_success",+ "name": original,+ "input": {},+ }+ ]+ assert alias not in event_text+ assert "call_abandoned" not in event_text+ assert sum(event.event == "message_start" for event in parsed) == 1+ assert sum(event.event == "message_stop" for event in parsed) == 1+@pytest.mark.asyncioasync def test_primary_replay_and_continuation_share_five_attempts(self):"""Four replays plus continuation emit one unduplicated response."""@@ -1293,6 +1355,233 @@ class TestProcessToolCall:assert "search" in event_textassert "call_123" in event_text+ def test_structured_tool_call_restores_portable_wire_alias(self):+ """A wire alias never escapes in the Anthropic tool block."""+ provider = _make_provider()+ original = "mcp__portable_output__" + "x" * 70+ request = _make_request(+ tools=[{"name": original, "input_schema": {"type": "object"}}]+ )+ codec = OpenAIToolNameCodec.from_request(request)+ alias = codec.encode(original)+ sse = AnthropicStreamLedger("msg_test", "test-model")++ events = list(+ _make_tool_assembler(provider).process_tool_call(+ {+ "index": 0,+ "id": "call_alias",+ "function": {"name": alias, "arguments": "{}"},+ },+ sse,+ tool_names=codec,+ tool_name_buffers={},+ )+ )++ event_text = "".join(events)+ assert original in event_text+ assert alias not in event_text+ assert (+ sum(+ event.event == "content_block_start"+ for event in parse_sse_text(event_text)+ )+ == 1+ )++ def test_tool_name_restores_before_nim_argument_alias_lookup(self):+ """Generic name decoding composes with original-name NIM arg metadata."""+ provider = _make_provider()+ original = "mcp__nim_argument_composition__" + "x" * 70+ request = _make_request(+ tools=[+ {+ "name": original,+ "input_schema": {+ "type": "object",+ "properties": {"type": {"type": "string"}},+ "required": ["type"],+ },+ }+ ]+ )+ codec = OpenAIToolNameCodec.from_request(request)+ sse = AnthropicStreamLedger("msg_test", "test-model")++ events = list(+ _make_tool_assembler(provider).process_tool_call(+ {+ "index": 0,+ "id": "call_composed",+ "function": {+ "name": codec.encode(original),+ "arguments": '{"_fcc_arg_type":"file"}',+ },+ },+ sse,+ tool_names=codec,+ tool_name_buffers={},+ tool_argument_aliases={original: {"_fcc_arg_type": "type"}},+ tool_argument_alias_buffers={},+ )+ )++ parsed = parse_sse_text("".join(events))+ start = next(+ event.data["content_block"]+ for event in parsed+ if event.event == "content_block_start"+ )+ argument_delta = next(+ event.data["delta"]["partial_json"]+ for event in parsed+ if event.event == "content_block_delta"+ )+ assert start["name"] == original+ assert json.loads(argument_delta) == {"type": "file"}++ def test_fragmented_wire_alias_starts_one_original_tool_block(self):+ """A split alias is held until the exact request alias is complete."""+ provider = _make_provider()+ original = "mcp__fragmented_output__" + "x" * 70+ request = _make_request(+ tools=[{"name": original, "input_schema": {"type": "object"}}]+ )+ codec = OpenAIToolNameCodec.from_request(request)+ alias = codec.encode(original)+ split = len(alias) // 2+ buffers: dict[int, str] = {}+ sse = AnthropicStreamLedger("msg_test", "test-model")+ assembler = _make_tool_assembler(provider)++ first = list(+ assembler.process_tool_call(+ {+ "index": 0,+ "id": "call_split_alias",+ "function": {"name": alias[:split], "arguments": ""},+ },+ sse,+ tool_names=codec,+ tool_name_buffers=buffers,+ )+ )+ second = list(+ assembler.process_tool_call(+ {+ "index": 0,+ "id": None,+ "function": {"name": alias[split:], "arguments": "{}"},+ },+ sse,+ tool_names=codec,+ tool_name_buffers=buffers,+ )+ )++ assert first == []+ event_text = "".join(second)+ assert original in event_text+ assert alias not in event_text+ assert (+ sum(+ event.event == "content_block_start"+ for event in parse_sse_text(event_text)+ )+ == 1+ )+ assert buffers == {}++ def test_valid_name_that_prefixes_alias_is_resolved_on_flush(self):+ """An ambiguous valid name is delayed, not mistaken for an alias fragment."""+ provider = _make_provider()+ original = "tool"+ long_name = "tool." + "x" * 70+ request = _make_request(+ tools=[+ {"name": original, "input_schema": {"type": "object"}},+ {"name": long_name, "input_schema": {"type": "object"}},+ ]+ )+ codec = OpenAIToolNameCodec.from_request(request)+ assert codec.is_alias_prefix(original)+ buffers: dict[int, str] = {}+ sse = AnthropicStreamLedger("msg_test", "test-model")+ assembler = _make_tool_assembler(provider)++ initial = list(+ assembler.process_tool_call(+ {+ "index": 0,+ "id": "call_valid",+ "function": {"name": original, "arguments": "{}"},+ },+ sse,+ tool_names=codec,+ tool_name_buffers=buffers,+ )+ )+ flushed = list(+ assembler.flush_tool_name_buffers(+ sse,+ tool_names=codec,+ tool_name_buffers=buffers,+ tool_argument_aliases={},+ tool_argument_alias_buffers={},+ )+ )++ assert initial == []+ assert original in "".join(flushed)+ assert buffers == {}++ def test_buffered_collector_decodes_before_schema_validation(self):+ """Recovery validates the original tool identity, not its wire alias."""+ original = "mcp__recovery_output__" + "x" * 70+ request = _make_request(+ tools=[{"name": original, "input_schema": {"type": "object"}}]+ )+ codec = OpenAIToolNameCodec.from_request(request)+ collector = OpenAIToolCallCollector()+ collector.add(+ SimpleNamespace(+ index=0,+ id="call_recovered",+ function=SimpleNamespace(name=codec.encode(original), arguments="{}"),+ )+ )++ calls = collector.completed_calls(request, tool_names=codec)++ assert calls is not None+ assert calls[0]["function"]["name"] == original++ def test_heuristic_tool_call_restores_original_name(self):+ """Complete heuristic calls share the same outbound name contract."""+ original = "mcp__heuristic_output__" + "x" * 70+ request = _make_request(+ tools=[{"name": original, "input_schema": {"type": "object"}}]+ )+ codec = OpenAIToolNameCodec.from_request(request)+ sse = AnthropicStreamLedger("msg_test", "test-model")++ events = list(+ iter_heuristic_tool_use_sse(+ sse,+ {+ "id": "call_heuristic",+ "name": codec.encode(original),+ "input": {},+ },+ tool_names=codec,+ )+ )++ event_text = "".join(events)+ assert original in event_text+ assert codec.encode(original) not in event_text+def test_tool_call_id_arrives_before_name_still_emits_id_and_name(self):"""Split-stream tool: id (no name) then name then args; id preserved on start."""provider = _make_provider()diff --git a/uv.lock b/uv.lockindex 0bfad1ec..67348144 100644--- a/uv.lock+++ b/uv.lock@@ -620,7 +620,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "4.16.0"+version = "4.16.1"source = { editable = "." }dependencies = [{ name = "aiohttp" },