tokensafe 2.7.2 → 2.7.3

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.
@@ -153,7 +153,7 @@ def handle(event: str, payload: dict) -> dict:
153
153
  tool_input = {}
154
154
  if tool in ("Bash", "Shell", "bash"):
155
155
  command = str(tool_input.get("command") or "")
156
- verdict = guard_command(command, AGENT, session_id)
156
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
157
157
  if verdict["decision"] == "deny":
158
158
  return {
159
159
  "hookSpecificOutput": {
@@ -42,7 +42,7 @@ def handle(event: str, payload: dict) -> dict:
42
42
 
43
43
  if event == "beforeShellExecution":
44
44
  command = str(payload.get("command") or "")
45
- verdict = guard_command(command, AGENT, session_id)
45
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
46
46
  if verdict["decision"] == "deny":
47
47
  return {"permission": "deny", "user_message": verdict["reason"]}
48
48
  if verdict["decision"] == "ask":
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.7.2",
4
+ "version": "2.7.3",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.7.2",
4
+ "version": "2.7.3",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "2.7.2",
6
+ "version": "2.7.3",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.7.2",
33
+ "version": "2.7.3",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "2.7.2",
49
+ "version": "2.7.3",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -60,6 +60,8 @@ Quick pointers:
60
60
  - Search: `tokensafe:scoped_search(query, scope)` — never raw grep.
61
61
  - Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps.
62
62
  - Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
63
+ - Directory: `tokensafe:list_dir(path, depth=2)` — clean tree, never verbose `ls -la`.
64
+ - Terminal: `tokensafe:sanitize_command(command, cwd)` — bounded logs/diffs, test runner guards.
63
65
  - Context: `tokensafe:compact_conversation(transcript_path)` / `tokensafe:context_budget`.
64
66
 
65
67
  ---
@@ -74,7 +74,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
74
74
  ```
75
75
  *Extracts the targeted `LuckyWheelTab` implementation plus compact 1-line signatures for 1-hop dependencies with inert code and imports folded. Pass `"dep_mode": "full"` for full dependency bodies, `"include_deps": false` for 0-hop isolation, or `"force_full": true` to bypass a session pointer hit.*
76
76
 
77
- ### 3. Public API Map Workflow
77
+ ### 4. Public API Map Workflow
78
78
  ```json
79
79
  {
80
80
  "ServerName": "tokensafe",
@@ -86,21 +86,20 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
86
86
  ```
87
87
  *Returns all exported interfaces and types without reading hundreds of module files.*
88
88
 
89
- ### 4. Pre-flight Security & Hygiene Audit
89
+ ### 5. Pre-flight Security & Hygiene Audit
90
90
  ```json
91
91
  {
92
92
  "ServerName": "tokensafe",
93
93
  "ToolName": "guard_inspect",
94
94
  "Arguments": {
95
95
  "command": "git add .env",
96
- "code": "const key = process.env.JWT_SECRET || 'hardcoded_secret';",
97
96
  "file_path": "src/auth.ts"
98
97
  }
99
98
  }
100
99
  ```
101
100
  *Validates commands and code snippets before execution; returns structured pass/block verdict with check_name.*
102
101
 
103
- ### 5. Context Budget → Smart Compact Workflow
102
+ ### 6. Context Budget → Smart Compact Workflow
104
103
  ```json
105
104
  {
106
105
  "ServerName": "tokensafe",
@@ -127,7 +127,7 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
127
127
  return "", meta
128
128
 
129
129
 
130
- def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, Any]:
130
+ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "") -> Dict[str, Any]:
131
131
  """Pre-execution shell guard. Returns:
132
132
  {decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is the
133
133
  MEASURED mass of blocked output (0 for allowed commands)."""
@@ -161,19 +161,19 @@ def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, A
161
161
  if re.search(pat, text):
162
162
  blocked("DESTRUCTIVE", "Blocked: irreversible/destructive operation")
163
163
  return result
164
- # RAW_CODE_SEARCH (deny): recursive grep/rg/find crawls over source trees
165
- # are the exact workflow the tokensafe MCP tools replace. TokenSafeGuard
166
- # already enforces this on the Antigravity path (inspect_command) — share
167
- # its check here so Claude Code / Cursor adapters honor the same policy
168
- # with the same "use tokensafe:scoped_search" guidance. Fail-open on
169
- # import problems, like every adapter guard path.
164
+ # Full TokenSafeGuard delegation: the Antigravity path (pre_tool_use.py) runs
165
+ # TokenSafeGuard.inspect_command, and the Claude Code / Cursor adapters must
166
+ # honor the SAME policy suite (GIT_SECRET_STAGING, SQL_INJECTION,
167
+ # INSECURE_CORS, DATA_EXFILTRATION, DESTRUCTIVE_RM flag/target variants, and
168
+ # raw code search with the MCP-tools guidance) instead of a regex subset.
169
+ # Fail-open on import problems, like every adapter guard path.
170
170
  try:
171
171
  from src.guard import TokenSafeGuard
172
- search_err = TokenSafeGuard._check_raw_code_search(cmd)
172
+ guard_res = TokenSafeGuard.inspect_command(cmd, cwd=cwd or None)
173
173
  except Exception:
174
- search_err = None
175
- if search_err:
176
- blocked("RAW_CODE_SEARCH", search_err)
174
+ guard_res = None
175
+ if guard_res is not None and getattr(guard_res, "blocked", False):
176
+ blocked(guard_res.check_name or "GUARD", guard_res.reason)
177
177
  return result
178
178
  for pat in _TLS_BYPASS_PATTERNS:
179
179
  if re.search(pat, text):
package/src/installer.py CHANGED
@@ -49,9 +49,14 @@ UNIFIED_TOKENSAFE_RULE = (
49
49
  "2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context.\n"
50
50
  "3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
51
51
  "4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
52
- "5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
53
- "6. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage; when it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` before continuing.\n"
54
- "7. **Proof-of-Savings Turn Footer (always in English)**:\n"
52
+ "5. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens).\n"
53
+ "6. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
54
+ "7. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
55
+ "8. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage; when it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` before continuing.\n"
56
+ "9. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
57
+ "Never hardcode real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Whenever a secret fallback attempt is blocked, state:\n"
58
+ "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
59
+ "10. **Proof-of-Savings Turn Footer (always in English)**:\n"
55
60
  "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
56
61
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
57
62
  )
package/src/mcp_server.py CHANGED
@@ -40,7 +40,7 @@ from src.license_manager import LicenseManager
40
40
 
41
41
  SERVER_INFO = {
42
42
  "name": "tokensafe-mcp",
43
- "version": "2.7.2"
43
+ "version": "2.7.3"
44
44
  }
45
45
 
46
46
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -714,8 +714,6 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
714
714
  total_seen = idx
715
715
  if idx <= cap:
716
716
  raw_lines.append(line)
717
- elif idx == cap + 1:
718
- pass
719
717
  raw_chunk = "".join(raw_lines)
720
718
  if total_seen > cap:
721
719
  raw_chunk += f"\n// [TokenSafe Community 500k limit reached: showing raw lines 1-{cap} of {total_seen}. AST/graph slicing & pointer dedup are paused.]\n"
package/src/proxy.py CHANGED
@@ -8,6 +8,7 @@ Endpoint: http://127.0.0.1:8765/v1
8
8
  import sys
9
9
  import os
10
10
  import json
11
+ import time
11
12
  import queue
12
13
  import threading
13
14
  import urllib.request
@@ -63,6 +64,329 @@ class EventBroadcaster:
63
64
 
64
65
  BROADCASTER = EventBroadcaster()
65
66
 
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # OpenAI <-> Anthropic payload translation.
70
+ # The proxy accepts OpenAI /v1/chat/completions bodies from any agent; when the
71
+ # resolved upstream is Anthropic (/v1/messages) the body, response, SSE stream,
72
+ # and error envelopes must be converted in-flight, otherwise the raw OpenAI
73
+ # shape is rejected by the Anthropic API (missing max_tokens, system role, etc).
74
+ # ---------------------------------------------------------------------------
75
+
76
+ _ANTHROPIC_FINISH_MAP = {
77
+ "end_turn": "stop",
78
+ "stop_sequence": "stop",
79
+ "max_tokens": "length",
80
+ "tool_use": "tool_calls",
81
+ "refusal": "content_filter",
82
+ }
83
+
84
+ _OPENAI_ONLY_FIELDS = (
85
+ "frequency_penalty", "presence_penalty", "logprobs", "top_logprobs", "n",
86
+ "response_format", "seed", "stream_options", "user", "parallel_tool_calls",
87
+ "prompt_cache_key", "logit_bias", "service_tier",
88
+ )
89
+
90
+
91
+ def _blocks_from_content(content: Any, role: str = "user") -> List[Dict[str, Any]]:
92
+ """Converts one OpenAI message content (str or block list) into Anthropic content blocks."""
93
+ blocks: List[Dict[str, Any]] = []
94
+ if isinstance(content, str):
95
+ if content:
96
+ blocks.append({"type": "text", "text": content})
97
+ return blocks
98
+ if not isinstance(content, list):
99
+ return blocks
100
+ for blk in content:
101
+ if not isinstance(blk, dict):
102
+ continue
103
+ btype = blk.get("type")
104
+ if btype == "text" and isinstance(blk.get("text"), str):
105
+ nb = {"type": "text", "text": blk["text"]}
106
+ if isinstance(blk.get("cache_control"), dict):
107
+ nb["cache_control"] = blk["cache_control"]
108
+ blocks.append(nb)
109
+ elif btype == "image_url":
110
+ url = (blk.get("image_url") or {}).get("url", "") if isinstance(blk.get("image_url"), dict) else ""
111
+ if url.startswith("data:"):
112
+ head, _, b64 = url.partition(",")
113
+ media = head[5:].split(";", 1)[0] or "image/png"
114
+ if b64:
115
+ blocks.append({"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}})
116
+ elif url:
117
+ blocks.append({"type": "image", "source": {"type": "url", "url": url}})
118
+ return blocks
119
+
120
+
121
+ def _collapse_plain_text(blocks: List[Dict[str, Any]]) -> Any:
122
+ """Collapses pure-text blocks (no cache_control) back into a plain string —
123
+ Anthropic accepts string content, and it keeps payloads closest to the client's shape."""
124
+ if not blocks or any(b.get("type") != "text" or "cache_control" in b for b in blocks):
125
+ return blocks
126
+ texts = [b.get("text", "") for b in blocks]
127
+ return texts[0] if len(texts) == 1 else "\n\n".join(texts)
128
+
129
+
130
+ def _merge_same_role(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
131
+ """Anthropic requires alternating roles; folds consecutive same-role messages."""
132
+ merged: List[Dict[str, Any]] = []
133
+ for msg in messages:
134
+ if merged and merged[-1].get("role") == msg.get("role"):
135
+ prev = merged[-1]
136
+ prev_c = prev.get("content")
137
+ cur_c = msg.get("content")
138
+ prev_blocks = prev_c if isinstance(prev_c, list) else ([{"type": "text", "text": prev_c}] if prev_c else [])
139
+ cur_blocks = cur_c if isinstance(cur_c, list) else ([{"type": "text", "text": cur_c}] if cur_c else [])
140
+ prev["content"] = prev_blocks + cur_blocks
141
+ else:
142
+ merged.append(msg)
143
+ return merged
144
+
145
+
146
+ def _translate_openai_payload_to_anthropic(payload: Dict[str, Any]) -> Dict[str, Any]:
147
+ """Converts an OpenAI chat-completions payload into an Anthropic /v1/messages payload."""
148
+ src_messages = payload.get("messages") if isinstance(payload.get("messages"), list) else []
149
+
150
+ system_parts: List[Dict[str, Any]] = []
151
+ out_messages: List[Dict[str, Any]] = []
152
+ for msg in src_messages:
153
+ if not isinstance(msg, dict):
154
+ continue
155
+ role = msg.get("role")
156
+ if role in ("system", "developer"):
157
+ for blk in _blocks_from_content(msg.get("content"), role):
158
+ system_parts.append(blk)
159
+ continue
160
+
161
+ if role == "assistant":
162
+ blocks: List[Dict[str, Any]] = _blocks_from_content(msg.get("content"), "assistant")
163
+ for tc in (msg.get("tool_calls") or []):
164
+ if not isinstance(tc, dict):
165
+ continue
166
+ fn = tc.get("function") or {}
167
+ try:
168
+ tool_input = json.loads(fn.get("arguments") or "{}")
169
+ if not isinstance(tool_input, dict):
170
+ tool_input = {"_raw": tool_input}
171
+ except Exception:
172
+ tool_input = {}
173
+ blocks.append({
174
+ "type": "tool_use",
175
+ "id": tc.get("id") or "toolu_call",
176
+ "name": fn.get("name") or "unknown",
177
+ "input": tool_input,
178
+ })
179
+ if not blocks:
180
+ blocks = [{"type": "text", "text": ""}]
181
+ out_messages.append({"role": "assistant", "content": _collapse_plain_text(blocks) if len(blocks) == 1 and blocks[0].get("type") == "text" else blocks})
182
+ elif role == "tool":
183
+ tc_content = msg.get("content")
184
+ text = tc_content if isinstance(tc_content, str) else json.dumps(tc_content, ensure_ascii=False)
185
+ out_messages.append({
186
+ "role": "user",
187
+ "content": [{"type": "tool_result", "tool_use_id": msg.get("tool_call_id") or "toolu_call", "content": [{"type": "text", "text": text}]}],
188
+ })
189
+ elif role == "user":
190
+ out_messages.append({"role": "user", "content": _collapse_plain_text(_blocks_from_content(msg.get("content"), "user")) or [{"type": "text", "text": ""}]})
191
+
192
+ out: Dict[str, Any] = {
193
+ "model": payload.get("model") or "claude-3-5-sonnet-latest",
194
+ "max_tokens": payload.get("max_tokens") if isinstance(payload.get("max_tokens"), int) and payload["max_tokens"] > 0 else 4096,
195
+ "messages": _merge_same_role(out_messages),
196
+ }
197
+ if system_parts:
198
+ out["system"] = system_parts if len(system_parts) > 1 or system_parts[0].get("cache_control") else system_parts[0]["text"]
199
+ if isinstance(payload.get("temperature"), (int, float)):
200
+ out["temperature"] = payload["temperature"]
201
+ if isinstance(payload.get("top_p"), (int, float)):
202
+ out["top_p"] = payload["top_p"]
203
+ if payload.get("stop"):
204
+ out["stop_sequences"] = payload["stop"] if isinstance(payload["stop"], list) else [payload["stop"]]
205
+ if isinstance(payload.get("stream"), bool):
206
+ out["stream"] = payload["stream"]
207
+
208
+ # Tools: OpenAI {type:function, function:{...}} -> Anthropic schema.
209
+ # Tools already in Anthropic shape ({name, input_schema}) pass through untouched.
210
+ tools = payload.get("tools")
211
+ if isinstance(tools, list) and tools:
212
+ ant_tools = []
213
+ for t in tools:
214
+ if not isinstance(t, dict):
215
+ continue
216
+ if isinstance(t.get("input_schema"), dict) and t.get("name"):
217
+ at = dict(t)
218
+ else:
219
+ fn = t.get("function") if isinstance(t.get("function"), dict) else t
220
+ name = fn.get("name")
221
+ if not name:
222
+ continue
223
+ at = {
224
+ "name": name,
225
+ "description": fn.get("description") or "",
226
+ "input_schema": fn.get("parameters") if isinstance(fn.get("parameters"), dict) else {"type": "object", "properties": {}},
227
+ }
228
+ if isinstance(t.get("cache_control"), dict):
229
+ at["cache_control"] = t["cache_control"]
230
+ ant_tools.append(at)
231
+ if ant_tools:
232
+ out["tools"] = ant_tools
233
+ tc = payload.get("tool_choice")
234
+ if tc == "auto" or (isinstance(tc, dict) and tc.get("type") == "auto"):
235
+ out["tool_choice"] = {"type": "auto"}
236
+ elif tc == "required" or (isinstance(tc, dict) and tc.get("type") == "required"):
237
+ out["tool_choice"] = {"type": "any"}
238
+ elif isinstance(tc, dict) and tc.get("type") == "function":
239
+ fname = (tc.get("function") or {}).get("name")
240
+ if fname:
241
+ out["tool_choice"] = {"type": "tool", "name": fname}
242
+
243
+ for k in _OPENAI_ONLY_FIELDS:
244
+ out.pop(k, None)
245
+ return out
246
+
247
+
248
+ def _translate_anthropic_json_to_openai(resp_json: Dict[str, Any], fallback_model: str = "") -> Dict[str, Any]:
249
+ """Converts a non-streaming Anthropic /v1/messages response into an OpenAI chat.completion."""
250
+ if not isinstance(resp_json, dict) or resp_json.get("type") not in (None, "message"):
251
+ return resp_json # already OpenAI-shaped or unknown envelope: pass through
252
+ blocks = resp_json.get("content") if isinstance(resp_json.get("content"), list) else []
253
+ text_parts: List[str] = []
254
+ tool_calls = []
255
+ for blk in blocks:
256
+ if not isinstance(blk, dict):
257
+ continue
258
+ if blk.get("type") == "text" and isinstance(blk.get("text"), str):
259
+ text_parts.append(blk["text"])
260
+ elif blk.get("type") == "tool_use":
261
+ tool_calls.append({
262
+ "id": blk.get("id") or f"call_{blk.get('name', 'tool')}",
263
+ "type": "function",
264
+ "function": {
265
+ "name": blk.get("name") or "unknown",
266
+ "arguments": json.dumps(blk.get("input") or {}, ensure_ascii=False),
267
+ },
268
+ })
269
+ usage = resp_json.get("usage") or {}
270
+ in_tok = int(usage.get("input_tokens") or 0)
271
+ out_tok = int(usage.get("output_tokens") or 0)
272
+ cache_read = int(usage.get("cache_read_input_tokens") or 0)
273
+ finish = _ANTHROPIC_FINISH_MAP.get(resp_json.get("stop_reason"), "stop" if resp_json.get("stop_reason") else None)
274
+ message: Dict[str, Any] = {"role": "assistant", "content": "\n\n".join(text_parts) if text_parts else None}
275
+ if tool_calls:
276
+ message["tool_calls"] = tool_calls
277
+ translated = {
278
+ "id": resp_json.get("id") or f"chatcmpl-{int(time.time() * 1000)}",
279
+ "object": "chat.completion",
280
+ "created": int(time.time()),
281
+ "model": resp_json.get("model") or fallback_model,
282
+ "choices": [{"index": 0, "message": message, "finish_reason": finish}],
283
+ "usage": {
284
+ "prompt_tokens": in_tok,
285
+ "completion_tokens": out_tok,
286
+ "total_tokens": in_tok + out_tok,
287
+ "prompt_tokens_details": {"cached_tokens": cache_read},
288
+ },
289
+ }
290
+ return translated
291
+
292
+
293
+ def _translate_anthropic_error_body(err_bytes: bytes) -> bytes:
294
+ """Maps an Anthropic error envelope {type:error,error:{type,message}} onto the OpenAI one."""
295
+ try:
296
+ data = json.loads(err_bytes.decode("utf-8"))
297
+ if isinstance(data, dict) and isinstance(data.get("error"), dict) and data.get("type") == "error":
298
+ inner = data["error"]
299
+ return json.dumps({"error": {"message": inner.get("message", "Upstream error"), "type": inner.get("type", "api_error"), "code": None}}).encode("utf-8")
300
+ except Exception:
301
+ pass
302
+ return err_bytes
303
+
304
+
305
+ class _AnthropicSSETranslator:
306
+ """Converts an Anthropic /v1/messages SSE event stream into OpenAI chat.completion.chunk SSE lines."""
307
+
308
+ def __init__(self, model: str = ""):
309
+ self.model = model or "claude"
310
+ self._buf = b""
311
+ self._tool_blocks: Dict[int, Dict[str, Any]] = {}
312
+ self._chunk_id = f"chatcmpl-{int(time.time() * 1000)}"
313
+ self._done = False
314
+ self._usage_in = 0
315
+
316
+ def _chunk(self, delta: Dict[str, Any], finish: Any = None) -> bytes:
317
+ payload = {
318
+ "id": self._chunk_id,
319
+ "object": "chat.completion.chunk",
320
+ "created": int(time.time()),
321
+ "model": self.model,
322
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
323
+ }
324
+ return (b"data: " + json.dumps(payload, ensure_ascii=False).encode("utf-8") + b"\n\n")
325
+
326
+ def _handle_event(self, event: str, data: Dict[str, Any]) -> bytes:
327
+ out = b""
328
+ if event == "message_start":
329
+ msg = data.get("message") or {}
330
+ if msg.get("model"):
331
+ self.model = msg["model"]
332
+ self._usage_in = int((msg.get("usage") or {}).get("input_tokens") or 0)
333
+ out += self._chunk({"role": "assistant", "content": ""})
334
+ elif event == "content_block_start":
335
+ blk = data.get("content_block") or {}
336
+ if blk.get("type") == "tool_use":
337
+ idx = int(data.get("index") or 0)
338
+ self._tool_blocks[idx] = {"id": blk.get("id") or "toolu_call", "name": blk.get("name") or "unknown"}
339
+ out += self._chunk({"tool_calls": [{"index": idx, "id": self._tool_blocks[idx]["id"], "type": "function", "function": {"name": self._tool_blocks[idx]["name"], "arguments": ""}}]})
340
+ elif event == "content_block_delta":
341
+ delta = data.get("delta") or {}
342
+ if delta.get("type") == "text_delta" and isinstance(delta.get("text"), str):
343
+ out += self._chunk({"content": delta["text"]})
344
+ elif delta.get("type") == "input_json_delta":
345
+ idx = int(data.get("index") or 0)
346
+ out += self._chunk({"tool_calls": [{"index": idx, "function": {"arguments": delta.get("partial_json") or ""}}]})
347
+ elif event == "message_delta":
348
+ delta = data.get("delta") or {}
349
+ finish = _ANTHROPIC_FINISH_MAP.get(delta.get("stop_reason"))
350
+ if finish or data.get("usage"):
351
+ out += self._chunk({}, finish=finish)
352
+ elif event == "message_stop" and not self._done:
353
+ self._done = True
354
+ out += b"data: [DONE]\n\n"
355
+ return out
356
+
357
+ def feed(self, chunk: bytes) -> bytes:
358
+ """Feeds raw upstream bytes; returns translated OpenAI SSE bytes (may be empty)."""
359
+ if not chunk:
360
+ return b""
361
+ self._buf += chunk
362
+ out = b""
363
+ while True:
364
+ nl = self._buf.find(b"\n")
365
+ if nl < 0:
366
+ break
367
+ line = self._buf[:nl].rstrip(b"\r")
368
+ self._buf = self._buf[nl + 1:]
369
+ if not line:
370
+ continue
371
+ if line.startswith(b"event:"):
372
+ self._pending_event = line[6:].strip().decode("utf-8", "replace")
373
+ elif line.startswith(b"data:"):
374
+ try:
375
+ data = json.loads(line[5:].strip().decode("utf-8"))
376
+ except Exception:
377
+ continue
378
+ if isinstance(data, dict):
379
+ out += self._handle_event(getattr(self, "_pending_event", ""), data)
380
+ return out
381
+
382
+ def flush(self) -> bytes:
383
+ """Emits a final [DONE] if the upstream stream ended without message_stop."""
384
+ if self._done:
385
+ return b""
386
+ self._done = True
387
+ return self._chunk({}, finish="stop") + b"data: [DONE]\n\n"
388
+
389
+
66
390
  class TokenSafeProxyHandler(BaseHTTPRequestHandler):
67
391
  """Handles HTTP requests and proxies /v1/chat/completions with token optimization."""
68
392
 
@@ -324,6 +648,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
324
648
  payload["tools"], provider=provider, inject_cache_control=False
325
649
  )
326
650
 
651
+ if provider == "anthropic":
652
+ payload = _translate_openai_payload_to_anthropic(payload)
653
+
327
654
  headers = {"Content-Type": "application/json"}
328
655
  if provider == "anthropic":
329
656
  x_api_key = self.headers.get("x-api-key", "") if hasattr(self.headers, "get") else ""
@@ -357,6 +684,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
357
684
  if is_stream:
358
685
  self.send_header("Cache-Control", "no-cache")
359
686
  self.end_headers()
687
+ sse_t = _AnthropicSSETranslator(str(payload.get("model") or "")) if provider == "anthropic" else None
360
688
  reader = getattr(resp, "read1", None) or resp.read
361
689
  while True:
362
690
  try:
@@ -364,15 +692,33 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
364
692
  except TypeError:
365
693
  chunk = resp.read()
366
694
  if chunk:
367
- self.wfile.write(chunk)
368
- self.wfile.flush()
695
+ out = sse_t.feed(chunk) if sse_t else chunk
696
+ if out:
697
+ self.wfile.write(out)
698
+ self.wfile.flush()
369
699
  break
370
700
  if not chunk:
371
701
  break
372
- self.wfile.write(chunk)
373
- self.wfile.flush()
702
+ out = sse_t.feed(chunk) if sse_t else chunk
703
+ if out:
704
+ self.wfile.write(out)
705
+ self.wfile.flush()
706
+ if sse_t:
707
+ tail = sse_t.flush()
708
+ if tail:
709
+ self.wfile.write(tail)
710
+ self.wfile.flush()
374
711
  else:
375
712
  resp_data = resp.read()
713
+ if provider == "anthropic":
714
+ try:
715
+ raw_json = json.loads(resp_data.decode("utf-8"))
716
+ resp_data = json.dumps(
717
+ _translate_anthropic_json_to_openai(raw_json, str(payload.get("model") or "")),
718
+ ensure_ascii=False,
719
+ ).encode("utf-8")
720
+ except Exception:
721
+ pass
376
722
  self.send_header("Content-Length", str(len(resp_data)))
377
723
  self.end_headers()
378
724
  self.wfile.write(resp_data)
@@ -401,6 +747,8 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
401
747
  with e:
402
748
  err_body = e.read()
403
749
  ctype = e.headers.get("Content-Type", "application/json") if e.headers else "application/json"
750
+ if provider == "anthropic":
751
+ err_body = _translate_anthropic_error_body(err_body)
404
752
  self.send_response(e.code)
405
753
  self.send_header("Content-Type", ctype)
406
754
  self.send_header("Content-Length", str(len(err_body)))
@@ -228,7 +228,7 @@ class TelemetrySync:
228
228
  current_last_id = last_id
229
229
  headers = {
230
230
  "Content-Type": "application/json",
231
- "User-Agent": "TokenSafe-Sync/2.7.2"
231
+ "User-Agent": "TokenSafe-Sync/2.7.3"
232
232
  }
233
233
  if active_key:
234
234
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "2.7.2"
20
+ CURRENT_VERSION = "2.7.3"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage