tokensafe 4.16.3 → 5.0.0

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.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +1 -1
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2487
  26. package/src/mcp_server.py +11 -5437
  27. package/src/proxy.py +11 -1834
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +21 -18
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +51 -10
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +729 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/{src → tokensafe}/ingress_staging.py +9 -9
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/{src → tokensafe}/read_baseline.py +1 -1
  100. package/{src → tokensafe}/repo_compute.py +1 -1
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -0,0 +1,2075 @@
1
+ """
2
+ Local AI Transparent Proxy for Token Optimizer.
3
+ Intercepts LLM requests from any agent (Cursor, Claude Code, Windsurf, Aider, Cline).
4
+ Performs in-flight prompt compaction, output streaming, tool loop detection, and token tracking.
5
+ Endpoint: http://127.0.0.1:8765/v1
6
+ """
7
+
8
+ import sys
9
+ import os
10
+ import re
11
+ import io
12
+ import json
13
+ import time
14
+ import queue
15
+ import threading
16
+ import urllib.request
17
+ import urllib.error
18
+ import urllib.parse
19
+ from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
20
+ from typing import Dict, Any, List, Optional, Tuple
21
+
22
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
+ sys.path.insert(0, BASE_DIR)
24
+
25
+ from tokensafe.compactor import PromptCompactor
26
+ from tokensafe.metrics import MetricsTracker
27
+ from tokensafe.dashboard import Dashboard
28
+ from tokensafe.secret_redactor import SecretRedactor
29
+ from tokensafe.graph_engine import GraphEngine
30
+ from tokensafe.cache_normalizer import PromptCacheNormalizer
31
+ from tokensafe.governor import ContextGovernor
32
+ from tokensafe.result_ledger import fold_catalog_results, fold_tool_results
33
+ from tokensafe.thinking_fold import fold_aged_thinking
34
+ from tokensafe.tool_pruner import _tool_name, apply_subset, detect_prune_miss
35
+ from tokensafe.paths import resolve_data_dir
36
+
37
+ DEFAULT_PORT = 8765
38
+ def _in_container() -> bool:
39
+ if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):
40
+ return True
41
+ try:
42
+ with open("/proc/1/cgroup", "r", encoding="utf-8") as fh:
43
+ data = fh.read()
44
+ return any(k in data for k in ("docker", "containerd", "kubepods", "podman"))
45
+ except OSError:
46
+ return False
47
+
48
+
49
+ def _resolve_bind_host() -> str:
50
+ """Interface the proxy listens on: loopback unless explicitly widened.
51
+
52
+ TOKENSAFE_HOST is the explicit switch. The generic HOST variable is set by
53
+ many dev setups (HOST=0.0.0.0 for a front-end dev server); honoring it on a
54
+ workstation turned the proxy into a LAN relay that injects the server-side
55
+ API keys. It is still honored inside a container, where the published-port
56
+ mapping is the boundary (the shipped Dockerfile uses it).
57
+ """
58
+ explicit = os.environ.get("TOKENSAFE_HOST", "").strip()
59
+ if explicit:
60
+ return explicit
61
+ legacy = os.environ.get("HOST", "").strip()
62
+ if legacy and _in_container():
63
+ return legacy
64
+ return "127.0.0.1"
65
+
66
+
67
+ DEFAULT_HOST = _resolve_bind_host()
68
+
69
+ _LOOPBACK_ORIGIN_HOSTS = frozenset({"127.0.0.1", "localhost", "0.0.0.0", "::1", "[::1]"})
70
+
71
+
72
+ def _origin_allowed(origin: str, custom_origins: str = "") -> bool:
73
+ """Exact scheme+host match for the browser Origin header (port free on loopback).
74
+
75
+ A `startswith("http://localhost")` test also accepted
76
+ `http://localhost.evil.com`, a host the attacker controls.
77
+ """
78
+ try:
79
+ parsed = urllib.parse.urlsplit(origin.strip())
80
+ except ValueError:
81
+ return False
82
+ scheme = (parsed.scheme or "").lower()
83
+ host = (parsed.hostname or "").lower()
84
+ if not scheme or not host:
85
+ return False
86
+ if scheme == "http" and host in _LOOPBACK_ORIGIN_HOSTS:
87
+ return True
88
+ if scheme == "https" and host == "tokensafe.dev":
89
+ return True
90
+ origin_norm = f"{scheme}://{parsed.netloc.lower()}"
91
+ for allowed in (o.strip() for o in (custom_origins or "").split(",")):
92
+ if not allowed:
93
+ continue
94
+ try:
95
+ a = urllib.parse.urlsplit(allowed)
96
+ except ValueError:
97
+ continue
98
+ if a.scheme and a.netloc and origin_norm == f"{a.scheme.lower()}://{a.netloc.lower()}":
99
+ return True
100
+ return False
101
+ DEFAULT_UPSTREAM = "https://api.deepseek.com/v1"
102
+
103
+ class EventBroadcaster:
104
+ """Thread-safe pub/sub for Server-Sent Events (SSE) streaming."""
105
+ def __init__(self):
106
+ self._subscribers: List[queue.Queue] = []
107
+ self._lock = threading.Lock()
108
+
109
+ def subscribe(self) -> queue.Queue:
110
+ q = queue.Queue(maxsize=50)
111
+ with self._lock:
112
+ self._subscribers.append(q)
113
+ return q
114
+
115
+ def unsubscribe(self, q: queue.Queue):
116
+ with self._lock:
117
+ if q in self._subscribers:
118
+ self._subscribers.remove(q)
119
+
120
+ def publish(self, event_type: str, data: Dict[str, Any]):
121
+ # Live relay: anonymized metadata copy to the cloud live view (best-effort)
122
+ try:
123
+ from tokensafe.live_relay import LIVE_RELAY
124
+ LIVE_RELAY.record(event_type, data if isinstance(data, dict) else {})
125
+ except Exception:
126
+ pass
127
+ payload = f"event: {event_type}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
128
+ with self._lock:
129
+ dead = []
130
+ for q in self._subscribers:
131
+ try:
132
+ q.put_nowait(payload)
133
+ except queue.Full:
134
+ dead.append(q)
135
+ for d in dead:
136
+ self._subscribers.remove(d)
137
+
138
+ BROADCASTER = EventBroadcaster()
139
+
140
+ _CACHE_OBS_MIN_INTERVAL_S = 30.0
141
+ _last_cache_obs_ts = 0.0
142
+ _SESSION_CACHE_WARM: Dict[Tuple[str, str], bool] = {}
143
+ # Set when the last response came back fully uncached on a large prompt: the
144
+ # provider's prompt cache expired (idle gap, model switch, restart). The next
145
+ # request then forces the ledger fold so the cold prompt is billed smaller.
146
+ _COLD_CACHE_PENDING: Dict[Tuple[str, str], bool] = {}
147
+ _CACHE_STATE_LOCK = threading.Lock()
148
+ _DEEP_REASONING_RE = re.compile(
149
+ r"\b(architect|architecture|design|plan|audit|security|migrate|migration|investigate|refactor|root\s+cause)\b"
150
+ r"|архитектур|план|аудит|расследован|безопасност|рефактор",
151
+ re.IGNORECASE,
152
+ )
153
+
154
+
155
+ def _apply_effort_clamp(
156
+ payload: Dict[str, Any],
157
+ messages: List[Dict[str, Any]],
158
+ provider: str,
159
+ ) -> Optional[str]:
160
+ """Clamps reasoning/thinking effort on routine or tool-continuation turns.
161
+
162
+ Z.ai Coding Plan defaults `thinking: enabled` (without explicit effort) to
163
+ `max` effort, inflating expensive output tokens (x16-x24). Tool-result
164
+ continuation turns clamp to `low`; routine non-architectural turns clamp
165
+ to `medium`. Opt-out via TOKENSAFE_EFFORT_CLAMP=0.
166
+ """
167
+ mode = os.environ.get("TOKENSAFE_EFFORT_CLAMP", "1").strip().lower()
168
+ if mode in ("0", "false", "no", "off"):
169
+ return None
170
+ strict = mode == "strict"
171
+
172
+ last_msg = messages[-1] if messages and isinstance(messages[-1], dict) else {}
173
+ last_role = str(last_msg.get("role") or "")
174
+ last_user_text = ""
175
+ for m in reversed(messages or []):
176
+ if isinstance(m, dict) and m.get("role") == "user":
177
+ c = m.get("content")
178
+ if isinstance(c, str):
179
+ last_user_text = c
180
+ elif isinstance(c, list):
181
+ last_user_text = " ".join(
182
+ str(b.get("text") or "") for b in c if isinstance(b, dict) and b.get("text")
183
+ )
184
+ break
185
+
186
+ is_deep = bool(_DEEP_REASONING_RE.search(last_user_text)) or len(last_user_text) >= 600
187
+ if last_role == "tool":
188
+ target_effort = "low"
189
+ elif not is_deep:
190
+ target_effort = "medium"
191
+ else:
192
+ return None
193
+
194
+ if provider == "anthropic":
195
+ thinking_cfg = payload.get("_tokensafe_thinking_cfg") or payload.get("thinking")
196
+ out_cfg = payload.get("_tokensafe_output_config") or payload.get("output_config")
197
+ model_l = str(payload.get("model") or "").lower()
198
+ # Only touch payloads that use thinking/effort or GLM/Claude models.
199
+ if thinking_cfg is None and out_cfg is None and "glm" not in model_l and "claude" not in model_l:
200
+ return None
201
+ out_cfg_dict = dict(out_cfg) if isinstance(out_cfg, dict) else {}
202
+ cur_effort = str(out_cfg_dict.get("effort") or "").strip().lower()
203
+ if cur_effort and cur_effort not in ("high", "max", "xhigh", "ultra", "auto", "adaptive") and not strict:
204
+ return None
205
+ if cur_effort == "high" and not strict and last_role != "tool":
206
+ return None
207
+ out_cfg_dict["effort"] = target_effort
208
+ payload["_tokensafe_output_config"] = out_cfg_dict
209
+ return target_effort
210
+
211
+ if "reasoning_effort" in payload:
212
+ cur_re = str(payload.get("reasoning_effort") or "").strip().lower()
213
+ if cur_re in ("", "high", "xhigh", "max") or strict:
214
+ payload["reasoning_effort"] = target_effort
215
+ return target_effort
216
+ return None
217
+
218
+
219
+ STREAM_USAGE_PROVIDERS = frozenset({"openai", "deepseek", "gemini", "generic"})
220
+
221
+
222
+ def _ensure_stream_usage(payload: Dict[str, Any], provider: str) -> bool:
223
+ """Asks a streaming OpenAI-dialect request to end with a usage chunk.
224
+
225
+ Providers omit usage on `stream: true` unless `stream_options.include_usage`
226
+ is set, which leaves the cold-cache detector blind exactly when it matters.
227
+ Anthropic streams carry usage in `message_delta` already, so they are skipped.
228
+ Returns True when the payload was changed.
229
+ """
230
+ if not isinstance(payload, dict) or not payload.get("stream"):
231
+ return False
232
+ if provider not in STREAM_USAGE_PROVIDERS:
233
+ return False
234
+ if os.environ.get("TOKENSAFE_STREAM_USAGE", "1") in ("0", "false", "False"):
235
+ return False
236
+ stream_opts = payload.get("stream_options")
237
+ if not isinstance(stream_opts, dict):
238
+ stream_opts = {}
239
+ if stream_opts.get("include_usage"):
240
+ return False
241
+ stream_opts["include_usage"] = True
242
+ payload["stream_options"] = stream_opts
243
+ return True
244
+
245
+
246
+ def _record_cache_obs(tracker, provider: str, mutation_kinds: List[str],
247
+ input_tokens: int, cache_read: int, cache_write: int,
248
+ model: str = "", output_tokens: int = 0,
249
+ input_is_uncached: Optional[bool] = None) -> None:
250
+ """CACHE_OBS: per-response KV-cache observation (zero-savings telemetry).
251
+
252
+ Lets the dashboard PROVE cache stability: average cache-hit ratio on
253
+ requests where history-mutation stages fired vs clean requests. Clean
254
+ samples are throttled; every mutated request is recorded — that is the
255
+ signal this metric exists for."""
256
+ global _last_cache_obs_ts
257
+ mutated = bool(mutation_kinds)
258
+ now = time.time()
259
+ if not mutated and (now - _last_cache_obs_ts) < _CACHE_OBS_MIN_INTERVAL_S:
260
+ return
261
+ _last_cache_obs_ts = now
262
+ est_credits = None
263
+ if "glm" in (model or "").lower():
264
+ try:
265
+ from tokensafe.burn_monitor import estimate_zai_credits
266
+ if input_is_uncached is None:
267
+ input_is_uncached = (provider == "anthropic")
268
+ uncached = int(input_tokens or 0) if input_is_uncached else max(0, int(input_tokens or 0) - int(cache_read or 0))
269
+ est_credits = estimate_zai_credits(uncached, int(cache_read or 0), int(output_tokens or 0), model=model)
270
+ except Exception:
271
+ est_credits = None
272
+ try:
273
+ details: Dict[str, Any] = {
274
+ "provider": str(provider),
275
+ "input": int(input_tokens or 0),
276
+ "cache_read": int(cache_read or 0),
277
+ "cache_write": int(cache_write or 0),
278
+ "mutations": list(mutation_kinds or []),
279
+ }
280
+ if model:
281
+ details["model"] = str(model)
282
+ if output_tokens:
283
+ details["output"] = int(output_tokens)
284
+ if est_credits is not None:
285
+ details["est_credits"] = est_credits
286
+ tracker.record_event(
287
+ session_id="proxy_session",
288
+ event_type="CACHE_OBS",
289
+ original_tokens=0,
290
+ optimized_tokens=0,
291
+ details=details,
292
+ measurement="measured",
293
+ )
294
+ except Exception:
295
+ pass
296
+
297
+
298
+ # ---------------------------------------------------------------------------
299
+ # OpenAI <-> Anthropic payload translation.
300
+ # The proxy accepts OpenAI /v1/chat/completions bodies from any agent; when the
301
+ # resolved upstream is Anthropic (/v1/messages) the body, response, SSE stream,
302
+ # and error envelopes must be converted in-flight, otherwise the raw OpenAI
303
+ # shape is rejected by the Anthropic API (missing max_tokens, system role, etc).
304
+ # ---------------------------------------------------------------------------
305
+
306
+ _ANTHROPIC_FINISH_MAP = {
307
+ "end_turn": "stop",
308
+ "stop_sequence": "stop",
309
+ "max_tokens": "length",
310
+ "tool_use": "tool_calls",
311
+ "refusal": "content_filter",
312
+ }
313
+
314
+ _OPENAI_ONLY_FIELDS = (
315
+ "frequency_penalty", "presence_penalty", "logprobs", "top_logprobs", "n",
316
+ "response_format", "seed", "stream_options", "user", "parallel_tool_calls",
317
+ "prompt_cache_key", "logit_bias", "service_tier",
318
+ )
319
+
320
+
321
+ def _blocks_from_content(content: Any, role: str = "user") -> List[Dict[str, Any]]:
322
+ """Converts one OpenAI message content (str or block list) into Anthropic content blocks."""
323
+ blocks: List[Dict[str, Any]] = []
324
+ if isinstance(content, str):
325
+ if content:
326
+ blocks.append({"type": "text", "text": content})
327
+ return blocks
328
+ if not isinstance(content, list):
329
+ return blocks
330
+ for blk in content:
331
+ if not isinstance(blk, dict):
332
+ continue
333
+ btype = blk.get("type")
334
+ # Empty text blocks are rejected by strict Anthropic mirrors (z.ai 1214)
335
+ # and carry no information — drop them at the source.
336
+ if btype == "text" and isinstance(blk.get("text"), str) and blk["text"]:
337
+ nb = {"type": "text", "text": blk["text"]}
338
+ if isinstance(blk.get("cache_control"), dict):
339
+ nb["cache_control"] = blk["cache_control"]
340
+ blocks.append(nb)
341
+ elif btype == "image_url":
342
+ url = (blk.get("image_url") or {}).get("url", "") if isinstance(blk.get("image_url"), dict) else ""
343
+ if url.startswith("data:"):
344
+ head, _, b64 = url.partition(",")
345
+ media = head[5:].split(";", 1)[0] or "image/png"
346
+ if b64:
347
+ blocks.append({"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}})
348
+ elif url:
349
+ blocks.append({"type": "image", "source": {"type": "url", "url": url}})
350
+ elif btype == "_tokensafe_block" and isinstance(blk.get("block"), dict):
351
+ # Anthropic-only block (e.g. `document`) carried through the OpenAI-form
352
+ # pipeline by ingest; a cache breakpoint set on the wrapper moves onto it.
353
+ nb = dict(blk["block"])
354
+ if isinstance(blk.get("cache_control"), dict):
355
+ nb["cache_control"] = blk["cache_control"]
356
+ blocks.append(nb)
357
+ return blocks
358
+
359
+
360
+ def _collapse_plain_text(blocks: List[Dict[str, Any]]) -> Any:
361
+ """Collapses pure-text blocks (no cache_control) back into a plain string —
362
+ Anthropic accepts string content, and it keeps payloads closest to the client's shape."""
363
+ if not blocks or any(b.get("type") != "text" or "cache_control" in b for b in blocks):
364
+ return blocks
365
+ texts = [b.get("text", "") for b in blocks]
366
+ return texts[0] if len(texts) == 1 else "\n\n".join(texts)
367
+
368
+
369
+ def _merge_same_role(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
370
+ """Anthropic requires alternating roles; folds consecutive same-role messages."""
371
+ merged: List[Dict[str, Any]] = []
372
+ for msg in messages:
373
+ if merged and merged[-1].get("role") == msg.get("role"):
374
+ prev = merged[-1]
375
+ prev_c = prev.get("content")
376
+ cur_c = msg.get("content")
377
+ prev_blocks = prev_c if isinstance(prev_c, list) else ([{"type": "text", "text": prev_c}] if prev_c else [])
378
+ cur_blocks = cur_c if isinstance(cur_c, list) else ([{"type": "text", "text": cur_c}] if cur_c else [])
379
+ prev["content"] = prev_blocks + cur_blocks
380
+ else:
381
+ merged.append(msg)
382
+ return merged
383
+
384
+
385
+ def _translate_openai_payload_to_anthropic(payload: Dict[str, Any]) -> Dict[str, Any]:
386
+ """Converts an OpenAI chat-completions payload into an Anthropic /v1/messages payload."""
387
+ src_messages = payload.get("messages") if isinstance(payload.get("messages"), list) else []
388
+
389
+ system_parts: List[Dict[str, Any]] = []
390
+ out_messages: List[Dict[str, Any]] = []
391
+ for msg in src_messages:
392
+ if not isinstance(msg, dict):
393
+ continue
394
+ role = msg.get("role")
395
+ if role in ("system", "developer"):
396
+ for blk in _blocks_from_content(msg.get("content"), role):
397
+ system_parts.append(blk)
398
+ continue
399
+
400
+ if role == "assistant":
401
+ blocks: List[Dict[str, Any]] = _blocks_from_content(msg.get("content"), "assistant")
402
+ thinking = msg.get("_tokensafe_thinking") if isinstance(msg.get("_tokensafe_thinking"), list) else []
403
+ has_tool_use = False
404
+ for tc in (msg.get("tool_calls") or []):
405
+ if not isinstance(tc, dict):
406
+ continue
407
+ has_tool_use = True
408
+ fn = tc.get("function") or {}
409
+ try:
410
+ tool_input = json.loads(fn.get("arguments") or "{}")
411
+ if not isinstance(tool_input, dict):
412
+ tool_input = {"_raw": tool_input}
413
+ except Exception:
414
+ # Self-healing: repair malformed argument JSON instead of
415
+ # silently dropping the tool call's inputs.
416
+ from tokensafe.json_repair import parse_tool_arguments
417
+ tool_input = parse_tool_arguments(fn.get("arguments")) or {}
418
+ blocks.append({
419
+ "type": "tool_use",
420
+ "id": tc.get("id") or "toolu_call",
421
+ "name": fn.get("name") or "unknown",
422
+ "input": tool_input,
423
+ })
424
+ if not blocks and not thinking:
425
+ # An assistant turn with neither text, tool_use, nor thinking is
426
+ # illegal upstream (z.ai answers 1214 "messages parameter illegal").
427
+ continue
428
+ if thinking:
429
+ # Extended-thinking models (GLM via z.ai, Claude): assistant
430
+ # history must carry its thinking blocks back, signature included —
431
+ # thinking first, then text/tool_use. Dropping them (the old
432
+ # ingest behavior) trips strict mirrors with 1214.
433
+ content: Any = thinking + blocks if blocks else list(thinking)
434
+ elif len(blocks) == 1 and blocks[0].get("type") == "text":
435
+ content = _collapse_plain_text(blocks)
436
+ else:
437
+ content = blocks
438
+ out_messages.append({"role": "assistant", "content": content})
439
+ elif role == "tool":
440
+ tc_content = msg.get("content")
441
+ text = tc_content if isinstance(tc_content, str) else json.dumps(tc_content, ensure_ascii=False)
442
+ # tool_result.content goes out as a plain STRING: the Anthropic
443
+ # API accepts both shapes, but the Z.ai /api/anthropic mirror
444
+ # (code 1214 / "Input should be a valid dictionary") rejects
445
+ # the block-list form — proven by live probes 2026-11-18. The list
446
+ # form is used only when the result carries images/documents, which
447
+ # a string cannot hold and which were dropped outright before.
448
+ media = msg.get("_tokensafe_media") if isinstance(msg.get("_tokensafe_media"), list) else []
449
+ result_content: Any = text
450
+ if media:
451
+ result_content = ([{"type": "text", "text": text}] if text else []) + [dict(b) for b in media]
452
+ result_block: Dict[str, Any] = {
453
+ "type": "tool_result",
454
+ "tool_use_id": msg.get("tool_call_id") or "toolu_call",
455
+ "content": result_content,
456
+ }
457
+ if msg.get("_tokensafe_is_error") is True:
458
+ result_block["is_error"] = True
459
+ out_messages.append({"role": "user", "content": [result_block]})
460
+ elif role == "user":
461
+ blocks = _blocks_from_content(msg.get("content"), "user")
462
+ if not blocks:
463
+ # Empty user turns are rejected by strict mirrors — drop instead
464
+ # of emitting {"type":"text","text":""}; adjacent same-role
465
+ # messages are re-merged below, so alternation stays valid.
466
+ continue
467
+ out_messages.append({"role": "user", "content": _collapse_plain_text(blocks)})
468
+
469
+ out: Dict[str, Any] = {
470
+ "model": payload.get("model") or "claude-3-5-sonnet-latest",
471
+ "max_tokens": payload.get("max_tokens") if isinstance(payload.get("max_tokens"), int) and payload["max_tokens"] > 0 else 4096,
472
+ "messages": _merge_same_role(out_messages),
473
+ }
474
+ if system_parts:
475
+ out["system"] = system_parts if len(system_parts) > 1 or system_parts[0].get("cache_control") else system_parts[0]["text"]
476
+ if isinstance(payload.get("temperature"), (int, float)):
477
+ out["temperature"] = payload["temperature"]
478
+ if isinstance(payload.get("top_p"), (int, float)):
479
+ out["top_p"] = payload["top_p"]
480
+ if payload.get("stop"):
481
+ out["stop_sequences"] = payload["stop"] if isinstance(payload["stop"], list) else [payload["stop"]]
482
+ if isinstance(payload.get("stream"), bool):
483
+ out["stream"] = payload["stream"]
484
+
485
+ # Tools: OpenAI {type:function, function:{...}} -> Anthropic schema.
486
+ # Tools already in Anthropic shape ({name, input_schema}) pass through untouched.
487
+ tools = payload.get("tools")
488
+ if isinstance(tools, list) and tools:
489
+ ant_tools = []
490
+ for t in tools:
491
+ if not isinstance(t, dict):
492
+ continue
493
+ if isinstance(t.get("input_schema"), dict) and t.get("name"):
494
+ at = dict(t)
495
+ else:
496
+ fn = t.get("function") if isinstance(t.get("function"), dict) else t
497
+ name = fn.get("name")
498
+ if not name:
499
+ continue
500
+ at = {
501
+ "name": name,
502
+ "description": fn.get("description") or "",
503
+ "input_schema": fn.get("parameters") if isinstance(fn.get("parameters"), dict) else {"type": "object", "properties": {}},
504
+ }
505
+ if isinstance(t.get("cache_control"), dict):
506
+ at["cache_control"] = t["cache_control"]
507
+ ant_tools.append(at)
508
+ if ant_tools:
509
+ out["tools"] = ant_tools
510
+ tc = payload.get("tool_choice")
511
+ if tc == "auto" or (isinstance(tc, dict) and tc.get("type") == "auto"):
512
+ out["tool_choice"] = {"type": "auto"}
513
+ elif tc == "required" or (isinstance(tc, dict) and tc.get("type") == "required"):
514
+ out["tool_choice"] = {"type": "any"}
515
+ elif isinstance(tc, dict) and tc.get("type") == "function":
516
+ fname = (tc.get("function") or {}).get("name")
517
+ if fname:
518
+ out["tool_choice"] = {"type": "tool", "name": fname}
519
+
520
+ for k in _OPENAI_ONLY_FIELDS:
521
+ out.pop(k, None)
522
+ if isinstance(payload.get("_tokensafe_thinking_cfg"), dict):
523
+ out["thinking"] = payload["_tokensafe_thinking_cfg"]
524
+ elif isinstance(payload.get("thinking"), dict):
525
+ out["thinking"] = payload["thinking"]
526
+ if isinstance(payload.get("_tokensafe_output_config"), dict):
527
+ out["output_config"] = payload["_tokensafe_output_config"]
528
+ elif isinstance(payload.get("output_config"), dict):
529
+ out["output_config"] = payload["output_config"]
530
+ return out
531
+
532
+
533
+ def _translate_anthropic_json_to_openai(resp_json: Dict[str, Any], fallback_model: str = "") -> Dict[str, Any]:
534
+ """Converts a non-streaming Anthropic /v1/messages response into an OpenAI chat.completion."""
535
+ if not isinstance(resp_json, dict) or resp_json.get("type") not in (None, "message"):
536
+ return resp_json # already OpenAI-shaped or unknown envelope: pass through
537
+ blocks = resp_json.get("content") if isinstance(resp_json.get("content"), list) else []
538
+ text_parts: List[str] = []
539
+ tool_calls = []
540
+ for blk in blocks:
541
+ if not isinstance(blk, dict):
542
+ continue
543
+ if blk.get("type") == "text" and isinstance(blk.get("text"), str):
544
+ text_parts.append(blk["text"])
545
+ elif blk.get("type") == "tool_use":
546
+ tool_calls.append({
547
+ "id": blk.get("id") or f"call_{blk.get('name', 'tool')}",
548
+ "type": "function",
549
+ "function": {
550
+ "name": blk.get("name") or "unknown",
551
+ "arguments": json.dumps(blk.get("input") or {}, ensure_ascii=False),
552
+ },
553
+ })
554
+ usage = resp_json.get("usage") or {}
555
+ in_tok = int(usage.get("input_tokens") or 0)
556
+ out_tok = int(usage.get("output_tokens") or 0)
557
+ cache_read = int(usage.get("cache_read_input_tokens") or 0)
558
+ finish = _ANTHROPIC_FINISH_MAP.get(resp_json.get("stop_reason"), "stop" if resp_json.get("stop_reason") else None)
559
+ message: Dict[str, Any] = {"role": "assistant", "content": "\n\n".join(text_parts) if text_parts else None}
560
+ if tool_calls:
561
+ message["tool_calls"] = tool_calls
562
+ translated = {
563
+ "id": resp_json.get("id") or f"chatcmpl-{int(time.time() * 1000)}",
564
+ "object": "chat.completion",
565
+ "created": int(time.time()),
566
+ "model": resp_json.get("model") or fallback_model,
567
+ "choices": [{"index": 0, "message": message, "finish_reason": finish}],
568
+ "usage": {
569
+ "prompt_tokens": in_tok,
570
+ "completion_tokens": out_tok,
571
+ "total_tokens": in_tok + out_tok,
572
+ "prompt_tokens_details": {"cached_tokens": cache_read},
573
+ },
574
+ }
575
+ return translated
576
+
577
+
578
+ def _translate_anthropic_error_body(err_bytes: bytes) -> bytes:
579
+ """Maps an Anthropic error envelope {type:error,error:{type,message}} onto the OpenAI one."""
580
+ try:
581
+ data = json.loads(err_bytes.decode("utf-8"))
582
+ if isinstance(data, dict) and isinstance(data.get("error"), dict) and data.get("type") == "error":
583
+ inner = data["error"]
584
+ return json.dumps({"error": {"message": inner.get("message", "Upstream error"), "type": inner.get("type", "api_error"), "code": None}}).encode("utf-8")
585
+ except Exception:
586
+ pass
587
+ return err_bytes
588
+
589
+
590
+ def _translate_openai_error_body_to_anthropic(err_bytes: bytes) -> bytes:
591
+ """Maps an OpenAI error envelope {"error":{message,type}} onto the Anthropic one."""
592
+ try:
593
+ data = json.loads(err_bytes.decode("utf-8"))
594
+ if (
595
+ isinstance(data, dict)
596
+ and isinstance(data.get("error"), dict)
597
+ and data.get("type") != "error" # already Anthropic envelope
598
+ ):
599
+ inner = data["error"]
600
+ return json.dumps({
601
+ "type": "error",
602
+ "error": {"type": str(inner.get("type") or "api_error"), "message": str(inner.get("message") or "Upstream error")},
603
+ }).encode("utf-8")
604
+ except Exception:
605
+ pass
606
+ return err_bytes
607
+
608
+
609
+ _TOOL_RESULT_MEDIA_TYPES = ("image", "document")
610
+
611
+ # Anthropic request headers a client may set that change how upstream reads the
612
+ # body: beta features (extended context, interleaved thinking, OAuth) and the
613
+ # API version. Dropping them made beta-gated requests fail or silently degrade.
614
+ _ANTHROPIC_PASSTHROUGH_HEADERS = ("anthropic-beta", "anthropic-version")
615
+ _ANTHROPIC_DEFAULT_VERSION = "2023-06-01"
616
+
617
+
618
+ def _anthropic_upstream_headers(client_headers: Any, auth_header: str, resolved_key: str) -> Dict[str, str]:
619
+ """Auth and protocol headers for an Anthropic(-compatible) upstream.
620
+
621
+ - `x-api-key` from the client wins.
622
+ - An OAuth access token (Claude subscription, `sk-ant-oat…`) must stay
623
+ `Authorization: Bearer`; re-sending it as `x-api-key` is rejected.
624
+ - Any other bearer value is an API key sent OpenAI-style and is moved to
625
+ `x-api-key`, which is what the Anthropic API expects.
626
+ - `anthropic-beta` / `anthropic-version` are forwarded; the version defaults.
627
+ """
628
+ def _get(name: str) -> str:
629
+ try:
630
+ return str(client_headers.get(name, "") or "") if hasattr(client_headers, "get") else ""
631
+ except Exception:
632
+ return ""
633
+
634
+ out: Dict[str, str] = {}
635
+ x_api_key = _get("x-api-key").strip()
636
+ raw_auth = (auth_header or "").strip()
637
+ bearer = raw_auth[7:].strip() if raw_auth.lower().startswith("bearer ") else raw_auth
638
+ if x_api_key:
639
+ out["x-api-key"] = x_api_key
640
+ elif bearer and bearer.startswith("sk-ant-oat"):
641
+ out["Authorization"] = f"Bearer {bearer}"
642
+ elif bearer:
643
+ out["x-api-key"] = bearer
644
+ elif resolved_key:
645
+ out["x-api-key"] = resolved_key
646
+ for name in _ANTHROPIC_PASSTHROUGH_HEADERS:
647
+ value = _get(name).strip()
648
+ if value:
649
+ out[name] = value
650
+ out.setdefault("anthropic-version", _ANTHROPIC_DEFAULT_VERSION)
651
+ return out
652
+
653
+
654
+ def _upstream_timeout(is_stream: bool) -> float:
655
+ """Socket timeout for the upstream call.
656
+
657
+ Streaming: the gap allowed between chunks. Non-streaming: the whole answer
658
+ arrives at once, so the read waits for the full generation; long or
659
+ extended-thinking completions take minutes, and the old 30 s cut them off as
660
+ `502 Upstream proxy error: timed out`. 600 s matches the official SDKs'
661
+ default; TOKENSAFE_UPSTREAM_TIMEOUT overrides it.
662
+ """
663
+ if is_stream:
664
+ return 120.0
665
+ try:
666
+ return max(30.0, float(os.environ.get("TOKENSAFE_UPSTREAM_TIMEOUT", "600")))
667
+ except (TypeError, ValueError):
668
+ return 600.0
669
+
670
+
671
+ def _strip_anthropic_side_channels(payload: Dict[str, Any]) -> None:
672
+ """Removes ingest-only side-channel keys before an OpenAI-dialect upstream.
673
+
674
+ `_tokensafe_is_error` becomes a visible text marker, because the OpenAI tool
675
+ message has no error flag and the model must still learn the tool failed.
676
+ """
677
+ payload.pop("_tokensafe_thinking_cfg", None)
678
+ payload.pop("_tokensafe_output_config", None)
679
+ for msg in payload.get("messages") or []:
680
+ if not isinstance(msg, dict):
681
+ continue
682
+ msg.pop("_tokensafe_thinking", None)
683
+ msg.pop("_tokensafe_media", None)
684
+ if msg.pop("_tokensafe_is_error", None) and msg.get("role") == "tool":
685
+ body = msg.get("content")
686
+ msg["content"] = "[tool error]\n" + (body if isinstance(body, str) else json.dumps(body, ensure_ascii=False))
687
+ content = msg.get("content")
688
+ if isinstance(content, list):
689
+ kept = [b for b in content if not (isinstance(b, dict) and b.get("type") == "_tokensafe_block")]
690
+ if len(kept) != len(content):
691
+ msg["content"] = kept if kept else ""
692
+
693
+
694
+ def _translate_anthropic_payload_to_openai(payload: Dict[str, Any]) -> Dict[str, Any]:
695
+ """Converts an Anthropic /v1/messages request payload into the OpenAI chat-completions
696
+ shape used by the internal optimization pipeline (ledger fold, governor, cache
697
+ normalizer operate on the OpenAI form)."""
698
+ out_messages: List[Dict[str, Any]] = []
699
+
700
+ def _text_blocks(content: Any) -> str:
701
+ if isinstance(content, str):
702
+ return content
703
+ if isinstance(content, list):
704
+ parts = []
705
+ for b in content:
706
+ if isinstance(b, dict) and isinstance(b.get("text"), str):
707
+ parts.append(b["text"])
708
+ return "\n".join(parts)
709
+ return ""
710
+
711
+ system_text = _text_blocks(payload.get("system"))
712
+ if system_text:
713
+ out_messages.append({"role": "system", "content": system_text})
714
+
715
+ for msg in payload.get("messages") or []:
716
+ if not isinstance(msg, dict):
717
+ continue
718
+ role = msg.get("role")
719
+ content = msg.get("content")
720
+ if role == "assistant":
721
+ text_parts: List[str] = []
722
+ tool_calls = []
723
+ thinking_blocks: List[Dict[str, Any]] = []
724
+ blocks = content if isinstance(content, list) else ([{"type": "text", "text": content}] if isinstance(content, str) else [])
725
+ for blk in blocks:
726
+ if not isinstance(blk, dict):
727
+ continue
728
+ if blk.get("type") == "text" and isinstance(blk.get("text"), str):
729
+ text_parts.append(blk["text"])
730
+ elif blk.get("type") in ("thinking", "redacted_thinking"):
731
+ # Side-channel: extended-thinking blocks must survive the
732
+ # OpenAI-form pipeline untouched so the outbound Anthropic
733
+ # translation can restore them (strict mirrors reject
734
+ # assistant history whose tool_use turns lost their thinking
735
+ # prefix — z.ai 1214 "messages parameter is illegal").
736
+ thinking_blocks.append(blk)
737
+ elif blk.get("type") == "tool_use":
738
+ tool_calls.append({
739
+ "id": blk.get("id") or f"call_{blk.get('name', 'tool')}",
740
+ "type": "function",
741
+ "function": {
742
+ "name": blk.get("name") or "unknown",
743
+ "arguments": json.dumps(blk.get("input") or {}, ensure_ascii=False),
744
+ },
745
+ })
746
+ m: Dict[str, Any] = {"role": "assistant", "content": "\n\n".join(text_parts) if text_parts else None}
747
+ if tool_calls:
748
+ m["tool_calls"] = tool_calls
749
+ if thinking_blocks:
750
+ m["_tokensafe_thinking"] = thinking_blocks
751
+ out_messages.append(m)
752
+ elif role == "user":
753
+ blocks = content if isinstance(content, list) else ([{"type": "text", "text": content}] if isinstance(content, str) else [])
754
+ pending_results: List[Dict[str, Any]] = []
755
+ user_parts: List[Dict[str, Any]] = []
756
+ def _flush_user_parts():
757
+ if not user_parts:
758
+ return
759
+ if all(p.get("type") == "text" for p in user_parts):
760
+ pending_results.append({"role": "user", "content": "\n".join(p.get("text", "") for p in user_parts)})
761
+ else:
762
+ pending_results.append({"role": "user", "content": list(user_parts)})
763
+ user_parts.clear()
764
+
765
+ for blk in blocks:
766
+ if not isinstance(blk, dict):
767
+ continue
768
+ btype = blk.get("type")
769
+ if btype == "tool_result":
770
+ _flush_user_parts()
771
+ tc = blk.get("content")
772
+ text = tc if isinstance(tc, str) else _text_blocks(tc) if isinstance(tc, list) else json.dumps(tc, ensure_ascii=False)
773
+ tool_msg: Dict[str, Any] = {"role": "tool", "tool_call_id": blk.get("tool_use_id") or "toolu_call", "content": text}
774
+ # Side-channels, restored by the outbound Anthropic translation:
775
+ # is_error tells the model the tool FAILED (without it a failed
776
+ # Bash reads as a success), and image/document blocks inside the
777
+ # result (a Read of a PNG/PDF, a screenshot) have no OpenAI
778
+ # tool-message equivalent. The text pipeline still sees `text`.
779
+ if blk.get("is_error") is True:
780
+ tool_msg["_tokensafe_is_error"] = True
781
+ if isinstance(tc, list):
782
+ media = [b for b in tc if isinstance(b, dict) and b.get("type") in _TOOL_RESULT_MEDIA_TYPES]
783
+ if media:
784
+ tool_msg["_tokensafe_media"] = media
785
+ pending_results.append(tool_msg)
786
+ elif btype == "document" and isinstance(blk.get("source"), dict):
787
+ # No OpenAI chat equivalent: carried verbatim for an Anthropic
788
+ # upstream (and stripped before an OpenAI-dialect one).
789
+ user_parts.append({"type": "_tokensafe_block", "block": blk})
790
+ elif btype == "text" and isinstance(blk.get("text"), str):
791
+ user_parts.append({"type": "text", "text": blk["text"]})
792
+ elif btype == "image" and isinstance(blk.get("source"), dict):
793
+ src = blk["source"]
794
+ if src.get("type") == "base64" and src.get("data"):
795
+ media = src.get("media_type") or "image/png"
796
+ user_parts.append({"type": "image_url", "image_url": {"url": f"data:{media};base64,{src['data']}"}})
797
+ elif src.get("url"):
798
+ user_parts.append({"type": "image_url", "image_url": {"url": src["url"]}})
799
+ _flush_user_parts()
800
+ out_messages.extend(pending_results)
801
+ if not pending_results:
802
+ out_messages.append({"role": "user", "content": ""})
803
+
804
+ out: Dict[str, Any] = {
805
+ "model": payload.get("model") or "gpt-4o-mini",
806
+ "max_tokens": payload.get("max_tokens") if isinstance(payload.get("max_tokens"), int) and payload["max_tokens"] > 0 else 4096,
807
+ "messages": out_messages,
808
+ }
809
+ if isinstance(payload.get("temperature"), (int, float)):
810
+ out["temperature"] = payload["temperature"]
811
+ if isinstance(payload.get("top_p"), (int, float)):
812
+ out["top_p"] = payload["top_p"]
813
+ if payload.get("stop_sequences"):
814
+ out["stop"] = payload["stop_sequences"]
815
+ if isinstance(payload.get("stream"), bool):
816
+ out["stream"] = payload["stream"]
817
+ if isinstance(payload.get("thinking"), dict):
818
+ out["_tokensafe_thinking_cfg"] = payload["thinking"]
819
+ if isinstance(payload.get("output_config"), dict):
820
+ out["_tokensafe_output_config"] = payload["output_config"]
821
+ tools = payload.get("tools")
822
+ if isinstance(tools, list) and tools:
823
+ oai_tools = []
824
+ for t in tools:
825
+ if not isinstance(t, dict) or not t.get("name"):
826
+ continue
827
+ if isinstance(t.get("parameters"), dict) and t.get("function") is None:
828
+ # already OpenAI-shaped
829
+ oai_tools.append(t)
830
+ continue
831
+ oai_tools.append({
832
+ "type": "function",
833
+ "function": {
834
+ "name": t["name"],
835
+ "description": t.get("description") or "",
836
+ "parameters": t.get("input_schema") if isinstance(t.get("input_schema"), dict) else {"type": "object", "properties": {}},
837
+ },
838
+ })
839
+ if oai_tools:
840
+ out["tools"] = oai_tools
841
+ tc = payload.get("tool_choice")
842
+ if tc == "auto" or (isinstance(tc, dict) and tc.get("type") == "auto"):
843
+ out["tool_choice"] = "auto"
844
+ elif tc == "none" or (isinstance(tc, dict) and tc.get("type") == "none"):
845
+ out["tool_choice"] = "none"
846
+ elif tc == "required" or (isinstance(tc, dict) and tc.get("type") == "any"):
847
+ out["tool_choice"] = "required"
848
+ elif isinstance(tc, dict) and tc.get("type") == "tool" and tc.get("name"):
849
+ out["tool_choice"] = {"type": "function", "function": {"name": tc["name"]}}
850
+ return out
851
+
852
+
853
+ def _translate_openai_json_to_anthropic(resp_json: Dict[str, Any], fallback_model: str = "") -> Dict[str, Any]:
854
+ """Converts a non-streaming OpenAI chat.completion into an Anthropic /v1/messages response."""
855
+ if not isinstance(resp_json, dict) or resp_json.get("object") not in (None, "chat.completion"):
856
+ return resp_json # already Anthropic-shaped or unknown envelope
857
+ choice = (resp_json.get("choices") or [{}])[0]
858
+ msg = choice.get("message") or {}
859
+ blocks: List[Dict[str, Any]] = []
860
+ if isinstance(msg.get("content"), str) and msg["content"]:
861
+ blocks.append({"type": "text", "text": msg["content"]})
862
+ for tc in msg.get("tool_calls") or []:
863
+ if not isinstance(tc, dict):
864
+ continue
865
+ fn = tc.get("function") or {}
866
+ try:
867
+ tool_input = json.loads(fn.get("arguments") or "{}")
868
+ if not isinstance(tool_input, dict):
869
+ tool_input = {"_raw": tool_input}
870
+ except Exception:
871
+ tool_input = {"_raw": fn.get("arguments")}
872
+ blocks.append({"type": "tool_use", "id": tc.get("id") or "toolu_call", "name": fn.get("name") or "unknown", "input": tool_input})
873
+ if not blocks:
874
+ blocks = [{"type": "text", "text": ""}]
875
+ usage = resp_json.get("usage") or {}
876
+ finish = choice.get("finish_reason")
877
+ stop_reason = {"stop": "end_turn", "length": "max_tokens", "tool_calls": "tool_use"}.get(finish, "end_turn" if finish else None)
878
+ out: Dict[str, Any] = {
879
+ "id": resp_json.get("id") or f"msg_{int(time.time() * 1000)}",
880
+ "type": "message",
881
+ "role": "assistant",
882
+ "model": resp_json.get("model") or fallback_model,
883
+ "content": blocks,
884
+ "stop_reason": stop_reason,
885
+ "usage": {
886
+ "input_tokens": int(usage.get("prompt_tokens") or 0),
887
+ "output_tokens": int(usage.get("completion_tokens") or 0),
888
+ },
889
+ }
890
+ return out
891
+
892
+
893
+ class _OpenAISSEToAnthropicTranslator:
894
+ """Converts an OpenAI chat.completion.chunk SSE stream into Anthropic /v1/messages SSE events."""
895
+
896
+ def __init__(self, model: str = ""):
897
+ self.model = model or "claude"
898
+ self._buf = b""
899
+ self._started = False
900
+ self._text_open = False
901
+ self._tool_open: Dict[int, int] = {}
902
+ self._active_tool_idx: Optional[int] = None
903
+ self._block_index = -1
904
+ self._msg_id = f"msg_{int(time.time() * 1000)}"
905
+ self._done = False
906
+ self._finished = False
907
+ self._usage_out = 0
908
+
909
+ def _event(self, name: str, data: Dict[str, Any]) -> bytes:
910
+ return (f"event: {name}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n").encode("utf-8")
911
+
912
+ def _start_message(self) -> bytes:
913
+ self._started = True
914
+ return self._event("message_start", {
915
+ "type": "message_start",
916
+ "message": {
917
+ "id": self._msg_id, "type": "message", "role": "assistant",
918
+ "model": self.model, "content": [],
919
+ "usage": {"input_tokens": 0, "output_tokens": 0},
920
+ },
921
+ })
922
+
923
+ def _close_open_blocks(self) -> bytes:
924
+ out = b""
925
+ if self._text_open:
926
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._text_block_idx})
927
+ self._text_open = False
928
+ if self._active_tool_idx is not None and self._active_tool_idx in self._tool_open:
929
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._tool_open[self._active_tool_idx]})
930
+ self._active_tool_idx = None
931
+ return out
932
+
933
+ def _handle_chunk(self, chunk: Dict[str, Any]) -> bytes:
934
+ out = b""
935
+ if not self._started:
936
+ out += self._start_message()
937
+ choices = chunk.get("choices") or []
938
+ choice = choices[0] if choices else {}
939
+ delta = choice.get("delta") or {}
940
+ if isinstance(delta.get("content"), str) and delta["content"]:
941
+ if not self._text_open:
942
+ if self._active_tool_idx is not None:
943
+ out += self._close_open_blocks()
944
+ self._block_index += 1
945
+ self._text_block_idx = self._block_index
946
+ out += self._event("content_block_start", {"type": "content_block_start", "index": self._text_block_idx, "content_block": {"type": "text", "text": ""}})
947
+ self._text_open = True
948
+ out += self._event("content_block_delta", {"type": "content_block_delta", "index": self._text_block_idx, "delta": {"type": "text_delta", "text": delta["content"]}})
949
+ for tc in delta.get("tool_calls") or []:
950
+ if not isinstance(tc, dict):
951
+ continue
952
+ idx = int(tc.get("index") or 0)
953
+ if idx not in self._tool_open:
954
+ out += self._close_open_blocks()
955
+ self._block_index += 1
956
+ blk_idx = self._block_index
957
+ self._tool_open[idx] = blk_idx
958
+ self._active_tool_idx = idx
959
+ fn = tc.get("function") or {}
960
+ out += self._event("content_block_start", {
961
+ "type": "content_block_start", "index": blk_idx,
962
+ "content_block": {"type": "tool_use", "id": tc.get("id") or f"toolu_{idx}", "name": fn.get("name") or "unknown", "input": {}},
963
+ })
964
+ else:
965
+ blk_idx = self._tool_open[idx]
966
+ fn = tc.get("function") or {}
967
+ if fn.get("arguments"):
968
+ out += self._event("content_block_delta", {"type": "content_block_delta", "index": blk_idx, "delta": {"type": "input_json_delta", "partial_json": fn["arguments"]}})
969
+ finish = choice.get("finish_reason")
970
+ usage = chunk.get("usage") or {}
971
+ if usage.get("completion_tokens"):
972
+ self._usage_out = int(usage["completion_tokens"])
973
+ if finish and not self._finished:
974
+ self._finished = True
975
+ out += self._close_open_blocks()
976
+ stop_reason = {"stop": "end_turn", "length": "max_tokens", "tool_calls": "tool_use"}.get(finish, "end_turn")
977
+ out += self._event("message_delta", {
978
+ "type": "message_delta",
979
+ "delta": {"stop_reason": stop_reason, "stop_sequence": None},
980
+ "usage": {"output_tokens": self._usage_out},
981
+ })
982
+ return out
983
+
984
+ def feed(self, chunk: bytes) -> bytes:
985
+ if not chunk:
986
+ return b""
987
+ self._buf += chunk
988
+ out = b""
989
+ while True:
990
+ nl = self._buf.find(b"\n")
991
+ if nl < 0:
992
+ break
993
+ line = self._buf[:nl].rstrip(b"\r")
994
+ self._buf = self._buf[nl + 1:]
995
+ if not line:
996
+ continue
997
+ if not line.startswith(b"data:"):
998
+ continue
999
+ body = line[5:].strip()
1000
+ if body == b"[DONE]":
1001
+ if not self._done:
1002
+ self._done = True
1003
+ out += self._close_open_blocks()
1004
+ if not self._finished:
1005
+ self._finished = True
1006
+ out += self._event("message_delta", {
1007
+ "type": "message_delta",
1008
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
1009
+ "usage": {"output_tokens": self._usage_out},
1010
+ })
1011
+ out += self._event("message_stop", {"type": "message_stop"})
1012
+ continue
1013
+ try:
1014
+ data = json.loads(body.decode("utf-8"))
1015
+ except Exception:
1016
+ continue
1017
+ if isinstance(data, dict):
1018
+ out += self._handle_chunk(data)
1019
+ return out
1020
+
1021
+ def flush(self) -> bytes:
1022
+ """Emits final Anthropic close events if the upstream ended abruptly."""
1023
+ if self._done and self._started:
1024
+ return b""
1025
+ out = b""
1026
+ if not self._started:
1027
+ out += self._start_message()
1028
+ out += self._close_open_blocks()
1029
+ if not self._done:
1030
+ out += self._event("message_delta", {
1031
+ "type": "message_delta",
1032
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
1033
+ "usage": {"output_tokens": self._usage_out},
1034
+ })
1035
+ out += self._event("message_stop", {"type": "message_stop"})
1036
+ self._done = True
1037
+ return out
1038
+
1039
+
1040
+ class _AnthropicSSETranslator:
1041
+ """Converts an Anthropic /v1/messages SSE event stream into OpenAI chat.completion.chunk SSE lines."""
1042
+
1043
+ def __init__(self, model: str = ""):
1044
+ self.model = model or "claude"
1045
+ self._buf = b""
1046
+ self._tool_blocks: Dict[int, Dict[str, Any]] = {}
1047
+ self._chunk_id = f"chatcmpl-{int(time.time() * 1000)}"
1048
+ self._done = False
1049
+ self._usage_in = 0
1050
+
1051
+ def _chunk(self, delta: Dict[str, Any], finish: Any = None) -> bytes:
1052
+ payload = {
1053
+ "id": self._chunk_id,
1054
+ "object": "chat.completion.chunk",
1055
+ "created": int(time.time()),
1056
+ "model": self.model,
1057
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
1058
+ }
1059
+ return (b"data: " + json.dumps(payload, ensure_ascii=False).encode("utf-8") + b"\n\n")
1060
+
1061
+ def _touch_proxy_model_state(self, model: str) -> None:
1062
+ """Persists the last-seen model so hook-side attribution can read it:
1063
+ adapters resolve event models from ~/.tokensafe/data/proxy_state.json
1064
+ because lifecycle hosts never pass the model to hooks. Throttled to one
1065
+ write per 30s (or on model change); never raises."""
1066
+ now = time.time()
1067
+ if model == getattr(self, "_model_state_model", "") and now - getattr(self, "_model_state_ts", 0.0) < 30.0:
1068
+ return
1069
+ try:
1070
+ from tokensafe.paths import resolve_data_dir
1071
+ state_path = os.path.join(resolve_data_dir(), "proxy_state.json")
1072
+ tmp = f"{state_path}.tmp.{os.getpid()}"
1073
+ with open(tmp, "w", encoding="utf-8") as f:
1074
+ json.dump({"model": str(model or "")[:64], "ts": now}, f)
1075
+ os.replace(tmp, state_path)
1076
+ self._model_state_ts = now
1077
+ self._model_state_model = model
1078
+ except Exception:
1079
+ pass
1080
+
1081
+ def _handle_event(self, event: str, data: Dict[str, Any]) -> bytes:
1082
+ out = b""
1083
+ if event == "message_start":
1084
+ msg = data.get("message") or {}
1085
+ if msg.get("model"):
1086
+ self.model = msg["model"]
1087
+ self._touch_proxy_model_state(str(self.model))
1088
+ self._usage_in = int((msg.get("usage") or {}).get("input_tokens") or 0)
1089
+ out += self._chunk({"role": "assistant", "content": ""})
1090
+ elif event == "content_block_start":
1091
+ blk = data.get("content_block") or {}
1092
+ if blk.get("type") == "tool_use":
1093
+ idx = int(data.get("index") or 0)
1094
+ self._tool_blocks[idx] = {"id": blk.get("id") or "toolu_call", "name": blk.get("name") or "unknown"}
1095
+ out += self._chunk({"tool_calls": [{"index": idx, "id": self._tool_blocks[idx]["id"], "type": "function", "function": {"name": self._tool_blocks[idx]["name"], "arguments": ""}}]})
1096
+ elif event == "content_block_delta":
1097
+ delta = data.get("delta") or {}
1098
+ if delta.get("type") == "text_delta" and isinstance(delta.get("text"), str):
1099
+ out += self._chunk({"content": delta["text"]})
1100
+ elif delta.get("type") == "input_json_delta":
1101
+ idx = int(data.get("index") or 0)
1102
+ out += self._chunk({"tool_calls": [{"index": idx, "function": {"arguments": delta.get("partial_json") or ""}}]})
1103
+ elif event == "message_delta":
1104
+ delta = data.get("delta") or {}
1105
+ finish = _ANTHROPIC_FINISH_MAP.get(delta.get("stop_reason"))
1106
+ if finish or data.get("usage"):
1107
+ out += self._chunk({}, finish=finish)
1108
+ elif event == "message_stop" and not self._done:
1109
+ self._done = True
1110
+ out += b"data: [DONE]\n\n"
1111
+ return out
1112
+
1113
+ def feed(self, chunk: bytes) -> bytes:
1114
+ """Feeds raw upstream bytes; returns translated OpenAI SSE bytes (may be empty)."""
1115
+ if not chunk:
1116
+ return b""
1117
+ self._buf += chunk
1118
+ out = b""
1119
+ while True:
1120
+ nl = self._buf.find(b"\n")
1121
+ if nl < 0:
1122
+ break
1123
+ line = self._buf[:nl].rstrip(b"\r")
1124
+ self._buf = self._buf[nl + 1:]
1125
+ if not line:
1126
+ continue
1127
+ if line.startswith(b"event:"):
1128
+ self._pending_event = line[6:].strip().decode("utf-8", "replace")
1129
+ elif line.startswith(b"data:"):
1130
+ try:
1131
+ data = json.loads(line[5:].strip().decode("utf-8"))
1132
+ except Exception:
1133
+ continue
1134
+ if isinstance(data, dict):
1135
+ out += self._handle_event(getattr(self, "_pending_event", ""), data)
1136
+ return out
1137
+
1138
+ def flush(self) -> bytes:
1139
+ """Emits a final [DONE] if the upstream stream ended without message_stop."""
1140
+ if self._done:
1141
+ return b""
1142
+ self._done = True
1143
+ return self._chunk({}, finish="stop") + b"data: [DONE]\n\n"
1144
+
1145
+
1146
+ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1147
+ """Handles HTTP requests and proxies /v1/chat/completions with token optimization."""
1148
+
1149
+ def log_message(self, format, *args):
1150
+ # Mute noisy default server logs
1151
+ pass
1152
+
1153
+ def _validate_origin(self) -> bool:
1154
+ """Protects against DNS rebinding and cross-origin attacks from arbitrary browser origins."""
1155
+ origin = self.headers.get("Origin", "")
1156
+ if origin and not _origin_allowed(origin, os.environ.get("TOKENSAFE_ALLOWED_ORIGINS", "")):
1157
+ self.send_response(403)
1158
+ self.send_header("Content-Type", "application/json")
1159
+ self.end_headers()
1160
+ self.wfile.write(b'{"error": "Forbidden: Untrusted cross-origin request rejected"}')
1161
+ return False
1162
+ return True
1163
+
1164
+ def do_GET(self):
1165
+ if not self._validate_origin():
1166
+ return
1167
+
1168
+ if self.path == "/health":
1169
+ payload_bytes = json.dumps({"status": "active", "proxy": "tokensafe"}).encode("utf-8")
1170
+ self.send_response(200)
1171
+ self.send_header("Content-Type", "application/json")
1172
+ self.send_header("Content-Length", str(len(payload_bytes)))
1173
+ self.end_headers()
1174
+ self.wfile.write(payload_bytes)
1175
+ return
1176
+
1177
+ if self.path in ("/v1/models", "/models"):
1178
+ # Some agent harnesses probe /v1/models on connect before chatting.
1179
+ # The proxy is transparent about upstream models, so we serve a
1180
+ # minimal OpenAI-shaped empty catalog instead of a 404.
1181
+ body = json.dumps({"object": "list", "data": []}).encode("utf-8")
1182
+ self.send_response(200)
1183
+ self.send_header("Content-Type", "application/json")
1184
+ self.send_header("Content-Length", str(len(body)))
1185
+ self.end_headers()
1186
+ self.wfile.write(body)
1187
+ return
1188
+
1189
+ if self.path in ("/", "/dashboard", "/dashboard.html"):
1190
+ tracker = _shared_metrics_tracker()
1191
+ html_bytes = Dashboard(tracker).render_html().encode("utf-8")
1192
+ self.send_response(200)
1193
+ self.send_header("Content-Type", "text/html; charset=utf-8")
1194
+ self.send_header("Content-Length", str(len(html_bytes)))
1195
+ self.end_headers()
1196
+ self.wfile.write(html_bytes)
1197
+
1198
+ elif self.path in ("/metrics", "/api/metrics"):
1199
+ tracker = _shared_metrics_tracker()
1200
+ summary = tracker.get_summary()
1201
+ summary_bytes = json.dumps(summary, indent=2).encode("utf-8")
1202
+ self.send_response(200)
1203
+ self.send_header("Content-Type", "application/json")
1204
+ self.send_header("Content-Length", str(len(summary_bytes)))
1205
+ self.end_headers()
1206
+ self.wfile.write(summary_bytes)
1207
+
1208
+ elif self.path in ("/api/events", "/events"):
1209
+ tracker = _shared_metrics_tracker()
1210
+ self.send_response(200)
1211
+ self.send_header("Content-Type", "text/event-stream")
1212
+ self.send_header("Cache-Control", "no-cache")
1213
+ self.send_header("Connection", "keep-alive")
1214
+ self.send_header("Access-Control-Allow-Origin", "*")
1215
+ self.end_headers()
1216
+
1217
+ q = BROADCASTER.subscribe()
1218
+ try:
1219
+ initial_summary = tracker.get_summary()
1220
+ init_msg = f"event: init\ndata: {json.dumps(initial_summary, ensure_ascii=False)}\n\n"
1221
+ self.wfile.write(init_msg.encode("utf-8"))
1222
+ self.wfile.flush()
1223
+
1224
+ while True:
1225
+ try:
1226
+ msg = q.get(timeout=15.0)
1227
+ self.wfile.write(msg.encode("utf-8"))
1228
+ self.wfile.flush()
1229
+ except queue.Empty:
1230
+ self.wfile.write(b": heartbeat\n\n")
1231
+ self.wfile.flush()
1232
+ except (BrokenPipeError, ConnectionResetError):
1233
+ pass
1234
+ finally:
1235
+ BROADCASTER.unsubscribe(q)
1236
+ return
1237
+
1238
+ else:
1239
+ err_bytes = b'{"error": "Not found"}'
1240
+ self.send_response(404)
1241
+ self.send_header("Content-Type", "application/json")
1242
+ self.send_header("Content-Length", str(len(err_bytes)))
1243
+ self.end_headers()
1244
+ self.wfile.write(err_bytes)
1245
+
1246
+ def do_POST(self):
1247
+ if not self._validate_origin():
1248
+ return
1249
+
1250
+ if self.path.startswith("/v1/chat/completions"):
1251
+ self._touch_proxy_heartbeat()
1252
+ self.handle_chat_completions()
1253
+ elif self.path.startswith("/v1/messages"):
1254
+ # Anthropic-shape ingest (Claude Code points ANTHROPIC_BASE_URL here):
1255
+ # translate to the internal OpenAI form, run the same optimization
1256
+ # pipeline, and translate the response back to Anthropic shape.
1257
+ if not self._ingest_anthropic_body():
1258
+ return
1259
+ self._touch_proxy_heartbeat()
1260
+ self.handle_chat_completions()
1261
+ else:
1262
+ self.send_response(404)
1263
+ self.end_headers()
1264
+
1265
+ def _ingest_anthropic_body(self) -> bool:
1266
+ """Translates the request body from Anthropic /v1/messages shape to the
1267
+ internal OpenAI chat-completions shape. Returns False after sending an
1268
+ error response when the payload is invalid."""
1269
+ try:
1270
+ body = self._read_request_body()
1271
+ payload = json.loads(body.decode("utf-8"))
1272
+ if not isinstance(payload, dict) or not isinstance(payload.get("messages"), list):
1273
+ raise ValueError("JSON body must be an Anthropic messages object")
1274
+ except Exception as e:
1275
+ self._send_json_error(400, f"Invalid /v1/messages payload: {e}")
1276
+ return False
1277
+ try:
1278
+ openai_payload = _translate_anthropic_payload_to_openai(payload)
1279
+ except Exception as e:
1280
+ try:
1281
+ sys.stderr.write(f"[TokenSafe][debug] translate fail body[:800]={json.dumps(payload)[:800]}\n")
1282
+ except Exception:
1283
+ pass
1284
+ self._send_json_error(400, f"Failed to translate Anthropic payload: {e}")
1285
+ return False
1286
+ self._client_shape = "anthropic"
1287
+ # Hand the translated body to handle_chat_completions directly: the
1288
+ # original Content-Length header no longer matches the new bytes.
1289
+ self._ingested_body = json.dumps(openai_payload, ensure_ascii=False).encode("utf-8")
1290
+ return True
1291
+
1292
+ @staticmethod
1293
+ def _touch_proxy_heartbeat():
1294
+ """Marks the proxy as actively serving agent traffic.
1295
+
1296
+ Lifecycle hooks read this marker to skip their own prompt compaction:
1297
+ when the proxy is in the loop it REPLACES the last user message with the
1298
+ TOCP form, so hook-side injection would double-count the same prompt."""
1299
+ try:
1300
+ marker = os.path.join(resolve_data_dir(), ".proxy_active")
1301
+ with open(marker, "w", encoding="utf-8") as f:
1302
+ f.write(str(int(__import__("time").time())))
1303
+ except Exception:
1304
+ pass
1305
+
1306
+ def _read_request_body(self) -> bytes:
1307
+ te = str(self.headers.get("Transfer-Encoding", "")).lower()
1308
+ if "chunked" in te:
1309
+ chunks: List[bytes] = []
1310
+ while True:
1311
+ line = self.rfile.readline()
1312
+ if not line:
1313
+ break
1314
+ size_str = line.split(b";", 1)[0].strip()
1315
+ chunk_size = int(size_str, 16)
1316
+ if chunk_size == 0:
1317
+ while True:
1318
+ trailer = self.rfile.readline()
1319
+ if not trailer or trailer in (b"\r\n", b"\n"):
1320
+ break
1321
+ break
1322
+ chunks.append(self.rfile.read(chunk_size))
1323
+ self.rfile.readline() # trailing CRLF
1324
+ return b"".join(chunks)
1325
+ content_len = max(0, int(self.headers.get("Content-Length", 0)))
1326
+ return self.rfile.read(content_len)
1327
+
1328
+ def _send_json_error(self, status_code: int, message: str):
1329
+ try:
1330
+ sys.stderr.write(f"[TokenSafe] {self.command} {self.path} -> {status_code}: {message}\n")
1331
+ except Exception:
1332
+ pass
1333
+ # Anthropic-dialect clients (ZCode /v1/messages) expect the Anthropic
1334
+ # error envelope; OpenAI-shape clients keep the flat {"error": ...} form.
1335
+ client_shape = getattr(self, "_client_shape", "") or (
1336
+ "anthropic" if self.path.rstrip("/").endswith("/v1/messages") else ""
1337
+ )
1338
+ if client_shape == "anthropic":
1339
+ err_type = "api_error" if status_code >= 500 else "invalid_request_error"
1340
+ err_body: Dict[str, Any] = {"type": "error", "error": {"type": err_type, "message": message}}
1341
+ else:
1342
+ err_body = {"error": message}
1343
+ err_bytes = json.dumps(err_body).encode("utf-8")
1344
+ # Client may have already hung up (BrokenPipeError in the traceback log
1345
+ # used to bury the real cause under a full socketserver dump).
1346
+ try:
1347
+ self.send_response(status_code)
1348
+ self.send_header("Content-Type", "application/json")
1349
+ self.send_header("Content-Length", str(len(err_bytes)))
1350
+ self.end_headers()
1351
+ self.wfile.write(err_bytes)
1352
+ except (BrokenPipeError, ConnectionResetError):
1353
+ self.close_connection = True
1354
+
1355
+ def handle_chat_completions(self):
1356
+ try:
1357
+ body = getattr(self, "_ingested_body", None)
1358
+ if body is None:
1359
+ body = self._read_request_body()
1360
+ payload = json.loads(body.decode("utf-8"))
1361
+ if not isinstance(payload, dict):
1362
+ raise ValueError("JSON body must be an object")
1363
+ except Exception as e:
1364
+ self._send_json_error(400, f"Invalid JSON payload: {e}")
1365
+ return
1366
+
1367
+ proxy_tracker = _shared_metrics_tracker()
1368
+ from tokensafe.license_manager import LicenseManager
1369
+ quota = LicenseManager.check_quota(proxy_tracker)
1370
+ is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
1371
+
1372
+ # 1. Local Secret Redaction: Scrub credentials across all messages before dispatch (always active)
1373
+ messages = payload.get("messages", [])
1374
+ if messages:
1375
+ messages, secrets_scrubbed = SecretRedactor.redact_messages(messages)
1376
+ if secrets_scrubbed > 0:
1377
+ print(f"[TokenSafe] Scrubbed {secrets_scrubbed} sensitive secret(s) from payload before transmission.")
1378
+
1379
+ # Stage-local stats init: kept defined even when the quota gate skips
1380
+ # the stages below (the CACHE_OBS signature reads them afterwards).
1381
+ ledger_stats: Dict[str, Any] = {}
1382
+ think_stats: Dict[str, Any] = {}
1383
+ gov_stats: Dict[str, Any] = {}
1384
+ prompt_mutated = False
1385
+ clamped_effort: Optional[str] = None
1386
+
1387
+ # 1.2 Resolve Multi-Provider Upstream & API Key early so ROI gates and
1388
+ # effort clamping know the exact upstream provider, model, and warm-cache state.
1389
+ auth_header = self.headers.get("Authorization", "")
1390
+ incoming_key = auth_header[7:].strip() if auth_header.lower().startswith("bearer ") else ""
1391
+ if not incoming_key:
1392
+ try:
1393
+ incoming_key = self.headers.get("x-api-key", "") or ""
1394
+ except Exception:
1395
+ incoming_key = ""
1396
+ custom_url = _apply_route_override(incoming_key, os.environ.get("TOKENSAFE_UPSTREAM_URL", ""))
1397
+
1398
+ conf_keys = _load_proxy_config()
1399
+
1400
+ upstream_url, resolved_key = self._resolve_upstream(conf_keys, custom_url)
1401
+ provider = self._detect_provider(upstream_url)
1402
+ client_anthropic = getattr(self, "_client_shape", "") == "anthropic"
1403
+ if client_anthropic and provider == "anthropic" and not upstream_url.rstrip("/").endswith("/v1/messages"):
1404
+ after_host = upstream_url.split("://", 1)[-1]
1405
+ path = "/" + after_host.split("/", 1)[1] if "/" in after_host else ""
1406
+ if not path or path.rstrip("/").endswith("/anthropic"):
1407
+ upstream_url = f"{upstream_url.rstrip('/')}/v1/messages"
1408
+ upstream_model = os.environ.get("TOKENSAFE_UPSTREAM_MODEL", "").strip()
1409
+ if upstream_model:
1410
+ payload["model"] = upstream_model
1411
+
1412
+ active_model = str(payload.get("model") or "")
1413
+ cache_state_key = (_key_fingerprint(incoming_key or resolved_key), active_model)
1414
+ with _CACHE_STATE_LOCK:
1415
+ session_cache_warm = _SESSION_CACHE_WARM.get(cache_state_key)
1416
+ cold_restart = _COLD_CACHE_PENDING.pop(cache_state_key, False)
1417
+ if cold_restart:
1418
+ print("[TokenSafe] Cold prompt cache detected — forcing a history fold to shrink the uncached bill.")
1419
+
1420
+ # 1.5 Tool Result Ledger: fold aged, oversized tool results into compact
1421
+ # anchors + local archive (idempotent via marker; cache-aware ROI gate).
1422
+ if messages and not is_quota_exceeded:
1423
+ try:
1424
+ messages, ledger_stats = fold_tool_results(
1425
+ messages,
1426
+ model=active_model,
1427
+ provider=provider,
1428
+ cache_warm=session_cache_warm,
1429
+ force_fold=cold_restart,
1430
+ )
1431
+ payload["messages"] = messages
1432
+ if ledger_stats.get("folded"):
1433
+ print(
1434
+ f"[TokenSafe] Tool Result Ledger: folded {ledger_stats['folded']} result(s), "
1435
+ f"~{ledger_stats['saved_tokens']} input tokens lighter."
1436
+ )
1437
+ except Exception:
1438
+ pass
1439
+
1440
+ # 1.55 String Catalog Policy: a tool result that is an i18n catalog is
1441
+ # replaced by a digest immediately, regardless of age. This is the
1442
+ # only stage that sees native host reads (read_file), so it runs
1443
+ # even when the license quota is exhausted — it lowers the bill.
1444
+ if messages:
1445
+ try:
1446
+ messages, catalog_stats = fold_catalog_results(messages)
1447
+ payload["messages"] = messages
1448
+ if catalog_stats.get("folded"):
1449
+ print(
1450
+ f"[TokenSafe] String catalogs: folded {catalog_stats['folded']} result(s), "
1451
+ f"~{catalog_stats['saved_tokens']} input tokens lighter."
1452
+ )
1453
+ except Exception:
1454
+ pass
1455
+
1456
+ # 1.6 Aged Thinking Fold (enabled by default; opt-out TOKENSAFE_FOLD_THINKING=0):
1457
+ # collapse extended-thinking payloads of aged assistant turns into
1458
+ # one-line stubs, gated by the same cache-break ROI check.
1459
+ if messages and not is_quota_exceeded:
1460
+ try:
1461
+ messages, think_stats = fold_aged_thinking(
1462
+ messages,
1463
+ model=active_model,
1464
+ provider=provider,
1465
+ cache_warm=session_cache_warm,
1466
+ )
1467
+ payload["messages"] = messages
1468
+ if think_stats.get("folded"):
1469
+ print(
1470
+ f"[TokenSafe] Aged thinking folded: {think_stats['folded']} turn(s), "
1471
+ f"~{think_stats['saved_tokens']} input tokens lighter."
1472
+ )
1473
+ except Exception:
1474
+ pass
1475
+
1476
+ # 2. Ingress Optimization: REPLACE the last message with its TOCP form
1477
+ # ONLY when the latest message is an actual user prompt (never mutate an
1478
+ # older cached user turn mid-tool-loop).
1479
+ target_symbol = None
1480
+ if messages and not is_quota_exceeded and messages[-1].get("role") == "user":
1481
+ msg = messages[-1]
1482
+ if isinstance(msg.get("content"), str):
1483
+ raw_user = msg["content"]
1484
+ staged = None
1485
+ try:
1486
+ from tokensafe.ingress_staging import stage as _stage_ingress
1487
+
1488
+ staged = _stage_ingress(raw_user, agent="proxy", session_id="proxy_session")
1489
+ except Exception:
1490
+ staged = None
1491
+ if staged:
1492
+ # The proxy is the one ingress path that discards the original
1493
+ # in place; the handle is what keeps it recoverable.
1494
+ msg["content"] = staged["context_text"]
1495
+ prompt_mutated = True
1496
+ try:
1497
+ proxy_tracker.record_event(
1498
+ session_id="proxy_session",
1499
+ event_type="PROMPT",
1500
+ original_tokens=staged["original_tokens"],
1501
+ optimized_tokens=staged["injected_tokens"],
1502
+ details={
1503
+ "mode": "proxy_ingress",
1504
+ "hash": staged["hash"],
1505
+ "sections": len(staged["sections"]),
1506
+ "tier": "INGRESS",
1507
+ },
1508
+ measurement="measured",
1509
+ )
1510
+ from tokensafe.telemetry_sync import TelemetrySync
1511
+ TelemetrySync.sync_background(throttle_seconds=5.0)
1512
+ except Exception:
1513
+ pass
1514
+ else:
1515
+ compaction = PromptCompactor.compact(raw_user, enable_distill=False)
1516
+ if compaction["saved_tokens"] > 5:
1517
+ msg["content"] = compaction["compact_text"]
1518
+ prompt_mutated = True
1519
+ try:
1520
+ proxy_tracker.record_event(
1521
+ session_id="proxy_session",
1522
+ event_type="PROMPT",
1523
+ original_tokens=compaction["original_tokens"],
1524
+ optimized_tokens=compaction["compact_tokens"],
1525
+ details={
1526
+ "mode": "proxy_replace",
1527
+ "action": compaction.get("action"),
1528
+ "symbol": compaction.get("symbol"),
1529
+ "tier": compaction.get("tier", "REGEX"),
1530
+ },
1531
+ measurement="measured",
1532
+ )
1533
+ from tokensafe.telemetry_sync import TelemetrySync
1534
+ TelemetrySync.sync_background(throttle_seconds=5.0)
1535
+ except Exception:
1536
+ pass
1537
+ target_symbol = compaction.get("symbol")
1538
+
1539
+ # 3. Automatic Architecture Awareness & OUMV Capability Matrix (deterministic
1540
+ # across turns for the active workspace so KV-cache prefixes stay identical).
1541
+ if messages and not is_quota_exceeded:
1542
+ try:
1543
+ from tokensafe.paths import get_active_workspace
1544
+ from tokensafe.retrofit import format_oumv_workspace_brief
1545
+ ws_root = get_active_workspace()
1546
+ if ws_root:
1547
+ graph = GraphEngine.get_instance(ws_root)
1548
+ banner = graph.format_topology_banner()
1549
+ oumv_brief = format_oumv_workspace_brief(ws_root, include_live=False)
1550
+ first_msg = messages[0]
1551
+ if isinstance(first_msg.get("content"), str) and first_msg.get("role") == "system":
1552
+ blocks = []
1553
+ if banner and "[TokenSafe Architecture" not in first_msg["content"]:
1554
+ blocks.append(banner)
1555
+ if oumv_brief and "[TokenSafe OUMV Workspace Matrix" not in first_msg["content"]:
1556
+ blocks.append(oumv_brief)
1557
+ if blocks:
1558
+ first_msg["content"] = "\n".join(blocks) + "\n" + first_msg["content"]
1559
+ except Exception:
1560
+ pass
1561
+
1562
+ # 4.5 Effort Clamp: reduce Z.ai/Anthropic default `max` effort on
1563
+ # tool-continuation ("low") and routine ("medium") turns.
1564
+ if messages and not is_quota_exceeded:
1565
+ try:
1566
+ clamped_effort = _apply_effort_clamp(payload, messages, provider)
1567
+ if clamped_effort:
1568
+ BROADCASTER.publish("effort_clamp", {"model": active_model, "effort": clamped_effort})
1569
+ except Exception:
1570
+ clamped_effort = None
1571
+
1572
+ # 5. Epoch-Aware Context Governor (runs BEFORE cache normalization so breakpoints stay valid)
1573
+ if messages and not is_quota_exceeded:
1574
+ messages, gov_stats = ContextGovernor.govern_messages(
1575
+ messages,
1576
+ session_id="proxy_session",
1577
+ model=str(payload.get("model") or ""),
1578
+ append_only=True,
1579
+ )
1580
+ payload["messages"] = messages
1581
+ if gov_stats.get("throttled"):
1582
+ BROADCASTER.publish("governor_throttle", gov_stats)
1583
+
1584
+ # 5.5 Session-stable tool pruning (opt-in, TOKENSAFE_TOOL_PRUNING=1):
1585
+ # relevance subset chosen once per pseudo-session and kept
1586
+ # byte-stable for the whole session (KV-cache safe). The agent
1587
+ # still knows ALL its tools — pruned-tool calls still execute;
1588
+ # we only measure the miss rate.
1589
+ sent_tool_names = None
1590
+ if isinstance(payload.get("tools"), list) and payload["tools"] and not is_quota_exceeded:
1591
+ sent_tool_names = {n for n in (_tool_name(t) for t in payload["tools"]) if n}
1592
+ try:
1593
+ pruned_tools, prune_meta = apply_subset(
1594
+ payload["tools"],
1595
+ payload.get("messages") or [],
1596
+ str(payload.get("model") or ""),
1597
+ )
1598
+ if prune_meta.get("applied"):
1599
+ payload["tools"] = pruned_tools
1600
+ sent_tool_names = {n for n in (_tool_name(t) for t in pruned_tools) if n}
1601
+ print(f"[TokenSafe] Tool pruning: {prune_meta.get('pool')} → {prune_meta.get('subset')} tools (session-stable).")
1602
+ except Exception:
1603
+ pass
1604
+
1605
+ # 6. Prompt Cache Prefix & Tool Normalization (multi-breakpoint + deterministic ordering)
1606
+ if not is_quota_exceeded:
1607
+ if messages:
1608
+ messages, cache_meta = PromptCacheNormalizer.normalize_messages(
1609
+ messages,
1610
+ provider=provider,
1611
+ inject_cache_control=(provider == "anthropic"),
1612
+ tools=payload.get("tools") if isinstance(payload.get("tools"), list) else None,
1613
+ )
1614
+ payload["messages"] = messages
1615
+ if cache_meta.get("normalized_tools") is not None:
1616
+ payload["tools"] = cache_meta["normalized_tools"]
1617
+ if provider == "openai" and cache_meta.get("prompt_cache_key"):
1618
+ payload.setdefault("prompt_cache_key", cache_meta["prompt_cache_key"])
1619
+ elif "tools" in payload and isinstance(payload["tools"], list):
1620
+ payload["tools"] = PromptCacheNormalizer.normalize_tools(
1621
+ payload["tools"], provider=provider, inject_cache_control=False
1622
+ )
1623
+
1624
+ # Request mutation signature for cache-stability telemetry: which
1625
+ # history-mutation stages fired on THIS request (the CACHE_OBS panel
1626
+ # splits the cache-hit ratio into mutated vs clean by this list).
1627
+ mutation_kinds = [
1628
+ kind for kind, fired in (
1629
+ ("ledger", bool(ledger_stats.get("folded"))),
1630
+ ("thinking", bool(think_stats.get("folded"))),
1631
+ ("prompt", prompt_mutated),
1632
+ ("governor", bool(gov_stats.get("saved_tokens"))),
1633
+ ) if fired
1634
+ ]
1635
+
1636
+ if provider == "anthropic":
1637
+ # Outbound OpenAI->Anthropic translation is skipped when the CLIENT
1638
+ # itself speaks Anthropic (ingest): the pipeline ran on the internal
1639
+ # OpenAI form, and this puts it back into Anthropic shape for upstream.
1640
+ payload = _translate_openai_payload_to_anthropic(payload)
1641
+ else:
1642
+ # The ingest side-channels are Anthropic-only — never leak them into
1643
+ # an OpenAI-dialect upstream request.
1644
+ _strip_anthropic_side_channels(payload)
1645
+
1646
+ # Ask OpenAI-dialect providers to emit the trailing usage chunk; without
1647
+ # it a streaming session reports no input/cache numbers at all, and the
1648
+ # cold-cache detector stays blind. Must run BEFORE the body is
1649
+ # serialized below — this cost one live-test failure to notice.
1650
+ _ensure_stream_usage(payload, provider)
1651
+
1652
+ headers = {"Content-Type": "application/json", "Accept-Encoding": "identity"}
1653
+ if provider == "anthropic":
1654
+ headers.update(_anthropic_upstream_headers(self.headers, auth_header, resolved_key))
1655
+ elif auth_header:
1656
+ headers["Authorization"] = auth_header
1657
+ elif resolved_key:
1658
+ headers["Authorization"] = f"Bearer {resolved_key}"
1659
+
1660
+ req = urllib.request.Request(
1661
+ upstream_url,
1662
+ data=json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8"),
1663
+ headers=headers
1664
+ )
1665
+
1666
+ is_stream = bool(payload.get("stream"))
1667
+ req_timeout = _upstream_timeout(is_stream)
1668
+ try:
1669
+ with urllib.request.urlopen(req, timeout=req_timeout) as resp:
1670
+ self.send_response(resp.status)
1671
+ for k, v in resp.getheaders():
1672
+ if k.lower() == "content-type":
1673
+ self.send_header(k, v)
1674
+ if is_quota_exceeded:
1675
+ self.send_header("X-TokenSafe-Quota", "exceeded")
1676
+
1677
+ if is_stream:
1678
+ self.send_header("Cache-Control", "no-cache")
1679
+ self.end_headers()
1680
+ # Stream translation matrix:
1681
+ # anthropic upstream + openai client -> Anthropic SSE -> OpenAI chunks
1682
+ # openai upstream + anthropic client -> OpenAI chunks -> Anthropic SSE
1683
+ # otherwise -> byte passthrough
1684
+ sse_t = None
1685
+ if provider == "anthropic" and not client_anthropic:
1686
+ sse_t = _AnthropicSSETranslator(str(payload.get("model") or ""))
1687
+ elif provider != "anthropic" and client_anthropic:
1688
+ sse_t = _OpenAISSEToAnthropicTranslator(str(payload.get("model") or ""))
1689
+ reader = getattr(resp, "read1", None) or resp.read
1690
+ # Best-effort usage capture from the stream tail: Anthropic
1691
+ # reports final usage in the trailing message_delta events.
1692
+ # Bounded tail capture runs for every dialect: with
1693
+ # stream_options.include_usage the final OpenAI chunk (or
1694
+ # the trailing Anthropic message_delta) carries the usage.
1695
+ sse_tail = bytearray()
1696
+ while True:
1697
+ try:
1698
+ chunk = reader(4096)
1699
+ except TypeError:
1700
+ # Defensive fallback for readers without sized reads:
1701
+ # buffer the whole stream, emit once (no streaming).
1702
+ chunk = resp.read()
1703
+ if chunk:
1704
+ out = sse_t.feed(chunk) if sse_t else chunk
1705
+ if out:
1706
+ self.wfile.write(out)
1707
+ self.wfile.flush()
1708
+ break
1709
+ if not chunk:
1710
+ break
1711
+ if sse_tail is not None:
1712
+ sse_tail.extend(chunk)
1713
+ if len(sse_tail) > 65536:
1714
+ del sse_tail[: len(sse_tail) - 65536]
1715
+ out = sse_t.feed(chunk) if sse_t else chunk
1716
+ if out:
1717
+ self.wfile.write(out)
1718
+ self.wfile.flush()
1719
+ if sse_t:
1720
+ tail = sse_t.flush()
1721
+ if tail:
1722
+ self.wfile.write(tail)
1723
+ self.wfile.flush()
1724
+ # Parse trailing usage (non-fatal; non-Anthropic streams skip)
1725
+ try:
1726
+ if sse_t is not None and sse_tail:
1727
+ tail_text = sse_tail.decode("utf-8", "replace")
1728
+ m_usage = re.search(
1729
+ r'"usage":\s*\{[^}]*"(?:cache_read_input_tokens|input_tokens|prompt_tokens)":\s*(\d+)',
1730
+ tail_text,
1731
+ )
1732
+ m_cached = re.search(
1733
+ r'"(?:cached_tokens|cache_read_input_tokens|prompt_cache_hit_tokens)":\s*(\d+)',
1734
+ tail_text,
1735
+ )
1736
+ if m_cached:
1737
+ BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(m_cached.group(1))})
1738
+ elif m_usage:
1739
+ BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": 0})
1740
+ # Cache-stability observation (Anthropic-shape tails):
1741
+ # input/cache fields live in message_start, which the
1742
+ # 64KB tail may evict on very long streams — record
1743
+ # only when at least one real field survived.
1744
+ m_in = re.search(r'"(?:prompt_tokens|input_tokens)":\s*(\d+)', tail_text)
1745
+ m_out = re.search(r'"(?:completion_tokens|output_tokens)":\s*(\d+)', tail_text)
1746
+ m_cw = re.search(r'"cache_creation_input_tokens":\s*(\d+)', tail_text)
1747
+ sse_input = int(m_in.group(1)) if m_in else 0
1748
+ sse_cached = int(m_cached.group(1)) if m_cached else 0
1749
+ sse_out = int(m_out.group(1)) if m_out else 0
1750
+ with _CACHE_STATE_LOCK:
1751
+ _SESSION_CACHE_WARM[cache_state_key] = bool(sse_cached > 0)
1752
+ if sse_input >= 50000 and sse_cached == 0:
1753
+ _COLD_CACHE_PENDING[cache_state_key] = True
1754
+ if m_cached or sse_input > 0:
1755
+ _record_cache_obs(
1756
+ proxy_tracker, provider, mutation_kinds,
1757
+ sse_input,
1758
+ sse_cached,
1759
+ int(m_cw.group(1)) if m_cw else 0,
1760
+ model=active_model,
1761
+ output_tokens=sse_out,
1762
+ input_is_uncached=True,
1763
+ )
1764
+ except Exception:
1765
+ pass
1766
+ else:
1767
+ resp_data = resp.read()
1768
+ if provider == "anthropic" and not client_anthropic:
1769
+ try:
1770
+ raw_json = json.loads(resp_data.decode("utf-8"))
1771
+ resp_data = json.dumps(
1772
+ _translate_anthropic_json_to_openai(raw_json, str(payload.get("model") or "")),
1773
+ ensure_ascii=False,
1774
+ ).encode("utf-8")
1775
+ except Exception:
1776
+ pass
1777
+ elif client_anthropic and provider != "anthropic":
1778
+ try:
1779
+ raw_json = json.loads(resp_data.decode("utf-8"))
1780
+ resp_data = json.dumps(
1781
+ _translate_openai_json_to_anthropic(raw_json, str(payload.get("model") or "")),
1782
+ ensure_ascii=False,
1783
+ ).encode("utf-8")
1784
+ except Exception:
1785
+ pass
1786
+ self.send_header("Content-Length", str(len(resp_data)))
1787
+ self.end_headers()
1788
+ self.wfile.write(resp_data)
1789
+
1790
+ try:
1791
+ resp_json = json.loads(resp_data.decode("utf-8"))
1792
+ usage = resp_json.get("usage") or {}
1793
+ cached = (
1794
+ (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
1795
+ or usage.get("cache_read_input_tokens")
1796
+ or usage.get("prompt_cache_hit_tokens")
1797
+ or 0
1798
+ )
1799
+ # Cache-stability observation (non-stream path: both
1800
+ # Anthropic and OpenAI usage shapes are available).
1801
+ in_tok_obs = int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0)
1802
+ out_tok_obs = int(usage.get("completion_tokens") or usage.get("output_tokens") or 0)
1803
+ with _CACHE_STATE_LOCK:
1804
+ _SESSION_CACHE_WARM[cache_state_key] = bool(int(cached or 0) > 0)
1805
+ if in_tok_obs >= 50000 and int(cached or 0) == 0:
1806
+ _COLD_CACHE_PENDING[cache_state_key] = True
1807
+ _record_cache_obs(
1808
+ proxy_tracker, provider, mutation_kinds,
1809
+ in_tok_obs,
1810
+ int(cached or 0),
1811
+ int(usage.get("cache_creation_input_tokens") or 0),
1812
+ model=active_model,
1813
+ output_tokens=out_tok_obs,
1814
+ input_is_uncached=("input_tokens" in usage and "prompt_tokens" not in usage),
1815
+ )
1816
+ if cached:
1817
+ BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(cached)})
1818
+ # Prune-miss telemetry: model called a tool outside the
1819
+ # sent subset (call still flows to the agent).
1820
+ if sent_tool_names:
1821
+ miss = detect_prune_miss(resp_json, sent_tool_names)
1822
+ if miss:
1823
+ BROADCASTER.publish("prune_miss", {"tool": miss})
1824
+ try:
1825
+ proxy_tracker.record_event(
1826
+ session_id="proxy_session",
1827
+ event_type="TOOL_PRUNE_MISS",
1828
+ original_tokens=0,
1829
+ optimized_tokens=0,
1830
+ details={"tool": miss, "subset_size": len(sent_tool_names)},
1831
+ )
1832
+ except Exception:
1833
+ pass
1834
+ except Exception:
1835
+ pass
1836
+
1837
+ # Broadcast live telemetry update to SSE dashboard subscribers
1838
+ try:
1839
+ summary = proxy_tracker.get_summary()
1840
+ BROADCASTER.publish("stats_update", summary)
1841
+ except Exception:
1842
+ pass
1843
+ except urllib.error.HTTPError as e:
1844
+ with e:
1845
+ err_body = e.read()
1846
+ ctype = e.headers.get("Content-Type", "application/json") if e.headers else "application/json"
1847
+ # Permanent diagnostics: upstream rejections were previously forwarded
1848
+ # to the client without any server-side trace, making incidents like
1849
+ # z.ai 1214 undiagnosable from proxy.log alone.
1850
+ try:
1851
+ sys.stderr.write(
1852
+ f"[TokenSafe] {self.command} {self.path} -> upstream {e.code}: "
1853
+ f"{err_body[:400].decode('utf-8', 'replace')}\n"
1854
+ )
1855
+ if e.code == 400:
1856
+ sys.stderr.write(
1857
+ "[TokenSafe][debug] upstream-400 payload preview: "
1858
+ f"model={payload.get('model')!r} msgs={len(payload.get('messages') or [])} "
1859
+ f"body[:1200]={json.dumps(payload, ensure_ascii=False)[:1200]}\n"
1860
+ )
1861
+ except Exception:
1862
+ pass
1863
+ if provider == "anthropic" and not client_anthropic:
1864
+ err_body = _translate_anthropic_error_body(err_body)
1865
+ elif client_anthropic and provider != "anthropic":
1866
+ err_body = _translate_openai_error_body_to_anthropic(err_body)
1867
+ self.send_response(e.code)
1868
+ self.send_header("Content-Type", ctype)
1869
+ self.send_header("Content-Length", str(len(err_body)))
1870
+ self.end_headers()
1871
+ self.wfile.write(err_body)
1872
+ except Exception as e:
1873
+ self._send_json_error(502, f"Upstream proxy error: {str(e)}")
1874
+
1875
+ @staticmethod
1876
+ def _detect_provider(upstream_url: str) -> str:
1877
+ url = (upstream_url or "").lower()
1878
+ if "anthropic.com" in url:
1879
+ return "anthropic"
1880
+ # Anthropic-compatible mirrors (e.g. Z.ai /api/anthropic[/v1/messages]
1881
+ # coding-plan endpoint): same wire dialect, client x-api-key is forwarded as-is.
1882
+ # Match "/anthropic" as a path SEGMENT, not a substring — a URL like
1883
+ # ".../my-anthropic-proxy/v1/chat/completions" is an OpenAI-dialect host.
1884
+ if re.search(r"/anthropic(/|$)", url):
1885
+ return "anthropic"
1886
+ if "openai.com" in url:
1887
+ return "openai"
1888
+ if "googleapis.com" in url or "generativelanguage" in url:
1889
+ return "gemini"
1890
+ if "deepseek.com" in url:
1891
+ return "deepseek"
1892
+ return "generic"
1893
+
1894
+ @staticmethod
1895
+ def _resolve_upstream(conf_keys: Dict[str, Any], custom_url: str):
1896
+ deepseek_key = os.environ.get("DEEPSEEK_API_KEY", "") or conf_keys.get("deepseek_api_key", "")
1897
+ openai_key = os.environ.get("OPENAI_API_KEY", "") or conf_keys.get("openai_api_key", "")
1898
+ gemini_key = os.environ.get("GEMINI_API_KEY", "") or conf_keys.get("gemini_api_key", "")
1899
+ anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "") or conf_keys.get("anthropic_api_key", "")
1900
+ generic_upstream_key = os.environ.get("TOKENSAFE_UPSTREAM_KEY", "")
1901
+
1902
+ pref = str(conf_keys.get("preferred_provider", "")).lower()
1903
+ if not custom_url:
1904
+ if (pref == "gemini" and gemini_key) or (gemini_key and not deepseek_key and not openai_key):
1905
+ return "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", gemini_key
1906
+ if openai_key and not deepseek_key:
1907
+ return "https://api.openai.com/v1/chat/completions", openai_key
1908
+ if anthropic_key and not deepseek_key:
1909
+ return "https://api.anthropic.com/v1/messages", anthropic_key
1910
+ return "https://api.deepseek.com/chat/completions", (deepseek_key or generic_upstream_key)
1911
+
1912
+ if "openai.com" in custom_url:
1913
+ return custom_url, (openai_key or generic_upstream_key or deepseek_key)
1914
+ if "anthropic.com" in custom_url:
1915
+ return custom_url, (anthropic_key or generic_upstream_key)
1916
+ if "googleapis.com" in custom_url:
1917
+ return custom_url, (gemini_key or generic_upstream_key)
1918
+ return custom_url, (deepseek_key or generic_upstream_key or openai_key)
1919
+
1920
+ def _key_fingerprint(api_key: str) -> str:
1921
+ """Stable fingerprint of a client API key (never store the key itself)."""
1922
+ import hashlib
1923
+ return hashlib.sha256((api_key or "").strip().encode("utf-8")).hexdigest()[:16]
1924
+
1925
+
1926
+ _JSON_FILE_CACHE: Dict[str, Tuple[Tuple[int, int, int, int], Any]] = {}
1927
+ _JSON_FILE_CACHE_LOCK = threading.Lock()
1928
+ _JSON_PARSE_FAILED = object()
1929
+
1930
+
1931
+ def _load_json_file_cached(path: str) -> Any:
1932
+ """Parsed JSON content of `path`, or None when the file is missing or invalid.
1933
+
1934
+ The parse is cached per path and keyed by the file's (device, inode,
1935
+ mtime_ns, size) stamp, so an unchanged file is stat'ed but not re-read;
1936
+ any write or atomic replace changes the stamp and forces a re-parse.
1937
+ Returns a deep copy: callers may mutate the result freely."""
1938
+ import copy
1939
+
1940
+ try:
1941
+ st = os.stat(path)
1942
+ except OSError:
1943
+ with _JSON_FILE_CACHE_LOCK:
1944
+ _JSON_FILE_CACHE.pop(path, None)
1945
+ return None
1946
+ stamp = (st.st_dev, st.st_ino, st.st_mtime_ns, st.st_size)
1947
+ with _JSON_FILE_CACHE_LOCK:
1948
+ entry = _JSON_FILE_CACHE.get(path)
1949
+ if entry is not None and entry[0] == stamp:
1950
+ data = entry[1]
1951
+ else:
1952
+ try:
1953
+ with open(path, "r", encoding="utf-8") as f:
1954
+ data = json.load(f)
1955
+ except Exception:
1956
+ data = _JSON_PARSE_FAILED
1957
+ with _JSON_FILE_CACHE_LOCK:
1958
+ _JSON_FILE_CACHE[path] = (stamp, data)
1959
+ if data is _JSON_PARSE_FAILED:
1960
+ return None
1961
+ return copy.deepcopy(data)
1962
+
1963
+
1964
+ def _load_proxy_config() -> Dict[str, Any]:
1965
+ """The data dir's config.json (provider keys), cached by file stamp."""
1966
+ data = _load_json_file_cached(os.path.join(resolve_data_dir(), "config.json"))
1967
+ return data if isinstance(data, dict) else {}
1968
+
1969
+
1970
+ _SHARED_TRACKER_LOCK = threading.Lock()
1971
+ _SHARED_TRACKER: Optional[Tuple[Tuple[Any, ...], Any]] = None
1972
+
1973
+
1974
+ def _shared_metrics_tracker() -> Any:
1975
+ """One MetricsTracker reused across proxy requests, created lazily.
1976
+
1977
+ Keyed by everything MetricsTracker() reads at construction (the database
1978
+ path from TOKENSAFE_DB_PATH or the data dir, and the retention env), so a
1979
+ changed data dir or env yields a fresh tracker exactly as before. The
1980
+ tracker has no per-request state; request threads are worker threads, so
1981
+ each call opens and closes its own connection (see MetricsTracker)."""
1982
+ global _SHARED_TRACKER
1983
+ db_path = os.environ.get("TOKENSAFE_DB_PATH", os.path.join(resolve_data_dir(), "metrics.db"))
1984
+ key = (
1985
+ MetricsTracker,
1986
+ os.path.abspath(db_path),
1987
+ os.environ.get("TOKENSAFE_RETENTION_DAYS", "30"),
1988
+ os.environ.get("TOKENSAFE_MAX_EVENTS", "5000"),
1989
+ )
1990
+ with _SHARED_TRACKER_LOCK:
1991
+ entry = _SHARED_TRACKER
1992
+ if entry is not None and entry[0] == key:
1993
+ tracker = entry[1]
1994
+ else:
1995
+ tracker = MetricsTracker()
1996
+ _SHARED_TRACKER = (key, tracker)
1997
+ return tracker
1998
+ # A fresh tracker re-creates the schema when the database file was deleted
1999
+ # or emptied; keep that for the reused one (a stat-only no-op otherwise).
2000
+ try:
2001
+ tracker._init_db()
2002
+ except Exception:
2003
+ pass
2004
+ return tracker
2005
+
2006
+
2007
+ def _load_proxy_routes() -> Dict[str, Any]:
2008
+ """Per-agent upstream route table written by the installer
2009
+ (fingerprint -> {upstream_url, label}). Checked per request so routes
2010
+ added by `tokensafe proxy on` are picked up without a daemon restart; the
2011
+ parse is cached until the file's stamp changes."""
2012
+ try:
2013
+ data = _load_json_file_cached(os.path.join(resolve_data_dir(), "proxy_routes.json"))
2014
+ if isinstance(data, dict):
2015
+ return {str(k): v for k, v in data.items() if isinstance(v, dict)}
2016
+ except Exception:
2017
+ pass
2018
+ return {}
2019
+
2020
+
2021
+ def _apply_route_override(incoming_key: str, custom_url: str) -> str:
2022
+ """Returns the upstream URL for this client key: installer-registered route
2023
+ first (one proxy serves several agents with different providers), then the
2024
+ TOKENSAFE_UPSTREAM_URL env, then the default provider resolution."""
2025
+ if incoming_key:
2026
+ route = _load_proxy_routes().get(_key_fingerprint(incoming_key))
2027
+ if isinstance(route, dict) and route.get("upstream_url"):
2028
+ return str(route["upstream_url"])
2029
+ return custom_url
2030
+
2031
+
2032
+ def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
2033
+ # Auto-initialize Knowledge Graph & API Surface on startup
2034
+ hubs_summary = "active"
2035
+ try:
2036
+ graph = GraphEngine.get_instance(os.getcwd())
2037
+ graph.generate_api_surface()
2038
+ god_nodes = graph.get_god_nodes(3)
2039
+ if god_nodes:
2040
+ hubs_summary = ", ".join([f"{g['file']} ({g['dependents']} deps)" for g in god_nodes])
2041
+ except Exception as e:
2042
+ hubs_summary = f"initialized ({e})"
2043
+
2044
+ server_address = (host, port)
2045
+ class _TokenSafeThreadingServer(ThreadingHTTPServer):
2046
+ daemon_threads = True
2047
+ allow_reuse_address = True
2048
+
2049
+ def handle_error(self, request, client_address):
2050
+ # Client hangups (agent cancelled a request mid-stream) are routine
2051
+ # here — keep them out of proxy.log, surface everything else.
2052
+ import sys as _sys
2053
+ exc = _sys.exc_info()[1]
2054
+ if isinstance(exc, (BrokenPipeError, ConnectionResetError, TimeoutError)):
2055
+ return
2056
+ super().handle_error(request, client_address)
2057
+
2058
+ httpd = _TokenSafeThreadingServer(server_address, TokenSafeProxyHandler)
2059
+ display_host = "localhost" if host in ("0.0.0.0", "", "127.0.0.1") else host
2060
+ print(f"\n⚡ TokenSafe Local AI Proxy running on: http://{display_host}:{port} (bound to {host})")
2061
+ print(f" Dashboard: http://{display_host}:{port}/dashboard")
2062
+ print(f" OpenAI-compatible URL: http://{display_host}:{port}/v1")
2063
+ print(f" Auto-Graph: {hubs_summary}")
2064
+ print(f" API Surface: tokensafe-out/API_SURFACE.md")
2065
+ try:
2066
+ httpd.serve_forever()
2067
+ except KeyboardInterrupt:
2068
+ print("\nProxy stopped.")
2069
+
2070
+ def main():
2071
+ port = int(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_PORT
2072
+ run_proxy(port)
2073
+
2074
+ if __name__ == "__main__":
2075
+ main()