tokensafe 4.6.0 → 4.6.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.
@@ -10,7 +10,12 @@ Supported query types:
10
10
  - 'regex': regular expression pattern matching.
11
11
  - 'glob': file name and path pattern matching.
12
12
  - 'fuzzy': case-insensitive fuzzy path and symbol search.
13
- - 'git': read-only git queries (status, diff, log, show, branch, rev-parse, ls-files).
13
+ - 'git': read-only git queries (status, diff, log, show, branch, rev-parse,
14
+ ls-files, blame, shortlog, describe, tag) with writing/escaping flags blocked.
15
+
16
+ `path` may point to a directory or to a single file. A missing path, an
17
+ uncompilable regex, and an unknown `file_type` are reported as per-query
18
+ errors instead of silent zero-hit results.
14
19
  """
15
20
 
16
21
  import os
@@ -36,11 +41,15 @@ ALLOWED_GIT_COMMANDS = {
36
41
  HARDENED_GIT_BASE_ARGS = [
37
42
  "--no-optional-locks",
38
43
  "-c", "core.fsmonitor=false",
44
+ "-c", "core.quotePath=false",
39
45
  "-c", "diff.external=",
40
46
  "-c", "gpg.program=false",
41
- "--no-pager"
47
+ "--no-pager",
42
48
  ]
43
49
 
50
+ # Subcommands that support --no-textconv (a per-command option, not a global one)
51
+ _TEXTCONV_SUBCOMMANDS = frozenset({"diff", "log", "show", "blame"})
52
+
44
53
 
45
54
  def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
46
55
  """Checks if git command is strictly read-only and returns tokens."""
@@ -57,8 +66,15 @@ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
57
66
  if subcmd not in ALLOWED_GIT_COMMANDS:
58
67
  return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
59
68
 
60
- # Block destructive, config-overriding, or mutating flags
61
- _BLOCKED_GIT_PREFIXES = ("-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output", "--ext-diff", "--exec")
69
+ # Block destructive, config-overriding, escaping, or helper-executing options.
70
+ # --no-index/--contents/--pathspec-from-file read arbitrary files outside the
71
+ # workspace root the MCP handler confines sub-queries to; --textconv runs
72
+ # repo-configured helpers, so it is blocked and --no-textconv is forced below.
73
+ _BLOCKED_GIT_PREFIXES = (
74
+ "-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output",
75
+ "--ext-diff", "--exec", "--no-index", "--contents", "--pathspec-from-file",
76
+ "--textconv",
77
+ )
62
78
  _READ_ONLY_BRANCH_TAG_FLAGS = {
63
79
  "-l", "--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--verbose",
64
80
  "--show-current", "--contains", "--no-contains", "--merged", "--no-merged",
@@ -80,7 +96,7 @@ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
80
96
  return True, "", tokens
81
97
 
82
98
 
83
- def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, Any]:
99
+ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5, max_results: int = 50) -> Dict[str, Any]:
84
100
  """Runs a read-only git query."""
85
101
  is_safe, err_msg, tokens = _is_git_command_safe(pattern)
86
102
  if not is_safe:
@@ -90,15 +106,24 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, An
90
106
  if not git_bin:
91
107
  return {"error": "git executable not found in PATH", "matches": [], "count": 0}
92
108
 
93
- cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
109
+ # --no-textconv is a per-subcommand option (diff/log/show/blame), so it must
110
+ # follow the subcommand, not sit in the global option block.
111
+ if tokens and tokens[0].lower() in _TEXTCONV_SUBCOMMANDS:
112
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, tokens[0], "--no-textconv", *tokens[1:]]
113
+ else:
114
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
115
+
94
116
  env = os.environ.copy()
95
117
  env["GIT_TERMINAL_PROMPT"] = "0"
96
118
  env["GIT_PAGER"] = "cat"
119
+ # Never let git consume the MCP server's own stdin (rev-parse --parseopt blocks on it).
120
+ stdin_devnull = subprocess.DEVNULL
97
121
 
98
122
  try:
99
123
  proc = subprocess.run(
100
124
  cmd,
101
125
  cwd=cwd,
126
+ stdin=stdin_devnull,
102
127
  stdout=subprocess.PIPE,
103
128
  stderr=subprocess.PIPE,
104
129
  text=True,
@@ -111,7 +136,8 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, An
111
136
 
112
137
  raw_out = strip_ansi(proc.stdout or "").strip()
113
138
  lines = [l for l in raw_out.splitlines() if l.strip()]
114
- return {"matches": lines[:50], "count": len(lines), "raw": "\n".join(lines[:50])}
139
+ limited = lines[:max_results]
140
+ return {"matches": limited, "count": len(limited), "raw": "\n".join(limited)}
115
141
  except subprocess.TimeoutExpired:
116
142
  return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
117
143
  except Exception as e:
@@ -159,11 +185,16 @@ def _run_rg_query(
159
185
  proc = subprocess.run(
160
186
  cmd,
161
187
  cwd=cwd,
188
+ stdin=subprocess.DEVNULL,
162
189
  stdout=subprocess.PIPE,
163
190
  stderr=subprocess.PIPE,
164
191
  text=True,
165
192
  timeout=5
166
193
  )
194
+ err_text = (proc.stderr or "").strip()
195
+ # rg exits 1 for "no matches" (not an error) and 2 for real failures.
196
+ if proc.returncode not in (0, 1) and err_text:
197
+ raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
167
198
  matches = []
168
199
  _rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
169
200
  for line in proc.stdout.splitlines():
@@ -198,6 +229,37 @@ def _iter_search_files(search_root: str, cwd: str):
198
229
  yield full_path, os.path.relpath(full_path, cwd)
199
230
 
200
231
 
232
+ # Approximation of ripgrep's --type map for the pure-Python fallback, so the
233
+ # file_type filter is not silently ignored when rg is unavailable.
234
+ FILE_TYPE_EXTENSIONS = {
235
+ "typescript": {".ts", ".tsx", ".mts", ".cts"},
236
+ "ts": {".ts", ".tsx", ".mts", ".cts"},
237
+ "javascript": {".js", ".jsx", ".mjs", ".cjs"},
238
+ "js": {".js", ".jsx", ".mjs", ".cjs"},
239
+ "python": {".py", ".pyi"},
240
+ "py": {".py", ".pyi"},
241
+ "rust": {".rs"},
242
+ "go": {".go"},
243
+ "java": {".java"},
244
+ "ruby": {".rb"},
245
+ "php": {".php"},
246
+ "c": {".c", ".h"},
247
+ "cpp": {".cpp", ".cc", ".cxx", ".hpp", ".hh"},
248
+ "csharp": {".cs"},
249
+ "markdown": {".md", ".markdown"},
250
+ "md": {".md", ".markdown"},
251
+ "json": {".json"},
252
+ "yaml": {".yaml", ".yml"},
253
+ "toml": {".toml"},
254
+ "html": {".html", ".htm"},
255
+ "css": {".css", ".scss", ".sass", ".less"},
256
+ "sql": {".sql"},
257
+ "shell": {".sh", ".bash", ".zsh"},
258
+ "swift": {".swift"},
259
+ "kotlin": {".kt", ".kts"},
260
+ }
261
+
262
+
201
263
  def _run_python_text_search(
202
264
  pattern: str,
203
265
  cwd: str,
@@ -206,20 +268,30 @@ def _run_python_text_search(
206
268
  case_sensitive: bool = False,
207
269
  scope: str = "all",
208
270
  glob_filter: Optional[str] = None,
271
+ file_type: Optional[str] = None,
209
272
  max_results: int = 25
210
273
  ) -> List[Dict[str, Any]]:
211
- """Pure Python search fallback."""
274
+ """Pure Python search fallback. Raises ValueError for an unusable regex or file_type."""
212
275
  search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
213
276
  if not os.path.exists(search_root):
214
277
  return []
215
278
 
279
+ type_exts = None
280
+ if file_type:
281
+ type_exts = FILE_TYPE_EXTENSIONS.get(str(file_type).lower().lstrip("."))
282
+ if type_exts is None:
283
+ raise ValueError(
284
+ f"unsupported file_type '{file_type}' (known: {', '.join(sorted(FILE_TYPE_EXTENSIONS))})"
285
+ )
286
+
216
287
  regex = None
217
288
  if is_regex:
218
289
  flags = 0 if case_sensitive else re.IGNORECASE
219
290
  try:
220
291
  regex = re.compile(pattern, flags)
221
- except re.error:
222
- regex = None
292
+ except re.error as e:
293
+ # Never degrade to a literal search: that silently returns bogus hits.
294
+ raise ValueError(f"invalid regular expression: {e}")
223
295
 
224
296
  matches = []
225
297
  target_lower = pattern if case_sensitive else pattern.lower()
@@ -234,6 +306,8 @@ def _run_python_text_search(
234
306
  continue
235
307
  if scope == "code" and ext not in CODE_EXTENSIONS:
236
308
  continue
309
+ if type_exts is not None and ext not in type_exts:
310
+ continue
237
311
  if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
238
312
  continue
239
313
 
@@ -312,20 +386,39 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
312
386
  output_mode = str(query_dict.get("output_mode") or "content").lower()
313
387
  file_type = query_dict.get("file_type")
314
388
  glob_filter = query_dict.get("glob")
389
+ scope = str(query_dict.get("scope") or "all").lower()
315
390
 
316
391
  if not pattern and q_type != "git":
317
392
  return {"type": q_type, "pattern": pattern, "error": "Empty pattern.", "matches": [], "count": 0}
318
393
 
394
+ # A path that does not exist must be an explicit error: an empty result list
395
+ # is indistinguishable from a genuine zero-hit search.
396
+ if path_filter:
397
+ search_root = os.path.normpath(os.path.join(cwd, str(path_filter)))
398
+ if not os.path.exists(search_root):
399
+ return {
400
+ "type": q_type,
401
+ "pattern": pattern,
402
+ "error": f"path does not exist: {path_filter}",
403
+ "matches": [],
404
+ "count": 0,
405
+ }
406
+
319
407
  if q_type == "git":
320
- res = _run_git_query(pattern, cwd)
408
+ git_cwd = os.path.normpath(os.path.join(cwd, str(path_filter))) if path_filter else cwd
409
+ res = _run_git_query(pattern, git_cwd, max_results=max_res)
321
410
  return {"type": "git", "pattern": pattern, **res}
322
411
 
323
412
  if q_type == "glob":
324
413
  matched_paths = _run_glob_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
414
+ if output_mode == "count":
415
+ return {"type": "glob", "pattern": pattern, "count": len(matched_paths)}
325
416
  return {"type": "glob", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
326
417
 
327
418
  if q_type == "fuzzy":
328
419
  matched_paths = _run_fuzzy_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
420
+ if output_mode == "count":
421
+ return {"type": "fuzzy", "pattern": pattern, "count": len(matched_paths)}
329
422
  return {"type": "fuzzy", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
330
423
 
331
424
  is_regex = (q_type == "regex")
@@ -341,16 +434,20 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
341
434
  max_results=max_res
342
435
  )
343
436
 
344
- matches = rg_matches if rg_matches is not None else _run_python_text_search(
345
- pattern=pattern,
346
- cwd=cwd,
347
- path_filter=path_filter,
348
- is_regex=is_regex,
349
- case_sensitive=case_sensitive,
350
- scope="all",
351
- glob_filter=glob_filter,
352
- max_results=max_res
353
- )
437
+ try:
438
+ matches = rg_matches if rg_matches is not None else _run_python_text_search(
439
+ pattern=pattern,
440
+ cwd=cwd,
441
+ path_filter=path_filter,
442
+ is_regex=is_regex,
443
+ case_sensitive=case_sensitive,
444
+ scope=scope,
445
+ glob_filter=glob_filter,
446
+ file_type=file_type,
447
+ max_results=max_res
448
+ )
449
+ except ValueError as e:
450
+ return {"type": q_type, "pattern": pattern, "error": str(e), "matches": [], "count": 0}
354
451
 
355
452
  if output_mode == "files_with_matches":
356
453
  unique_files = list(dict.fromkeys(m["file"] for m in matches if isinstance(m, dict) and "file" in m))
@@ -418,11 +515,13 @@ def execute_batch_search(
418
515
  if q_type == "git":
419
516
  raw_git = res.get("raw")
420
517
  if raw_git:
421
- md_lines.append("```text\n" + raw_git[:1200] + "\n```")
518
+ md_lines.append("```text\n" + raw_git + "\n```")
422
519
  elif not matches:
423
520
  md_lines.append("*(clean / no output)*")
424
521
  elif isinstance(matches, list):
425
- for m in matches[:15]:
522
+ # Honor the caller's max_results instead of a fixed 15-item cap;
523
+ # the Zero-Spill Guard folds oversized payloads at the MCP boundary.
524
+ for m in matches:
426
525
  if isinstance(m, dict):
427
526
  f_name = m.get("file", "")
428
527
  l_num = m.get("line", "")
@@ -430,12 +529,11 @@ def execute_batch_search(
430
529
  md_lines.append(f"- `{f_name}:{l_num}`: {content}")
431
530
  elif isinstance(m, str):
432
531
  md_lines.append(f"- `{m}`")
433
- if len(matches) > 15:
434
- md_lines.append(f"- *(+{len(matches) - 15} more matches)*")
435
532
 
436
533
  summary_md = "\n".join(md_lines)
534
+ errored = [r for r in results if isinstance(r, dict) and r.get("error")]
437
535
  return {
438
- "success": True,
536
+ "success": not (errored and len(errored) == len(results)),
439
537
  "query_count": len(queries),
440
538
  "results": results,
441
539
  "summary_md": summary_md
package/src/cli.py CHANGED
@@ -97,6 +97,7 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
97
97
  def _print_help():
98
98
  print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
99
99
  print("Commands:")
100
+ print(" dev [dir] [--port=5173] Start Vite+React DevServer with OUMV (zero repo footprint)")
100
101
  print(" integrate [--dry-run] Retrofit OUMV into existing project (React, Vue, FastAPI, Go)")
101
102
  print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
102
103
  print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
@@ -734,6 +735,33 @@ def main(argv: Optional[List[str]] = None):
734
735
  print(f" Backend Runtime: {status['backend'].get('status', 'OK')} ({status['backend'].get('name', 'N/A')})")
735
736
  print(f" Workspace: {status.get('workspace')}\n")
736
737
 
738
+ elif command == "dev":
739
+ from src.retrofit import resolve_zero_footprint_vite_command
740
+ target_dir = os.getcwd()
741
+ port_val: Optional[int] = None
742
+ host_val: Optional[str] = None
743
+ open_browser = False
744
+ for a in args[1:]:
745
+ if a.startswith("--port="):
746
+ try:
747
+ port_val = int(a.split("=", 1)[1])
748
+ except ValueError:
749
+ pass
750
+ elif a.startswith("--host="):
751
+ host_val = a.split("=", 1)[1]
752
+ elif a == "--host":
753
+ host_val = "true"
754
+ elif a == "--open":
755
+ open_browser = True
756
+ elif not a.startswith("-"):
757
+ target_dir = os.path.abspath(a)
758
+ cmd, source = resolve_zero_footprint_vite_command(
759
+ target_dir, port=port_val, host=host_val, open_browser=open_browser
760
+ )
761
+ print(f"⚡ Launching Zero-Footprint Vite+React OUMV server ({source})...")
762
+ proc = subprocess.run(cmd, cwd=target_dir)
763
+ sys.exit(proc.returncode)
764
+
737
765
  elif command in ("burn", "burn-monitor"):
738
766
  from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
739
767
  from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
@@ -382,6 +382,11 @@ class CommandSanitizer:
382
382
  if build_guard:
383
383
  return build_guard
384
384
 
385
+ # vite / React+Vite dev servers: route through zero-footprint `tokensafe dev`
386
+ dev_guard = cls._optimize_vite_dev_stage(stage, cwd)
387
+ if dev_guard:
388
+ return dev_guard
389
+
385
390
  # find: prune unbounded recursion on simple directory crawls (avoid breaking -o / -exec / -delete expressions)
386
391
  if cmd_tok == "find" and "node_modules" not in stage and ".git" not in stage:
387
392
  has_complex = any(a in ("-o", "-or", "-exec", "-execdir", "-delete", "(") for a in cmd_args)
@@ -677,6 +682,95 @@ class CommandSanitizer:
677
682
  wrapped = f"tokensafe wrap {shlex.quote(stage)}"
678
683
  return wrapped, saved, reason, None
679
684
 
685
+ @classmethod
686
+ def _optimize_vite_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
687
+ """
688
+ Rewrites Vite+React dev server launches (`vite`, `npm run dev`, `bun run dev`, `pnpm dev`, `yarn dev`)
689
+ to zero-footprint `tokensafe dev` when `tokensafe-ui` is not yet wired in the project's Vite config,
690
+ so live OUMV RPC starts automatically without mutating repository files.
691
+ """
692
+ if not cwd or not os.path.isdir(cwd):
693
+ return None
694
+ if cls._TOKENSAFE_WRAP_RE.search(stage) or cls._TOKENSAFE_TESTS_RE.search(stage):
695
+ return None
696
+ if cls._has_redirect(stage) or "|" in stage:
697
+ return None
698
+
699
+ cmd_tok, cmd_args = cls._primary_cmd_and_args(stage)
700
+ if not cmd_tok:
701
+ return None
702
+
703
+ is_vite_dev = False
704
+ passthrough: List[str] = []
705
+
706
+ def _extract_vite_flags(args_list: List[str]) -> List[str]:
707
+ out: List[str] = []
708
+ i = 0
709
+ while i < len(args_list):
710
+ a = args_list[i]
711
+ if a in ("--open",):
712
+ out.append(a)
713
+ elif a == "--host":
714
+ if i + 1 < len(args_list) and not args_list[i + 1].startswith("-"):
715
+ out.append(f"--host={args_list[i + 1]}")
716
+ i += 1
717
+ else:
718
+ out.append("--host")
719
+ elif a.startswith(("--port=", "--host=")):
720
+ out.append(a)
721
+ elif a in ("--port", "-p") and i + 1 < len(args_list):
722
+ out.append(f"--port={args_list[i + 1]}")
723
+ i += 1
724
+ i += 1
725
+ return out
726
+
727
+ pkg_json_path = os.path.join(cwd, "package.json")
728
+ if not os.path.isfile(pkg_json_path):
729
+ return None
730
+ try:
731
+ with open(pkg_json_path, "r", encoding="utf-8") as fh:
732
+ pkg = json.load(fh)
733
+ except Exception:
734
+ return None
735
+ if not isinstance(pkg, dict):
736
+ return None
737
+ deps = {**(pkg.get("dependencies") or {}), **(pkg.get("devDependencies") or {})}
738
+ if "react" not in deps or "vite" not in deps:
739
+ return None
740
+
741
+ # Skip if tokensafe-ui is already wired into vite.config.*
742
+ for cfg_name in ("vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs"):
743
+ cfg_path = os.path.join(cwd, cfg_name)
744
+ if os.path.isfile(cfg_path):
745
+ try:
746
+ with open(cfg_path, "r", encoding="utf-8", errors="ignore") as cf:
747
+ if "tokensafe-ui" in cf.read():
748
+ return None
749
+ except Exception:
750
+ pass
751
+
752
+ if cmd_tok == "vite" and (not cmd_args or cmd_args[0].startswith("-") or cmd_args[0] in ("dev", "serve")):
753
+ is_vite_dev = True
754
+ passthrough = _extract_vite_flags(cmd_args)
755
+ elif cmd_tok in ("npx", "bunx") and cmd_args[:1] == ["vite"] and (len(cmd_args) == 1 or cmd_args[1].startswith("-") or cmd_args[1] in ("dev", "serve")):
756
+ is_vite_dev = True
757
+ passthrough = _extract_vite_flags(cmd_args[1:])
758
+ elif cmd_tok in ("npm", "bun", "pnpm", "yarn"):
759
+ sub = cmd_args[:2]
760
+ is_dev_script = (sub == ["run", "dev"]) or (cmd_tok in ("pnpm", "yarn") and cmd_args[:1] == ["dev"])
761
+ if is_dev_script:
762
+ scripts = pkg.get("scripts") if isinstance(pkg.get("scripts"), dict) else {}
763
+ dev_script = str(scripts.get("dev") or "")
764
+ if re.search(r"(?:^|\s)vite(?:\s|$)", dev_script):
765
+ is_vite_dev = True
766
+ passthrough = _extract_vite_flags(cmd_args)
767
+
768
+ if not is_vite_dev or not cls._is_tokensafe_available():
769
+ return None
770
+
771
+ flags_str = (" " + " ".join(passthrough)) if passthrough else ""
772
+ return f"tokensafe dev{flags_str}", 500, "Routed Vite+React dev server through zero-footprint `tokensafe dev` for live OUMV", None
773
+
680
774
  @classmethod
681
775
  def sanitize(cls, command: str, cwd: Optional[str] = None) -> Tuple[Optional[str], int, str]:
682
776
  """
package/src/guard.py CHANGED
@@ -587,8 +587,44 @@ class TokenSafeGuard:
587
587
  reason=code_search_err
588
588
  )
589
589
 
590
+ # 6. Live OUMV Localhost Curl Guard (use tokensafe:oumv instead of raw curl against active OUMV ports)
591
+ oumv_curl_err = cls._check_live_oumv_curl(stages, cwd)
592
+ if oumv_curl_err:
593
+ return GuardResult(
594
+ blocked=True,
595
+ check_name="OUMV_BYPASS",
596
+ reason=oumv_curl_err,
597
+ )
598
+
590
599
  return GuardResult(blocked=False)
591
600
 
601
+ @classmethod
602
+ def _check_live_oumv_curl(cls, stages: List[str], cwd: str = "") -> Optional[str]:
603
+ """Blocks raw curl/wget against localhost ports managed by a live OUMV runtime."""
604
+ if not cwd or not os.path.isdir(cwd):
605
+ return None
606
+ try:
607
+ from src.oumv_gateway import OUMVGateway
608
+ live_ports = OUMVGateway.get_live_ports(cwd)
609
+ except Exception:
610
+ live_ports = []
611
+ if not live_ports:
612
+ return None
613
+
614
+ for stage in stages:
615
+ cmd_tok, _ = cls._stage_cmd_tokens(stage)
616
+ if cmd_tok not in ("curl", "wget", "http", "https"):
617
+ continue
618
+ for m in re.finditer(r"https?://(?:localhost|127\.0\.0\.1):(\d+)(/[^\s\"']*)?", stage, re.IGNORECASE):
619
+ port = int(m.group(1))
620
+ url_path = m.group(2) or "/"
621
+ if port in live_ports and not url_path.startswith(("/health", "/__oumv/", "/__tokensafe_ui/", "/__agent_dom/")):
622
+ return (
623
+ f"Live OUMV runtime is active on localhost:{port}. "
624
+ f"Use tokensafe:oumv(action='observe'|'understand'|'verify') instead of raw '{cmd_tok}'."
625
+ )
626
+ return None
627
+
592
628
  @classmethod
593
629
  def _has_code_target_in_args(cls, cmd_tok: str, cmd_args: List[str]) -> bool:
594
630
  """Separates grep/rg/find pattern vs path args so grep 'app' server.log is not flagged."""
package/src/installer.py CHANGED
@@ -60,7 +60,10 @@ UNIFIED_TOKENSAFE_RULE = (
60
60
  "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
61
61
  "11. **Proof-of-Savings Turn Footer (strictly English)**: Append on tool-using turns:\n"
62
62
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
63
- "12. **Universal OUMV Protocol (`oumv`)**: Inspect live Frontend/Backend runtimes via `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` instead of headless browsers or blind shell curls.\n"
63
+ "12. **Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Go, FastAPI), "
64
+ "ALWAYS prefer `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` BEFORE full file crawls, raw curls, or browser checks — "
65
+ "static OUMV works offline on read/edit tasks too, and `tokensafe dev` starts zero-footprint live Vite+React RPC without touching repo files. "
66
+ "In mixed monorepos (e.g. React + Node.js), use `oumv` on supported profiles and `repo_map`/`smart_read_file`/`scoped_search` on unsupported stacks (e.g. `backend/node`).\n"
64
67
  )
65
68
 
66
69
  # Short pointer written into PROJECT-level rule files when the full protocol is
@@ -72,7 +75,7 @@ POINTER_RULE = (
72
75
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
73
76
  "Core tools: `tokensafe:repo_map(view='graph'|'api'|'tree')` for architecture & directory trees, "
74
77
  "`tokensafe:scoped_search` (single or `queries` batch, never raw grep/find), `tokensafe:smart_read_file` (symbol, `targets` bundle, or `.d.ts` `package_name`), "
75
- "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` for live runtime introspection/verification, "
78
+ "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Go/FastAPI stacks — live or static offline; check `status` in mixed monorepos), "
76
79
  "`tokensafe:session_context(action='budget'|'compact'|'prune'|'mistakes')` for context & anti-stuck hygiene, and "
77
80
  "`tokensafe:run_helper(action='sanitize'|'guard'|'diff'|'deps'|'web'|'expand'|'image'|'compress')`; "
78
81
  "never hardcode secret fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
@@ -2164,7 +2167,8 @@ WantedBy=default.target
2164
2167
  if h_ok:
2165
2168
  msg = f"{msg}; {h_msg}"
2166
2169
  results[key] = {"name": info["name"], "success": ok, "message": msg}
2167
- # Also configure project rules
2170
+ # Also configure project rules and ensure zero-footprint tokensafe-ui companion CLI
2171
+ cls._ensure_tokensafe_ui_global(install_if_missing=True)
2168
2172
  proj_res = cls.install_project(os.getcwd())
2169
2173
  return {
2170
2174
  "agents": results,
@@ -2221,6 +2225,9 @@ WantedBy=default.target
2221
2225
  print(f" \033[31m✖\033[0m \033[1m{name}\033[0m: {msg}")
2222
2226
 
2223
2227
  print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
2228
+ ui_sync = cls._ensure_tokensafe_ui_global(install_if_missing=True)
2229
+ if ui_sync.get("ok"):
2230
+ print(f" \033[32m✔\033[0m Zero-footprint Vite+React companion tokensafe-ui {ui_sync['action']} globally.")
2224
2231
  print(" Restart your IDE / Agent to start saving tokens automatically.\n")
2225
2232
  cls.maybe_prompt_account_login(context="install")
2226
2233
  cls._ensure_proxy_default("install")
@@ -2545,6 +2552,46 @@ WantedBy=default.target
2545
2552
 
2546
2553
  return restarted
2547
2554
 
2555
+ @classmethod
2556
+ def _ensure_tokensafe_ui_global(
2557
+ cls,
2558
+ npm_bins: Optional[List[str]] = None,
2559
+ install_if_missing: bool = True,
2560
+ ) -> Dict[str, Any]:
2561
+ """Installs or upgrades global `tokensafe-ui` for zero-footprint Vite+React `tokensafe dev`."""
2562
+ candidates = npm_bins or ([cls._find_npm()] if cls._find_npm() else [])
2563
+ for npm_bin in candidates:
2564
+ if not npm_bin:
2565
+ continue
2566
+ npm_env = cls._npm_subprocess_env(npm_bin)
2567
+ try:
2568
+ res = subprocess.run(
2569
+ [npm_bin, "list", "-g", "--depth=0", "tokensafe-ui"],
2570
+ env=npm_env,
2571
+ capture_output=True,
2572
+ text=True,
2573
+ timeout=10,
2574
+ )
2575
+ already_installed = "tokensafe-ui@" in (res.stdout or "")
2576
+ if not already_installed and not install_if_missing:
2577
+ continue
2578
+ up_res = subprocess.run(
2579
+ [npm_bin, "install", "-g", "tokensafe-ui@latest"],
2580
+ env=npm_env,
2581
+ capture_output=True,
2582
+ text=True,
2583
+ timeout=90,
2584
+ )
2585
+ if up_res.returncode == 0:
2586
+ return {
2587
+ "ok": True,
2588
+ "action": "upgraded" if already_installed else "installed",
2589
+ "npm": npm_bin,
2590
+ }
2591
+ except Exception:
2592
+ continue
2593
+ return {"ok": False, "action": "skipped"}
2594
+
2548
2595
  @staticmethod
2549
2596
  def _semver_dir_key(name: str) -> Tuple[int, ...]:
2550
2597
  """Parses a version directory name like 'v24.14.0' into a numeric sort key."""
@@ -2746,12 +2793,15 @@ WantedBy=default.target
2746
2793
  print(f" {YELLOW}⚠{RESET} pip update skipped: {e}")
2747
2794
  pip_cmd = pip_bin
2748
2795
 
2749
- # 3b. Check and upgrade TokenSafe ecosystem packages (Frontend & Backend)
2796
+ # 3b. Check and upgrade TokenSafe Ecosystem packages (Frontend & Backend)
2750
2797
  print(f"\n {CYAN}→{RESET} Checking TokenSafe Ecosystem packages (UI & Backend)...")
2751
2798
  target_npm_bins = upgraded_npm_bins or ([primary_npm] if primary_npm else [])
2799
+ ui_sync = cls._ensure_tokensafe_ui_global(npm_bins=target_npm_bins, install_if_missing=False)
2800
+ if ui_sync.get("ok"):
2801
+ print(f" {GREEN}✔{RESET} tokensafe-ui {ui_sync['action']} globally ({ui_sync['npm']}).")
2752
2802
  for npm_bin in target_npm_bins:
2753
2803
  npm_env = cls._npm_subprocess_env(npm_bin)
2754
- for pkg in ("tokensafe-ui", "create-tokensafe-ui"):
2804
+ for pkg in ("create-tokensafe-ui",):
2755
2805
  try:
2756
2806
  res = subprocess.run([npm_bin, "list", "-g", "--depth=0", pkg], env=npm_env, capture_output=True, text=True, timeout=10)
2757
2807
  if f"{pkg}@" in (res.stdout or ""):