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/retrofit.py
CHANGED
|
@@ -353,6 +353,13 @@ def generate_config(
|
|
|
353
353
|
os.makedirs(target_dir, exist_ok=True)
|
|
354
354
|
with open(target_file, "w", encoding="utf-8") as f:
|
|
355
355
|
json.dump(config, f, indent=2)
|
|
356
|
+
# The manifest must never show up as an untracked change: ignore it via
|
|
357
|
+
# .git/info/exclude (local-only) instead of editing the tracked .gitignore.
|
|
358
|
+
try:
|
|
359
|
+
from src.paths import ensure_local_git_exclude
|
|
360
|
+
ensure_local_git_exclude(workspace_dir)
|
|
361
|
+
except Exception:
|
|
362
|
+
pass
|
|
356
363
|
|
|
357
364
|
return config, target_file, True
|
|
358
365
|
|
|
@@ -468,7 +475,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
|
|
|
468
475
|
"technology": {
|
|
469
476
|
"language": "python",
|
|
470
477
|
"framework": "fastapi",
|
|
471
|
-
"package": {"manager": "pip", "name": "tokensafe-python", "install":
|
|
478
|
+
"package": {"manager": "pip", "name": "tokensafe-backend-python", "install": 'pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"'},
|
|
472
479
|
},
|
|
473
480
|
"capabilities": [
|
|
474
481
|
{"name": "observe.resources", "constraints": {"readOnly": True, "developmentOnly": False}},
|
|
@@ -490,8 +497,54 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
|
|
|
490
497
|
]
|
|
491
498
|
|
|
492
499
|
|
|
500
|
+
def _adapter_presence(workspace_dir: str, profile: str, provider: str, framework: str) -> Dict[str, Any]:
|
|
501
|
+
"""Best-effort, side-effect-free check whether an adapter is available locally.
|
|
502
|
+
|
|
503
|
+
Returns {"installed": bool, "evidence": str} where evidence names what was
|
|
504
|
+
actually found — never a bare True.
|
|
505
|
+
"""
|
|
506
|
+
ws = os.path.abspath(workspace_dir)
|
|
507
|
+
if profile == "frontend":
|
|
508
|
+
pkg_json = os.path.join(ws, "node_modules", "tokensafe-ui", "package.json")
|
|
509
|
+
if os.path.isfile(pkg_json):
|
|
510
|
+
return {"installed": True, "evidence": "node_modules/tokensafe-ui"}
|
|
511
|
+
return {"installed": False, "evidence": "node_modules/tokensafe-ui missing (run: npm install -D tokensafe-ui)"}
|
|
512
|
+
|
|
513
|
+
if provider == "fastapi":
|
|
514
|
+
try:
|
|
515
|
+
import importlib.util
|
|
516
|
+
if importlib.util.find_spec("tokensafe_python") is not None:
|
|
517
|
+
return {"installed": True, "evidence": "tokensafe_python importable"}
|
|
518
|
+
except Exception:
|
|
519
|
+
pass
|
|
520
|
+
for req in ("requirements.txt", "pyproject.toml"):
|
|
521
|
+
path = os.path.join(ws, req)
|
|
522
|
+
try:
|
|
523
|
+
if os.path.isfile(path):
|
|
524
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
525
|
+
if "tokensafe" in fh.read():
|
|
526
|
+
return {"installed": True, "evidence": f"{req} declares tokensafe"}
|
|
527
|
+
except Exception:
|
|
528
|
+
pass
|
|
529
|
+
return {"installed": False, "evidence": 'tokensafe_python not importable (run: pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python")'}
|
|
530
|
+
|
|
531
|
+
if provider == "go":
|
|
532
|
+
for rel in ("go.mod", os.path.join("go", "go.mod")):
|
|
533
|
+
path = os.path.join(ws, rel)
|
|
534
|
+
try:
|
|
535
|
+
if os.path.isfile(path):
|
|
536
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
537
|
+
if "tokensafe-backend/go" in fh.read():
|
|
538
|
+
return {"installed": True, "evidence": f"{rel} requires tokensafe-backend/go"}
|
|
539
|
+
except Exception:
|
|
540
|
+
pass
|
|
541
|
+
return {"installed": False, "evidence": "tokensafe-backend/go not in go.mod (run: go get github.com/tokensafe-dev/tokensafe-backend/go@vX.Y.Z)"}
|
|
542
|
+
|
|
543
|
+
return {"installed": False, "evidence": f"no adapter published for {provider}/{framework}"}
|
|
544
|
+
|
|
545
|
+
|
|
493
546
|
def run_doctor(workspace_dir: str) -> Dict[str, Any]:
|
|
494
|
-
"""Diagnostics
|
|
547
|
+
"""Diagnostics for OUMV configuration, detected adapters and agent readiness."""
|
|
495
548
|
stack = detect_project_stack(workspace_dir)
|
|
496
549
|
conf_path = os.path.join(workspace_dir, ".tokensafe", "oumv.json")
|
|
497
550
|
runtime_paths = [
|
|
@@ -522,6 +575,34 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
|
|
|
522
575
|
except Exception:
|
|
523
576
|
pass
|
|
524
577
|
|
|
578
|
+
# Per-profile readiness: a config file alone is not "ready for agent".
|
|
579
|
+
readiness: Dict[str, Any] = {}
|
|
580
|
+
for profile, key in (("frontend", "frontend"), ("backend", "backend")):
|
|
581
|
+
detected = stack.get(key)
|
|
582
|
+
if not detected:
|
|
583
|
+
continue
|
|
584
|
+
provider = detected.get("provider", "")
|
|
585
|
+
framework = detected.get("framework", "")
|
|
586
|
+
presence = _adapter_presence(workspace_dir, profile, provider, framework)
|
|
587
|
+
live = has_runtime and runtime_data.get("type", profile) in (profile, None)
|
|
588
|
+
readiness[profile] = {
|
|
589
|
+
"provider": provider,
|
|
590
|
+
"framework": framework,
|
|
591
|
+
"installed": presence["installed"],
|
|
592
|
+
"evidence": presence["evidence"],
|
|
593
|
+
"live": bool(live),
|
|
594
|
+
"ready": bool(presence["installed"] or live),
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
permissions = config_data.get("permissions", {"observe": True, "mutate": True})
|
|
598
|
+
config_enabled = bool(config_data.get("oumv", {}).get("enabled", has_config))
|
|
599
|
+
ready_for_agent = bool(
|
|
600
|
+
has_config
|
|
601
|
+
and config_enabled
|
|
602
|
+
and permissions.get("observe", True)
|
|
603
|
+
and all(item["ready"] for item in readiness.values())
|
|
604
|
+
)
|
|
605
|
+
|
|
525
606
|
return {
|
|
526
607
|
"workspace": workspace_dir,
|
|
527
608
|
"detected_stack": stack,
|
|
@@ -529,8 +610,14 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
|
|
|
529
610
|
"config": config_data,
|
|
530
611
|
"runtime_beacon_present": has_runtime,
|
|
531
612
|
"runtime_beacon": runtime_data,
|
|
532
|
-
"permissions":
|
|
533
|
-
"
|
|
613
|
+
"permissions": permissions,
|
|
614
|
+
"adapter_readiness": readiness,
|
|
615
|
+
"ready_for_agent": ready_for_agent,
|
|
616
|
+
"blocking": [
|
|
617
|
+
f"{profile}: {item['evidence']}"
|
|
618
|
+
for profile, item in readiness.items()
|
|
619
|
+
if not item["ready"]
|
|
620
|
+
],
|
|
534
621
|
}
|
|
535
622
|
|
|
536
623
|
|
package/src/savings.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Canonical savings report for agents and hooks.
|
|
2
|
+
|
|
3
|
+
Agents must never quote savings from a guess or from a stray database file: the
|
|
4
|
+
one source of truth is the canonical data dir resolved by ``src.paths``
|
|
5
|
+
(``TOKENSAFE_DATA_DIR`` or ``~/.tokensafe/data``). This module exposes it as a
|
|
6
|
+
single JSON-able report, including the difference between:
|
|
7
|
+
* live events still in ``events`` / ``lifetime_aggregates``, and
|
|
8
|
+
* totals already pruned from the local DB but counted in the cloud mirror
|
|
9
|
+
(``pruned_synced_*``).
|
|
10
|
+
|
|
11
|
+
Repository-local ``data/metrics.db`` files are legacy/test artifacts and are NOT
|
|
12
|
+
read here.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import sqlite3
|
|
18
|
+
from typing import Any, Dict, Optional
|
|
19
|
+
|
|
20
|
+
from src.metrics import MetricsTracker
|
|
21
|
+
from src.paths import resolve_data_dir
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _pruned_synced(db_path: str) -> Dict[str, int]:
|
|
25
|
+
try:
|
|
26
|
+
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
|
27
|
+
try:
|
|
28
|
+
row = conn.execute(
|
|
29
|
+
"SELECT pruned_synced_orig_tokens, pruned_synced_saved_tokens FROM lifetime_aggregates WHERE id = 1"
|
|
30
|
+
).fetchone()
|
|
31
|
+
finally:
|
|
32
|
+
conn.close()
|
|
33
|
+
if not row:
|
|
34
|
+
return {"original_tokens": 0, "saved_tokens": 0}
|
|
35
|
+
return {"original_tokens": int(row[0] or 0), "saved_tokens": int(row[1] or 0)}
|
|
36
|
+
except Exception:
|
|
37
|
+
return {"original_tokens": 0, "saved_tokens": 0}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_savings_report(tracker: Optional[MetricsTracker] = None) -> Dict[str, Any]:
|
|
41
|
+
"""Returns canonical totals, last event, and the cumulative explanation."""
|
|
42
|
+
tracker = tracker or MetricsTracker()
|
|
43
|
+
summary = tracker.get_summary()
|
|
44
|
+
last_events = tracker.get_recent_events(limit=1)
|
|
45
|
+
|
|
46
|
+
live_saved = int(summary.get("total_saved_tokens", 0))
|
|
47
|
+
pruned = _pruned_synced(tracker.db_path)
|
|
48
|
+
cumulative = live_saved + pruned["saved_tokens"]
|
|
49
|
+
|
|
50
|
+
last_event = None
|
|
51
|
+
if last_events:
|
|
52
|
+
event = last_events[0]
|
|
53
|
+
last_event = {
|
|
54
|
+
"timestamp": event.get("timestamp"),
|
|
55
|
+
"event_type": event.get("event_type"),
|
|
56
|
+
"tool": event.get("event_type"),
|
|
57
|
+
"session_id": event.get("session_id"),
|
|
58
|
+
"saved_tokens": int(event.get("saved_tokens") or 0),
|
|
59
|
+
"original_tokens": int(event.get("original_tokens") or 0),
|
|
60
|
+
"optimized_tokens": int(event.get("optimized_tokens") or 0),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
"source": "canonical",
|
|
65
|
+
"data_dir": resolve_data_dir(),
|
|
66
|
+
"db_path": tracker.db_path,
|
|
67
|
+
"total_events": int(summary.get("total_events", 0)),
|
|
68
|
+
"sessions": int(summary.get("session_count", 0)),
|
|
69
|
+
"saved_tokens_live": live_saved,
|
|
70
|
+
"saved_tokens_measured": int(summary.get("total_saved_tokens_measured", 0)),
|
|
71
|
+
"saved_tokens_estimated": int(summary.get("total_saved_tokens_estimated", 0)),
|
|
72
|
+
"pruned_synced_saved_tokens": pruned["saved_tokens"],
|
|
73
|
+
"cumulative_saved_tokens": cumulative,
|
|
74
|
+
"usd_saved_approx": summary.get("total_usd_saved", 0.0),
|
|
75
|
+
"reduction_pct": summary.get("overall_reduction_pct", 0.0),
|
|
76
|
+
"last_event": last_event,
|
|
77
|
+
"note": (
|
|
78
|
+
"cumulative = live events + totals pruned locally but already synced; "
|
|
79
|
+
"per-turn delta must be read from last_event, never guessed"
|
|
80
|
+
),
|
|
81
|
+
}
|
package/src/scaffold.py
CHANGED
|
@@ -335,10 +335,16 @@ class ProjectScaffolder:
|
|
|
335
335
|
) -> Dict[str, Any]:
|
|
336
336
|
"""Generates project template files in target_dir."""
|
|
337
337
|
template = template.lower().strip()
|
|
338
|
-
|
|
339
|
-
|
|
338
|
+
valid = (
|
|
339
|
+
"fullstack", "ui", "backend", "python", "fastapi", "go", "gin",
|
|
340
|
+
"react-fastapi", "react-go", "vue-gin", "react", "vue",
|
|
341
|
+
)
|
|
342
|
+
if template not in valid:
|
|
343
|
+
raise ValueError(
|
|
344
|
+
f"Unknown template: '{template}'. Valid options: {', '.join(valid)}"
|
|
345
|
+
)
|
|
340
346
|
|
|
341
|
-
if template
|
|
347
|
+
if template == "python":
|
|
342
348
|
template = "backend"
|
|
343
349
|
|
|
344
350
|
os.makedirs(target_dir, exist_ok=True)
|
|
@@ -404,13 +410,64 @@ class ProjectScaffolder:
|
|
|
404
410
|
readme = cls._generate_readme(project_name, template="ui")
|
|
405
411
|
_write("README.md", readme)
|
|
406
412
|
|
|
407
|
-
elif template in ("
|
|
408
|
-
|
|
413
|
+
elif template in ("react-fastapi", "react-go", "vue-gin"):
|
|
414
|
+
frontend, backend = template.split("-")
|
|
415
|
+
cls._scaffold_react_ui(target_dir, project_name, subpath="frontend", write_fn=_write, write_json_fn=_write_json) if frontend == "react" else cls._scaffold_vue_ui(target_dir, project_name, subpath="frontend", write_fn=_write, write_json_fn=_write_json)
|
|
416
|
+
if backend in ("go", "gin"):
|
|
417
|
+
cls._scaffold_go_backend(target_dir, project_name, subpath="backend", write_fn=_write)
|
|
418
|
+
backend_url = "http://localhost:8080/__oumv/rpc"
|
|
419
|
+
backend_name = "tokensafe-backend"
|
|
420
|
+
else:
|
|
421
|
+
cls._scaffold_backend(target_dir, project_name, subpath="backend", write_fn=_write)
|
|
422
|
+
backend_url = "http://localhost:8000/__oumv/rpc"
|
|
423
|
+
backend_name = "tokensafe-python"
|
|
424
|
+
_write_json(os.path.join(".tokensafe", "runtime.json"), {
|
|
425
|
+
"frontend": {
|
|
426
|
+
"name": "tokensafe-ui",
|
|
427
|
+
"version": "0.1.22",
|
|
428
|
+
"url": "http://localhost:5173/__oumv/rpc",
|
|
429
|
+
},
|
|
430
|
+
"backend": {"name": backend_name, "version": "0.4.0", "url": backend_url},
|
|
431
|
+
})
|
|
432
|
+
_write("AGENTS.md", cls._generate_agents_md(project_name, is_fullstack=True))
|
|
433
|
+
_write("README.md", cls._generate_recipe_readme(project_name, template))
|
|
434
|
+
_write("package.json", json.dumps({
|
|
435
|
+
"name": project_name.lower().replace(" ", "-"),
|
|
436
|
+
"private": True,
|
|
437
|
+
"scripts": {
|
|
438
|
+
"dev": "tokensafe dev frontend",
|
|
439
|
+
"dev:api": "tokensafe run-backend"
|
|
440
|
+
+ (" go run ./backend" if backend in ("go", "gin")
|
|
441
|
+
else " uvicorn main:app --reload --app-dir backend"),
|
|
442
|
+
},
|
|
443
|
+
}, indent=2) + "\n")
|
|
444
|
+
|
|
445
|
+
elif template in ("react", "vue"):
|
|
446
|
+
if template == "react":
|
|
447
|
+
cls._scaffold_react_ui(target_dir, project_name, subpath="", write_fn=_write, write_json_fn=_write_json)
|
|
448
|
+
else:
|
|
449
|
+
cls._scaffold_vue_ui(target_dir, project_name, subpath="", write_fn=_write, write_json_fn=_write_json)
|
|
450
|
+
_write_json(os.path.join(".tokensafe", "runtime.json"), {
|
|
451
|
+
"frontend": {
|
|
452
|
+
"name": "tokensafe-ui",
|
|
453
|
+
"version": "0.1.22",
|
|
454
|
+
"url": "http://localhost:5173/__oumv/rpc",
|
|
455
|
+
},
|
|
456
|
+
})
|
|
457
|
+
_write("AGENTS.md", cls._generate_agents_md(project_name, is_fullstack=False, is_ui=True))
|
|
458
|
+
_write("README.md", cls._generate_recipe_readme(project_name, template))
|
|
459
|
+
|
|
460
|
+
elif template in ("backend", "go", "gin", "fastapi"):
|
|
461
|
+
is_go = template in ("go", "gin")
|
|
462
|
+
if is_go:
|
|
463
|
+
cls._scaffold_go_backend(target_dir, project_name, subpath="", write_fn=_write)
|
|
464
|
+
else:
|
|
465
|
+
cls._scaffold_backend(target_dir, project_name, subpath="", write_fn=_write)
|
|
409
466
|
runtime_config = {
|
|
410
467
|
"backend": {
|
|
411
|
-
"name": "tokensafe-
|
|
412
|
-
"version": "0.
|
|
413
|
-
"url": "http://localhost:
|
|
468
|
+
"name": "tokensafe-backend" if is_go else "tokensafe-python",
|
|
469
|
+
"version": "0.4.0" if is_go else "0.3.0",
|
|
470
|
+
"url": "http://localhost:8080/__oumv/rpc" if is_go else "http://localhost:8000/__oumv/rpc"
|
|
414
471
|
}
|
|
415
472
|
}
|
|
416
473
|
_write_json(os.path.join(".tokensafe", "runtime.json"), runtime_config)
|
|
@@ -441,6 +498,131 @@ class ProjectScaffolder:
|
|
|
441
498
|
write_fn(p(os.path.join("src", "main.ts")), DEFAULT_MAIN_TS)
|
|
442
499
|
write_fn(p(os.path.join("src", "App.tsx")), DEFAULT_APP_TSX)
|
|
443
500
|
|
|
501
|
+
# ---- framework recipes: user picks the stack, we wire OUMV -------------
|
|
502
|
+
|
|
503
|
+
@classmethod
|
|
504
|
+
def _scaffold_react_ui(cls, target_dir, project_name, subpath, write_fn, write_json_fn):
|
|
505
|
+
p = lambda rel: os.path.join(subpath, rel) if subpath else rel
|
|
506
|
+
slug = project_name.lower().replace(" ", "-")
|
|
507
|
+
write_json_fn(p("package.json"), {
|
|
508
|
+
"name": f"{slug}-web",
|
|
509
|
+
"private": True,
|
|
510
|
+
"type": "module",
|
|
511
|
+
"scripts": {
|
|
512
|
+
# `tokensafe dev` serves OUMV with an inline Vite config: no plugin
|
|
513
|
+
# line, no descriptor, nothing to commit.
|
|
514
|
+
"dev": "tokensafe dev",
|
|
515
|
+
"build": "vite build",
|
|
516
|
+
},
|
|
517
|
+
"dependencies": {"react": "^18.3.1", "react-dom": "^18.3.1"},
|
|
518
|
+
"devDependencies": {
|
|
519
|
+
"@vitejs/plugin-react": "^4.3.1",
|
|
520
|
+
"vite": "^5.4.0",
|
|
521
|
+
"tokensafe-ui": "^0.1.22",
|
|
522
|
+
},
|
|
523
|
+
})
|
|
524
|
+
write_json_fn(p("tsconfig.json"), {
|
|
525
|
+
"compilerOptions": {
|
|
526
|
+
"target": "ES2022",
|
|
527
|
+
"module": "ESNext",
|
|
528
|
+
"moduleResolution": "Bundler",
|
|
529
|
+
"jsx": "react-jsx",
|
|
530
|
+
"strict": True,
|
|
531
|
+
"skipLibCheck": True,
|
|
532
|
+
"noEmit": True,
|
|
533
|
+
},
|
|
534
|
+
"include": ["src"],
|
|
535
|
+
})
|
|
536
|
+
write_fn(p("vite.config.ts"), "import { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\n// OUMV is served by `tokensafe dev` (zero repo footprint); this config stays plain.\nexport default defineConfig({ plugins: [react()] });\n")
|
|
537
|
+
write_fn(p("index.html"), f"<!doctype html>\n<html lang=\"en\">\n <head><meta charset=\"utf-8\" /><title>{project_name}</title></head>\n <body><div id=\"root\"></div><script type=\"module\" src=\"/src/main.tsx\"></script></body>\n</html>\n")
|
|
538
|
+
write_fn(p("src/main.tsx"), """import { useState } from 'react';
|
|
539
|
+
import { createRoot } from 'react-dom/client';
|
|
540
|
+
|
|
541
|
+
export function App() {
|
|
542
|
+
const [count, setCount] = useState(0);
|
|
543
|
+
return (
|
|
544
|
+
<main>
|
|
545
|
+
<h1>__NAME__</h1>
|
|
546
|
+
<button onClick={() => setCount(count + 1)}>count: {count}</button>
|
|
547
|
+
</main>
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
createRoot(document.getElementById('root')!).render(<App />);
|
|
552
|
+
""".replace("__NAME__", project_name))
|
|
553
|
+
write_fn(p("src/style.css"), "body { font-family: system-ui, sans-serif; margin: 2rem; }\n")
|
|
554
|
+
|
|
555
|
+
@classmethod
|
|
556
|
+
def _scaffold_vue_ui(cls, target_dir, project_name, subpath, write_fn, write_json_fn):
|
|
557
|
+
p = lambda rel: os.path.join(subpath, rel) if subpath else rel
|
|
558
|
+
slug = project_name.lower().replace(" ", "-")
|
|
559
|
+
write_json_fn(p("package.json"), {
|
|
560
|
+
"name": f"{slug}-web",
|
|
561
|
+
"private": True,
|
|
562
|
+
"type": "module",
|
|
563
|
+
"scripts": {"dev": "tokensafe dev", "build": "vite build"},
|
|
564
|
+
"dependencies": {"vue": "^3.4.0"},
|
|
565
|
+
"devDependencies": {
|
|
566
|
+
"@vitejs/plugin-vue": "^5.1.0",
|
|
567
|
+
"vite": "^5.4.0",
|
|
568
|
+
"tokensafe-ui": "^0.1.22",
|
|
569
|
+
},
|
|
570
|
+
})
|
|
571
|
+
write_fn(p("vite.config.ts"), "import { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\n// OUMV is served by `tokensafe dev` (zero repo footprint).\nexport default defineConfig({ plugins: [vue()] });\n")
|
|
572
|
+
write_fn(p("index.html"), f"<!doctype html>\n<html lang=\"en\">\n <head><meta charset=\"utf-8\" /><title>{project_name}</title></head>\n <body><div id=\"app\"></div><script type=\"module\" src=\"/src/main.ts\"></script></body>\n</html>\n")
|
|
573
|
+
write_fn(p("src/main.ts"), "import { createApp } from 'vue';\nimport App from './App.vue';\n\ncreateApp(App).mount('#app');\n")
|
|
574
|
+
write_fn(p("src/App.vue"), f"<template>\n <main>\n <h1>{project_name}</h1>\n <button @click=\"count++\">count: {{{{ count }}}}</button>\n </main>\n</template>\n\n<script setup lang=\"ts\">\nimport {{ ref }} from 'vue';\nconst count = ref(0);\n</script>\n")
|
|
575
|
+
|
|
576
|
+
@classmethod
|
|
577
|
+
def _scaffold_go_backend(cls, target_dir, project_name, subpath, write_fn):
|
|
578
|
+
p = lambda rel: os.path.join(subpath, rel) if subpath else rel
|
|
579
|
+
slug = project_name.lower().replace(" ", "-")
|
|
580
|
+
write_fn(p("go.mod"), f"module example.com/{slug}\n\ngo 1.21\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.10.0\n\tgithub.com/tokensafe-dev/tokensafe-backend/go v0.4.3\n)\n")
|
|
581
|
+
write_fn(p("main.go"), """package main
|
|
582
|
+
|
|
583
|
+
import (
|
|
584
|
+
"net/http"
|
|
585
|
+
|
|
586
|
+
"github.com/gin-gonic/gin"
|
|
587
|
+
oumvgin "github.com/tokensafe-dev/tokensafe-backend/go/pkg/adapters/gin"
|
|
588
|
+
)
|
|
589
|
+
|
|
590
|
+
func main() {
|
|
591
|
+
r := gin.Default()
|
|
592
|
+
r.GET("/api/health", func(c *gin.Context) {
|
|
593
|
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
594
|
+
})
|
|
595
|
+
|
|
596
|
+
// OUMV: observe/understand/mutate/verify over POST /__oumv/rpc.
|
|
597
|
+
oumvgin.AutoMount(r)
|
|
598
|
+
|
|
599
|
+
_ = r.Run(":8080")
|
|
600
|
+
}
|
|
601
|
+
""")
|
|
602
|
+
|
|
603
|
+
@classmethod
|
|
604
|
+
def _generate_recipe_readme(cls, project_name: str, template: str) -> str:
|
|
605
|
+
return f"""# {project_name}
|
|
606
|
+
|
|
607
|
+
Generated by `tokensafe create --template {template}`.
|
|
608
|
+
|
|
609
|
+
## Run
|
|
610
|
+
|
|
611
|
+
```bash
|
|
612
|
+
npm install # root + frontend deps (if applicable)
|
|
613
|
+
npm run dev # frontend through `tokensafe dev` (OUMV, zero repo footprint)
|
|
614
|
+
npm run dev:api # backend through `tokensafe run-backend` / go run
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
## Working with an AI agent
|
|
618
|
+
|
|
619
|
+
The adapters are already wired, so an agent works through the OUMV protocol:
|
|
620
|
+
|
|
621
|
+
* frontend — `tokensafe dev` serves L0-L4 plus OCC source edits; nothing is added to git.
|
|
622
|
+
* backend — FastAPI auto-mounts via `tokensafe run-backend`, Go via `oumvgin.AutoMount`.
|
|
623
|
+
* `tokensafe inject --status` prints the live wiring plan; `tokensafe oumv doctor` shows readiness.
|
|
624
|
+
"""
|
|
625
|
+
|
|
444
626
|
@classmethod
|
|
445
627
|
def _scaffold_backend(cls, target_dir: str, project_name: str, subpath: str, write_fn):
|
|
446
628
|
p = lambda rel: os.path.join(subpath, rel) if subpath else rel
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Per-workspace routing brief injected into the agent's context.
|
|
2
|
+
|
|
3
|
+
The brief is the single source of truth for "what do I work through here?":
|
|
4
|
+
|
|
5
|
+
* OUMV-supported stacks (React/Vue + Vite, FastAPI, Go/Gin|Chi) get the exact
|
|
6
|
+
activation command and the ``oumv`` tool verbs to use;
|
|
7
|
+
* unsupported stacks (Node/Express, Django, ...) are named so the agent falls back
|
|
8
|
+
to the TokenSafe tools instead of wasting turns probing ``oumv``;
|
|
9
|
+
* everything is delivered through hooks / MCP instructions — nothing is written
|
|
10
|
+
into the repository.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
from typing import Any, Dict, List, Optional
|
|
18
|
+
|
|
19
|
+
MAX_BRIEF_CHARS = 1200
|
|
20
|
+
|
|
21
|
+
_FRONTEND_LINES = {
|
|
22
|
+
"react": (
|
|
23
|
+
"frontend {provider}/{framework}: OUMV live via `tokensafe dev` "
|
|
24
|
+
"(zero repo footprint, L0-L4, OCC edits). Call tokensafe:oumv(action='observe', level='L1') "
|
|
25
|
+
"before reading files; run `tokensafe dev` if no runtime is live."
|
|
26
|
+
),
|
|
27
|
+
"vue": (
|
|
28
|
+
"frontend {provider}/{framework}: OUMV via `tokensafe dev` (L0-L2 from DOM). "
|
|
29
|
+
"Use tokensafe:oumv observe before file crawls."
|
|
30
|
+
),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
_BACKEND_LINES = {
|
|
34
|
+
"fastapi": (
|
|
35
|
+
"backend fastapi/fastapi: OUMV auto-mounts when the dev server runs through "
|
|
36
|
+
"`tokensafe run-backend uvicorn <module:app> --reload` (RPC at /__oumv/rpc). "
|
|
37
|
+
"Prefer tokensafe:oumv(action='observe'|'understand'|'mutate'|'verify') over grep/curl."
|
|
38
|
+
),
|
|
39
|
+
"go": (
|
|
40
|
+
"backend {provider}/{framework}: OUMV mounts with one AutoMount line "
|
|
41
|
+
"(`tokensafe inject --status` shows it; `tokensafe inject --revert` removes it). "
|
|
42
|
+
"Use tokensafe:oumv for endpoints/source/impact, oumv_verify for in-process checks."
|
|
43
|
+
),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _read_permissions(workspace: str) -> Dict[str, Any]:
|
|
48
|
+
path = os.path.join(workspace, ".tokensafe", "oumv.json")
|
|
49
|
+
try:
|
|
50
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
51
|
+
return json.load(f).get("permissions", {}) or {}
|
|
52
|
+
except Exception:
|
|
53
|
+
return {}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
|
|
57
|
+
"""Exact next command(s) when an adapter is missing — no guessing."""
|
|
58
|
+
hints: List[str] = []
|
|
59
|
+
try:
|
|
60
|
+
from src.retrofit import run_doctor
|
|
61
|
+
doctor = run_doctor(workspace)
|
|
62
|
+
except Exception:
|
|
63
|
+
return hints
|
|
64
|
+
|
|
65
|
+
readiness = doctor.get("adapter_readiness") or {}
|
|
66
|
+
for profile, item in readiness.items():
|
|
67
|
+
if item.get("ready"):
|
|
68
|
+
continue
|
|
69
|
+
if profile == "frontend":
|
|
70
|
+
hints.append("activate frontend: run `tokensafe dev` (installs nothing into the repo)")
|
|
71
|
+
elif item.get("provider") == "fastapi":
|
|
72
|
+
hints.append('activate backend: `pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"` then run the server via `tokensafe run-backend ...`')
|
|
73
|
+
elif item.get("provider") == "go":
|
|
74
|
+
hints.append(
|
|
75
|
+
"activate backend: `go get github.com/tokensafe-dev/tokensafe-backend/go@v0.4.3` "
|
|
76
|
+
"then `tokensafe inject` (one line, reversible)"
|
|
77
|
+
)
|
|
78
|
+
if not hints and not readiness:
|
|
79
|
+
hints.append("run `tokensafe inject --status` for the exact wiring plan")
|
|
80
|
+
return hints
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def build_workspace_brief(
|
|
84
|
+
workspace: Optional[str] = None,
|
|
85
|
+
include_live: bool = False,
|
|
86
|
+
max_chars: int = MAX_BRIEF_CHARS,
|
|
87
|
+
) -> str:
|
|
88
|
+
"""Builds the compact routing brief. Returns "" for non-project directories."""
|
|
89
|
+
if not workspace or not os.path.isdir(workspace):
|
|
90
|
+
return ""
|
|
91
|
+
try:
|
|
92
|
+
from src.paths import is_project_root
|
|
93
|
+
if not is_project_root(workspace):
|
|
94
|
+
return ""
|
|
95
|
+
except Exception:
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
from src.retrofit import detect_project_stack
|
|
100
|
+
stack = detect_project_stack(workspace)
|
|
101
|
+
except Exception:
|
|
102
|
+
return ""
|
|
103
|
+
|
|
104
|
+
frontend = stack.get("frontend") or {}
|
|
105
|
+
backend = stack.get("backend") or {}
|
|
106
|
+
if not frontend and not backend:
|
|
107
|
+
return ""
|
|
108
|
+
|
|
109
|
+
lines: List[str] = ["[TokenSafe OUMV routing brief]"]
|
|
110
|
+
for entry in (frontend, backend):
|
|
111
|
+
if not entry:
|
|
112
|
+
continue
|
|
113
|
+
provider = str(entry.get("provider") or "")
|
|
114
|
+
framework = str(entry.get("framework") or "")
|
|
115
|
+
template = _FRONTEND_LINES.get(provider) if entry is frontend else _BACKEND_LINES.get(provider)
|
|
116
|
+
if template:
|
|
117
|
+
lines.append("- " + template.format(provider=provider, framework=framework))
|
|
118
|
+
else:
|
|
119
|
+
lines.append(
|
|
120
|
+
f"- {provider}/{framework}: OUMV has no adapter yet — use "
|
|
121
|
+
"tokensafe:repo_map / scoped_search / smart_read_file instead of oumv."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
permissions = _read_permissions(workspace)
|
|
125
|
+
if permissions:
|
|
126
|
+
mutate = permissions.get("mutate", True)
|
|
127
|
+
lines.append(
|
|
128
|
+
"- mutations: "
|
|
129
|
+
+ ("enabled with guardrails (OCC version, path jail, syntax pre-flight, backups)"
|
|
130
|
+
if mutate else "disabled by .tokensafe/oumv.json (permissions.mutate=false)")
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
if include_live:
|
|
134
|
+
try:
|
|
135
|
+
from src.oumv_gateway import OUMVGateway
|
|
136
|
+
status = OUMVGateway.status(workspace_dir=workspace)
|
|
137
|
+
live = []
|
|
138
|
+
for profile in ("frontend", "backend"):
|
|
139
|
+
item = status.get(profile) or {}
|
|
140
|
+
if item.get("url") or item.get("status") in ("OK", "LIVE"):
|
|
141
|
+
live.append(f"{profile}={item.get('url') or item.get('name', 'live')}")
|
|
142
|
+
if live:
|
|
143
|
+
lines.append("- live runtimes: " + ", ".join(live) + " — inspect/verify via OUMV first")
|
|
144
|
+
except Exception:
|
|
145
|
+
pass
|
|
146
|
+
|
|
147
|
+
hints = _activation(workspace, stack)
|
|
148
|
+
if hints:
|
|
149
|
+
lines.append("- " + "; ".join(hints))
|
|
150
|
+
|
|
151
|
+
brief = "\n".join(lines)
|
|
152
|
+
if len(brief) > max_chars:
|
|
153
|
+
brief = brief[: max_chars - 1].rstrip() + "…"
|
|
154
|
+
return brief
|