tokensafe 4.6.1 → 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.
@@ -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,127 @@ class CommandSanitizer:
677
682
  wrapped = f"tokensafe wrap {shlex.quote(stage)}"
678
683
  return wrapped, saved, reason, None
679
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
+
698
+ @classmethod
699
+ def _optimize_vite_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
700
+ """
701
+ Rewrites Vite+React dev server launches (`vite`, `npm run dev`, `bun run dev`, `pnpm dev`, `yarn dev`)
702
+ to zero-footprint `tokensafe dev` when `tokensafe-ui` is not yet wired in the project's Vite config,
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.
708
+ """
709
+ if not cwd or not os.path.isdir(cwd):
710
+ return None
711
+ if cls._TOKENSAFE_WRAP_RE.search(stage) or cls._TOKENSAFE_TESTS_RE.search(stage):
712
+ return None
713
+ if cls._has_redirect(stage) or "|" in stage:
714
+ return None
715
+
716
+ cmd_tok, cmd_args = cls._primary_cmd_and_args(stage)
717
+ if not cmd_tok:
718
+ return None
719
+
720
+ is_vite_dev = False
721
+ passthrough: List[str] = []
722
+ unknown: List[str] = []
723
+
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."""
726
+ out: List[str] = []
727
+ rest: List[str] = []
728
+ i = 0
729
+ if args_list[:1] == ["--"]:
730
+ i = 1
731
+ while i < len(args_list):
732
+ a = args_list[i]
733
+ if a == "--":
734
+ rest.extend(args_list[i:])
735
+ break
736
+ if a in ("--open",):
737
+ out.append(a)
738
+ elif a == "--host":
739
+ if i + 1 < len(args_list) and not args_list[i + 1].startswith("-"):
740
+ out.append(f"--host={args_list[i + 1]}")
741
+ i += 1
742
+ else:
743
+ out.append("--host")
744
+ elif a.startswith(("--port=", "--host=")):
745
+ out.append(a)
746
+ elif a in ("--port", "-p") and i + 1 < len(args_list):
747
+ out.append(f"--port={args_list[i + 1]}")
748
+ i += 1
749
+ else:
750
+ rest.append(a)
751
+ i += 1
752
+ return out, rest
753
+
754
+ pkg_json_path = os.path.join(cwd, "package.json")
755
+ if not os.path.isfile(pkg_json_path):
756
+ return None
757
+ try:
758
+ with open(pkg_json_path, "r", encoding="utf-8") as fh:
759
+ pkg = json.load(fh)
760
+ except Exception:
761
+ return None
762
+ if not isinstance(pkg, dict):
763
+ return None
764
+ deps = {**(pkg.get("dependencies") or {}), **(pkg.get("devDependencies") or {})}
765
+ if "react" not in deps or "vite" not in deps:
766
+ return None
767
+
768
+ # Skip if tokensafe-ui is already wired into vite.config.*
769
+ for cfg_name in ("vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs"):
770
+ cfg_path = os.path.join(cwd, cfg_name)
771
+ if os.path.isfile(cfg_path):
772
+ try:
773
+ with open(cfg_path, "r", encoding="utf-8", errors="ignore") as cf:
774
+ if "tokensafe-ui" in cf.read():
775
+ return None
776
+ except Exception:
777
+ pass
778
+
779
+ if cmd_tok == "vite" and (not cmd_args or cmd_args[0].startswith("-") or cmd_args[0] in ("dev", "serve")):
780
+ is_vite_dev = True
781
+ rest_args = cmd_args[1:] if cmd_args[:1] in (["dev"], ["serve"]) else cmd_args
782
+ passthrough, unknown = _extract_vite_flags(rest_args)
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")):
784
+ is_vite_dev = True
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)
787
+ elif cmd_tok in ("npm", "bun", "pnpm", "yarn"):
788
+ sub = cmd_args[:2]
789
+ is_dev_script = (sub == ["run", "dev"]) or (cmd_tok in ("pnpm", "yarn") and cmd_args[:1] == ["dev"])
790
+ if is_dev_script:
791
+ scripts = pkg.get("scripts") if isinstance(pkg.get("scripts"), dict) else {}
792
+ dev_script = str(scripts.get("dev") or "")
793
+ if re.search(r"(?:^|\s)vite(?:\s|$)", dev_script):
794
+ is_vite_dev = True
795
+ script_idx = 2 if sub == ["run", "dev"] else 1
796
+ passthrough, unknown = _extract_vite_flags(cmd_args[script_idx:])
797
+
798
+ if not is_vite_dev or unknown:
799
+ return None
800
+ if not cls._tokensafe_ui_available(cwd):
801
+ return None
802
+
803
+ flags_str = (" " + " ".join(passthrough)) if passthrough else ""
804
+ return f"tokensafe dev{flags_str}", 500, "Routed Vite+React dev server through zero-footprint `tokensafe dev` for live OUMV", None
805
+
680
806
  @classmethod
681
807
  def sanitize(cls, command: str, cwd: Optional[str] = None) -> Tuple[Optional[str], int, str]:
682
808
  """
package/src/guard.py CHANGED
@@ -587,8 +587,55 @@ 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 _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
+
606
+ @classmethod
607
+ def _check_live_oumv_curl(cls, stages: List[str], cwd: str = "") -> Optional[str]:
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
+ """
613
+ if not cwd or not os.path.isdir(cwd):
614
+ return None
615
+ if not cls._oumv_curl_guard_enabled():
616
+ return None
617
+ try:
618
+ from src.oumv_gateway import OUMVGateway
619
+ live_ports = OUMVGateway.get_live_ports(cwd)
620
+ except Exception:
621
+ live_ports = []
622
+ if not live_ports:
623
+ return None
624
+
625
+ for stage in stages:
626
+ cmd_tok, _ = cls._stage_cmd_tokens(stage)
627
+ if cmd_tok not in ("curl", "wget", "http", "https"):
628
+ continue
629
+ for m in re.finditer(r"https?://(?:localhost|127\.0\.0\.1):(\d+)(/[^\s\"']*)?", stage, re.IGNORECASE):
630
+ port = int(m.group(1))
631
+ url_path = m.group(2) or "/"
632
+ if port in live_ports and not url_path.startswith(("/health", "/__oumv/", "/__tokensafe_ui/", "/__agent_dom/")):
633
+ return (
634
+ f"Live OUMV runtime is active on localhost:{port}. "
635
+ f"Use tokensafe:oumv(action='observe'|'understand'|'verify') instead of raw '{cmd_tok}'."
636
+ )
637
+ return None
638
+
592
639
  @classmethod
593
640
  def _has_code_target_in_args(cls, cmd_tok: str, cmd_args: List[str]) -> bool:
594
641
  """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,21 @@ 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']}).")
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
+ )
2752
2808
  for npm_bin in target_npm_bins:
2753
2809
  npm_env = cls._npm_subprocess_env(npm_bin)
2754
- for pkg in ("tokensafe-ui", "create-tokensafe-ui"):
2810
+ for pkg in ("create-tokensafe-ui",):
2755
2811
  try:
2756
2812
  res = subprocess.run([npm_bin, "list", "-g", "--depth=0", pkg], env=npm_env, capture_output=True, text=True, timeout=10)
2757
2813
  if f"{pkg}@" in (res.stdout or ""):
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.6.1"
45
+ "version": "4.6.3"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -1285,6 +1285,13 @@ def handle_tool_call(name: str, args: dict) -> dict:
1285
1285
  )
1286
1286
  except Exception:
1287
1287
  pass
1288
+ try:
1289
+ from src.adapter_core import get_oumv_read_edit_advisory
1290
+ oumv_note = get_oumv_read_edit_advisory(active_ws or os.path.dirname(abs_path), abs_path, _mcp_session_id())
1291
+ if oumv_note and content_parts and isinstance(content_parts[-1], dict):
1292
+ content_parts[-1]["text"] = f"{content_parts[-1].get('text', '')}\n\n{oumv_note}"
1293
+ except Exception:
1294
+ pass
1288
1295
  return result
1289
1296
  except Exception as e:
1290
1297
  return _fallback_error(name, f"{type(e).__name__}: {str(e)}")
@@ -2598,7 +2605,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2598
2605
  lvl = str(args.get("level") or "L0").strip()
2599
2606
  tgt = str(args.get("target") or "").strip() or None
2600
2607
  rt = str(args.get("runtime") or "auto").strip()
2601
- res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt)
2608
+ ws = str(args.get("workspace_dir") or "").strip() or None
2609
+ res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws)
2602
2610
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2603
2611
  except Exception as e:
2604
2612
  return _fallback_error("oumv_observe", f"failed to observe OUMV runtime: {e}")
@@ -2609,7 +2617,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2609
2617
  qry = str(args.get("query") or "causality").strip()
2610
2618
  tgt = str(args.get("target") or "").strip() or None
2611
2619
  rt = str(args.get("runtime") or "auto").strip()
2612
- res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt)
2620
+ ws = str(args.get("workspace_dir") or "").strip() or None
2621
+ res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws)
2613
2622
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2614
2623
  except Exception as e:
2615
2624
  return _fallback_error("oumv_understand", f"failed to query OUMV understanding: {e}")
@@ -2622,7 +2631,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2622
2631
  rep = args.get("replacement")
2623
2632
  ev = str(args.get("expectedVersion") or "").strip() or None
2624
2633
  rt = str(args.get("runtime") or "auto").strip()
2625
- res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt)
2634
+ ws = str(args.get("workspace_dir") or "").strip() or None
2635
+ res = OUMVGateway.mutate(path=p, symbol=sym, replacement=rep, expected_version=ev, runtime=rt, workspace_dir=ws)
2626
2636
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2627
2637
  except Exception as e:
2628
2638
  return _fallback_error("oumv_mutate", f"failed to apply OUMV mutation: {e}")
@@ -2634,7 +2644,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2634
2644
  act = str(args.get("action") or "invoke").strip()
2635
2645
  payload = args.get("payload") if isinstance(args.get("payload"), dict) else None
2636
2646
  rt = str(args.get("runtime") or "auto").strip()
2637
- res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt)
2647
+ ws = str(args.get("workspace_dir") or "").strip() or None
2648
+ res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws)
2638
2649
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2639
2650
  except Exception as e:
2640
2651
  return _fallback_error("oumv_verify", f"failed to verify OUMV action: {e}")
@@ -2644,7 +2655,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2644
2655
  from src.oumv_gateway import OUMVGateway
2645
2656
  qry = str(args.get("query") or "overview").strip()
2646
2657
  tgt = str(args.get("target") or "").strip() or None
2647
- res = OUMVGateway.graph(query=qry, target=tgt)
2658
+ ws = str(args.get("workspace_dir") or "").strip() or None
2659
+ res = OUMVGateway.graph(query=qry, target=tgt, workspace_dir=ws)
2648
2660
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
2649
2661
  except Exception as e:
2650
2662
  return _fallback_error("oumv_graph", f"failed to query cross-stack graph: {e}")
@@ -2890,8 +2902,59 @@ def _redact_result_secrets(result):
2890
2902
  return redacted
2891
2903
 
2892
2904
 
2905
+ _ENVELOPE_HEADROOM_BYTES = 200
2906
+
2907
+
2908
+ def _wire_bytes(text: str) -> int:
2909
+ """Bytes this text costs on the wire after json.dumps(..., ensure_ascii=False).
2910
+
2911
+ The MCP boundary serializes with ensure_ascii=False, so every newline, tab,
2912
+ quote and backslash is escaped to two characters. Measuring raw UTF-8
2913
+ undercounts newline-heavy output (logs) by up to 2x, which used to let a
2914
+ "capped" payload spill to disk anyway.
2915
+ """
2916
+ try:
2917
+ return len(json.dumps(text, ensure_ascii=False).encode("utf-8")) - 2
2918
+ except Exception:
2919
+ return len(str(text).encode("utf-8"))
2920
+
2921
+
2922
+ def _fit_prefix(text: str, limit_bytes: int) -> str:
2923
+ """Longest-ish prefix of `text` whose wire cost fits `limit_bytes` (never raises)."""
2924
+ if limit_bytes <= 0 or not text:
2925
+ return ""
2926
+ cost = _wire_bytes(text)
2927
+ if cost <= limit_bytes:
2928
+ return text
2929
+ n = len(text)
2930
+ guess = max(1, int(n * limit_bytes / max(1, cost)))
2931
+ for _ in range(8):
2932
+ candidate = text[:guess]
2933
+ if _wire_bytes(candidate) <= limit_bytes:
2934
+ return candidate
2935
+ guess = max(1, int(guess * 0.8))
2936
+ return text[:1]
2937
+
2938
+
2939
+ def _fit_suffix(text: str, limit_bytes: int) -> str:
2940
+ """Longest-ish suffix of `text` whose wire cost fits `limit_bytes` (never raises)."""
2941
+ if limit_bytes <= 0 or not text:
2942
+ return ""
2943
+ cost = _wire_bytes(text)
2944
+ if cost <= limit_bytes:
2945
+ return text
2946
+ n = len(text)
2947
+ guess = max(1, int(n * limit_bytes / max(1, cost)))
2948
+ for _ in range(8):
2949
+ candidate = text[-guess:]
2950
+ if _wire_bytes(candidate) <= limit_bytes:
2951
+ return candidate
2952
+ guess = max(1, int(guess * 0.8))
2953
+ return text[-1:]
2954
+
2955
+
2893
2956
  def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2894
- """Folds `text` into at most `limit_bytes` UTF-8 bytes.
2957
+ """Folds `text` into at most `limit_bytes` WIRE bytes (JSON-escaped cost).
2895
2958
 
2896
2959
  Never raises and never returns an over-budget string: if the stash write is
2897
2960
  unavailable the content is truncated with an explicit marker instead of
@@ -2904,8 +2967,7 @@ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2904
2967
  clean_text = strip_ansi(text)
2905
2968
  except Exception:
2906
2969
  clean_text = text
2907
- raw = clean_text.encode("utf-8")
2908
- if len(raw) <= limit_bytes:
2970
+ if _wire_bytes(clean_text) <= limit_bytes:
2909
2971
  return clean_text
2910
2972
 
2911
2973
  marker = ""
@@ -2918,10 +2980,9 @@ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2918
2980
  marker = "[TokenSafe Zero-Spill Guard: content folded; stash copy unavailable]"
2919
2981
 
2920
2982
  footer = "\n" + marker
2921
- footer_bytes = len(footer.encode("utf-8"))
2922
- budget = limit_bytes - footer_bytes
2983
+ budget = limit_bytes - _wire_bytes(footer)
2923
2984
  if budget <= 40:
2924
- return marker.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2985
+ return _fit_prefix(marker, limit_bytes)
2925
2986
 
2926
2987
  lines = clean_text.splitlines()
2927
2988
  if len(lines) > 35:
@@ -2930,41 +2991,39 @@ def _fold_text_for_guard(text: str, limit_bytes: int, tool_name: str) -> str:
2930
2991
  omitted = len(lines) - (len(head) + len(tail))
2931
2992
  msg = f"\n... [{omitted} lines / {len(clean_text)} chars folded by TokenSafe Zero-Spill Guard] ...\n"
2932
2993
  tail_str = "\n".join(tail)
2933
- tail_bytes = len(tail_str.encode("utf-8"))
2934
- msg_bytes = len(msg.encode("utf-8"))
2994
+ msg_bytes = _wire_bytes(msg)
2995
+ tail_bytes = _wire_bytes(tail_str)
2935
2996
  if msg_bytes + tail_bytes < budget:
2936
2997
  head_budget = budget - msg_bytes - tail_bytes
2937
2998
  head_str = ""
2938
2999
  for line in head:
2939
3000
  candidate = head_str + line + "\n"
2940
- if len(candidate.encode("utf-8")) <= head_budget:
3001
+ if _wire_bytes(candidate) <= head_budget:
2941
3002
  head_str = candidate
2942
3003
  else:
2943
3004
  break
2944
3005
  folded = f"{head_str.rstrip()}{msg}{tail_str}{footer}"
2945
- if len(folded.encode("utf-8")) <= limit_bytes:
3006
+ if _wire_bytes(folded) <= limit_bytes:
2946
3007
  return folded
2947
3008
 
2948
3009
  msg = "\n... [content folded by TokenSafe Zero-Spill Guard] ...\n"
2949
- avail = budget - len(msg.encode("utf-8"))
3010
+ avail = budget - _wire_bytes(msg)
2950
3011
  if avail <= 40:
2951
- return marker.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
2952
- head_n = avail // 2
2953
- tail_n = avail - head_n
2954
- head_s = raw[:head_n].decode("utf-8", errors="ignore")
2955
- tail_s = raw[len(raw) - tail_n:].decode("utf-8", errors="ignore") if tail_n else ""
3012
+ return _fit_prefix(marker, limit_bytes)
3013
+ head_s = _fit_prefix(clean_text, max(1, avail // 2))
3014
+ tail_s = _fit_suffix(clean_text[len(head_s):], max(0, avail - _wire_bytes(head_s)))
2956
3015
  folded = f"{head_s}{msg}{tail_s}{footer}"
2957
- if len(folded.encode("utf-8")) > limit_bytes:
2958
- folded = folded.encode("utf-8")[:limit_bytes].decode("utf-8", errors="ignore")
3016
+ if _wire_bytes(folded) > limit_bytes:
3017
+ folded = _fit_prefix(folded, limit_bytes)
2959
3018
  return folded
2960
3019
 
2961
3020
 
2962
3021
  def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int = 8800) -> Any:
2963
3022
  """Zero-Spill Guard: keeps the whole tools/call payload under `max_bytes`.
2964
3023
 
2965
- The budget is per RESPONSE, not per text block: several medium blocks used
2966
- to slip through and spill to disk. Only ~90% of `max_bytes` is spent on
2967
- text, leaving headroom for the JSON escaping the JSON-RPC envelope adds.
3024
+ The budget is per RESPONSE, not per text block, and it is measured in the
3025
+ bytes the JSON-RPC envelope will actually carry (JSON-escaped), leaving a
3026
+ fixed headroom for the envelope itself.
2968
3027
  """
2969
3028
  if not isinstance(result, dict):
2970
3029
  return result
@@ -2976,8 +3035,8 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
2976
3035
  if not text_idx:
2977
3036
  return result
2978
3037
 
2979
- budget = max(256, int(max_bytes * 0.9))
2980
- sizes = {i: len(str(content[i].get("text") or "").encode("utf-8")) for i in text_idx}
3038
+ budget = max(256, max_bytes - _ENVELOPE_HEADROOM_BYTES)
3039
+ sizes = {i: _wire_bytes(str(content[i].get("text") or "")) for i in text_idx}
2981
3040
  total = sum(sizes.values())
2982
3041
  if total <= budget:
2983
3042
  return result
@@ -2993,7 +3052,7 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
2993
3052
  continue
2994
3053
  folded = _fold_text_for_guard(str(content[i].get("text") or ""), target, tool_name)
2995
3054
  new_content[i] = {**content[i], "text": folded}
2996
- total = total - sizes[i] + len(folded.encode("utf-8"))
3055
+ total = total - sizes[i] + _wire_bytes(folded)
2997
3056
 
2998
3057
  if total > budget:
2999
3058
  # Last resort: keep only the first block, folded to the full budget.
@@ -3001,6 +3060,9 @@ def _cap_mcp_output_size(result: Any, tool_name: str = "tool", max_bytes: int =
3001
3060
  kept = _fold_text_for_guard(str(content[first].get("text") or ""), budget, tool_name)
3002
3061
  for i in text_idx[1:]:
3003
3062
  new_content[i] = {**new_content[i], "text": ""}
3063
+ # Final guarantee on the wire budget even if the fold overshot.
3064
+ if _wire_bytes(kept) > budget:
3065
+ kept = _fit_prefix(kept, budget)
3004
3066
  new_content[first] = {**content[first], "text": kept}
3005
3067
 
3006
3068
  new_res = dict(result)