File size: 13,343 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""Every ingress/egress pair survives a tool turn with protected reasoning."""

import asyncio
import json
from copy import deepcopy
from unittest.mock import patch

import httpx
import httpx2
import pytest
from fastapi.testclient import TestClient
from openai import AsyncOpenAI

from free_claude_code.config.provider_catalog import GEMINI_DEFAULT_BASE
from free_claude_code.config.settings import Settings
from free_claude_code.core.anthropic import aggregate_anthropic_sse_to_message
from free_claude_code.core.anthropic.stream_contracts import parse_sse_text
from free_claude_code.core.chat_completions.response import ChatResponseAccumulator
from free_claude_code.core.gemini.response import GeminiResponseAccumulator
from free_claude_code.providers.gemini import GeminiProvider
from free_claude_code.providers.open_router import OpenRouterProvider
from tests.api.support import create_test_app, provider_manager_for_app
from tests.providers.support import immediate_admission, make_provider_config
from tests.providers.test_custom_provider import definition, provider
from tests.providers.test_history_transports import _native
from tests.providers.test_native_tool_arguments import tool_events

SCHEMA = {"type": "object", "properties": {"path": {"type": "string"}}}
GEMINI_PARTS = [
    {"text": "Find 17.", "thought": True},
    {
        "functionCall": {"id": "call_probe", "name": "read", "args": {"path": "kept"}},
        "thoughtSignature": "native-google-signature",
    },
]


@pytest.mark.parametrize("tool_type", [None, "custom", "web_search_20250305"])
def test_messages_custom_tool_type_is_translated_to_native_gemini(tool_type):
    from tests.providers.test_gemini import _sse

    bodies = []

    def reply(request):
        bodies.append(json.loads(request.content))
        return _sse([{"text": "hello"}])

    tool = {"name": "read", "description": "Read a file", "input_schema": SCHEMA}
    if tool_type is not None:
        tool["type"] = tool_type
    with TestClient(matrix_app("gemini", reply)) as client:
        response = client.post(
            "/v1/messages",
            json={
                "model": "public",
                "messages": [{"role": "user", "content": "hello"}],
                "max_tokens": 128,
                "tools": [tool],
            },
        )
    if tool_type == "web_search_20250305":
        assert response.status_code == 400
        assert not bodies
    else:
        assert response.status_code == 200, response.text
        assert bodies[0]["tools"] == [
            {
                "functionDeclarations": [
                    {
                        "name": "read",
                        "description": "Read a file",
                        "parametersJsonSchema": SCHEMA,
                    }
                ]
            }
        ]


def source_events(protocol):
    if protocol == "gemini":
        return [
            {
                "responseId": "native-response",
                "modelVersion": "upstream",
                "candidates": [
                    {
                        "index": 0,
                        "content": {"role": "model", "parts": GEMINI_PARTS},
                        "finishReason": "STOP",
                    }
                ],
            }
        ]
    events = tool_events(protocol, '{"path":"kept"}')
    native = _native(protocol)
    if protocol == "chat":
        return [
            {
                **events[0],
                "choices": [{"index": 0, "delta": native, "finish_reason": None}],
            },
            *events,
        ]
    if protocol == "messages":
        tail = deepcopy(events[1:])
        for event in tail:
            if "index" in event:
                event["index"] += 1
        return [
            events[0],
            {"type": "content_block_start", "index": 0, "content_block": native},
            {"type": "content_block_stop", "index": 0},
            *tail,
        ]
    for event in events:
        if "output_index" in event:
            event["output_index"] += 1
    events[-1]["response"]["output"].insert(0, native)
    events.insert(
        1, {"type": "response.output_item.done", "output_index": 0, "item": native}
    )
    return [{**event, "sequence_number": index} for index, event in enumerate(events)]


def matrix_app(protocol, reply, *, max_attempts=2, model_fallbacks=None):
    if protocol == "gemini":
        instance = GeminiProvider(
            make_provider_config(api_key="upstream-key", base_url=GEMINI_DEFAULT_BASE),
            admission=immediate_admission(max_attempts=max_attempts),
            transport=httpx.MockTransport(reply),
        )
        provider_id = "gemini"
        settings = Settings(MODEL="gemini/models/backend")
    elif protocol == "chat":
        client = AsyncOpenAI(
            api_key="upstream-key",
            base_url="https://upstream.invalid/v1",
            max_retries=0,
            http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(reply)),
        )
        with patch(
            "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
            return_value=client,
        ):
            instance = OpenRouterProvider(
                make_provider_config(
                    api_key="upstream-key", base_url="https://upstream.invalid/v1"
                ),
                admission=immediate_admission(max_attempts=max_attempts),
            )
        provider_id = "open_router"
        settings = Settings(
            MODEL="open_router/backend", MODEL_FALLBACKS=model_fallbacks
        )
    else:
        configured = definition(
            api_format="anthropic_messages"
            if protocol == "messages"
            else "openai_responses",
            api_keys=["upstream-key"],
        )
        instance = provider(configured, openai_handler=reply, messages_handler=reply)
        provider_id = configured.provider_id
        settings = Settings(
            MODEL=f"{provider_id}/backend", custom_providers=(configured,)
        )
    return create_test_app(settings, providers={provider_id: instance})


def ingress_request(wire, streaming, history=None):
    tools = (
        [{"name": "read", "input_schema": SCHEMA}]
        if wire == "messages"
        else [
            {"type": "function", "function": {"name": "read", "parameters": SCHEMA}}
            if wire == "chat"
            else {"type": "function", "name": "read", "parameters": SCHEMA}
        ]
    )
    if wire == "gemini":
        method = "streamGenerateContent?alt=sse" if streaming else "generateContent"
        return f"/v1beta/models/public:{method}", {
            "contents": history or [{"role": "user", "parts": [{"text": "hello"}]}],
            "tools": [
                {
                    "functionDeclarations": [
                        {"name": "read", "parametersJsonSchema": SCHEMA}
                    ]
                }
            ],
            "generationConfig": {"thinkingConfig": {"includeThoughts": True}},
        }
    body = {
        "model": "public",
        "stream": streaming,
        "tools": tools,
        "input" if wire == "responses" else "messages": history
        or [{"role": "user", "content": "hello"}],
    }
    if wire == "messages":
        body["max_tokens"] = 100
    return "/v1/chat/completions" if wire == "chat" else f"/v1/{wire}", body


def response_value(response, wire, streaming):
    assert response.status_code == 200, response.text
    if not streaming:
        return response.json()
    events = parse_sse_text(response.text)
    if wire == "responses":
        assert events[-1].event == "response.completed", response.text
        return events[-1].data["response"]
    if wire == "messages":

        async def stream():
            yield response.text

        message, error, stopped = asyncio.run(
            aggregate_anthropic_sse_to_message(stream())
        )
        assert error is None and stopped, response.text
        return message
    accumulator = (
        ChatResponseAccumulator() if wire == "chat" else GeminiResponseAccumulator()
    )
    for event in events:
        accumulator.feed(event.data)
    if wire == "chat":
        assert response.text.endswith("data: [DONE]\n\n"), response.text
        assert isinstance(accumulator, ChatResponseAccumulator)
        accumulator.finish()
    return accumulator.result()


def reply_history(value, wire):
    initial = {"role": "user", "content": "hello"}
    if wire == "messages":
        call = next(block for block in value["content"] if block["type"] == "tool_use")
        assert call["input"] == {"path": "kept"}
        return [
            initial,
            {"role": "assistant", "content": value["content"]},
            {
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": call["id"],
                        "content": "tool-value",
                    }
                ],
            },
        ]
    if wire == "responses":
        call = next(item for item in value["output"] if item["type"] == "function_call")
        assert json.loads(call["arguments"]) == {"path": "kept"}
        return [
            initial,
            *value["output"],
            {
                "type": "function_call_output",
                "call_id": call["call_id"],
                "output": "tool-value",
            },
        ]
    if wire == "chat":
        message = value["choices"][0]["message"]
        call = message["tool_calls"][0]
        assert json.loads(call["function"]["arguments"]) == {"path": "kept"}
        return [
            initial,
            message,
            {"role": "tool", "tool_call_id": call["id"], "content": "tool-value"},
        ]
    content = value["candidates"][0]["content"]
    call = next(
        part["functionCall"] for part in content["parts"] if "functionCall" in part
    )
    assert call["args"] == {"path": "kept"}
    return [
        {"role": "user", "parts": [{"text": "hello"}]},
        content,
        {
            "role": "user",
            "parts": [
                {
                    "functionResponse": {
                        "id": call["id"],
                        "name": "read",
                        "response": {"output": "tool-value"},
                    }
                }
            ],
        },
    ]


@pytest.mark.parametrize("protocol", ["chat", "messages", "responses", "gemini"])
@pytest.mark.parametrize(
    ("wire", "streaming"),
    [
        (wire, stream)
        for wire in ("messages", "responses", "chat", "gemini")
        for stream in (False, True)
        if wire != "responses" or stream
    ],
)
def test_all_sixteen_paths_replay_native_state_and_tool_results(
    protocol, wire, streaming
):
    bodies = []

    def reply(request):
        bodies.append(json.loads(request.content))
        events = source_events(protocol)
        raw = "".join(
            (f"event: {event['type']}\n" if protocol == "messages" else "")
            + f"data: {json.dumps(event)}\n\n"
            for event in events
        )
        response = (
            httpx.Response if protocol in {"messages", "gemini"} else httpx2.Response
        )
        return response(200, headers={"content-type": "text/event-stream"}, text=raw)

    app = matrix_app(protocol, reply)
    with TestClient(app) as client:
        path, body = ingress_request(wire, streaming)
        first = response_value(client.post(path, json=body), wire, streaming)
        assert "Find 17." in json.dumps(first)
        path, body = ingress_request(wire, streaming, reply_history(first, wire))
        response_value(client.post(path, json=body), wire, streaming)
        assert provider_manager_for_app(app)._current.active_leases == 0
    assert len(bodies) == 2
    assert "tool-value" in json.dumps(bodies[1])
    if protocol == "gemini":
        assert bodies[1]["contents"][1] == {"role": "model", "parts": GEMINI_PARTS}
    elif protocol == "messages":
        replayed = next(
            block
            for block in bodies[1]["messages"][1]["content"]
            if block.get("type") == "thinking"
        )
        expected = _native(protocol)
        # The existing Messages -> Responses codec retains signed fields, but
        # has never retained arbitrary block extensions. New paths retain both.
        if wire == "responses":
            expected.pop("extension")
        assert replayed == expected
    elif protocol == "responses":
        assert _native(protocol) in bodies[1]["input"]
    else:
        assistant = next(
            message
            for message in bodies[1]["messages"]
            if message["role"] == "assistant"
        )
        if wire in {"chat", "gemini"}:
            assert (
                assistant["reasoning_details"] == _native(protocol)["reasoning_details"]
            )
        else:
            # Existing Messages/Responses presentations expose Chat's opaque
            # bytes separately from its readable scalar representation.
            assert any(
                detail.get("data") == "opaque-original"
                for detail in assistant["reasoning_details"]
            )
            assert json.dumps(assistant).count("Find 17.") == 1