File size: 17,028 Bytes
9f6a4bd
e99df76
691dc7c
3934d27
8e438ab
3934d27
 
 
 
 
 
 
 
a9e27c0
2e7b8ca
8e438ab
 
 
 
3934d27
a9e27c0
e99df76
3934d27
691dc7c
 
a9e27c0
3934d27
 
 
691dc7c
3934d27
 
691dc7c
 
3934d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
3934d27
 
 
 
 
 
 
 
a9e27c0
3934d27
 
a9e27c0
691dc7c
3934d27
691dc7c
 
9f6a4bd
6dc304d
691dc7c
 
 
a9e27c0
691dc7c
 
 
 
 
3934d27
 
 
 
 
 
 
 
 
 
 
a9e27c0
3934d27
 
8e438ab
 
 
 
 
691dc7c
 
8e438ab
3934d27
 
 
 
 
 
691dc7c
3934d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e438ab
 
 
 
691dc7c
 
 
 
8e438ab
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
 
3934d27
8e438ab
3934d27
 
 
 
 
 
 
8e438ab
 
 
e99df76
a9e27c0
3934d27
 
 
 
 
 
8e438ab
 
e99df76
3934d27
 
 
 
 
 
 
 
 
 
8e438ab
 
e99df76
a9e27c0
3934d27
 
8e438ab
a9e27c0
3934d27
 
8e438ab
3934d27
 
 
 
 
8e438ab
 
 
e99df76
3934d27
 
691dc7c
3934d27
 
 
 
 
8e438ab
691dc7c
8e438ab
e99df76
8e438ab
 
 
 
 
 
 
 
 
 
 
 
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7b8ca
 
 
 
 
 
 
 
 
 
 
 
a9e27c0
2e7b8ca
 
 
 
 
 
 
 
 
 
 
8e438ab
 
 
 
 
 
 
 
 
 
691dc7c
e99df76
a9e27c0
2e7b8ca
8e438ab
 
 
 
 
 
 
e99df76
8e438ab
 
2e7b8ca
8e438ab
a9e27c0
8e438ab
 
 
 
 
 
 
e99df76
a9e27c0
8e438ab
 
2e7b8ca
 
 
a9e27c0
8e438ab
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7b8ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e438ab
 
 
 
 
 
 
 
e99df76
8e438ab
 
691dc7c
8e438ab
 
 
 
 
 
691dc7c
e99df76
3934d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9e27c0
3934d27
 
 
 
 
 
 
 
 
 
 
a9e27c0
3934d27
 
 
 
8e438ab
3934d27
 
 
 
 
 
 
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
from __future__ import annotations
"""OpenCode provider with catalog-driven Chat/Responses dispatch."""

import sys
from collections.abc import AsyncIterator, Mapping
from dataclasses import dataclass

import httpx

from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.application.model_metadata import ProviderModelInfo
from free_claude_code.core.anthropic import ReasoningReplayMode
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.chat_completions.request import ChatRequest
from free_claude_code.core.gemini import GeminiRequest
from free_claude_code.core.openai_responses import (
    OpenAIResponsesRequest,
    ResponsesToolPolicy,
)
from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy
from free_claude_code.core.stream_output import StreamOutput
from free_claude_code.core.stream_recovery import ContinuationSeed
from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import BaseProvider, ProviderConfig
from free_claude_code.providers.endpoint_types import EndpointContext
from free_claude_code.providers.history_negotiation import HistoryModeCache
from free_claude_code.providers.http import close_provider_stream
from free_claude_code.providers.openai_chat import (
    NO_REASONING,
    OpenAIChatBehavior,
    OpenAIChatProfile,
    OpenAIChatRequestPolicy,
    OpenAIChatTransport,
    create_chat_client,
)
from free_claude_code.providers.openai_responses import OpenAIResponsesTransport

from .catalog import (
    OpenCodeCatalog,
    OpenCodeCatalogSnapshot,
    OpenCodeModelRoute,
    OpenCodeUpstreamTransport,
)


@dataclass(frozen=True, slots=True)
class OpenCodeProfile:
    """Immutable identity and catalog configuration for one OpenCode plan."""

    provider_id: str
    provider_name: str
    catalog_key: str
    chat_profile: OpenAIChatProfile


def _profile(
    provider_id: str,
    provider_name: str,
    catalog_key: str,
) -> OpenCodeProfile:
    return OpenCodeProfile(
        provider_id=provider_id,
        provider_name=provider_name,
        catalog_key=catalog_key,
        chat_profile=OpenAIChatProfile(
            OpenAIChatRequestPolicy(
                provider_name=provider_name,
                reasoning_replay=ReasoningReplayMode.REASONING_CONTENT,
            ),
            NO_REASONING,
            user_agent="opencode",
        ),
    )


_PROFILES = {
    "opencode_zen": _profile("opencode_zen", "OPENCODE_ZEN", "opencode"),
    "opencode_go": _profile("opencode_go", "OPENCODE_GO", "opencode-go"),
}


class OpenCodeProvider(BaseProvider):
    """Route OpenCode models through their catalog-declared OpenAI endpoint."""

    def __init__(
        self,
        config: ProviderConfig,
        *,
        profile: OpenCodeProfile,
        admission: ProviderAdmissionController,
        history_cache: HistoryModeCache | None = None,
        catalog_client: httpx.AsyncClient | None = None,
    ) -> None:
        super().__init__(config, history_cache=history_cache)
        self._client = create_chat_client(
            config,
            base_url=profile.chat_profile.base_url(config.base_url).rstrip("/"),
            provider_name=profile.provider_name,
            default_headers={"User-Agent": "opencode"},
        )
        self._chat = OpenAIChatTransport(
            client=self._client,
            admission=admission,
            history_cache=self._history_cache,
            behavior=OpenAIChatBehavior(profile.chat_profile),
            read_timeout_s=config.http_read_timeout,
            log_raw_sse_events=config.log_raw_sse_events,
            log_api_error_tracebacks=config.log_api_error_tracebacks,
        )
        self._opencode_profile = profile
        self._catalog = OpenCodeCatalog(
            config,
            provider_key=profile.catalog_key,
            provider_name=profile.provider_name,
            admission=admission,
            client=catalog_client,
        )
        self._responses = OpenAIResponsesTransport(
            client=self._client,
            admission=admission,
            history_cache=self._history_cache,
            provider_name=profile.provider_name,
            read_timeout_s=config.http_read_timeout,
            log_raw_sse_events=config.log_raw_sse_events,
            tool_policy=ResponsesToolPolicy(
                custom_tools_as_functions=True,
                explicit_search_parameters=True,
                text_only_web_search=True,
                client_tool_search=True,
                flatten_namespaces=True,
            ),
        )

    async def cleanup(self) -> None:
        """Close both owned clients even when one cleanup fails."""
        errors: list[Exception] = []
        try:
            await self._client.close()
        except Exception as exc:
            errors.append(exc)
        try:
            await self._catalog.cleanup()
        except Exception as exc:
            errors.append(exc)
        if len(errors) == 1:
            raise errors[0]
        if errors:
            raise ExceptionGroup("OpenCode provider cleanup failed", errors)

    async def list_model_infos(self) -> frozenset[ProviderModelInfo]:
        snapshot = await self._catalog.refresh()
        return snapshot.model_infos

    def _upstream_headers(
        self, request_headers: Mapping[str, str]
    ) -> Mapping[str, str]:
        headers = {name.lower(): value for name, value in request_headers.items()}
        upstream_headers = {}
        user_agent = headers.get("user-agent")
        if user_agent and user_agent.isascii() and user_agent.strip():
            upstream_headers["User-Agent"] = user_agent
        for name in (
            "x-opencode-session",
            "session-id",
            "x-session-id",
            "x-claude-code-session-id",
            "session_id",
            "x-grok-session-id",
            "x-meta-ai-gateway-session-id",
            "x-tbh-session-id",
            "x-fcc-launch-id",
        ):
            session_id = headers.get(name)
            if session_id and session_id.strip():
                upstream_headers["x-opencode-session"] = session_id
                break
        return upstream_headers

    def stream_messages(
        self,
        request: MessagesRequest,
        input_tokens: int = 0,
        *,
        request_id: str | None = None,
        response_model: str | None = None,
        reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
        endpoint_context: EndpointContext | None = None,
        request_headers: Mapping[str, str] | None = None,
        model_info: ProviderModelInfo | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[StreamOutput]:
        return self._dispatch_stream(
            request,
            input_tokens=input_tokens,
            request_id=request_id,
            response_model=response_model or request.model,
            reasoning=reasoning,
            endpoint_context=endpoint_context,
            request_headers=request_headers,
            continuation=continuation,
        )

    async def _dispatch_stream(
        self,
        request: MessagesRequest,
        *,
        input_tokens: int,
        request_id: str | None,
        response_model: str,
        reasoning: ReasoningPolicy,
        endpoint_context: EndpointContext | None = None,
        request_headers: Mapping[str, str] | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[StreamOutput]:
        snapshot = await self._catalog.snapshot(request_id=request_id)
        route = self._require_route(snapshot, request.model)
        routed = _routed_messages_request(request, route)
        selected_stream: AsyncIterator[StreamOutput] | None = None
        try:
            if route.transport is OpenCodeUpstreamTransport.RESPONSES:
                selected_stream = self._responses.stream_messages(
                    routed,
                    input_tokens=input_tokens,
                    request_id=request_id,
                    response_model=response_model,
                    reasoning=reasoning,
                    endpoint_context=endpoint_context,
                    extra_headers=self._upstream_headers(request_headers or {}),
                    model_info=route.model_info,
                    continuation=continuation,
                )
            else:
                selected_stream = self._chat.stream_messages(
                    routed,
                    input_tokens=input_tokens,
                    request_id=request_id,
                    response_model=response_model,
                    reasoning=reasoning,
                    endpoint_context=endpoint_context,
                    extra_headers=self._upstream_headers(request_headers or {}),
                    model_info=route.model_info,
                    continuation=continuation,
                )
            async for event in selected_stream:
                yield event
        finally:
            if selected_stream is not None:
                await close_provider_stream(
                    selected_stream,
                    active_error=sys.exception(),
                    provider_name=self._opencode_profile.provider_name,
                    request_id=request_id,
                )

    def stream_chat(
        self,
        request: ChatRequest,
        input_tokens: int = 0,
        *,
        request_id: str | None = None,
        response_model: str | None = None,
        reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
        endpoint_context: EndpointContext | None = None,
        request_headers: Mapping[str, str] | None = None,
        model_info: ProviderModelInfo | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[StreamOutput]:
        return self._dispatch_openai_stream(
            request,
            input_tokens=input_tokens,
            request_id=request_id,
            response_model=response_model or request.model,
            reasoning=reasoning,
            endpoint_context=endpoint_context,
            request_headers=request_headers,
            continuation=continuation,
        )

    def stream_gemini(
        self,
        request: GeminiRequest,
        input_tokens: int = 0,
        *,
        request_id: str | None = None,
        response_model: str | None = None,
        reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
        endpoint_context: EndpointContext | None = None,
        request_headers: Mapping[str, str] | None = None,
        model_info: ProviderModelInfo | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[StreamOutput]:
        return self._dispatch_openai_stream(
            request,
            input_tokens=input_tokens,
            request_id=request_id,
            response_model=response_model or request.model,
            reasoning=reasoning,
            endpoint_context=endpoint_context,
            request_headers=request_headers,
            continuation=continuation,
        )

    def stream_responses(
        self,
        request: OpenAIResponsesRequest,
        input_tokens: int = 0,
        *,
        request_id: str | None = None,
        response_model: str | None = None,
        reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
        endpoint_context: EndpointContext | None = None,
        request_headers: Mapping[str, str] | None = None,
        model_info: ProviderModelInfo | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[StreamOutput]:
        return self._dispatch_openai_stream(
            request,
            input_tokens=input_tokens,
            request_id=request_id,
            response_model=response_model or request.model,
            reasoning=reasoning,
            endpoint_context=endpoint_context,
            request_headers=request_headers,
            continuation=continuation,
        )

    async def _dispatch_openai_stream(
        self,
        request: OpenAIResponsesRequest | GeminiRequest | ChatRequest,
        *,
        input_tokens: int,
        request_id: str | None,
        response_model: str,
        reasoning: ReasoningPolicy,
        endpoint_context: EndpointContext | None = None,
        request_headers: Mapping[str, str] | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[StreamOutput]:
        snapshot = await self._catalog.snapshot(request_id=request_id)
        route = self._require_route(snapshot, request.model)
        routed = request.model_copy(
            update={"model": route.upstream_model_id}, deep=True
        )
        selected_stream: AsyncIterator[StreamOutput] | None = None
        try:
            if isinstance(routed, ChatRequest):
                transport = (
                    self._responses
                    if route.transport is OpenCodeUpstreamTransport.RESPONSES
                    else self._chat
                )
                selected_stream = transport.stream_chat(
                    routed,
                    input_tokens=input_tokens,
                    request_id=request_id,
                    response_model=response_model,
                    reasoning=reasoning,
                    endpoint_context=endpoint_context,
                    extra_headers=self._upstream_headers(request_headers or {}),
                    continuation=continuation,
                )
            elif isinstance(routed, GeminiRequest):
                transport = (
                    self._responses
                    if route.transport is OpenCodeUpstreamTransport.RESPONSES
                    else self._chat
                )
                selected_stream = transport.stream_gemini(
                    routed,
                    input_tokens=input_tokens,
                    request_id=request_id,
                    response_model=response_model,
                    reasoning=reasoning,
                    endpoint_context=endpoint_context,
                    extra_headers=self._upstream_headers(request_headers or {}),
                    continuation=continuation,
                )
            elif route.transport is OpenCodeUpstreamTransport.RESPONSES:
                selected_stream = self._responses.stream_responses(
                    routed,
                    input_tokens=input_tokens,
                    request_id=request_id,
                    response_model=response_model,
                    reasoning=reasoning,
                    endpoint_context=endpoint_context,
                    extra_headers=self._upstream_headers(request_headers or {}),
                    continuation=continuation,
                )
            else:
                selected_stream = self._chat.stream_responses(
                    routed,
                    input_tokens=input_tokens,
                    request_id=request_id,
                    response_model=response_model,
                    reasoning=reasoning,
                    endpoint_context=endpoint_context,
                    extra_headers=self._upstream_headers(request_headers or {}),
                    continuation=continuation,
                )
            async for event in selected_stream:
                yield event
        finally:
            if selected_stream is not None:
                await close_provider_stream(
                    selected_stream,
                    active_error=sys.exception(),
                    provider_name=self._opencode_profile.provider_name,
                    request_id=request_id,
                )

    def _require_route(
        self,
        snapshot: OpenCodeCatalogSnapshot,
        selector_id: str,
    ) -> OpenCodeModelRoute:
        route = snapshot.route(selector_id)
        if route is not None:
            return route
        raise InvalidRequestError(
            f"{self._opencode_profile.provider_name} does not advertise "
            f"model {selector_id!r} in its active catalog."
        )


def create_opencode_provider(
    provider_id: str,
    config: ProviderConfig,
    admission: ProviderAdmissionController,
    history_cache: HistoryModeCache | None = None,
    *,
    catalog_client: httpx.AsyncClient | None = None,
) -> OpenCodeProvider:
    """Construct one catalog-aware OpenCode provider."""
    profile = _PROFILES.get(provider_id)
    if profile is None:
        raise KeyError(f"No OpenCode profile for {provider_id!r}")
    return OpenCodeProvider(
        config,
        profile=profile,
        admission=admission,
        history_cache=history_cache,
        catalog_client=catalog_client,
    )


def _routed_messages_request(
    request: MessagesRequest,
    route: OpenCodeModelRoute,
) -> MessagesRequest:
    return request.model_copy(
        update={"model": route.upstream_model_id},
        deep=True,
    )