tokensafe 4.6.2 → 4.6.4
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/README.md +38 -5
- package/hooks/claude_code_hook.py +22 -0
- package/hooks/kimi_hook.py +20 -0
- package/hooks/pre_tool_use.py +0 -9
- package/hooks/session_start.py +16 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +57 -21
- package/src/auto_inject.py +517 -0
- package/src/batch_editor.py +36 -2
- package/src/batch_search.py +31 -5
- package/src/cli.py +152 -10
- package/src/command_sanitizer.py +92 -6
- package/src/guard.py +75 -11
- package/src/installer.py +6 -0
- package/src/mcp_server.py +84 -25
- package/src/oumv_gateway.py +168 -19
- package/src/paths.py +58 -0
- package/src/retrofit.py +219 -45
- package/src/savings.py +81 -0
- package/src/scaffold.py +190 -8
- package/src/session_brief.py +154 -0
- package/src/snapshot.py +3 -2
- package/src/telemetry_sync.py +98 -26
- package/src/transcript_analyzer.py +13 -9
- 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/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
|
package/src/snapshot.py
CHANGED
|
@@ -286,8 +286,9 @@ def build_workspace_snapshot(workspace_dir: str, max_bytes: int = 1400) -> Optio
|
|
|
286
286
|
|
|
287
287
|
sections = ["[TokenSafe Workspace Snapshot]"]
|
|
288
288
|
|
|
289
|
-
# 1. Git summary
|
|
290
|
-
|
|
289
|
+
# 1. Git summary. SessionStart blocks on this, and it issues three sequential
|
|
290
|
+
# git calls: keep the per-call budget at 0.6s (<=1.8s total), not 2s each.
|
|
291
|
+
git_sum = _get_git_summary(workspace_dir, timeout_sec=0.6)
|
|
291
292
|
if git_sum:
|
|
292
293
|
sections.append(git_sum)
|
|
293
294
|
|
package/src/telemetry_sync.py
CHANGED
|
@@ -67,6 +67,47 @@ def _sync_state_path() -> str:
|
|
|
67
67
|
return os.path.join(_data_dir(), "sync_state.json")
|
|
68
68
|
|
|
69
69
|
|
|
70
|
+
_ROLLUP_WATERMARK_KEYS = (
|
|
71
|
+
"last_synced_rollup_tokens",
|
|
72
|
+
"last_synced_rollup_orig",
|
|
73
|
+
"last_synced_rollup_usd",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _sync_meta_read(db_path: str, key: str) -> Optional[str]:
|
|
78
|
+
"""Reads a durable sync marker from the metrics DB (survives state-file loss)."""
|
|
79
|
+
try:
|
|
80
|
+
with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
|
|
81
|
+
conn.execute("PRAGMA busy_timeout=3000")
|
|
82
|
+
row = conn.execute("SELECT value FROM sync_meta WHERE key = ?", (key,)).fetchone()
|
|
83
|
+
return str(row[0]) if row and row[0] is not None else None
|
|
84
|
+
except Exception:
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _sync_meta_write(db_path: str, values: Dict[str, Any]) -> None:
|
|
89
|
+
"""Persists durable sync markers next to the events they describe (best effort)."""
|
|
90
|
+
if not values:
|
|
91
|
+
return
|
|
92
|
+
for _attempt in range(2):
|
|
93
|
+
try:
|
|
94
|
+
with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
|
|
95
|
+
# The sync loop holds a read connection open while paging.
|
|
96
|
+
conn.execute("PRAGMA busy_timeout=3000")
|
|
97
|
+
conn.execute("CREATE TABLE IF NOT EXISTS sync_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
|
98
|
+
conn.executemany(
|
|
99
|
+
"INSERT INTO sync_meta (key, value) VALUES (?, ?) "
|
|
100
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
101
|
+
[(k, str(v)) for k, v in values.items()],
|
|
102
|
+
)
|
|
103
|
+
conn.commit()
|
|
104
|
+
return
|
|
105
|
+
except sqlite3.OperationalError:
|
|
106
|
+
time.sleep(0.2)
|
|
107
|
+
except Exception:
|
|
108
|
+
return
|
|
109
|
+
|
|
110
|
+
|
|
70
111
|
def _sync_lock_path() -> str:
|
|
71
112
|
if SYNC_LOCK_PATH != _DEFAULT_SYNC_LOCK_PATH:
|
|
72
113
|
return SYNC_LOCK_PATH
|
|
@@ -93,31 +134,52 @@ class TelemetrySync:
|
|
|
93
134
|
|
|
94
135
|
@classmethod
|
|
95
136
|
def get_state(cls) -> Dict[str, Any]:
|
|
96
|
-
"""Loads sync cursor state from
|
|
137
|
+
"""Loads sync cursor state, overlaying durable watermarks from the metrics DB.
|
|
138
|
+
|
|
139
|
+
sync_state.json is easy to lose (fresh data dir, manual cleanup), and losing it
|
|
140
|
+
makes the client replay its whole lifetime rollup, which the server cannot tell
|
|
141
|
+
apart from real usage. The metrics DB survives, so the larger watermark wins.
|
|
142
|
+
"""
|
|
97
143
|
state_path = _sync_state_path()
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
144
|
+
state: Dict[str, Any] = {
|
|
145
|
+
"last_synced_event_id": 0,
|
|
146
|
+
"last_synced_at": 0,
|
|
147
|
+
"total_synced_events": 0,
|
|
148
|
+
"lifetime_rollup_synced": False,
|
|
149
|
+
}
|
|
150
|
+
if os.path.exists(state_path):
|
|
151
|
+
try:
|
|
152
|
+
with open(state_path, "r", encoding="utf-8") as f:
|
|
153
|
+
loaded = json.load(f)
|
|
154
|
+
if isinstance(loaded, dict):
|
|
155
|
+
state.update(loaded)
|
|
156
|
+
except Exception:
|
|
157
|
+
pass
|
|
158
|
+
|
|
159
|
+
db_path = _metrics_db_path()
|
|
160
|
+
durable_rollup = False
|
|
161
|
+
for key in _ROLLUP_WATERMARK_KEYS:
|
|
162
|
+
raw = _sync_meta_read(db_path, key)
|
|
163
|
+
if raw is None:
|
|
164
|
+
continue
|
|
165
|
+
try:
|
|
166
|
+
durable = float(raw) if key.endswith("_usd") else int(float(raw))
|
|
167
|
+
except (TypeError, ValueError):
|
|
168
|
+
continue
|
|
169
|
+
if durable > 0:
|
|
170
|
+
durable_rollup = True
|
|
171
|
+
current = state.get(key)
|
|
172
|
+
try:
|
|
173
|
+
current_val: Optional[float] = (
|
|
174
|
+
float(current) if key.endswith("_usd") else int(float(current))
|
|
175
|
+
) if current is not None else None
|
|
176
|
+
except (TypeError, ValueError):
|
|
177
|
+
current_val = None
|
|
178
|
+
if current_val is None or durable > current_val:
|
|
179
|
+
state[key] = durable
|
|
180
|
+
if durable_rollup:
|
|
181
|
+
state["lifetime_rollup_synced"] = True
|
|
182
|
+
return state
|
|
121
183
|
|
|
122
184
|
@classmethod
|
|
123
185
|
def save_state(cls, state: Dict[str, Any]):
|
|
@@ -249,7 +311,7 @@ class TelemetrySync:
|
|
|
249
311
|
current_last_id = last_id
|
|
250
312
|
headers = {
|
|
251
313
|
"Content-Type": "application/json",
|
|
252
|
-
"User-Agent": "TokenSafe-Sync/4.6.
|
|
314
|
+
"User-Agent": "TokenSafe-Sync/4.6.4"
|
|
253
315
|
}
|
|
254
316
|
if active_key:
|
|
255
317
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -316,7 +378,11 @@ class TelemetrySync:
|
|
|
316
378
|
"model": "aggregate",
|
|
317
379
|
"timestamp": int(time.time()),
|
|
318
380
|
# Rolled-up historical mass of mixed provenance: conservatively estimated.
|
|
319
|
-
"measurement": "estimated"
|
|
381
|
+
"measurement": "estimated",
|
|
382
|
+
# Idempotency key: the cumulative total at emit time.
|
|
383
|
+
# A replay (state loss) repeats the same key and the
|
|
384
|
+
# server collapses it; a newer total is a real delta.
|
|
385
|
+
"client_event_id": f"rollup:{current_rollup_tokens}",
|
|
320
386
|
})
|
|
321
387
|
except Exception:
|
|
322
388
|
pass
|
|
@@ -468,6 +534,12 @@ class TelemetrySync:
|
|
|
468
534
|
last_synced_rollup = current_rollup_tokens
|
|
469
535
|
last_synced_rollup_orig = current_rollup_orig
|
|
470
536
|
last_synced_rollup_usd = current_rollup_usd
|
|
537
|
+
# Durable copy: survives deletion/corruption of sync_state.json.
|
|
538
|
+
_sync_meta_write(db_path, {
|
|
539
|
+
"last_synced_rollup_tokens": last_synced_rollup,
|
|
540
|
+
"last_synced_rollup_orig": last_synced_rollup_orig,
|
|
541
|
+
"last_synced_rollup_usd": last_synced_rollup_usd,
|
|
542
|
+
})
|
|
471
543
|
cls.save_state({
|
|
472
544
|
"last_synced_event_id": current_last_id,
|
|
473
545
|
"last_synced_at": int(time.time()),
|
|
@@ -145,7 +145,9 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
145
145
|
tool_counts: Dict[str, int] = {}
|
|
146
146
|
disk_spills = 0
|
|
147
147
|
tokensafe_calls = 0
|
|
148
|
-
|
|
148
|
+
# Only branches that positively recognise a schema set this. The Antigravity
|
|
149
|
+
# catch-all matches any {"type": ...} line, so it must not count as recognition.
|
|
150
|
+
explicit_matched = False
|
|
149
151
|
seen_claude_messages = set()
|
|
150
152
|
|
|
151
153
|
timestamps: List[datetime.datetime] = []
|
|
@@ -196,7 +198,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
196
198
|
|
|
197
199
|
# ZCode model-io schema
|
|
198
200
|
if step.get("type") == "model_io" or ("request" in step and "response" in step and "model" in step):
|
|
199
|
-
|
|
201
|
+
explicit_matched = True
|
|
200
202
|
if detected_agent in ("antigravity", "unknown"):
|
|
201
203
|
detected_agent = "zcode"
|
|
202
204
|
llm_turns += 1
|
|
@@ -255,7 +257,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
255
257
|
# Claude Code / Kimi JSONL schema
|
|
256
258
|
msg = step.get("message") if isinstance(step.get("message"), dict) else None
|
|
257
259
|
if msg is not None:
|
|
258
|
-
|
|
260
|
+
explicit_matched = True
|
|
259
261
|
# Claude Code writes one JSONL line per content block, all sharing
|
|
260
262
|
# the same message.id and repeating the identical usage object.
|
|
261
263
|
# Count the turn and its tokens once per message id.
|
|
@@ -299,7 +301,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
299
301
|
# Codex event schema
|
|
300
302
|
payload = step.get("payload") if isinstance(step.get("payload"), dict) else {}
|
|
301
303
|
if step.get("type") == "event_msg" and payload.get("type") == "token_count":
|
|
302
|
-
|
|
304
|
+
explicit_matched = True
|
|
303
305
|
last_u = (payload.get("info") or {}).get("last_token_usage") or {}
|
|
304
306
|
if isinstance(last_u, dict) and last_u:
|
|
305
307
|
_track_ts(_parse_iso_ts(step.get("timestamp")))
|
|
@@ -318,8 +320,8 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
318
320
|
s_type = step.get("type")
|
|
319
321
|
tool_calls = step.get("tool_calls") or []
|
|
320
322
|
if s_type or tool_calls or "created_at" in step:
|
|
321
|
-
schema_matched = True
|
|
322
323
|
if s_type == "PLANNER_RESPONSE" or tool_calls:
|
|
324
|
+
explicit_matched = explicit_matched or s_type == "PLANNER_RESPONSE"
|
|
323
325
|
llm_turns += 1
|
|
324
326
|
# Timestamps only on real turns: status/heartbeat steps would
|
|
325
327
|
# otherwise fabricate "gaps" during long tool executions.
|
|
@@ -361,7 +363,7 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
361
363
|
})
|
|
362
364
|
|
|
363
365
|
schema_warning = None
|
|
364
|
-
if not
|
|
366
|
+
if not explicit_matched and llm_turns == 0 and total_input == 0 and total_output == 0:
|
|
365
367
|
schema_warning = "no recognized transcript schema matched; all metrics are zero"
|
|
366
368
|
if detected_agent in ("auto", "", "antigravity"):
|
|
367
369
|
detected_agent = "unknown"
|
|
@@ -398,8 +400,10 @@ def compare_transcripts(before_path: str, after_path: str) -> Dict[str, Any]:
|
|
|
398
400
|
"""
|
|
399
401
|
Compares two transcripts (A/B testing before vs after TokenSafe optimization).
|
|
400
402
|
"""
|
|
401
|
-
|
|
402
|
-
|
|
403
|
+
# "auto" lets path-based agent detection decide; the old default label
|
|
404
|
+
# ("antigravity") mislabelled every Claude/Codex/ZCode transcript.
|
|
405
|
+
a = analyze_transcript(before_path, agent_type="auto")
|
|
406
|
+
b = analyze_transcript(after_path, agent_type="auto")
|
|
403
407
|
|
|
404
408
|
if "error" in a:
|
|
405
409
|
return {"error": f"Before transcript error: {a['error']}"}
|
|
@@ -503,4 +507,4 @@ def render_comparison_report(comp: Dict[str, Any]) -> str:
|
|
|
503
507
|
lines.append(f"{label:<26} | {b_val:<12} | {a_val:<12} | {pct_str:<14}")
|
|
504
508
|
|
|
505
509
|
lines.append("")
|
|
506
|
-
return "\n".join(lines)
|
|
510
|
+
return "\n".join(lines)
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.6.
|
|
20
|
+
CURRENT_VERSION = "4.6.4"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|