tokensafe 4.5.0 → 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 (62) 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 +28 -10
  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 +10 -4
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -24
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -86
  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 +73 -22
  22. package/src/batch_search.py +31 -11
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +34 -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 +31 -9
  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_server.py +487 -48
  43. package/src/metrics.py +10 -1
  44. package/src/mistakes.py +4 -2
  45. package/src/paths.py +4 -1
  46. package/src/proxy.py +302 -123
  47. package/src/result_ledger.py +39 -1
  48. package/src/schema_slicer.py +40 -18
  49. package/src/scoped_search.py +66 -23
  50. package/src/skeletonizer.py +22 -11
  51. package/src/slicer.py +6 -4
  52. package/src/stash.py +37 -7
  53. package/src/superseded.py +42 -23
  54. package/src/syntax_guard.py +2 -0
  55. package/src/team_cache.py +3 -0
  56. package/src/telemetry_sync.py +66 -53
  57. package/src/thinking_fold.py +50 -12
  58. package/src/transcript_analyzer.py +270 -68
  59. package/src/treesitter_backend.py +2 -0
  60. package/src/type_slicer.py +60 -18
  61. package/src/version_checker.py +1 -1
  62. package/src/web_reader.py +55 -22
@@ -0,0 +1,581 @@
1
+ """
2
+ TokenSafe Multi-Agent Live Burn Monitor & Cache-Break ROI Engine.
3
+
4
+ Provides:
5
+ 1. Provider/model token multipliers and Z.ai Peak-Hours awareness.
6
+ 2. Cache-aware ROI gate (evaluate_fold_roi) shared by proxy folding stages
7
+ (result_ledger.py, thinking_fold.py) so mutating a warm KV-cache prefix
8
+ only fires when expected future savings outweigh the cache-break cost.
9
+ 3. Fast tail-reading Live Burn Monitor across ZCode, Claude Code, Antigravity,
10
+ Codex, Cursor, and Kimi transcripts/logs (works with or without the proxy).
11
+ """
12
+
13
+ import datetime
14
+ import glob
15
+ import json
16
+ import os
17
+ import re
18
+ import time
19
+ from typing import Any, Dict, List, Optional, Tuple
20
+
21
+ from src.tokenizer import count_tokens
22
+
23
+ # (M_input, M_cache, M_output) per 10,000 tokens (Z.ai) or relative cost ratio.
24
+ _MODEL_MULTIPLIERS: List[Tuple[str, Tuple[float, float, float]]] = [
25
+ ("glm-5.3-flash", (1.15, 0.28, 4.0)),
26
+ ("glm-5.3", (6.9, 1.7, 24.0)),
27
+ ("glm-5.4", (4.6, 1.1, 16.0)),
28
+ ("glm-5", (4.6, 1.1, 16.0)),
29
+ ("claude", (1.25, 0.10, 5.0)),
30
+ ("deepseek", (1.0, 0.10, 2.0)),
31
+ ("gpt-5", (1.0, 0.10, 4.0)),
32
+ ("gpt-4", (1.0, 0.50, 4.0)),
33
+ ("o1", (1.0, 0.50, 4.0)),
34
+ ("o3", (1.0, 0.25, 4.0)),
35
+ ("o4", (1.0, 0.25, 4.0)),
36
+ ("gemini", (1.0, 0.25, 4.0)),
37
+ ]
38
+
39
+ _DEFAULT_MULTIPLIERS = (1.0, 0.25, 4.0)
40
+ _ZAI_MODELS = ("glm-5.3", "glm-5.4", "glm-5.3-flash", "glm-5")
41
+ _RATE_LIMIT_CODES = ("1310", "1308", "1302")
42
+
43
+
44
+ def get_model_multipliers(model: str = "", provider: str = "") -> Tuple[float, float, float]:
45
+ """Returns (M_input, M_cache, M_output) multipliers for a model/provider."""
46
+ m = (model or "").strip().lower()
47
+ p = (provider or "").strip().lower()
48
+ for prefix, mults in _MODEL_MULTIPLIERS:
49
+ if prefix in m:
50
+ return mults
51
+ if "anthropic" in p:
52
+ return (1.25, 0.10, 5.0)
53
+ if "deepseek" in p:
54
+ return (1.0, 0.10, 2.0)
55
+ if "openai" in p or "gemini" in p:
56
+ return (1.0, 0.25, 4.0)
57
+ return _DEFAULT_MULTIPLIERS
58
+
59
+
60
+ def is_zai_peak_hour(now: Optional[datetime.datetime] = None) -> bool:
61
+ """True during Z.ai Peak Hours: Mon-Fri 14:00-18:00 SST (UTC+8)."""
62
+ if now is None:
63
+ now = datetime.datetime.now(datetime.timezone.utc)
64
+ elif now.tzinfo is None:
65
+ now = now.replace(tzinfo=datetime.timezone.utc)
66
+ sst = now.astimezone(datetime.timezone(datetime.timedelta(hours=8)))
67
+ return sst.weekday() < 5 and 14 <= sst.hour < 18
68
+
69
+
70
+ def estimate_zai_credits(
71
+ uncached_input: int,
72
+ cache_read: int,
73
+ output_tokens: int,
74
+ model: str = "glm-5.4",
75
+ peak: Optional[bool] = None,
76
+ ) -> float:
77
+ """Estimates Z.ai Coding Plan credit consumption using the official formula."""
78
+ m_in, m_cache, m_out = get_model_multipliers(model)
79
+ raw = (
80
+ max(0, uncached_input) * m_in
81
+ + max(0, cache_read) * m_cache
82
+ + max(0, output_tokens) * m_out
83
+ ) / 10000.0
84
+ if peak is None:
85
+ peak = is_zai_peak_hour()
86
+ return round(raw if peak else raw * 0.5, 2)
87
+
88
+
89
+ def _msg_tokens(msg: Any) -> int:
90
+ if not isinstance(msg, dict):
91
+ return 0
92
+ total = 0
93
+ content = msg.get("content")
94
+ if isinstance(content, str):
95
+ total += count_tokens(content)
96
+ elif isinstance(content, list):
97
+ for blk in content:
98
+ if isinstance(blk, dict):
99
+ txt = blk.get("text") or blk.get("thinking") or ""
100
+ if isinstance(txt, str):
101
+ total += count_tokens(txt)
102
+ for tc in msg.get("tool_calls") or []:
103
+ if isinstance(tc, dict):
104
+ fn = tc.get("function") or {}
105
+ total += count_tokens(str(fn.get("name") or "") + str(fn.get("arguments") or ""))
106
+ for tb in msg.get("_tokensafe_thinking") or []:
107
+ if isinstance(tb, dict):
108
+ total += count_tokens(str(tb.get("text") or tb.get("thinking") or ""))
109
+ return total
110
+
111
+
112
+ def evaluate_fold_roi(
113
+ messages: List[Dict[str, Any]],
114
+ earliest_fold_idx: int,
115
+ saved_tokens: int,
116
+ model: str = "",
117
+ provider: str = "",
118
+ cache_warm: Optional[bool] = None,
119
+ remaining_turns: int = 8,
120
+ force_fold: bool = False,
121
+ ) -> Dict[str, Any]:
122
+ """Evaluates whether mutating history at `earliest_fold_idx` beats the KV-cache break cost.
123
+
124
+ Compares:
125
+ cache_break_cost = suffix_tokens * (M_in - M_cache)
126
+ expected_savings = saved_tokens * M_cache * remaining_turns
127
+ Cold prefixes (force_fold=True, cache_warm=False, or small <20k sessions when
128
+ cache_warm is unknown) fold unconditionally.
129
+ """
130
+ m_in, m_cache, _ = get_model_multipliers(model, provider)
131
+ suffix_tokens = sum(_msg_tokens(m) for m in messages[earliest_fold_idx + 1 :])
132
+ total_tokens = sum(_msg_tokens(m) for m in messages)
133
+
134
+ if force_fold:
135
+ is_warm = False
136
+ elif cache_warm is not None:
137
+ is_warm = bool(cache_warm)
138
+ else:
139
+ is_warm = total_tokens >= 20000
140
+
141
+ cache_break_cost = round(suffix_tokens * max(0.0, m_in - m_cache), 2) if is_warm else 0.0
142
+ expected_savings = round(max(0, saved_tokens) * max(0.05, m_cache) * max(1, remaining_turns), 2)
143
+ should_fold = (not is_warm) or (expected_savings > cache_break_cost)
144
+
145
+ return {
146
+ "should_fold": should_fold,
147
+ "cache_warm": is_warm,
148
+ "suffix_tokens": suffix_tokens,
149
+ "total_tokens": total_tokens,
150
+ "saved_tokens": saved_tokens,
151
+ "cache_break_cost": cache_break_cost,
152
+ "expected_savings": expected_savings,
153
+ "m_in": m_in,
154
+ "m_cache": m_cache,
155
+ }
156
+
157
+
158
+ def _read_tail_lines(path: str, max_bytes: int = 65536) -> List[str]:
159
+ """Reads up to the last `max_bytes` of a file safely and fast."""
160
+ try:
161
+ size = os.path.getsize(path)
162
+ with open(path, "rb") as f:
163
+ if size > max_bytes:
164
+ f.seek(size - max_bytes)
165
+ chunk = f.read()
166
+ nl = chunk.find(b"\n")
167
+ if nl != -1:
168
+ chunk = chunk[nl + 1 :]
169
+ else:
170
+ chunk = f.read()
171
+ return [ln for ln in chunk.decode("utf-8", errors="replace").splitlines() if ln.strip()]
172
+ except Exception:
173
+ return []
174
+
175
+
176
+ def _parse_iso(ts: Optional[str]) -> Optional[float]:
177
+ if not ts or not isinstance(ts, str):
178
+ return None
179
+ try:
180
+ dt = datetime.datetime.fromisoformat(ts.replace("Z", "+00:00"))
181
+ if dt.tzinfo is None:
182
+ dt = dt.replace(tzinfo=datetime.timezone.utc)
183
+ return dt.timestamp()
184
+ except Exception:
185
+ return None
186
+
187
+
188
+ def _scan_zcode_tail(home: str, session_id: str = "", explicit_path: str = "") -> Optional[Dict[str, Any]]:
189
+ rollout_dir = os.path.join(home, ".zcode", "cli", "rollout")
190
+ if explicit_path and os.path.isfile(explicit_path) and "model-io-" in os.path.basename(explicit_path):
191
+ candidates = [explicit_path]
192
+ elif os.path.isdir(rollout_dir):
193
+ candidates = glob.glob(os.path.join(rollout_dir, "model-io-*.jsonl"))
194
+ else:
195
+ return None
196
+ if not candidates:
197
+ return None
198
+
199
+ now = time.time()
200
+ active_parallel = 0
201
+ best_path = None
202
+ best_mtime = 0.0
203
+ for fp in candidates:
204
+ try:
205
+ mt = os.path.getmtime(fp)
206
+ if now - mt <= 90.0:
207
+ active_parallel += 1
208
+ if session_id and session_id in os.path.basename(fp):
209
+ best_path = fp
210
+ best_mtime = mt
211
+ elif not (session_id and best_path and session_id in os.path.basename(best_path)) and mt > best_mtime:
212
+ best_mtime = mt
213
+ best_path = fp
214
+ except Exception:
215
+ continue
216
+
217
+ if not best_path or (now - best_mtime > 3600 and not explicit_path):
218
+ return None
219
+
220
+ lines = _read_tail_lines(best_path, max_bytes=131072)
221
+ models_seen: List[str] = []
222
+ last_in = last_cr = last_out = last_reason_chars = last_text_chars = 0
223
+ prev_model = ""
224
+ model_switches = 0
225
+ zero_usage = 0
226
+ tool_schema_tokens = 0
227
+ turns = 0
228
+
229
+ for ln in lines[-20:]:
230
+ try:
231
+ obj = json.loads(ln)
232
+ except Exception:
233
+ continue
234
+ turns += 1
235
+ m_info = obj.get("model")
236
+ m_id = (m_info.get("modelId") or m_info.get("id") or "") if isinstance(m_info, dict) else str(m_info or "")
237
+ if m_id:
238
+ if prev_model and m_id != prev_model:
239
+ model_switches += 1
240
+ prev_model = m_id
241
+ models_seen.append(m_id)
242
+ resp = obj.get("response") or {}
243
+ u = resp.get("usage") or {}
244
+ if "inputTokens" in u:
245
+ raw_in = int(u.get("inputTokens") or 0)
246
+ cr = int(u.get("cacheReadTokens") or u.get("cacheReadInputTokens") or u.get("cache_read_input_tokens") or 0)
247
+ cw = int(u.get("cacheWriteTokens") or u.get("cacheCreationInputTokens") or u.get("cache_creation_input_tokens") or 0)
248
+ out_t = int(u.get("outputTokens") or u.get("output_tokens") or 0)
249
+ if ("cacheReadInputTokens" in u or "cache_read_input_tokens" in u) and "cacheReadTokens" not in u:
250
+ in_t = raw_in + cr + cw
251
+ else:
252
+ in_t = raw_in
253
+ else:
254
+ raw_in = int(u.get("input_tokens") or 0)
255
+ cr = int(u.get("cache_read_input_tokens") or 0)
256
+ cw = int(u.get("cache_creation_input_tokens") or 0)
257
+ in_t = raw_in + cr + cw
258
+ out_t = int(u.get("output_tokens") or 0)
259
+ if in_t == 0:
260
+ zero_usage += 1
261
+ else:
262
+ last_in = in_t
263
+ last_cr = cr
264
+ last_out = out_t
265
+ last_reason_chars = len(resp.get("reasoningText") or "")
266
+ last_text_chars = len(resp.get("text") or "")
267
+ req_body = (obj.get("request") or {}).get("body") or {}
268
+ if isinstance(req_body, dict) and isinstance(req_body.get("tools"), list) and not tool_schema_tokens:
269
+ tool_schema_tokens = len(json.dumps(req_body["tools"], ensure_ascii=False)) // 4
270
+
271
+ # Check recent ZCode daily log for 1302/1308/1310 rate limits
272
+ rate_limit_hits: Dict[str, int] = {}
273
+ log_dir = os.path.join(home, ".zcode", "cli", "log")
274
+ if os.path.isdir(log_dir):
275
+ logs = sorted(glob.glob(os.path.join(log_dir, "zcode-*.jsonl")), key=os.path.getmtime, reverse=True)
276
+ if logs:
277
+ for ln in _read_tail_lines(logs[0], max_bytes=65536):
278
+ if "model.request.failed" in ln or "rate_limit" in ln:
279
+ for code in _RATE_LIMIT_CODES:
280
+ if code in ln:
281
+ rate_limit_hits[code] = rate_limit_hits.get(code, 0) + 1
282
+
283
+ cache_hit_pct = round((last_cr / last_in * 100.0), 1) if last_in > 0 else 100.0
284
+ return {
285
+ "agent": "zcode",
286
+ "file_path": best_path,
287
+ "model": prev_model,
288
+ "turns_sampled": turns,
289
+ "last_input_tokens": last_in,
290
+ "last_cache_read_tokens": last_cr,
291
+ "last_output_tokens": last_out,
292
+ "cache_hit_pct": cache_hit_pct,
293
+ "model_switches": model_switches,
294
+ "zero_usage_turns": zero_usage,
295
+ "reasoning_chars": last_reason_chars,
296
+ "visible_chars": last_text_chars,
297
+ "tool_schema_tokens": tool_schema_tokens,
298
+ "active_parallel_sessions": active_parallel,
299
+ "rate_limit_hits": rate_limit_hits,
300
+ }
301
+
302
+
303
+ def _scan_claude_or_kimi_tail(transcript_path: str, agent: str) -> Optional[Dict[str, Any]]:
304
+ if not transcript_path or not os.path.isfile(transcript_path):
305
+ return None
306
+ lines = _read_tail_lines(transcript_path, max_bytes=65536)
307
+ last_in = last_cr = last_cw = last_out = 0
308
+ prev_model = ""
309
+ model_switches = 0
310
+ turns = 0
311
+ prev_ts: Optional[float] = None
312
+ max_gap_s = 0.0
313
+
314
+ for ln in lines[-30:]:
315
+ try:
316
+ obj = json.loads(ln)
317
+ except Exception:
318
+ continue
319
+ ts = _parse_iso(obj.get("timestamp") or obj.get("created_at"))
320
+ if ts is not None:
321
+ if prev_ts is not None:
322
+ max_gap_s = max(max_gap_s, ts - prev_ts)
323
+ prev_ts = ts
324
+ msg = obj.get("message") if isinstance(obj.get("message"), dict) else obj
325
+ u = msg.get("usage") if isinstance(msg, dict) else None
326
+ m_id = str((msg.get("model") if isinstance(msg, dict) else "") or obj.get("model") or "")
327
+ if m_id:
328
+ if prev_model and m_id != prev_model:
329
+ model_switches += 1
330
+ prev_model = m_id
331
+ if isinstance(u, dict):
332
+ turns += 1
333
+ raw_in = int(u.get("input_tokens") or 0)
334
+ cr = int(u.get("cache_read_input_tokens") or 0)
335
+ cw = int(u.get("cache_creation_input_tokens") or 0)
336
+ tot_in = raw_in + cr + cw
337
+ if tot_in > 0:
338
+ last_in = tot_in
339
+ last_cr = cr
340
+ last_cw = cw
341
+ last_out = int(u.get("output_tokens") or 0)
342
+
343
+ if turns == 0 and not lines:
344
+ return None
345
+ cache_hit_pct = round((last_cr / last_in * 100.0), 1) if last_in > 0 else 100.0
346
+ return {
347
+ "agent": agent,
348
+ "file_path": transcript_path,
349
+ "model": prev_model,
350
+ "turns_sampled": turns,
351
+ "last_input_tokens": last_in,
352
+ "last_cache_read_tokens": last_cr,
353
+ "last_cache_write_tokens": last_cw,
354
+ "last_output_tokens": last_out,
355
+ "cache_hit_pct": cache_hit_pct,
356
+ "model_switches": model_switches,
357
+ "max_gap_seconds": round(max_gap_s, 1),
358
+ "active_parallel_sessions": 1,
359
+ "rate_limit_hits": {},
360
+ }
361
+
362
+
363
+ def _scan_generic_transcript_tail(transcript_path: str, agent: str) -> Optional[Dict[str, Any]]:
364
+ if not transcript_path or not os.path.isfile(transcript_path):
365
+ return None
366
+ lines = _read_tail_lines(transcript_path, max_bytes=65536)
367
+ turns = 0
368
+ spills = 0
369
+ total_chars = 0
370
+ prev_ts: Optional[float] = None
371
+ max_gap_s = 0.0
372
+ for ln in lines:
373
+ total_chars += len(ln)
374
+ try:
375
+ step = json.loads(ln)
376
+ except Exception:
377
+ continue
378
+ ts = _parse_iso(step.get("created_at") or step.get("timestamp"))
379
+ if ts is not None:
380
+ if prev_ts is not None:
381
+ max_gap_s = max(max_gap_s, ts - prev_ts)
382
+ prev_ts = ts
383
+ if step.get("type") == "PLANNER_RESPONSE" or step.get("tool_calls") or step.get("role") == "assistant":
384
+ turns += 1
385
+ content = step.get("content") or ""
386
+ if isinstance(content, str) and "The output was large and was saved to:" in content:
387
+ spills += 1
388
+ return {
389
+ "agent": agent,
390
+ "file_path": transcript_path,
391
+ "model": "",
392
+ "turns_sampled": turns,
393
+ "last_input_tokens": total_chars // 4,
394
+ "last_cache_read_tokens": 0,
395
+ "last_output_tokens": 0,
396
+ "cache_hit_pct": 100.0,
397
+ "model_switches": 0,
398
+ "disk_spills": spills,
399
+ "max_gap_seconds": round(max_gap_s, 1),
400
+ "active_parallel_sessions": 1,
401
+ "rate_limit_hits": {},
402
+ }
403
+
404
+
405
+ def collect_live_burn_snapshot(
406
+ agent: str = "auto",
407
+ session_id: str = "",
408
+ transcript_path: str = "",
409
+ home_dir: Optional[str] = None,
410
+ ) -> Optional[Dict[str, Any]]:
411
+ """Collects a fast tail snapshot of the active session for any supported agent."""
412
+ home = home_dir or os.path.expanduser("~")
413
+ ag = (agent or "auto").lower()
414
+
415
+ if ag == "zcode" or (transcript_path and "model-io-" in os.path.basename(transcript_path)):
416
+ return _scan_zcode_tail(home, session_id=session_id, explicit_path=transcript_path)
417
+
418
+ if ag in ("claude_code", "claude", "kimi", "kimi_code"):
419
+ if transcript_path and os.path.isfile(transcript_path):
420
+ return _scan_claude_or_kimi_tail(transcript_path, ag)
421
+ if ag in ("claude_code", "claude"):
422
+ proj_files = glob.glob(os.path.join(home, ".claude", "projects", "*", "*.jsonl"))
423
+ if proj_files:
424
+ newest = max(proj_files, key=os.path.getmtime)
425
+ if time.time() - os.path.getmtime(newest) <= 3600:
426
+ return _scan_claude_or_kimi_tail(newest, "claude_code")
427
+ return None
428
+
429
+ if transcript_path and os.path.isfile(transcript_path):
430
+ return _scan_generic_transcript_tail(transcript_path, ag)
431
+
432
+ if ag == "auto":
433
+ z = _scan_zcode_tail(home, session_id=session_id)
434
+ if z:
435
+ return z
436
+ return None
437
+
438
+
439
+ def evaluate_burn_warnings(
440
+ snapshot: Optional[Dict[str, Any]],
441
+ now: Optional[datetime.datetime] = None,
442
+ ) -> List[Dict[str, str]]:
443
+ """Evaluates structured burn warnings from a live snapshot."""
444
+ if not snapshot:
445
+ return []
446
+ warnings: List[Dict[str, str]] = []
447
+ model = str(snapshot.get("model") or "")
448
+ m_lower = model.lower()
449
+ in_tok = int(snapshot.get("last_input_tokens") or 0)
450
+ cache_hit = float(snapshot.get("cache_hit_pct") or 100.0)
451
+ turns = int(snapshot.get("turns_sampled") or 0)
452
+ switches = int(snapshot.get("model_switches") or 0)
453
+ parallel = int(snapshot.get("active_parallel_sessions") or 0)
454
+ reason_c = int(snapshot.get("reasoning_chars") or 0)
455
+ vis_c = int(snapshot.get("visible_chars") or 0)
456
+ tool_tok = int(snapshot.get("tool_schema_tokens") or 0)
457
+ rl_hits = snapshot.get("rate_limit_hits") or {}
458
+
459
+ if in_tok >= 120000:
460
+ warnings.append({
461
+ "code": "context_bloat",
462
+ "message": (
463
+ f"Session context reached {in_tok:,} tokens — even cached turns burn high quota. "
464
+ f"Consider starting a fresh session or compacting."
465
+ ),
466
+ })
467
+
468
+ if turns >= 2 and in_tok >= 20000 and cache_hit < 50.0:
469
+ extra = " (triggered by mid-session model switch)" if switches > 0 else ""
470
+ warnings.append({
471
+ "code": "cache_crash",
472
+ "message": (
473
+ f"Prompt cache hit dropped to {cache_hit:.0f}% on {in_tok:,} input tokens{extra} — "
474
+ f"uncached reads burn ~4x more quota."
475
+ ),
476
+ })
477
+
478
+ if "glm-5.3" in m_lower and "flash" not in m_lower and is_zai_peak_hour(now):
479
+ warnings.append({
480
+ "code": "zai_peak_glm53",
481
+ "message": (
482
+ f"Running {model} during Z.ai Peak Hours (14:00-18:00 UTC+8, 2x rate vs off-peak). "
483
+ f"GLM-5.4 is ~33% cheaper and GLM-5.3-Flash is ~6x cheaper."
484
+ ),
485
+ })
486
+
487
+ if reason_c > 8000 and reason_c > max(1, vis_c) * 4:
488
+ warnings.append({
489
+ "code": "hidden_reasoning",
490
+ "message": (
491
+ f"Hidden thinking consumed {reason_c:,} chars vs {vis_c:,} visible chars on last turn "
492
+ f"(output tokens carry the highest multiplier)."
493
+ ),
494
+ })
495
+
496
+ if parallel >= 2:
497
+ warnings.append({
498
+ "code": "parallel_sessions",
499
+ "message": (
500
+ f"{parallel} active sessions are drawing from the same quota pool concurrently "
501
+ f"(risk of 1302 concurrency throttling and multiplied burn)."
502
+ ),
503
+ })
504
+
505
+ if tool_tok >= 15000:
506
+ warnings.append({
507
+ "code": "tool_schema_bloat",
508
+ "message": (
509
+ f"Declared tool schemas add ~{tool_tok:,} tokens on every turn. "
510
+ f"Disable unused MCP servers to cut baseline burn."
511
+ ),
512
+ })
513
+
514
+ if rl_hits:
515
+ summary = ", ".join(f"{k}x{v}" for k, v in sorted(rl_hits.items()))
516
+ warnings.append({
517
+ "code": "rate_limit_recent",
518
+ "message": f"Recent Z.ai rate/quota errors detected in logs ({summary}).",
519
+ })
520
+
521
+ return warnings
522
+
523
+
524
+ def _dedup_state_path() -> str:
525
+ try:
526
+ from src.paths import resolve_data_dir
527
+ return os.path.join(resolve_data_dir(), "burn_alerts_state.json")
528
+ except Exception:
529
+ return os.path.join(os.path.expanduser("~"), ".tokensafe", "data", "burn_alerts_state.json")
530
+
531
+
532
+ def get_burn_warnings(
533
+ agent: str = "auto",
534
+ session_id: str = "",
535
+ transcript_path: str = "",
536
+ cooldown_seconds: float = 300.0,
537
+ home_dir: Optional[str] = None,
538
+ ) -> Optional[str]:
539
+ """Returns a concise formatted burn alert banner (rate-limited per session+code), or None."""
540
+ snap = collect_live_burn_snapshot(
541
+ agent=agent, session_id=session_id, transcript_path=transcript_path, home_dir=home_dir
542
+ )
543
+ warnings = evaluate_burn_warnings(snap)
544
+ if not warnings:
545
+ return None
546
+
547
+ now = time.time()
548
+ state_path = _dedup_state_path()
549
+ state: Dict[str, float] = {}
550
+ if cooldown_seconds > 0 and os.path.isfile(state_path):
551
+ try:
552
+ with open(state_path, "r", encoding="utf-8") as f:
553
+ loaded = json.load(f)
554
+ if isinstance(loaded, dict):
555
+ state = {k: float(v) for k, v in loaded.items() if now - float(v) < 86400}
556
+ except Exception:
557
+ state = {}
558
+
559
+ fresh: List[Dict[str, str]] = []
560
+ sess_key = session_id or os.path.basename((snap or {}).get("file_path") or "default")
561
+ for w in warnings:
562
+ key = f"{sess_key}:{w['code']}"
563
+ if cooldown_seconds <= 0 or (now - state.get(key, 0.0)) >= cooldown_seconds:
564
+ fresh.append(w)
565
+ state[key] = now
566
+
567
+ if not fresh:
568
+ return None
569
+
570
+ if cooldown_seconds > 0:
571
+ try:
572
+ os.makedirs(os.path.dirname(state_path), exist_ok=True)
573
+ with open(state_path, "w", encoding="utf-8") as f:
574
+ json.dump(state, f)
575
+ except Exception:
576
+ pass
577
+
578
+ lines = ["🔥 **TokenSafe Live Burn Guard:**"]
579
+ for w in fresh[:3]:
580
+ lines.append(f"• {w['message']}")
581
+ return "\n".join(lines)
@@ -55,6 +55,8 @@ def _inject_cache_control_on_msg(msg: Dict[str, Any]) -> bool:
55
55
  continue
56
56
  if btype == "text" and not str(block.get("text", "")).strip():
57
57
  continue
58
+ if "cache_control" in block:
59
+ return False
58
60
  block["cache_control"] = {"type": "ephemeral"}
59
61
  msg["content"] = copied
60
62
  return True
package/src/cli.py CHANGED
@@ -730,6 +730,35 @@ def main(argv: Optional[List[str]] = None):
730
730
  print(f" Backend Runtime: {status['backend'].get('status', 'OK')} ({status['backend'].get('name', 'N/A')})")
731
731
  print(f" Workspace: {status.get('workspace')}\n")
732
732
 
733
+ elif command in ("burn", "burn-monitor"):
734
+ from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
735
+ from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
736
+ agent_filter = "auto"
737
+ for i, a in enumerate(args):
738
+ if a.startswith("--agent="):
739
+ agent_filter = a.split("=", 1)[1]
740
+ elif a in ("--agent", "-a") and i + 1 < len(args):
741
+ agent_filter = args[i + 1]
742
+ print("\n\033[1m\033[36m🔥 TOKENSAFE MULTI-AGENT LIVE BURN MONITOR 🔥\033[0m\n")
743
+ print(f" Z.ai Peak Hours (Mon-Fri 14:00-18:00 SST): {'ACTIVE (1.0x = 2x off-peak)' if is_zai_peak_hour() else 'OFF-PEAK (0.5x rate)'}")
744
+ found = discover_transcript_paths(agent=agent_filter, limit=8)
745
+ if not found:
746
+ print(" No active session transcripts/rollouts found.\n")
747
+ sys.exit(0)
748
+ analyzed = [analyze_transcript(fp, agent_type=ag_type) for ag_type, fp, _ in found]
749
+ print(render_transcripts_report(analyzed))
750
+ for ag in ("zcode", "claude_code", "antigravity"):
751
+ if agent_filter not in ("auto", ag):
752
+ continue
753
+ snap = collect_live_burn_snapshot(agent=ag)
754
+ if snap:
755
+ warns = evaluate_burn_warnings(snap)
756
+ if warns:
757
+ print(f" [{ag}] Active session alerts:")
758
+ for w in warns:
759
+ print(f" • {w['message']}")
760
+ sys.exit(0)
761
+
733
762
  elif command in ("transcripts", "transcript"):
734
763
  from src.transcript_analyzer import (
735
764
  discover_transcript_paths,
@@ -1041,13 +1070,14 @@ def main(argv: Optional[List[str]] = None):
1041
1070
  sys.exit(0)
1042
1071
 
1043
1072
  # 1. Request device code
1073
+ from src.version_checker import CURRENT_VERSION
1044
1074
  machine_fp = LicenseManager.get_machine_fingerprint()
1045
1075
  payload = {
1046
1076
  "machine_fp": machine_fp,
1047
1077
  "platform": platform.system()[:32],
1048
1078
  "arch": platform.machine()[:32],
1049
1079
  "agent": str(LicenseManager.detect_agent())[:32],
1050
- "version": "",
1080
+ "version": CURRENT_VERSION[:32],
1051
1081
  "hostname": platform.node()[:64]
1052
1082
  }
1053
1083
  try:
@@ -1064,7 +1094,7 @@ def main(argv: Optional[List[str]] = None):
1064
1094
  print(" Check your internet connection and try again.\n")
1065
1095
  sys.exit(1)
1066
1096
 
1067
- if not init_data.get("success"):
1097
+ if not (init_data.get("success") or init_data.get("ok")):
1068
1098
  print(f"\033[31m✖ Authorization initiation failed: {init_data.get('error')}\033[0m\n")
1069
1099
  sys.exit(1)
1070
1100
 
@@ -1134,7 +1164,7 @@ def main(argv: Optional[List[str]] = None):
1134
1164
  # 3. Save license and device token
1135
1165
  lic_key = approved_data.get("license_key", "")
1136
1166
  dev_tok = approved_data.get("device_token", "")
1137
- auth_email = approved_data.get("email", "")
1167
+ auth_email = approved_data.get("email") or approved_data.get("user_email") or ""
1138
1168
 
1139
1169
  ok, msg = LicenseManager.save_license(lic_key, device_token=dev_tok)
1140
1170
  if ok:
@@ -1614,7 +1644,7 @@ def main(argv: Optional[List[str]] = None):
1614
1644
 
1615
1645
  else:
1616
1646
  print(f"Unknown command: {command}")
1617
- print("Available commands: stats, status, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
1647
+ print("Available commands: init, login, logout, stats, status, sync, html, test, tests, expand-ref, wrap, web, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, mistakes, vacuum, prune, digest, activate, license, markdown, install, uninstall, setup, update, check-update, reset. Run 'tokensafe help' for details.")
1618
1648
  sys.exit(1)
1619
1649
 
1620
1650
  if __name__ == "__main__":
package/src/compactor.py CHANGED
@@ -79,7 +79,7 @@ class PromptCompactor:
79
79
  r"\b(можешь ли ты|можешь|не мог бы ты|помоги мне|помоги пожалуйста|мне нужно|я хочу чтобы ты|я хочу|нужно чтобы|надо чтобы|надо|нужно|давай)\b",
80
80
  r"\b(подскажи как|подскажи пожалуйста|подскажи|расскажи как|сделай так чтобы|сделай пожалуйста|попробуй|попробуем)\b",
81
81
  r"\b(как думаешь|как считаешь|по твоему мнению|в чем проблема|почему|почему падает|не работает)\b",
82
- r"\b(в файле|из файла|внутри файла|файле|файл|функцию|функция|функции|метод|методе|метода|класс|классе|класса|код|кода|строку|строка|проект|проекта|проекте|описани\w*|пояснени\w*|информаци\w*|баз\w*\s+данных|баз[аеуоы]|бд|database)\b",
82
+ r"\b(в файле|из файла|внутри файла|файле|файл|функцию|функция|функции|метод|методе|метода|класс|классе|класса|код|кода|строку|строка|проект|проекта|проекте|описани\w*|пояснени\w*|информаци\w*)\b",
83
83
  r"\b(добавь туда|сделай её|сделай его|сделай их|чтобы было|чтобы он|чтобы она|чтобы оно|для этого|для того чтобы)\b",
84
84
  # Note: «не» (negation) is deliberately NOT stripped — removing it inverted
85
85
  # the meaning of prompts like "не удаляй файл" ("do not delete the file").