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