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 interrupted client tool discovery replay (#1834)

Ali Khokhare4bedb45d0c2
diff --git a/pyproject.toml b/pyproject.toml
index f9640fa0..e6a5056d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "6.2.41"
+version = "6.2.42"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/src/free_claude_code/core/openai_responses/chat_request.py b/src/free_claude_code/core/openai_responses/chat_request.py
index b85e339e..26814935 100644
--- a/src/free_claude_code/core/openai_responses/chat_request.py
+++ b/src/free_claude_code/core/openai_responses/chat_request.py
@@ -370,8 +370,10 @@ def build_responses_chat_request(
if request.instructions:
builder.system_parts.append(request.instructions)
original_items = _input_items(adapter.original.input)
- for index, item in enumerate(_input_items(request.input)):
- source = original_items[index]
+ for source_index, item in zip(
+ adapter.input_source_indices, _input_items(request.input), strict=True
+ ):
+ source = original_items[source_index]
builder.add(
item,
source_type=optional_str(source.get("type"))
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 b6e9f8b6..0c5b92a8 100644
--- a/src/free_claude_code/core/openai_responses/tool_adaptation.py
+++ b/src/free_claude_code/core/openai_responses/tool_adaptation.py
@@ -18,6 +18,7 @@ from .tool_search import (
ClientSearchHistory,
active_client_tools,
is_client_search,
+ is_unfinished_search_call,
normalize_tool_search,
resolve_client_search_history,
search_function_name,
@@ -71,6 +72,23 @@ class ResponsesToolAdapter:
if policy.client_tool_search
else ClientSearchHistory(frozenset(), {})
)
+ input_items = (
+ self.request.input
+ if isinstance(self.request.input, list)
+ else []
+ if self.request.input is None
+ else [self.request.input]
+ )
+ retained_input = [
+ (index, item)
+ for index, item in enumerate(input_items)
+ if index not in self._search_history.omitted_items
+ ]
+ self.input_source_indices = tuple(index for index, _ in retained_input)
+ if self._search_history.omitted_items and not retained_input:
+ raise ResponsesConversionError(
+ "Responses request must contain usable input."
+ )
if policy == ResponsesToolPolicy():
return
client_search = policy.client_tool_search and (
@@ -88,7 +106,7 @@ class ResponsesToolAdapter:
):
self._register_tools(self.request.tools)
if isinstance(self.request.input, list):
- for index, item in enumerate(self.request.input):
+ for index, item in retained_input:
if isinstance(item, dict) and item.get("type") in (
"function_call",
"custom_tool_call",
@@ -109,8 +127,7 @@ class ResponsesToolAdapter:
self.request.tools = cast(list[JsonObject], self._tools(self.request.tools))
if isinstance(self.request.input, list):
self.request.input = [
- self._input(item, index)
- for index, item in enumerate(self.request.input)
+ self._input(item, index) for index, item in retained_input
]
if (
policy.custom_tools_as_functions
@@ -452,29 +469,26 @@ class ResponsesToolAdapter:
),
}
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,
+ arguments = value.get("arguments")
+ if not is_unfinished_search_call(value):
+ try:
+ arguments = (
+ json.loads(
+ arguments,
+ parse_float=_canonical_number,
+ parse_constant=_reject_json_constant,
+ )
+ if isinstance(arguments, str) and arguments
+ else None
+ )
+ except ValueError as exc:
+ raise ResponsesConversionError(
+ "Invalid client search arguments."
+ ) from exc
+ if not isinstance(arguments, dict):
+ raise ResponsesConversionError(
+ "Client search arguments must be a JSON object."
)
- 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
@@ -690,10 +704,15 @@ class ResponsesToolEventAdapter:
"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 item.get("type") == "tool_search_call":
+ if isinstance(item_id := item.get("id"), str):
+ self._search_items.add(item_id)
+ if (
+ event_type == "response.output_item.added"
+ and isinstance(original_item, dict)
+ and original_item.get("type") == "function_call"
+ ):
+ item["arguments"] = {}
if (
isinstance(original_item, dict)
and original_item.get("type") == "function_call"
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 12177fbe..df7b95eb 100644
--- a/src/free_claude_code/core/openai_responses/tool_search.py
+++ b/src/free_claude_code/core/openai_responses/tool_search.py
@@ -19,10 +19,15 @@ def is_client_search(value: Mapping[str, JsonValue]) -> bool:
}
+def is_unfinished_search_call(value: Mapping[str, JsonValue]) -> bool:
+ return value.get("status") in ("in_progress", "incomplete", "failed")
+
+
@dataclass(frozen=True, slots=True)
class ClientSearchHistory:
client_items: frozenset[int]
output_tools: dict[int, list[JsonObject]]
+ omitted_items: frozenset[int] = frozenset()
def resolve_client_search_history(items: JsonValue) -> ClientSearchHistory:
@@ -51,6 +56,8 @@ def resolve_client_search_history(items: JsonValue) -> ClientSearchHistory:
executions[call_id] = cast(str, execution)
client_items: set[int] = set()
outputs: dict[int, list[JsonObject]] = {}
+ omitted_items: set[int] = set()
+ latest_calls: dict[str, int] = {}
for index, item in searches.items():
execution = item.get("execution")
call_id = item.get("call_id")
@@ -58,6 +65,16 @@ def resolve_client_search_history(items: JsonValue) -> ClientSearchHistory:
execution = executions.get(call_id)
if execution != "client":
continue
+ if item.get("type") == "tool_search_call":
+ if isinstance(call_id, str) and call_id:
+ latest_calls[call_id] = index
+ if is_unfinished_search_call(item):
+ omitted_items.add(index)
+ continue
+ elif isinstance(call_id, str) and latest_calls.get(call_id) in omitted_items:
+ # Bind each result to its preceding occurrence, not every reused ID.
+ omitted_items.add(index)
+ continue
client_items.add(index)
if item.get("type") == "tool_search_output":
tools = item.get("tools")
@@ -72,7 +89,9 @@ def resolve_client_search_history(items: JsonValue) -> ClientSearchHistory:
[],
]
)
- return ClientSearchHistory(frozenset(client_items), outputs)
+ return ClientSearchHistory(
+ frozenset(client_items), outputs, frozenset(omitted_items)
+ )
def active_client_tools(
diff --git a/tests/core/openai_responses/test_client_tool_discovery.py b/tests/core/openai_responses/test_client_tool_discovery.py
index 13e44d89..cebe5b06 100644
--- a/tests/core/openai_responses/test_client_tool_discovery.py
+++ b/tests/core/openai_responses/test_client_tool_discovery.py
@@ -11,7 +11,7 @@ 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.json_types import JsonObject, JsonValue
from free_claude_code.core.openai_responses import (
OpenAIResponsesRequest,
ResponsesConversionError,
@@ -19,6 +19,7 @@ from free_claude_code.core.openai_responses import (
ResponsesToolPolicy,
build_responses_chat_request,
)
+from free_claude_code.core.openai_tool_names import encode_openai_chat_tool_names
from free_claude_code.providers.openai_chat.stream_output import (
ChatStreamUsage,
ResponsesChatStreamOutput,
@@ -214,6 +215,54 @@ def test_native_rejects_ambiguous_bare_names() -> None:
)
[email protected]("execution", ["server", "client"])
+ "policy",
+ [
+ ResponsesToolPolicy(flatten_namespaces=True),
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ explicit_search_parameters=True,
+ text_only_web_search=True,
+ client_tool_search=True,
+ flatten_namespaces=True,
+ ),
+ ],
+ ids=["namespaces", "opencode"],
+)
+def test_native_search_preserves_added_arguments(
+ execution: str, policy: ResponsesToolPolicy
+) -> None:
+ adapter = ResponsesToolAdapter(
+ OpenAIResponsesRequest(
+ model="example",
+ input="Find tools",
+ tools=[{**SEARCH, "execution": execution}],
+ ),
+ policy,
+ )
+ events = adapter.event_adapter()
+ assert events is not None
+ payload: JsonObject = {
+ "type": "response.output_item.added",
+ "sequence_number": 0,
+ "output_index": 0,
+ "item": {
+ "type": "tool_search_call",
+ "id": "search_native",
+ "call_id": "search",
+ "execution": execution,
+ "status": "in_progress",
+ "arguments": {"query": "Find deployment tools"},
+ },
+ }
+ original = deepcopy(payload)
+ assert list(events.feed("response.output_item.added", payload)) == [
+ ("response.output_item.added", original)
+ ]
+ assert payload == original
+
+
def test_native_search_buffers_partial_added_arguments() -> None:
adapter = _native_adapter([SEARCH])
events = adapter.event_adapter()
@@ -277,6 +326,468 @@ def test_native_does_not_publish_empty_completed_arguments_as_success() -> None:
)
[email protected]("terminal", ["failed", "incomplete"])
[email protected]("arguments", ['{"query":', None, {"query": "agent"}])
+def test_interrupted_discovery_preserves_terminal_failure(
+ terminal: str, arguments: JsonValue
+) -> None:
+ adapter = _native_adapter([SEARCH])
+ presenter = NativeResponsesPresenter(
+ public_model="example", tool_events=adapter.event_adapter()
+ )
+ item: JsonObject = {
+ "type": "function_call",
+ "id": "fc_search",
+ "call_id": "search",
+ "name": "fcc_tool_search",
+ "status": "incomplete",
+ "arguments": arguments,
+ }
+ sibling: JsonObject = {
+ "type": "message",
+ "id": "msg_saved",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": "Saved work", "annotations": []}],
+ }
+ response = parse_sse_text(_responses_event_stream(""))[-1].data["response"]
+ response["usage"]["input_tokens_details"]["cache_write_tokens"] = 0
+ response.update(
+ status=terminal,
+ output=[sibling, item],
+ error={"code": "server_error", "message": "Original upstream timeout"}
+ if terminal == "failed"
+ else None,
+ incomplete_details={"reason": "max_output_tokens"}
+ if terminal == "incomplete"
+ else None,
+ )
+ original = deepcopy(response)
+ chunks = list(
+ presenter.feed(
+ "response.output_item.added",
+ {"output_index": 1, "item": {**item, "status": "in_progress"}},
+ )
+ )
+ chunks.extend(
+ presenter.feed(
+ "response.function_call_arguments.delta",
+ {"output_index": 1, "item_id": "fc_search", "delta": '"agent"}'},
+ )
+ )
+ chunks.extend(
+ presenter.feed("response.output_item.done", {"output_index": 1, "item": item})
+ )
+ chunks.extend(presenter.feed(f"response.{terminal}", {"response": response}))
+ events = parse_sse_text("".join(chunks))
+ assert [event.event for event in events] == [
+ "response.output_item.added",
+ "response.output_item.done",
+ f"response.{terminal}",
+ ]
+ assert events[0].data["item"]["arguments"] == {}
+ restored = {key: value for key, value in item.items() if key != "name"}
+ restored.update(type="tool_search_call", execution="client")
+ assert events[1].data["item"] == restored
+ actual = events[-1].data["response"]
+ assert actual["output"] == [sibling, restored]
+ assert actual["error"] == original["error"]
+ assert actual["incomplete_details"] == original["incomplete_details"]
+ assert response == original
+ parser: TypeAdapter[ResponseStreamEvent] = TypeAdapter(ResponseStreamEvent)
+ for event in events:
+ parser.validate_python(event.data)
+
+
[email protected]("native", [False, True])
+ ("status", "argument_fields", "implicit_execution"),
+ [
+ ("incomplete", {"arguments": '{"query":'}, None),
+ ("in_progress", {"arguments": {"query": "agent"}}, None),
+ ("failed", {"arguments": {}}, None),
+ ("incomplete", {}, "call"),
+ ("incomplete", {"arguments": None}, "output"),
+ ("incomplete", {"arguments": "{}"}, None),
+ ("incomplete", {"arguments": []}, None),
+ ],
+)
+def test_interrupted_discovery_is_excluded_before_tool_activation(
+ native: bool,
+ status: str,
+ argument_fields: JsonObject,
+ implicit_execution: str | None,
+) -> None:
+ call: JsonObject = {
+ "type": "tool_search_call",
+ "call_id": "search",
+ "execution": "client",
+ "status": status,
+ **argument_fields,
+ }
+ result: JsonObject = {
+ "type": "tool_search_output",
+ "call_id": "search",
+ "execution": "client",
+ "status": "completed",
+ # Discarded definitions must not reach validation or name registration.
+ "tools": [{"type": "namespace", "tools": "invalid"}]
+ if status == "failed"
+ else [AGENTS],
+ }
+ if implicit_execution == "call":
+ call.pop("execution")
+ elif implicit_execution == "output":
+ result["execution"] = None
+ user: JsonObject = {"role": "user", "content": "Find a tool"}
+ retry: JsonObject = {"role": "user", "content": "Continue"}
+ request = OpenAIResponsesRequest(
+ model="example", input=[user, call, result, retry], tools=[SEARCH]
+ )
+ original = request.model_dump()
+ if native:
+ prepared = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(client_tool_search=True, flatten_namespaces=True),
+ ).request
+ assert prepared.input == [user, retry]
+ assert [tool["name"] for tool in prepared.tools or []] == ["fcc_tool_search"]
+ else:
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ assert body["messages"] == [user, retry]
+ assert [
+ tool["function"]["name"] for tool in cast(list[Any], body["tools"])
+ ] == ["fcc_tool_search"]
+ assert request.model_dump() == original
+
+
[email protected]("native", [False, True])
+def test_interrupted_discovery_keeps_completed_occurrences_of_reused_id(
+ native: bool,
+) -> None:
+ history: list[JsonValue] = [{"role": "user", "content": "Find tools"}]
+ for status, name in [
+ ("completed", "first"),
+ ("incomplete", "discarded"),
+ ("completed", "last"),
+ ]:
+ history.extend(
+ [
+ {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "reused",
+ "status": status,
+ "arguments": {"query": name},
+ },
+ {
+ "type": "tool_search_output",
+ "execution": "client",
+ "call_id": "reused",
+ "tools": [
+ {
+ "type": "function",
+ "name": name,
+ "parameters": {"type": "object"},
+ }
+ ],
+ },
+ ]
+ )
+ request = OpenAIResponsesRequest(model="example", input=history, tools=[SEARCH])
+ 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)
+ calls = [
+ item["arguments"] for item in items if item.get("type") == "function_call"
+ ]
+ results = [
+ json.loads(item["output"])
+ for item in items
+ if item.get("type") == "function_call_output"
+ ]
+ names = [tool["name"] for tool in prepared.tools or []]
+ else:
+ body = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ ).body
+ messages = cast(list[dict[str, Any]], body["messages"])
+ calls = [
+ call["function"]["arguments"]
+ for message in messages
+ for call in message.get("tool_calls", [])
+ ]
+ results = [
+ json.loads(message["content"])
+ for message in messages
+ if message["role"] == "tool"
+ ]
+ names = [tool["function"]["name"] for tool in cast(list[Any], body["tools"])]
+ assert [json.loads(arguments) for arguments in calls] == [
+ {"query": "first"},
+ {"query": "last"},
+ ]
+ assert [tools[0]["name"] for tools in results] == ["first", "last"]
+ assert set(names) == {"first", "last", "fcc_tool_search"}
+ assert request.model_dump() == original
+
+
[email protected]("native", [False, True])
+def test_interrupted_discovery_keeps_custom_output_source_and_later_discovery(
+ native: bool,
+) -> None:
+ custom_output: JsonValue = [
+ {"type": "input_image", "image_url": "data:image/png;base64,cG5n"}
+ ]
+ history: list[JsonValue] = [
+ {"role": "user", "content": "Edit and then find a tool"},
+ {
+ "type": "reasoning",
+ "content": [{"type": "reasoning_text", "text": "Saved reasoning"}],
+ },
+ {
+ "type": "custom_tool_call",
+ "call_id": "edit",
+ "name": "edit",
+ "input": "patch",
+ },
+ {
+ "type": "tool_search_call",
+ "call_id": "aborted",
+ "execution": "client",
+ "status": "incomplete",
+ "arguments": {},
+ },
+ {
+ "type": "tool_search_output",
+ "call_id": "aborted",
+ "execution": "client",
+ "tools": [],
+ },
+ {"type": "custom_tool_call_output", "call_id": "edit", "output": custom_output},
+ {
+ "type": "tool_search_call",
+ "call_id": "found",
+ "execution": "client",
+ "arguments": {"query": "lookup"},
+ },
+ {
+ "type": "tool_search_output",
+ "call_id": "found",
+ "execution": "client",
+ "tools": [
+ {
+ "type": "function",
+ "name": "lookup files",
+ "parameters": {"type": "object"},
+ }
+ ],
+ },
+ {
+ "type": "function_call",
+ "call_id": "lookup",
+ "name": "lookup files",
+ "arguments": "{}",
+ },
+ {"type": "function_call_output", "call_id": "lookup", "output": "Found files"},
+ ]
+ request = OpenAIResponsesRequest(
+ model="example",
+ input=history,
+ tools=[SEARCH, {"type": "custom", "name": "edit", "format": {"type": "text"}}],
+ )
+ original = request.model_dump()
+ if native:
+ prepared = ResponsesToolAdapter(
+ request,
+ ResponsesToolPolicy(
+ custom_tools_as_functions=True,
+ client_tool_search=True,
+ flatten_namespaces=True,
+ ),
+ ).request
+ items = cast(list[dict[str, Any]], prepared.input)
+ assert [item.get("call_id") for item in items] == [
+ None,
+ None,
+ "edit",
+ "edit",
+ "found",
+ "found",
+ "lookup",
+ "lookup",
+ ]
+ assert items[1] == history[1]
+ assert items[3]["output"] == custom_output
+ assert items[-1]["output"] == "Found files"
+ assert json.loads(items[5]["output"])[0]["name"] == "lookup files"
+ else:
+ translated = build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.REASONING_CONTENT
+ )
+ body = translated.body
+ encode_openai_chat_tool_names(body, translated.tool_names)
+ messages = cast(list[dict[str, Any]], body["messages"])
+ assert [
+ item.get("tool_call_id") for item in messages if item["role"] == "tool"
+ ] == ["edit", "found", "lookup"]
+ assert messages[1]["reasoning_content"] == "Saved reasoning"
+ assert json.loads(messages[2]["content"]) == custom_output
+ found = next(item for item in messages if item.get("tool_call_id") == "found")
+ wire_name = json.loads(found["content"])[0]["name"]
+ assert " " not in wire_name
+ assert any(
+ tool["function"]["name"] == wire_name
+ for tool in cast(list[Any], body["tools"])
+ )
+ assert messages[-2]["tool_calls"][0]["function"]["name"] == wire_name
+ assert messages[-1]["content"] == "Found files"
+ assert request.model_dump() == original
+
+
[email protected]("native", [False, True])
+def test_interrupted_discovery_cannot_leave_empty_provider_input(native: bool) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[
+ {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "status": "incomplete",
+ "arguments": {},
+ }
+ ],
+ )
+ with pytest.raises(ResponsesConversionError, match="usable input"):
+ if native:
+ ResponsesToolAdapter(request, ResponsesToolPolicy(client_tool_search=True))
+ else:
+ build_responses_chat_request(
+ request, reasoning_replay=ReasoningReplayMode.DISABLED
+ )
+
+
[email protected]("status", ["omitted", None, "completed"])
[email protected]("arguments", [None, '{"query":'])
+def test_completed_discovery_history_still_requires_object_arguments(
+ status: str | None, arguments: JsonValue
+) -> None:
+ call: JsonObject = {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "arguments": arguments,
+ }
+ if status != "omitted":
+ call["status"] = status
+ with pytest.raises(ResponsesConversionError, match="arguments must be an object"):
+ ResponsesToolAdapter(
+ OpenAIResponsesRequest(model="example", input=[call], tools=[SEARCH]),
+ ResponsesToolPolicy(client_tool_search=True),
+ )
+
+
+ ("enabled", "execution"), [(False, "client"), (True, "server"), (True, None)]
+)
+def test_interrupted_discovery_filter_respects_execution_policy(
+ enabled: bool, execution: str | None
+) -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ input=[
+ {
+ "type": "tool_search_call",
+ "execution": execution,
+ "call_id": "search",
+ "status": "incomplete",
+ "arguments": '{"query":',
+ },
+ {
+ "type": "tool_search_output",
+ "execution": execution,
+ "call_id": "search",
+ "tools": [],
+ },
+ ],
+ )
+ original = request.model_dump()
+ adapter = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(client_tool_search=enabled)
+ )
+ assert adapter.request.model_dump() == original
+ assert request.model_dump() == original
+
+
+def test_interrupted_discovery_alone_does_not_enable_search() -> None:
+ user: JsonObject = {"role": "user", "content": "Continue"}
+ request = OpenAIResponsesRequest(
+ model="example",
+ input=[
+ user,
+ {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "status": "incomplete",
+ "arguments": None,
+ },
+ ],
+ )
+ prepared = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(client_tool_search=True)
+ ).request
+ assert prepared.input == [user]
+ assert prepared.tools is None
+
+
+def test_interrupted_discovery_snapshot_can_be_followed_by_completed_call() -> None:
+ request = OpenAIResponsesRequest(
+ model="example",
+ tools=[SEARCH],
+ input=[
+ {"role": "user", "content": "Find a tool"},
+ {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "status": "in_progress",
+ "arguments": None,
+ },
+ {
+ "type": "tool_search_call",
+ "execution": "client",
+ "call_id": "search",
+ "status": "completed",
+ "arguments": {"query": "agent"},
+ },
+ {
+ "type": "tool_search_output",
+ "execution": "client",
+ "call_id": "search",
+ "tools": [AGENTS],
+ },
+ ],
+ )
+ prepared = ResponsesToolAdapter(
+ request, ResponsesToolPolicy(client_tool_search=True, flatten_namespaces=True)
+ ).request
+ items = cast(list[dict[str, Any]], prepared.input)
+ assert len(items) == 3
+ assert items[1]["status"] == "completed"
+ assert json.loads(items[1]["arguments"]) == {"query": "agent"}
+ assert json.loads(items[2]["output"])[0]["name"] == "agents__spawn_agent"
+ assert "agents__spawn_agent" in [tool["name"] for tool in prepared.tools or []]
+
+
def test_search_lowering_does_not_shadow_a_real_function() -> None:
adapter = _native_adapter(
[
diff --git a/tests/providers/test_openai_responses_transport.py b/tests/providers/test_openai_responses_transport.py
index cb9a45ae..aa826109 100644
--- a/tests/providers/test_openai_responses_transport.py
+++ b/tests/providers/test_openai_responses_transport.py
@@ -4,6 +4,8 @@ import asyncio
import json
import re
from collections.abc import Callable, Mapping
+from copy import deepcopy
+from typing import Any
import httpx2
import pytest
@@ -19,6 +21,7 @@ from free_claude_code.core.anthropic.stream_contracts import (
thinking_content,
)
from free_claude_code.core.failures import ExecutionFailure, FailureKind
+from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.openai_responses import (
OpenAIResponsesRequest,
ResponsesToolPolicy,
@@ -30,6 +33,7 @@ from free_claude_code.providers.openai_chat.stream_output import (
ResponsesChatStreamOutput,
)
from free_claude_code.providers.openai_responses import OpenAIResponsesTransport
+from tests.core.openai_responses.test_client_tool_discovery import AGENTS, SEARCH
from tests.providers.support import REASONING_ON, immediate_admission
@@ -846,6 +850,177 @@ async def test_native_committed_truncation_emits_one_failed_terminal() -> None:
assert events[-1].data["response"]["status"] == "failed"
+async def test_interrupted_discovery_can_continue_through_native_transport() -> None:
+ bodies: list[dict[str, Any]] = []
+ saved_text = "Saved work" * 7_000
+ user: JsonObject = {"role": "user", "content": "Find an agent"}
+ retry: JsonObject = {"role": "user", "content": "Continue"}
+ sibling: JsonObject = {
+ "id": "item_text",
+ "type": "message",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": saved_text, "annotations": []}],
+ }
+ error = {"code": "server_error", "message": "Original upstream timeout"}
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ body = json.loads(request.content)
+ bodies.append(body)
+ created = {
+ "type": "response.created",
+ "sequence_number": 0,
+ "response": {
+ **_completed_response(),
+ "status": "in_progress",
+ "usage": None,
+ },
+ }
+ call = {
+ "type": "function_call",
+ "id": "fc_search",
+ "call_id": "search",
+ "name": "fcc_tool_search",
+ "status": "incomplete",
+ "arguments": '{"query":',
+ }
+ if len(bodies) == 1:
+ events = [
+ created,
+ # Commit the attempt before its failure, using the existing buffer limit.
+ _text_delta(saved_text, sequence=1),
+ {
+ "type": "response.output_item.done",
+ "sequence_number": 2,
+ "output_index": 0,
+ "item": sibling,
+ },
+ {
+ "type": "response.output_item.added",
+ "sequence_number": 3,
+ "output_index": 1,
+ "item": {**call, "status": "in_progress"},
+ },
+ {
+ "type": "response.failed",
+ "sequence_number": 4,
+ "response": {
+ **_completed_response(),
+ "status": "failed",
+ "error": error,
+ "output": [sibling, call],
+ },
+ },
+ ]
+ elif len(bodies) == 2:
+ assert body["input"] == [user, sibling, retry]
+ complete = {
+ **call,
+ "call_id": "retry_search",
+ "status": "completed",
+ "arguments": '{"query":"agent"}',
+ }
+ events = [
+ created,
+ {
+ "type": "response.output_item.added",
+ "sequence_number": 1,
+ "output_index": 0,
+ "item": {**complete, "status": "in_progress", "arguments": ""},
+ },
+ {
+ "type": "response.output_item.done",
+ "sequence_number": 2,
+ "output_index": 0,
+ "item": complete,
+ },
+ {
+ "type": "response.completed",
+ "sequence_number": 3,
+ "response": {**_completed_response(), "output": [complete]},
+ },
+ ]
+ else:
+ assert len(bodies) == 3
+ assert body["input"][-2]["type"] == "function_call"
+ assert body["input"][-2]["call_id"] == "retry_search"
+ result = body["input"][-1]
+ assert result["type"] == "function_call_output"
+ assert result["call_id"] == "retry_search"
+ assert json.loads(result["output"])[0]["name"] == "agents__spawn_agent"
+ assert "agents__spawn_agent" in [tool["name"] for tool in body["tools"]]
+ events = [created, _completed_event()]
+ return httpx2.Response(
+ 200, headers={"content-type": "text/event-stream"}, text=_sse(*events)
+ )
+
+ client = _client(handler)
+ transport = _transport(
+ client,
+ max_attempts=2,
+ tool_policy=ResponsesToolPolicy(
+ client_tool_search=True, flatten_namespaces=True
+ ),
+ )
+ history: list[JsonObject] = [user]
+ try:
+ first = OpenAIResponsesRequest(model="example", input=history, tools=[SEARCH])
+ original = first.model_dump()
+ events = parse_sse_text("".join(await _collect_native(transport, first)))
+ assert first.model_dump() == original
+ failed = events[-1].data["response"]
+ assert events[-1].event == "response.failed"
+ assert failed["error"] == error
+ assert failed["output"][0] == sibling
+ partial = failed["output"][1]
+ assert partial["type"] == "tool_search_call"
+ assert partial["arguments"] == '{"query":'
+ assert partial["status"] == "incomplete"
+ assert len(bodies) == 1
+ history.extend([*failed["output"], retry])
+ second = OpenAIResponsesRequest(model="example", input=history, tools=[SEARCH])
+ original = deepcopy(history)
+ events = parse_sse_text("".join(await _collect_native(transport, second)))
+ assert history == original
+ assert events[-1].event == "response.completed"
+ complete = events[-1].data["response"]["output"][0]
+ assert complete["type"] == "tool_search_call"
+ assert complete["arguments"] == {"query": "agent"}
+ history.extend(
+ [
+ complete,
+ {
+ "type": "tool_search_output",
+ "execution": "client",
+ "call_id": "retry_search",
+ "tools": [AGENTS],
+ },
+ ]
+ )
+ events = parse_sse_text(
+ "".join(
+ await _collect_native(
+ transport,
+ OpenAIResponsesRequest(
+ model="example", input=history, tools=[SEARCH]
+ ),
+ )
+ )
+ )
+ assert events[-1].event == "response.completed"
+ with pytest.raises(InvalidRequestError, match="usable input"):
+ await _collect_native(
+ transport,
+ OpenAIResponsesRequest(
+ model="example", input=[partial], tools=[SEARCH]
+ ),
+ )
+ assert len(bodies) == 3
+ finally:
+ await client.close()
+
+
@pytest.mark.asyncio
async def test_native_response_incomplete_is_a_normal_terminal() -> None:
incomplete = {
diff --git a/uv.lock b/uv.lock
index 385bf719..76b39c11 100644
--- a/uv.lock
+++ b/uv.lock
@@ -599,7 +599,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "6.2.41"
+version = "6.2.42"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },