tokensafe 4.5.0 → 4.5.2

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 +78 -13
  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 +96 -54
  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
@@ -19,92 +19,127 @@ import json
19
19
  import datetime
20
20
  from typing import Dict, Any, List, Optional, Tuple
21
21
 
22
+ from src.burn_monitor import estimate_zai_credits, evaluate_burn_warnings
23
+
22
24
 
23
25
  def _parse_iso_ts(ts_str: Optional[str]) -> Optional[datetime.datetime]:
24
- if not ts_str:
26
+ if not ts_str or not isinstance(ts_str, str):
25
27
  return None
26
28
  try:
27
- # Normalize trailing Z or offsets
28
29
  clean = ts_str.replace("Z", "+00:00")
29
- return datetime.datetime.fromisoformat(clean)
30
+ dt = datetime.datetime.fromisoformat(clean)
31
+ if dt.tzinfo is None:
32
+ dt = dt.replace(tzinfo=datetime.timezone.utc)
33
+ return dt
30
34
  except Exception:
31
35
  return None
32
36
 
33
37
 
38
+ def _detect_agent_from_path(file_path: str) -> str:
39
+ norm = file_path.replace("\\", "/")
40
+ if "/.zcode/" in norm or os.path.basename(norm).startswith("model-io-"):
41
+ return "zcode"
42
+ if "/.claude/" in norm:
43
+ return "claude"
44
+ if "/.codex/" in norm:
45
+ return "codex"
46
+ if "/.kimi-code/" in norm:
47
+ return "kimi"
48
+ if "/.cursor/" in norm:
49
+ return "cursor"
50
+ if "/.gemini/" in norm:
51
+ return "antigravity"
52
+ return "auto"
53
+
54
+
34
55
  def discover_transcript_paths(
35
56
  agent: str = "auto",
36
57
  explicit_path: Optional[str] = None,
37
58
  limit: int = 20
38
59
  ) -> List[Tuple[str, str, float]]:
39
60
  """
40
- Finds transcript files sorted newest first.
61
+ Finds transcript files sorted newest first across Antigravity, ZCode,
62
+ Claude Code, Codex, Kimi, and Cursor.
41
63
  Returns list of (agent_type, file_path, mtime).
42
64
  """
43
65
  if explicit_path:
44
66
  p = os.path.abspath(explicit_path)
45
67
  if os.path.isfile(p):
46
- return [("custom", p, os.path.getmtime(p))]
68
+ det = _detect_agent_from_path(p)
69
+ return [(det if det != "auto" else "custom", p, os.path.getmtime(p))]
47
70
  elif os.path.isdir(p):
48
71
  found = []
49
72
  for root, _, files in os.walk(p):
50
73
  for f in files:
51
74
  if f.endswith(".jsonl"):
52
75
  fp = os.path.join(root, f)
53
- found.append(("custom", fp, os.path.getmtime(fp)))
76
+ det = _detect_agent_from_path(fp)
77
+ found.append((det if det != "auto" else "custom", fp, os.path.getmtime(fp)))
54
78
  found.sort(key=lambda x: x[2], reverse=True)
55
79
  return found[:limit]
56
80
 
57
81
  home = os.path.expanduser("~")
58
82
  candidates: List[Tuple[str, str, float]] = []
83
+ ag = (agent or "auto").lower()
59
84
 
60
- # 1. Google Antigravity transcripts
61
- if agent in ("auto", "antigravity", "gemini"):
62
- agy_patterns = [
63
- os.path.join(home, ".gemini", "antigravity", "brain", "*", ".system_generated", "logs", "transcript.jsonl"),
64
- os.path.join(home, ".gemini", "antigravity", "brain", "*", "transcript.jsonl"),
65
- ]
66
- for pat in agy_patterns:
67
- for fp in glob.glob(pat):
68
- try:
69
- candidates.append(("antigravity", fp, os.path.getmtime(fp)))
70
- except Exception:
71
- pass
72
-
73
- # 2. Claude Code transcripts
74
- if agent in ("auto", "claude", "claude_code"):
75
- claude_pattern = os.path.join(home, ".claude", "projects", "*", "transcripts", "*.jsonl")
76
- for fp in glob.glob(claude_pattern):
85
+ def _add_glob(ag_label: str, pattern: str, recursive: bool = False) -> None:
86
+ for fp in glob.glob(pattern, recursive=recursive):
77
87
  try:
78
- candidates.append(("claude", fp, os.path.getmtime(fp)))
79
- except Exception:
80
- pass
81
- claude_sess = os.path.join(home, ".claude", "sessions", "*.jsonl")
82
- for fp in glob.glob(claude_sess):
83
- try:
84
- candidates.append(("claude", fp, os.path.getmtime(fp)))
88
+ candidates.append((ag_label, fp, os.path.getmtime(fp)))
85
89
  except Exception:
86
90
  pass
87
91
 
88
- # 3. Codex transcripts
89
- if agent in ("auto", "codex"):
90
- codex_pattern = os.path.join(home, ".codex", "sessions", "*.jsonl")
91
- for fp in glob.glob(codex_pattern):
92
- try:
93
- candidates.append(("codex", fp, os.path.getmtime(fp)))
94
- except Exception:
95
- pass
92
+ # 1. Google Antigravity transcripts
93
+ if ag in ("auto", "antigravity", "gemini"):
94
+ _add_glob("antigravity", os.path.join(home, ".gemini", "antigravity", "brain", "*", ".system_generated", "logs", "transcript.jsonl"))
95
+ _add_glob("antigravity", os.path.join(home, ".gemini", "antigravity", "brain", "*", "transcript.jsonl"))
96
+
97
+ # 2. ZCode model-io rollouts
98
+ if ag in ("auto", "zcode", "z.ai"):
99
+ _add_glob("zcode", os.path.join(home, ".zcode", "cli", "rollout", "model-io-*.jsonl"))
100
+
101
+ # 3. Claude Code transcripts
102
+ if ag in ("auto", "claude", "claude_code"):
103
+ _add_glob("claude", os.path.join(home, ".claude", "projects", "*", "transcripts", "*.jsonl"))
104
+ _add_glob("claude", os.path.join(home, ".claude", "projects", "*", "*.jsonl"))
105
+ _add_glob("claude", os.path.join(home, ".claude", "sessions", "*.jsonl"))
106
+
107
+ # 4. Codex transcripts
108
+ if ag in ("auto", "codex"):
109
+ _add_glob("codex", os.path.join(home, ".codex", "sessions", "**", "*.jsonl"), recursive=True)
96
110
 
97
- candidates.sort(key=lambda x: x[2], reverse=True)
98
- return candidates[:limit]
111
+ # 5. Kimi Code transcripts
112
+ if ag in ("auto", "kimi", "kimi_code"):
113
+ _add_glob("kimi", os.path.join(home, ".kimi-code", "sessions", "**", "*.jsonl"), recursive=True)
114
+
115
+ # 6. Cursor transcripts
116
+ if ag in ("auto", "cursor"):
117
+ _add_glob("cursor", os.path.join(home, ".cursor", "projects", "*", "agent-transcripts", "*.jsonl"))
118
+
119
+ seen = set()
120
+ unique: List[Tuple[str, str, float]] = []
121
+ for item in candidates:
122
+ if item[1] not in seen:
123
+ seen.add(item[1])
124
+ unique.append(item)
125
+
126
+ unique.sort(key=lambda x: x[2], reverse=True)
127
+ return unique[:limit]
99
128
 
100
129
 
101
130
  def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[str, Any]:
102
131
  """
103
- Parses a single transcript.jsonl file and extracts latency, turns, tool calls, and spills.
132
+ Parses a single transcript/rollout JSONL file across Antigravity, ZCode,
133
+ Claude Code, Codex, Kimi, or Cursor.
104
134
  """
105
135
  if not os.path.isfile(file_path):
106
136
  return {"error": f"File not found: {file_path}"}
107
137
 
138
+ detected_agent = agent_type
139
+ if detected_agent in ("auto", "custom", ""):
140
+ p_agent = _detect_agent_from_path(file_path)
141
+ detected_agent = p_agent if p_agent != "auto" else "antigravity"
142
+
108
143
  total_lines = 0
109
144
  llm_turns = 0
110
145
  total_tool_calls = 0
@@ -114,9 +149,36 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
114
149
 
115
150
  timestamps: List[datetime.datetime] = []
116
151
  long_turn_gaps = 0
117
-
118
152
  prev_ts: Optional[datetime.datetime] = None
119
153
 
154
+ total_input = 0
155
+ total_cache_read = 0
156
+ total_cache_write = 0
157
+ total_output = 0
158
+ total_reasoning_chars = 0
159
+ total_visible_chars = 0
160
+ tool_schema_tokens = 0
161
+ model_switches = 0
162
+ prev_model = ""
163
+ last_in = last_cr = last_out = last_reason_chars = last_vis_chars = 0
164
+ est_credits_total = 0.0
165
+
166
+ def _track_ts(dt: Optional[datetime.datetime]) -> None:
167
+ nonlocal prev_ts, long_turn_gaps
168
+ if dt is None:
169
+ return
170
+ timestamps.append(dt)
171
+ if prev_ts is not None and (dt - prev_ts).total_seconds() > 60:
172
+ long_turn_gaps += 1
173
+ prev_ts = dt
174
+
175
+ def _track_tool(t_name: str) -> None:
176
+ nonlocal total_tool_calls, tokensafe_calls
177
+ total_tool_calls += 1
178
+ tool_counts[t_name] = tool_counts.get(t_name, 0) + 1
179
+ if "tokensafe" in t_name.lower():
180
+ tokensafe_calls += 1
181
+
120
182
  try:
121
183
  with open(file_path, "r", encoding="utf-8", errors="replace") as f:
122
184
  for line in f:
@@ -128,30 +190,129 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
128
190
  step = json.loads(line)
129
191
  except Exception:
130
192
  continue
193
+ if not isinstance(step, dict):
194
+ continue
195
+
196
+ # ZCode model-io schema
197
+ if step.get("type") == "model_io" or ("request" in step and "response" in step and "model" in step):
198
+ if detected_agent == "antigravity":
199
+ detected_agent = "zcode"
200
+ llm_turns += 1
201
+ _track_ts(_parse_iso_ts(step.get("startedAt") or step.get("completedAt")))
202
+ m_info = step.get("model")
203
+ m_id = (m_info.get("modelId") or m_info.get("id") or "") if isinstance(m_info, dict) else str(m_info or "")
204
+ if m_id:
205
+ if prev_model and m_id != prev_model:
206
+ model_switches += 1
207
+ prev_model = m_id
208
+
209
+ req_body = (step.get("request") or {}).get("body") or {}
210
+ if not tool_schema_tokens and isinstance(req_body, dict) and isinstance(req_body.get("tools"), list):
211
+ tool_schema_tokens = len(json.dumps(req_body["tools"], ensure_ascii=False)) // 4
212
+
213
+ resp = step.get("response") or {}
214
+ for tc in resp.get("toolCalls") or []:
215
+ if isinstance(tc, dict):
216
+ _track_tool(str(tc.get("toolName") or tc.get("name") or "unknown"))
217
+
218
+ rtxt = resp.get("reasoningText") or ""
219
+ ttxt = resp.get("text") or ""
220
+ total_reasoning_chars += len(rtxt)
221
+ total_visible_chars += len(ttxt)
222
+
223
+ u = resp.get("usage") or {}
224
+ if "inputTokens" in u:
225
+ raw_in = int(u.get("inputTokens") or 0)
226
+ cr = int(u.get("cacheReadTokens") or u.get("cacheReadInputTokens") or u.get("cache_read_input_tokens") or 0)
227
+ cw = int(u.get("cacheWriteTokens") or u.get("cacheCreationInputTokens") or u.get("cache_creation_input_tokens") or 0)
228
+ out_t = int(u.get("outputTokens") or u.get("output_tokens") or 0)
229
+ if ("cacheReadInputTokens" in u or "cache_read_input_tokens" in u) and "cacheReadTokens" not in u:
230
+ in_t = raw_in + cr + cw
231
+ uncached_turn = raw_in
232
+ else:
233
+ in_t = raw_in
234
+ uncached_turn = max(0, in_t - cr)
235
+ else:
236
+ raw_in = int(u.get("input_tokens") or 0)
237
+ cr = int(u.get("cache_read_input_tokens") or 0)
238
+ cw = int(u.get("cache_creation_input_tokens") or 0)
239
+ in_t = raw_in + cr + cw
240
+ uncached_turn = raw_in
241
+ out_t = int(u.get("output_tokens") or 0)
242
+ if in_t > 0:
243
+ last_in, last_cr, last_out = in_t, cr, out_t
244
+ last_reason_chars, last_vis_chars = len(rtxt), len(ttxt)
245
+ total_input += in_t
246
+ total_cache_read += cr
247
+ total_cache_write += cw
248
+ total_output += out_t
249
+ if "glm" in m_id.lower():
250
+ est_credits_total += estimate_zai_credits(uncached_turn, cr, out_t, model=m_id)
251
+ continue
252
+
253
+ # Claude Code / Kimi JSONL schema
254
+ msg = step.get("message") if isinstance(step.get("message"), dict) else None
255
+ if msg is not None:
256
+ _track_ts(_parse_iso_ts(step.get("timestamp") or step.get("created_at")))
257
+ m_id = str(msg.get("model") or step.get("model") or "")
258
+ if m_id:
259
+ if prev_model and m_id != prev_model:
260
+ model_switches += 1
261
+ prev_model = m_id
262
+ if msg.get("role") == "assistant" or step.get("type") == "assistant":
263
+ llm_turns += 1
264
+ u = msg.get("usage")
265
+ if isinstance(u, dict):
266
+ raw_in = int(u.get("input_tokens") or 0)
267
+ cr = int(u.get("cache_read_input_tokens") or 0)
268
+ cw = int(u.get("cache_creation_input_tokens") or 0)
269
+ out_t = int(u.get("output_tokens") or 0)
270
+ tot_in = raw_in + cr + cw
271
+ if tot_in > 0:
272
+ last_in, last_cr, last_out = tot_in, cr, out_t
273
+ total_input += tot_in
274
+ total_cache_read += cr
275
+ total_cache_write += cw
276
+ total_output += out_t
277
+ content = msg.get("content")
278
+ if isinstance(content, list):
279
+ for blk in content:
280
+ if isinstance(blk, dict) and blk.get("type") == "tool_use":
281
+ _track_tool(str(blk.get("name") or "unknown"))
282
+ elif isinstance(blk, dict) and blk.get("type") == "thinking":
283
+ total_reasoning_chars += len(str(blk.get("thinking") or ""))
284
+ elif isinstance(blk, dict) and blk.get("type") == "text":
285
+ total_visible_chars += len(str(blk.get("text") or ""))
286
+ continue
287
+
288
+ # Codex event schema
289
+ payload = step.get("payload") if isinstance(step.get("payload"), dict) else {}
290
+ if step.get("type") == "event_msg" and payload.get("type") == "token_count":
291
+ _track_ts(_parse_iso_ts(step.get("timestamp")))
292
+ last_u = (payload.get("info") or {}).get("last_token_usage") or {}
293
+ if isinstance(last_u, dict):
294
+ llm_turns += 1
295
+ in_t = int(last_u.get("input_tokens") or 0)
296
+ cr = int(last_u.get("cached_input_tokens") or 0)
297
+ out_t = int(last_u.get("output_tokens") or 0)
298
+ total_input += in_t
299
+ total_cache_read += cr
300
+ total_output += out_t
301
+ if in_t > 0:
302
+ last_in, last_cr, last_out = in_t, cr, out_t
303
+ continue
131
304
 
132
305
  # Antigravity schema
133
306
  s_type = step.get("type")
134
- created_at = _parse_iso_ts(step.get("created_at"))
135
- if created_at:
136
- timestamps.append(created_at)
137
- if prev_ts:
138
- gap_sec = (created_at - prev_ts).total_seconds()
139
- if gap_sec > 60:
140
- long_turn_gaps += 1
141
- prev_ts = created_at
142
-
307
+ _track_ts(_parse_iso_ts(step.get("created_at") or step.get("timestamp")))
143
308
  tool_calls = step.get("tool_calls") or []
144
309
  if s_type == "PLANNER_RESPONSE" or tool_calls:
145
310
  llm_turns += 1
146
311
 
147
312
  if isinstance(tool_calls, list):
148
- total_tool_calls += len(tool_calls)
149
313
  for tc in tool_calls:
150
314
  if isinstance(tc, dict):
151
- t_name = tc.get("name") or tc.get("tool") or "unknown"
152
- tool_counts[t_name] = tool_counts.get(t_name, 0) + 1
153
- if "tokensafe" in t_name.lower():
154
- tokensafe_calls += 1
315
+ _track_tool(str(tc.get("name") or tc.get("tool") or "unknown"))
155
316
 
156
317
  content = step.get("content") or ""
157
318
  if isinstance(content, str) and "The output was large and was saved to:" in content:
@@ -164,10 +325,29 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
164
325
  duration_sec = max(0.0, (timestamps[-1] - timestamps[0]).total_seconds())
165
326
 
166
327
  batch_factor = round(total_tool_calls / max(1, llm_turns), 2)
328
+ cache_hit_pct = round((total_cache_read / total_input * 100.0), 1) if total_input > 0 else 0.0
329
+ uncached_input = max(0, total_input - total_cache_read)
330
+ last_cache_hit = round((last_cr / last_in * 100.0), 1) if last_in > 0 else 100.0
331
+ burn_warnings = evaluate_burn_warnings({
332
+ "agent": detected_agent,
333
+ "model": prev_model,
334
+ "turns_sampled": llm_turns,
335
+ "last_input_tokens": last_in,
336
+ "last_cache_read_tokens": last_cr,
337
+ "last_output_tokens": last_out,
338
+ "cache_hit_pct": last_cache_hit,
339
+ "model_switches": model_switches,
340
+ "reasoning_chars": last_reason_chars,
341
+ "visible_chars": last_vis_chars,
342
+ "tool_schema_tokens": tool_schema_tokens,
343
+ "active_parallel_sessions": 1,
344
+ "rate_limit_hits": {},
345
+ })
167
346
 
168
347
  return {
169
348
  "file_path": file_path,
170
- "agent": agent_type,
349
+ "agent": detected_agent,
350
+ "model": prev_model,
171
351
  "total_steps": total_lines,
172
352
  "llm_turns": llm_turns,
173
353
  "total_tool_calls": total_tool_calls,
@@ -176,7 +356,18 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
176
356
  "disk_spills": disk_spills,
177
357
  "tokensafe_calls": tokensafe_calls,
178
358
  "long_turn_gaps_gt_60s": long_turn_gaps,
179
- "duration_seconds": round(duration_sec, 1)
359
+ "duration_seconds": round(duration_sec, 1),
360
+ "input_tokens": total_input,
361
+ "cache_read_tokens": total_cache_read,
362
+ "cache_write_tokens": total_cache_write,
363
+ "uncached_input_tokens": uncached_input,
364
+ "output_tokens": total_output,
365
+ "reasoning_chars": total_reasoning_chars,
366
+ "cache_hit_pct": cache_hit_pct,
367
+ "est_credits": round(est_credits_total, 1),
368
+ "tool_schema_tokens": tool_schema_tokens,
369
+ "model_switches": model_switches,
370
+ "burn_warnings": burn_warnings,
180
371
  }
181
372
 
182
373
 
@@ -221,25 +412,36 @@ def render_transcripts_report(results: List[Dict[str, Any]]) -> str:
221
412
  lines.append("║ 📊 TOKENSAFE TRANSCRIPT BENCHMARK ANALYZER ║")
222
413
  lines.append("╚══════════════════════════════════════════════════════════════════════════════════════════════╝\n")
223
414
 
224
- lines.append(f"{'#':<3} | {'Agent':<12} | {'Turns':<6} | {'Tools':<6} | {'Batching':<8} | {'Spills':<6} | {'Gaps >60s':<10} | {'Duration':<10} | {'Session Path'}")
225
- lines.append("-" * 96)
415
+ lines.append(f"{'#':<3} | {'Agent':<11} | {'Model':<14} | {'Turns':<5} | {'Tools':<5} | {'InTok':<8} | {'Cache%':<6} | {'Credits':<7} | {'Duration':<8} | {'Session Path'}")
416
+ lines.append("-" * 106)
226
417
 
227
418
  for i, res in enumerate(results):
228
419
  if "error" in res:
229
420
  lines.append(f"{i+1:<3} | Error: {res['error']}")
230
421
  continue
231
- agent = res.get("agent", "unknown")[:12]
422
+ agent = str(res.get("agent", "unknown"))[:11]
423
+ model = str(res.get("model") or "-")[:14]
232
424
  turns = res.get("llm_turns", 0)
233
425
  tools = res.get("total_tool_calls", 0)
234
- batch = f"{res.get('tool_batch_factor', 0.0):.2f}x"
235
- spills = res.get("disk_spills", 0)
236
- gaps = res.get("long_turn_gaps_gt_60s", 0)
426
+ in_tok = res.get("input_tokens", 0)
427
+ in_str = f"{in_tok/1000:.0f}k" if in_tok >= 1000 else (str(in_tok) if in_tok else "-")
428
+ cache_str = f"{res.get('cache_hit_pct', 0.0):.0f}%" if in_tok else "-"
429
+ cred = res.get("est_credits", 0.0)
430
+ cred_str = f"{cred:.1f}" if cred else "-"
237
431
  dur = f"{res.get('duration_seconds', 0.0):.0f}s"
238
432
  parts = res.get("file_path", "").split(os.sep)
239
- sess_name = parts[-4] if len(parts) >= 4 and parts[-2] == "logs" else (parts[-2] if len(parts) >= 2 else "session")
240
- if len(sess_name) > 18:
241
- sess_name = sess_name[:15] + "..."
242
- lines.append(f"{i+1:<3} | {agent:<12} | {turns:<6} | {tools:<6} | {batch:<8} | {spills:<6} | {gaps:<10} | {dur:<10} | {sess_name}")
433
+ sess_name = parts[-4] if len(parts) >= 4 and parts[-2] == "logs" else os.path.basename(res.get("file_path", "session"))
434
+ if len(sess_name) > 20:
435
+ sess_name = sess_name[:17] + "..."
436
+ lines.append(f"{i+1:<3} | {agent:<11} | {model:<14} | {turns:<5} | {tools:<5} | {in_str:<8} | {cache_str:<6} | {cred_str:<7} | {dur:<8} | {sess_name}")
437
+
438
+ flagged = [r for r in results if r.get("burn_warnings")]
439
+ if flagged:
440
+ lines.append("\n🔥 Burn Warnings:")
441
+ for r in flagged[:5]:
442
+ name = os.path.basename(r.get("file_path", ""))
443
+ for w in r["burn_warnings"][:2]:
444
+ lines.append(f" • [{r.get('agent')}:{name[:24]}] {w['message']}")
243
445
 
244
446
  lines.append("")
245
447
  return "\n".join(lines)
@@ -563,6 +563,8 @@ class TreeSitterBackend:
563
563
  if ntype in _CONTAINER_NODE_TYPES:
564
564
  cname = cls._extract_symbol_name(node, code_bytes)
565
565
  next_stack = container_stack + [cname] if cname else container_stack
566
+ if keep_symbols is not None and cname and cname in keep_symbols:
567
+ return # Requesting a class/struct/interface preserves all its methods
566
568
  for child in node.children:
567
569
  walk(child, next_stack, in_kept_scope)
568
570
  return
@@ -117,8 +117,9 @@ class TypeSlicer:
117
117
  Resolves symlinks for pnpm/bun and supports scoped packages (@scope/pkg).
118
118
  """
119
119
  curr = os.path.abspath(start_dir or os.getcwd())
120
- parts = package_name.strip().split("/")
121
-
120
+ parts = [p for p in package_name.strip().split("/") if p]
121
+ types_scope_name = package_name.strip().replace("@", "").replace("/", "__")
122
+
122
123
  for _ in range(8):
123
124
  node_modules = os.path.join(curr, "node_modules")
124
125
  if os.path.isdir(node_modules):
@@ -128,6 +129,13 @@ class TypeSlicer:
128
129
  return os.path.realpath(cand)
129
130
  except Exception:
130
131
  return cand
132
+ # Also check standalone @types/<pkg> if main package isn't installed
133
+ types_cand = os.path.join(node_modules, "@types", types_scope_name)
134
+ if os.path.isdir(types_cand):
135
+ try:
136
+ return os.path.realpath(types_cand)
137
+ except Exception:
138
+ return types_cand
131
139
  parent = os.path.dirname(curr)
132
140
  if parent == curr:
133
141
  break
@@ -148,6 +156,15 @@ class TypeSlicer:
148
156
  root_export = meta["exports"].get(".")
149
157
  if isinstance(root_export, dict):
150
158
  types_rel = root_export.get("types")
159
+ if not types_rel:
160
+ for sub_key in ("import", "require", "default", "node"):
161
+ sub = root_export.get(sub_key)
162
+ if isinstance(sub, dict) and sub.get("types"):
163
+ types_rel = sub.get("types")
164
+ break
165
+ if isinstance(sub, dict) and isinstance(sub.get("default"), dict) and sub["default"].get("types"):
166
+ types_rel = sub["default"].get("types")
167
+ break
151
168
  except Exception:
152
169
  pass
153
170
 
@@ -163,17 +180,18 @@ class TypeSlicer:
163
180
  if os.path.isfile(standard_index):
164
181
  return standard_index
165
182
 
166
- # Check @types/<pkg> fallback in node_modules
167
- node_modules_parent = os.path.dirname(pkg_dir)
168
- if os.path.basename(node_modules_parent) != "node_modules":
169
- # Scoped package parent
170
- node_modules_parent = os.path.dirname(node_modules_parent)
171
-
172
- if os.path.basename(node_modules_parent) == "node_modules":
173
- types_scope_name = pkg_name.replace("@", "").replace("/", "__")
174
- types_cand = os.path.join(node_modules_parent, "@types", types_scope_name, "index.d.ts")
175
- if os.path.isfile(types_cand):
176
- return types_cand
183
+ # Check @types/<pkg> fallback in node_modules (including when resolved via .pnpm symlink)
184
+ types_scope_name = pkg_name.replace("@", "").replace("/", "__")
185
+ check_nm = os.path.dirname(pkg_dir)
186
+ for _ in range(5):
187
+ if os.path.basename(check_nm) == "node_modules":
188
+ types_cand = os.path.join(check_nm, "@types", types_scope_name, "index.d.ts")
189
+ if os.path.isfile(types_cand):
190
+ return types_cand
191
+ parent_nm = os.path.dirname(check_nm)
192
+ if parent_nm == check_nm:
193
+ break
194
+ check_nm = parent_nm
177
195
 
178
196
  return None
179
197
 
@@ -200,18 +218,42 @@ class TypeSlicer:
200
218
  open_braces = 0
201
219
  brace_started = False
202
220
  truncated = False
221
+ overload_sig_re = re.compile(
222
+ rf'^\s*(?:export\s+)?(?:declare\s+)?function\s+{re.escape(symbol)}\b'
223
+ )
203
224
 
204
- for line in lines:
225
+ for idx, line in enumerate(lines):
205
226
  collected.append(line)
206
227
  open_braces += line.count("{") - line.count("}")
207
228
  if "{" in line:
208
229
  brace_started = True
209
230
 
210
- # For type alias (type X = ...;) or single-line declarations
211
- if not brace_started and line.strip().endswith(";"):
212
- break
213
- if brace_started and open_braces <= 0:
231
+ if kind == "function" and not brace_started and line.strip().endswith(";"):
232
+ # Collect consecutive TS function overloads for the same symbol
233
+ next_line = lines[idx + 1] if idx + 1 < len(lines) else ""
234
+ if overload_sig_re.match(next_line):
235
+ if len(collected) >= max_lines:
236
+ truncated = True
237
+ break
238
+ continue
214
239
  break
240
+
241
+ if open_braces <= 0:
242
+ stripped = line.strip()
243
+ if stripped.endswith(";"):
244
+ # Wait if next non-empty line continues a union/intersection without semicolon yet
245
+ break
246
+ if brace_started:
247
+ # Wait for trailing union member on type X = { a: 1 } | { b: 2 };
248
+ next_non_empty = ""
249
+ for j in range(idx + 1, min(idx + 4, len(lines))):
250
+ if lines[j].strip():
251
+ next_non_empty = lines[j].strip()
252
+ break
253
+ if next_non_empty.startswith(("|", "&")) or stripped.endswith(("|", "&", "=")):
254
+ continue
255
+ break
256
+
215
257
  if len(collected) >= max_lines:
216
258
  truncated = True
217
259
  break
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.5.0"
20
+ CURRENT_VERSION = "4.5.2"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage