File size: 7,694 Bytes
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7b8ca
e99df76
 
 
 
 
 
 
 
 
 
2e7b8ca
 
 
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
"""Withhold incomplete client tool calls at the public SSE delivery boundary."""

from collections.abc import Mapping
from typing import Literal, cast

from free_claude_code.core.anthropic.stream_contracts import parse_sse_text
from free_claude_code.core.json_types import JsonValue
from free_claude_code.core.openai_responses import is_client_search

from .stream_frames import frame_data, replace_frame_data

type CallKey = int | str

_UNFINISHED = frozenset({"in_progress", "incomplete", "failed"})
_FAILURES = frozenset({"error", "response.error", "response.failed"})
_RESPONSES_TERMINALS = frozenset({"response.completed", "response.incomplete"})
_ARGUMENT_EVENTS = frozenset(
    {
        "response.function_call_arguments.delta",
        "response.function_call_arguments.done",
        "response.custom_tool_call_input.delta",
        "response.custom_tool_call_input.done",
    }
)


def _client_call(item: Mapping[str, object]) -> bool:
    kind = item.get("type")
    if kind in {
        "function_call",
        "custom_tool_call",
        "computer_call",
        "local_shell_call",
        "apply_patch_call",
    }:
        return True
    if kind == "tool_search_call":
        return is_client_search(cast(Mapping[str, JsonValue], item))
    environment = item.get("environment")
    return (
        kind == "shell_call"
        and isinstance(environment, Mapping)
        and environment.get("type") == "local"
    )


class ToolCallBuffer:
    """Select complete groups in source order, without owning public delivery."""

    def __init__(self, wire_api: Literal["messages", "responses", "gemini"]) -> None:
        self._wire_api = wire_api
        self._frames: list[str] = []
        self._calls: set[CallKey] = set()
        self._pending: set[CallKey] = set()
        self._delivered: set[CallKey] = set()
        self._discarded: set[CallKey] = set()
        self._ids: dict[str, CallKey] = {}
        self._indices: dict[int, CallKey] = {}

    def feed(self, frame: str) -> list[str]:
        if self._wire_api == "gemini":
            # Gemini presenters release only complete, object-valued calls.
            return [frame]
        events = parse_sse_text(frame)
        if not events:
            return self._publish(frame)
        event = events[0]
        data = cast(Mapping[str, object], event.data)
        kind = event.event or data.get("type")
        if kind in _FAILURES:
            self._discard_group()
            return [self._filter_snapshot(frame, failed=True)]
        if self._wire_api == "messages":
            index = data.get("index")
            block = data.get("content_block")
            if isinstance(index, int) and not isinstance(index, bool):
                if (
                    kind == "content_block_start"
                    and isinstance(block, Mapping)
                    and block.get("type") == "tool_use"
                ):
                    self._begin_call(index)
                elif kind == "content_block_stop":
                    self._pending.discard(index)
            if kind == "message_stop" and self._pending:
                self._discard_group()
        else:
            item = data.get("item")
            item = item if isinstance(item, Mapping) else {}
            if _client_call(item) or kind in _ARGUMENT_EVENTS:
                key = self._key(data, item)
                if key is not None:
                    if kind == "response.output_item.done":
                        self._calls.add(key)
                        if item.get("status") in _UNFINISHED:
                            self._pending.add(key)
                        else:
                            self._pending.discard(key)
                    else:
                        self._begin_call(key)
            if kind in _RESPONSES_TERMINALS:
                response = data.get("response")
                output = (
                    response.get("output") if isinstance(response, Mapping) else None
                )
                if isinstance(response, Mapping) and isinstance(output, list):
                    for value in output:
                        if isinstance(value, Mapping) and _client_call(value):
                            key = self._key({}, value)
                            if not self._withheld_item(value, response.get("status")):
                                self._pending.discard(key)
                if self._pending:
                    self._discard_group()
            if isinstance(data.get("response"), Mapping):
                frame = self._filter_snapshot(frame)
        return self._publish(frame)

    def _begin_call(self, key: CallKey) -> None:
        if key not in self._calls:
            self._calls.add(key)
            self._pending.add(key)

    def _key(
        self, data: Mapping[str, object], item: Mapping[str, object]
    ) -> CallKey | None:
        ids = [
            value
            for value in (data.get("item_id"), item.get("id"), item.get("call_id"))
            if isinstance(value, str) and value
        ]
        index = data.get("output_index")
        index = (
            index if isinstance(index, int) and not isinstance(index, bool) else None
        )
        key = next((self._ids[value] for value in ids if value in self._ids), None)
        if key is None and index is not None:
            key = self._indices.get(index, index)
        if key is None and ids:
            key = ids[0]
        if key is not None:
            for value in ids:
                self._ids[value] = key
            if index is not None:
                self._indices[index] = key
        return key

    def _publish(self, frame: str) -> list[str]:
        if not self._calls:
            return [frame]
        self._frames.append(frame)
        if self._pending:
            return []
        frames, self._frames = self._frames, []
        self._delivered.update(self._calls)
        self._calls.clear()
        return frames

    def _discard_group(self) -> None:
        self._discarded.update(self._calls)
        self._frames.clear()
        self._calls.clear()
        self._pending.clear()

    def _filter_snapshot(self, frame: str, *, failed: bool = False) -> str:
        # Parse only frames we may edit using decimal-aware JSON; all other
        # payloads, including argument strings and SSE framing, stay verbatim.
        value = frame_data(frame)
        if value is None:
            return frame
        response = value.get("response")
        if not isinstance(response, dict):
            return frame
        output = response.get("output")
        if not isinstance(output, list):
            return frame
        retained = [
            item
            for item in output
            if not (
                isinstance(item, Mapping)
                and _client_call(item)
                and self._withheld_item(item, response.get("status"), failed=failed)
            )
        ]
        if len(retained) == len(output):
            return frame
        response["output"] = retained
        return replace_frame_data(frame, value)

    def _withheld_item(
        self,
        item: Mapping[str, object],
        response_status: object,
        *,
        failed: bool = False,
    ) -> bool:
        key = self._key({}, item)
        status = item.get("status")
        return (
            key in self._discarded
            or status in _UNFINISHED
            or (failed and key not in self._delivered)
            or (
                status is None
                and response_status != "completed"
                and key not in self._delivered
            )
        )