tokensafe 4.6.2 → 4.6.3

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.
package/src/retrofit.py CHANGED
@@ -9,6 +9,13 @@ import json
9
9
  import time
10
10
  from typing import Dict, Any, List, Optional, Tuple
11
11
 
12
+ # Top-level directories that hold frontend source in a repo-root app (as opposed to
13
+ # scripts/, tooling/ and configs, which are .ts/.js but not OUMV-observable).
14
+ _FRONTEND_SOURCE_DIRS = frozenset({
15
+ "src", "app", "pages", "components", "hooks", "lib", "features",
16
+ "views", "stores", "store", "utils", "layouts", "router", "routes", "api",
17
+ })
18
+
12
19
 
13
20
  def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]], List[str]]:
14
21
  """Inspects a single package.json for frontend or Node.js backend stack."""
@@ -125,16 +132,29 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
125
132
  "packages": [],
126
133
  }
127
134
 
135
+ def _add_detected(rel_path: str) -> None:
136
+ if rel_path not in stack["detected_files"]:
137
+ stack["detected_files"].append(rel_path)
138
+
139
+ def _add_package(entry: Dict[str, Any]) -> None:
140
+ """Adds a package once: the same manifest is reachable from the root scan
141
+ (e.g. python/pyproject.toml) and from monorepo discovery."""
142
+ key = (entry.get("role"), entry.get("path"), entry.get("framework"))
143
+ for existing in stack["packages"]:
144
+ if (existing.get("role"), existing.get("path"), existing.get("framework")) == key:
145
+ return
146
+ stack["packages"].append(entry)
147
+
128
148
  def _scan_dir(target_dir: str):
129
149
  rel = os.path.relpath(target_dir, workspace_dir) or "."
130
150
  pkg_json_path = os.path.join(target_dir, "package.json")
131
151
  if os.path.isfile(pkg_json_path):
132
- stack["detected_files"].append(os.path.relpath(pkg_json_path, workspace_dir))
152
+ _add_detected(os.path.relpath(pkg_json_path, workspace_dir))
133
153
  fe_info, be_info, _ = _detect_package_json_entry(pkg_json_path, rel_dir=rel)
134
154
  if fe_info:
135
155
  if not stack["frontend"]:
136
156
  stack["frontend"] = fe_info
137
- stack["packages"].append({
157
+ _add_package({
138
158
  "role": "frontend",
139
159
  "path": rel,
140
160
  "framework": fe_info["framework"],
@@ -147,7 +167,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
147
167
  if be_info:
148
168
  if not stack["backend"]:
149
169
  stack["backend"] = be_info
150
- stack["packages"].append({
170
+ _add_package({
151
171
  "role": "backend",
152
172
  "path": rel,
153
173
  "framework": be_info["framework"],
@@ -163,8 +183,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
163
183
  go_mod_path = os.path.join(target_dir, "go", "go.mod")
164
184
  if os.path.isfile(go_mod_path):
165
185
  rel_mod = os.path.relpath(go_mod_path, workspace_dir)
166
- if rel_mod not in stack["detected_files"]:
167
- stack["detected_files"].append(rel_mod)
186
+ _add_detected(rel_mod)
168
187
  if "go" not in stack["package_managers"]:
169
188
  stack["package_managers"].append("go")
170
189
  framework = "net/http"
@@ -190,7 +209,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
190
209
  }
191
210
  if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
192
211
  stack["backend"] = go_entry
193
- stack["packages"].append({
212
+ _add_package({
194
213
  "role": "backend",
195
214
  "path": go_entry["root"],
196
215
  "framework": framework,
@@ -210,8 +229,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
210
229
  for pf in py_files:
211
230
  if os.path.isfile(pf):
212
231
  rel_pf = os.path.relpath(pf, workspace_dir)
213
- if rel_pf not in stack["detected_files"]:
214
- stack["detected_files"].append(rel_pf)
232
+ _add_detected(rel_pf)
215
233
  if "pip/python" not in stack["package_managers"]:
216
234
  stack["package_managers"].append("pip/python")
217
235
  try:
@@ -236,9 +254,11 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
236
254
  "oumv_supported": supported,
237
255
  "status": "ready" if supported else "planned",
238
256
  }
239
- if not stack["backend"]:
257
+ # A supported Python backend outranks an unsupported Node one,
258
+ # mirroring the Go precedence rule above.
259
+ if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
240
260
  stack["backend"] = py_entry
241
- stack["packages"].append({
261
+ _add_package({
242
262
  "role": "backend",
243
263
  "path": py_entry["root"],
244
264
  "framework": framework,
@@ -253,7 +273,7 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
253
273
 
254
274
  _scan_dir(workspace_dir)
255
275
  if os.path.isfile(os.path.join(workspace_dir, "pnpm-workspace.yaml")):
256
- stack["detected_files"].append("pnpm-workspace.yaml")
276
+ _add_detected("pnpm-workspace.yaml")
257
277
 
258
278
  for lock, pm in [("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm")]:
259
279
  if os.path.isfile(os.path.join(workspace_dir, lock)):
@@ -577,51 +597,88 @@ class OUMVProjectContext:
577
597
  return "auto"
578
598
 
579
599
 
580
- def resolve_zero_footprint_vite_command(
581
- workspace_dir: str,
582
- port: Optional[int] = None,
583
- host: Optional[str] = None,
584
- open_browser: bool = False,
585
- ) -> Tuple[List[str], str]:
586
- """Resolves zero-footprint tokensafe-ui Vite+React runner command without editing repo files."""
600
+ _UI_CLI_CACHE: Dict[str, Tuple[float, Optional[Tuple[List[str], str]]]] = {}
601
+ _UI_CLI_CACHE_TTL: float = 60.0
602
+
603
+
604
+ def _resolve_tokensafe_ui_cli_uncached(workspace_dir: str) -> Optional[Tuple[List[str], str]]:
605
+ """Finds an installed tokensafe-ui CLI without touching the network.
606
+
607
+ Returns (argv prefix, human source) or None when the companion CLI is absent.
608
+ """
587
609
  import shutil
588
610
  import subprocess
589
611
 
590
612
  ws = os.path.abspath(workspace_dir)
591
- cli_flags: List[str] = []
592
- if port is not None:
593
- cli_flags.append(f"--port={port}")
594
- if host:
595
- cli_flags.append(f"--host={host}")
596
- if open_browser:
597
- cli_flags.append("--open")
598
613
 
599
- # 1. Local project node_modules/.bin/tokensafe-ui (if present)
614
+ # 1. Explicit override wins: lets CI pin a checkout without a global install.
615
+ env_cli = os.environ.get("TOKENSAFE_UI_CLI")
616
+ if env_cli and os.path.isfile(env_cli):
617
+ return (["node", env_cli], "TOKENSAFE_UI_CLI")
618
+
619
+ # 2. Local project node_modules/.bin/tokensafe-ui (if present)
600
620
  local_bin = os.path.join(ws, "node_modules", ".bin", "tokensafe-ui")
601
621
  if os.path.isfile(local_bin):
602
- return ([local_bin, "dev", ws, *cli_flags], "local node_modules")
622
+ return ([local_bin], "local node_modules")
603
623
 
604
- # 2. Global tokensafe-ui binary on PATH
624
+ # 3. Global tokensafe-ui binary on PATH
605
625
  global_bin = shutil.which("tokensafe-ui")
606
626
  if global_bin:
607
- return ([global_bin, "dev", ws, *cli_flags], "global PATH")
627
+ return ([global_bin], "global PATH")
608
628
 
609
- # 3. npm global root package
629
+ # 4. npm global root package (nvm-style installs whose bin dir is not on PATH)
610
630
  try:
611
631
  res = subprocess.run(["npm", "root", "-g"], capture_output=True, text=True, timeout=3)
612
632
  if res.returncode == 0:
613
- global_root = res.stdout.strip()
614
- cli_js = os.path.join(global_root, "tokensafe-ui", "bin", "cli.js")
633
+ cli_js = os.path.join(res.stdout.strip(), "tokensafe-ui", "bin", "cli.js")
615
634
  if os.path.isfile(cli_js):
616
- return (["node", cli_js, "dev", ws, *cli_flags], "npm global root")
635
+ return (["node", cli_js], "npm global root")
617
636
  except Exception:
618
637
  pass
638
+ return None
619
639
 
620
- # 4. Explicit override or npx fallback (zero edits to workspace package.json)
621
- env_cli = os.environ.get("TOKENSAFE_UI_CLI")
622
- if env_cli and os.path.isfile(env_cli):
623
- return (["node", env_cli, "dev", ws, *cli_flags], "TOKENSAFE_UI_CLI")
624
640
 
641
+ def resolve_tokensafe_ui_cli(workspace_dir: str) -> Optional[Tuple[List[str], str]]:
642
+ """Cached resolver for the tokensafe-ui CLI (60s TTL per workspace).
643
+
644
+ Called from the command sanitizer, which runs per shell command; the npm-root
645
+ probe alone costs ~200 ms, so it must not repeat on every invocation.
646
+ """
647
+ ws = os.path.abspath(workspace_dir)
648
+ now = time.time()
649
+ hit = _UI_CLI_CACHE.get(ws)
650
+ if hit and (now - hit[0]) < _UI_CLI_CACHE_TTL:
651
+ return hit[1]
652
+ resolved = _resolve_tokensafe_ui_cli_uncached(ws)
653
+ _UI_CLI_CACHE[ws] = (now, resolved)
654
+ return resolved
655
+
656
+
657
+ def resolve_zero_footprint_vite_command(
658
+ workspace_dir: str,
659
+ port: Optional[int] = None,
660
+ host: Optional[str] = None,
661
+ open_browser: bool = False,
662
+ ) -> Tuple[List[str], str]:
663
+ """Resolves zero-footprint tokensafe-ui Vite+React runner command without editing repo files."""
664
+ import shutil
665
+
666
+ ws = os.path.abspath(workspace_dir)
667
+ cli_flags: List[str] = []
668
+ if port is not None:
669
+ cli_flags.append(f"--port={port}")
670
+ if host:
671
+ cli_flags.append(f"--host={host}")
672
+ if open_browser:
673
+ cli_flags.append("--open")
674
+
675
+ resolved = resolve_tokensafe_ui_cli(ws)
676
+ if resolved:
677
+ prefix, source = resolved
678
+ return ([*prefix, "dev", ws, *cli_flags], source)
679
+
680
+ # Explicit `tokensafe dev` may bootstrap the companion package via npx; the
681
+ # command sanitizer never rewrites to this path (see CommandSanitizer).
625
682
  npx_bin = shutil.which("npx") or "npx"
626
683
  return ([npx_bin, "--yes", "tokensafe-ui", "dev", ws, *cli_flags], "npx tokensafe-ui")
627
684
 
@@ -676,7 +733,27 @@ def format_oumv_workspace_brief(workspace_dir: str, include_live: bool = False)
676
733
  return "[TokenSafe OUMV Workspace Matrix | " + " | ".join(parts) + "]"
677
734
 
678
735
 
679
- def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str) -> Optional[Dict[str, Any]]:
736
+ _STACK_CACHE: Dict[str, Tuple[float, Dict[str, Any]]] = {}
737
+ _STACK_CACHE_TTL: float = 60.0
738
+
739
+
740
+ def detect_project_stack_cached(workspace_dir: str, ttl: float = _STACK_CACHE_TTL) -> Dict[str, Any]:
741
+ """Short-TTL cache for hot paths (read/edit hooks run per tool call).
742
+
743
+ Direct callers keep using detect_project_stack() so tests that mutate
744
+ manifests between calls always see fresh results.
745
+ """
746
+ ws = os.path.realpath(os.path.abspath(workspace_dir))
747
+ now = time.time()
748
+ hit = _STACK_CACHE.get(ws)
749
+ if hit and (now - hit[0]) < ttl:
750
+ return hit[1]
751
+ stack = detect_project_stack(workspace_dir)
752
+ _STACK_CACHE[ws] = (now, stack)
753
+ return stack
754
+
755
+
756
+ def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str, use_cache: bool = False) -> Optional[Dict[str, Any]]:
680
757
  """Returns the supported stack entry owning `file_path`, or None if unsupported (e.g. backend/node)."""
681
758
  if not workspace_dir or not file_path:
682
759
  return None
@@ -686,7 +763,7 @@ def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str) -> Optio
686
763
  return None
687
764
 
688
765
  rel = os.path.relpath(f_abs, ws_abs).replace(os.sep, "/")
689
- stack = detect_project_stack(ws_abs)
766
+ stack = detect_project_stack_cached(ws_abs) if use_cache else detect_project_stack(ws_abs)
690
767
  packages = stack.get("packages") or []
691
768
  # Match most specific package path first
692
769
  sorted_pkgs = sorted(
@@ -701,8 +778,18 @@ def is_path_in_supported_oumv_scope(workspace_dir: str, file_path: str) -> Optio
701
778
  return None
702
779
  ext = os.path.splitext(f_abs)[1].lower()
703
780
  role = pkg.get("role")
704
- if role == "frontend" and ext in (".tsx", ".jsx", ".vue", ".ts", ".js"):
705
- return pkg
781
+ if role == "frontend":
782
+ if ext in (".tsx", ".jsx", ".vue"):
783
+ return pkg
784
+ if ext in (".ts", ".js"):
785
+ # A repository-root frontend also owns scripts/, configs and
786
+ # tooling in .ts/.js; only nudge files under source-like dirs.
787
+ if p_rel != ".":
788
+ return pkg
789
+ top = rel.split("/", 1)[0].lower()
790
+ if "/" in rel and top in _FRONTEND_SOURCE_DIRS:
791
+ return pkg
792
+ return None
706
793
  if role == "backend" and ext in (".go", ".py"):
707
794
  return pkg
708
795
  return None
package/src/snapshot.py CHANGED
@@ -286,8 +286,9 @@ def build_workspace_snapshot(workspace_dir: str, max_bytes: int = 1400) -> Optio
286
286
 
287
287
  sections = ["[TokenSafe Workspace Snapshot]"]
288
288
 
289
- # 1. Git summary
290
- git_sum = _get_git_summary(workspace_dir)
289
+ # 1. Git summary. SessionStart blocks on this, and it issues three sequential
290
+ # git calls: keep the per-call budget at 0.6s (<=1.8s total), not 2s each.
291
+ git_sum = _get_git_summary(workspace_dir, timeout_sec=0.6)
291
292
  if git_sum:
292
293
  sections.append(git_sum)
293
294
 
@@ -249,7 +249,7 @@ class TelemetrySync:
249
249
  current_last_id = last_id
250
250
  headers = {
251
251
  "Content-Type": "application/json",
252
- "User-Agent": "TokenSafe-Sync/4.6.2"
252
+ "User-Agent": "TokenSafe-Sync/4.6.3"
253
253
  }
254
254
  if active_key:
255
255
  headers["Authorization"] = f"Bearer {active_key}"
@@ -316,7 +316,11 @@ class TelemetrySync:
316
316
  "model": "aggregate",
317
317
  "timestamp": int(time.time()),
318
318
  # Rolled-up historical mass of mixed provenance: conservatively estimated.
319
- "measurement": "estimated"
319
+ "measurement": "estimated",
320
+ # Idempotency key: the cumulative total at emit time.
321
+ # A replay (state loss) repeats the same key and the
322
+ # server collapses it; a newer total is a real delta.
323
+ "client_event_id": f"rollup:{current_rollup_tokens}",
320
324
  })
321
325
  except Exception:
322
326
  pass
@@ -145,7 +145,9 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
145
145
  tool_counts: Dict[str, int] = {}
146
146
  disk_spills = 0
147
147
  tokensafe_calls = 0
148
- schema_matched = False
148
+ # Only branches that positively recognise a schema set this. The Antigravity
149
+ # catch-all matches any {"type": ...} line, so it must not count as recognition.
150
+ explicit_matched = False
149
151
  seen_claude_messages = set()
150
152
 
151
153
  timestamps: List[datetime.datetime] = []
@@ -196,7 +198,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
196
198
 
197
199
  # ZCode model-io schema
198
200
  if step.get("type") == "model_io" or ("request" in step and "response" in step and "model" in step):
199
- schema_matched = True
201
+ explicit_matched = True
200
202
  if detected_agent in ("antigravity", "unknown"):
201
203
  detected_agent = "zcode"
202
204
  llm_turns += 1
@@ -255,7 +257,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
255
257
  # Claude Code / Kimi JSONL schema
256
258
  msg = step.get("message") if isinstance(step.get("message"), dict) else None
257
259
  if msg is not None:
258
- schema_matched = True
260
+ explicit_matched = True
259
261
  # Claude Code writes one JSONL line per content block, all sharing
260
262
  # the same message.id and repeating the identical usage object.
261
263
  # Count the turn and its tokens once per message id.
@@ -299,7 +301,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
299
301
  # Codex event schema
300
302
  payload = step.get("payload") if isinstance(step.get("payload"), dict) else {}
301
303
  if step.get("type") == "event_msg" and payload.get("type") == "token_count":
302
- schema_matched = True
304
+ explicit_matched = True
303
305
  last_u = (payload.get("info") or {}).get("last_token_usage") or {}
304
306
  if isinstance(last_u, dict) and last_u:
305
307
  _track_ts(_parse_iso_ts(step.get("timestamp")))
@@ -318,8 +320,8 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
318
320
  s_type = step.get("type")
319
321
  tool_calls = step.get("tool_calls") or []
320
322
  if s_type or tool_calls or "created_at" in step:
321
- schema_matched = True
322
323
  if s_type == "PLANNER_RESPONSE" or tool_calls:
324
+ explicit_matched = explicit_matched or s_type == "PLANNER_RESPONSE"
323
325
  llm_turns += 1
324
326
  # Timestamps only on real turns: status/heartbeat steps would
325
327
  # otherwise fabricate "gaps" during long tool executions.
@@ -361,7 +363,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
361
363
  })
362
364
 
363
365
  schema_warning = None
364
- if not schema_matched:
366
+ if not explicit_matched and llm_turns == 0 and total_input == 0 and total_output == 0:
365
367
  schema_warning = "no recognized transcript schema matched; all metrics are zero"
366
368
  if detected_agent in ("auto", "", "antigravity"):
367
369
  detected_agent = "unknown"
@@ -398,8 +400,10 @@ def compare_transcripts(before_path: str, after_path: str) -> Dict[str, Any]:
398
400
  """
399
401
  Compares two transcripts (A/B testing before vs after TokenSafe optimization).
400
402
  """
401
- a = analyze_transcript(before_path)
402
- b = analyze_transcript(after_path)
403
+ # "auto" lets path-based agent detection decide; the old default label
404
+ # ("antigravity") mislabelled every Claude/Codex/ZCode transcript.
405
+ a = analyze_transcript(before_path, agent_type="auto")
406
+ b = analyze_transcript(after_path, agent_type="auto")
403
407
 
404
408
  if "error" in a:
405
409
  return {"error": f"Before transcript error: {a['error']}"}
@@ -503,4 +507,4 @@ def render_comparison_report(comp: Dict[str, Any]) -> str:
503
507
  lines.append(f"{label:<26} | {b_val:<12} | {a_val:<12} | {pct_str:<14}")
504
508
 
505
509
  lines.append("")
506
- return "\n".join(lines)
510
+ return "\n".join(lines)
@@ -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.6.2"
20
+ CURRENT_VERSION = "4.6.3"
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