File size: 4,631 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
"""Application web-tool behavior through its explicit outbound capability."""

import asyncio
from collections.abc import AsyncIterator

import pytest

from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.application.execution import ProviderExecutor
from free_claude_code.application.routing import ModelRouter
from free_claude_code.application.web_tools.ports import WebFetchEgressPolicy
from free_claude_code.application.web_tools.service import WebToolService
from free_claude_code.config.settings import Settings
from free_claude_code.core.anthropic.models import Message, MessagesRequest, Tool
from free_claude_code.core.stream_output import StreamOutput
from free_claude_code.core.web_tools import WebFetchResult
from tests.web_tools_support import StubWebToolsClient


async def _no_provider(_provider_id, _api_key_number):
    pytest.fail("This request must not resolve a provider")


def _service(settings, client, *, token_counter=lambda *_: 5):
    return WebToolService(
        settings=settings,
        client=client,
        executor=ProviderExecutor(_no_provider),
        token_counter=token_counter,
    )


def _request(tool, *, typed=True):
    return MessagesRequest(
        model="claude-sonnet",
        messages=[Message(role="user", content="https://example.com/")],
        tools=[
            Tool(
                name=tool,
                type=(
                    "web_fetch_20250910"
                    if tool == "web_fetch"
                    else "web_search_20250305"
                )
                if typed
                else None,
            )
        ],
        tool_choice={"type": "tool", "name": tool},
    )


async def _drain(body: AsyncIterator[StreamOutput]) -> str:
    return "".join([frame async for packet in body for frame in packet.frames])


def test_ordinary_client_tool_needs_no_web_or_token_work():
    settings = Settings()
    service = _service(
        settings,
        StubWebToolsClient(),
        token_counter=lambda *_: pytest.fail("Unhandled request counted tokens"),
    )
    routed = ModelRouter(settings).resolve_messages_request(
        _request("web_search", typed=False)
    )
    assert service.try_stream_messages(routed, request_id="req_unhandled") is None


def test_disabled_tool_fails_during_preparation():
    settings = Settings().model_copy(update={"enable_web_server_tools": False})
    service = _service(settings, StubWebToolsClient())
    routed = ModelRouter(settings).resolve_messages_request(_request("web_fetch"))
    with pytest.raises(InvalidRequestError, match="disabled"):
        service.try_stream_messages(routed, request_id="req_disabled")


@pytest.mark.asyncio
async def test_concurrent_requests_keep_their_own_egress_policy():
    entered, release = asyncio.Event(), asyncio.Event()

    class Client(StubWebToolsClient):
        def __init__(self):
            self.policies = []

        async def fetch(
            self, url: str, *, egress: WebFetchEgressPolicy
        ) -> WebFetchResult:
            self.policies.append(egress)
            if len(self.policies) == 2:
                entered.set()
            await release.wait()
            return WebFetchResult(
                url=url, title="page", media_type="text/plain", data="text"
            )

    client = Client()
    settings = [
        Settings().model_copy(
            update={
                "web_fetch_allow_private_networks": False,
                "web_fetch_allowed_schemes": "https",
            }
        ),
        Settings().model_copy(
            update={
                "web_fetch_allow_private_networks": True,
                "web_fetch_allowed_schemes": "http, https",
            }
        ),
    ]
    tasks = []
    try:
        for index, snapshot in enumerate(settings):
            service = _service(snapshot, client)
            body = service.try_stream_messages(
                ModelRouter(snapshot).resolve_messages_request(_request("web_fetch")),
                request_id=f"req_{index}",
            )
            assert body is not None
            tasks.append(asyncio.create_task(_drain(body)))
        await asyncio.wait_for(entered.wait(), 1)
        assert client.policies == [
            WebFetchEgressPolicy(False, frozenset({"https"})),
            WebFetchEgressPolicy(True, frozenset({"http", "https"})),
        ]
        release.set()
        outputs = await asyncio.gather(*tasks)
        assert all("web_fetch_tool_result" in output for output in outputs)
    finally:
        release.set()
        await asyncio.gather(*tasks, return_exceptions=True)