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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
from __future__ import annotations
"""Application workflow for supported local Anthropic web-tool requests."""

import asyncio
import uuid
from collections.abc import AsyncIterator, Mapping
from dataclasses import replace
from datetime import UTC, datetime
from urllib.parse import urlparse, urlsplit

from loguru import logger

from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.application.execution import ProviderExecutor, TokenCounter
from free_claude_code.application.response_collection import collect_response
from free_claude_code.application.routing import RoutedMessagesRequest
from free_claude_code.config.settings import Settings
from free_claude_code.core.anthropic import (
    aggregate_anthropic_sse_to_message,
    anthropic_status_for_error_type,
)
from free_claude_code.core.anthropic.server_tool_sse import (
    ServerToolResponseContext,
    server_tool_completion_frames,
    server_tool_finish_frames,
    server_tool_message_start_frames,
    server_tool_result_frames,
    server_tool_start_frames,
    server_tool_use_frames,
    web_fetch_result_block,
    web_search_result_block,
    web_tool_error_block,
)
from free_claude_code.core.failures import ExecutionFailure, FailureKind
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.stream_output import StreamOutput
from free_claude_code.core.trace import trace_event
from free_claude_code.core.web_tools import WebSearchResult

from .ports import (
    WebFetchEgressPolicy,
    WebFetchEgressViolation,
    WebToolsPort,
    web_fetch_allowed_scheme_set,
)
from .request import (
    HIDDEN_WEB_SEARCH_NAME,
    AutomaticWebSearchPlan,
    WebSearchDomainFilter,
    extract_query,
    extract_url,
    forced_server_tool_name,
    forced_tool_turn_text,
    plan_automatic_web_search,
    unsupported_server_tool_error,
)


class WebToolService:
    """Coordinate one tool request using the originating settings and executor."""

    def __init__(
        self,
        *,
        settings: Settings,
        client: WebToolsPort,
        executor: ProviderExecutor,
        token_counter: TokenCounter,
    ) -> None:
        self._client = client
        self._executor = executor
        self._token_counter = token_counter
        self._enabled = settings.enable_web_server_tools
        self._verbose_client_errors = settings.log_api_error_tracebacks
        self._egress = WebFetchEgressPolicy(
            allow_private_network_targets=settings.web_fetch_allow_private_networks,
            allowed_schemes=web_fetch_allowed_scheme_set(
                settings.web_fetch_allowed_schemes
            ),
        )

    def try_stream_messages(
        self, routed: RoutedMessagesRequest, *, request_id: str
    ) -> AsyncIterator[StreamOutput] | None:
        """Validate synchronously; return a lazy body only for handled requests."""
        request = routed.request
        plan = plan_automatic_web_search(request, web_tools_enabled=self._enabled)
        if plan is None:
            error = unsupported_server_tool_error(
                request, web_tools_enabled=self._enabled
            )
            if error is not None:
                raise InvalidRequestError(error)
        tool_name = forced_server_tool_name(request)
        if plan is None and tool_name is None:
            return None
        input_tokens = self._token_counter(
            request.messages, request.system, request.tools
        )
        if plan is not None:
            return self._stream_automatic_search(
                routed, plan, request_id=request_id, fallback_input_tokens=input_tokens
            )
        assert tool_name is not None
        trace_event(
            stage="routing",
            event="free_claude_code.api.optimization.web_server_tool",
            source="api",
            model=routed.resolved.original_model,
        )
        text = forced_tool_turn_text(request)
        tool_input = (
            {"query": extract_query(text)}
            if tool_name == "web_search"
            else {"url": extract_url(text)}
        )
        return self._stream_local_tool(
            tool_name=tool_name,
            tool_input=tool_input,
            input_tokens=input_tokens,
            response_model=routed.resolved.original_model,
        )

    async def _stream_automatic_search(
        self,
        routed: RoutedMessagesRequest,
        plan: AutomaticWebSearchPlan,
        *,
        request_id: str,
        fallback_input_tokens: int,
    ) -> AsyncIterator[StreamOutput]:
        """Keep one provider decision private, then replay it or execute search."""
        translated = replace(routed, request=plan.request)
        trace_event(
            stage="routing",
            event="free_claude_code.api.web_search.automatic_recognized",
            source="api",
            request_id=request_id,
            model=routed.resolved.original_model,
        )
        provider_stream = self._executor.stream_messages(
            translated,
            raw_log_payload=plan.request.model_dump,
            request_id=request_id,
        )
        chunks = await collect_response(provider_stream, protocol="messages")

        message, stream_error, _complete = await aggregate_anthropic_sse_to_message(
            _iterate_chunks(chunks)
        )
        if stream_error is not None:
            raise _execution_failure_from_stream_error(stream_error)
        tool_calls = _tool_calls(message)
        if not tool_calls:
            trace_event(
                stage="execution",
                event="free_claude_code.api.web_search.automatic_declined",
                source="api",
                request_id=request_id,
                model=routed.resolved.original_model,
            )
            for chunk in chunks:
                yield StreamOutput((chunk,))
            return
        queries: list[str] = []
        for call in tool_calls:
            if call.get("name") != HIDDEN_WEB_SEARCH_NAME:
                raise _protocol_failure(
                    "Upstream model returned an unexpected tool for automatic WebSearch.",
                    request_id=request_id,
                )
            arguments = call.get("input")
            if not isinstance(arguments, dict) or set(arguments) != {"query"}:
                raise _protocol_failure(
                    "Upstream model returned malformed arguments for automatic WebSearch.",
                    request_id=request_id,
                )
            raw_query = arguments.get("query")
            if not isinstance(raw_query, str) or not raw_query.strip():
                raise _protocol_failure(
                    "Upstream model returned an empty query for automatic WebSearch.",
                    request_id=request_id,
                )
            queries.append(raw_query.strip())
        provider_usage = _provider_usage(message)
        input_tokens = _integer_field(provider_usage, "input_tokens")
        if input_tokens is None:
            input_tokens = fallback_input_tokens

        trace_event(
            stage="execution",
            event="free_claude_code.api.web_search.automatic_selected",
            source="api",
            request_id=request_id,
            model=routed.resolved.original_model,
        )
        message_id = f"msg_{uuid.uuid4()}"
        contexts = [
            ServerToolResponseContext(
                message_id=message_id,
                tool_id=f"srvtoolu_{uuid.uuid4().hex}",
                model=routed.resolved.original_model,
                tool_name="web_search",
                tool_input={"query": query},
                input_tokens=input_tokens,
                provider_usage=provider_usage,
            )
            for query in queries
        ]
        executed = min(len(contexts), plan.max_uses or len(contexts))
        for frame in server_tool_message_start_frames(contexts[0]):
            yield StreamOutput((frame,))

        limit = asyncio.Semaphore(4)

        async def search_one(
            context: ServerToolResponseContext,
        ) -> tuple[JsonObject, str]:
            async with limit:
                return await self._search_result(context, plan.domains)

        summaries: list[str] = []
        async with asyncio.TaskGroup() as group:
            tasks = [
                group.create_task(search_one(context))
                for context in contexts[:executed]
            ]
            for index, context in enumerate(contexts):
                for frame in server_tool_use_frames(context, index=index * 2):
                    yield StreamOutput((frame,))
                if index < executed:
                    result_block, summary = await tasks[index]
                else:
                    result_block = web_tool_error_block(
                        context, error_code="max_uses_exceeded"
                    )
                    summary = (
                        f"Web search limit reached for: {context.tool_input['query']}"
                    )
                for frame in server_tool_result_frames(
                    result_block, index=index * 2 + 1
                ):
                    yield StreamOutput((frame,))
                summaries.append(summary)

        for frame in server_tool_finish_frames(
            contexts[0],
            summary="\n\n".join(summaries),
            index=len(contexts) * 2,
            request_count=executed,
        ):
            yield StreamOutput((frame,))
        trace_event(
            stage="execution",
            event="free_claude_code.api.web_search.automatic_completed",
            source="api",
            request_id=request_id,
            model=routed.resolved.original_model,
        )

    async def _stream_local_tool(
        self,
        *,
        tool_name: str,
        tool_input: dict[str, str],
        input_tokens: int,
        response_model: str,
        provider_usage: Mapping[str, object] | None = None,
        domains: WebSearchDomainFilter | None = None,
    ) -> AsyncIterator[StreamOutput]:
        context = ServerToolResponseContext(
            message_id=f"msg_{uuid.uuid4()}",
            tool_id=f"srvtoolu_{uuid.uuid4().hex}",
            model=response_model,
            tool_name=tool_name,
            tool_input=tool_input,
            input_tokens=input_tokens,
            provider_usage=provider_usage,
        )
        for frame in server_tool_start_frames(context):
            yield StreamOutput((frame,))

        if tool_name == "web_search":
            result_block, summary = await self._search_result(context, domains)
        else:
            try:
                fetched = await self._client.fetch(
                    tool_input["url"], egress=self._egress
                )
                result_block = web_fetch_result_block(
                    context, fetched, retrieved_at=datetime.now(UTC).isoformat()
                )
                summary = fetched.data
            except Exception as error:
                _log_web_tool_failure(tool_name, error, fetch_url=tool_input["url"])
                result_block = web_tool_error_block(context)
                summary = _web_tool_client_error_summary(
                    tool_name, error, verbose=self._verbose_client_errors
                )

        for frame in server_tool_completion_frames(
            context, result_block, summary=summary
        ):
            yield StreamOutput((frame,))

    async def _search_result(
        self,
        context: ServerToolResponseContext,
        domains: WebSearchDomainFilter | None,
    ) -> tuple[JsonObject, str]:
        query = context.tool_input["query"]
        try:
            results = await self._client.search(query)
            if domains is not None:
                results = _filter_results(results, domains)
            return web_search_result_block(context, results), _search_summary(
                query, results
            )
        except Exception as error:
            _log_web_tool_failure("web_search", error, fetch_url=None)
            return web_tool_error_block(context), _web_tool_client_error_summary(
                "web_search", error, verbose=self._verbose_client_errors
            )


def _search_summary(query: str, results: list[WebSearchResult]) -> str:
    if not results:
        return f"No web search results found for: {query}"
    lines = [f"Search results for: {query}"]
    for index, result in enumerate(results, start=1):
        lines.append(f"{index}. {result.title}\n{result.url}")
    return "\n\n".join(lines)


async def _iterate_chunks(chunks: tuple[str, ...]) -> AsyncIterator[str]:
    for chunk in chunks:
        yield chunk


def _tool_calls(message: Mapping[str, object]) -> list[dict[str, object]]:
    content = message.get("content")
    if not isinstance(content, list):
        return []
    calls: list[dict[str, object]] = []
    for block in content:
        if not isinstance(block, dict) or block.get("type") != "tool_use":
            continue
        calls.append({str(key): value for key, value in block.items()})
    return calls


def _provider_usage(message: Mapping[str, object]) -> dict[str, object]:
    usage = message.get("usage")
    if not isinstance(usage, dict):
        return {}
    return {str(key): value for key, value in usage.items()}


def _integer_field(values: Mapping[str, object], key: str) -> int | None:
    value = values.get(key)
    return value if isinstance(value, int) and not isinstance(value, bool) else None


def _filter_results(
    results: list[WebSearchResult],
    domains: WebSearchDomainFilter,
) -> list[WebSearchResult]:
    if not domains.allowed and not domains.blocked:
        return results
    return [result for result in results if _hostname_is_allowed(result.url, domains)]


def _hostname_is_allowed(url: str, domains: WebSearchDomainFilter) -> bool:
    hostname = urlsplit(url).hostname
    if hostname is None:
        return False
    try:
        normalized = hostname.encode("idna").decode("ascii").lower()
    except UnicodeError:
        return False
    if domains.allowed and not any(
        _is_hostname_or_subdomain(normalized, domain) for domain in domains.allowed
    ):
        return False
    return not any(
        _is_hostname_or_subdomain(normalized, domain) for domain in domains.blocked
    )


def _is_hostname_or_subdomain(hostname: str, domain: str) -> bool:
    return hostname == domain or hostname.endswith(f".{domain}")


def _execution_failure_from_stream_error(
    error: Mapping[str, object],
) -> ExecutionFailure:
    raw_type = error.get("type")
    error_type = raw_type if isinstance(raw_type, str) else "api_error"
    raw_message = error.get("message")
    message = (
        raw_message
        if isinstance(raw_message, str) and raw_message.strip()
        else "Provider request failed unexpectedly."
    )
    status = anthropic_status_for_error_type(error_type)
    kind = {
        400: FailureKind.INVALID_REQUEST,
        401: FailureKind.AUTHENTICATION,
        402: FailureKind.PERMISSION,
        403: FailureKind.PERMISSION,
        404: FailureKind.INVALID_REQUEST,
        413: FailureKind.INVALID_REQUEST,
        429: FailureKind.RATE_LIMIT,
        504: FailureKind.TIMEOUT,
        529: FailureKind.OVERLOADED,
    }.get(status, FailureKind.UPSTREAM)
    return ExecutionFailure(
        kind=kind,
        status_code=status,
        message=message,
        retryable=False,
    )


def _protocol_failure(message: str, *, request_id: str) -> ExecutionFailure:
    return ExecutionFailure(
        kind=FailureKind.UPSTREAM,
        status_code=500,
        message=f"{message}\n\nRequest ID: {request_id}",
        retryable=False,
    )


def _safe_public_host_for_logs(url: str) -> str:
    host = urlparse(url).hostname or ""
    return host[:253]


def _log_web_tool_failure(
    tool_name: str,
    error: BaseException,
    *,
    fetch_url: str | None = None,
) -> None:
    exc_type = type(error).__name__
    if isinstance(error, WebFetchEgressViolation):
        host = _safe_public_host_for_logs(fetch_url) if fetch_url else ""
        logger.warning(
            "web_tool_egress_rejected tool={} exc_type={} host={!r}",
            tool_name,
            exc_type,
            host,
        )
        return
    if tool_name == "web_fetch" and fetch_url:
        logger.warning(
            "web_tool_failure tool={} exc_type={} host={!r}",
            tool_name,
            exc_type,
            _safe_public_host_for_logs(fetch_url),
        )
    else:
        logger.warning("web_tool_failure tool={} exc_type={}", tool_name, exc_type)


def _web_tool_client_error_summary(
    tool_name: str,
    error: BaseException,
    *,
    verbose: bool,
) -> str:
    if verbose:
        return f"{tool_name} failed: {type(error).__name__}"
    return "Web tool request failed."