tokensafe 4.6.1 → 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.
- package/.codex-plugin/plugin.json +1 -1
- package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
- package/hooks/pre_tool_use.py +26 -0
- package/hooks/session_start.py +8 -2
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +6 -1
- package/src/adapter_core.py +66 -4
- package/src/cli.py +28 -0
- package/src/command_sanitizer.py +94 -0
- package/src/guard.py +36 -0
- package/src/installer.py +55 -5
- package/src/mcp_server.py +18 -6
- package/src/oumv_gateway.py +171 -31
- package/src/proxy.py +11 -4
- package/src/retrofit.py +380 -99
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -174,6 +174,15 @@ 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
|
+
|
|
177
186
|
# 3. Output Guard (shared guard_write, v3.0.0): deny wholesale overwrite of
|
|
178
187
|
# large existing files to enforce edit_file; ask on small-delta writes.
|
|
179
188
|
if canon_tool == "write":
|
|
@@ -268,6 +277,14 @@ def _handle(payload: dict) -> dict:
|
|
|
268
277
|
|
|
269
278
|
# Step 3A: If model explicitly specified line range, respect it
|
|
270
279
|
if start_line is not None and end_line is not None:
|
|
280
|
+
if not response.get("reason"):
|
|
281
|
+
try:
|
|
282
|
+
from src.adapter_core import get_oumv_read_edit_advisory
|
|
283
|
+
oumv_note = get_oumv_read_edit_advisory(hook_cwd, path or raw_path, conversation_id)
|
|
284
|
+
if oumv_note:
|
|
285
|
+
response["reason"] = oumv_note
|
|
286
|
+
except Exception:
|
|
287
|
+
pass
|
|
271
288
|
return response
|
|
272
289
|
|
|
273
290
|
# Step 3B: If a specific symbol/function is targeted in user prompt, check graph-guided skeleton first
|
|
@@ -341,6 +358,15 @@ def _handle(payload: dict) -> dict:
|
|
|
341
358
|
)
|
|
342
359
|
return response
|
|
343
360
|
|
|
361
|
+
if not response.get("reason"):
|
|
362
|
+
try:
|
|
363
|
+
from src.adapter_core import get_oumv_read_edit_advisory
|
|
364
|
+
oumv_note = get_oumv_read_edit_advisory(hook_cwd, path or raw_path, conversation_id)
|
|
365
|
+
if oumv_note:
|
|
366
|
+
response["reason"] = oumv_note
|
|
367
|
+
except Exception:
|
|
368
|
+
pass
|
|
369
|
+
|
|
344
370
|
# 4. run_command Optimization & TokenSafe Guard
|
|
345
371
|
elif canon_tool == "bash":
|
|
346
372
|
from src.guard import TokenSafeGuard
|
package/hooks/session_start.py
CHANGED
|
@@ -105,15 +105,21 @@ 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
|
|
108
109
|
graph = GraphEngine.get_instance(workspace_root)
|
|
109
110
|
banner = graph.format_topology_banner()
|
|
111
|
+
oumv_brief = format_oumv_workspace_brief(workspace_root, include_live=True)
|
|
112
|
+
extra = []
|
|
110
113
|
if banner:
|
|
111
|
-
|
|
112
|
-
f"{directives}\n\n"
|
|
114
|
+
extra.append(
|
|
113
115
|
f"{banner}\n"
|
|
114
116
|
"⚡ Core God Nodes and dependency hubs mapped above. "
|
|
115
117
|
"Call 'tokensafe:repo_map(view=\"graph\", project_path=...)' for full dependency trees."
|
|
116
118
|
)
|
|
119
|
+
if oumv_brief:
|
|
120
|
+
extra.append(oumv_brief)
|
|
121
|
+
if extra:
|
|
122
|
+
directives = f"{directives}\n\n" + "\n".join(extra)
|
|
117
123
|
except Exception:
|
|
118
124
|
pass
|
|
119
125
|
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.6.
|
|
3
|
+
"version": "4.6.2",
|
|
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.
|
|
4
|
+
"version": "4.6.2",
|
|
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.
|
|
4
|
+
"version": "4.6.2",
|
|
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/rules/AGENTS.md
CHANGED
|
@@ -45,7 +45,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
45
45
|
- `"diff"` (`diff`): slice unified git diffs
|
|
46
46
|
- `"image"` (`image_path`, `max_edge=1024`): downscale screenshots (-50-75% vision tokens)
|
|
47
47
|
- `"compress"` (`prompt`): TOCP S-expression compression
|
|
48
|
-
7. **Universal OUMV Protocol (`oumv`)**:
|
|
48
|
+
7. **Universal OUMV Protocol (`oumv` — Mandatory When Supported)**: When a project uses an OUMV-supported stack (`frontend/react` Vite, `frontend/vue`, `frontend/solid`, `backend/go`, `backend/fastapi`), ALWAYS prefer `tokensafe:oumv(action="status"|"observe"|"understand"|"verify"|"mutate"|"graph", ...)` BEFORE full file crawls, raw `curl`, or headless browsers — even for read/edit tasks (static AST OUMV works offline without running dev/build). For Vite+React, use `tokensafe dev` to start live OUMV with zero repository footprint. In mixed monorepos (e.g. React + Node.js), inspect `oumv(action="status")` / `[TokenSafe OUMV Workspace Matrix]`: use `oumv` on supported profiles and fall back to `repo_map` + `smart_read_file` + `scoped_search` for unsupported stacks (`backend/node`).
|
|
49
49
|
8. **Bounded Reads & Styles**: Never call raw `read_file` without `StartLine`/`EndLine` on files > 100 lines. `smart_read_file` preserves CSS/SCSS/Tailwind design tokens (`:root`, `@theme`) in full.
|
|
50
50
|
|
|
51
51
|
### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
|
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.
|
|
6
|
+
"version": "4.6.2",
|
|
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.
|
|
26
|
+
"version": "4.6.2",
|
|
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.
|
|
42
|
+
"version": "4.6.2",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -110,7 +110,12 @@ TokenSafe actively maximizes provider KV-cache hit rates alongside token compres
|
|
|
110
110
|
|
|
111
111
|
## Universal OUMV Protocol (Runtime Introspection & Verification)
|
|
112
112
|
|
|
113
|
-
TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to inspect, reason about, edit, and verify
|
|
113
|
+
TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to inspect, reason about, edit, and verify Frontend (`tokensafe-ui`, React 18/19 + Vite, Vue 3) and Backend (`Go` Gin/Chi/net-http, `FastAPI`) services without heavy headless browsers or unconstrained shell curls.
|
|
114
|
+
|
|
115
|
+
### OUMV-First Policy, Zero-Footprint & Mixed Monorepos
|
|
116
|
+
- **Mandatory When Supported (Even Without Dev/Build Running)**: If the workspace contains a supported profile (`frontend/react`, `frontend/vue`, `frontend/solid`, `backend/go`, `backend/fastapi`), prefer `tokensafe:oumv` (`status` -> `observe` L0/L1/L2 -> `understand` impact -> `mutate` -> `verify`) BEFORE brute-force reading components or running `curl`/browsers. Static OUMV works offline even when the agent only reads and edits files.
|
|
117
|
+
- **Zero-Footprint Vite+React (`tokensafe dev`)**: Running `tokensafe dev` (or `vite` / `npm run dev` rewritten automatically by `CommandSanitizer`) starts the project's Vite+React DevServer with `tokensafeReact()` injected in memory and runtime state stored under `~/.tokensafe/runtimes/<hash>.json` (sidecar L2 contracts in `~/.tokensafe/contracts/<hash>.json`) — leaving **0 modified/untracked files** in the repository.
|
|
118
|
+
- **Monorepo Capability Boundaries**: In mixed monorepos (e.g., `apps/web` in React + `apps/api` in Node.js/Express), check `oumv(action="status")` or `[TokenSafe OUMV Workspace Matrix]`. Use `tokensafe:oumv(runtime="frontend")` for React, and use `repo_map` + `smart_read_file` + `scoped_search` + normal tests for unsupported backends like `backend/node` (`status: planned`).
|
|
114
119
|
|
|
115
120
|
1. **LIVE RUNTIME HEALTH (`oumv(action="status")`)**:
|
|
116
121
|
- Call `tokensafe:oumv(action="status")` to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend ports 8080/8000).
|
package/src/adapter_core.py
CHANGED
|
@@ -44,7 +44,8 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
44
44
|
"• Before large multi-step tasks: call 'tokensafe:session_context(action=\"budget\", model=...)' to check context headroom and Quality Score (Grade S-F).\n"
|
|
45
45
|
"• When context budget reports warning/critical or Grade C/F: call 'tokensafe:session_context(action=\"compact\", transcript_path=...)' to fold history before continuing.\n"
|
|
46
46
|
"• Prohibited File Edits: NEVER use 'sed -i', 'perl -i', or stream editors to modify source files; ALWAYS use 'edit_file' with exact string targets. NEVER suppress errors with '2>/dev/null'.\n"
|
|
47
|
-
"• Prefer 'edit_file' over 'write_file' for existing files
|
|
47
|
+
"• Prefer 'edit_file' over 'write_file' for existing files.\n"
|
|
48
|
+
"• Universal OUMV Protocol (Mandatory When Supported): If the workspace reports an OUMV-supported stack (React+Vite, Vue, Solid, Go, FastAPI), ALWAYS prefer the 'oumv' MCP tool (status/observe/understand/verify) before full file crawls, raw curl, or browser checks — even when only reading/editing files (static AST OUMV works offline; use 'tokensafe dev' for zero-footprint live Vite+React). Check capability boundaries in mixed monorepos (for unsupported stacks like backend/node Express/Fastify/Nest, use repo_map/smart_read_file/scoped_search)."
|
|
48
49
|
)
|
|
49
50
|
|
|
50
51
|
# High-precision deny patterns: secrets and irreversible destruction only.
|
|
@@ -456,6 +457,53 @@ def _extract_path(tool_input: Dict[str, Any]) -> str:
|
|
|
456
457
|
return ""
|
|
457
458
|
|
|
458
459
|
|
|
460
|
+
def get_oumv_read_edit_advisory(workspace_dir: str, file_path: str, session_id: str = "") -> Optional[str]:
|
|
461
|
+
"""One-shot per-session advisory when reading/editing files inside an OUMV-supported stack
|
|
462
|
+
(React+Vite, Vue, Solid, Go, FastAPI) without having called `tokensafe:oumv` recently.
|
|
463
|
+
|
|
464
|
+
Returns None immediately for unsupported stacks in mixed monorepos (e.g. backend/node),
|
|
465
|
+
when OUMV was already used in this workspace, or if already nudged in this session.
|
|
466
|
+
"""
|
|
467
|
+
if not file_path:
|
|
468
|
+
return None
|
|
469
|
+
try:
|
|
470
|
+
from src.paths import get_active_workspace, resolve_data_dir
|
|
471
|
+
from src.retrofit import is_path_in_supported_oumv_scope
|
|
472
|
+
from src.oumv_gateway import OUMVGateway
|
|
473
|
+
import hashlib
|
|
474
|
+
|
|
475
|
+
ws = workspace_dir or get_active_workspace()
|
|
476
|
+
if not ws or not os.path.isdir(ws):
|
|
477
|
+
return None
|
|
478
|
+
pkg = is_path_in_supported_oumv_scope(ws, file_path)
|
|
479
|
+
if not pkg:
|
|
480
|
+
return None
|
|
481
|
+
if OUMVGateway.was_recently_used(ws):
|
|
482
|
+
return None
|
|
483
|
+
|
|
484
|
+
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}")
|
|
486
|
+
if os.path.isfile(marker):
|
|
487
|
+
return None
|
|
488
|
+
os.makedirs(os.path.dirname(marker), exist_ok=True)
|
|
489
|
+
with open(marker, "w", encoding="utf-8") as f:
|
|
490
|
+
f.write(str(time.time()))
|
|
491
|
+
|
|
492
|
+
live_ports = OUMVGateway.get_live_ports(ws)
|
|
493
|
+
if live_ports:
|
|
494
|
+
return (
|
|
495
|
+
f"[TokenSafe OUMV]: Live {pkg.get('provider')}/{pkg.get('framework')} OUMV runtime is active (port {live_ports[0]}). "
|
|
496
|
+
f"Prefer tokensafe:oumv(action='observe'|'understand'|'verify') for live DOM/state/causality instead of manual file crawling."
|
|
497
|
+
)
|
|
498
|
+
vite_tip = "; run 'tokensafe dev' for zero-footprint live Vite+React RPC" if pkg.get("vite") else ""
|
|
499
|
+
return (
|
|
500
|
+
f"[TokenSafe OUMV]: '{os.path.basename(file_path)}' belongs to an OUMV-supported {pkg.get('provider')}/{pkg.get('framework')} stack. "
|
|
501
|
+
f"Use tokensafe:oumv(action='observe', level='L1') or oumv(action='understand', query='impact') first (works statically offline{vite_tip})."
|
|
502
|
+
)
|
|
503
|
+
except Exception:
|
|
504
|
+
return None
|
|
505
|
+
|
|
506
|
+
|
|
459
507
|
def _large_read_advisory(file_path: str, tool_input: Dict[str, Any]) -> Optional[str]:
|
|
460
508
|
"""Non-blocking advisory when an agent reads an entire large code file unbounded."""
|
|
461
509
|
if not file_path or not os.path.isfile(file_path):
|
|
@@ -609,6 +657,15 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
609
657
|
)
|
|
610
658
|
except Exception:
|
|
611
659
|
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
|
+
}
|
|
612
669
|
return {}
|
|
613
670
|
|
|
614
671
|
if canon == "read":
|
|
@@ -616,13 +673,18 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
616
673
|
verdict = guard_read(file_path, agent, session_id, transcript_path=tp)
|
|
617
674
|
if verdict["decision"] == "deny":
|
|
618
675
|
return _cc_decision("deny", verdict["reason"])
|
|
619
|
-
|
|
620
|
-
|
|
676
|
+
advisories = [
|
|
677
|
+
msg for msg in (
|
|
678
|
+
_large_read_advisory(file_path, tool_input),
|
|
679
|
+
get_oumv_read_edit_advisory(cwd, file_path, session_id),
|
|
680
|
+
) if msg
|
|
681
|
+
]
|
|
682
|
+
if advisories:
|
|
621
683
|
return {
|
|
622
684
|
"hookSpecificOutput": {
|
|
623
685
|
"hookEventName": "PreToolUse",
|
|
624
686
|
"permissionDecision": "allow",
|
|
625
|
-
"additionalContext":
|
|
687
|
+
"additionalContext": "\n".join(advisories),
|
|
626
688
|
}
|
|
627
689
|
}
|
|
628
690
|
return {}
|
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
|
package/src/command_sanitizer.py
CHANGED
|
@@ -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`)**:
|
|
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`
|
|
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
|
|
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 ("
|
|
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 ""):
|