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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.6.2",
2
+ "version": "4.6.3",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -174,15 +174,6 @@ def _handle(payload: dict) -> dict:
174
174
  except Exception:
175
175
  pass
176
176
 
177
- if canon_tool == "edit" and not response.get("reason"):
178
- try:
179
- from src.adapter_core import get_oumv_read_edit_advisory
180
- oumv_note = get_oumv_read_edit_advisory(hook_cwd, path or raw_path, conversation_id)
181
- if oumv_note:
182
- response["reason"] = oumv_note
183
- except Exception:
184
- pass
185
-
186
177
  # 3. Output Guard (shared guard_write, v3.0.0): deny wholesale overwrite of
187
178
  # large existing files to enforce edit_file; ask on small-delta writes.
188
179
  if canon_tool == "write":
@@ -105,10 +105,8 @@ def main():
105
105
  try:
106
106
  if workspace_paths:
107
107
  from src.graph_engine import GraphEngine
108
- from src.retrofit import format_oumv_workspace_brief
109
108
  graph = GraphEngine.get_instance(workspace_root)
110
109
  banner = graph.format_topology_banner()
111
- oumv_brief = format_oumv_workspace_brief(workspace_root, include_live=True)
112
110
  extra = []
113
111
  if banner:
114
112
  extra.append(
@@ -116,8 +114,14 @@ def main():
116
114
  "⚡ Core God Nodes and dependency hubs mapped above. "
117
115
  "Call 'tokensafe:repo_map(view=\"graph\", project_path=...)' for full dependency trees."
118
116
  )
119
- if oumv_brief:
120
- extra.append(oumv_brief)
117
+ # Separate try: an OUMV brief failure must not drop the God-Nodes banner.
118
+ try:
119
+ from src.retrofit import format_oumv_workspace_brief
120
+ oumv_brief = format_oumv_workspace_brief(workspace_root, include_live=True)
121
+ if oumv_brief:
122
+ extra.append(oumv_brief)
123
+ except Exception:
124
+ pass
121
125
  if extra:
122
126
  directives = f"{directives}\n\n" + "\n".join(extra)
123
127
  except Exception:
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.6.2",
3
+ "version": "4.6.3",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.6.2",
4
+ "version": "4.6.3",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.6.2",
4
+ "version": "4.6.3",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "logo": "assets/logo.png",
7
7
  "developerName": "TokenSafe",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.6.2",
6
+ "version": "4.6.3",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.6.2",
26
+ "version": "4.6.3",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.6.2",
42
+ "version": "4.6.3",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -457,6 +457,26 @@ def _extract_path(tool_input: Dict[str, Any]) -> str:
457
457
  return ""
458
458
 
459
459
 
460
+ _NUDGE_GC_AGE_SEC = 7 * 86400
461
+
462
+
463
+ def _gc_oumv_markers(data_dir: str) -> None:
464
+ """Drops one-shot OUMV markers older than a week: one accrues per session forever."""
465
+ try:
466
+ now = time.time()
467
+ for name in os.listdir(data_dir):
468
+ if not name.startswith((".oumv_nudge_", ".oumv_used_")):
469
+ continue
470
+ marker_path = os.path.join(data_dir, name)
471
+ try:
472
+ if now - os.path.getmtime(marker_path) > _NUDGE_GC_AGE_SEC:
473
+ os.unlink(marker_path)
474
+ except OSError:
475
+ pass
476
+ except Exception:
477
+ pass
478
+
479
+
460
480
  def get_oumv_read_edit_advisory(workspace_dir: str, file_path: str, session_id: str = "") -> Optional[str]:
461
481
  """One-shot per-session advisory when reading/editing files inside an OUMV-supported stack
462
482
  (React+Vite, Vue, Solid, Go, FastAPI) without having called `tokensafe:oumv` recently.
@@ -475,17 +495,21 @@ def get_oumv_read_edit_advisory(workspace_dir: str, file_path: str, session_id:
475
495
  ws = workspace_dir or get_active_workspace()
476
496
  if not ws or not os.path.isdir(ws):
477
497
  return None
478
- pkg = is_path_in_supported_oumv_scope(ws, file_path)
479
- if not pkg:
480
- return None
498
+ # Cheap marker first: resolving the owning stack walks every manifest in
499
+ # the monorepo, and this runs on every read/write hook.
481
500
  if OUMVGateway.was_recently_used(ws):
482
501
  return None
502
+ pkg = is_path_in_supported_oumv_scope(ws, file_path, use_cache=True)
503
+ if not pkg:
504
+ return None
483
505
 
484
506
  sess_key = hashlib.sha256(f"{session_id or 'default'}:{os.path.realpath(ws)}".encode("utf-8")).hexdigest()[:16]
485
- marker = os.path.join(resolve_data_dir(), f".oumv_nudge_{sess_key}")
507
+ data_dir = resolve_data_dir()
508
+ marker = os.path.join(data_dir, f".oumv_nudge_{sess_key}")
486
509
  if os.path.isfile(marker):
487
510
  return None
488
- os.makedirs(os.path.dirname(marker), exist_ok=True)
511
+ os.makedirs(data_dir, exist_ok=True)
512
+ _gc_oumv_markers(data_dir)
489
513
  with open(marker, "w", encoding="utf-8") as f:
490
514
  f.write(str(time.time()))
491
515
 
@@ -550,15 +574,14 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
550
574
  tp = str(payload.get("transcript_path") or "")
551
575
  canon = canonical_tool_name(tool)
552
576
 
553
- def _cc_decision(decision: str, reason: str, extra_ctx: str = "") -> Dict[str, Any]:
554
- inner: Dict[str, Any] = {
555
- "hookEventName": "PreToolUse",
556
- "permissionDecision": decision,
557
- "permissionDecisionReason": reason,
577
+ def _cc_decision(decision: str, reason: str) -> Dict[str, Any]:
578
+ return {
579
+ "hookSpecificOutput": {
580
+ "hookEventName": "PreToolUse",
581
+ "permissionDecision": decision,
582
+ "permissionDecisionReason": reason,
583
+ }
558
584
  }
559
- if extra_ctx:
560
- inner["additionalContext"] = extra_ctx
561
- return {"hookSpecificOutput": inner}
562
585
 
563
586
  # 1. Loop Detector Guard (all tools)
564
587
  try:
@@ -657,15 +680,9 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
657
680
  )
658
681
  except Exception:
659
682
  pass
660
- oumv_note = get_oumv_read_edit_advisory(cwd, file_path, session_id)
661
- if oumv_note:
662
- return {
663
- "hookSpecificOutput": {
664
- "hookEventName": "PreToolUse",
665
- "permissionDecision": "allow",
666
- "additionalContext": oumv_note,
667
- }
668
- }
683
+ # No OUMV advisory on edit: PreToolUse could only deliver it by returning an
684
+ # explicit permissionDecision, and "allow" auto-approves the edit (bypassing the
685
+ # user's permission prompt). The read branch already delivers the same nudge.
669
686
  return {}
670
687
 
671
688
  if canon == "read":
@@ -452,6 +452,7 @@ def execute_batch_edits(
452
452
  "allow_overwrite": overwrite,
453
453
  "hunk_count": 0,
454
454
  "noop_hunks": 0,
455
+ "clamped_hunks": 0,
455
456
  }
456
457
  continue
457
458
 
@@ -465,6 +466,7 @@ def execute_batch_edits(
465
466
  current_text = prior_prepared["new_content"]
466
467
  prev_hunk_count = prior_prepared["hunk_count"]
467
468
  prev_noop_count = prior_prepared.get("noop_hunks", 0)
469
+ prev_clamped_count = prior_prepared.get("clamped_hunks", 0)
468
470
  is_create = prior_prepared["is_create"]
469
471
  else:
470
472
  if not os.path.exists(abs_path):
@@ -486,11 +488,14 @@ def execute_batch_edits(
486
488
  continue
487
489
  prev_hunk_count = 0
488
490
  prev_noop_count = 0
491
+ prev_clamped_count = 0
489
492
  is_create = False
490
493
 
491
494
  file_failed = False
492
495
  applied_hunk_count = 0
493
496
  noop_hunk_count = prev_noop_count
497
+ clamped_hunk_count = 0
498
+ hunk_clamped = False
494
499
 
495
500
  for hunk_idx, hunk in enumerate(hunks):
496
501
  if not isinstance(hunk, dict):
@@ -524,6 +529,15 @@ def execute_batch_edits(
524
529
  file_failed = True
525
530
  break
526
531
 
532
+ # Clamp end_line beyond EOF: clients routinely read N lines and pass
533
+ # start+limit, and a hard error costs a whole extra turn. The result
534
+ # reports clamped_hunks so a shrunken region is never silent.
535
+ if e_val is not None and e_val > 0:
536
+ line_count = len(current_text.splitlines(keepends=True))
537
+ if e_val > line_count:
538
+ e_val = line_count
539
+ hunk_clamped = True
540
+
527
541
  new_text, err = _apply_hunk_to_text(
528
542
  current_text,
529
543
  target=str(target),
@@ -544,6 +558,9 @@ def execute_batch_edits(
544
558
 
545
559
  current_text = new_text
546
560
  applied_hunk_count += 1
561
+ if hunk_clamped:
562
+ clamped_hunk_count += 1
563
+ hunk_clamped = False
547
564
 
548
565
  if not file_failed:
549
566
  prepared_files[abs_path] = {
@@ -552,6 +569,7 @@ def execute_batch_edits(
552
569
  "is_create": is_create,
553
570
  "hunk_count": prev_hunk_count + applied_hunk_count,
554
571
  "noop_hunks": noop_hunk_count,
572
+ "clamped_hunks": prev_clamped_count + clamped_hunk_count,
555
573
  }
556
574
 
557
575
  # Atomic enforcement: if any file failed and not best_effort, reject all
@@ -589,6 +607,18 @@ def execute_batch_edits(
589
607
  write_aborted = False
590
608
  for abs_p, p_info in prepared_files.items():
591
609
  try:
610
+ if p_info["hunk_count"] == 0 and not p_info["is_create"]:
611
+ # Pure no-op batch entry: report it, but never rewrite identical
612
+ # bytes (that would bump mtime/inode and invalidate readers).
613
+ applied_files_info.append({
614
+ "path": p_info["rel_path"],
615
+ "hunks": 0,
616
+ "noop_hunks": p_info.get("noop_hunks", 0),
617
+ "clamped_hunks": p_info.get("clamped_hunks", 0),
618
+ "is_create": False,
619
+ "unchanged": True,
620
+ })
621
+ continue
592
622
  existed = os.path.exists(abs_p)
593
623
  orig_bytes: Optional[bytes] = None
594
624
  orig_mode: Optional[int] = None
@@ -610,6 +640,7 @@ def execute_batch_edits(
610
640
  "path": p_info["rel_path"],
611
641
  "hunks": p_info["hunk_count"],
612
642
  "noop_hunks": p_info.get("noop_hunks", 0),
643
+ "clamped_hunks": p_info.get("clamped_hunks", 0),
613
644
  "is_create": not existed,
614
645
  })
615
646
  except Exception as e:
@@ -627,14 +658,17 @@ def execute_batch_edits(
627
658
  "path": p_info["rel_path"],
628
659
  "hunks": p_info["hunk_count"],
629
660
  "noop_hunks": p_info.get("noop_hunks", 0),
661
+ "clamped_hunks": p_info.get("clamped_hunks", 0),
630
662
  "is_create": p_info["is_create"],
631
663
  "dry_run": True
632
664
  })
633
665
 
666
+ total_changed_hunks = sum(int(p.get("hunk_count") or 0) for p in prepared_files.values())
634
667
  result: Dict[str, Any] = {
635
668
  "success": len(applied_files_info) > 0 and len(failed_files) == 0,
636
669
  "applied_count": len(applied_files_info),
637
670
  "applied_files": applied_files_info,
671
+ "changed_hunks": total_changed_hunks,
638
672
  "failed_count": len(failed_files),
639
673
  "failed_files": failed_files,
640
674
  "dry_run": dry_run,
@@ -655,8 +689,8 @@ def execute_batch_edits(
655
689
  if isinstance(result.get("verify"), dict):
656
690
  result["verify"]["rolled_back"] = True
657
691
 
658
- # Execute inline verify command if requested and files were modified (shell=False, allowlisted argv)
659
- if verified_argv and applied_files_info and not dry_run:
692
+ # Execute inline verify command if requested and at least one byte actually changed
693
+ if verified_argv and applied_files_info and not dry_run and total_changed_hunks > 0:
660
694
  cmd_str = str(verify).strip()
661
695
  t0 = time.time()
662
696
  try:
@@ -137,7 +137,13 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5, max_results: in
137
137
  raw_out = strip_ansi(proc.stdout or "").strip()
138
138
  lines = [l for l in raw_out.splitlines() if l.strip()]
139
139
  limited = lines[:max_results]
140
- return {"matches": limited, "count": len(limited), "raw": "\n".join(limited)}
140
+ return {
141
+ "matches": limited,
142
+ # count is the true number of matching lines; matches may be truncated.
143
+ "count": len(lines),
144
+ "truncated": len(lines) > len(limited),
145
+ "raw": "\n".join(limited),
146
+ }
141
147
  except subprocess.TimeoutExpired:
142
148
  return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
143
149
  except Exception as e:
@@ -152,7 +158,8 @@ def _run_rg_query(
152
158
  case_sensitive: bool = False,
153
159
  file_type: Optional[str] = None,
154
160
  glob_filter: Optional[str] = None,
155
- max_results: int = 25
161
+ max_results: int = 25,
162
+ scope: str = "all"
156
163
  ) -> Optional[List[Dict[str, Any]]]:
157
164
  """Attempts fast search via ripgrep if available."""
158
165
  rg_bin = shutil.which("rg")
@@ -195,6 +202,7 @@ def _run_rg_query(
195
202
  # rg exits 1 for "no matches" (not an error) and 2 for real failures.
196
203
  if proc.returncode not in (0, 1) and err_text:
197
204
  raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
205
+ scope_all = str(scope or "all").lower() in ("", "all")
198
206
  matches = []
199
207
  _rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
200
208
  for line in proc.stdout.splitlines():
@@ -204,6 +212,15 @@ def _run_rg_query(
204
212
  if m_line:
205
213
  raw_file, raw_lnum, raw_txt = m_line.groups()
206
214
  f_path = os.path.relpath(raw_file, cwd)
215
+ # ripgrep has no notion of TokenSafe scopes: apply the same matcher
216
+ # the Python fallback uses so results do not change with rg presence.
217
+ if not scope_all:
218
+ try:
219
+ from src.scoped_search import ScopedSearch
220
+ if not ScopedSearch.is_match_file(f_path, f_path, str(scope).lower()):
221
+ continue
222
+ except Exception:
223
+ pass
207
224
  try:
208
225
  l_num = int(raw_lnum)
209
226
  except ValueError:
@@ -304,8 +321,16 @@ def _run_python_text_search(
304
321
  ext = os.path.splitext(full_path)[1].lower()
305
322
  if ext in IGNORED_EXTENSIONS:
306
323
  continue
307
- if scope == "code" and ext not in CODE_EXTENSIONS:
308
- continue
324
+ # One matcher for every scope ("code", "config", extensions, globs):
325
+ # reusing ScopedSearch keeps the fallback identical to the rg path.
326
+ if str(scope or "all").lower() not in ("", "all"):
327
+ try:
328
+ from src.scoped_search import ScopedSearch
329
+ if not ScopedSearch.is_match_file(full_path, rel_p, str(scope).lower()):
330
+ continue
331
+ except Exception:
332
+ if scope == "code" and ext not in CODE_EXTENSIONS:
333
+ continue
309
334
  if type_exts is not None and ext not in type_exts:
310
335
  continue
311
336
  if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
@@ -431,7 +456,8 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
431
456
  case_sensitive=case_sensitive,
432
457
  file_type=file_type,
433
458
  glob_filter=glob_filter,
434
- max_results=max_res
459
+ max_results=max_res,
460
+ scope=scope
435
461
  )
436
462
 
437
463
  try:
package/src/cli.py CHANGED
@@ -97,7 +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
+ print(" dev [dir] [--port N] [--host H] [--open] Start Vite+React DevServer with OUMV (zero repo footprint)")
101
101
  print(" integrate [--dry-run] Retrofit OUMV into existing project (React, Vue, FastAPI, Go)")
102
102
  print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
103
103
  print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
@@ -695,8 +695,14 @@ def main(argv: Optional[List[str]] = None):
695
695
  print(f" \033[33m[DRY-RUN]\033[0m Proposed configuration (.tokensafe/oumv.json):")
696
696
  print(json.dumps(cfg, indent=4))
697
697
  elif created:
698
+ mutate_enabled = cfg.get("permissions", {}).get("mutate", True)
699
+ policy = (
700
+ "\033[32menabled out-of-the-box (OCC + syntax guard + backups)\033[0m"
701
+ if mutate_enabled
702
+ else "\033[33mread-only (mutate: false)\033[0m"
703
+ )
698
704
  print(f" ✔ Generated OUMV config: \033[1m{conf_file}\033[0m")
699
- print(f" ✔ Mutation policy: \033[32mread-only (mutate: false)\033[0m")
705
+ print(f" ✔ Mutation policy: {policy}")
700
706
  print(f" ✔ Profiles enabled: {', '.join(cfg.get('oumv', {}).get('profiles', []))}")
701
707
  print("\n Project is now retrofitted for OUMV. AI coding agents can inspect components and endpoints.\n")
702
708
  else:
@@ -741,20 +747,42 @@ def main(argv: Optional[List[str]] = None):
741
747
  port_val: Optional[int] = None
742
748
  host_val: Optional[str] = None
743
749
  open_browser = False
744
- for a in args[1:]:
750
+ unknown_flags: List[str] = []
751
+ i = 1
752
+ while i < len(args):
753
+ a = args[i]
754
+ nxt = args[i + 1] if i + 1 < len(args) else None
745
755
  if a.startswith("--port="):
746
756
  try:
747
757
  port_val = int(a.split("=", 1)[1])
748
758
  except ValueError:
749
759
  pass
760
+ elif a == "--port":
761
+ if nxt is not None:
762
+ try:
763
+ port_val = int(nxt)
764
+ i += 1
765
+ except ValueError:
766
+ unknown_flags.append(a)
767
+ else:
768
+ unknown_flags.append(a)
750
769
  elif a.startswith("--host="):
751
770
  host_val = a.split("=", 1)[1]
752
771
  elif a == "--host":
753
- host_val = "true"
772
+ if nxt is not None and not nxt.startswith("-"):
773
+ host_val = nxt
774
+ i += 1
775
+ else:
776
+ host_val = "true"
754
777
  elif a == "--open":
755
778
  open_browser = True
756
- elif not a.startswith("-"):
779
+ elif a.startswith("-"):
780
+ unknown_flags.append(a)
781
+ else:
757
782
  target_dir = os.path.abspath(a)
783
+ i += 1
784
+ if unknown_flags:
785
+ print(f"⚠ Ignoring unsupported 'tokensafe dev' flag(s): {' '.join(unknown_flags)}")
758
786
  cmd, source = resolve_zero_footprint_vite_command(
759
787
  target_dir, port=port_val, host=host_val, open_browser=open_browser
760
788
  )
@@ -682,12 +682,29 @@ class CommandSanitizer:
682
682
  wrapped = f"tokensafe wrap {shlex.quote(stage)}"
683
683
  return wrapped, saved, reason, None
684
684
 
685
+ @classmethod
686
+ def _tokensafe_ui_available(cls, cwd: str) -> bool:
687
+ """True when a tokensafe-ui CLI is installed locally or globally.
688
+
689
+ Without it the rewrite would make `npm run dev` fetch the companion package
690
+ via npx at dev-server start (or fail offline), so the command must stay as-is.
691
+ """
692
+ try:
693
+ from src.retrofit import resolve_tokensafe_ui_cli
694
+ return resolve_tokensafe_ui_cli(cwd) is not None
695
+ except Exception:
696
+ return False
697
+
685
698
  @classmethod
686
699
  def _optimize_vite_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
687
700
  """
688
701
  Rewrites Vite+React dev server launches (`vite`, `npm run dev`, `bun run dev`, `pnpm dev`, `yarn dev`)
689
702
  to zero-footprint `tokensafe dev` when `tokensafe-ui` is not yet wired in the project's Vite config,
690
703
  so live OUMV RPC starts automatically without mutating repository files.
704
+
705
+ Only launches whose flags `tokensafe dev` can reproduce are rewritten: any other
706
+ flag (`--mode`, `--config`, `--`, …) means the original command is preserved,
707
+ because dropping it would silently start the dev server in a different config.
691
708
  """
692
709
  if not cwd or not os.path.isdir(cwd):
693
710
  return None
@@ -702,12 +719,20 @@ class CommandSanitizer:
702
719
 
703
720
  is_vite_dev = False
704
721
  passthrough: List[str] = []
722
+ unknown: List[str] = []
705
723
 
706
- def _extract_vite_flags(args_list: List[str]) -> List[str]:
724
+ def _extract_vite_flags(args_list: List[str]) -> Tuple[List[str], List[str]]:
725
+ """Splits dev flags tokensafe-ui supports from everything it would drop."""
707
726
  out: List[str] = []
727
+ rest: List[str] = []
708
728
  i = 0
729
+ if args_list[:1] == ["--"]:
730
+ i = 1
709
731
  while i < len(args_list):
710
732
  a = args_list[i]
733
+ if a == "--":
734
+ rest.extend(args_list[i:])
735
+ break
711
736
  if a in ("--open",):
712
737
  out.append(a)
713
738
  elif a == "--host":
@@ -721,8 +746,10 @@ class CommandSanitizer:
721
746
  elif a in ("--port", "-p") and i + 1 < len(args_list):
722
747
  out.append(f"--port={args_list[i + 1]}")
723
748
  i += 1
749
+ else:
750
+ rest.append(a)
724
751
  i += 1
725
- return out
752
+ return out, rest
726
753
 
727
754
  pkg_json_path = os.path.join(cwd, "package.json")
728
755
  if not os.path.isfile(pkg_json_path):
@@ -751,10 +778,12 @@ class CommandSanitizer:
751
778
 
752
779
  if cmd_tok == "vite" and (not cmd_args or cmd_args[0].startswith("-") or cmd_args[0] in ("dev", "serve")):
753
780
  is_vite_dev = True
754
- passthrough = _extract_vite_flags(cmd_args)
781
+ rest_args = cmd_args[1:] if cmd_args[:1] in (["dev"], ["serve"]) else cmd_args
782
+ passthrough, unknown = _extract_vite_flags(rest_args)
755
783
  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
784
  is_vite_dev = True
757
- passthrough = _extract_vite_flags(cmd_args[1:])
785
+ rest_args = cmd_args[2:] if cmd_args[1:2] in (["dev"], ["serve"]) else cmd_args[1:]
786
+ passthrough, unknown = _extract_vite_flags(rest_args)
758
787
  elif cmd_tok in ("npm", "bun", "pnpm", "yarn"):
759
788
  sub = cmd_args[:2]
760
789
  is_dev_script = (sub == ["run", "dev"]) or (cmd_tok in ("pnpm", "yarn") and cmd_args[:1] == ["dev"])
@@ -763,9 +792,12 @@ class CommandSanitizer:
763
792
  dev_script = str(scripts.get("dev") or "")
764
793
  if re.search(r"(?:^|\s)vite(?:\s|$)", dev_script):
765
794
  is_vite_dev = True
766
- passthrough = _extract_vite_flags(cmd_args)
795
+ script_idx = 2 if sub == ["run", "dev"] else 1
796
+ passthrough, unknown = _extract_vite_flags(cmd_args[script_idx:])
767
797
 
768
- if not is_vite_dev or not cls._is_tokensafe_available():
798
+ if not is_vite_dev or unknown:
799
+ return None
800
+ if not cls._tokensafe_ui_available(cwd):
769
801
  return None
770
802
 
771
803
  flags_str = (" " + " ".join(passthrough)) if passthrough else ""
package/src/guard.py CHANGED
@@ -598,11 +598,22 @@ class TokenSafeGuard:
598
598
 
599
599
  return GuardResult(blocked=False)
600
600
 
601
+ @classmethod
602
+ def _oumv_curl_guard_enabled(cls) -> bool:
603
+ """Kill switch in the FileState style: TOKENSAFE_OUMV_CURL_GUARD=0/false/no/off."""
604
+ return os.environ.get("TOKENSAFE_OUMV_CURL_GUARD", "").strip().lower() not in ("0", "false", "no", "off")
605
+
601
606
  @classmethod
602
607
  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."""
608
+ """Blocks raw curl/wget against localhost ports managed by a live OUMV runtime.
609
+
610
+ get_live_ports() only returns ports that are fresh and actually listening, so a
611
+ stale descriptor (crashed dev server, port reused) can never hard-block curl.
612
+ """
604
613
  if not cwd or not os.path.isdir(cwd):
605
614
  return None
615
+ if not cls._oumv_curl_guard_enabled():
616
+ return None
606
617
  try:
607
618
  from src.oumv_gateway import OUMVGateway
608
619
  live_ports = OUMVGateway.get_live_ports(cwd)
package/src/installer.py CHANGED
@@ -2799,6 +2799,12 @@ WantedBy=default.target
2799
2799
  ui_sync = cls._ensure_tokensafe_ui_global(npm_bins=target_npm_bins, install_if_missing=False)
2800
2800
  if ui_sync.get("ok"):
2801
2801
  print(f" {GREEN}✔{RESET} tokensafe-ui {ui_sync['action']} globally ({ui_sync['npm']}).")
2802
+ else:
2803
+ # `tokensafe dev` and the vite-dev rewrite both need this companion CLI.
2804
+ print(
2805
+ f" {YELLOW}⚠{RESET} tokensafe-ui not installed — run "
2806
+ f"`tokensafe install` to enable zero-footprint live Vite+React OUMV."
2807
+ )
2802
2808
  for npm_bin in target_npm_bins:
2803
2809
  npm_env = cls._npm_subprocess_env(npm_bin)
2804
2810
  for pkg in ("create-tokensafe-ui",):