tokensafe 4.6.4 → 4.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +2 -2
- package/LICENSE +202 -21
- package/README.md +30 -4
- package/hooks/claude_code_hook.py +17 -15
- package/hooks/kimi_hook.py +14 -12
- package/hooks/pre_invocation.py +7 -12
- package/hooks/session_start.py +8 -2
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/src/acp/__init__.py +15 -0
- package/src/acp/server.py +328 -0
- package/src/adapter_core.py +2 -1
- package/src/agent/__init__.py +11 -0
- package/src/agent/context.py +99 -0
- package/src/agent/loop.py +385 -0
- package/src/agent/pricing.py +77 -0
- package/src/agent/providers.py +486 -0
- package/src/agent/tools.py +98 -0
- package/src/agent_firewall.py +16 -1
- package/src/auto_inject.py +93 -7
- package/src/batch_editor.py +106 -15
- package/src/bench/__init__.py +1 -0
- package/src/bench/driver.py +234 -0
- package/src/bench/go_target.py +646 -0
- package/src/bench/mechanics.py +214 -0
- package/src/bench/react_target.py +541 -0
- package/src/bench/runner.py +331 -0
- package/src/bench/tokensafe_mcp.py +144 -0
- package/src/cli.py +156 -0
- package/src/history_compactor.py +200 -2
- package/src/installer.py +3 -3
- package/src/mcp_server.py +510 -237
- package/src/paths.py +41 -2
- package/src/retrofit.py +27 -5
- package/src/scaffold.py +8 -6
- package/src/scoped_search.py +67 -5
- package/src/session_brief.py +180 -15
- package/src/session_context.py +124 -0
- package/src/skeletonizer.py +9 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
"""Streaming model providers for the agent loop.
|
|
2
|
+
|
|
3
|
+
Two wire formats cover every backend TokenSafe needs: OpenAI-compatible
|
|
4
|
+
``/chat/completions`` (DeepSeek, OpenAI, Ollama, LM Studio, OpenRouter) and
|
|
5
|
+
Anthropic ``/v1/messages``. Both are parsed into one event stream, so the loop
|
|
6
|
+
never branches on provider and the UI gets the same deltas either way.
|
|
7
|
+
|
|
8
|
+
The hard part of streaming is not the HTTP call, it is reassembly: tool-call
|
|
9
|
+
arguments arrive as JSON fragments across chunks (OpenAI) or as
|
|
10
|
+
``input_json_delta`` pieces inside a content block (Anthropic). That logic
|
|
11
|
+
lives here, next to the wire format that defines it, and is covered by tests
|
|
12
|
+
with canned SSE fixtures.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import threading
|
|
20
|
+
import urllib.error
|
|
21
|
+
import urllib.request
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
24
|
+
|
|
25
|
+
from src.agent.pricing import usd as price_usd
|
|
26
|
+
from src.json_repair import parse_tool_arguments
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ProviderError(RuntimeError):
|
|
30
|
+
"""Configuration or transport failure the caller should surface verbatim."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class ToolCall:
|
|
35
|
+
id: str
|
|
36
|
+
name: str
|
|
37
|
+
arguments: Dict[str, Any] = field(default_factory=dict)
|
|
38
|
+
raw_arguments: str = ""
|
|
39
|
+
parse_error: str = ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Usage:
|
|
44
|
+
input_tokens: int = 0
|
|
45
|
+
output_tokens: int = 0
|
|
46
|
+
cache_hit_tokens: int = 0
|
|
47
|
+
calls: int = 0
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def cache_miss_tokens(self) -> int:
|
|
51
|
+
return max(0, self.input_tokens - self.cache_hit_tokens)
|
|
52
|
+
|
|
53
|
+
def add(self, payload: Dict[str, Any]) -> None:
|
|
54
|
+
if not payload:
|
|
55
|
+
return
|
|
56
|
+
prompt = payload.get("prompt_tokens", payload.get("input_tokens"))
|
|
57
|
+
completion = payload.get("completion_tokens", payload.get("output_tokens"))
|
|
58
|
+
if prompt is not None:
|
|
59
|
+
self.input_tokens = max(self.input_tokens, int(prompt))
|
|
60
|
+
if completion is not None:
|
|
61
|
+
self.output_tokens = max(self.output_tokens, int(completion))
|
|
62
|
+
details = payload.get("prompt_tokens_details") or payload.get("cache_read_input_tokens_details") or {}
|
|
63
|
+
cached = (
|
|
64
|
+
payload.get("prompt_cache_hit_tokens")
|
|
65
|
+
or payload.get("cache_read_input_tokens")
|
|
66
|
+
or (details.get("cached_tokens") if isinstance(details, dict) else None)
|
|
67
|
+
)
|
|
68
|
+
if cached is not None:
|
|
69
|
+
self.cache_hit_tokens = max(self.cache_hit_tokens, int(cached))
|
|
70
|
+
|
|
71
|
+
def as_dict(self, model: str) -> Dict[str, Any]:
|
|
72
|
+
cost = price_usd(model, self.cache_miss_tokens, self.cache_hit_tokens, self.output_tokens)
|
|
73
|
+
return {
|
|
74
|
+
"input_tokens": self.input_tokens,
|
|
75
|
+
"output_tokens": self.output_tokens,
|
|
76
|
+
"cache_hit_tokens": self.cache_hit_tokens,
|
|
77
|
+
"cache_miss_tokens": self.cache_miss_tokens,
|
|
78
|
+
"calls": self.calls,
|
|
79
|
+
"usd": cost["usd"],
|
|
80
|
+
"priced": cost["priced"],
|
|
81
|
+
"price_snapshot": cost["price_snapshot"],
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class StreamEvent:
|
|
87
|
+
type: str # text | thinking | tool_call | usage | done
|
|
88
|
+
text: str = ""
|
|
89
|
+
tool_call: Optional[ToolCall] = None
|
|
90
|
+
usage: Dict[str, Any] = field(default_factory=dict)
|
|
91
|
+
stop_reason: str = ""
|
|
92
|
+
detail: str = ""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class ProviderConfig:
|
|
97
|
+
name: str
|
|
98
|
+
wire: str # "openai" | "anthropic"
|
|
99
|
+
base_url: str
|
|
100
|
+
api_key_env: str = ""
|
|
101
|
+
default_model: str = ""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
PRESETS: Dict[str, ProviderConfig] = {
|
|
105
|
+
"deepseek": ProviderConfig("deepseek", "openai", "https://api.deepseek.com", "DEEPSEEK_API_KEY", "deepseek-chat"),
|
|
106
|
+
"openai": ProviderConfig("openai", "openai", "https://api.openai.com/v1", "OPENAI_API_KEY", ""),
|
|
107
|
+
"openrouter": ProviderConfig("openrouter", "openai", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY", ""),
|
|
108
|
+
"ollama": ProviderConfig("ollama", "openai", "http://127.0.0.1:11434/v1", "", "qwen2.5-coder:7b"),
|
|
109
|
+
"lmstudio": ProviderConfig("lmstudio", "openai", "http://127.0.0.1:1234/v1", "", ""),
|
|
110
|
+
"anthropic": ProviderConfig("anthropic", "anthropic", "https://api.anthropic.com", "ANTHROPIC_API_KEY", ""),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _infer_provider(model: str) -> str:
|
|
115
|
+
m = (model or "").lower()
|
|
116
|
+
if m.startswith("claude"):
|
|
117
|
+
return "anthropic"
|
|
118
|
+
if m.startswith(("gpt", "o1", "o3", "o4", "chatgpt")):
|
|
119
|
+
return "openai"
|
|
120
|
+
if m.startswith("deepseek"):
|
|
121
|
+
return "deepseek"
|
|
122
|
+
explicit = os.environ.get("TOKENSAFE_AGENT_PROVIDER", "").strip().lower()
|
|
123
|
+
return explicit if explicit in PRESETS else "deepseek"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class Provider:
|
|
127
|
+
"""Base class: wire parsing lives in subclasses, config plumbing here."""
|
|
128
|
+
|
|
129
|
+
wire = ""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
config: ProviderConfig,
|
|
134
|
+
model: str = "",
|
|
135
|
+
api_key: Optional[str] = None,
|
|
136
|
+
base_url: Optional[str] = None,
|
|
137
|
+
timeout: float = 120.0,
|
|
138
|
+
max_output_tokens: Optional[int] = None,
|
|
139
|
+
):
|
|
140
|
+
self.config = config
|
|
141
|
+
self.model = model or config.default_model or os.environ.get("TOKENSAFE_AGENT_MODEL", "")
|
|
142
|
+
if not self.model:
|
|
143
|
+
raise ProviderError(
|
|
144
|
+
f"no model selected for provider '{config.name}': pass --model or set TOKENSAFE_AGENT_MODEL"
|
|
145
|
+
)
|
|
146
|
+
self.base_url = (base_url or os.environ.get("TOKENSAFE_AGENT_BASE_URL") or config.base_url).rstrip("/")
|
|
147
|
+
self.api_key = api_key if api_key is not None else (
|
|
148
|
+
os.environ.get(config.api_key_env, "") if config.api_key_env else ""
|
|
149
|
+
)
|
|
150
|
+
if config.api_key_env and not self.api_key:
|
|
151
|
+
raise ProviderError(
|
|
152
|
+
f"missing API key: set {config.api_key_env} (provider '{config.name}')"
|
|
153
|
+
)
|
|
154
|
+
self.timeout = timeout
|
|
155
|
+
self.max_output_tokens = max_output_tokens or int(os.environ.get("TOKENSAFE_AGENT_MAX_OUTPUT", "4096"))
|
|
156
|
+
|
|
157
|
+
# -- transport ---------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
def _headers(self) -> Dict[str, str]:
|
|
160
|
+
headers = {"Content-Type": "application/json", "Accept": "text/event-stream"}
|
|
161
|
+
if self.api_key:
|
|
162
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
163
|
+
return headers
|
|
164
|
+
|
|
165
|
+
def _endpoint(self) -> str:
|
|
166
|
+
raise NotImplementedError
|
|
167
|
+
|
|
168
|
+
def _payload(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]]) -> Dict[str, Any]:
|
|
169
|
+
raise NotImplementedError
|
|
170
|
+
|
|
171
|
+
def _open(self, payload: Dict[str, Any]) -> Iterator[str]:
|
|
172
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
173
|
+
request = urllib.request.Request(self._endpoint(), data=body, headers=self._headers(), method="POST")
|
|
174
|
+
try:
|
|
175
|
+
response = urllib.request.urlopen(request, timeout=self.timeout)
|
|
176
|
+
except urllib.error.HTTPError as exc:
|
|
177
|
+
detail = ""
|
|
178
|
+
try:
|
|
179
|
+
detail = exc.read().decode("utf-8", "replace")[:600]
|
|
180
|
+
except Exception:
|
|
181
|
+
pass
|
|
182
|
+
raise ProviderError(f"{self.config.name} HTTP {exc.code}: {detail or exc.reason}") from exc
|
|
183
|
+
except urllib.error.URLError as exc:
|
|
184
|
+
raise ProviderError(f"{self.config.name} connection failed: {exc.reason}") from exc
|
|
185
|
+
try:
|
|
186
|
+
for raw_line in response:
|
|
187
|
+
yield raw_line.decode("utf-8", "replace").rstrip("\n")
|
|
188
|
+
finally:
|
|
189
|
+
try:
|
|
190
|
+
response.close()
|
|
191
|
+
except Exception:
|
|
192
|
+
pass
|
|
193
|
+
|
|
194
|
+
# -- public ------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
def stream(
|
|
197
|
+
self,
|
|
198
|
+
messages: List[Dict[str, Any]],
|
|
199
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
200
|
+
cancel: Optional[threading.Event] = None,
|
|
201
|
+
) -> Iterator[StreamEvent]:
|
|
202
|
+
raise NotImplementedError
|
|
203
|
+
|
|
204
|
+
def complete(
|
|
205
|
+
self,
|
|
206
|
+
messages: List[Dict[str, Any]],
|
|
207
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
208
|
+
cancel: Optional[threading.Event] = None,
|
|
209
|
+
) -> Dict[str, Any]:
|
|
210
|
+
"""Drain the stream into one assistant message (used by tests and the CLI)."""
|
|
211
|
+
text_parts: List[str] = []
|
|
212
|
+
tool_calls: List[ToolCall] = []
|
|
213
|
+
usage = Usage()
|
|
214
|
+
stop_reason = ""
|
|
215
|
+
for event in self.stream(messages, tools=tools, cancel=cancel):
|
|
216
|
+
if event.type == "text":
|
|
217
|
+
text_parts.append(event.text)
|
|
218
|
+
elif event.type == "tool_call" and event.tool_call:
|
|
219
|
+
tool_calls.append(event.tool_call)
|
|
220
|
+
elif event.type == "usage":
|
|
221
|
+
usage.add(event.usage)
|
|
222
|
+
elif event.type == "done":
|
|
223
|
+
stop_reason = event.stop_reason or stop_reason
|
|
224
|
+
return {
|
|
225
|
+
"content": "".join(text_parts),
|
|
226
|
+
"tool_calls": tool_calls,
|
|
227
|
+
"usage": usage,
|
|
228
|
+
"stop_reason": stop_reason,
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class OpenAICompatibleProvider(Provider):
|
|
233
|
+
wire = "openai"
|
|
234
|
+
|
|
235
|
+
def _endpoint(self) -> str:
|
|
236
|
+
return f"{self.base_url}/chat/completions"
|
|
237
|
+
|
|
238
|
+
def _payload(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]]) -> Dict[str, Any]:
|
|
239
|
+
body: Dict[str, Any] = {
|
|
240
|
+
"model": self.model,
|
|
241
|
+
"messages": messages,
|
|
242
|
+
"stream": True,
|
|
243
|
+
"stream_options": {"include_usage": True},
|
|
244
|
+
"temperature": float(os.environ.get("TOKENSAFE_AGENT_TEMPERATURE", "0")),
|
|
245
|
+
}
|
|
246
|
+
if tools:
|
|
247
|
+
body["tools"] = [{"type": "function", "function": tool} for tool in tools]
|
|
248
|
+
return body
|
|
249
|
+
|
|
250
|
+
def stream(self, messages, tools=None, cancel=None):
|
|
251
|
+
pending: Dict[int, Dict[str, str]] = {}
|
|
252
|
+
stop_reason = ""
|
|
253
|
+
for line in self._open(self._payload(messages, tools)):
|
|
254
|
+
if cancel is not None and cancel.is_set():
|
|
255
|
+
yield StreamEvent("done", stop_reason="cancelled")
|
|
256
|
+
return
|
|
257
|
+
if not line.startswith("data:"):
|
|
258
|
+
continue
|
|
259
|
+
data = line[5:].strip()
|
|
260
|
+
if not data or data == "[DONE]":
|
|
261
|
+
continue
|
|
262
|
+
try:
|
|
263
|
+
chunk = json.loads(data)
|
|
264
|
+
except Exception:
|
|
265
|
+
continue
|
|
266
|
+
if chunk.get("usage"):
|
|
267
|
+
yield StreamEvent("usage", usage=chunk["usage"])
|
|
268
|
+
for choice in chunk.get("choices") or []:
|
|
269
|
+
delta = choice.get("delta") or {}
|
|
270
|
+
if delta.get("content"):
|
|
271
|
+
yield StreamEvent("text", text=str(delta["content"]))
|
|
272
|
+
if delta.get("reasoning_content"):
|
|
273
|
+
yield StreamEvent("thinking", text=str(delta["reasoning_content"]))
|
|
274
|
+
for fragment in delta.get("tool_calls") or []:
|
|
275
|
+
index = int(fragment.get("index", 0) or 0)
|
|
276
|
+
slot = pending.setdefault(index, {"id": "", "name": "", "args": ""})
|
|
277
|
+
if fragment.get("id"):
|
|
278
|
+
slot["id"] = str(fragment["id"])
|
|
279
|
+
function = fragment.get("function") or {}
|
|
280
|
+
name = str(function.get("name") or "")
|
|
281
|
+
if name:
|
|
282
|
+
if not slot["name"]:
|
|
283
|
+
slot["name"] = name
|
|
284
|
+
elif name not in slot["name"]:
|
|
285
|
+
slot["name"] += name
|
|
286
|
+
if function.get("arguments"):
|
|
287
|
+
slot["args"] += str(function["arguments"])
|
|
288
|
+
if choice.get("finish_reason"):
|
|
289
|
+
stop_reason = str(choice["finish_reason"])
|
|
290
|
+
for index in sorted(pending):
|
|
291
|
+
slot = pending[index]
|
|
292
|
+
if not slot["name"]:
|
|
293
|
+
continue
|
|
294
|
+
yield StreamEvent("tool_call", tool_call=_finalize_tool_call(slot["id"], slot["name"], slot["args"]))
|
|
295
|
+
if stop_reason == "tool_calls" or pending:
|
|
296
|
+
stop_reason = "tool_calls" if pending else stop_reason
|
|
297
|
+
yield StreamEvent("done", stop_reason=stop_reason or "end_turn")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class AnthropicProvider(Provider):
|
|
301
|
+
wire = "anthropic"
|
|
302
|
+
|
|
303
|
+
def _headers(self) -> Dict[str, str]:
|
|
304
|
+
headers = {
|
|
305
|
+
"Content-Type": "application/json",
|
|
306
|
+
"Accept": "text/event-stream",
|
|
307
|
+
"anthropic-version": os.environ.get("ANTHROPIC_VERSION", "2023-06-01"),
|
|
308
|
+
}
|
|
309
|
+
if self.api_key:
|
|
310
|
+
headers["x-api-key"] = self.api_key
|
|
311
|
+
return headers
|
|
312
|
+
|
|
313
|
+
def _endpoint(self) -> str:
|
|
314
|
+
base = self.base_url
|
|
315
|
+
if base.endswith("/v1"):
|
|
316
|
+
return f"{base}/messages"
|
|
317
|
+
return f"{base}/v1/messages"
|
|
318
|
+
|
|
319
|
+
def _payload(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]]) -> Dict[str, Any]:
|
|
320
|
+
system, converted = to_anthropic_messages(messages)
|
|
321
|
+
body: Dict[str, Any] = {
|
|
322
|
+
"model": self.model,
|
|
323
|
+
"max_tokens": self.max_output_tokens,
|
|
324
|
+
"messages": converted,
|
|
325
|
+
"stream": True,
|
|
326
|
+
}
|
|
327
|
+
if system:
|
|
328
|
+
body["system"] = system
|
|
329
|
+
if tools:
|
|
330
|
+
body["tools"] = [
|
|
331
|
+
{
|
|
332
|
+
"name": tool["name"],
|
|
333
|
+
"description": tool.get("description", ""),
|
|
334
|
+
"input_schema": tool.get("input_schema") or tool.get("inputSchema") or {"type": "object"},
|
|
335
|
+
}
|
|
336
|
+
for tool in tools
|
|
337
|
+
]
|
|
338
|
+
return body
|
|
339
|
+
|
|
340
|
+
def stream(self, messages, tools=None, cancel=None):
|
|
341
|
+
current: Dict[int, Dict[str, Any]] = {}
|
|
342
|
+
stop_reason = ""
|
|
343
|
+
usage_payload: Dict[str, Any] = {}
|
|
344
|
+
for line in self._open(self._payload(messages, tools)):
|
|
345
|
+
if cancel is not None and cancel.is_set():
|
|
346
|
+
yield StreamEvent("done", stop_reason="cancelled")
|
|
347
|
+
return
|
|
348
|
+
if not line.startswith("data:"):
|
|
349
|
+
continue
|
|
350
|
+
data = line[5:].strip()
|
|
351
|
+
if not data:
|
|
352
|
+
continue
|
|
353
|
+
try:
|
|
354
|
+
event = json.loads(data)
|
|
355
|
+
except Exception:
|
|
356
|
+
continue
|
|
357
|
+
kind = event.get("type")
|
|
358
|
+
if kind == "content_block_start":
|
|
359
|
+
block = event.get("content_block") or {}
|
|
360
|
+
index = int(event.get("index", 0) or 0)
|
|
361
|
+
if block.get("type") == "tool_use":
|
|
362
|
+
current[index] = {
|
|
363
|
+
"id": str(block.get("id") or ""),
|
|
364
|
+
"name": str(block.get("name") or ""),
|
|
365
|
+
"args": "",
|
|
366
|
+
}
|
|
367
|
+
elif kind == "content_block_delta":
|
|
368
|
+
index = int(event.get("index", 0) or 0)
|
|
369
|
+
delta = event.get("delta") or {}
|
|
370
|
+
delta_type = delta.get("type")
|
|
371
|
+
if delta_type == "text_delta":
|
|
372
|
+
yield StreamEvent("text", text=str(delta.get("text") or ""))
|
|
373
|
+
elif delta_type == "thinking_delta":
|
|
374
|
+
yield StreamEvent("thinking", text=str(delta.get("thinking") or ""))
|
|
375
|
+
elif delta_type == "input_json_delta" and index in current:
|
|
376
|
+
current[index]["args"] += str(delta.get("partial_json") or "")
|
|
377
|
+
elif kind == "content_block_stop":
|
|
378
|
+
index = int(event.get("index", 0) or 0)
|
|
379
|
+
slot = current.pop(index, None)
|
|
380
|
+
if slot and slot.get("name"):
|
|
381
|
+
yield StreamEvent(
|
|
382
|
+
"tool_call",
|
|
383
|
+
tool_call=_finalize_tool_call(slot["id"], slot["name"], slot["args"]),
|
|
384
|
+
)
|
|
385
|
+
elif kind == "message_start":
|
|
386
|
+
message = event.get("message") or {}
|
|
387
|
+
if message.get("usage"):
|
|
388
|
+
usage_payload.update(message["usage"])
|
|
389
|
+
yield StreamEvent("usage", usage=message["usage"])
|
|
390
|
+
elif kind == "message_delta":
|
|
391
|
+
delta = event.get("delta") or {}
|
|
392
|
+
if delta.get("stop_reason"):
|
|
393
|
+
stop_reason = str(delta["stop_reason"])
|
|
394
|
+
if event.get("usage"):
|
|
395
|
+
usage_payload.update(event["usage"])
|
|
396
|
+
yield StreamEvent("usage", usage=event["usage"])
|
|
397
|
+
elif kind == "message_stop":
|
|
398
|
+
break
|
|
399
|
+
yield StreamEvent("done", stop_reason=stop_reason or "end_turn")
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _finalize_tool_call(call_id: str, name: str, raw_args: str) -> ToolCall:
|
|
403
|
+
raw = raw_args or "{}"
|
|
404
|
+
parsed = parse_tool_arguments(raw)
|
|
405
|
+
if parsed is None:
|
|
406
|
+
return ToolCall(
|
|
407
|
+
id=call_id or f"call_{name}",
|
|
408
|
+
name=name,
|
|
409
|
+
arguments={},
|
|
410
|
+
raw_arguments=raw,
|
|
411
|
+
parse_error="arguments were not valid JSON",
|
|
412
|
+
)
|
|
413
|
+
return ToolCall(id=call_id or f"call_{name}", name=name, arguments=parsed, raw_arguments=raw)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def to_anthropic_messages(messages: List[Dict[str, Any]]) -> tuple[str, List[Dict[str, Any]]]:
|
|
417
|
+
"""Convert canonical (OpenAI-shaped) messages into Anthropic's block format."""
|
|
418
|
+
system_parts: List[str] = []
|
|
419
|
+
converted: List[Dict[str, Any]] = []
|
|
420
|
+
|
|
421
|
+
for message in messages:
|
|
422
|
+
role = message.get("role")
|
|
423
|
+
content = message.get("content")
|
|
424
|
+
if role == "system":
|
|
425
|
+
if isinstance(content, str) and content:
|
|
426
|
+
system_parts.append(content)
|
|
427
|
+
continue
|
|
428
|
+
if role == "tool":
|
|
429
|
+
block = {
|
|
430
|
+
"type": "tool_result",
|
|
431
|
+
"tool_use_id": message.get("tool_call_id") or "",
|
|
432
|
+
"content": content if isinstance(content, str) else json.dumps(content, ensure_ascii=False),
|
|
433
|
+
}
|
|
434
|
+
converted.append({"role": "user", "content": [block]})
|
|
435
|
+
continue
|
|
436
|
+
if role == "assistant":
|
|
437
|
+
blocks: List[Dict[str, Any]] = []
|
|
438
|
+
if isinstance(content, str) and content:
|
|
439
|
+
blocks.append({"type": "text", "text": content})
|
|
440
|
+
for call in message.get("tool_calls") or []:
|
|
441
|
+
function = call.get("function") or {}
|
|
442
|
+
raw_args = function.get("arguments") or "{}"
|
|
443
|
+
parsed = parse_tool_arguments(raw_args) or {}
|
|
444
|
+
blocks.append(
|
|
445
|
+
{
|
|
446
|
+
"type": "tool_use",
|
|
447
|
+
"id": call.get("id") or "",
|
|
448
|
+
"name": function.get("name") or "",
|
|
449
|
+
"input": parsed,
|
|
450
|
+
}
|
|
451
|
+
)
|
|
452
|
+
converted.append({"role": "assistant", "content": blocks or [{"type": "text", "text": ""}]})
|
|
453
|
+
continue
|
|
454
|
+
text = content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
|
|
455
|
+
converted.append({"role": "user", "content": [{"type": "text", "text": text}]})
|
|
456
|
+
|
|
457
|
+
# Anthropic requires alternating roles; parallel tool results arrive as
|
|
458
|
+
# consecutive user messages, so merge adjacent blocks of the same role.
|
|
459
|
+
merged: List[Dict[str, Any]] = []
|
|
460
|
+
for message in converted:
|
|
461
|
+
if merged and merged[-1]["role"] == message["role"]:
|
|
462
|
+
merged[-1]["content"].extend(message["content"])
|
|
463
|
+
else:
|
|
464
|
+
merged.append(message)
|
|
465
|
+
return "\n\n".join(system_parts), merged
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def resolve_provider(
|
|
469
|
+
model: str = "",
|
|
470
|
+
provider: str = "",
|
|
471
|
+
base_url: str = "",
|
|
472
|
+
api_key: Optional[str] = None,
|
|
473
|
+
) -> Provider:
|
|
474
|
+
"""Pick a provider from an explicit name, the model prefix, or the env."""
|
|
475
|
+
selected = (provider or "").strip().lower()
|
|
476
|
+
if not selected:
|
|
477
|
+
configured = os.environ.get("TOKENSAFE_AGENT_PROVIDER", "").strip().lower()
|
|
478
|
+
selected = configured if configured in PRESETS else _infer_provider(model)
|
|
479
|
+
if selected not in PRESETS:
|
|
480
|
+
raise ProviderError(
|
|
481
|
+
f"unknown provider '{selected}'. Known: {', '.join(sorted(PRESETS))}"
|
|
482
|
+
)
|
|
483
|
+
config = PRESETS[selected]
|
|
484
|
+
resolved_model = model or os.environ.get("TOKENSAFE_AGENT_MODEL", "") or config.default_model
|
|
485
|
+
cls = AnthropicProvider if config.wire == "anthropic" else OpenAICompatibleProvider
|
|
486
|
+
return cls(config, model=resolved_model, api_key=api_key, base_url=base_url or "")
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Tool surface for the in-process loop.
|
|
2
|
+
|
|
3
|
+
The loop calls ``handle_tool_call`` directly. There is no stdio JSON-RPC hop
|
|
4
|
+
and, more importantly, no second copy of the schemas: the same ``TOOLS`` list
|
|
5
|
+
that the MCP client sees is the list the model sees. One registry, one
|
|
6
|
+
behaviour, one place to change an argument contract.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any, Dict, List, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
DEFAULT_TOOL_NAMES: Sequence[str] = (
|
|
16
|
+
"smart_read_file",
|
|
17
|
+
"scoped_search",
|
|
18
|
+
"apply_edits",
|
|
19
|
+
"repo_map",
|
|
20
|
+
"session_context",
|
|
21
|
+
"oumv",
|
|
22
|
+
"run_helper",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
# Tool output above this is truncated before it re-enters the model context.
|
|
26
|
+
# The MCP server already caps its own replies, but a direct call bypasses the
|
|
27
|
+
# transport, so the loop enforces its own ceiling.
|
|
28
|
+
RESULT_MAX_CHARS = int(os.environ.get("TOKENSAFE_AGENT_TOOL_RESULT_CHARS", "24000"))
|
|
29
|
+
|
|
30
|
+
_TOOL_KINDS = {
|
|
31
|
+
"smart_read_file": "read",
|
|
32
|
+
"scoped_search": "search",
|
|
33
|
+
"repo_map": "search",
|
|
34
|
+
"apply_edits": "edit",
|
|
35
|
+
"run_helper": "other",
|
|
36
|
+
"session_context": "other",
|
|
37
|
+
"oumv": "other",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class ToolResult:
|
|
43
|
+
name: str
|
|
44
|
+
ok: bool
|
|
45
|
+
text: str
|
|
46
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
47
|
+
truncated: bool = False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def tool_schemas(names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
|
|
51
|
+
"""OpenAI/Anthropic-neutral schemas straight from the MCP tool registry."""
|
|
52
|
+
from src.mcp_server import TOOLS
|
|
53
|
+
|
|
54
|
+
index = {tool["name"]: tool for tool in TOOLS}
|
|
55
|
+
selected = list(names or DEFAULT_TOOL_NAMES)
|
|
56
|
+
schemas: List[Dict[str, Any]] = []
|
|
57
|
+
for name in selected:
|
|
58
|
+
spec = index.get(name)
|
|
59
|
+
if not spec:
|
|
60
|
+
continue
|
|
61
|
+
schemas.append(
|
|
62
|
+
{
|
|
63
|
+
"name": name,
|
|
64
|
+
"description": spec.get("description", ""),
|
|
65
|
+
"input_schema": spec.get("inputSchema") or {"type": "object", "properties": {}},
|
|
66
|
+
}
|
|
67
|
+
)
|
|
68
|
+
return schemas
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def tool_kind(name: str) -> str:
|
|
72
|
+
return _TOOL_KINDS.get(name, "other")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def dispatch_tool(name: str, arguments: Dict[str, Any]) -> ToolResult:
|
|
76
|
+
"""Execute one tool call through the canonical MCP handler."""
|
|
77
|
+
from src.mcp_server import handle_tool_call
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
result = handle_tool_call(name, dict(arguments or {}))
|
|
81
|
+
except Exception as exc: # the handler catches internally; this is belt-and-braces
|
|
82
|
+
return ToolResult(name=name, ok=False, text=f"{type(exc).__name__}: {exc}")
|
|
83
|
+
|
|
84
|
+
parts = result.get("content") or []
|
|
85
|
+
text = "".join(part.get("text", "") for part in parts if isinstance(part, dict))
|
|
86
|
+
ok = not result.get("isError", False)
|
|
87
|
+
if not text:
|
|
88
|
+
text = "(no output)"
|
|
89
|
+
truncated = False
|
|
90
|
+
if len(text) > RESULT_MAX_CHARS:
|
|
91
|
+
omitted = len(text) - RESULT_MAX_CHARS
|
|
92
|
+
text = (
|
|
93
|
+
text[:RESULT_MAX_CHARS]
|
|
94
|
+
+ f"\n// [TokenSafe: tool result truncated, {omitted:,} chars omitted. "
|
|
95
|
+
f"Narrow the call instead of re-reading.]"
|
|
96
|
+
)
|
|
97
|
+
truncated = True
|
|
98
|
+
return ToolResult(name=name, ok=ok, text=text, raw=result, truncated=truncated)
|
package/src/agent_firewall.py
CHANGED
|
@@ -25,6 +25,11 @@ class AgentFirewall:
|
|
|
25
25
|
_PRUNE_INTERVAL = 3600.0 # amortized hourly prune of the persistent layer
|
|
26
26
|
_PRUNE_KEEP = 500
|
|
27
27
|
_last_prune = 0.0
|
|
28
|
+
# Content this process has actually delivered. The cache is keyed by session_id,
|
|
29
|
+
# and host session ids like "mcp:<client>" outlive one process — so a DB hit alone
|
|
30
|
+
# does not mean the caller already has the bytes in context, and saying "reused
|
|
31
|
+
# session read" when it doesn't is how an agent talks itself out of a needed read.
|
|
32
|
+
_EMITTED_IN_PROCESS = set()
|
|
28
33
|
|
|
29
34
|
@classmethod
|
|
30
35
|
def _ensure_table(cls, tracker: MetricsTracker):
|
|
@@ -189,7 +194,14 @@ class AgentFirewall:
|
|
|
189
194
|
)
|
|
190
195
|
opt_tokens = count_tokens(payload)
|
|
191
196
|
else:
|
|
192
|
-
|
|
197
|
+
emitted_key = (abs_path, symbol_key)
|
|
198
|
+
if hit_scope == "persistent":
|
|
199
|
+
scope_label = "Persistent cache"
|
|
200
|
+
elif emitted_key in cls._EMITTED_IN_PROCESS:
|
|
201
|
+
scope_label = "Reused session read"
|
|
202
|
+
else:
|
|
203
|
+
scope_label = "Cached read (same file, unchanged on disk)"
|
|
204
|
+
cls._EMITTED_IN_PROCESS.add(emitted_key)
|
|
193
205
|
sym_label = f"::{symbol_key}" if symbol_key else ""
|
|
194
206
|
# Static deterministic header (no changing hit counters that bust LLM prefix KV-cache)
|
|
195
207
|
header = (
|
|
@@ -251,6 +263,9 @@ class AgentFirewall:
|
|
|
251
263
|
tokens = count_tokens(content)
|
|
252
264
|
now = int(time.time())
|
|
253
265
|
content_hash = cls._file_content_hash(abs_path)
|
|
266
|
+
# record_cache runs right after the caller received this content, so from here
|
|
267
|
+
# on a hit in this process really is a repeat of what the agent already has.
|
|
268
|
+
cls._EMITTED_IN_PROCESS.add((abs_path, symbol_key))
|
|
254
269
|
|
|
255
270
|
def _insert():
|
|
256
271
|
with tracker._get_connection() as conn:
|