tokensafe 4.6.3 → 4.7.0
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 +2 -2
- package/LICENSE +202 -21
- package/README.md +44 -7
- package/hooks/claude_code_hook.py +24 -2
- package/hooks/kimi_hook.py +20 -0
- package/hooks/pre_invocation.py +7 -12
- package/hooks/session_start.py +8 -0
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -1
- package/server.json +3 -3
- package/src/acp/__init__.py +15 -0
- package/src/acp/server.py +328 -0
- package/src/adapter_core.py +22 -3
- package/src/agent/__init__.py +11 -0
- package/src/agent/context.py +99 -0
- package/src/agent/loop.py +385 -0
- package/src/agent/pricing.py +77 -0
- package/src/agent/providers.py +486 -0
- package/src/agent/tools.py +98 -0
- package/src/auto_inject.py +517 -0
- package/src/bench/__init__.py +1 -0
- package/src/bench/driver.py +219 -0
- package/src/bench/go_target.py +360 -0
- package/src/bench/react_target.py +234 -0
- package/src/bench/runner.py +247 -0
- package/src/cli.py +244 -5
- package/src/command_sanitizer.py +54 -0
- package/src/guard.py +63 -10
- package/src/history_compactor.py +200 -2
- package/src/mcp_server.py +65 -13
- package/src/paths.py +99 -2
- package/src/retrofit.py +91 -4
- package/src/savings.py +81 -0
- package/src/scaffold.py +190 -8
- package/src/session_brief.py +154 -0
- package/src/session_context.py +124 -0
- package/src/telemetry_sync.py +93 -25
- package/src/version_checker.py +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/src/cli.py
CHANGED
|
@@ -9,6 +9,7 @@ Used by:
|
|
|
9
9
|
|
|
10
10
|
import sys
|
|
11
11
|
import os
|
|
12
|
+
import shutil
|
|
12
13
|
import subprocess
|
|
13
14
|
from typing import Optional, List, Dict, Any
|
|
14
15
|
|
|
@@ -99,11 +100,14 @@ def _print_help():
|
|
|
99
100
|
print("Commands:")
|
|
100
101
|
print(" dev [dir] [--port N] [--host H] [--open] Start Vite+React DevServer with OUMV (zero repo footprint)")
|
|
101
102
|
print(" integrate [--dry-run] Retrofit OUMV into existing project (React, Vue, FastAPI, Go)")
|
|
103
|
+
print(" inject [status|apply|revert] Auto-wire adapters with zero repo footprint (add --dry-run)")
|
|
102
104
|
print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
|
|
103
105
|
print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
|
|
104
106
|
print(" create <name> [--template ...] Greenfield project scaffolder (tokensafe-ui + tokensafe-backend)")
|
|
105
107
|
print(" init [--template ...] Initialize TokenSafe stack in current directory")
|
|
106
108
|
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
109
|
+
print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
|
|
110
|
+
print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
|
|
107
111
|
print(" status One-screen health check: hooks, weekly savings, tier, sync")
|
|
108
112
|
print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
|
|
109
113
|
print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
|
|
@@ -133,6 +137,8 @@ def _print_help():
|
|
|
133
137
|
print(" logout / unlink Unlink this device and remove local license")
|
|
134
138
|
print(" sync Sync telemetry with the cloud backend")
|
|
135
139
|
print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
|
|
140
|
+
print(" agent [--model M] [-C dir] <prompt> One agent turn in this workspace (streaming tool use)")
|
|
141
|
+
print(" acp ACP agent server over stdio (Zed, JetBrains, Neovim, Emacs)")
|
|
136
142
|
print(" --version Print version and exit")
|
|
137
143
|
|
|
138
144
|
|
|
@@ -335,6 +341,27 @@ def main(argv: Optional[List[str]] = None):
|
|
|
335
341
|
print(ledger)
|
|
336
342
|
print()
|
|
337
343
|
|
|
344
|
+
elif command in ("savings", "saved"):
|
|
345
|
+
# Canonical, machine-readable savings numbers. Agents must cite this
|
|
346
|
+
# command instead of guessing (see the footer rule in AGENTS.md).
|
|
347
|
+
from src.savings import build_savings_report
|
|
348
|
+
|
|
349
|
+
report = build_savings_report()
|
|
350
|
+
if "--json" in args:
|
|
351
|
+
import json as _json
|
|
352
|
+
print(_json.dumps(report, indent=2, ensure_ascii=False))
|
|
353
|
+
else:
|
|
354
|
+
last = report.get("last_event") or {}
|
|
355
|
+
print("\n\033[1m\033[36m⚡ TOKENSAFE SAVINGS (canonical) ⚡\033[0m\n")
|
|
356
|
+
print(f" Data dir: {report['data_dir']}")
|
|
357
|
+
print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
|
|
358
|
+
print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
|
|
359
|
+
print(f" Saved (pruned+sync): {report['pruned_synced_saved_tokens']:,} tokens")
|
|
360
|
+
print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens (≈${report['usd_saved_approx']:.2f})")
|
|
361
|
+
if last:
|
|
362
|
+
print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
|
|
363
|
+
print()
|
|
364
|
+
|
|
338
365
|
elif command in ("stats", "dashboard"):
|
|
339
366
|
tracker = MetricsTracker()
|
|
340
367
|
dashboard = Dashboard(tracker)
|
|
@@ -573,6 +600,16 @@ def main(argv: Optional[List[str]] = None):
|
|
|
573
600
|
template = "fullstack"
|
|
574
601
|
force = False
|
|
575
602
|
|
|
603
|
+
if "--list" in args:
|
|
604
|
+
print("\nAvailable recipes:")
|
|
605
|
+
print(" react-fastapi React 18 + Vite + FastAPI (recommended)")
|
|
606
|
+
print(" react-go React 18 + Vite + Go/Gin")
|
|
607
|
+
print(" vue-gin Vue 3 + Vite + Go/Gin")
|
|
608
|
+
print(" react / vue frontend only (OUMV via `tokensafe dev`)")
|
|
609
|
+
print(" fastapi / gin backend only (auto-mount)")
|
|
610
|
+
print(" backend, ui, fullstack legacy TokenSafe-native templates\n")
|
|
611
|
+
return
|
|
612
|
+
|
|
576
613
|
i = 1
|
|
577
614
|
while i < len(args):
|
|
578
615
|
arg = args[i]
|
|
@@ -581,13 +618,17 @@ def main(argv: Optional[List[str]] = None):
|
|
|
581
618
|
print("Usage:")
|
|
582
619
|
print(" tokensafe create <project-name> [options]\n")
|
|
583
620
|
print("Options:")
|
|
584
|
-
print(" --template <type>
|
|
621
|
+
print(" --template <type> recipe or stack:")
|
|
622
|
+
print(" react-fastapi (recommended), react-go, vue-gin,")
|
|
623
|
+
print(" react, vue, fastapi, gin, backend, ui, fullstack")
|
|
585
624
|
print(" --force, -f Overwrite existing files")
|
|
586
625
|
print(" --help, -h Show this help screen\n")
|
|
587
626
|
print("Examples:")
|
|
588
627
|
print(" tokensafe create my-app")
|
|
589
628
|
print(" tokensafe create my-dashboard --template ui")
|
|
590
|
-
print(" tokensafe create store-api --template
|
|
629
|
+
print(" tokensafe create store-api --template fastapi")
|
|
630
|
+
print(" tokensafe create shop --template react-fastapi")
|
|
631
|
+
print(" tokensafe create edge-api --template gin\n")
|
|
591
632
|
return
|
|
592
633
|
elif arg in ("--template", "-t") and i + 1 < len(args):
|
|
593
634
|
template = args[i + 1]
|
|
@@ -644,7 +685,9 @@ def main(argv: Optional[List[str]] = None):
|
|
|
644
685
|
print("Usage:")
|
|
645
686
|
print(" tokensafe init [options]\n")
|
|
646
687
|
print("Options:")
|
|
647
|
-
print(" --template <type>
|
|
688
|
+
print(" --template <type> recipe or stack:")
|
|
689
|
+
print(" react-fastapi (recommended), react-go, vue-gin,")
|
|
690
|
+
print(" react, vue, fastapi, gin, backend, ui, fullstack")
|
|
648
691
|
print(" --force, -f Overwrite existing files\n")
|
|
649
692
|
return
|
|
650
693
|
elif arg in ("--template", "-t") and i + 1 < len(args):
|
|
@@ -708,6 +751,72 @@ def main(argv: Optional[List[str]] = None):
|
|
|
708
751
|
else:
|
|
709
752
|
print(f" ✔ Existing configuration preserved: \033[1m{conf_file}\033[0m (use --force to overwrite)\n")
|
|
710
753
|
|
|
754
|
+
elif command in ("run-backend", "run_backend"):
|
|
755
|
+
# Executes the user's dev-server command with the OUMV autoload hook active.
|
|
756
|
+
# Nothing is written into the repository: the hook lives in ~/.tokensafe.
|
|
757
|
+
from src.auto_inject import backend_env, ensure_python_autoload
|
|
758
|
+
|
|
759
|
+
argv_rest = [a for a in args[1:]]
|
|
760
|
+
if not argv_rest:
|
|
761
|
+
print("usage: tokensafe run-backend <command...> e.g. tokensafe run-backend uvicorn app:app --reload")
|
|
762
|
+
return
|
|
763
|
+
ensure_python_autoload()
|
|
764
|
+
env = backend_env()
|
|
765
|
+
tool = argv_rest[0]
|
|
766
|
+
resolved = shutil.which(tool)
|
|
767
|
+
if not resolved:
|
|
768
|
+
print(f"tokensafe run-backend: `{tool}` not found on PATH")
|
|
769
|
+
return
|
|
770
|
+
os.execvpe(resolved, argv_rest, env)
|
|
771
|
+
|
|
772
|
+
elif command in ("inject", "wire"):
|
|
773
|
+
from src import auto_inject
|
|
774
|
+
|
|
775
|
+
if "--status" in args:
|
|
776
|
+
sub = "status"
|
|
777
|
+
elif "--revert" in args:
|
|
778
|
+
sub = "revert"
|
|
779
|
+
else:
|
|
780
|
+
positional = [a for a in args[1:] if not a.startswith("-")]
|
|
781
|
+
sub = positional[0] if positional and positional[0] in ("status", "apply", "revert") else "apply"
|
|
782
|
+
dry_run = "--dry-run" in args
|
|
783
|
+
workspace = os.getcwd()
|
|
784
|
+
|
|
785
|
+
if sub == "status":
|
|
786
|
+
data = auto_inject.plan(workspace)
|
|
787
|
+
print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV INJECT PLAN ⚡\033[0m\n")
|
|
788
|
+
print(f" Profiles: {', '.join(data['profiles']) or 'none detected'}")
|
|
789
|
+
for action in data["actions"]:
|
|
790
|
+
writes = "writes repo" if action["writes_repo"] else "zero repo footprint"
|
|
791
|
+
print(f" - {action['kind']:<24} {action['profile']:<9} {writes}")
|
|
792
|
+
if action.get("entrypoint"):
|
|
793
|
+
print(f" entrypoint: {action['entrypoint']} (patched: {action.get('already_patched')})")
|
|
794
|
+
if action.get("install"):
|
|
795
|
+
print(f" install: {action['install']}")
|
|
796
|
+
if action.get("run"):
|
|
797
|
+
print(f" run: {action['run']}")
|
|
798
|
+
print(f" Python autoload: {'✔ installed' if data['python_autoload_present'] else '○ not installed'}")
|
|
799
|
+
print(f" Revertable: {'✔ yes' if data['revertable'] else '○ no'}\n")
|
|
800
|
+
elif sub == "revert":
|
|
801
|
+
result = auto_inject.revert(workspace)
|
|
802
|
+
state = result.get("go", {}).get("status", "nothing-to-revert")
|
|
803
|
+
print(f" Go patch: {state}")
|
|
804
|
+
if result.get("go", {}).get("entrypoint"):
|
|
805
|
+
print(f" Restored: {result['go']['entrypoint']}")
|
|
806
|
+
else:
|
|
807
|
+
result = auto_inject.apply(workspace, dry_run=dry_run, include_go=True)
|
|
808
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
809
|
+
cfg = result.get("config", {})
|
|
810
|
+
print(f"\n{prefix}OUMV config: {cfg.get('path')} ({'created' if cfg.get('created') else 'preserved'}), mutate={cfg.get('mutate')}")
|
|
811
|
+
for action in result.get("actions", []):
|
|
812
|
+
status = action.get("status", "?")
|
|
813
|
+
print(f" {prefix}{action['kind']}: {status}")
|
|
814
|
+
if action.get("run"):
|
|
815
|
+
print(f" run: {action['run']}")
|
|
816
|
+
if action.get("reason"):
|
|
817
|
+
print(f" reason: {action['reason']}")
|
|
818
|
+
print()
|
|
819
|
+
|
|
711
820
|
elif command in ("adapters", "adapter"):
|
|
712
821
|
from src.retrofit import get_adapters_catalog
|
|
713
822
|
catalog = get_adapters_catalog()
|
|
@@ -731,8 +840,16 @@ def main(argv: Optional[List[str]] = None):
|
|
|
731
840
|
be = doc['detected_stack'].get('backend')
|
|
732
841
|
print(f" Detected Frontend: {fe['framework'] if fe else 'None'}")
|
|
733
842
|
print(f" Detected Backend: {be['framework'] if be else 'None'}")
|
|
734
|
-
mut = doc['permissions'].get('mutate',
|
|
735
|
-
print(f" Mutation Permission: {'✔ Enabled' if mut else '○ Read-
|
|
843
|
+
mut = doc['permissions'].get('mutate', True)
|
|
844
|
+
print(f" Mutation Permission: {'✔ Enabled (out-of-the-box, guarded)' if mut else '○ Read-only (mutate: false)'}")
|
|
845
|
+
for profile, item in (doc.get('adapter_readiness') or {}).items():
|
|
846
|
+
state = "✔ ready" if item["ready"] else "○ not ready"
|
|
847
|
+
live = " (live)" if item["live"] else ""
|
|
848
|
+
print(f" Adapter {profile:<10} {state}{live}: {item['provider']}/{item['framework']} — {item['evidence']}")
|
|
849
|
+
print(f" Ready for agent: {'✔ yes' if doc.get('ready_for_agent') else '○ no'}")
|
|
850
|
+
for reason in doc.get('blocking') or []:
|
|
851
|
+
print(f" - {reason}")
|
|
852
|
+
print()
|
|
736
853
|
else:
|
|
737
854
|
from src.oumv_gateway import OUMVGateway
|
|
738
855
|
status = OUMVGateway.status()
|
|
@@ -790,6 +907,43 @@ def main(argv: Optional[List[str]] = None):
|
|
|
790
907
|
proc = subprocess.run(cmd, cwd=target_dir)
|
|
791
908
|
sys.exit(proc.returncode)
|
|
792
909
|
|
|
910
|
+
elif command in ("bench-oumv", "bench_oumv"):
|
|
911
|
+
# Measured, agent-driven benchmark (DeepSeek by default): real oracle,
|
|
912
|
+
# provider-side token accounting, hard budget cap.
|
|
913
|
+
from src.bench import go_target, react_target
|
|
914
|
+
from src.bench.runner import render_markdown, run_matrix, run_react_matrix, write_artifacts
|
|
915
|
+
|
|
916
|
+
def _flag(name: str, default: str) -> str:
|
|
917
|
+
for i, arg in enumerate(args):
|
|
918
|
+
if arg == name and i + 1 < len(args):
|
|
919
|
+
return args[i + 1]
|
|
920
|
+
if arg.startswith(name + "="):
|
|
921
|
+
return arg.split("=", 1)[1]
|
|
922
|
+
return default
|
|
923
|
+
|
|
924
|
+
target = _flag("--target", "go")
|
|
925
|
+
catalogue = react_target.TASKS if target == "react" else go_target.TASKS
|
|
926
|
+
tasks_arg = _flag("--tasks", "all")
|
|
927
|
+
task_ids = list(catalogue) if tasks_arg == "all" else [t.strip() for t in tasks_arg.split(",") if t.strip()]
|
|
928
|
+
arms = [a.strip() for a in _flag("--arms", "baseline,oumv").split(",") if a.strip()]
|
|
929
|
+
runs = int(_flag("--runs", "1"))
|
|
930
|
+
budget = float(_flag("--budget", "1.0"))
|
|
931
|
+
model = _flag("--model", "deepseek-chat")
|
|
932
|
+
max_steps = int(_flag("--max-steps", "14"))
|
|
933
|
+
|
|
934
|
+
print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}\n")
|
|
935
|
+
if target == "react":
|
|
936
|
+
report = run_react_matrix(task_ids, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
|
|
937
|
+
else:
|
|
938
|
+
report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
|
|
939
|
+
paths = write_artifacts(report)
|
|
940
|
+
if "--json" in args:
|
|
941
|
+
import json as _json
|
|
942
|
+
print(_json.dumps(report, indent=2, ensure_ascii=False))
|
|
943
|
+
else:
|
|
944
|
+
print(render_markdown(report))
|
|
945
|
+
print(f"artifacts: {paths['markdown']}\n {paths['json']}\n")
|
|
946
|
+
|
|
793
947
|
elif command in ("burn", "burn-monitor"):
|
|
794
948
|
from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
|
|
795
949
|
from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
|
|
@@ -978,6 +1132,91 @@ def main(argv: Optional[List[str]] = None):
|
|
|
978
1132
|
from src.mcp_server import run_mcp_server
|
|
979
1133
|
run_mcp_server()
|
|
980
1134
|
|
|
1135
|
+
elif command in ("acp",):
|
|
1136
|
+
from src.acp.server import run_acp_server
|
|
1137
|
+
run_acp_server()
|
|
1138
|
+
|
|
1139
|
+
elif command in ("agent", "run-agent", "run_agent"):
|
|
1140
|
+
opts = {"model": "", "provider": "", "base_url": "", "root": "", "max_steps": 16, "budget": 1.0}
|
|
1141
|
+
prompt_parts: List[str] = []
|
|
1142
|
+
index = 1
|
|
1143
|
+
while index < len(args):
|
|
1144
|
+
arg = args[index]
|
|
1145
|
+
if arg in ("--model", "-m") and index + 1 < len(args):
|
|
1146
|
+
opts["model"] = args[index + 1]
|
|
1147
|
+
index += 2
|
|
1148
|
+
elif arg == "--provider" and index + 1 < len(args):
|
|
1149
|
+
opts["provider"] = args[index + 1]
|
|
1150
|
+
index += 2
|
|
1151
|
+
elif arg in ("--base-url", "--base_url") and index + 1 < len(args):
|
|
1152
|
+
opts["base_url"] = args[index + 1]
|
|
1153
|
+
index += 2
|
|
1154
|
+
elif arg in ("--root", "-C") and index + 1 < len(args):
|
|
1155
|
+
opts["root"] = args[index + 1]
|
|
1156
|
+
index += 2
|
|
1157
|
+
elif arg == "--max-steps" and index + 1 < len(args):
|
|
1158
|
+
try:
|
|
1159
|
+
opts["max_steps"] = int(args[index + 1])
|
|
1160
|
+
except ValueError:
|
|
1161
|
+
pass
|
|
1162
|
+
index += 2
|
|
1163
|
+
elif arg == "--budget" and index + 1 < len(args):
|
|
1164
|
+
try:
|
|
1165
|
+
opts["budget"] = float(args[index + 1])
|
|
1166
|
+
except ValueError:
|
|
1167
|
+
pass
|
|
1168
|
+
index += 2
|
|
1169
|
+
else:
|
|
1170
|
+
prompt_parts.append(arg)
|
|
1171
|
+
index += 1
|
|
1172
|
+
prompt = " ".join(prompt_parts).strip()
|
|
1173
|
+
if not prompt:
|
|
1174
|
+
print("Usage: tokensafe agent [--model M] [--provider P] [--base-url U] [-C dir] "
|
|
1175
|
+
"[--max-steps N] [--budget USD] <prompt>")
|
|
1176
|
+
sys.exit(1)
|
|
1177
|
+
from src.agent.loop import AgentConfig, AgentLoop
|
|
1178
|
+
from src.agent.providers import ProviderError
|
|
1179
|
+
import json as _json
|
|
1180
|
+
|
|
1181
|
+
def _sink(event):
|
|
1182
|
+
kind = event.get("type")
|
|
1183
|
+
if kind == "text":
|
|
1184
|
+
sys.stdout.write(event.get("text") or "")
|
|
1185
|
+
sys.stdout.flush()
|
|
1186
|
+
elif kind == "tool_call":
|
|
1187
|
+
rendered = _json.dumps(event.get("arguments"), ensure_ascii=False)[:160]
|
|
1188
|
+
print(f"\n\033[2m→ {event.get('name')} {rendered}\033[0m")
|
|
1189
|
+
elif kind == "tool_result":
|
|
1190
|
+
state = "ok" if event.get("ok") else "error"
|
|
1191
|
+
print(f"\033[2m← {event.get('name')}: {state} ({len(event.get('text') or '')} chars)\033[0m")
|
|
1192
|
+
elif kind == "compaction":
|
|
1193
|
+
print(f"\033[2m[context compacted: {event.get('before')} → {event.get('after')} tokens]\033[0m")
|
|
1194
|
+
|
|
1195
|
+
loop = AgentLoop(
|
|
1196
|
+
root=opts["root"] or None,
|
|
1197
|
+
session_id="cli:agent",
|
|
1198
|
+
config=AgentConfig(
|
|
1199
|
+
model=opts["model"],
|
|
1200
|
+
provider=opts["provider"],
|
|
1201
|
+
base_url=opts["base_url"],
|
|
1202
|
+
max_steps=opts["max_steps"],
|
|
1203
|
+
budget_usd=opts["budget"],
|
|
1204
|
+
),
|
|
1205
|
+
event_sink=_sink,
|
|
1206
|
+
)
|
|
1207
|
+
try:
|
|
1208
|
+
result = loop.run(prompt)
|
|
1209
|
+
except ProviderError as exc:
|
|
1210
|
+
print(f"\n\033[31mError:\033[0m {exc}")
|
|
1211
|
+
sys.exit(2)
|
|
1212
|
+
usage = result.usage
|
|
1213
|
+
priced = "" if usage.get("priced") else " · unpriced model"
|
|
1214
|
+
print(
|
|
1215
|
+
f"\n\033[2m[{result.stop_reason} · {result.steps} step(s) · "
|
|
1216
|
+
f"{usage.get('input_tokens', 0)} in / {usage.get('output_tokens', 0)} out · "
|
|
1217
|
+
f"${usage.get('usd', 0.0):.4f}{priced}]\033[0m"
|
|
1218
|
+
)
|
|
1219
|
+
|
|
981
1220
|
elif command in ("mcp-proxy", "mcp_proxy"):
|
|
982
1221
|
target_args = list(args[1:])
|
|
983
1222
|
if target_args and target_args[0] == "--":
|
package/src/command_sanitizer.py
CHANGED
|
@@ -387,6 +387,12 @@ class CommandSanitizer:
|
|
|
387
387
|
if dev_guard:
|
|
388
388
|
return dev_guard
|
|
389
389
|
|
|
390
|
+
# FastAPI dev servers: run through `tokensafe run-backend` so the global
|
|
391
|
+
# autoload hook mounts OUMV without editing the project.
|
|
392
|
+
py_dev_guard = cls._optimize_python_dev_stage(stage, cwd)
|
|
393
|
+
if py_dev_guard:
|
|
394
|
+
return py_dev_guard
|
|
395
|
+
|
|
390
396
|
# find: prune unbounded recursion on simple directory crawls (avoid breaking -o / -exec / -delete expressions)
|
|
391
397
|
if cmd_tok == "find" and "node_modules" not in stage and ".git" not in stage:
|
|
392
398
|
has_complex = any(a in ("-o", "-or", "-exec", "-execdir", "-delete", "(") for a in cmd_args)
|
|
@@ -695,6 +701,54 @@ class CommandSanitizer:
|
|
|
695
701
|
except Exception:
|
|
696
702
|
return False
|
|
697
703
|
|
|
704
|
+
@classmethod
|
|
705
|
+
def _is_fastapi_workspace(cls, cwd: Optional[str]) -> bool:
|
|
706
|
+
"""Cheap, side-effect-free FastAPI detection for the rewrite decision."""
|
|
707
|
+
if not cwd or not os.path.isdir(cwd):
|
|
708
|
+
return False
|
|
709
|
+
for name in ("pyproject.toml", "requirements.txt", "main.py", "app.py"):
|
|
710
|
+
path = os.path.join(cwd, name)
|
|
711
|
+
try:
|
|
712
|
+
if os.path.isfile(path):
|
|
713
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
714
|
+
if "fastapi" in f.read().lower():
|
|
715
|
+
return True
|
|
716
|
+
except OSError:
|
|
717
|
+
continue
|
|
718
|
+
app_dir = os.path.join(cwd, "app")
|
|
719
|
+
for name in ("main.py", "app.py"):
|
|
720
|
+
path = os.path.join(app_dir, name)
|
|
721
|
+
try:
|
|
722
|
+
if os.path.isfile(path):
|
|
723
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
724
|
+
if "fastapi" in f.read().lower():
|
|
725
|
+
return True
|
|
726
|
+
except OSError:
|
|
727
|
+
continue
|
|
728
|
+
return False
|
|
729
|
+
|
|
730
|
+
@classmethod
|
|
731
|
+
def _optimize_python_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
|
|
732
|
+
"""Rewrites `uvicorn ...` / `python -m uvicorn ...` into `tokensafe run-backend ...`.
|
|
733
|
+
|
|
734
|
+
The wrapper only sets PYTHONPATH/TOKENSAFE_OUMV_AUTOMOUNT and execs the same
|
|
735
|
+
command, so the agent keeps control of ports/flags and the repository stays
|
|
736
|
+
untouched.
|
|
737
|
+
"""
|
|
738
|
+
stripped = stage.strip()
|
|
739
|
+
if "tokensafe run-backend" in stripped or "tokensafe inject" in stripped:
|
|
740
|
+
return None
|
|
741
|
+
if not re.match(r"^(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:python[0-9.]*\s+-m\s+)?uvicorn\b", stripped):
|
|
742
|
+
return None
|
|
743
|
+
if not cls._is_fastapi_workspace(cwd):
|
|
744
|
+
return None
|
|
745
|
+
return (
|
|
746
|
+
f"tokensafe run-backend {stripped}",
|
|
747
|
+
1400,
|
|
748
|
+
"Routed FastAPI dev server through `tokensafe run-backend` (auto-mounts OUMV, no repo changes)",
|
|
749
|
+
None,
|
|
750
|
+
)
|
|
751
|
+
|
|
698
752
|
@classmethod
|
|
699
753
|
def _optimize_vite_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
|
|
700
754
|
"""
|
package/src/guard.py
CHANGED
|
@@ -23,6 +23,64 @@ from src.command_sanitizer import CommandSanitizer
|
|
|
23
23
|
|
|
24
24
|
_TOKENSAFE_SRC_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
25
25
|
|
|
26
|
+
# --------------------------------------------------------------------------- #
|
|
27
|
+
# Network data-exfiltration detection (shell-flow aware)
|
|
28
|
+
#
|
|
29
|
+
# The previous single regex matched `-d` inside `tokensafe-dev` together with the
|
|
30
|
+
# word `token` inside `tokensafe-python`, across a `;` separator, so read-only
|
|
31
|
+
# checks like `curl … https://pypi.org/… ; gh secret list -R org/repo` were
|
|
32
|
+
# blocked. It also flagged any script that merely quoted such a command in a
|
|
33
|
+
# heredoc. Detection is now per shell segment and only fires on a sensitive
|
|
34
|
+
# *file* actually being uploaded.
|
|
35
|
+
# --------------------------------------------------------------------------- #
|
|
36
|
+
|
|
37
|
+
_EXFIL_SENSITIVE_PATH = (
|
|
38
|
+
r"(?:\.env(?:\.[\w-]+)?|id_rsa|id_ed25519|credentials\.json|service_account\.json|"
|
|
39
|
+
r"\.npmrc|\.pypirc|[\w.-]*\.(?:pem|key)|secrets?\.(?:json|ya?ml|toml|env))"
|
|
40
|
+
)
|
|
41
|
+
_EXFIL_FILE = rf"(?:[\w./~-]*/)?{_EXFIL_SENSITIVE_PATH}"
|
|
42
|
+
_EXFIL_NET = r"(?:sudo\s+)?(?:curl|wget|nc|ncat|netcat)"
|
|
43
|
+
|
|
44
|
+
_EXFIL_PATTERNS = (
|
|
45
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:--data(?:-binary|-raw)?|--post-file|-d|-T|--upload-file)(?:[=\s]+)@?['\"]?{_EXFIL_FILE}",
|
|
46
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:-F|--form)\s+[^=\s]*=@['\"]?{_EXFIL_FILE}",
|
|
47
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*<\s*['\"]?{_EXFIL_FILE}",
|
|
48
|
+
rf"\bcat\s+['\"]?{_EXFIL_FILE}['\"]?\s*\|\s*{_EXFIL_NET}\b",
|
|
49
|
+
# command substitution / backticks reading a sensitive file into the URL
|
|
50
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*\$\(\s*(?:cat\s+)?['\"]?{_EXFIL_FILE}",
|
|
51
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*`cat\s+['\"]?{_EXFIL_FILE}",
|
|
52
|
+
)
|
|
53
|
+
_EXFIL_COMPILED = tuple(re.compile(p, re.IGNORECASE) for p in _EXFIL_PATTERNS)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _strip_heredocs(command: str) -> str:
|
|
57
|
+
"""Drops heredoc bodies: their text is data for an interpreter, not shell flow."""
|
|
58
|
+
lines = command.splitlines()
|
|
59
|
+
kept = []
|
|
60
|
+
i = 0
|
|
61
|
+
while i < len(lines):
|
|
62
|
+
line = lines[i]
|
|
63
|
+
kept.append(line)
|
|
64
|
+
match = re.search(r"<<-?\s*['\"]?([A-Za-z_]\w*)['\"]?", line)
|
|
65
|
+
if match:
|
|
66
|
+
tag = match.group(1)
|
|
67
|
+
i += 1
|
|
68
|
+
while i < len(lines) and lines[i].strip() != tag:
|
|
69
|
+
i += 1
|
|
70
|
+
i += 1
|
|
71
|
+
return "\n".join(kept)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _detect_shell_exfiltration(command: str):
|
|
75
|
+
"""Returns the offending fragment when a sensitive file is sent to a network client."""
|
|
76
|
+
shell = _strip_heredocs(command or "")
|
|
77
|
+
for pattern in _EXFIL_COMPILED:
|
|
78
|
+
match = pattern.search(shell)
|
|
79
|
+
if match:
|
|
80
|
+
return match.group(0)
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
26
84
|
class GuardResult(NamedTuple):
|
|
27
85
|
blocked: bool
|
|
28
86
|
reason: Optional[str] = None
|
|
@@ -536,20 +594,15 @@ class TokenSafeGuard:
|
|
|
536
594
|
),
|
|
537
595
|
)
|
|
538
596
|
|
|
539
|
-
# 3. Network Data Exfiltration Prevention (
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
rf"""(?:\b(?:curl|wget|nc|ncat|netcat)\b.*?(?:\$\(\s*(?:cat\s+)?<?\s*[^)]*{_SENS_EXFIL}[^)]*\)|`cat\s+[^`]*{_SENS_EXFIL}[^`]*`|(?:-d|--data|--data-binary|--data-raw|-T|--upload-file)[=\s]*@?[^\s]*{_SENS_EXFIL}|-F\s+[^=]*=@[^\s]*{_SENS_EXFIL}|--post-file[=\s]+[^\s]*{_SENS_EXFIL}|<\s*[^\s]*{_SENS_EXFIL})|\bcat\s+[^\s|]*{_SENS_EXFIL}\s*\|\s*(?:curl|wget|nc|ncat|netcat)\b)""",
|
|
543
|
-
cmd,
|
|
544
|
-
re.IGNORECASE
|
|
545
|
-
)
|
|
546
|
-
if exfil_pattern:
|
|
597
|
+
# 3. Network Data Exfiltration Prevention (uploading sensitive FILES to a network client)
|
|
598
|
+
exfil_hit = _detect_shell_exfiltration(cmd)
|
|
599
|
+
if exfil_hit:
|
|
547
600
|
return GuardResult(
|
|
548
601
|
blocked=True,
|
|
549
602
|
check_name="DATA_EXFILTRATION",
|
|
550
603
|
reason=(
|
|
551
|
-
f"Blocked potential credential exfiltration via network command: '{
|
|
552
|
-
f"
|
|
604
|
+
f"Blocked potential credential exfiltration via network command: '{exfil_hit}'. "
|
|
605
|
+
f"Uploading local sensitive files (.env / private keys) to remote endpoints is prohibited."
|
|
553
606
|
)
|
|
554
607
|
)
|
|
555
608
|
|