tokensafe 4.4.9 → 4.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +44 -15
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +24 -1
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -21
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -76
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +403 -0
  22. package/src/batch_search.py +428 -0
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +85 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +232 -52
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_proxy.py +13 -7
  43. package/src/mcp_server.py +758 -26
  44. package/src/metrics.py +10 -1
  45. package/src/mistakes.py +4 -2
  46. package/src/oumv_gateway.py +81 -7
  47. package/src/paths.py +4 -1
  48. package/src/proxy.py +302 -123
  49. package/src/result_ledger.py +39 -1
  50. package/src/schema_slicer.py +40 -18
  51. package/src/scoped_search.py +66 -23
  52. package/src/skeletonizer.py +22 -11
  53. package/src/slicer.py +6 -4
  54. package/src/snapshot.py +249 -0
  55. package/src/stash.py +37 -7
  56. package/src/superseded.py +42 -23
  57. package/src/syntax_guard.py +86 -0
  58. package/src/team_cache.py +3 -0
  59. package/src/telemetry_sync.py +66 -53
  60. package/src/thinking_fold.py +50 -12
  61. package/src/transcript_analyzer.py +483 -0
  62. package/src/treesitter_backend.py +2 -0
  63. package/src/type_slicer.py +60 -18
  64. package/src/version_checker.py +1 -1
  65. package/src/web_reader.py +55 -22
package/src/proxy.py CHANGED
@@ -16,7 +16,7 @@ import threading
16
16
  import urllib.request
17
17
  import urllib.error
18
18
  from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
19
- from typing import Dict, Any, List
19
+ from typing import Dict, Any, List, Optional, Tuple
20
20
 
21
21
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22
22
  sys.path.insert(0, BASE_DIR)
@@ -76,10 +76,83 @@ BROADCASTER = EventBroadcaster()
76
76
 
77
77
  _CACHE_OBS_MIN_INTERVAL_S = 30.0
78
78
  _last_cache_obs_ts = 0.0
79
+ _SESSION_CACHE_WARM: Dict[Tuple[str, str], bool] = {}
80
+ _CACHE_STATE_LOCK = threading.Lock()
81
+ _DEEP_REASONING_RE = re.compile(
82
+ r"\b(architect|architecture|design|plan|audit|security|migrate|migration|investigate|refactor|root\s+cause)\b"
83
+ r"|архитектур|план|аудит|расследован|безопасност|рефактор",
84
+ re.IGNORECASE,
85
+ )
86
+
87
+
88
+ def _apply_effort_clamp(
89
+ payload: Dict[str, Any],
90
+ messages: List[Dict[str, Any]],
91
+ provider: str,
92
+ ) -> Optional[str]:
93
+ """Clamps reasoning/thinking effort on routine or tool-continuation turns.
94
+
95
+ Z.ai Coding Plan defaults `thinking: enabled` (without explicit effort) to
96
+ `max` effort, inflating expensive output tokens (x16-x24). Tool-result
97
+ continuation turns clamp to `low`; routine non-architectural turns clamp
98
+ to `medium`. Opt-out via TOKENSAFE_EFFORT_CLAMP=0.
99
+ """
100
+ mode = os.environ.get("TOKENSAFE_EFFORT_CLAMP", "1").strip().lower()
101
+ if mode in ("0", "false", "no", "off"):
102
+ return None
103
+ strict = mode == "strict"
104
+
105
+ last_msg = messages[-1] if messages and isinstance(messages[-1], dict) else {}
106
+ last_role = str(last_msg.get("role") or "")
107
+ last_user_text = ""
108
+ for m in reversed(messages or []):
109
+ if isinstance(m, dict) and m.get("role") == "user":
110
+ c = m.get("content")
111
+ if isinstance(c, str):
112
+ last_user_text = c
113
+ elif isinstance(c, list):
114
+ last_user_text = " ".join(
115
+ str(b.get("text") or "") for b in c if isinstance(b, dict) and b.get("text")
116
+ )
117
+ break
118
+
119
+ is_deep = bool(_DEEP_REASONING_RE.search(last_user_text)) or len(last_user_text) >= 600
120
+ if last_role == "tool":
121
+ target_effort = "low"
122
+ elif not is_deep:
123
+ target_effort = "medium"
124
+ else:
125
+ return None
126
+
127
+ if provider == "anthropic":
128
+ thinking_cfg = payload.get("_tokensafe_thinking_cfg") or payload.get("thinking")
129
+ out_cfg = payload.get("_tokensafe_output_config") or payload.get("output_config")
130
+ model_l = str(payload.get("model") or "").lower()
131
+ # Only touch payloads that use thinking/effort or GLM/Claude models.
132
+ if thinking_cfg is None and out_cfg is None and "glm" not in model_l and "claude" not in model_l:
133
+ return None
134
+ out_cfg_dict = dict(out_cfg) if isinstance(out_cfg, dict) else {}
135
+ cur_effort = str(out_cfg_dict.get("effort") or "").strip().lower()
136
+ if cur_effort and cur_effort not in ("high", "max", "xhigh", "ultra", "auto", "adaptive") and not strict:
137
+ return None
138
+ if cur_effort == "high" and not strict and last_role != "tool":
139
+ return None
140
+ out_cfg_dict["effort"] = target_effort
141
+ payload["_tokensafe_output_config"] = out_cfg_dict
142
+ return target_effort
143
+
144
+ if "reasoning_effort" in payload:
145
+ cur_re = str(payload.get("reasoning_effort") or "").strip().lower()
146
+ if cur_re in ("", "high", "xhigh", "max") or strict:
147
+ payload["reasoning_effort"] = target_effort
148
+ return target_effort
149
+ return None
79
150
 
80
151
 
81
152
  def _record_cache_obs(tracker, provider: str, mutation_kinds: List[str],
82
- input_tokens: int, cache_read: int, cache_write: int) -> None:
153
+ input_tokens: int, cache_read: int, cache_write: int,
154
+ model: str = "", output_tokens: int = 0,
155
+ input_is_uncached: Optional[bool] = None) -> None:
83
156
  """CACHE_OBS: per-response KV-cache observation (zero-savings telemetry).
84
157
 
85
158
  Lets the dashboard PROVE cache stability: average cache-hit ratio on
@@ -92,19 +165,36 @@ def _record_cache_obs(tracker, provider: str, mutation_kinds: List[str],
92
165
  if not mutated and (now - _last_cache_obs_ts) < _CACHE_OBS_MIN_INTERVAL_S:
93
166
  return
94
167
  _last_cache_obs_ts = now
168
+ est_credits = None
169
+ if "glm" in (model or "").lower():
170
+ try:
171
+ from src.burn_monitor import estimate_zai_credits
172
+ if input_is_uncached is None:
173
+ input_is_uncached = (provider == "anthropic")
174
+ uncached = int(input_tokens or 0) if input_is_uncached else max(0, int(input_tokens or 0) - int(cache_read or 0))
175
+ est_credits = estimate_zai_credits(uncached, int(cache_read or 0), int(output_tokens or 0), model=model)
176
+ except Exception:
177
+ est_credits = None
95
178
  try:
179
+ details: Dict[str, Any] = {
180
+ "provider": str(provider),
181
+ "input": int(input_tokens or 0),
182
+ "cache_read": int(cache_read or 0),
183
+ "cache_write": int(cache_write or 0),
184
+ "mutations": list(mutation_kinds or []),
185
+ }
186
+ if model:
187
+ details["model"] = str(model)
188
+ if output_tokens:
189
+ details["output"] = int(output_tokens)
190
+ if est_credits is not None:
191
+ details["est_credits"] = est_credits
96
192
  tracker.record_event(
97
193
  session_id="proxy_session",
98
194
  event_type="CACHE_OBS",
99
195
  original_tokens=0,
100
196
  optimized_tokens=0,
101
- details={
102
- "provider": str(provider),
103
- "input": int(input_tokens or 0),
104
- "cache_read": int(cache_read or 0),
105
- "cache_write": int(cache_write or 0),
106
- "mutations": list(mutation_kinds or []),
107
- },
197
+ details=details,
108
198
  measurement="measured",
109
199
  )
110
200
  except Exception:
@@ -318,6 +408,14 @@ def _translate_openai_payload_to_anthropic(payload: Dict[str, Any]) -> Dict[str,
318
408
 
319
409
  for k in _OPENAI_ONLY_FIELDS:
320
410
  out.pop(k, None)
411
+ if isinstance(payload.get("_tokensafe_thinking_cfg"), dict):
412
+ out["thinking"] = payload["_tokensafe_thinking_cfg"]
413
+ elif isinstance(payload.get("thinking"), dict):
414
+ out["thinking"] = payload["thinking"]
415
+ if isinstance(payload.get("_tokensafe_output_config"), dict):
416
+ out["output_config"] = payload["_tokensafe_output_config"]
417
+ elif isinstance(payload.get("output_config"), dict):
418
+ out["output_config"] = payload["output_config"]
321
419
  return out
322
420
 
323
421
 
@@ -458,15 +556,35 @@ def _translate_anthropic_payload_to_openai(payload: Dict[str, Any]) -> Dict[str,
458
556
  elif role == "user":
459
557
  blocks = content if isinstance(content, list) else ([{"type": "text", "text": content}] if isinstance(content, str) else [])
460
558
  pending_results: List[Dict[str, Any]] = []
559
+ user_parts: List[Dict[str, Any]] = []
560
+ def _flush_user_parts():
561
+ if not user_parts:
562
+ return
563
+ if all(p.get("type") == "text" for p in user_parts):
564
+ pending_results.append({"role": "user", "content": "\n".join(p.get("text", "") for p in user_parts)})
565
+ else:
566
+ pending_results.append({"role": "user", "content": list(user_parts)})
567
+ user_parts.clear()
568
+
461
569
  for blk in blocks:
462
570
  if not isinstance(blk, dict):
463
571
  continue
464
- if blk.get("type") == "tool_result":
572
+ btype = blk.get("type")
573
+ if btype == "tool_result":
574
+ _flush_user_parts()
465
575
  tc = blk.get("content")
466
576
  text = tc if isinstance(tc, str) else _text_blocks(tc) if isinstance(tc, list) else json.dumps(tc, ensure_ascii=False)
467
577
  pending_results.append({"role": "tool", "tool_call_id": blk.get("tool_use_id") or "toolu_call", "content": text})
468
- elif blk.get("type") == "text" and isinstance(blk.get("text"), str):
469
- pending_results.append({"role": "user", "content": blk["text"]})
578
+ elif btype == "text" and isinstance(blk.get("text"), str):
579
+ user_parts.append({"type": "text", "text": blk["text"]})
580
+ elif btype == "image" and isinstance(blk.get("source"), dict):
581
+ src = blk["source"]
582
+ if src.get("type") == "base64" and src.get("data"):
583
+ media = src.get("media_type") or "image/png"
584
+ user_parts.append({"type": "image_url", "image_url": {"url": f"data:{media};base64,{src['data']}"}})
585
+ elif src.get("url"):
586
+ user_parts.append({"type": "image_url", "image_url": {"url": src["url"]}})
587
+ _flush_user_parts()
470
588
  out_messages.extend(pending_results)
471
589
  if not pending_results:
472
590
  out_messages.append({"role": "user", "content": ""})
@@ -484,6 +602,10 @@ def _translate_anthropic_payload_to_openai(payload: Dict[str, Any]) -> Dict[str,
484
602
  out["stop"] = payload["stop_sequences"]
485
603
  if isinstance(payload.get("stream"), bool):
486
604
  out["stream"] = payload["stream"]
605
+ if isinstance(payload.get("thinking"), dict):
606
+ out["_tokensafe_thinking_cfg"] = payload["thinking"]
607
+ if isinstance(payload.get("output_config"), dict):
608
+ out["_tokensafe_output_config"] = payload["output_config"]
487
609
  tools = payload.get("tools")
488
610
  if isinstance(tools, list) and tools:
489
611
  oai_tools = []
@@ -505,7 +627,11 @@ def _translate_anthropic_payload_to_openai(payload: Dict[str, Any]) -> Dict[str,
505
627
  if oai_tools:
506
628
  out["tools"] = oai_tools
507
629
  tc = payload.get("tool_choice")
508
- if tc == "required" or (isinstance(tc, dict) and tc.get("type") == "any"):
630
+ if tc == "auto" or (isinstance(tc, dict) and tc.get("type") == "auto"):
631
+ out["tool_choice"] = "auto"
632
+ elif tc == "none" or (isinstance(tc, dict) and tc.get("type") == "none"):
633
+ out["tool_choice"] = "none"
634
+ elif tc == "required" or (isinstance(tc, dict) and tc.get("type") == "any"):
509
635
  out["tool_choice"] = "required"
510
636
  elif isinstance(tc, dict) and tc.get("type") == "tool" and tc.get("name"):
511
637
  out["tool_choice"] = {"type": "function", "function": {"name": tc["name"]}}
@@ -560,8 +686,9 @@ class _OpenAISSEToAnthropicTranslator:
560
686
  self._buf = b""
561
687
  self._started = False
562
688
  self._text_open = False
563
- self._tool_open: Dict[int, bool] = {}
564
- self._block_index = 0
689
+ self._tool_open: Dict[int, int] = {}
690
+ self._active_tool_idx: Optional[int] = None
691
+ self._block_index = -1
565
692
  self._msg_id = f"msg_{int(time.time() * 1000)}"
566
693
  self._done = False
567
694
  self._finished = False
@@ -581,6 +708,16 @@ class _OpenAISSEToAnthropicTranslator:
581
708
  },
582
709
  })
583
710
 
711
+ def _close_open_blocks(self) -> bytes:
712
+ out = b""
713
+ if self._text_open:
714
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._text_block_idx})
715
+ self._text_open = False
716
+ if self._active_tool_idx is not None and self._active_tool_idx in self._tool_open:
717
+ out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._tool_open[self._active_tool_idx]})
718
+ self._active_tool_idx = None
719
+ return out
720
+
584
721
  def _handle_chunk(self, chunk: Dict[str, Any]) -> bytes:
585
722
  out = b""
586
723
  if not self._started:
@@ -590,36 +727,40 @@ class _OpenAISSEToAnthropicTranslator:
590
727
  delta = choice.get("delta") or {}
591
728
  if isinstance(delta.get("content"), str) and delta["content"]:
592
729
  if not self._text_open:
593
- out += self._event("content_block_start", {"type": "content_block_start", "index": self._block_index, "content_block": {"type": "text", "text": ""}})
730
+ if self._active_tool_idx is not None:
731
+ out += self._close_open_blocks()
732
+ self._block_index += 1
733
+ self._text_block_idx = self._block_index
734
+ out += self._event("content_block_start", {"type": "content_block_start", "index": self._text_block_idx, "content_block": {"type": "text", "text": ""}})
594
735
  self._text_open = True
595
- out += self._event("content_block_delta", {"type": "content_block_delta", "index": self._block_index, "delta": {"type": "text_delta", "text": delta["content"]}})
736
+ out += self._event("content_block_delta", {"type": "content_block_delta", "index": self._text_block_idx, "delta": {"type": "text_delta", "text": delta["content"]}})
596
737
  for tc in delta.get("tool_calls") or []:
597
738
  if not isinstance(tc, dict):
598
739
  continue
599
740
  idx = int(tc.get("index") or 0)
600
741
  if idx not in self._tool_open:
601
- if self._text_open:
602
- out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
603
- self._text_open = False
742
+ out += self._close_open_blocks()
604
743
  self._block_index += 1
605
- self._tool_open[idx] = True
744
+ blk_idx = self._block_index
745
+ self._tool_open[idx] = blk_idx
746
+ self._active_tool_idx = idx
606
747
  fn = tc.get("function") or {}
607
748
  out += self._event("content_block_start", {
608
- "type": "content_block_start", "index": self._block_index,
749
+ "type": "content_block_start", "index": blk_idx,
609
750
  "content_block": {"type": "tool_use", "id": tc.get("id") or f"toolu_{idx}", "name": fn.get("name") or "unknown", "input": {}},
610
751
  })
752
+ else:
753
+ blk_idx = self._tool_open[idx]
611
754
  fn = tc.get("function") or {}
612
755
  if fn.get("arguments"):
613
- out += self._event("content_block_delta", {"type": "content_block_delta", "index": self._block_index, "delta": {"type": "input_json_delta", "partial_json": fn["arguments"]}})
756
+ out += self._event("content_block_delta", {"type": "content_block_delta", "index": blk_idx, "delta": {"type": "input_json_delta", "partial_json": fn["arguments"]}})
614
757
  finish = choice.get("finish_reason")
615
758
  usage = chunk.get("usage") or {}
616
759
  if usage.get("completion_tokens"):
617
760
  self._usage_out = int(usage["completion_tokens"])
618
761
  if finish and not self._finished:
619
762
  self._finished = True
620
- if self._text_open:
621
- out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
622
- self._text_open = False
763
+ out += self._close_open_blocks()
623
764
  stop_reason = {"stop": "end_turn", "length": "max_tokens", "tool_calls": "tool_use"}.get(finish, "end_turn")
624
765
  out += self._event("message_delta", {
625
766
  "type": "message_delta",
@@ -647,13 +788,14 @@ class _OpenAISSEToAnthropicTranslator:
647
788
  if body == b"[DONE]":
648
789
  if not self._done:
649
790
  self._done = True
650
- if self._text_open:
651
- out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
652
- out += self._event("message_delta", {
653
- "type": "message_delta",
654
- "delta": {"stop_reason": "end_turn", "stop_sequence": None},
655
- "usage": {"output_tokens": self._usage_out},
656
- })
791
+ out += self._close_open_blocks()
792
+ if not self._finished:
793
+ self._finished = True
794
+ out += self._event("message_delta", {
795
+ "type": "message_delta",
796
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
797
+ "usage": {"output_tokens": self._usage_out},
798
+ })
657
799
  out += self._event("message_stop", {"type": "message_stop"})
658
800
  continue
659
801
  try:
@@ -671,8 +813,7 @@ class _OpenAISSEToAnthropicTranslator:
671
813
  out = b""
672
814
  if not self._started:
673
815
  out += self._start_message()
674
- if self._text_open:
675
- out += self._event("content_block_stop", {"type": "content_block_stop", "index": self._block_index})
816
+ out += self._close_open_blocks()
676
817
  if not self._done:
677
818
  out += self._event("message_delta", {
678
819
  "type": "message_delta",
@@ -1034,13 +1175,56 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1034
1175
  think_stats: Dict[str, Any] = {}
1035
1176
  gov_stats: Dict[str, Any] = {}
1036
1177
  prompt_mutated = False
1178
+ clamped_effort: Optional[str] = None
1179
+
1180
+ # 1.2 Resolve Multi-Provider Upstream & API Key early so ROI gates and
1181
+ # effort clamping know the exact upstream provider, model, and warm-cache state.
1182
+ auth_header = self.headers.get("Authorization", "")
1183
+ incoming_key = auth_header[7:].strip() if auth_header.lower().startswith("bearer ") else ""
1184
+ if not incoming_key:
1185
+ try:
1186
+ incoming_key = self.headers.get("x-api-key", "") or ""
1187
+ except Exception:
1188
+ incoming_key = ""
1189
+ custom_url = _apply_route_override(incoming_key, os.environ.get("TOKENSAFE_UPSTREAM_URL", ""))
1190
+
1191
+ data_dir = resolve_data_dir()
1192
+ conf_keys = {}
1193
+ config_path = os.path.join(data_dir, "config.json")
1194
+ if os.path.exists(config_path):
1195
+ try:
1196
+ with open(config_path) as f:
1197
+ conf_keys = json.load(f)
1198
+ except Exception:
1199
+ pass
1200
+
1201
+ upstream_url, resolved_key = self._resolve_upstream(conf_keys, custom_url)
1202
+ provider = self._detect_provider(upstream_url)
1203
+ client_anthropic = getattr(self, "_client_shape", "") == "anthropic"
1204
+ if client_anthropic and provider == "anthropic" and not upstream_url.rstrip("/").endswith("/v1/messages"):
1205
+ after_host = upstream_url.split("://", 1)[-1]
1206
+ path = "/" + after_host.split("/", 1)[1] if "/" in after_host else ""
1207
+ if not path or path.rstrip("/").endswith("/anthropic"):
1208
+ upstream_url = f"{upstream_url.rstrip('/')}/v1/messages"
1209
+ upstream_model = os.environ.get("TOKENSAFE_UPSTREAM_MODEL", "").strip()
1210
+ if upstream_model:
1211
+ payload["model"] = upstream_model
1212
+
1213
+ active_model = str(payload.get("model") or "")
1214
+ cache_state_key = (_key_fingerprint(incoming_key or resolved_key), active_model)
1215
+ with _CACHE_STATE_LOCK:
1216
+ session_cache_warm = _SESSION_CACHE_WARM.get(cache_state_key)
1037
1217
 
1038
1218
  # 1.5 Tool Result Ledger: fold aged, oversized tool results into compact
1039
- # anchors + local archive (idempotent via marker; cache-aware). Runs
1040
- # before the governor so the governor sees the lightened mass.
1219
+ # anchors + local archive (idempotent via marker; cache-aware ROI gate).
1041
1220
  if messages and not is_quota_exceeded:
1042
1221
  try:
1043
- messages, ledger_stats = fold_tool_results(messages)
1222
+ messages, ledger_stats = fold_tool_results(
1223
+ messages,
1224
+ model=active_model,
1225
+ provider=provider,
1226
+ cache_warm=session_cache_warm,
1227
+ )
1044
1228
  payload["messages"] = messages
1045
1229
  if ledger_stats.get("folded"):
1046
1230
  print(
@@ -1050,14 +1234,17 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1050
1234
  except Exception:
1051
1235
  pass
1052
1236
 
1053
- # 1.6 Aged Thinking Fold (OPT-IN, DEFAULT OFF via TOKENSAFE_FOLD_THINKING):
1237
+ # 1.6 Aged Thinking Fold (enabled by default; opt-out TOKENSAFE_FOLD_THINKING=0):
1054
1238
  # collapse extended-thinking payloads of aged assistant turns into
1055
- # one-line stubs. The _tokensafe_thinking side-channel key stays a
1056
- # valid text block for shape-sensitive mirrors (the 1214 class).
1057
- # Enable only after the upstream shape probe matrix passes.
1239
+ # one-line stubs, gated by the same cache-break ROI check.
1058
1240
  if messages and not is_quota_exceeded:
1059
1241
  try:
1060
- messages, think_stats = fold_aged_thinking(messages)
1242
+ messages, think_stats = fold_aged_thinking(
1243
+ messages,
1244
+ model=active_model,
1245
+ provider=provider,
1246
+ cache_warm=session_cache_warm,
1247
+ )
1061
1248
  payload["messages"] = messages
1062
1249
  if think_stats.get("folded"):
1063
1250
  print(
@@ -1067,89 +1254,63 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1067
1254
  except Exception:
1068
1255
  pass
1069
1256
 
1070
- # 2. Ingress Optimization: REPLACE the last user message with its TOCP form.
1071
- # Paused when Community 500k monthly measured quota is exceeded.
1257
+ # 2. Ingress Optimization: REPLACE the last message with its TOCP form
1258
+ # ONLY when the latest message is an actual user prompt (never mutate an
1259
+ # older cached user turn mid-tool-loop).
1072
1260
  target_symbol = None
1073
- if messages and not is_quota_exceeded:
1074
- for idx in reversed(range(len(messages))):
1075
- msg = messages[idx]
1076
- if msg.get("role") == "user" and isinstance(msg.get("content"), str):
1077
- raw_user = msg["content"]
1078
- compaction = PromptCompactor.compact(raw_user, enable_distill=False)
1079
- if compaction["saved_tokens"] > 5:
1080
- msg["content"] = compaction["compact_text"]
1081
- prompt_mutated = True
1082
- try:
1083
- proxy_tracker.record_event(
1084
- session_id="proxy_session",
1085
- event_type="PROMPT",
1086
- original_tokens=compaction["original_tokens"],
1087
- optimized_tokens=compaction["compact_tokens"],
1088
- details={
1089
- "mode": "proxy_replace",
1090
- "action": compaction.get("action"),
1091
- "symbol": compaction.get("symbol"),
1092
- "tier": compaction.get("tier", "REGEX"),
1093
- },
1094
- measurement="measured", # bytes literally swapped
1095
- )
1096
- from src.telemetry_sync import TelemetrySync
1097
- TelemetrySync.sync_background(throttle_seconds=5.0)
1098
- except Exception:
1099
- pass
1100
- target_symbol = compaction.get("symbol")
1101
- break
1261
+ if messages and not is_quota_exceeded and messages[-1].get("role") == "user":
1262
+ msg = messages[-1]
1263
+ if isinstance(msg.get("content"), str):
1264
+ raw_user = msg["content"]
1265
+ compaction = PromptCompactor.compact(raw_user, enable_distill=False)
1266
+ if compaction["saved_tokens"] > 5:
1267
+ msg["content"] = compaction["compact_text"]
1268
+ prompt_mutated = True
1269
+ try:
1270
+ proxy_tracker.record_event(
1271
+ session_id="proxy_session",
1272
+ event_type="PROMPT",
1273
+ original_tokens=compaction["original_tokens"],
1274
+ optimized_tokens=compaction["compact_tokens"],
1275
+ details={
1276
+ "mode": "proxy_replace",
1277
+ "action": compaction.get("action"),
1278
+ "symbol": compaction.get("symbol"),
1279
+ "tier": compaction.get("tier", "REGEX"),
1280
+ },
1281
+ measurement="measured",
1282
+ )
1283
+ from src.telemetry_sync import TelemetrySync
1284
+ TelemetrySync.sync_background(throttle_seconds=5.0)
1285
+ except Exception:
1286
+ pass
1287
+ target_symbol = compaction.get("symbol")
1102
1288
 
1103
- # 3. Automatic Architecture Awareness (God Nodes Injection)
1289
+ # 3. Automatic Architecture Awareness (God Nodes Injection — deterministic
1290
+ # across turns for the active workspace so KV-cache prefixes stay identical).
1104
1291
  if messages and not is_quota_exceeded:
1105
1292
  try:
1106
- graph = GraphEngine.get_instance(os.getcwd())
1107
- banner = graph.format_topology_banner()
1108
- first_msg = messages[0]
1109
- if banner and isinstance(first_msg.get("content"), str) and "[TokenSafe Architecture" not in first_msg["content"]:
1110
- if first_msg.get("role") == "system":
1111
- first_msg["content"] = f"{banner}\n{first_msg['content']}"
1293
+ from src.paths import get_active_workspace
1294
+ ws_root = get_active_workspace()
1295
+ if ws_root:
1296
+ graph = GraphEngine.get_instance(ws_root)
1297
+ banner = graph.format_topology_banner()
1298
+ first_msg = messages[0]
1299
+ if banner and isinstance(first_msg.get("content"), str) and "[TokenSafe Architecture" not in first_msg["content"]:
1300
+ if first_msg.get("role") == "system":
1301
+ first_msg["content"] = f"{banner}\n{first_msg['content']}"
1112
1302
  except Exception:
1113
1303
  pass
1114
1304
 
1115
- # 4. Resolve Multi-Provider Upstream & API Key (needed before provider-aware cache breakpoints)
1116
- auth_header = self.headers.get("Authorization", "")
1117
- incoming_key = auth_header[7:].strip() if auth_header.lower().startswith("bearer ") else ""
1118
- if not incoming_key:
1119
- try:
1120
- incoming_key = self.headers.get("x-api-key", "") or ""
1121
- except Exception:
1122
- incoming_key = ""
1123
- custom_url = _apply_route_override(incoming_key, os.environ.get("TOKENSAFE_UPSTREAM_URL", ""))
1124
-
1125
- data_dir = resolve_data_dir()
1126
- conf_keys = {}
1127
- config_path = os.path.join(data_dir, "config.json")
1128
- if os.path.exists(config_path):
1305
+ # 4.5 Effort Clamp: reduce Z.ai/Anthropic default `max` effort on
1306
+ # tool-continuation ("low") and routine ("medium") turns.
1307
+ if messages and not is_quota_exceeded:
1129
1308
  try:
1130
- with open(config_path) as f:
1131
- conf_keys = json.load(f)
1309
+ clamped_effort = _apply_effort_clamp(payload, messages, provider)
1310
+ if clamped_effort:
1311
+ BROADCASTER.publish("effort_clamp", {"model": active_model, "effort": clamped_effort})
1132
1312
  except Exception:
1133
- pass
1134
-
1135
- upstream_url, resolved_key = self._resolve_upstream(conf_keys, custom_url)
1136
- provider = self._detect_provider(upstream_url)
1137
- # Client shape: "anthropic" when the request arrived on /v1/messages
1138
- # (Claude Code via ANTHROPIC_BASE_URL), else OpenAI-native.
1139
- client_anthropic = getattr(self, "_client_shape", "") == "anthropic"
1140
- # Defensive endpoint completion: an anthropic-dialect upstream registered
1141
- # as a bare host (https://api.anthropic.com) or an /anthropic mirror base
1142
- # must receive the payload on its /v1/messages endpoint, not on "/".
1143
- if client_anthropic and provider == "anthropic" and not upstream_url.rstrip("/").endswith("/v1/messages"):
1144
- after_host = upstream_url.split("://", 1)[-1]
1145
- path = "/" + after_host.split("/", 1)[1] if "/" in after_host else ""
1146
- if not path or path.rstrip("/").endswith("/anthropic"):
1147
- upstream_url = f"{upstream_url.rstrip('/')}/v1/messages"
1148
- # Optional upstream model mapping: route client model names (e.g. claude-*)
1149
- # to the model the upstream account actually serves.
1150
- upstream_model = os.environ.get("TOKENSAFE_UPSTREAM_MODEL", "").strip()
1151
- if upstream_model:
1152
- payload["model"] = upstream_model
1313
+ clamped_effort = None
1153
1314
 
1154
1315
  # 5. Epoch-Aware Context Governor (runs BEFORE cache normalization so breakpoints stay valid)
1155
1316
  if messages and not is_quota_exceeded:
@@ -1190,6 +1351,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1190
1351
  messages, cache_meta = PromptCacheNormalizer.normalize_messages(
1191
1352
  messages,
1192
1353
  provider=provider,
1354
+ inject_cache_control=(provider == "anthropic"),
1193
1355
  tools=payload.get("tools") if isinstance(payload.get("tools"), list) else None,
1194
1356
  )
1195
1357
  payload["messages"] = messages
@@ -1220,13 +1382,15 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1220
1382
  # OpenAI form, and this puts it back into Anthropic shape for upstream.
1221
1383
  payload = _translate_openai_payload_to_anthropic(payload)
1222
1384
  else:
1223
- # The ingest thinking side-channel is Anthropic-only — never leak it
1224
- # into an OpenAI-dialect upstream request.
1385
+ # The ingest thinking/effort side-channels are Anthropic-only — never leak
1386
+ # them into an OpenAI-dialect upstream request.
1387
+ payload.pop("_tokensafe_thinking_cfg", None)
1388
+ payload.pop("_tokensafe_output_config", None)
1225
1389
  for _m in payload.get("messages") or []:
1226
1390
  if isinstance(_m, dict):
1227
1391
  _m.pop("_tokensafe_thinking", None)
1228
1392
 
1229
- headers = {"Content-Type": "application/json"}
1393
+ headers = {"Content-Type": "application/json", "Accept-Encoding": "identity"}
1230
1394
  if provider == "anthropic":
1231
1395
  x_api_key = self.headers.get("x-api-key", "") if hasattr(self.headers, "get") else ""
1232
1396
  bearer_key = auth_header[7:].strip() if auth_header.lower().startswith("bearer ") else auth_header.strip()
@@ -1251,7 +1415,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1251
1415
  with urllib.request.urlopen(req, timeout=req_timeout) as resp:
1252
1416
  self.send_response(resp.status)
1253
1417
  for k, v in resp.getheaders():
1254
- if k.lower() in ("content-type", "content-encoding"):
1418
+ if k.lower() == "content-type":
1255
1419
  self.send_header(k, v)
1256
1420
  if is_quota_exceeded:
1257
1421
  self.send_header("X-TokenSafe-Quota", "exceeded")
@@ -1318,14 +1482,22 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1318
1482
  # 64KB tail may evict on very long streams — record
1319
1483
  # only when at least one real field survived.
1320
1484
  m_in = re.search(r'"input_tokens":\s*(\d+)', tail_text)
1485
+ m_out = re.search(r'"output_tokens":\s*(\d+)', tail_text)
1321
1486
  m_cw = re.search(r'"cache_creation_input_tokens":\s*(\d+)', tail_text)
1322
1487
  sse_input = int(m_in.group(1)) if m_in else 0
1488
+ sse_cached = int(m_cached.group(1)) if m_cached else 0
1489
+ sse_out = int(m_out.group(1)) if m_out else 0
1490
+ with _CACHE_STATE_LOCK:
1491
+ _SESSION_CACHE_WARM[cache_state_key] = bool(sse_cached > 0)
1323
1492
  if m_cached or sse_input > 0:
1324
1493
  _record_cache_obs(
1325
1494
  proxy_tracker, provider, mutation_kinds,
1326
1495
  sse_input,
1327
- int(m_cached.group(1)) if m_cached else 0,
1496
+ sse_cached,
1328
1497
  int(m_cw.group(1)) if m_cw else 0,
1498
+ model=active_model,
1499
+ output_tokens=sse_out,
1500
+ input_is_uncached=True,
1329
1501
  )
1330
1502
  except Exception:
1331
1503
  pass
@@ -1364,11 +1536,18 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1364
1536
  )
1365
1537
  # Cache-stability observation (non-stream path: both
1366
1538
  # Anthropic and OpenAI usage shapes are available).
1539
+ in_tok_obs = int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0)
1540
+ out_tok_obs = int(usage.get("completion_tokens") or usage.get("output_tokens") or 0)
1541
+ with _CACHE_STATE_LOCK:
1542
+ _SESSION_CACHE_WARM[cache_state_key] = bool(int(cached or 0) > 0)
1367
1543
  _record_cache_obs(
1368
1544
  proxy_tracker, provider, mutation_kinds,
1369
- int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0),
1545
+ in_tok_obs,
1370
1546
  int(cached or 0),
1371
1547
  int(usage.get("cache_creation_input_tokens") or 0),
1548
+ model=active_model,
1549
+ output_tokens=out_tok_obs,
1550
+ input_is_uncached=("input_tokens" in usage and "prompt_tokens" not in usage),
1372
1551
  )
1373
1552
  if cached:
1374
1553
  BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(cached)})