Skip to content

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 Codex client tool discovery and sub-agent calls (#1765)

Ali Khokharefff10e2a22b
diff --git a/pyproject.toml b/pyproject.toml
index d5e631e1..c1fcc1ec 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "6.2.12"
+version = "6.2.13"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
@@ -31,6 +31,7 @@ dependencies = [
"pystray>=0.19.5; sys_platform == 'win32' or sys_platform == 'darwin'",
"Pillow>=12.0.0; sys_platform == 'win32' or sys_platform == 'darwin'",
"github-copilot-sdk==1.0.13",
+ "simplejson>=4.1.2",
]
[project.scripts]
diff --git a/src/free_claude_code/core/openai_responses/__init__.py b/src/free_claude_code/core/openai_responses/__init__.py
index 0d410d26..32b65c15 100644
--- a/src/free_claude_code/core/openai_responses/__init__.py
+++ b/src/free_claude_code/core/openai_responses/__init__.py
@@ -44,7 +44,6 @@ from .tool_adaptation import (
from .tools import (
ResponsesToolIdentity,
flatten_responses_tool_name,
- responses_tool_identity_from_wire_name,
)
__all__ = [
@@ -87,6 +86,5 @@ __all__ = [
"responses_reasoning_config",
"responses_reasoning_policy",
"responses_stream_failure_from_event",
- "responses_tool_identity_from_wire_name",
"tool_item",
]
diff --git a/src/free_claude_code/core/openai_responses/chat_request.py b/src/free_claude_code/core/openai_responses/chat_request.py
index 105ddc7a..b85e339e 100644
--- a/src/free_claude_code/core/openai_responses/chat_request.py
+++ b/src/free_claude_code/core/openai_responses/chat_request.py
@@ -31,29 +31,14 @@ from .reasoning import (
combine_reasoning,
encrypted_reasoning_from_item,
)
+from .tool_adaptation import ResponsesToolAdapter, ResponsesToolPolicy
from .tools import (
call_id_from_item,
- custom_tool_description,
- custom_tool_input_schema,
- custom_tool_input_text,
- flatten_responses_tool_name,
optional_str,
parse_arguments,
required_str,
)
-_PASSIVE_TOOL_TYPES = frozenset(
- {
- "computer",
- "file_search",
- "image_generation",
- "local_shell",
- "mcp",
- "tool_search",
- "web_search",
- "web_search_preview",
- }
-)
_CHAT_OPTION_FIELDS = (
"frequency_penalty",
"logit_bias",
@@ -75,6 +60,7 @@ class ResponsesChatRequest:
tool_names: OpenAIToolNameCodec
tool_schemas: dict[str, JsonObject]
reserved_tool_ids: frozenset[str]
+ tool_adapter: ResponsesToolAdapter
@dataclass(slots=True)
@@ -122,8 +108,9 @@ class _ResponsesChatInputBuilder:
self._pending_reasoning = _PendingReasoning()
self._pending_rich_output_parts: list[dict[str, object]] = []
self._quarantined_call_ids: set[str] = set()
+ self._discovery_outputs: list[dict[str, object]] = []
- def add(self, item: JsonValue) -> None:
+ def add(self, item: JsonValue, *, source_type: str | None = None) -> None:
if isinstance(item, str):
self._flush_rich_outputs()
self._flush_reasoning()
@@ -146,11 +133,11 @@ class _ResponsesChatInputBuilder:
if item_type == "reasoning":
self._pending_reasoning.add(item)
return
- if item_type in {"function_call", "custom_tool_call"}:
- self._add_tool_call(item, custom=item_type == "custom_tool_call")
+ if item_type == "function_call":
+ self._add_tool_call(item)
return
- if item_type in {"function_call_output", "custom_tool_call_output"}:
- self._add_tool_output(item, function=item_type == "function_call_output")
+ if item_type == "function_call_output":
+ self._add_tool_output(item, source_type=source_type)
return
if item_type == "computer_call_output":
self._add_computer_output(item)
@@ -185,6 +172,16 @@ class _ResponsesChatInputBuilder:
self._flush_reasoning()
return self.system_parts, self.messages
+ def encode_discovery_outputs(self, tool_names: OpenAIToolNameCodec) -> None:
+ """Encode FCC's discovery definitions with the final Chat name mapping."""
+ if not tool_names.has_aliases:
+ return
+ for message in self._discovery_outputs:
+ tools = json.loads(cast(str, message["content"]))
+ for tool in tools:
+ tool["name"] = tool_names.encode(tool["name"])
+ message["content"] = json.dumps(tools)
+
def _add_message(self, item: Mapping[str, JsonValue]) -> None:
role = required_str(item.get("role", "user"), "input.role")
if role in {"developer", "system"}:
@@ -207,30 +204,24 @@ class _ResponsesChatInputBuilder:
return
self.messages.append(message)
- def _add_tool_call(self, item: Mapping[str, JsonValue], *, custom: bool) -> None:
+ def _add_tool_call(self, item: Mapping[str, JsonValue]) -> None:
call_id = call_id_from_item(item)
- name = _tool_identity_name(item)
- if custom:
- arguments = json.dumps(
- {"input": custom_tool_input_text(item.get("input"))},
- separators=(",", ":"),
+ name = required_str(item.get("name"), "function_call.name")
+ raw_arguments = item.get("arguments")
+ try:
+ parse_arguments(raw_arguments)
+ except ResponsesConversionError as exc:
+ self._quarantined_call_ids.add(call_id)
+ self._pending_reasoning.take()
+ trace_event(
+ stage="responses",
+ event="responses.input.function_call_quarantined",
+ source="openai_responses",
+ call_id=call_id,
+ error_type=type(exc).__name__,
)
- else:
- raw_arguments = item.get("arguments")
- try:
- parse_arguments(raw_arguments)
- except ResponsesConversionError as exc:
- self._quarantined_call_ids.add(call_id)
- self._pending_reasoning.take()
- trace_event(
- stage="responses",
- event="responses.input.function_call_quarantined",
- source="openai_responses",
- call_id=call_id,
- error_type=type(exc).__name__,
- )
- return
- arguments = _arguments_text(raw_arguments)
+ return
+ arguments = _arguments_text(raw_arguments)
message: dict[str, object] | None = self._last_tool_call_message()
if message is None:
@@ -254,8 +245,9 @@ class _ResponsesChatInputBuilder:
message.setdefault("reasoning_content", "")
def _add_tool_output(
- self, item: Mapping[str, JsonValue], *, function: bool
+ self, item: Mapping[str, JsonValue], *, source_type: str | None
) -> None:
+ function = source_type != "custom_tool_call_output"
call_id = call_id_from_item(item)
if function and call_id in self._quarantined_call_ids:
return
@@ -280,6 +272,8 @@ class _ResponsesChatInputBuilder:
),
}
)
+ if source_type == "tool_search_output":
+ self._discovery_outputs.append(self.messages[-1])
if rich_parts is not None:
self._pending_rich_output_parts.extend(rich_parts)
@@ -360,14 +354,30 @@ def build_responses_chat_request(
structured_reasoning_details: bool = False,
) -> ResponsesChatRequest:
"""Translate a Responses request directly into one Chat Completions body."""
+ adapter = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ flatten_namespaces=True,
+ client_tool_search=True,
+ ),
+ )
+ request = adapter.request
builder = _ResponsesChatInputBuilder(
reasoning_replay=reasoning_replay,
structured_reasoning_details=structured_reasoning_details,
)
if request.instructions:
builder.system_parts.append(request.instructions)
- for item in _input_items(request.input):
- builder.add(item)
+ original_items = _input_items(adapter.original.input)
+ for index, item in enumerate(_input_items(request.input)):
+ source = original_items[index]
+ builder.add(
+ item,
+ source_type=optional_str(source.get("type"))
+ if isinstance(source, dict)
+ else None,
+ )
system_parts, raw_messages = builder.finish()
messages = cast(
list[dict[str, object]],
@@ -414,11 +424,13 @@ def build_responses_chat_request(
tool_schemas = _body_tool_schemas(body)
reserved_tool_ids = frozenset(_body_tool_call_ids(body))
tool_names = OpenAIToolNameCodec.from_names(_body_tool_names(body))
+ builder.encode_discovery_outputs(tool_names)
return ResponsesChatRequest(
body=body,
tool_names=tool_names,
tool_schemas=tool_schemas,
reserved_tool_ids=reserved_tool_ids,
+ tool_adapter=adapter,
)
@@ -506,12 +518,6 @@ def _image_part(part: Mapping[str, JsonValue], *, context: str) -> dict[str, obj
return {"type": "image_url", "image_url": image_url}
-def _tool_identity_name(item: Mapping[str, JsonValue]) -> str:
- name = required_str(item.get("name"), f"{item.get('type')}.name")
- namespace = optional_str(item.get("namespace"))
- return flatten_responses_tool_name(name, namespace=namespace)
-
-
def _arguments_text(value: JsonValue) -> str:
if isinstance(value, str):
return value
@@ -583,37 +589,8 @@ def _chat_tools(
for tool in tools or ():
tool_type = tool.get("type")
if tool_type == "function":
- converted_tool, name = _chat_function_tool(tool, namespace=None)
+ converted_tool, name = _chat_function_tool(tool)
_append_unique_chat_tool(converted, names, converted_tool, name)
- elif tool_type == "custom":
- converted_tool, name = _chat_custom_tool(tool, namespace=None)
- _append_unique_chat_tool(converted, names, converted_tool, name)
- elif tool_type == "namespace":
- namespace = required_str(tool.get("name"), "tool.namespace.name")
- nested = tool.get("tools")
- if not isinstance(nested, Sequence) or isinstance(
- nested, str | bytes | bytearray
- ):
- raise ResponsesConversionError(
- f"Responses namespace tool {namespace!r} tools must be a list"
- )
- for nested_tool in nested:
- if not isinstance(nested_tool, Mapping):
- continue
- nested_type = nested_tool.get("type")
- if nested_type == "function":
- converted_tool, name = _chat_function_tool(
- nested_tool, namespace=namespace
- )
- elif nested_type == "custom":
- converted_tool, name = _chat_custom_tool(
- nested_tool, namespace=namespace
- )
- else:
- continue
- _append_unique_chat_tool(converted, names, converted_tool, name)
- elif isinstance(tool_type, str) and tool_type in _PASSIVE_TOOL_TYPES:
- continue
return converted, frozenset(names)
@@ -631,14 +608,9 @@ def _append_unique_chat_tool(
names.add(name)
-def _chat_function_tool(
- tool: Mapping[str, JsonValue], *, namespace: str | None
-) -> tuple[dict[str, object], str]:
- nested = tool.get("function")
- source = nested if isinstance(nested, Mapping) else tool
- name = required_str(source.get("name"), "tool.name")
- wire_name = flatten_responses_tool_name(name, namespace=namespace)
- parameters = source.get("parameters")
+def _chat_function_tool(tool: Mapping[str, JsonValue]) -> tuple[dict[str, object], str]:
+ name = required_str(tool.get("name"), "tool.name")
+ parameters = tool.get("parameters")
if parameters is None:
parameters = {"type": "object", "properties": {}}
if not isinstance(parameters, Mapping):
@@ -646,31 +618,15 @@ def _chat_function_tool(
f"Responses tool {name!r} parameters must be an object"
)
function: dict[str, object] = {
- "name": wire_name,
+ "name": name,
"parameters": dict(parameters),
}
- if description := optional_str(source.get("description")):
+ if description := optional_str(tool.get("description")):
function["description"] = description
- strict = source.get("strict")
+ strict = tool.get("strict")
if isinstance(strict, bool):
function["strict"] = strict
- return {"type": "function", "function": function}, wire_name
-
-
-def _chat_custom_tool(
- tool: Mapping[str, JsonValue], *, namespace: str | None
-) -> tuple[dict[str, object], str]:
- nested = tool.get("custom")
- source = nested if isinstance(nested, Mapping) else tool
- name = required_str(source.get("name"), "tool.name")
- wire_name = flatten_responses_tool_name(name, namespace=namespace)
- function: dict[str, object] = {
- "name": wire_name,
- "parameters": custom_tool_input_schema(),
- }
- if description := custom_tool_description(source):
- function["description"] = description
- return {"type": "function", "function": function}, wire_name
+ return {"type": "function", "function": function}, name
def _chat_tool_choice(
@@ -689,20 +645,14 @@ def _chat_tool_choice(
choice_type = value.get("type")
if choice_type in {"auto", "any", "required"}:
return "required" if choice_type in {"any", "required"} else "auto"
- if choice_type not in {"function", "custom", "tool"}:
+ if choice_type != "function":
return None
- source = value.get("custom")
- choice = source if isinstance(source, Mapping) else value
- name = optional_str(choice.get("name"))
+ name = optional_str(value.get("name"))
if not name:
return None
- namespace = optional_str(choice.get("namespace")) or optional_str(
- value.get("namespace")
- )
- wire_name = flatten_responses_tool_name(name, namespace=namespace)
- if wire_name not in available_names:
+ if name not in available_names:
return None
- return {"type": "function", "function": {"name": wire_name}}
+ return {"type": "function", "function": {"name": name}}
def _chat_response_format(value: JsonValue) -> object | None:
diff --git a/src/free_claude_code/core/openai_responses/events.py b/src/free_claude_code/core/openai_responses/events.py
index 75d8a330..940b8fe9 100644
--- a/src/free_claude_code/core/openai_responses/events.py
+++ b/src/free_claude_code/core/openai_responses/events.py
@@ -5,6 +5,8 @@ from collections.abc import Mapping
from copy import deepcopy
from typing import Any, cast
+import simplejson
+
from free_claude_code.core.diagnostics import safe_exception_message
from free_claude_code.core.failures import find_execution_failure
from free_claude_code.core.json_types import JsonObject, JsonValue
@@ -21,7 +23,7 @@ OPENAI_RESPONSES_SSE_HEADERS: dict[str, str] = {
def format_response_sse_event(event_type: str, data: Mapping[str, Any]) -> str:
"""Format one OpenAI Responses SSE event."""
- return f"event: {event_type}\ndata: {json.dumps(data)}\n\n"
+ return f"event: {event_type}\ndata: {simplejson.dumps(data, use_decimal=True)}\n\n"
def committed_response_failure_frame(
diff --git a/src/free_claude_code/core/openai_responses/streaming/completion.py b/src/free_claude_code/core/openai_responses/streaming/completion.py
index 12b66614..bb19d191 100644
--- a/src/free_claude_code/core/openai_responses/streaming/completion.py
+++ b/src/free_claude_code/core/openai_responses/streaming/completion.py
@@ -26,10 +26,12 @@ class ResponseBlockCompleter:
*,
events: ResponseEventBuilder,
on_invalid_function_call: InvalidFunctionCallHandler,
+ prepare_tool_arguments: Callable[[str, str], str] | None = None,
) -> None:
self._ledger = ledger
self._events = events
self._on_invalid_function_call = on_invalid_function_call
+ self._prepare_tool_arguments = prepare_tool_arguments
def complete_block(self, state: BlockState) -> list[str]:
if isinstance(state, TextBlockState):
@@ -66,9 +68,13 @@ class ResponseBlockCompleter:
def _complete_tool_block(self, state: ToolBlockState) -> list[str]:
if state.kind == "custom":
return self._complete_custom_tool_block(state)
- raw_arguments = "".join(state.argument_parts) or "{}"
+ raw_arguments = "".join(state.argument_parts)
try:
- arguments = normalized_function_call_arguments(raw_arguments)
+ arguments = (
+ self._prepare_tool_arguments(state.name, raw_arguments)
+ if self._prepare_tool_arguments is not None
+ else normalized_function_call_arguments(raw_arguments or "{}")
+ )
except ResponsesConversionError as exc:
return self._on_invalid_function_call(state, exc)
item = tool_item(state, status="completed", arguments=arguments)
diff --git a/src/free_claude_code/core/openai_responses/streaming/event_builders.py b/src/free_claude_code/core/openai_responses/streaming/event_builders.py
index bb324874..025142f3 100644
--- a/src/free_claude_code/core/openai_responses/streaming/event_builders.py
+++ b/src/free_claude_code/core/openai_responses/streaming/event_builders.py
@@ -1,6 +1,9 @@
"""OpenAI Responses SSE event builders."""
-from typing import Any
+from collections.abc import Callable, Iterable
+from typing import Any, cast
+
+from free_claude_code.core.json_types import JsonObject
from ..events import format_response_sse_event
@@ -8,8 +11,13 @@ from ..events import format_response_sse_event
class ResponseEventBuilder:
"""Build one ordered Responses event stream."""
- def __init__(self) -> None:
+ def __init__(
+ self,
+ transform: Callable[[str, JsonObject], Iterable[tuple[str, JsonObject]]]
+ | None = None,
+ ) -> None:
self._next_sequence_number = 0
+ self._transform = transform
def response_created(self, response: dict[str, Any]) -> str:
return self._format(
@@ -182,4 +190,9 @@ class ResponseEventBuilder:
def _format(self, event_type: str, data: dict[str, Any]) -> str:
data["sequence_number"] = self._next_sequence_number
self._next_sequence_number += 1
+ if self._transform is not None:
+ return "".join(
+ format_response_sse_event(kind, payload)
+ for kind, payload in self._transform(event_type, cast(JsonObject, data))
+ )
return format_response_sse_event(event_type, data)
diff --git a/src/free_claude_code/core/openai_responses/tool_adaptation.py b/src/free_claude_code/core/openai_responses/tool_adaptation.py
index f4b98927..351d0988 100644
--- a/src/free_claude_code/core/openai_responses/tool_adaptation.py
+++ b/src/free_claude_code/core/openai_responses/tool_adaptation.py
@@ -4,13 +4,23 @@ import json
from collections.abc import Iterable, Mapping
from copy import deepcopy
from dataclasses import dataclass
-from typing import cast
+from decimal import Decimal
+from typing import Never, cast
+
+import simplejson
from free_claude_code.core.json_types import JsonObject, JsonValue
from .errors import ResponsesConversionError
from .models import OpenAIResponsesRequest
-from .tool_search import normalize_tool_search
+from .tool_search import (
+ ClientSearchHistory,
+ active_client_tools,
+ is_client_search,
+ normalize_tool_search,
+ resolve_client_search_history,
+ search_function_name,
+)
from .tools import (
ResponsesToolIdentity,
custom_tool_description,
@@ -28,6 +38,8 @@ class ResponsesToolPolicy:
custom_tools_as_functions: bool = False
explicit_search_parameters: bool = False
text_only_web_search: bool = False
+ client_tool_search: bool = False
+ flatten_namespaces: bool = False
@dataclass(frozen=True, slots=True)
@@ -44,60 +56,176 @@ class ResponsesToolAdapter:
def __init__(
self, request: OpenAIResponsesRequest, policy: ResponsesToolPolicy
) -> None:
+ self.original = request
self.request = request.model_copy(deep=True)
self._policy = policy
self._identities: dict[tuple[str | None, str], ResponsesToolIdentity] = {}
+ self._wire_names: dict[ResponsesToolIdentity, str] = {}
+ self._declared: set[ResponsesToolIdentity] = set()
+ self._namespace_headers: dict[tuple[str | None, str], JsonObject] = {}
self._edits: list[_DefinitionEdit] = []
+ self._search_name: str | None = None
+ self._search_history = (
+ resolve_client_search_history(self.request.input)
+ if policy.client_tool_search
+ else ClientSearchHistory(frozenset(), {})
+ )
if policy == ResponsesToolPolicy():
return
+ client_search = policy.client_tool_search and (
+ self._search_history.client_items
+ or any(is_client_search(tool) for tool in request.tools or [])
+ )
+ if client_search:
+ self.request.tools = active_client_tools(
+ self.request.tools, self._search_history
+ )
+ if (
+ policy.custom_tools_as_functions
+ or policy.flatten_namespaces
+ or policy.client_tool_search
+ ):
+ self._register_tools(self.request.tools)
+ if isinstance(self.request.input, list):
+ for index, item in enumerate(self.request.input):
+ if isinstance(item, dict) and item.get("type") in (
+ "function_call",
+ "custom_tool_call",
+ ):
+ self._wire_name(_call_identity(item))
+ elif (
+ isinstance(item, dict)
+ and item.get("type") == "tool_search_output"
+ ):
+ self._register_tools(
+ self._search_history.output_tools.get(
+ index, item.get("tools")
+ )
+ )
+ if client_search:
+ self._search_name = search_function_name(self._wire_names.values())
if self.request.tools:
self.request.tools = cast(list[JsonObject], self._tools(self.request.tools))
if isinstance(self.request.input, list):
- self.request.input = [self._input(item) for item in self.request.input]
- if policy.custom_tools_as_functions:
+ self.request.input = [
+ self._input(item, index)
+ for index, item in enumerate(self.request.input)
+ ]
+ if (
+ policy.custom_tools_as_functions
+ or policy.client_tool_search
+ or policy.flatten_namespaces
+ ):
self.request.tool_choice = self._choice(self.request.tool_choice)
- def _register(self, identity: ResponsesToolIdentity, wire_name: str) -> None:
- key = (identity.namespace, wire_name)
+ def _wire_name(self, identity: ResponsesToolIdentity) -> str:
+ if identity in self._wire_names:
+ return self._wire_names[identity]
+ wire_name = (
+ flatten_responses_tool_name(identity.name, namespace=identity.namespace)
+ if self._policy.flatten_namespaces
+ or (identity.kind == "custom" and self._policy.custom_tools_as_functions)
+ else identity.name
+ )
+ key = (
+ None if self._policy.flatten_namespaces else identity.namespace,
+ wire_name,
+ )
existing = self._identities.get(key)
if existing is not None and existing != identity:
raise ResponsesConversionError("Tool names collide after conversion.")
self._identities[key] = identity
+ self._wire_names[identity] = wire_name
+ return wire_name
+
+ def _register_tools(self, tools: JsonValue, namespace: str | None = None) -> None:
+ if not isinstance(tools, list):
+ return
+ for tool in tools:
+ if not isinstance(tool, dict):
+ continue
+ if tool.get("type") == "namespace":
+ if not isinstance(tool.get("tools"), list):
+ raise ResponsesConversionError("Namespace tools must be a list.")
+ self._register_tools(tool.get("tools"), _name(tool))
+ elif tool.get("type") in ("function", "custom"):
+ identity = _definition_identity(tool, namespace)
+ self._wire_name(identity)
+ self._declared.add(identity)
def _tools(
- self, tools: JsonValue, namespace: str | None = None, scope: str | None = None
+ self,
+ tools: JsonValue,
+ namespace: str | None = None,
+ scope: str | None = None,
) -> JsonValue:
if not isinstance(tools, list):
return tools
- return [self._tool(tool, namespace, scope) for tool in tools]
+ result: list[JsonValue] = []
+ for tool in tools:
+ if (
+ self._policy.flatten_namespaces
+ and isinstance(tool, dict)
+ and tool.get("type") == "namespace"
+ ):
+ name = _name(tool)
+ self._namespace_headers[(scope, name)] = {
+ key: deepcopy(value)
+ for key, value in tool.items()
+ if key != "tools"
+ }
+ children = self._tools(tool.get("tools"), name, scope)
+ if isinstance(children, list):
+ result.extend(children)
+ else:
+ result.append(self._tool(tool, namespace, scope))
+ return result
def _tool(
self, value: JsonValue, namespace: str | None, scope: str | None
) -> JsonValue:
if not isinstance(value, dict):
return value
- tool = value
+ tool = dict(value)
kind = tool.get("type")
+ if (
+ self._policy.client_tool_search
+ and kind == "tool_search"
+ and is_client_search(tool)
+ ):
+ if self._policy.explicit_search_parameters:
+ tool = normalize_tool_search(tool)
+ if not isinstance(tool.get("parameters"), dict):
+ raise ResponsesConversionError(
+ "Client tool search requires an argument schema."
+ )
+ return {
+ "type": "function",
+ "name": self._search_name,
+ "description": tool.get("description", "Find callable tools."),
+ "parameters": deepcopy(tool["parameters"]),
+ "strict": False,
+ }
if kind == "namespace":
return {
**tool,
"tools": self._tools(tool.get("tools"), _name(tool), scope),
}
- if self._policy.custom_tools_as_functions and kind in {"custom", "function"}:
+ if (
+ self._policy.custom_tools_as_functions or self._policy.flatten_namespaces
+ ) and kind in {"custom", "function"}:
nested = tool.get(str(kind))
source = nested if isinstance(nested, dict) else tool
- name = _name(source)
- identity = ResponsesToolIdentity(
- kind="custom" if kind == "custom" else "function",
- name=name,
- namespace=namespace or _namespace(source),
- )
- wire_name = (
- flatten_responses_tool_name(name, namespace=identity.namespace)
- if kind == "custom"
- else name
- )
- self._register(identity, wire_name)
+ identity = _definition_identity(tool, namespace)
+ wire_name = self._wire_name(identity)
+ tool = {
+ **{key: child for key, child in tool.items() if key != kind},
+ **source,
+ "type": kind,
+ }
+ if self._policy.flatten_namespaces:
+ tool = {**tool, "name": wire_name}
+ tool.pop("namespace", None)
if kind == "custom":
tool = {
**{key: child for key, child in tool.items() if key != "custom"},
@@ -110,6 +238,8 @@ class ResponsesToolAdapter:
tool.pop("format", None)
if description := custom_tool_description(source):
tool["description"] = description
+ if self._policy.flatten_namespaces:
+ tool.pop("namespace", None)
if self._policy.explicit_search_parameters:
tool = normalize_tool_search(tool)
if self._policy.text_only_web_search and kind in {
@@ -131,29 +261,49 @@ class ResponsesToolAdapter:
self._edits.append(_DefinitionEdit(value, tool, namespace, scope))
return tool
- def _input(self, item: JsonValue) -> JsonValue:
+ def _input(self, item: JsonValue, index: int) -> JsonValue:
if not isinstance(item, dict):
return item
kind = item.get("type")
+ if index in self._search_history.client_items:
+ common = {
+ key: value
+ for key, value in item.items()
+ if key not in {"execution", "tools", "arguments"}
+ }
+ if kind == "tool_search_call":
+ arguments = item.get("arguments")
+ if not isinstance(arguments, dict):
+ raise ResponsesConversionError(
+ "Client search arguments must be an object."
+ )
+ return {
+ **common,
+ "type": "function_call",
+ "name": self._search_name,
+ "arguments": simplejson.dumps(arguments, use_decimal=True),
+ }
+ if kind == "tool_search_output":
+ active = self._search_history.output_tools[index]
+ return {
+ **common,
+ "type": "function_call_output",
+ "output": json.dumps(self._tools(active, scope=_scope(item))),
+ }
if kind == "tool_search_output":
- return {**item, "tools": self._tools(item.get("tools"), scope=_scope(item))}
- if not self._policy.custom_tools_as_functions:
+ return {
+ **item,
+ "tools": self._tools(item.get("tools"), scope=_scope(item)),
+ }
+ if (
+ not self._policy.custom_tools_as_functions
+ and not self._policy.flatten_namespaces
+ ):
return item
if kind in {"custom_tool_call", "function_call"}:
- name = _name(item)
- identity = ResponsesToolIdentity(
- kind="custom" if kind == "custom_tool_call" else "function",
- name=name,
- namespace=_namespace(item),
- )
- wire_name = (
- flatten_responses_tool_name(name, namespace=identity.namespace)
- if kind == "custom_tool_call"
- else name
- )
- self._register(identity, wire_name)
+ wire_name = self._wire_name(_call_identity(item))
if kind == "custom_tool_call":
- return {
+ call: JsonObject = {
**{key: value for key, value in item.items() if key != "input"},
"type": "function_call",
"name": wire_name,
@@ -162,6 +312,14 @@ class ResponsesToolAdapter:
ensure_ascii=False,
),
}
+ if self._policy.flatten_namespaces:
+ call.pop("namespace", None)
+ return call
+ if self._policy.flatten_namespaces:
+ return {
+ **{key: value for key, value in item.items() if key != "namespace"},
+ "name": wire_name,
+ }
if kind == "custom_tool_call_output":
return {**item, "type": "function_call_output"}
return item
@@ -169,34 +327,105 @@ class ResponsesToolAdapter:
def _choice(self, choice: JsonValue) -> JsonValue:
if not isinstance(choice, dict):
return choice
- if choice.get("type") == "custom":
- return {
- **choice,
+ if (
+ self._search_name is not None
+ and choice.get("type") == "tool_search"
+ and choice.get("execution") != "server"
+ ):
+ return {"type": "function", "name": self._search_name}
+ kind = choice.get("type")
+ if (
+ self._policy.flatten_namespaces and kind in ("function", "custom", "tool")
+ ) or (self._policy.custom_tools_as_functions and kind == "custom"):
+ identity = _definition_identity(choice)
+ if kind == "tool":
+ identity = next(
+ (
+ declared
+ for declared in self._declared
+ if declared.name == identity.name
+ and declared.namespace == identity.namespace
+ ),
+ identity,
+ )
+ result: JsonObject = {
+ **{
+ key: value
+ for key, value in choice.items()
+ if key not in ("custom", "function")
+ },
"type": "function",
- "name": flatten_responses_tool_name(
- _name(choice), namespace=_namespace(choice)
- ),
+ "name": self._wire_name(identity),
}
+ if self._policy.flatten_namespaces:
+ result.pop("namespace", None)
+ return result
children = choice.get("tools")
if isinstance(children, list):
return {**choice, "tools": [self._choice(tool) for tool in children]}
return choice
- def _custom(self, item: Mapping[str, JsonValue]) -> ResponsesToolIdentity | None:
+ def _is_search(self, item: Mapping[str, JsonValue]) -> bool:
+ return (
+ self._search_name is not None
+ and item.get("name") == self._search_name
+ and _namespace(item) is None
+ )
+
+ def _identity(self, item: Mapping[str, JsonValue]) -> ResponsesToolIdentity | None:
name = item.get("name")
- if not isinstance(name, str):
+ if not isinstance(name, str) or self._is_search(item):
return None
namespace = _namespace(item)
- if namespace is not None:
- identity = self._identities.get((namespace, name))
- else:
+ key = (None if self._policy.flatten_namespaces else namespace, name)
+ exact = self._identities.get(key)
+ if exact is not None and (namespace is None or exact.namespace == namespace):
+ return exact
+ candidates = {
+ identity
+ for (_, wire_name), identity in self._identities.items()
+ if wire_name == name
+ and (namespace is None or identity.namespace == namespace)
+ }
+ if not candidates and self._policy.flatten_namespaces:
candidates = {
identity
- for (_, wire_name), identity in self._identities.items()
- if wire_name == name
+ for identity in self._declared
+ if (namespace is None or identity.namespace == namespace)
+ and name in (identity.name, f"{identity.namespace}.{identity.name}")
}
- identity = next(iter(candidates)) if len(candidates) == 1 else None
- return identity if identity is not None and identity.kind == "custom" else None
+ if len(candidates) > 1 and self._policy.flatten_namespaces:
+ raise ResponsesConversionError("Ambiguous tool name returned by provider.")
+ return next(iter(candidates)) if len(candidates) == 1 else None
+
+ def prepare_arguments(
+ self, name: str, arguments: str, *, namespace: str | None = None
+ ) -> str:
+ """Validate provider arguments before publishing a completed tool call."""
+ identity = self._identity({"name": name, "namespace": namespace})
+ if identity is not None and identity.kind == "custom":
+ return json.dumps(
+ {"input": custom_tool_input_text_from_arguments(arguments)},
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ try:
+ parsed = json.loads(
+ arguments,
+ parse_float=_canonical_number,
+ parse_constant=_reject_json_constant,
+ )
+ except ValueError as exc:
+ raise ResponsesConversionError("Invalid tool call arguments.") from exc
+ if not isinstance(parsed, dict):
+ raise ResponsesConversionError("Tool call arguments must be a JSON object.")
+ return simplejson.dumps(
+ parsed,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ allow_nan=False,
+ use_decimal=True,
+ )
def restore_item(self, value: JsonValue) -> JsonValue:
if not isinstance(value, dict):
@@ -206,9 +435,63 @@ class ResponsesToolAdapter:
**value,
"tools": self.restore_tools(value.get("tools"), scope=_scope(value)),
}
- if (
- value.get("type") != "function_call"
- or (identity := self._custom(value)) is None
+ if value.get("type") != "function_call":
+ return value
+ identity = self._identity(value)
+ if value.get("status") == "completed" and (
+ self._policy.client_tool_search or self._policy.flatten_namespaces
+ ):
+ raw = value.get("arguments")
+ value = {
+ **value,
+ "arguments": self.prepare_arguments(
+ _name(value),
+ raw if isinstance(raw, str) else "",
+ namespace=_namespace(value),
+ ),
+ }
+ if self._is_search(value):
+ raw = value.get("arguments")
+ try:
+ arguments = (
+ {}
+ if value.get("status") == "in_progress"
+ else json.loads(
+ raw,
+ parse_float=_canonical_number,
+ parse_constant=_reject_json_constant,
+ )
+ if isinstance(raw, str) and raw
+ else None
+ )
+ except ValueError as exc:
+ raise ResponsesConversionError(
+ "Invalid client search arguments."
+ ) from exc
+ if not isinstance(arguments, dict) or (
+ not raw and value.get("status") != "in_progress"
+ ):
+ raise ResponsesConversionError(
+ "Client search arguments must be a JSON object."
+ )
+ return {
+ **{
+ key: child
+ for key, child in value.items()
+ if key not in {"name", "namespace", "arguments"}
+ },
+ "type": "tool_search_call",
+ "execution": "client",
+ "arguments": arguments,
+ }
+ if identity is None:
+ return value
+ if self._policy.flatten_namespaces:
+ value = {**value, "name": identity.name}
+ if identity.namespace is not None:
+ value["namespace"] = identity.namespace
+ if identity.kind != "custom" or not (
+ self._policy.custom_tools_as_functions or self._policy.flatten_namespaces
):
return value
arguments = value.get("arguments")
@@ -230,6 +513,7 @@ class ResponsesToolAdapter:
if not isinstance(tools, list):
return tools
result: list[JsonValue] = []
+ namespaces: dict[str, JsonObject] = {}
for tool in tools:
if isinstance(tool, dict):
if tool.get("type") == "namespace":
@@ -239,14 +523,42 @@ class ResponsesToolAdapter:
tool.get("tools"), _name(tool), scope
),
}
+ if self._policy.flatten_namespaces and namespace is None:
+ name = _name(tool)
+ if name in namespaces:
+ cast(list[JsonValue], namespaces[name]["tools"]).extend(
+ cast(list[JsonValue], tool["tools"])
+ )
+ continue
+ namespaces[name] = tool
else:
+ identity = (
+ self._identity(
+ {**tool, "namespace": namespace or _namespace(tool)}
+ )
+ if self._policy.flatten_namespaces
+ and tool.get("type") in ("function", "custom")
+ else None
+ )
+ wire_name = (
+ self._wire_names[identity]
+ if identity is not None
+ else tool.get("name")
+ )
edits = [
edit
for edit in self._edits
- if edit.namespace == namespace
- and edit.adapted.get("type") == tool.get("type")
- and edit.adapted.get("name") == tool.get("name")
+ if edit.adapted.get("type") == tool.get("type")
+ and edit.adapted.get("name") == wire_name
]
+ if self._policy.flatten_namespaces and tool.get("type") in (
+ "function",
+ "custom",
+ ):
+ if identity is None:
+ edits = []
+ else:
+ edits = [edit for edit in edits if edit.namespace == namespace]
scoped = [edit for edit in edits if edit.scope == scope]
if scoped:
edits = scoped
@@ -268,6 +580,31 @@ class ResponsesToolAdapter:
tool[key] = deepcopy(edit.original[key])
else:
tool.pop(key, None)
+ elif identity is not None:
+ tool = {**tool, "name": identity.name}
+ if (
+ identity is not None
+ and identity.namespace is not None
+ and namespace is None
+ ):
+ name = identity.namespace
+ if name not in namespaces:
+ header = self._namespace_headers.get(
+ (scope, name),
+ self._namespace_headers.get(
+ (None, name), {"type": "namespace", "name": name}
+ ),
+ )
+ namespaces[name] = {**deepcopy(header), "tools": []}
+ result.append(namespaces[name])
+ cast(list[JsonValue], namespaces[name]["tools"]).append(
+ {
+ key: value
+ for key, value in tool.items()
+ if key != "namespace"
+ }
+ )
+ continue
result.append(tool)
return result
@@ -276,7 +613,8 @@ class ResponsesToolAdapter:
return value
if (
value.get("type") == "function"
- and (identity := self._custom(value)) is not None
+ and (identity := self._identity(value)) is not None
+ and identity.kind == "custom"
):
value = {**value, "type": "custom", "name": identity.name}
if identity.namespace is not None:
@@ -290,8 +628,11 @@ class ResponsesToolAdapter:
return value
def event_adapter(self) -> ResponsesToolEventAdapter | None:
- if self._edits or any(
- identity.kind == "custom" for identity in self._identities.values()
+ if (
+ self._policy.client_tool_search
+ or self._policy.flatten_namespaces
+ or self._edits
+ or any(identity.kind == "custom" for identity in self._identities.values())
):
return ResponsesToolEventAdapter(self)
return None
@@ -303,6 +644,8 @@ class ResponsesToolEventAdapter:
def __init__(self, tools: ResponsesToolAdapter) -> None:
self._tools = tools
self._custom_items: set[str] = set()
+ self._search_items: set[str] = set()
+ self._function_items: set[str] = set()
self._sequence = 0
def feed(
@@ -316,6 +659,38 @@ class ResponsesToolEventAdapter:
item = self._tools.restore_item(original_item)
if isinstance(item, dict):
data["item"] = item
+ if item.get("type") == "function_call" and (
+ self._tools._policy.client_tool_search
+ or self._tools._policy.flatten_namespaces
+ ):
+ if isinstance(item_id := item.get("id"), str):
+ self._function_items.add(item_id)
+ if event_type == "response.output_item.added":
+ item["arguments"] = ""
+ if (
+ event_type == "response.output_item.done"
+ and item.get("status") == "completed"
+ ):
+ coordinates = {
+ "item_id": item.get("id"),
+ "output_index": data.get("output_index"),
+ }
+ arguments = item.get("arguments", "")
+ yield self._emit(
+ "response.function_call_arguments.delta",
+ {**coordinates, "delta": arguments},
+ )
+ identity = {
+ key: item[key] for key in ("name", "namespace") if key in item
+ }
+ yield self._emit(
+ "response.function_call_arguments.done",
+ {**coordinates, **identity, "arguments": arguments},
+ )
+ if item.get("type") == "tool_search_call" and isinstance(
+ item_id := item.get("id"), str
+ ):
+ self._search_items.add(item_id)
if (
isinstance(original_item, dict)
and original_item.get("type") == "function_call"
@@ -323,6 +698,8 @@ class ResponsesToolEventAdapter:
):
if isinstance(item_id := item.get("id"), str):
self._custom_items.add(item_id)
+ if event_type == "response.output_item.added":
+ item["input"] = ""
if event_type == "response.output_item.done":
coordinates = {
"item_id": item.get("id"),
@@ -343,9 +720,19 @@ class ResponsesToolEventAdapter:
"response.function_call_arguments.delta",
"response.function_call_arguments.done",
}
- and data.get("item_id") in self._custom_items
+ and data.get("item_id")
+ in self._custom_items | self._search_items | self._function_items
):
return
+ if (
+ self._tools._policy.flatten_namespaces
+ and event_type == "response.function_call_arguments.done"
+ ):
+ identity = self._tools._identity(data)
+ if identity is not None:
+ data["name"] = identity.name
+ if identity.namespace is not None:
+ data["namespace"] = identity.namespace
response = data.get("response")
if isinstance(response, dict):
if isinstance(output := response.get("output"), list):
@@ -353,10 +740,18 @@ class ResponsesToolEventAdapter:
self._tools.restore_item(value) for value in output
]
if "tools" in response:
- response["tools"] = self._tools.restore_tools(response["tools"])
+ response["tools"] = (
+ deepcopy(self._tools.original.tools or [])
+ if self._tools._policy.client_tool_search
+ or self._tools._policy.flatten_namespaces
+ else self._tools.restore_tools(response["tools"])
+ )
if "tool_choice" in response:
- response["tool_choice"] = self._tools.restore_choice(
- response["tool_choice"]
+ response["tool_choice"] = (
+ self._tools.original.tool_choice or "auto"
+ if self._tools._policy.client_tool_search
+ or self._tools._policy.flatten_namespaces
+ else self._tools.restore_choice(response["tool_choice"])
)
yield self._emit(event_type, data)
@@ -370,9 +765,42 @@ def _name(value: Mapping[str, JsonValue]) -> str:
return required_str(value.get("name"), "tool.name")
+def _definition_identity(
+ value: Mapping[str, JsonValue], namespace: str | None = None
+) -> ResponsesToolIdentity:
+ kind = "custom" if value.get("type") == "custom" else "function"
+ nested = value.get(kind)
+ if value.get("type") == "tool" and isinstance(value.get("custom"), dict):
+ nested = value["custom"]
+ source = nested if isinstance(nested, dict) else value
+ return ResponsesToolIdentity(
+ kind=kind,
+ name=_name(source),
+ namespace=namespace or _namespace(source) or _namespace(value),
+ )
+
+
+def _call_identity(item: Mapping[str, JsonValue]) -> ResponsesToolIdentity:
+ return ResponsesToolIdentity(
+ kind="custom" if item.get("type") == "custom_tool_call" else "function",
+ name=_name(item),
+ namespace=_namespace(item),
+ )
+
+
def _namespace(value: Mapping[str, JsonValue]) -> str | None:
return optional_str(value.get("namespace"))
def _scope(value: Mapping[str, JsonValue]) -> str | None:
return optional_str(value.get("call_id")) or optional_str(value.get("id"))
+
+
+def _canonical_number(value: str) -> int | Decimal:
+ """Codex integer parameters reject equivalent JSON floats such as 8.0."""
+ number = Decimal(value)
+ return int(number) if number == number.to_integral_value() else number
+
+
+def _reject_json_constant(value: str) -> Never:
+ raise ValueError(f"Non-finite JSON constant: {value}")
diff --git a/src/free_claude_code/core/openai_responses/tool_search.py b/src/free_claude_code/core/openai_responses/tool_search.py
index 16e5d50b..12177fbe 100644
--- a/src/free_claude_code/core/openai_responses/tool_search.py
+++ b/src/free_claude_code/core/openai_responses/tool_search.py
@@ -1,9 +1,147 @@
-"""Explicit argument schemas for providers requiring every search property."""
+"""Request-scoped client discovery and provider search argument schemas."""
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
+from copy import deepcopy
+from dataclasses import dataclass
+from typing import cast
from free_claude_code.core.json_types import JsonObject, JsonValue
+from .errors import ResponsesConversionError
+from .tools import optional_str, required_str
+
+
+def is_client_search(value: Mapping[str, JsonValue]) -> bool:
+ return value.get("execution") == "client" and value.get("type") in {
+ "tool_search",
+ "tool_search_call",
+ "tool_search_output",
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ClientSearchHistory:
+ client_items: frozenset[int]
+ output_tools: dict[int, list[JsonObject]]
+
+
+def resolve_client_search_history(items: JsonValue) -> ClientSearchHistory:
+ """Infer omitted execution only from search records with the same call ID."""
+ if not isinstance(items, list):
+ return ClientSearchHistory(frozenset(), {})
+ searches = {
+ index: item
+ for index, item in enumerate(items)
+ if isinstance(item, dict)
+ and item.get("type") in ("tool_search_call", "tool_search_output")
+ }
+ executions: dict[str, str] = {}
+ for item in searches.values():
+ call_id, execution = item.get("call_id"), item.get("execution")
+ if (
+ not isinstance(call_id, str)
+ or not call_id
+ or execution not in ("client", "server")
+ ):
+ continue
+ if call_id in executions and executions[call_id] != execution:
+ raise ResponsesConversionError(
+ "Conflicting tool search execution for one call ID."
+ )
+ executions[call_id] = cast(str, execution)
+ client_items: set[int] = set()
+ outputs: dict[int, list[JsonObject]] = {}
+ for index, item in searches.items():
+ execution = item.get("execution")
+ call_id = item.get("call_id")
+ if execution is None and isinstance(call_id, str) and call_id:
+ execution = executions.get(call_id)
+ if execution != "client":
+ continue
+ client_items.add(index)
+ if item.get("type") == "tool_search_output":
+ tools = item.get("tools")
+ accepted = item.get("status") in (None, "completed") and isinstance(
+ tools, list
+ )
+ outputs[index] = _merge_tool_groups(
+ [
+ [tool for tool in tools if isinstance(tool, dict)]
+ if accepted and isinstance(tools, list)
+ else [],
+ [],
+ ]
+ )
+ return ClientSearchHistory(frozenset(client_items), outputs)
+
+
+def active_client_tools(
+ tools: list[JsonObject] | None, history: ClientSearchHistory
+) -> list[JsonObject]:
+ """Resolve discoveries in history order, with explicit current tools last."""
+ return _merge_tool_groups([*history.output_tools.values(), tools or []])
+
+
+def _merge_tool_groups(groups: list[list[JsonObject]]) -> list[JsonObject]:
+ active: dict[tuple[str, str | None, str], JsonObject] = {}
+ hosted: list[JsonObject] = []
+ for group in groups:
+ declarations: dict[tuple[str, str | None, str], JsonObject] = {}
+ for tool in group:
+ namespace = None
+ children = [tool]
+ if tool.get("type") == "namespace":
+ namespace = required_str(tool.get("name"), "tool.namespace.name")
+ value = tool.get("tools")
+ if not isinstance(value, list):
+ raise ResponsesConversionError("Namespace tools must be a list.")
+ children = [child for child in value if isinstance(child, dict)]
+ for child in children:
+ kind = child.get("type")
+ if kind not in {"function", "custom"}:
+ if group is groups[-1]:
+ hosted.append(deepcopy(child))
+ continue
+ source = child.get(str(kind))
+ definition = deepcopy(source if isinstance(source, dict) else child)
+ definition["type"] = kind
+ definition.pop("defer_loading", None)
+ name = required_str(definition.get("name"), "tool.name")
+ ns = (
+ namespace
+ or optional_str(definition.get("namespace"))
+ or optional_str(child.get("namespace"))
+ )
+ if ns is not None:
+ definition["namespace"] = ns
+ identity = (str(kind), ns, name)
+ if identity in declarations and declarations[identity] != definition:
+ raise ResponsesConversionError("Conflicting tool definitions.")
+ declarations[identity] = definition
+ active.update(declarations)
+ result = list(hosted)
+ namespaces: dict[str, JsonObject] = {}
+ for (_, ns, _), definition in active.items():
+ if ns is None:
+ result.append(definition)
+ else:
+ if ns not in namespaces:
+ namespaces[ns] = {"type": "namespace", "name": ns, "tools": []}
+ result.append(namespaces[ns])
+ definition.pop("namespace", None)
+ cast(list[JsonValue], namespaces[ns]["tools"]).append(definition)
+ return result
+
+
+def search_function_name(reserved: Iterable[str]) -> str:
+ names = set(reserved)
+ name = "fcc_tool_search"
+ suffix = 0
+ while name in names:
+ suffix += 1
+ name = f"fcc_tool_search_{suffix}"
+ return name
+
def normalize_tool_search(tool: JsonObject) -> JsonObject:
"""Represent omitted search arguments as null without changing function tools."""
diff --git a/src/free_claude_code/core/openai_responses/tools.py b/src/free_claude_code/core/openai_responses/tools.py
index cb8eaee5..73752837 100644
--- a/src/free_claude_code/core/openai_responses/tools.py
+++ b/src/free_claude_code/core/openai_responses/tools.py
@@ -41,63 +41,6 @@ def flatten_responses_tool_name(name: str, *, namespace: str | None = None) -> s
return f"{combined[:prefix_len]}_{digest}"
-def responses_tool_identity_from_wire_name(
- tools: list[dict[str, Any]] | None, wire_name: str
-) -> ResponsesToolIdentity:
- """Return the Responses namespace/name represented by a flat tool name."""
-
- if tools is None:
- return ResponsesToolIdentity(kind="function", name=wire_name)
- for tool in tools:
- if not isinstance(tool, dict):
- continue
- tool_type = tool.get("type")
- if tool_type == "function":
- source = tool.get("function")
- function = source if isinstance(source, dict) else tool
- if (name := optional_str(function.get("name"))) and (
- flatten_responses_tool_name(name) == wire_name
- ):
- return ResponsesToolIdentity(kind="function", name=name)
- continue
- if tool_type == "custom":
- source = custom_tool_source(tool)
- if (name := optional_str(source.get("name"))) and (
- flatten_responses_tool_name(name) == wire_name
- ):
- return ResponsesToolIdentity(kind="custom", name=name)
- continue
- if tool_type != "namespace":
- continue
- namespace = optional_str(tool.get("name"))
- nested_tools = tool.get("tools")
- if not namespace or not isinstance(nested_tools, list):
- continue
- for nested_tool in nested_tools:
- if not isinstance(nested_tool, dict):
- continue
- nested_tool_type = nested_tool.get("type")
- if nested_tool_type == "function":
- source = nested_tool.get("function")
- function = source if isinstance(source, dict) else nested_tool
- if (name := optional_str(function.get("name"))) and (
- flatten_responses_tool_name(name, namespace=namespace) == wire_name
- ):
- return ResponsesToolIdentity(
- kind="function", name=name, namespace=namespace
- )
- continue
- if nested_tool_type == "custom":
- source = custom_tool_source(nested_tool)
- if (name := optional_str(source.get("name"))) and (
- flatten_responses_tool_name(name, namespace=namespace) == wire_name
- ):
- return ResponsesToolIdentity(
- kind="custom", name=name, namespace=namespace
- )
- return ResponsesToolIdentity(kind="function", name=wire_name)
-
-
def parse_arguments(value: Any) -> dict[str, Any]:
if value is None or value == "":
return {}
diff --git a/src/free_claude_code/providers/openai_chat/provider.py b/src/free_claude_code/providers/openai_chat/provider.py
index 475b4ad2..e4ab9c13 100644
--- a/src/free_claude_code/providers/openai_chat/provider.py
+++ b/src/free_claude_code/providers/openai_chat/provider.py
@@ -757,6 +757,7 @@ class OpenAIChatProvider(BaseProvider):
tool_names=translated.tool_names,
tool_schemas=translated.tool_schemas,
reserved_tool_ids=translated.reserved_tool_ids,
+ tool_adapter=translated.tool_adapter,
)
def _finalize_chat_body(
@@ -1113,7 +1114,7 @@ class OpenAIChatProvider(BaseProvider):
tool_schemas=tool_schemas,
reserved_tool_ids=translated.reserved_tool_ids,
output_factory=lambda: ResponsesChatStreamOutput(
- request,
+ translated.tool_adapter,
input_tokens=input_tokens,
response_model=public_model,
),
diff --git a/src/free_claude_code/providers/openai_chat/stream_output.py b/src/free_claude_code/providers/openai_chat/stream_output.py
index f328bf61..1b98d0d0 100644
--- a/src/free_claude_code/providers/openai_chat/stream_output.py
+++ b/src/free_claude_code/providers/openai_chat/stream_output.py
@@ -23,12 +23,12 @@ from free_claude_code.core.history_replay import (
)
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.openai_responses import (
- OpenAIResponsesRequest,
ReasoningBlockState,
ResponseBlockCompleter,
ResponseEventBuilder,
ResponsesConversionError,
ResponsesOutputLedger,
+ ResponsesToolAdapter,
TextBlockState,
ToolBlockState,
new_call_id,
@@ -38,7 +38,6 @@ from free_claude_code.core.openai_responses import (
openai_error_from_failure,
reasoning_output_item,
replay_unsafe_function_call_error,
- responses_tool_identity_from_wire_name,
tool_item,
)
from free_claude_code.core.token_estimation import estimate_text_tokens
@@ -487,22 +486,24 @@ class ResponsesChatStreamOutput(ChatStreamOutput):
def __init__(
self,
- request: OpenAIResponsesRequest,
+ tool_adapter: ResponsesToolAdapter,
*,
input_tokens: int,
response_model: str | None = None,
) -> None:
super().__init__(input_tokens=input_tokens)
- self._request = request
- self._response_model = response_model or request.model
+ self._request = tool_adapter.original
+ self._response_model = response_model or self._request.model
self._response_id = new_response_id()
self._created_at = int(time.time())
self._ledger = ResponsesOutputLedger()
- self._events = ResponseEventBuilder()
+ tool_events = tool_adapter.event_adapter()
+ self._events = ResponseEventBuilder(tool_events.feed if tool_events else None)
self._completer = ResponseBlockCompleter(
self._ledger,
events=self._events,
on_invalid_function_call=self._fail_invalid_function_call,
+ prepare_tool_arguments=tool_adapter.prepare_arguments,
)
self._text_state: TextBlockState | None = None
self._reasoning_state: ReasoningBlockState | None = None
@@ -649,19 +650,14 @@ class ResponsesChatStreamOutput(ChatStreamOutput):
return self._completer.complete_block(state)
def _start_tool_block(self, tool_index: int, state: ChatToolState) -> str:
- identity = responses_tool_identity_from_wire_name(
- self._request.tools, state.name
- )
output_index = self._ledger.reserve_output_slot()
output_state = ToolBlockState(
index=output_index,
output_index=output_index,
- item_id=f"{'ctc' if identity.kind == 'custom' else 'fc'}_"
- f"{uuid.uuid4().hex[:24]}",
+ item_id=f"fc_{uuid.uuid4().hex[:24]}",
call_id=state.tool_id or new_call_id(),
- kind=identity.kind,
- name=identity.name,
- namespace=identity.namespace,
+ kind="function",
+ name=state.name,
)
self._tool_output_states[tool_index] = output_state
self._ledger.set_active_block(output_state)
diff --git a/src/free_claude_code/providers/opencode/provider.py b/src/free_claude_code/providers/opencode/provider.py
index 8f6ae0da..bad27a61 100644
--- a/src/free_claude_code/providers/opencode/provider.py
+++ b/src/free_claude_code/providers/opencode/provider.py
@@ -106,6 +106,8 @@ class OpenCodeProvider(OpenAIChatProvider):
custom_tools_as_functions=True,
explicit_search_parameters=True,
text_only_web_search=True,
+ client_tool_search=True,
+ flatten_namespaces=True,
),
)
diff --git a/tests/core/openai_responses/test_chat_request.py b/tests/core/openai_responses/test_chat_request.py
index 7539439d..8b6d3f0c 100644
--- a/tests/core/openai_responses/test_chat_request.py
+++ b/tests/core/openai_responses/test_chat_request.py
@@ -175,6 +175,7 @@ def test_build_responses_chat_request_preserves_rich_supported_semantics() -> No
"type": "function",
"function": {
"name": "apply patch",
+ "strict": False,
"description": (
"Apply a patch\n\nCustom tool input format: unconstrained text."
),
@@ -667,7 +668,7 @@ def test_build_responses_chat_request_rejects_message_with_only_file_id_image()
def test_build_responses_chat_request_rejects_colliding_tool_wire_names() -> None:
- with pytest.raises(ResponsesConversionError, match="same Chat-compatible name"):
+ with pytest.raises(ResponsesConversionError, match="collide"):
build_responses_chat_request(
_request(
tools=[
diff --git a/tests/core/openai_responses/test_client_tool_discovery.py b/tests/core/openai_responses/test_client_tool_discovery.py
new file mode 100644
index 00000000..13e44d89
--- /dev/null
+++ b/tests/core/openai_responses/test_client_tool_discovery.py
@@ -0,0 +1,1590 @@
+import json
+from copy import deepcopy
+from decimal import Decimal
+from typing import Any, cast
+
+import pytest
+from openai import omit
+from openai.lib.streaming.responses._responses import ResponseStreamState
+from openai.types.responses import ResponseStreamEvent
+from pydantic import TypeAdapter
+
+from free_claude_code.core.anthropic import ReasoningReplayMode
+from free_claude_code.core.anthropic.stream_contracts import parse_sse_text
+from free_claude_code.core.json_types import JsonObject
+from free_claude_code.core.openai_responses import (
+ OpenAIResponsesRequest,
+ ResponsesConversionError,
+ ResponsesToolAdapter,
+ ResponsesToolPolicy,
+ build_responses_chat_request,
+)
+from free_claude_code.providers.openai_chat.stream_output import (
+ ChatStreamUsage,
+ ResponsesChatStreamOutput,
+)
+from free_claude_code.providers.openai_responses.presentation import (
+ NativeResponsesPresenter,
+)
+from tests.providers.test_opencode import _responses_event_stream
+
+SEARCH: JsonObject = {
+ "type": "tool_search",
+ "execution": "client",
+ "description": "Find callable tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ "additionalProperties": False,
+ },
+}
+AGENTS: JsonObject = {
+ "type": "namespace",
+ "name": "agents",
+ "tools": [
+ {
+ "type": "function",
+ "name": "spawn_agent",
+ "defer_loading": True,
+ "parameters": {
+ "type": "object",
+ "properties": {"message": {"type": "string"}},
+ "required": ["message"],
+ },
+ }
+ ],
+}
+
+
+def test_chat_exposes_client_search_as_a_callable_function() -> None:
+ request = OpenAIResponsesRequest(
+ model="example", input="Find an agent", tools=[SEARCH]
+ )
+ translated = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ )
+ functions = cast(list[dict[str, Any]], translated.body.get("tools", []))
+ assert len(functions) == 1
+ assert functions[0]["function"]["parameters"] == SEARCH["parameters"]
+
+
+def test_chat_discovery_preserves_pairing_and_activates_returned_tool() -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[
+ {"role": "user", "content": "Find an agent"},
+ {
+ "type": "tool_search_call",
+ "call_id": "search",
+ "execution": "client",
+ "status": "completed",
+ "arguments": {"query": "agent"},
+ },
+ {
+ "type": "tool_search_output",
+ "call_id": "search",
+ "execution": "client",
+ "status": "completed",
+ "tools": [AGENTS],
+ },
+ ],
+ )
+ original = request.model_dump()
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ functions = {
+ t["function"]["name"]: t["function"]
+ for t in cast(list[dict[str, Any]], body.get("tools", []))
+ }
+ assert "agents__spawn_agent" in functions
+ messages = cast(list[dict[str, Any]], body["messages"])
+ assert messages[1]["tool_calls"][0]["id"] == "search"
+ assert json.loads(messages[1]["tool_calls"][0]["function"]["arguments"]) == {
+ "query": "agent"
+ }
+ assert messages[2]["role"] == "tool"
+ assert messages[2]["tool_call_id"] == "search"
+ assert "spawn_agent" in messages[2]["content"]
+ assert request.model_dump() == original
+
+
+def test_unique_bare_tool_name_restores_declared_namespace() -> None:
+ item = cast(
+ dict[str, Any],
+ _native_adapter([AGENTS]).restore_item(
+ {
+ "type": "function_call",
+ "name": "spawn_agent",
+ "arguments": '{"message":"hello"}',
+ }
+ ),
+ )
+ assert item["name"] == "spawn_agent"
+ assert item["namespace"] == "agents"
+
+
+def _native_adapter(tools: list[JsonObject]) -> ResponsesToolAdapter:
+ return ResponsesToolAdapter(
+ OpenAIResponsesRequest(model="example", input="hello", tools=tools),
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ client_tool_search=True,
+ flatten_namespaces=True,
+ ),
+ )
+
+
+def test_ordinary_request_definitions_remain_unchanged_without_discovery() -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="hello",
+ tools=[{**AGENTS, "description": "Agent tools"}, {"type": "web_search"}],
+ )
+ adapter = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(client_tool_search=True)
+ )
+ assert adapter.request.tools == request.tools
+
+
+def test_native_namespaced_argument_done_event_matches_completed_item() -> None:
+ adapter = _native_adapter([AGENTS])
+ events = adapter.event_adapter()
+ assert events is not None
+ item: JsonObject = {
+ "type": "function_call",
+ "id": "fc_one",
+ "call_id": "one",
+ "name": "agents__spawn_agent",
+ "arguments": "",
+ "status": "in_progress",
+ }
+ added = list(
+ events.feed("response.output_item.added", {"item": item, "output_index": 0})
+ )
+ assert cast(dict[str, Any], added[-1][1]["item"])["name"] == "spawn_agent"
+ done = list(
+ events.feed(
+ "response.function_call_arguments.done",
+ {
+ "item_id": "fc_one",
+ "name": "agents__spawn_agent",
+ "arguments": '{"message":"hello"}',
+ "output_index": 0,
+ },
+ )
+ )
+ assert done == []
+ completed = list(
+ events.feed(
+ "response.output_item.done",
+ {
+ "output_index": 0,
+ "item": {
+ **item,
+ "status": "completed",
+ "arguments": '{"message":"hello"}',
+ },
+ },
+ )
+ )
+ done_event = next(
+ data
+ for kind, data in completed
+ if kind == "response.function_call_arguments.done"
+ )
+ assert done_event["name"] == "spawn_agent"
+ assert done_event["namespace"] == "agents"
+
+
+def test_native_rejects_ambiguous_bare_names() -> None:
+ other = deepcopy(AGENTS)
+ other["name"] = "other"
+ adapter = _native_adapter([AGENTS, other])
+ with pytest.raises(ResponsesConversionError, match="Ambiguous"):
+ adapter.restore_item(
+ {
+ "type": "function_call",
+ "name": "spawn_agent",
+ "arguments": '{"message":"hello"}',
+ "status": "completed",
+ }
+ )
+
+
+def test_native_search_buffers_partial_added_arguments() -> None:
+ adapter = _native_adapter([SEARCH])
+ events = adapter.event_adapter()
+ assert events is not None
+ added = list(
+ events.feed(
+ "response.output_item.added",
+ {
+ "item": {
+ "type": "function_call",
+ "id": "fc_search",
+ "call_id": "search",
+ "name": "fcc_tool_search",
+ "status": "in_progress",
+ "arguments": '{"query":',
+ }
+ },
+ )
+ )
+ assert cast(dict[str, Any], added[-1][1]["item"])["type"] == "tool_search_call"
+ assert cast(dict[str, Any], added[-1][1]["item"])["arguments"] == {}
+ assert (
+ list(
+ events.feed(
+ "response.function_call_arguments.delta",
+ {"item_id": "fc_search", "delta": '"agent"}'},
+ )
+ )
+ == []
+ )
+ completed = list(
+ events.feed(
+ "response.output_item.done",
+ {
+ "item": {
+ "type": "function_call",
+ "id": "fc_search",
+ "call_id": "search",
+ "name": "fcc_tool_search",
+ "status": "completed",
+ "arguments": '{"query":"agent"}',
+ }
+ },
+ )
+ )
+ assert cast(dict[str, Any], completed[-1][1]["item"])["arguments"] == {
+ "query": "agent"
+ }
+
+
+def test_native_does_not_publish_empty_completed_arguments_as_success() -> None:
+ adapter = _native_adapter([AGENTS])
+ with pytest.raises(ResponsesConversionError, match="arguments"):
+ adapter.restore_item(
+ {
+ "type": "function_call",
+ "name": "agents__spawn_agent",
+ "status": "completed",
+ "arguments": "",
+ }
+ )
+
+
+def test_search_lowering_does_not_shadow_a_real_function() -> None:
+ adapter = _native_adapter(
+ [
+ SEARCH,
+ {
+ "type": "function",
+ "name": "fcc_tool_search",
+ "parameters": {"type": "object"},
+ },
+ ]
+ )
+ assert len({tool["name"] for tool in (adapter.request.tools or [])}) == 2
+ result = adapter.restore_item(
+ {
+ "type": "function_call",
+ "name": "fcc_tool_search",
+ "status": "completed",
+ "arguments": "{}",
+ }
+ )
+ assert isinstance(result, dict)
+ assert result["type"] == "function_call"
+
+
+def test_flattened_function_collision_is_rejected() -> None:
+ with pytest.raises(ResponsesConversionError, match="collide"):
+ _native_adapter(
+ [
+ AGENTS,
+ {
+ "type": "function",
+ "name": "agents__spawn_agent",
+ "parameters": {"type": "object"},
+ },
+ ]
+ )
+
+
[email protected]("search", [True, False])
+def test_integral_json_numbers_are_accepted_by_native_codex(search: bool) -> None:
+ adapter = _native_adapter([SEARCH, AGENTS])
+ value = adapter.restore_item(
+ {
+ "type": "function_call",
+ "name": "fcc_tool_search" if search else "agents__spawn_agent",
+ "status": "completed",
+ "arguments": '{"limit":8.0,"fraction":0.25,"nested":[30000.0]}',
+ }
+ )
+ assert isinstance(value, dict)
+ arguments = value["arguments"] if search else json.loads(str(value["arguments"]))
+ assert isinstance(arguments, dict)
+ assert type(arguments["limit"]) is int
+ assert arguments["fraction"] == 0.25
+ nested = arguments["nested"]
+ assert isinstance(nested, list)
+ assert type(nested[0]) is int
+
+
+def test_server_search_choice_stays_native() -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="hello",
+ tools=[{"type": "tool_search", "execution": "server"}],
+ tool_choice={"type": "tool_search", "execution": "server"},
+ )
+ adapter = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(client_tool_search=True, flatten_namespaces=True)
+ )
+ assert adapter.request.tool_choice == request.tool_choice
+
+
+def test_latest_discovery_and_explicit_definitions_have_stable_precedence() -> None:
+ def declaration(description: str) -> JsonObject:
+ return {
+ "type": "function",
+ "name": "lookup",
+ "description": description,
+ "parameters": {"type": "object"},
+ "defer_loading": True,
+ }
+
+ history = [
+ {
+ "type": "tool_search_output",
+ "call_id": str(i),
+ "execution": "client",
+ "status": "completed",
+ "tools": tools,
+ }
+ for i, tools in enumerate([[declaration("old")], [declaration("new")], []])
+ ]
+ request = OpenAIResponsesRequest(model="example", input=history, tools=[SEARCH])
+ adapter = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(client_tool_search=True)
+ )
+ definitions = adapter.request.tools or []
+ assert len(definitions) == 2
+ assert (
+ next(t for t in definitions if t.get("name") == "lookup")["description"]
+ == "new"
+ )
+ explicit = request.model_copy(update={"tools": [SEARCH, declaration("current")]})
+ definitions = (
+ ResponsesToolAdapter(
+ explicit, ResponsesToolPolicy(client_tool_search=True)
+ ).request.tools
+ or []
+ )
+ assert (
+ next(t for t in definitions if t.get("name") == "lookup")["description"]
+ == "current"
+ )
+ assert all("defer_loading" not in tool for tool in definitions)
+
+
+def test_conflicting_discovered_definitions_are_rejected() -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input=[
+ {
+ "type": "tool_search_output",
+ "execution": "client",
+ "status": "completed",
+ "call_id": "search",
+ "tools": [
+ {
+ "type": "function",
+ "name": "lookup",
+ "parameters": {"type": "object"},
+ },
+ {
+ "type": "function",
+ "name": "lookup",
+ "parameters": {"type": "string"},
+ },
+ ],
+ }
+ ],
+ tools=[SEARCH],
+ )
+ with pytest.raises(ResponsesConversionError, match="Conflicting"):
+ ResponsesToolAdapter(request, ResponsesToolPolicy(client_tool_search=True))
+
+
+def test_native_custom_namespace_is_removed_from_provider_definition() -> None:
+ adapter = _native_adapter(
+ [
+ {
+ "type": "custom",
+ "namespace": "editor",
+ "name": "edit",
+ "format": {"type": "text"},
+ }
+ ]
+ )
+ tool = (adapter.request.tools or [])[0]
+ assert tool["name"] == "editor__edit"
+ assert "namespace" not in tool
+
+
+def test_real_unnamespaced_tool_wins_over_bare_namespace_alias() -> None:
+ tools: list[JsonObject] = [
+ AGENTS,
+ {"type": "function", "name": "spawn_agent", "parameters": {"type": "object"}},
+ ]
+ item = cast(
+ dict[str, Any],
+ _native_adapter(tools).restore_item(
+ {"type": "function_call", "name": "spawn_agent", "arguments": "{}"}
+ ),
+ )
+ assert "namespace" not in item
+
+
[email protected]("prefix", ["", '{"limit":', '{"limit":8.0}'])
+def test_native_canonical_arguments_agree_across_the_stream(prefix: str) -> None:
+ adapter = _native_adapter([{**AGENTS, "description": "Agent tools"}])
+ stream = adapter.event_adapter()
+ assert stream is not None
+ item: JsonObject = {
+ "type": "function_call",
+ "id": "fc_one",
+ "call_id": "one",
+ "name": "agents__spawn_agent",
+ "status": "in_progress",
+ "arguments": prefix,
+ }
+ created = parse_sse_text(_responses_event_stream(""))[0].data
+ events = list(stream.feed("response.created", created))
+ events.extend(
+ stream.feed("response.output_item.added", {"item": item, "output_index": 0})
+ )
+ for fragment in ['{"limit":8.0}'[len(prefix) :]]:
+ events.extend(
+ stream.feed(
+ "response.function_call_arguments.delta",
+ {"item_id": "fc_one", "output_index": 0, "delta": fragment},
+ )
+ )
+ events.extend(
+ stream.feed(
+ "response.function_call_arguments.done",
+ {
+ "item_id": "fc_one",
+ "output_index": 0,
+ "name": "agents__spawn_agent",
+ "arguments": '{"limit":8.0}',
+ },
+ )
+ )
+ events.extend(
+ stream.feed(
+ "response.output_item.done",
+ {
+ "output_index": 0,
+ "item": {**item, "status": "completed", "arguments": '{"limit":8.0}'},
+ },
+ )
+ )
+ completed = cast(dict[str, Any], events[-1][1]["item"])
+ delta = "".join(
+ str(data["delta"])
+ for kind, data in events
+ if kind == "response.function_call_arguments.delta"
+ )
+ done = next(
+ data for kind, data in events if kind == "response.function_call_arguments.done"
+ )
+ assert delta == done["arguments"] == completed["arguments"]
+ sdk: ResponseStreamState[Any] = ResponseStreamState(
+ input_tools=omit, text_format=omit
+ )
+ parser: TypeAdapter[ResponseStreamEvent] = TypeAdapter(ResponseStreamEvent)
+ snapshots = [
+ event.snapshot
+ for _, data in events
+ for event in sdk.handle_event(parser.validate_python(data))
+ if event.type == "response.function_call_arguments.delta"
+ ]
+ assert snapshots == [completed["arguments"]]
+
+
+ ("prefix", "arguments"),
+ [
+ ("", '{"input":"whole"}'),
+ ('{"input":', '{"input":"whole"}'),
+ ('{"input":"whole"}', '{"input":"whole"}'),
+ ("wh", "whole"),
+ ],
+)
+def test_native_custom_input_is_emitted_once_when_buffered(
+ prefix: str, arguments: str
+) -> None:
+ adapter = _native_adapter([{"type": "custom", "name": "edit"}])
+ stream = adapter.event_adapter()
+ assert stream is not None
+ item: JsonObject = {
+ "type": "function_call",
+ "id": "fc",
+ "call_id": "call",
+ "name": "edit",
+ "status": "in_progress",
+ "arguments": prefix,
+ }
+ events = list(
+ stream.feed("response.output_item.added", {"output_index": 0, "item": item})
+ )
+ events.extend(
+ stream.feed(
+ "response.function_call_arguments.delta",
+ {"output_index": 0, "item_id": "fc", "delta": arguments[len(prefix) :]},
+ )
+ )
+ events.extend(
+ stream.feed(
+ "response.output_item.done",
+ {
+ "output_index": 0,
+ "item": {**item, "status": "completed", "arguments": arguments},
+ },
+ )
+ )
+ added = cast(dict[str, Any], events[0][1]["item"])
+ completed = cast(dict[str, Any], events[-1][1]["item"])
+ assembled = added["input"] + "".join(
+ str(data["delta"])
+ for kind, data in events
+ if kind == "response.custom_tool_call_input.delta"
+ )
+ assert assembled == completed["input"] == "whole"
+
+
+def test_unspecified_tool_metadata_keeps_native_defaults() -> None:
+ adapter = _native_adapter([])
+ events = adapter.event_adapter()
+ assert events is not None
+ result = list(
+ events.feed(
+ "response.completed",
+ {"response": {"output": [], "tools": [], "tool_choice": "auto"}},
+ )
+ )
+ response = cast(dict[str, Any], result[-1][1]["response"])
+ assert response["tool_choice"] == "auto"
+ assert response["tools"] == []
+
+
[email protected]("discovery", [False, True])
+def test_chat_forced_namespaced_custom_choice_is_lowered_once(discovery: bool) -> None:
+ custom: JsonObject = {
+ "type": "namespace",
+ "name": "editor",
+ "tools": [{"type": "custom", "name": "edit", "format": {"type": "text"}}],
+ }
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Edit the file",
+ tools=[custom, SEARCH] if discovery else [custom],
+ tool_choice={"type": "custom", "namespace": "editor", "name": "edit"},
+ )
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ assert body.get("tool_choice") == {
+ "type": "function",
+ "function": {"name": "editor__edit"},
+ }
+ functions = cast(list[dict[str, Any]], body["tools"])
+ assert any(tool["function"]["name"] == "editor__edit" for tool in functions)
+
+
[email protected]("native", [False, True])
[email protected]("namespace", [None, "editor"])
[email protected]("custom", [False, True])
[email protected]("nested", [False, True])
+def test_generic_choice_uses_declared_tool_kind(
+ native: bool, namespace: str | None, custom: bool, nested: bool
+) -> None:
+ definition: JsonObject = {
+ "type": "custom" if custom else "function",
+ "name": "edit",
+ }
+ if custom:
+ definition["format"] = {"type": "text"}
+ else:
+ definition["parameters"] = {"type": "object"}
+ choice: JsonObject = {"type": "tool", "name": "edit"}
+ tools = [definition]
+ if namespace:
+ tools = [{"type": "namespace", "name": namespace, "tools": tools}]
+ choice["namespace"] = namespace
+ if nested:
+ choice = {
+ "type": "tool",
+ "custom" if custom else "function": {
+ key: value for key, value in choice.items() if key != "type"
+ },
+ }
+ request = OpenAIResponsesRequest(
+ model="example", input="Edit", tools=tools, tool_choice=choice
+ )
+ original = request.model_dump()
+ wire_name = "editor__edit" if namespace else "edit"
+ if native:
+ prepared = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True, flatten_namespaces=True
+ ),
+ ).request
+ assert prepared.tool_choice == {"type": "function", "name": wire_name}
+ assert prepared.tools and prepared.tools[0]["name"] == wire_name
+ else:
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ assert body["tool_choice"] == {
+ "type": "function",
+ "function": {"name": wire_name},
+ }
+ assert (
+ cast(list[dict[str, Any]], body["tools"])[0]["function"]["name"]
+ == wire_name
+ )
+ assert request.model_dump() == original
+
+
[email protected]("native", [False, True])
+ "status", ["omitted", None, "completed", "in_progress", "incomplete", "failed"]
+)
+def test_discovery_optional_status_preserves_valid_tools(
+ native: bool, status: str | None
+) -> None:
+ result: JsonObject = {
+ "type": "tool_search_output",
+ "execution": "client",
+ "call_id": "search",
+ "tools": [
+ {"type": "function", "name": "lookup", "parameters": {"type": "object"}}
+ ],
+ }
+ if status != "omitted":
+ result["status"] = status
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[
+ {"role": "user", "content": "Find lookup"},
+ {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "arguments": {"query": "lookup"},
+ },
+ result,
+ ],
+ )
+ original = request.model_dump()
+ if native:
+ adapter = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(client_tool_search=True, flatten_namespaces=True),
+ )
+ definitions = adapter.request.tools or []
+ names = [tool.get("name") for tool in definitions]
+ items = cast(list[dict[str, Any]], adapter.request.input)
+ payload = json.loads(items[-1]["output"])
+ assert items[-1]["call_id"] == "search"
+ else:
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ definitions = cast(list[dict[str, Any]], body["tools"])
+ names = [tool["function"]["name"] for tool in definitions]
+ messages = cast(list[dict[str, Any]], body["messages"])
+ payload = json.loads(messages[-1]["content"])
+ assert messages[-1]["tool_call_id"] == "search"
+ accepted = status in {"omitted", None, "completed"}
+ assert ("lookup" in names) is accepted
+ assert payload == (
+ [{"type": "function", "name": "lookup", "parameters": {"type": "object"}}]
+ if accepted
+ else []
+ )
+ assert request.model_dump() == original
+
+
[email protected]("native", [False, True])
[email protected]("missing_side", ["call", "output"])
[email protected]("missing", ["omitted", None])
+def test_discovery_execution_is_inferred_from_the_matching_record(
+ native: bool, missing_side: str, missing: str | None
+) -> None:
+ call: JsonObject = {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "arguments": {"query": "agent"},
+ }
+ result: JsonObject = {
+ "type": "tool_search_output",
+ "execution": "client",
+ "call_id": "search",
+ "tools": [AGENTS],
+ }
+ item = call if missing_side == "call" else result
+ if missing == "omitted":
+ item.pop("execution")
+ else:
+ item["execution"] = missing
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[{"role": "user", "content": "Find agent"}, call, result],
+ )
+ original = request.model_dump()
+ if native:
+ prepared = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(client_tool_search=True, flatten_namespaces=True),
+ ).request
+ items = cast(list[dict[str, Any]], prepared.input)
+ assert items[-2]["type"] == "function_call"
+ assert items[-1]["type"] == "function_call_output"
+ assert items[-2]["call_id"] == items[-1]["call_id"] == "search"
+ assert "agents__spawn_agent" in [
+ tool.get("name") for tool in prepared.tools or []
+ ]
+ assert "spawn_agent" in items[-1]["output"]
+ else:
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ items = cast(list[dict[str, Any]], body["messages"])
+ assert items[-2]["tool_calls"][0]["id"] == "search"
+ assert items[-1]["role"] == "tool"
+ assert items[-1]["tool_call_id"] == "search"
+ assert "spawn_agent" in items[-1]["content"]
+ assert "agents__spawn_agent" in [
+ tool["function"]["name"]
+ for tool in cast(list[dict[str, Any]], body["tools"])
+ ]
+ assert request.model_dump() == original
+
+
[email protected]("execution", ["server", "omitted"])
+def test_discovery_call_id_does_not_imply_client_execution(execution: str) -> None:
+ call: JsonObject = {
+ "type": "tool_search_call",
+ "call_id": "search",
+ "arguments": {"query": "agent"},
+ }
+ if execution != "omitted":
+ call["execution"] = execution
+ result: JsonObject = {
+ "type": "tool_search_output",
+ "call_id": "search",
+ "tools": [AGENTS],
+ }
+ request = OpenAIResponsesRequest(
+ model="example", input=[call, result], tools=[SEARCH]
+ )
+ prepared = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(client_tool_search=True, flatten_namespaces=True)
+ ).request
+ items = cast(list[dict[str, Any]], prepared.input)
+ assert [item["type"] for item in items] == [
+ "tool_search_call",
+ "tool_search_output",
+ ]
+ assert "agents__spawn_agent" not in [
+ tool.get("name") for tool in prepared.tools or []
+ ]
+
+
[email protected]("native", [False, True])
+def test_discovery_rejects_conflicting_execution_for_one_call(native: bool) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[
+ {"role": "user", "content": "Find agent"},
+ {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "arguments": {"query": "agent"},
+ },
+ {
+ "type": "tool_search_output",
+ "execution": "server",
+ "call_id": "search",
+ "tools": [AGENTS],
+ },
+ ],
+ )
+ with pytest.raises(ResponsesConversionError, match="execution"):
+ if native:
+ ResponsesToolAdapter(request, ResponsesToolPolicy(client_tool_search=True))
+ else:
+ build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ )
+
+
+def _completed_tool_events(
+ request: OpenAIResponsesRequest, *, native: bool, name: str, arguments: str
+) -> list[dict[str, Any]]:
+ if native:
+ adapter = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ client_tool_search=True,
+ flatten_namespaces=True,
+ ),
+ )
+ events = adapter.event_adapter()
+ assert events is not None
+ item: JsonObject = {
+ "type": "function_call",
+ "id": "fc_test",
+ "call_id": "call_test",
+ "name": name,
+ "arguments": "",
+ "status": "in_progress",
+ }
+ completed: JsonObject = {**item, "arguments": arguments, "status": "completed"}
+ payloads: list[tuple[str, JsonObject]] = [
+ ("response.output_item.added", {"item": item, "output_index": 0}),
+ ("response.output_item.done", {"item": completed, "output_index": 0}),
+ (
+ "response.completed",
+ {"response": {"output": [completed], "status": "completed"}},
+ ),
+ ]
+ return [
+ data for kind, payload in payloads for _, data in events.feed(kind, payload)
+ ]
+ adapter = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).tool_adapter
+ writer = ResponsesChatStreamOutput(adapter, input_tokens=1)
+ frames = [*writer.start_events(), writer.start_tool_block(0, "call_test", name)]
+ frames.append(writer.emit_tool_delta(0, arguments))
+ frames.extend(
+ writer.finish_success(
+ stop_reason="tool_calls",
+ usage=ChatStreamUsage(input_tokens=1, output_tokens=1),
+ )
+ )
+ return [frame.data for frame in parse_sse_text("".join(frames))]
+
+
[email protected]("native", [False, True])
[email protected]("custom", [False, True])
+def test_namespaced_search_named_tool_keeps_its_identity_in_all_events(
+ native: bool, custom: bool
+) -> None:
+ tool: JsonObject = {
+ "type": "custom" if custom else "function",
+ "name": "fcc_tool_search",
+ }
+ if not custom:
+ tool["parameters"] = {"type": "object"}
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Use ordinary tool",
+ tools=[
+ SEARCH,
+ {"type": "namespace", "name": "ordinary", "tools": [tool]},
+ ],
+ )
+ events = _completed_tool_events(
+ request,
+ native=native,
+ name="ordinary__fcc_tool_search",
+ arguments='{"input":"patch"}' if custom else '{"query":"ordinary"}',
+ )
+ expected_type = "custom_tool_call" if custom else "function_call"
+ for event in events:
+ if "item" in event:
+ assert event["item"]["type"] == expected_type
+ assert event["item"]["name"] == "fcc_tool_search"
+ assert event["item"]["namespace"] == "ordinary"
+ final = events[-1]["response"]["output"][0]
+ assert final["type"] == expected_type
+ assert final["namespace"] == "ordinary"
+ assert final["call_id"] == "call_test"
+ assert (
+ final.get("input") == "patch"
+ if custom
+ else json.loads(final["arguments"]) == {"query": "ordinary"}
+ )
+
+
+def test_search_name_reserves_ordinary_calls_from_history() -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[
+ {
+ "type": "function_call",
+ "call_id": "old",
+ "name": "fcc_tool_search",
+ "arguments": "{}",
+ },
+ {"type": "function_call_output", "call_id": "old", "output": "done"},
+ ],
+ )
+ adapter = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ client_tool_search=True,
+ flatten_namespaces=True,
+ ),
+ )
+ helper = (adapter.request.tools or [])[0]
+ replay = cast(list[dict[str, Any]], adapter.request.input)[0]
+ assert helper["name"] != replay["name"]
+ restored = cast(
+ dict[str, Any], adapter.restore_item({**replay, "status": "completed"})
+ )
+ assert restored["type"] == "function_call"
+
+
[email protected]("native", [False, True])
+def test_nested_function_definition_and_choice_use_one_provider_name(
+ native: bool,
+) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Call lookup",
+ tools=[
+ {
+ "type": "namespace",
+ "name": "group",
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "parameters": {"type": "object"},
+ },
+ },
+ ],
+ },
+ ],
+ tool_choice={"type": "function", "name": "lookup", "namespace": "group"},
+ )
+ if native:
+ prepared = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(flatten_namespaces=True)
+ ).request
+ definition = (prepared.tools or [])[0]
+ assert "function" not in definition
+ assert definition["name"] == "group__lookup"
+ assert prepared.tool_choice == {"type": "function", "name": "group__lookup"}
+ else:
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ definition = cast(list[dict[str, Any]], body["tools"])[0]["function"]
+ assert definition["name"] == "group__lookup"
+ assert body["tool_choice"] == {
+ "type": "function",
+ "function": {"name": "group__lookup"},
+ }
+
+
[email protected]("native", [False, True])
[email protected]("custom", [False, True])
[email protected]("discovered", [False, True])
+def test_discovery_preserves_outer_namespace_in_nested_tools(
+ native: bool, custom: bool, discovered: bool
+) -> None:
+ kind = "custom" if custom else "function"
+ definition: JsonObject = {"name": "run"}
+ if custom:
+ definition["format"] = {"type": "text"}
+ else:
+ definition["parameters"] = {"type": "object"}
+ tool: JsonObject = {"type": kind, "namespace": "agents", kind: definition}
+ tools = [SEARCH]
+ items: list[JsonObject] = [{"role": "user", "content": "Run the agent tool"}]
+ if discovered:
+ items.extend(
+ [
+ {
+ "type": "tool_search_call",
+ "call_id": "search",
+ "execution": "client",
+ "status": "completed",
+ "arguments": {"query": "agent"},
+ },
+ {
+ "type": "tool_search_output",
+ "call_id": "search",
+ "execution": "client",
+ "status": "completed",
+ "tools": [tool],
+ },
+ ]
+ )
+ else:
+ tools.append(tool)
+ request = OpenAIResponsesRequest(
+ model="example",
+ input=items,
+ tools=tools,
+ tool_choice={"type": kind, "name": "run", "namespace": "agents"},
+ )
+ original = request.model_dump()
+ if native:
+ prepared = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ client_tool_search=True,
+ flatten_namespaces=True,
+ ),
+ ).request
+ assert {tool["name"] for tool in prepared.tools or []} == {
+ "fcc_tool_search",
+ "agents__run",
+ }
+ assert prepared.tool_choice == {"type": "function", "name": "agents__run"}
+ else:
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ assert {
+ tool["function"]["name"]
+ for tool in cast(list[dict[str, Any]], body["tools"])
+ } == {"fcc_tool_search", "agents__run"}
+ assert body["tool_choice"] == {
+ "type": "function",
+ "function": {"name": "agents__run"},
+ }
+ events = _completed_tool_events(
+ request,
+ native=native,
+ name="agents__run",
+ arguments='{"input":"hello"}' if custom else '{"message":"hello"}',
+ )
+ expected_type = "custom_tool_call" if custom else "function_call"
+ for event in events:
+ if "item" in event:
+ assert event["item"]["type"] == expected_type
+ assert event["item"]["name"] == "run"
+ assert event["item"]["namespace"] == "agents"
+ final = events[-1]["response"]["output"][0]
+ assert final["type"] == expected_type
+ assert final["name"] == "run"
+ assert final["namespace"] == "agents"
+ if custom:
+ assert final["input"] == "hello"
+ else:
+ assert json.loads(final["arguments"]) == {"message": "hello"}
+ assert request.model_dump() == original
+
+
+def test_chat_does_not_turn_missing_search_arguments_into_a_successful_call() -> None:
+ events = _completed_tool_events(
+ OpenAIResponsesRequest(model="example", input="Search", tools=[SEARCH]),
+ native=False,
+ name="fcc_tool_search",
+ arguments="",
+ )
+ assert events[-1]["type"] == "response.failed"
+ assert events[-1]["response"]["output"] == []
+
+
[email protected]("native", [False, True])
+def test_synthetic_search_wins_over_bare_aliases_of_real_tools(native: bool) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Search",
+ tools=[
+ SEARCH,
+ {
+ "type": "namespace",
+ "name": "editor",
+ "tools": [
+ {"type": "custom", "name": "fcc_tool_search"},
+ ],
+ },
+ {
+ "type": "namespace",
+ "name": "ordinary",
+ "tools": [
+ {
+ "type": "function",
+ "name": "fcc_tool_search",
+ "parameters": {"type": "object"},
+ },
+ ],
+ },
+ ],
+ )
+ events = _completed_tool_events(
+ request, native=native, name="fcc_tool_search", arguments='{"query":"agent"}'
+ )
+ item = events[-1]["response"]["output"][0]
+ assert item["type"] == "tool_search_call"
+ assert item["arguments"] == {"query": "agent"}
+ assert "namespace" not in item
+
+
[email protected]("native", [False, True])
+def test_malformed_namespace_is_not_silently_dropped(native: bool) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Hello",
+ tools=[
+ {"type": "namespace", "name": "ordinary", "tools": {}},
+ ],
+ )
+ with pytest.raises(ResponsesConversionError, match="list"):
+ if native:
+ ResponsesToolAdapter(request, ResponsesToolPolicy(flatten_namespaces=True))
+ else:
+ build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ )
+
+
[email protected]("native", [False, True])
+def test_interleaved_tool_kinds_keep_arguments_and_terminal_output_consistent(
+ native: bool,
+) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Use tools",
+ tools=[
+ SEARCH,
+ {
+ "type": "namespace",
+ "name": "group",
+ "tools": [
+ {
+ "type": "function",
+ "name": "lookup",
+ "parameters": {"type": "object"},
+ },
+ {"type": "custom", "name": "edit"},
+ ],
+ },
+ ],
+ )
+ names = ["fcc_tool_search", "group__lookup", "group__edit"]
+ fragments = [['{"query":', '"agent"}'], ['{"n":', "8.0}"], ["plain ", "patch"]]
+ events: list[dict[str, Any]]
+ if native:
+ adapter = _native_adapter(cast(list[JsonObject], request.tools))
+ stream = adapter.event_adapter()
+ assert stream is not None
+ items: list[JsonObject] = [
+ {
+ "id": f"fc_{i}",
+ "call_id": f"call_{i}",
+ "type": "function_call",
+ "status": "in_progress",
+ "name": name,
+ "arguments": "",
+ }
+ for i, name in enumerate(names)
+ ]
+ events = []
+ for i, item in enumerate(items):
+ events.extend(
+ data
+ for _, data in stream.feed(
+ "response.output_item.added", {"item": item, "output_index": i}
+ )
+ )
+ for part in range(2):
+ for i, item in enumerate(items):
+ events.extend(
+ data
+ for _, data in stream.feed(
+ "response.function_call_arguments.delta",
+ {
+ "item_id": item["id"],
+ "output_index": i,
+ "delta": fragments[i][part],
+ },
+ )
+ )
+ completed: list[JsonObject] = []
+ for i, item in enumerate(items):
+ finished: JsonObject = {
+ **item,
+ "status": "completed",
+ "arguments": "".join(fragments[i]),
+ }
+ completed.append(finished)
+ events.extend(
+ data
+ for _, data in stream.feed(
+ "response.output_item.done", {"item": finished, "output_index": i}
+ )
+ )
+ events.extend(
+ data
+ for _, data in stream.feed(
+ "response.completed",
+ {"response": {"output": completed, "status": "completed"}},
+ )
+ )
+ else:
+ prepared = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ )
+ writer = ResponsesChatStreamOutput(prepared.tool_adapter, input_tokens=1)
+ frames = [*writer.start_events()]
+ for i, name in enumerate(names):
+ frames.append(writer.start_tool_block(i, f"call_{i}", name))
+ for part in range(2):
+ frames.extend(
+ writer.emit_tool_delta(i, fragments[i][part]) for i in range(3)
+ )
+ frames.extend(
+ writer.finish_success(
+ stop_reason="tool_calls",
+ usage=ChatStreamUsage(input_tokens=1, output_tokens=1),
+ )
+ )
+ events = [frame.data for frame in parse_sse_text("".join(frames))]
+ final = events[-1]["response"]["output"]
+ assert final == [
+ event["item"]
+ for event in events
+ if event["type"] == "response.output_item.done"
+ ]
+ assert [item["call_id"] for item in final] == ["call_0", "call_1", "call_2"]
+ assert final[0]["type"] == "tool_search_call"
+ assert final[0]["arguments"] == {"query": "agent"}
+ assert final[1]["type"] == "function_call"
+ assert (final[1]["name"], final[1]["namespace"]) == ("lookup", "group")
+ assert final[1]["arguments"] == '{"n":8}'
+ assert final[2]["type"] == "custom_tool_call"
+ assert (final[2]["name"], final[2]["namespace"], final[2]["input"]) == (
+ "edit",
+ "group",
+ "plain patch",
+ )
+ argument_events = [
+ event
+ for event in events
+ if event["type"].startswith("response.function_call_arguments.")
+ ]
+ assert {event["item_id"] for event in argument_events} == {final[1]["id"]}
+ assert argument_events[-1]["arguments"] == final[1]["arguments"]
+ sequences = [event["sequence_number"] for event in events]
+ assert sequences == sorted(set(sequences))
+
+
+def test_chat_preserves_custom_result_text_serialization() -> None:
+ result = [{"type": "input_image", "image_url": "https://example.com/result.png"}]
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[{"type": "custom", "name": "edit"}],
+ input=[
+ {
+ "type": "custom_tool_call",
+ "call_id": "edit",
+ "name": "edit",
+ "input": "patch",
+ },
+ {"type": "custom_tool_call_output", "call_id": "edit", "output": result},
+ ],
+ )
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ messages = cast(list[dict[str, Any]], body["messages"])
+ assert len(messages) == 2
+ assert messages[-1] == {
+ "role": "tool",
+ "tool_call_id": "edit",
+ "content": json.dumps(result, separators=(",", ":")),
+ }
+
+
[email protected]("native", [False, True])
[email protected]("search", [False, True])
[email protected]("constant", ["NaN", "Infinity", "-Infinity"])
+def test_non_finite_arguments_cannot_complete_or_corrupt_sse(
+ native: bool, search: bool, constant: str
+) -> None:
+ request = OpenAIResponsesRequest(
+ model="example", input="Call a tool", tools=[SEARCH, AGENTS]
+ )
+ name = "fcc_tool_search" if search else "agents__spawn_agent"
+ arguments = '{"nested":[{"limit":' + constant + "}]}"
+ if native:
+ with pytest.raises(ResponsesConversionError, match="arguments"):
+ _completed_tool_events(request, native=True, name=name, arguments=arguments)
+ else:
+ events = _completed_tool_events(
+ request, native=False, name=name, arguments=arguments
+ )
+ assert events[-1]["type"] == "response.failed"
+ assert events[-1]["response"]["output"] == []
+ assert not any(event["type"] == "response.output_item.done" for event in events)
+ json.dumps(events, allow_nan=False)
+
+
[email protected]("native", [False, True])
+def test_non_finite_spellings_remain_valid_custom_text(native: bool) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Edit",
+ tools=[
+ {"type": "custom", "name": "edit"},
+ ],
+ )
+ events = _completed_tool_events(
+ request, native=native, name="edit", arguments="NaN Infinity -Infinity"
+ )
+ assert events[-1]["response"]["output"][0]["input"] == "NaN Infinity -Infinity"
+ json.dumps(events, allow_nan=False)
+
+
[email protected]("native", [False, True])
[email protected]("search", [False, True])
+def test_non_finite_spellings_in_json_strings_remain_valid(
+ native: bool, search: bool
+) -> None:
+ request = OpenAIResponsesRequest(
+ model="example", input="Call a tool", tools=[SEARCH, AGENTS]
+ )
+ events = _completed_tool_events(
+ request,
+ native=native,
+ name="fcc_tool_search" if search else "agents__spawn_agent",
+ arguments='{"text":"NaN Infinity -Infinity","limit":8.0}',
+ )
+ item = events[-1]["response"]["output"][0]
+ arguments = item["arguments"] if search else json.loads(item["arguments"])
+ assert arguments == {"text": "NaN Infinity -Infinity", "limit": 8}
+ assert type(arguments["limit"]) is int
+ json.dumps(events, allow_nan=False)
+
+
[email protected]("native", [False, True])
[email protected]("search", [False, True])
+ "number", ["1e-400", "-1e-400", "0.12345678901234567890123456789", "1.25", "8.0"]
+)
+def test_argument_numbers_survive_sse_serialization(
+ native: bool, search: bool, number: str
+) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Call a tool",
+ tools=[
+ SEARCH,
+ {"type": "function", "name": "lookup", "parameters": {"type": "object"}},
+ ],
+ )
+ arguments = (
+ '{"nested":{"values":[' + number + ',8.0],"text":' + json.dumps(number) + "}}"
+ )
+ name = "fcc_tool_search" if search else "lookup"
+ if native:
+ adapter = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ flatten_namespaces=True,
+ client_tool_search=True,
+ ),
+ )
+ presenter = NativeResponsesPresenter(
+ public_model="example", tool_events=adapter.event_adapter()
+ )
+ item: JsonObject = {
+ "type": "function_call",
+ "id": "fc",
+ "call_id": "call",
+ "name": name,
+ "arguments": "",
+ "status": "in_progress",
+ }
+ completed: JsonObject = {**item, "arguments": arguments, "status": "completed"}
+ frames = list(
+ presenter.feed(
+ "response.output_item.added", {"output_index": 0, "item": item}
+ )
+ )
+ frames.extend(
+ presenter.feed(
+ "response.output_item.done", {"output_index": 0, "item": completed}
+ )
+ )
+ frames.extend(
+ presenter.feed(
+ "response.completed",
+ {
+ "response": {
+ "id": "resp",
+ "model": "example",
+ "status": "completed",
+ "output": [completed],
+ }
+ },
+ )
+ )
+ else:
+ adapter = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).tool_adapter
+ writer = ResponsesChatStreamOutput(adapter, input_tokens=1)
+ frames = [
+ *writer.start_events(),
+ writer.start_tool_block(0, "call", name),
+ writer.emit_tool_delta(0, arguments),
+ ]
+ frames.extend(
+ writer.finish_success(
+ stop_reason="tool_calls",
+ usage=ChatStreamUsage(input_tokens=1, output_tokens=1),
+ )
+ )
+ events = [
+ json.loads(line[6:], parse_float=Decimal)
+ for line in "".join(frames).splitlines()
+ if line.startswith("data: ")
+ ]
+ items = [
+ event["item"]
+ for event in events
+ if event["type"] == "response.output_item.done"
+ ]
+ items.extend(events[-1]["response"]["output"])
+ assert len(items) == 2
+ for item in items:
+ actual = (
+ item["arguments"]
+ if search
+ else json.loads(item["arguments"], parse_float=Decimal)
+ )
+ assert actual == json.loads(arguments, parse_float=Decimal)
+ assert type(actual["nested"]["values"][1]) is int
+
+
[email protected]("custom", [False, True])
+def test_client_search_reserves_hosted_discovery_names_before_replay(
+ custom: bool,
+) -> None:
+ tool: JsonObject = {
+ "type": "custom" if custom else "function",
+ "name": "fcc_tool_search",
+ }
+ if not custom:
+ tool["parameters"] = {"type": "object"}
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[
+ {
+ "type": "tool_search_call",
+ "call_id": "server_search",
+ "execution": "server",
+ "status": "completed",
+ "arguments": {},
+ },
+ {
+ "type": "tool_search_output",
+ "call_id": "server_search",
+ "execution": "server",
+ "status": "completed",
+ "tools": [
+ tool,
+ {
+ "type": "function",
+ "name": "fcc_tool_search_1",
+ "parameters": {"type": "object"},
+ },
+ ],
+ },
+ ],
+ )
+ original = request.model_dump()
+ policy = ResponsesToolPolicy(
+ custom_tools_as_functions=True, flatten_namespaces=True, client_tool_search=True
+ )
+ adapter = ResponsesToolAdapter(request, policy)
+ assert adapter.request.tools and len(adapter.request.tools) == 1
+ assert adapter.request.tools[0]["name"] == "fcc_tool_search_2"
+ call = cast(
+ dict[str, Any],
+ adapter.restore_item(
+ {
+ "type": "function_call",
+ "id": "fc",
+ "call_id": "real",
+ "status": "completed",
+ "name": "fcc_tool_search",
+ "arguments": '{"input":"text"}' if custom else "{}",
+ }
+ ),
+ )
+ assert call["type"] == ("custom_tool_call" if custom else "function_call")
+ assert call["name"] == "fcc_tool_search"
+ search = cast(
+ dict[str, Any],
+ adapter.restore_item(
+ {
+ "type": "function_call",
+ "id": "fc_search",
+ "call_id": "client_search",
+ "status": "completed",
+ "name": "fcc_tool_search_2",
+ "arguments": '{"query":"lookup"}',
+ }
+ ),
+ )
+ assert search["type"] == "tool_search_call"
+ assert search["execution"] == "client"
+ continuation = request.model_copy(
+ update={
+ "input": [
+ *cast(list[JsonObject], request.input),
+ call,
+ {
+ "type": "custom_tool_call_output"
+ if custom
+ else "function_call_output",
+ "call_id": "real",
+ "output": "done",
+ },
+ ]
+ },
+ deep=True,
+ )
+ replay = ResponsesToolAdapter(continuation, policy)
+ assert (
+ replay.request.tools and replay.request.tools[0]["name"] == "fcc_tool_search_2"
+ )
+ assert (
+ cast(list[dict[str, Any]], replay.request.input)[-2]["name"]
+ == "fcc_tool_search"
+ )
+ assert request.model_dump() == original
diff --git a/tests/core/openai_responses/test_tool_adaptation.py b/tests/core/openai_responses/test_tool_adaptation.py
index 97a8c62c..2deb2217 100644
--- a/tests/core/openai_responses/test_tool_adaptation.py
+++ b/tests/core/openai_responses/test_tool_adaptation.py
@@ -1,3 +1,6 @@
+from copy import deepcopy
+from typing import Any, cast
+
import pytest
from free_claude_code.core.anthropic import ReasoningReplayMode
@@ -27,6 +30,160 @@ def _presenter(adapter: ResponsesToolAdapter) -> NativeResponsesPresenter:
)
[email protected]("custom", [False, True])
[email protected]("wrapped", [False, True])
+def test_hosted_discovery_restores_definitions_and_replays_flat_names(
+ custom: bool, wrapped: bool
+) -> None:
+ definition: JsonObject = {
+ "type": "custom" if custom else "function",
+ "name": "lookup",
+ "description": "Find a record",
+ "defer_loading": True,
+ }
+ if custom:
+ definition["format"] = {"type": "text"}
+ else:
+ definition["parameters"] = {"type": "object"}
+ namespace: JsonObject = {
+ "type": "namespace",
+ "name": "crm",
+ "description": "Record tools",
+ "tools": [
+ definition,
+ {"type": "function", "name": "unused", "parameters": {"type": "object"}},
+ ],
+ }
+ request = OpenAIResponsesRequest(
+ model="example",
+ input="Find a record",
+ tools=[
+ {"type": "tool_search", "execution": "server"},
+ namespace,
+ ],
+ )
+ original = request.model_dump()
+ policy = ResponsesToolPolicy(
+ custom_tools_as_functions=True, flatten_namespaces=True, client_tool_search=True
+ )
+ adapter = ResponsesToolAdapter(request, policy)
+ wire_definition = deepcopy(
+ next(
+ tool
+ for tool in adapter.request.tools or []
+ if tool.get("name") == "crm__lookup"
+ )
+ )
+ discovered: JsonObject = {
+ "type": "tool_search_output",
+ "id": "search_output",
+ "call_id": "search",
+ "execution": "server",
+ "status": "completed",
+ "tools": [{**namespace, "tools": [wire_definition]}]
+ if wrapped
+ else [wire_definition],
+ }
+ call: JsonObject = {
+ "type": "function_call",
+ "id": "fc_lookup",
+ "call_id": "lookup_call",
+ "name": "crm__lookup",
+ "status": "completed",
+ "arguments": '{"input":"record"}' if custom else "{}",
+ }
+ presenter = _presenter(adapter)
+ frames = [
+ *presenter.feed(
+ "response.output_item.done", {"output_index": 0, "item": discovered}
+ )
+ ]
+ frames.extend(
+ presenter.feed(
+ "response.completed",
+ {
+ "response": {
+ "id": "response",
+ "model": "example",
+ "status": "completed",
+ "output": [discovered, call],
+ }
+ },
+ )
+ )
+ events = parse_sse_text("".join(frames))
+ public = cast(list[JsonObject], events[-1].data["response"]["output"])
+ continuation = OpenAIResponsesRequest(
+ model="example",
+ tools=request.tools,
+ input=[
+ *public,
+ {
+ "type": "custom_tool_call_output" if custom else "function_call_output",
+ "call_id": "lookup_call",
+ "output": "Found",
+ },
+ ],
+ )
+ replay = cast(
+ list[dict[str, Any]], ResponsesToolAdapter(continuation, policy).request.input
+ )
+ assert public[0] == events[0].data["item"]
+ assert public[0]["tools"] == [{**namespace, "tools": [definition]}]
+ assert public[1]["name"] == "lookup"
+ assert public[1]["namespace"] == "crm"
+ assert public[1]["type"] == ("custom_tool_call" if custom else "function_call")
+ assert replay[0]["type"] == "tool_search_output"
+ assert replay[0]["tools"] == [wire_definition]
+ assert replay[1]["name"] == "crm__lookup"
+ assert "namespace" not in replay[1]
+ assert request.model_dump() == original
+
+
+def test_hosted_discovery_groups_mixed_flat_and_wrapped_definitions() -> None:
+ first: JsonObject = {
+ "type": "function",
+ "name": "lookup",
+ "parameters": {"type": "object"},
+ }
+ second: JsonObject = {
+ "type": "function",
+ "name": "update",
+ "parameters": {"type": "object"},
+ }
+ namespace: JsonObject = {
+ "type": "namespace",
+ "name": "crm",
+ "description": "Records",
+ "tools": [first, second],
+ }
+ adapter = ResponsesToolAdapter(
+ OpenAIResponsesRequest(model="example", input="Find tools", tools=[namespace]),
+ ResponsesToolPolicy(flatten_namespaces=True),
+ )
+ unrelated: JsonObject = {
+ "type": "function",
+ "name": "other",
+ "parameters": {"type": "object"},
+ }
+ result = cast(
+ dict[str, Any],
+ adapter.restore_item(
+ {
+ "type": "tool_search_output",
+ "execution": "server",
+ "status": "completed",
+ "tools": [
+ {**first, "name": "crm__lookup"},
+ unrelated,
+ {**namespace, "tools": [{**second, "name": "crm__update"}]},
+ ],
+ }
+ ),
+ )
+ assert result["tools"] == [namespace, unrelated]
+
+
def test_custom_tool_identity_and_history_preserve_namespaces() -> None:
request = OpenAIResponsesRequest(
model="example",
@@ -70,6 +227,7 @@ def test_custom_tool_identity_and_history_preserve_namespaces() -> None:
nested = wire["tools"][1]["tools"][0]
assert nested["type"] == "function"
assert wire["input"][0]["name"] == nested["name"]
+ assert wire["input"][0]["namespace"] == "editor"
assert wire["tool_choice"] == {
"type": "function",
"namespace": "editor",
diff --git a/tests/core/openai_responses/test_tool_search.py b/tests/core/openai_responses/test_tool_search.py
index d4329030..f9999178 100644
--- a/tests/core/openai_responses/test_tool_search.py
+++ b/tests/core/openai_responses/test_tool_search.py
@@ -3,8 +3,12 @@ from copy import deepcopy
import pytest
from jsonschema import Draft202012Validator
-from free_claude_code.core.json_types import JsonObject
-from free_claude_code.core.openai_responses.tool_search import normalize_tool_search
+from free_claude_code.core.json_types import JsonObject, JsonValue
+from free_claude_code.core.openai_responses.tool_search import (
+ ClientSearchHistory,
+ active_client_tools,
+ normalize_tool_search,
+)
def test_nested_search_arguments_keep_constraints_and_literal_data() -> None:
@@ -81,3 +85,36 @@ def test_nested_search_arguments_keep_constraints_and_literal_data() -> None:
)
def test_other_tool_definitions_are_preserved(tool: JsonObject) -> None:
assert normalize_tool_search(tool) == tool
+
+
[email protected]("kind", ["function", "custom"])
+ ("container", "inner", "expected"),
+ [
+ (None, None, "outer"),
+ (None, "", "outer"),
+ (None, 7, "outer"),
+ (None, "inner", "inner"),
+ ("container", "inner", "container"),
+ ],
+)
+def test_nested_tool_namespace_precedence_during_discovery(
+ kind: str, container: str | None, inner: JsonValue, expected: str
+) -> None:
+ tool: JsonObject = {
+ "type": kind,
+ "namespace": "outer",
+ kind: {"name": "run", "namespace": inner},
+ }
+ if container:
+ tool = {"type": "namespace", "name": container, "tools": [tool]}
+ original = deepcopy(tool)
+ resolved = active_client_tools([tool], ClientSearchHistory(frozenset(), {}))
+ assert resolved == [
+ {
+ "type": "namespace",
+ "name": expected,
+ "tools": [{"type": kind, "name": "run"}],
+ }
+ ]
+ assert tool == original
diff --git a/tests/providers/test_openai_chat_stream_output.py b/tests/providers/test_openai_chat_stream_output.py
index 3d8509e4..32a89cb7 100644
--- a/tests/providers/test_openai_chat_stream_output.py
+++ b/tests/providers/test_openai_chat_stream_output.py
@@ -3,7 +3,10 @@ from typing import cast
import pytest
+from free_claude_code.core.anthropic import ReasoningReplayMode
+from free_claude_code.core.anthropic.stream_contracts import parse_sse_text
from free_claude_code.core.failures import ExecutionFailure, FailureKind
+from free_claude_code.core.openai_responses import build_responses_chat_request
from free_claude_code.core.openai_responses.models import OpenAIResponsesRequest
from free_claude_code.providers.openai_chat.stream_output import (
AnthropicChatStreamOutput,
@@ -17,13 +20,26 @@ def _parse_frame(frame: str) -> tuple[str, dict[str, object]]:
return lines[0].removeprefix("event: "), json.loads(lines[1].removeprefix("data: "))
+def _parse_frames(frames: list[str]) -> list[tuple[str, dict[str, object]]]:
+ return [(event.event, event.data) for event in parse_sse_text("".join(frames))]
+
+
def _object_dict(value: object) -> dict[str, object]:
assert isinstance(value, dict)
return value
+def _responses_output(
+ request: OpenAIResponsesRequest, *, input_tokens: int
+) -> ResponsesChatStreamOutput:
+ prepared = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ )
+ return ResponsesChatStreamOutput(prepared.tool_adapter, input_tokens=input_tokens)
+
+
def _finished_responses_usage(usage: ChatStreamUsage) -> dict[str, object]:
- output = ResponsesChatStreamOutput(
+ output = _responses_output(
OpenAIResponsesRequest.model_validate(
{"model": "public-model", "input": "Hello"}
),
@@ -84,7 +100,7 @@ def test_anthropic_chat_output_preserves_existing_wire_lifecycle() -> None:
def test_responses_chat_output_emits_one_native_lifecycle_with_exact_usage() -> None:
- output = ResponsesChatStreamOutput(
+ output = _responses_output(
OpenAIResponsesRequest.model_validate(
{
"model": "public-model",
@@ -133,7 +149,7 @@ def test_responses_chat_output_emits_one_native_lifecycle_with_exact_usage() ->
)
)
- events = [_parse_frame(frame) for frame in frames if frame]
+ events = _parse_frames(frames)
event_types = [event_type for event_type, _ in events]
assert event_types.count("response.created") == 1
assert event_types.count("response.completed") == 1
@@ -239,7 +255,7 @@ def test_responses_chat_output_ignores_overflowing_read_without_losing_write() -
def test_responses_chat_output_finishes_committed_failure_once() -> None:
- output = ResponsesChatStreamOutput(
+ output = _responses_output(
OpenAIResponsesRequest.model_validate(
{"model": "public-model", "input": "Hello"}
),
@@ -256,7 +272,7 @@ def test_responses_chat_output_finishes_committed_failure_once() -> None:
frames.extend(output.finish_failure(failure))
frames.extend(output.finish_failure(failure))
- events = [_parse_frame(frame) for frame in frames if frame]
+ events = _parse_frames(frames)
assert [event_type for event_type, _ in events].count("response.failed") == 1
final = _object_dict(events[-1][1]["response"])
assert final["status"] == "failed"
@@ -265,7 +281,7 @@ def test_responses_chat_output_finishes_committed_failure_once() -> None:
def test_responses_chat_output_preserves_options_on_incomplete_terminal() -> None:
- output = ResponsesChatStreamOutput(
+ output = _responses_output(
OpenAIResponsesRequest.model_validate(
{
"model": "public-model",
@@ -287,7 +303,7 @@ def test_responses_chat_output_preserves_options_on_incomplete_terminal() -> Non
)
)
- events = [_parse_frame(frame) for frame in frames if frame]
+ events = _parse_frames(frames)
assert [event_type for event_type, _ in events].count("response.created") == 1
assert [event_type for event_type, _ in events].count("response.incomplete") == 1
final = _object_dict(events[-1][1]["response"])
@@ -301,7 +317,7 @@ def test_responses_chat_output_preserves_options_on_incomplete_terminal() -> Non
def test_responses_chat_output_preserves_custom_tool_free_form_input() -> None:
- output = ResponsesChatStreamOutput(
+ output = _responses_output(
OpenAIResponsesRequest.model_validate(
{
"model": "public-model",
@@ -328,7 +344,7 @@ def test_responses_chat_output_preserves_custom_tool_free_form_input() -> None:
)
)
- events = [_parse_frame(frame) for frame in frames if frame]
+ events = _parse_frames(frames)
final = _object_dict(events[-1][1]["response"])
final_output = final["output"]
assert isinstance(final_output, list)
@@ -345,7 +361,7 @@ def test_responses_chat_output_preserves_custom_tool_free_form_input() -> None:
def test_responses_chat_output_fails_malformed_function_call_once() -> None:
- output = ResponsesChatStreamOutput(
+ output = _responses_output(
OpenAIResponsesRequest.model_validate(
{
"model": "public-model",
@@ -378,7 +394,7 @@ def test_responses_chat_output_fails_malformed_function_call_once() -> None:
)
)
- events = [_parse_frame(frame) for frame in frames if frame]
+ events = _parse_frames(frames)
event_types = [event_type for event_type, _ in events]
assert event_types.count("response.failed") == 1
assert "response.completed" not in event_types
diff --git a/tests/providers/test_opencode.py b/tests/providers/test_opencode.py
index 66e5e0a1..6fc37026 100644
--- a/tests/providers/test_opencode.py
+++ b/tests/providers/test_opencode.py
@@ -930,13 +930,24 @@ async def test_discovered_custom_tools_survive_sdk_calls_and_replay(
def upstream(request: httpx2.Request) -> httpx2.Response:
body = json.loads(request.content)
for loaded in body["input"][:2]:
- assert loaded["execution"] == execution
- tool = loaded["tools"][0]["tools"][0]
+ if execution == "client":
+ assert loaded["type"] == "function_call_output"
+ tool = json.loads(loaded["output"])[0]
+ assert "defer_loading" not in tool
+ assert tool in body["tools"]
+ else:
+ assert loaded["execution"] == execution
+ tool = loaded["tools"][0]
+ assert tool["defer_loading"] is True
assert tool["type"] == "function"
- for field in ("defer_loading", "allowed_callers", "extension"):
+ assert tool["name"] == "editor__edit"
+ assert "namespace" not in tool
+ for field in ("allowed_callers", "extension"):
assert tool[field] == expected_tool[field]
if len(body["input"]) > 2:
assert body["input"][2]["type"] == "function_call"
+ assert body["input"][2]["name"] == tool["name"]
+ assert "namespace" not in body["input"][2]
assert json.loads(body["input"][2]["arguments"]) == {"input": "patch"}
assert body["input"][3] == {
"type": "function_call_output",
diff --git a/tests/providers/test_provider_client_tool_discovery.py b/tests/providers/test_provider_client_tool_discovery.py
new file mode 100644
index 00000000..ad6dede6
--- /dev/null
+++ b/tests/providers/test_provider_client_tool_discovery.py
@@ -0,0 +1,340 @@
+import json
+from typing import Any, cast
+
+import httpx2
+import pytest
+from openai import AsyncOpenAI
+
+from free_claude_code.config.settings import Settings
+from free_claude_code.core.anthropic.stream_contracts import parse_sse_text
+from free_claude_code.core.openai_responses import OpenAIResponsesRequest
+from free_claude_code.providers.openai_chat import OpenAIChatProvider
+from free_claude_code.providers.runtime.factory import create_provider
+from tests.core.openai_responses.test_client_tool_discovery import AGENTS, SEARCH
+from tests.providers.support import immediate_admission
+from tests.providers.test_opencode import (
+ _catalog_payload,
+ _provider_with_wire_transports,
+ _responses_event_stream,
+)
+
+
+ "provider_id", ["open_router", "nvidia_nim", "groq", "mistral", "opencode_zen"]
+)
[email protected]("custom", [False, True])
[email protected]("omit_discovery_metadata", [False, True])
+ ("tool_name", "namespaced"),
+ [(None, True), ("apply patch", False), ("x" * 80, False), ("apply patch", True)],
+)
+async def test_provider_discovery_call_and_result_round_trip(
+ provider_id: str,
+ custom: bool,
+ omit_discovery_metadata: bool,
+ tool_name: str | None,
+ namespaced: bool,
+) -> None:
+ native = provider_id == "opencode_zen"
+ requests: list[dict[str, Any]] = []
+ client_name = tool_name or ("edit" if custom else "spawn_agent")
+ namespace = ("editor" if custom else "agents") if namespaced else None
+ result_text = json.dumps([{"type": "function", "name": client_name}])
+
+ def upstream(request: httpx2.Request) -> httpx2.Response:
+ body = json.loads(request.content)
+ requests.append(body)
+ functions = (
+ {tool["name"]: tool for tool in body.get("tools", [])}
+ if native
+ else {
+ tool["function"]["name"]: tool["function"]
+ for tool in body.get("tools", [])
+ }
+ )
+ messages = body["input"] if native else body["messages"]
+ result_field = "output" if native else "content"
+ step = len(requests)
+ if step == 1:
+ assert len(functions) == 1
+ name = next(iter(functions))
+ assert (
+ functions[name]["parameters"]["properties"]["query"]["type"] == "string"
+ )
+ args = '{"query":"agent"}'
+ elif step == 2:
+ name = next(name for name in functions if name != "fcc_tool_search")
+ if not native:
+ assert len(name) <= 64
+ assert all(
+ char.isascii() and (char.isalnum() or char in "_-") for char in name
+ )
+ assert body["tool_choice"] == (
+ {"type": "function", "name": name}
+ if native
+ else {"type": "function", "function": {"name": name}}
+ )
+ assert (
+ messages[-1].get("type") == "function_call_output"
+ if native
+ else messages[-1]["role"] == "tool"
+ )
+ discovered = json.loads(messages[-1][result_field])
+ assert len(discovered) == 1
+ assert discovered[0]["name"] == name
+ assert discovered[0]["parameters"] == functions[name]["parameters"]
+ args = '{"input":"patch"}' if custom else '{"message":"hello"}'
+ else:
+ if native:
+ replayed_call = messages[-2]
+ assert replayed_call["type"] == "function_call"
+ assert replayed_call["name"] == requests[1]["tool_choice"]["name"]
+ assert "namespace" not in replayed_call
+ assert "namespace" not in functions[replayed_call["name"]]
+ assert json.loads(replayed_call["arguments"]) == (
+ {"input": "patch"} if custom else {"message": "hello"}
+ )
+ else:
+ replayed_call = messages[-2]["tool_calls"][0]
+ function = replayed_call["function"]
+ assert (
+ function["name"] == requests[1]["tool_choice"]["function"]["name"]
+ )
+ assert json.loads(function["arguments"]) == (
+ {"input": "patch"} if custom else {"message": "hello"}
+ )
+ assert function["name"] in functions
+ assert "namespace" not in function
+ assert (
+ messages[-1].get("type") == "function_call_output"
+ if native
+ else messages[-1]["role"] == "tool"
+ )
+ assert messages[-1][result_field] == result_text
+ name, args = "", ""
+ packets: list[dict[str, Any]]
+ if native:
+ packets = [
+ json.loads(line[6:])
+ for line in _responses_event_stream("done").splitlines()
+ if line.startswith("data: ")
+ ]
+ if name:
+ call = {
+ "type": "function_call",
+ "id": f"fc_{step}",
+ "call_id": f"call_{step}",
+ "name": name,
+ "arguments": args,
+ "status": "completed",
+ }
+ packets = [
+ packets[0],
+ {
+ "type": "response.output_item.added",
+ "output_index": 0,
+ "item": {**call, "status": "in_progress", "arguments": ""},
+ },
+ {
+ "type": "response.output_item.done",
+ "output_index": 0,
+ "item": call,
+ },
+ {
+ **packets[-1],
+ "response": {**packets[-1]["response"], "output": [call]},
+ },
+ ]
+ if not name:
+ message = {
+ "id": "msg_done",
+ "type": "message",
+ "status": "completed",
+ "role": "assistant",
+ "content": [
+ {"type": "output_text", "text": "done", "annotations": []}
+ ],
+ }
+ packets = [
+ packets[0],
+ {
+ "type": "response.output_item.added",
+ "output_index": 0,
+ "item": {**message, "status": "in_progress"},
+ },
+ {
+ "type": "response.output_item.done",
+ "output_index": 0,
+ "item": message,
+ },
+ {
+ **packets[-1],
+ "response": {**packets[-1]["response"], "output": [message]},
+ },
+ ]
+ return httpx2.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text="".join(
+ "data: " + json.dumps({**packet, "sequence_number": i}) + "\n\n"
+ for i, packet in enumerate(packets)
+ ),
+ )
+ delta = (
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": f"call_{step}",
+ "type": "function",
+ "function": {"name": name, "arguments": args},
+ }
+ ]
+ }
+ if name
+ else {"content": "done"}
+ )
+ packets = [
+ {
+ "id": "completion",
+ "object": "chat.completion.chunk",
+ "created": 0,
+ "model": "example",
+ "choices": [{"index": 0, "delta": delta, "finish_reason": None}],
+ },
+ {
+ "id": "completion",
+ "object": "chat.completion.chunk",
+ "created": 0,
+ "model": "example",
+ "choices": [
+ {
+ "index": 0,
+ "delta": {},
+ "finish_reason": "tool_calls" if name else "stop",
+ }
+ ],
+ },
+ ]
+ return httpx2.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text="".join("data: " + json.dumps(packet) + "\n\n" for packet in packets)
+ + "data: [DONE]\n\n",
+ )
+
+ if native:
+ provider, _, _ = _provider_with_wire_transports(
+ _catalog_payload(), generation_response=upstream
+ )
+ else:
+ provider = cast(
+ OpenAIChatProvider,
+ create_provider(
+ provider_id,
+ Settings(
+ open_router_api_key="test",
+ nvidia_nim_api_key="test",
+ groq_api_key="test",
+ mistral_api_key="test",
+ ),
+ ),
+ )
+ provider._admission = immediate_admission(provider_name=provider_id)
+ await provider._client.close()
+ provider._client = AsyncOpenAI(
+ api_key="test",
+ base_url="https://provider.test/v1",
+ http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(upstream)),
+ max_retries=0,
+ )
+ history: list[dict[str, Any]] = [
+ {"role": "user", "content": "Find a tool and use it"}
+ ]
+
+ async def turn() -> dict[str, Any]:
+ request = OpenAIResponsesRequest.model_validate(
+ {
+ "model": "responses-selector" if native else "example",
+ "input": history,
+ "tools": [SEARCH],
+ "tool_choice": {
+ "type": "tool",
+ "namespace": namespace,
+ "name": client_name,
+ }
+ if len(requests) == 1
+ else "auto",
+ "max_output_tokens": 128,
+ }
+ )
+ output = "".join([chunk async for chunk in provider.stream_responses(request)])
+ events = parse_sse_text(output)
+ assert events[-1].event == "response.completed"
+ response = events[-1].data["response"]
+ done_items = [
+ event.data["item"]
+ for event in events
+ if event.event == "response.output_item.done"
+ ]
+ assert response["output"] == done_items
+ sequences = [event.data["sequence_number"] for event in events]
+ assert sequences == sorted(set(sequences))
+ return response
+
+ try:
+ search = (await turn())["output"][0]
+ assert search["type"] == "tool_search_call"
+ assert search["execution"] == "client"
+ assert search["arguments"] == {"query": "agent"}
+ assert "name" not in search
+ definition = (
+ {"type": "custom", "name": client_name, "format": {"type": "text"}}
+ if custom
+ else {**cast(list[dict[str, Any]], AGENTS["tools"])[0], "name": client_name}
+ )
+ definitions = (
+ [{"type": "namespace", "name": namespace, "tools": [definition]}]
+ if namespaced
+ else [definition]
+ )
+ history.extend(
+ [
+ search,
+ {
+ "type": "tool_search_output",
+ "execution": "client",
+ "status": "completed",
+ "call_id": search["call_id"],
+ "tools": definitions,
+ },
+ ]
+ )
+ if omit_discovery_metadata:
+ history[-1].pop("execution")
+ history[-1].pop("status")
+ call = (await turn())["output"][0]
+ assert call["type"] == ("custom_tool_call" if custom else "function_call")
+ assert call.get("namespace") == namespace
+ assert call["name"] == client_name
+ if custom:
+ assert call["input"] == "patch"
+ else:
+ assert json.loads(call["arguments"]) == {"message": "hello"}
+ history.extend(
+ [
+ call,
+ {
+ "type": "custom_tool_call_output"
+ if custom
+ else "function_call_output",
+ "call_id": call["call_id"],
+ "output": result_text,
+ },
+ ]
+ )
+ assert (await turn())["output"][0]["content"][0]["text"] == "done"
+ assert len(requests) == 3
+ finally:
+ await provider.cleanup()
diff --git a/uv.lock b/uv.lock
index 2b2b43a7..a8384e37 100644
--- a/uv.lock
+++ b/uv.lock
@@ -598,7 +598,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "6.2.12"
+version = "6.2.13"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
@@ -620,6 +620,7 @@ dependencies = [
{ name = "python-dotenv" },
{ name = "python-telegram-bot" },
{ name = "requests", extra = ["socks"] },
+ { name = "simplejson" },
{ name = "tiktoken" },
{ name = "tomlkit" },
{ name = "uvicorn" },
@@ -675,6 +676,7 @@ requires-dist = [
{ name = "python-dotenv", specifier = ">=1.2.2" },
{ name = "python-telegram-bot", specifier = ">=22.8" },
{ name = "requests", extras = ["socks"], specifier = ">=2.34.2" },
+ { name = "simplejson", specifier = ">=4.1.2" },
{ name = "tiktoken", specifier = ">=0.13.0" },
{ name = "tomlkit", specifier = ">=0.13.3" },
{ name = "torch", marker = "extra == 'voice-local'", specifier = ">=2.13.0", index = "https://download.pytorch.org/whl/cu130" },
@@ -2435,6 +2437,37 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
]
+[[package]]
+name = "simplejson"
+version = "4.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f1/e3/1cc7dbf4deebc16e9dc42db37f473b5b612d021eb10e69974be308425171/simplejson-4.1.2.tar.gz", hash = "sha256:6ae4186f90362e9c03c80a1cd5062a20f3a11ac9d391f7ee0ef0701a0e2b7394", size = 121591, upload-time = "2026-08-27T00:38:27.527Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0a/a0/3a0934c2b465cb8bbd6fad7e9ca32cfd70f1a0ffd204e0e5db9704fa1fbb/simplejson-4.1.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:d999597ff19143130d2e52f363e5e7791703a87be3df9219fbec6eb54958d4d1", size = 112905, upload-time = "2026-08-27T00:37:28.074Z" },
+ { url = "https://files.pythonhosted.org/packages/05/ac/a9f131ae07efa8fd7b17961bdcdd5b6a00b0b49480cf66e379fe06459614/simplejson-4.1.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:37c0293cd6b04ab0e2c2bb8bcbe5c3c7c2cd3bd487bbd95c043237a7db4d4e9c", size = 92397, upload-time = "2026-08-27T00:37:29.471Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/0b/05e95a9a673adeeece7d368fd7ff305cfa00599d482a9ba23667af73ddf1/simplejson-4.1.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a48a827277963a557ad844c845fa8992356d1afd6edba76cd32fe056cbf8df2b", size = 92231, upload-time = "2026-08-27T00:37:30.619Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/95/2eddb2053b9ca497bbd07c663e54bb6e13747b1ff6c3f3c79a86b19ddd6d/simplejson-4.1.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d350798258029864b27bca50b4ce7ee138faf8f07be21d2192b7088da9c38074", size = 188580, upload-time = "2026-08-27T00:37:31.841Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/98/43eb3ed7edbb07afcb861fc24dfcfc52b0e83373236420dd59ba1dc9aacf/simplejson-4.1.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4c0bd55cc396b7dc1df43b19a9df8d85684fd84dc196fad674c1f4c4887279d0", size = 185310, upload-time = "2026-08-27T00:37:33.171Z" },
+ { url = "https://files.pythonhosted.org/packages/98/0b/2f60218ce135fad65dafd9998272c7fd029eb7195645c439395027a872a5/simplejson-4.1.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:205e28d0506e72cedf5b8bad4a946779db236d1fe4d43f2481a3361737ed573b", size = 193465, upload-time = "2026-08-27T00:37:34.49Z" },
+ { url = "https://files.pythonhosted.org/packages/73/5d/8270e305880188acbe83324c7f8d9a913cdfeec180bef845948113c96496/simplejson-4.1.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:87dd15ed478dc1dea9e5ee3e564bd49ff9f9ecab854a1ae896d66b8667387b28", size = 181501, upload-time = "2026-08-27T00:37:35.696Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/87/dd6b9713ddd91fbdf6f78cf87fe6ff11c3216d01795db6206ee77fb86a9a/simplejson-4.1.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:c8135ff667bd1c131964795196e2428a9db4befeb074133b314847675d6ca367", size = 189435, upload-time = "2026-08-27T00:37:36.924Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/b9/1ece5f5ea9c72eaf98ec06c3f73971c868971b4f8d0d266758e7d95dc95b/simplejson-4.1.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:7273dd5d56430549d5bea9176923891f765ddcc421a1a05c74c6ff5397edaa38", size = 185760, upload-time = "2026-08-27T00:37:38.205Z" },
+ { url = "https://files.pythonhosted.org/packages/99/70/9519355cebd5916aabd8d1397a626c9c2e97f47edc4827d3b0859d9903dc/simplejson-4.1.2-cp314-cp314-win32.whl", hash = "sha256:432cc50cc23ce980ec60d3cbf8f35383653fec9b4c952e24cded2f638a48f48e", size = 90304, upload-time = "2026-08-27T00:37:39.432Z" },
+ { url = "https://files.pythonhosted.org/packages/d0/81/4ed61f6cfa01e8d43ca242d04a6155091a7f19566f095715ed38a2dcfb80/simplejson-4.1.2-cp314-cp314-win_amd64.whl", hash = "sha256:a52db90cc4175bf7aaa36bf7b8c1ff92403349d2d999794ad3f75b175c627ff1", size = 92616, upload-time = "2026-08-27T00:37:40.607Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/f1/15e52fe9168510d78315439ad5d0f737e8c9f920cad251c989acac4ef263/simplejson-4.1.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:92e85afa383ac2f6a80ac0d9dc6ccf9e92bc19d24451c41d290e83bab5534ccb", size = 116460, upload-time = "2026-08-27T00:37:42.916Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/b3/1bec2de25e21864d9920bf00427f965da74052e84088b924c12c92a1b1b6/simplejson-4.1.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2081a5f1a1e2645d4b2db48e49b54862f60bc31387e71549c1d4679caacaf694", size = 94213, upload-time = "2026-08-27T00:37:44.193Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/fe/f82ff72f373f3cd9078819525940fefb35b36b0f4581e602a78952c84531/simplejson-4.1.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:fcc4c6b0ba1f0515cbab539b5b7c1b38f3671999b390f8056cd71ac05895d901", size = 93920, upload-time = "2026-08-27T00:37:45.409Z" },
+ { url = "https://files.pythonhosted.org/packages/53/cd/292be366a353aa16c7e77a2b37b83bfa24e4bbca9fbf9914475375eaf2b1/simplejson-4.1.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:119733522f1f5d50a4262820ec587753a368cce0231aae02b958bb47e705bc13", size = 218654, upload-time = "2026-08-27T00:37:46.659Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/4b/419a05e7aa24650a28c572a421ae71e3a40f5e10375efa2ce96db80cb358/simplejson-4.1.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:15ffd144c44be1f5ba2a9bc5641ea7af925b75e240adffb79ced67f35f58b4dd", size = 219738, upload-time = "2026-08-27T00:37:48.011Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/d8/6ca3a747348465a80c1dcf50f8265477806981253677331a2b217b414f36/simplejson-4.1.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4134f1afadf815295d5d38f50f2b64e1758ce053b552526b44f74c5a34bf9bab", size = 223936, upload-time = "2026-08-27T00:37:49.273Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/cb/5498d477c0131abf29349102c372307119c1b111d7992a8c899f8de03899/simplejson-4.1.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:601184707588eec8e04e16c534be5a4794aeac9a5163600e077c85c255a1f9b3", size = 214779, upload-time = "2026-08-27T00:37:50.63Z" },
+ { url = "https://files.pythonhosted.org/packages/33/ab/f39ffeb873375d3a733e886ca7c3e03131721e3e814edcd020cdfd339ef6/simplejson-4.1.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:3a2f883839314597ace1f48fda2e8f4bf1018674d3842823f54b027690b15e41", size = 219880, upload-time = "2026-08-27T00:37:51.934Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/cf/01e88370229d92f1e8b2bc660cb53b3c3b5068fe76768021a331c9f276f7/simplejson-4.1.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:d284ea3976a73054151e7906fc1b4fff25d589970532b6209ed7aeda9079747b", size = 215009, upload-time = "2026-08-27T00:37:53.217Z" },
+ { url = "https://files.pythonhosted.org/packages/fc/53/016a4132161e1ac0b75385c1f61dbd96c0dff57ad2bb09e6e1653cfd7513/simplejson-4.1.2-cp314-cp314t-win32.whl", hash = "sha256:14a6a1fd97aeb7ebc54773bd0d195b480e946b9a915ebd163671744a387abee6", size = 91670, upload-time = "2026-08-27T00:37:54.503Z" },
+ { url = "https://files.pythonhosted.org/packages/da/b2/6911f3b7d82f641b7050190cc64dbae6dcc1148bb02f7212b26f6119f0c2/simplejson-4.1.2-cp314-cp314t-win_amd64.whl", hash = "sha256:e933a481b825bac33fb274de49e1574f805f48442198e06b1f2c3b4cbde40350", size = 94267, upload-time = "2026-08-27T00:37:55.836Z" },
+ { url = "https://files.pythonhosted.org/packages/95/e2/7f47df8fbd3d9c35902b76c242e21759a27d6e8c030c901c4f0ad93dd10b/simplejson-4.1.2-py3-none-any.whl", hash = "sha256:93f95f6769f37f4c3763666950b23bf9b9230b60bf1d718845e92db2ebcbf32d", size = 71116, upload-time = "2026-08-27T00:38:26.256Z" },
+]
+
[[package]]
name = "six"
version = "1.17.0"