File size: 12,730 Bytes
9f6a4bd
e99df76
691dc7c
 
3934d27
 
261c237
3934d27
2415446
691dc7c
 
 
 
 
 
2415446
3934d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
3934d27
2415446
 
3934d27
2415446
 
 
 
 
 
 
 
 
 
3934d27
 
 
2415446
3934d27
 
2415446
3934d27
 
 
 
 
2415446
 
 
 
 
 
 
 
3934d27
 
2415446
 
 
3934d27
 
 
2415446
 
 
3934d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
3934d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
 
 
3934d27
 
 
 
 
691dc7c
3934d27
2415446
 
 
 
 
3934d27
2415446
 
 
3934d27
 
 
2415446
 
 
3934d27
 
 
2415446
 
3934d27
 
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3934d27
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3934d27
 
691dc7c
3934d27
691dc7c
3934d27
 
691dc7c
3934d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
"""Recognize the narrow Anthropic web-tool requests FCC can execute locally."""

import json
import re
from dataclasses import dataclass

from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.core.anthropic import MessagesRequest, Tool
from free_claude_code.core.anthropic.models import (
    ContentBlockServerToolUse,
    ContentBlockText,
    ContentBlockWebSearchToolResult,
    Message,
)

WEB_SEARCH_TYPE = "web_search_20250305"
WEB_FETCH_TYPE = "web_fetch_20250910"
HIDDEN_WEB_SEARCH_NAME = "fcc_web_search"

_SERVER_TOOL_TYPES = {
    "web_search": WEB_SEARCH_TYPE,
    "web_fetch": WEB_FETCH_TYPE,
}
_SERVER_TOOL_PREFIXES = ("web_search_", "web_fetch_")
_SERVER_HISTORY_TYPES = {
    "server_tool_use",
    "web_search_tool_result",
    "web_fetch_tool_result",
}
_WEB_SEARCH_OPTION_FIELDS = {"max_uses", "allowed_domains", "blocked_domains"}
_DOMAIN_PATTERN = re.compile(
    r"(?=.{1,253}\Z)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*"
    r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
)


@dataclass(frozen=True, slots=True)
class WebSearchDomainFilter:
    """Literal hostname constraints supplied by Claude Code."""

    allowed: tuple[str, ...] = ()
    blocked: tuple[str, ...] = ()


@dataclass(frozen=True, slots=True)
class AutomaticWebSearchPlan:
    """One exact Claude Code automatic-search request translated for a provider."""

    request: MessagesRequest
    domains: WebSearchDomainFilter
    max_uses: int | None


def forced_tool_turn_text(request: MessagesRequest) -> str:
    """Text for parsing forced server-tool inputs: latest user turn only."""
    if not request.messages:
        return ""

    for message in reversed(request.messages):
        if message.role == "user":
            return content_text(message.content)
    return ""


def forced_server_tool_name(request: MessagesRequest) -> str | None:
    """Return a forced supported server tool, never an ordinary same-name function."""
    choice = request.tool_choice
    if not isinstance(choice, dict) or choice.get("type") != "tool":
        return None
    name = choice.get("name")
    if not isinstance(name, str) or name not in _SERVER_TOOL_TYPES:
        return None
    expected_type = _SERVER_TOOL_TYPES[name]
    if any(
        tool.name == name and tool.type == expected_type for tool in request.tools or []
    ):
        return name
    return None


def has_tool_named(request: MessagesRequest, name: str) -> bool:
    return any(tool.name == name for tool in request.tools or [])


def is_web_server_tool_request(request: MessagesRequest) -> bool:
    """True only when the client forces one supported Anthropic server tool."""
    return forced_server_tool_name(request) is not None


def is_anthropic_server_tool_definition(tool: Tool) -> bool:
    """Whether ``tool.type`` identifies an Anthropic web server-tool family."""
    tool_type = tool.type
    return isinstance(tool_type, str) and tool_type.startswith(_SERVER_TOOL_PREFIXES)


def has_listed_anthropic_server_tools(request: MessagesRequest) -> bool:
    """True when tools include a typed Anthropic web server-tool definition."""
    return any(
        is_anthropic_server_tool_definition(tool) for tool in request.tools or []
    )


def plan_automatic_web_search(
    request: MessagesRequest,
    *,
    web_tools_enabled: bool,
) -> AutomaticWebSearchPlan | None:
    """Translate only Claude Code's server-tool-only automatic WebSearch request."""
    choice = request.tool_choice
    if choice is not None and choice != {"type": "auto"}:
        return None

    tools = request.tools or []
    server_tools = [tool for tool in tools if is_anthropic_server_tool_definition(tool)]
    if not server_tools:
        return None
    if len(tools) != 1 or len(server_tools) != 1:
        return None

    tool = server_tools[0]
    if tool.type != WEB_SEARCH_TYPE:
        return None
    if not web_tools_enabled:
        raise InvalidRequestError(
            "Anthropic web_search is disabled (ENABLE_WEB_SERVER_TOOLS=false). "
            "Enable local web tools or remove web_search from the request."
        )
    if tool.name != "web_search":
        raise InvalidRequestError(
            f"Server tool type {WEB_SEARCH_TYPE!r} must use name 'web_search'."
        )
    if tool.description is not None or tool.input_schema is not None:
        raise InvalidRequestError(
            "Anthropic web_search must not define description or input_schema."
        )

    options = tool.model_extra or {}
    unsupported = sorted(set(options) - _WEB_SEARCH_OPTION_FIELDS)
    if unsupported:
        raise InvalidRequestError(
            "Anthropic web_search contains unsupported option(s): "
            + ", ".join(unsupported)
            + "."
        )
    max_uses = _validate_max_uses(options.get("max_uses"))
    allowed = _parse_domains(
        options.get("allowed_domains"), field="web_search.allowed_domains"
    )
    blocked = _parse_domains(
        options.get("blocked_domains"), field="web_search.blocked_domains"
    )
    if allowed and blocked:
        raise InvalidRequestError(
            "web_search may define allowed_domains or blocked_domains, not both."
        )

    hidden_tool = Tool(
        name=HIDDEN_WEB_SEARCH_NAME,
        description="Search the public web for current information.",
        input_schema={
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"],
            "additionalProperties": False,
        },
    )
    translated = request.model_copy(
        update={
            "tools": [hidden_tool],
            "messages": _normalized_search_history(request.messages),
        },
        deep=True,
    )
    return AutomaticWebSearchPlan(
        request=translated,
        domains=WebSearchDomainFilter(allowed=allowed, blocked=blocked),
        max_uses=max_uses,
    )


def unsupported_server_tool_error(
    request: MessagesRequest, *, web_tools_enabled: bool
) -> str | None:
    """Return the user-facing error for a server-tool shape FCC does not handle."""
    forced = forced_server_tool_name(request)
    if forced and not web_tools_enabled:
        return (
            f"tool_choice forces Anthropic server tool {forced!r}, but local web "
            "server tools are disabled (ENABLE_WEB_SERVER_TOOLS=false). Enable "
            "them or remove the forced server tool."
        )
    if not forced and has_listed_anthropic_server_tools(request):
        return (
            "FCC supports automatic Anthropic web_search only for Claude Code's "
            f"{WEB_SEARCH_TYPE} server-tool-only request. Automatic web_fetch, "
            "mixed tools, and other server-tool choices are not supported."
        )
    return None


_INCOMPLETE_HISTORY = (
    "Automatic web_search does not accept incomplete or unsupported prior "
    "Anthropic server-tool history."
)


def _normalized_search_history(messages: list[Message]) -> list[Message]:
    """Quote completed local search data for every upstream transport."""
    normalized: list[Message] = []
    for message in messages:
        content = message.content
        if not isinstance(content, list) or not any(
            getattr(block, "type", None) in _SERVER_HISTORY_TYPES for block in content
        ):
            normalized.append(message)
            continue
        if message.role != "assistant":
            raise InvalidRequestError(_INCOMPLETE_HISTORY)

        uses: dict[str, ContentBlockServerToolUse] = {}
        results: dict[str, ContentBlockWebSearchToolResult] = {}
        for block in content:
            if isinstance(block, ContentBlockServerToolUse):
                query = block.input.get("query")
                if (
                    block.name != "web_search"
                    or not block.id
                    or block.id in uses
                    or set(block.input) != {"query"}
                    or not isinstance(query, str)
                    or not query.strip()
                ):
                    raise InvalidRequestError(_INCOMPLETE_HISTORY)
                uses[block.id] = block
            elif isinstance(block, ContentBlockWebSearchToolResult):
                if not block.tool_use_id or block.tool_use_id in results:
                    raise InvalidRequestError(_INCOMPLETE_HISTORY)
                results[block.tool_use_id] = block
            elif getattr(block, "type", None) in _SERVER_HISTORY_TYPES:
                raise InvalidRequestError(_INCOMPLETE_HISTORY)
        if not uses or uses.keys() != results.keys():
            raise InvalidRequestError(_INCOMPLETE_HISTORY)

        projected = []
        for block in content:
            if isinstance(block, ContentBlockServerToolUse):
                projected.append(_search_history_text(block, results[block.id]))
            elif not isinstance(block, ContentBlockWebSearchToolResult):
                projected.append(block)
        normalized.append(message.model_copy(update={"content": projected}, deep=True))
    return normalized


def _search_history_text(
    use: ContentBlockServerToolUse, result: ContentBlockWebSearchToolResult
) -> ContentBlockText:
    content = result.content
    if isinstance(content, list):
        hits: list[dict[str, str]] = []
        for hit in content:
            if (
                not isinstance(hit, dict)
                or hit.get("type") != "web_search_result"
                or not isinstance(hit.get("title"), str)
                or not isinstance(hit.get("url"), str)
            ):
                raise InvalidRequestError(_INCOMPLETE_HISTORY)
            hits.append({"title": hit["title"], "url": hit["url"]})
        record: dict[str, object] = {"query": use.input["query"], "results": hits}
    elif (
        isinstance(content, dict)
        and content.get("type") == "web_search_tool_result_error"
        and isinstance(content.get("error_code"), str)
    ):
        record = {"query": use.input["query"], "error_code": content["error_code"]}
    else:
        raise InvalidRequestError(_INCOMPLETE_HISTORY)
    return ContentBlockText(
        type="text",
        text="[Earlier web search data]\n"
        + json.dumps(record, ensure_ascii=False, separators=(",", ":")),
    )


def _validate_max_uses(value: object) -> int | None:
    if value is None:
        return None
    if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
        raise InvalidRequestError("web_search.max_uses must be a positive integer.")
    return value


def _parse_domains(value: object, *, field: str) -> tuple[str, ...]:
    if value is None:
        return ()
    if not isinstance(value, list):
        raise InvalidRequestError(f"{field} must be a list of literal hostnames.")

    domains: list[str] = []
    for entry in value:
        if not isinstance(entry, str) or not entry or entry != entry.strip():
            raise InvalidRequestError(f"{field} entries must be non-empty hostnames.")
        if any(character in entry for character in ":/\\?#@*"):
            raise InvalidRequestError(
                f"{field} entry {entry!r} must be a literal hostname without a "
                "scheme, port, path, query, fragment, user info, or wildcard."
            )
        try:
            domain = entry.encode("idna").decode("ascii").lower()
        except UnicodeError as exc:
            raise InvalidRequestError(
                f"{field} entry {entry!r} is not a valid hostname."
            ) from exc
        if _DOMAIN_PATTERN.fullmatch(domain) is None:
            raise InvalidRequestError(
                f"{field} entry {entry!r} is not a valid hostname."
            )
        domains.append(domain)

    if len(domains) != len(set(domains)):
        raise InvalidRequestError(f"{field} must not contain duplicate hostnames.")
    return tuple(domains)


def content_text(content: object) -> str:
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        parts = []
        for item in content:
            if isinstance(item, dict):
                parts.append(str(item.get("text", "")))
            else:
                parts.append(str(getattr(item, "text", "")))
        return "\n".join(part for part in parts if part)
    return str(content)


def extract_query(text: str) -> str:
    match = re.search(r"query:\s*(.+)", text, flags=re.IGNORECASE | re.DOTALL)
    if match:
        return match.group(1).strip().strip("\"'")
    return text.strip()


def extract_url(text: str) -> str:
    match = re.search(r"https?://\S+", text)
    return match.group(0).rstrip(").,]") if match else text.strip()