tokensafe 4.4.9 → 4.5.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 +1 -1
- package/hooks/session_start.py +20 -9
- package/kimi.plugin.json +1 -1
- package/mcp_config.json +18 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +5 -2
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +10 -0
- package/src/batch_editor.py +352 -0
- package/src/batch_search.py +408 -0
- package/src/cli.py +51 -0
- package/src/graph_engine.py +202 -44
- package/src/mcp_proxy.py +13 -7
- package/src/mcp_server.py +301 -8
- package/src/oumv_gateway.py +81 -7
- package/src/snapshot.py +249 -0
- package/src/syntax_guard.py +84 -0
- package/src/telemetry_sync.py +1 -1
- package/src/transcript_analyzer.py +281 -0
- package/src/version_checker.py +1 -1
package/src/snapshot.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Workspace Snapshot Generator (v3.5.0).
|
|
3
|
+
|
|
4
|
+
Produces a deterministic, token-efficient workspace snapshot (<=1.4 KB)
|
|
5
|
+
in ~35-50 ms on SessionStart. Injected once as a persistent systemMessage,
|
|
6
|
+
it eliminates the cold-start exploration phase (turns 1-3) where agents
|
|
7
|
+
waste 45+ seconds running exploratory `ls`, `git status`, and script lookups.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import json
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
from typing import Dict, Any, List, Optional, Set
|
|
16
|
+
|
|
17
|
+
HARDENED_GIT_BASE_ARGS = [
|
|
18
|
+
"--no-optional-locks",
|
|
19
|
+
"-c", "core.fsmonitor=false",
|
|
20
|
+
"-c", "diff.external=",
|
|
21
|
+
"-c", "gpg.program=false",
|
|
22
|
+
"--no-pager"
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
SKIP_SNAPSHOT_DIRS: Set[str] = {
|
|
26
|
+
".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
|
|
27
|
+
".next", ".turbo", ".idea", ".vscode", "coverage", ".pytest_cache",
|
|
28
|
+
".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info",
|
|
29
|
+
"Library", "Applications", "Pictures", "Movies", "Music", "Downloads",
|
|
30
|
+
".cache", ".npm", ".bun", ".rustup", ".cargo", ".local", ".output", ".vite"
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
COLLAPSE_DIRS: Set[str] = {
|
|
34
|
+
"tmp", "temp", "output", "outputs", "artifacts", "logs", "coverage",
|
|
35
|
+
"playwright-report", "test-results"
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
PRIORITY_DIRS: Set[str] = {
|
|
39
|
+
"src", "app", "lib", "packages", "server", "web", "client", "api", "tests", "test", "scripts"
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _is_system_or_home_root(p: str) -> bool:
|
|
44
|
+
"""Detects if directory is system root, /home, or user home root."""
|
|
45
|
+
try:
|
|
46
|
+
resolved = os.path.realpath(p)
|
|
47
|
+
root = os.path.splitdrive(resolved)[0] + os.sep if os.name == "nt" else "/"
|
|
48
|
+
if resolved == root:
|
|
49
|
+
return True
|
|
50
|
+
home = os.path.expanduser("~")
|
|
51
|
+
if os.path.realpath(home) == resolved:
|
|
52
|
+
return True
|
|
53
|
+
parent = os.path.dirname(resolved)
|
|
54
|
+
if parent == root and os.path.basename(resolved).lower() in ("users", "home", "var", "usr", "etc"):
|
|
55
|
+
return True
|
|
56
|
+
except Exception:
|
|
57
|
+
pass
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _get_git_summary(workspace_dir: str, timeout_sec: float = 0.5) -> Optional[str]:
|
|
62
|
+
"""Extracts git branch, working tree status, and last 3 commits in <= 350 ms."""
|
|
63
|
+
git_bin = shutil.which("git")
|
|
64
|
+
if not git_bin:
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
env = os.environ.copy()
|
|
68
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
69
|
+
env["GIT_PAGER"] = "cat"
|
|
70
|
+
|
|
71
|
+
def _run_git(args: List[str]) -> Optional[str]:
|
|
72
|
+
try:
|
|
73
|
+
res = subprocess.run(
|
|
74
|
+
[git_bin, *HARDENED_GIT_BASE_ARGS, *args],
|
|
75
|
+
cwd=workspace_dir,
|
|
76
|
+
stdout=subprocess.PIPE,
|
|
77
|
+
stderr=subprocess.PIPE,
|
|
78
|
+
text=True,
|
|
79
|
+
timeout=timeout_sec,
|
|
80
|
+
env=env
|
|
81
|
+
)
|
|
82
|
+
return res.stdout.strip() if res.returncode == 0 else None
|
|
83
|
+
except Exception:
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
branch = _run_git(["rev-parse", "--abbrev-ref", "HEAD"])
|
|
87
|
+
if not branch:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
status_raw = _run_git(["status", "--porcelain=v1"]) or ""
|
|
91
|
+
log_raw = _run_git(["log", "-n", "3", "--format=%h %s"]) or ""
|
|
92
|
+
|
|
93
|
+
parts = [f"Git: branch `{branch}`"]
|
|
94
|
+
|
|
95
|
+
# Modified files
|
|
96
|
+
status_lines = [l.strip() for l in status_raw.splitlines() if l.strip()]
|
|
97
|
+
if not status_lines:
|
|
98
|
+
parts.append("Working tree: clean")
|
|
99
|
+
else:
|
|
100
|
+
file_items = []
|
|
101
|
+
for l in status_lines[:6]:
|
|
102
|
+
# e.g. " M src/index.ts" -> "src/index.ts"
|
|
103
|
+
fname = l[3:].strip() if len(l) > 3 else l
|
|
104
|
+
file_items.append(fname)
|
|
105
|
+
more = f" (+{len(status_lines) - len(file_items)} more)" if len(status_lines) > len(file_items) else ""
|
|
106
|
+
parts.append(f"Working tree: {len(status_lines)} modified ({', '.join(file_items)}{more})")
|
|
107
|
+
|
|
108
|
+
# Recent commits
|
|
109
|
+
if log_raw:
|
|
110
|
+
commit_lines = [l.strip() for l in log_raw.splitlines() if l.strip()]
|
|
111
|
+
commit_items = [f"`{l.split(' ')[0]}` {l.split(' ', 1)[1][:40]}" if ' ' in l else f"`{l}`" for l in commit_lines]
|
|
112
|
+
parts.append(f"Recent commits: {', '.join(commit_items)}")
|
|
113
|
+
|
|
114
|
+
return " | ".join(parts)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _get_layout_summary(workspace_dir: str, max_depth: int = 2) -> Optional[str]:
|
|
118
|
+
"""Generates a compact 2-level directory tree without noise."""
|
|
119
|
+
try:
|
|
120
|
+
entries = sorted(os.listdir(workspace_dir))
|
|
121
|
+
except Exception:
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
top_dirs = []
|
|
125
|
+
top_files = []
|
|
126
|
+
|
|
127
|
+
for name in entries:
|
|
128
|
+
if name.startswith(".") or name in SKIP_SNAPSHOT_DIRS:
|
|
129
|
+
continue
|
|
130
|
+
full_p = os.path.join(workspace_dir, name)
|
|
131
|
+
if os.path.isdir(full_p):
|
|
132
|
+
top_dirs.append(name)
|
|
133
|
+
elif os.path.isfile(full_p):
|
|
134
|
+
top_files.append(name)
|
|
135
|
+
|
|
136
|
+
# Sort priority directories first
|
|
137
|
+
top_dirs.sort(key=lambda d: (0 if d in PRIORITY_DIRS else (2 if d in COLLAPSE_DIRS else 1), d.lower()))
|
|
138
|
+
|
|
139
|
+
lines = ["Layout (2 levels):"]
|
|
140
|
+
for d in top_dirs[:8]:
|
|
141
|
+
d_path = os.path.join(workspace_dir, d)
|
|
142
|
+
if d in COLLAPSE_DIRS:
|
|
143
|
+
lines.append(f" {d}/ (collapsed)")
|
|
144
|
+
continue
|
|
145
|
+
try:
|
|
146
|
+
sub = sorted(os.listdir(d_path))
|
|
147
|
+
sub_files = [s for s in sub if not s.startswith(".") and s not in SKIP_SNAPSHOT_DIRS][:6]
|
|
148
|
+
has_more = len(sub) > len(sub_files)
|
|
149
|
+
more_str = f" +{len(sub) - len(sub_files)}" if has_more else ""
|
|
150
|
+
lines.append(f" {d}/ ({', '.join(sub_files)}{more_str})")
|
|
151
|
+
except Exception:
|
|
152
|
+
lines.append(f" {d}/")
|
|
153
|
+
|
|
154
|
+
if top_files:
|
|
155
|
+
lines.append(f" Root files: {', '.join(top_files[:8])}")
|
|
156
|
+
|
|
157
|
+
return "\n".join(lines)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _get_scripts_summary(workspace_dir: str) -> Optional[str]:
|
|
161
|
+
"""Extracts project run/test/build scripts from package.json, Makefile, or pyproject.toml."""
|
|
162
|
+
scripts = []
|
|
163
|
+
|
|
164
|
+
# Node package.json
|
|
165
|
+
pkg_path = os.path.join(workspace_dir, "package.json")
|
|
166
|
+
if os.path.exists(pkg_path):
|
|
167
|
+
try:
|
|
168
|
+
with open(pkg_path, "r", encoding="utf-8") as f:
|
|
169
|
+
data = json.load(f)
|
|
170
|
+
pkg_scripts = data.get("scripts", {})
|
|
171
|
+
if isinstance(pkg_scripts, dict):
|
|
172
|
+
for k in ("test", "build", "typecheck", "lint", "dev", "start"):
|
|
173
|
+
if k in pkg_scripts:
|
|
174
|
+
scripts.append(f"{k} (`{pkg_scripts[k][:35]}`)")
|
|
175
|
+
except Exception:
|
|
176
|
+
pass
|
|
177
|
+
|
|
178
|
+
# Makefile
|
|
179
|
+
make_path = os.path.join(workspace_dir, "Makefile")
|
|
180
|
+
if not scripts and os.path.exists(make_path):
|
|
181
|
+
try:
|
|
182
|
+
with open(make_path, "r", encoding="utf-8", errors="replace") as f:
|
|
183
|
+
targets = []
|
|
184
|
+
for line in f:
|
|
185
|
+
m = re.match(r"^([a-zA-Z0-9_-]+):", line)
|
|
186
|
+
if m and not m.group(1).startswith("."):
|
|
187
|
+
targets.append(m.group(1))
|
|
188
|
+
if targets:
|
|
189
|
+
scripts.extend(targets[:6])
|
|
190
|
+
except Exception:
|
|
191
|
+
pass
|
|
192
|
+
|
|
193
|
+
# Python pyproject.toml
|
|
194
|
+
pyproject_path = os.path.join(workspace_dir, "pyproject.toml")
|
|
195
|
+
if os.path.exists(pyproject_path):
|
|
196
|
+
try:
|
|
197
|
+
with open(pyproject_path, "r", encoding="utf-8", errors="replace") as f:
|
|
198
|
+
text = f.read()
|
|
199
|
+
if "pytest" in text:
|
|
200
|
+
scripts.append("test (`pytest`)")
|
|
201
|
+
if "ruff" in text:
|
|
202
|
+
scripts.append("lint (`ruff check`)")
|
|
203
|
+
if "mypy" in text:
|
|
204
|
+
scripts.append("typecheck (`mypy`)")
|
|
205
|
+
except Exception:
|
|
206
|
+
pass
|
|
207
|
+
|
|
208
|
+
return f"Scripts: {', '.join(scripts)}" if scripts else None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def build_workspace_snapshot(workspace_dir: str, max_bytes: int = 1400) -> Optional[str]:
|
|
212
|
+
"""
|
|
213
|
+
Builds a high-density, sub-1.4 KB workspace snapshot in under 50 ms.
|
|
214
|
+
Returns None if workspace is system root, unreadable, or not a project directory.
|
|
215
|
+
"""
|
|
216
|
+
if not workspace_dir or not os.path.isdir(workspace_dir):
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
if _is_system_or_home_root(workspace_dir):
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
sections = ["[TokenSafe Workspace Snapshot]"]
|
|
223
|
+
|
|
224
|
+
# 1. Git summary
|
|
225
|
+
git_sum = _get_git_summary(workspace_dir)
|
|
226
|
+
if git_sum:
|
|
227
|
+
sections.append(git_sum)
|
|
228
|
+
|
|
229
|
+
# 2. Layout
|
|
230
|
+
layout_sum = _get_layout_summary(workspace_dir)
|
|
231
|
+
if layout_sum:
|
|
232
|
+
sections.append(layout_sum)
|
|
233
|
+
|
|
234
|
+
# 3. Scripts
|
|
235
|
+
scripts_sum = _get_scripts_summary(workspace_dir)
|
|
236
|
+
if scripts_sum:
|
|
237
|
+
sections.append(scripts_sum)
|
|
238
|
+
|
|
239
|
+
if len(sections) == 1:
|
|
240
|
+
return None
|
|
241
|
+
|
|
242
|
+
combined = "\n".join(sections)
|
|
243
|
+
combined_bytes = combined.encode("utf-8")
|
|
244
|
+
if len(combined_bytes) <= max_bytes:
|
|
245
|
+
return combined
|
|
246
|
+
|
|
247
|
+
# Safe truncation
|
|
248
|
+
truncated = combined_bytes[:max_bytes].decode("utf-8", errors="ignore")
|
|
249
|
+
return truncated.rsplit("\n", 1)[0]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Out-of-the-box syntax guard for OUMV direct workspace edits.
|
|
3
|
+
|
|
4
|
+
Validates replacement content BEFORE it is persisted so the agent can never
|
|
5
|
+
write syntactically broken code through the `oumv/mutate` offline fallback.
|
|
6
|
+
Runs strictly on the Python standard library; JavaScript checks shell out to
|
|
7
|
+
`node --check` when Node.js is available (best-effort, bounded timeout).
|
|
8
|
+
|
|
9
|
+
Languages without a checker are reported as "skipped" — honest reporting per
|
|
10
|
+
the OUMV spec §8 Mutation Policy (never imply a validation that did not run).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
import os
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
from typing import Dict
|
|
19
|
+
|
|
20
|
+
_NODE_TIMEOUT_SEC = 3.0
|
|
21
|
+
|
|
22
|
+
_EXT_STRATEGY = {
|
|
23
|
+
".py": "python-ast",
|
|
24
|
+
".js": "node-check",
|
|
25
|
+
".mjs": "node-check",
|
|
26
|
+
".cjs": "node-check",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check_syntax(abs_path: str, content: str) -> Dict[str, str]:
|
|
31
|
+
"""
|
|
32
|
+
Pre-flight syntax validation for a direct workspace edit.
|
|
33
|
+
|
|
34
|
+
Returns {"status": "passed"|"failed"|"skipped", "tool": str, "error": str}.
|
|
35
|
+
Never raises: a language we cannot validate is reported as "skipped".
|
|
36
|
+
"""
|
|
37
|
+
ext = os.path.splitext(abs_path)[1].lower()
|
|
38
|
+
strategy = _EXT_STRATEGY.get(ext)
|
|
39
|
+
|
|
40
|
+
if strategy == "python-ast":
|
|
41
|
+
try:
|
|
42
|
+
ast.parse(content)
|
|
43
|
+
return {"status": "passed", "tool": "python-ast"}
|
|
44
|
+
except SyntaxError as e:
|
|
45
|
+
return {"status": "failed", "tool": "python-ast", "error": f"line {e.lineno}: {e.msg}"}
|
|
46
|
+
|
|
47
|
+
if strategy == "node-check":
|
|
48
|
+
node_bin = shutil.which("node")
|
|
49
|
+
if not node_bin:
|
|
50
|
+
return {"status": "skipped", "tool": "node-check", "error": "node not found on PATH"}
|
|
51
|
+
# `node --check` requires a file: validate a temp copy so the target stays untouched.
|
|
52
|
+
tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="tokensafe_syntax_")
|
|
53
|
+
try:
|
|
54
|
+
with os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
|
|
55
|
+
f.write(content)
|
|
56
|
+
proc = subprocess.run(
|
|
57
|
+
[node_bin, "--check", tmp_path],
|
|
58
|
+
capture_output=True,
|
|
59
|
+
text=True,
|
|
60
|
+
timeout=_NODE_TIMEOUT_SEC,
|
|
61
|
+
)
|
|
62
|
+
if proc.returncode == 0:
|
|
63
|
+
return {"status": "passed", "tool": "node --check"}
|
|
64
|
+
err_lines = (proc.stderr or proc.stdout or "").strip().splitlines()
|
|
65
|
+
return {
|
|
66
|
+
"status": "failed",
|
|
67
|
+
"tool": "node --check",
|
|
68
|
+
"error": err_lines[0] if err_lines else "syntax check failed",
|
|
69
|
+
}
|
|
70
|
+
except subprocess.TimeoutExpired:
|
|
71
|
+
return {"status": "skipped", "tool": "node-check", "error": "timeout"}
|
|
72
|
+
except Exception as e: # noqa: BLE001 - guard must never raise
|
|
73
|
+
return {"status": "skipped", "tool": "node-check", "error": str(e)}
|
|
74
|
+
finally:
|
|
75
|
+
try:
|
|
76
|
+
os.unlink(tmp_path)
|
|
77
|
+
except OSError:
|
|
78
|
+
pass
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
"status": "skipped",
|
|
82
|
+
"tool": "none",
|
|
83
|
+
"error": f"no syntax checker for {ext or 'unknown extension'}",
|
|
84
|
+
}
|
package/src/telemetry_sync.py
CHANGED
|
@@ -241,7 +241,7 @@ class TelemetrySync:
|
|
|
241
241
|
current_last_id = last_id
|
|
242
242
|
headers = {
|
|
243
243
|
"Content-Type": "application/json",
|
|
244
|
-
"User-Agent": "TokenSafe-Sync/4.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.5.0"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Multi-Agent Transcript Analyzer (v3.5.0).
|
|
3
|
+
|
|
4
|
+
Inspects offline session transcripts across Google Antigravity, Claude Code,
|
|
5
|
+
Codex, Cursor, and Kimi to benchmark wall-clock latency, turn counts,
|
|
6
|
+
tool batching factors, prompt-cache decay zones, and disk spills.
|
|
7
|
+
|
|
8
|
+
Supports:
|
|
9
|
+
- Auto-discovery across local agent storage directories (~/.gemini, ~/.claude, ~/.codex).
|
|
10
|
+
- Turn & tool call decomposition.
|
|
11
|
+
- Antigravity 'output.txt' disk spill detection.
|
|
12
|
+
- Inter-turn elapsed time analysis (>60s cache-drop warning).
|
|
13
|
+
- Before vs. After A/B task comparison (--compare before.jsonl after.jsonl).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import glob
|
|
18
|
+
import json
|
|
19
|
+
import datetime
|
|
20
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _parse_iso_ts(ts_str: Optional[str]) -> Optional[datetime.datetime]:
|
|
24
|
+
if not ts_str:
|
|
25
|
+
return None
|
|
26
|
+
try:
|
|
27
|
+
# Normalize trailing Z or offsets
|
|
28
|
+
clean = ts_str.replace("Z", "+00:00")
|
|
29
|
+
return datetime.datetime.fromisoformat(clean)
|
|
30
|
+
except Exception:
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def discover_transcript_paths(
|
|
35
|
+
agent: str = "auto",
|
|
36
|
+
explicit_path: Optional[str] = None,
|
|
37
|
+
limit: int = 20
|
|
38
|
+
) -> List[Tuple[str, str, float]]:
|
|
39
|
+
"""
|
|
40
|
+
Finds transcript files sorted newest first.
|
|
41
|
+
Returns list of (agent_type, file_path, mtime).
|
|
42
|
+
"""
|
|
43
|
+
if explicit_path:
|
|
44
|
+
p = os.path.abspath(explicit_path)
|
|
45
|
+
if os.path.isfile(p):
|
|
46
|
+
return [("custom", p, os.path.getmtime(p))]
|
|
47
|
+
elif os.path.isdir(p):
|
|
48
|
+
found = []
|
|
49
|
+
for root, _, files in os.walk(p):
|
|
50
|
+
for f in files:
|
|
51
|
+
if f.endswith(".jsonl"):
|
|
52
|
+
fp = os.path.join(root, f)
|
|
53
|
+
found.append(("custom", fp, os.path.getmtime(fp)))
|
|
54
|
+
found.sort(key=lambda x: x[2], reverse=True)
|
|
55
|
+
return found[:limit]
|
|
56
|
+
|
|
57
|
+
home = os.path.expanduser("~")
|
|
58
|
+
candidates: List[Tuple[str, str, float]] = []
|
|
59
|
+
|
|
60
|
+
# 1. Google Antigravity transcripts
|
|
61
|
+
if agent in ("auto", "antigravity", "gemini"):
|
|
62
|
+
agy_patterns = [
|
|
63
|
+
os.path.join(home, ".gemini", "antigravity", "brain", "*", ".system_generated", "logs", "transcript.jsonl"),
|
|
64
|
+
os.path.join(home, ".gemini", "antigravity", "brain", "*", "transcript.jsonl"),
|
|
65
|
+
]
|
|
66
|
+
for pat in agy_patterns:
|
|
67
|
+
for fp in glob.glob(pat):
|
|
68
|
+
try:
|
|
69
|
+
candidates.append(("antigravity", fp, os.path.getmtime(fp)))
|
|
70
|
+
except Exception:
|
|
71
|
+
pass
|
|
72
|
+
|
|
73
|
+
# 2. Claude Code transcripts
|
|
74
|
+
if agent in ("auto", "claude", "claude_code"):
|
|
75
|
+
claude_pattern = os.path.join(home, ".claude", "projects", "*", "transcripts", "*.jsonl")
|
|
76
|
+
for fp in glob.glob(claude_pattern):
|
|
77
|
+
try:
|
|
78
|
+
candidates.append(("claude", fp, os.path.getmtime(fp)))
|
|
79
|
+
except Exception:
|
|
80
|
+
pass
|
|
81
|
+
claude_sess = os.path.join(home, ".claude", "sessions", "*.jsonl")
|
|
82
|
+
for fp in glob.glob(claude_sess):
|
|
83
|
+
try:
|
|
84
|
+
candidates.append(("claude", fp, os.path.getmtime(fp)))
|
|
85
|
+
except Exception:
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
# 3. Codex transcripts
|
|
89
|
+
if agent in ("auto", "codex"):
|
|
90
|
+
codex_pattern = os.path.join(home, ".codex", "sessions", "*.jsonl")
|
|
91
|
+
for fp in glob.glob(codex_pattern):
|
|
92
|
+
try:
|
|
93
|
+
candidates.append(("codex", fp, os.path.getmtime(fp)))
|
|
94
|
+
except Exception:
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
candidates.sort(key=lambda x: x[2], reverse=True)
|
|
98
|
+
return candidates[:limit]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[str, Any]:
|
|
102
|
+
"""
|
|
103
|
+
Parses a single transcript.jsonl file and extracts latency, turns, tool calls, and spills.
|
|
104
|
+
"""
|
|
105
|
+
if not os.path.isfile(file_path):
|
|
106
|
+
return {"error": f"File not found: {file_path}"}
|
|
107
|
+
|
|
108
|
+
total_lines = 0
|
|
109
|
+
llm_turns = 0
|
|
110
|
+
total_tool_calls = 0
|
|
111
|
+
tool_counts: Dict[str, int] = {}
|
|
112
|
+
disk_spills = 0
|
|
113
|
+
tokensafe_calls = 0
|
|
114
|
+
|
|
115
|
+
timestamps: List[datetime.datetime] = []
|
|
116
|
+
long_turn_gaps = 0
|
|
117
|
+
|
|
118
|
+
prev_ts: Optional[datetime.datetime] = None
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
122
|
+
for line in f:
|
|
123
|
+
line = line.strip()
|
|
124
|
+
if not line:
|
|
125
|
+
continue
|
|
126
|
+
total_lines += 1
|
|
127
|
+
try:
|
|
128
|
+
step = json.loads(line)
|
|
129
|
+
except Exception:
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
# Antigravity schema
|
|
133
|
+
s_type = step.get("type")
|
|
134
|
+
created_at = _parse_iso_ts(step.get("created_at"))
|
|
135
|
+
if created_at:
|
|
136
|
+
timestamps.append(created_at)
|
|
137
|
+
if prev_ts:
|
|
138
|
+
gap_sec = (created_at - prev_ts).total_seconds()
|
|
139
|
+
if gap_sec > 60:
|
|
140
|
+
long_turn_gaps += 1
|
|
141
|
+
prev_ts = created_at
|
|
142
|
+
|
|
143
|
+
tool_calls = step.get("tool_calls") or []
|
|
144
|
+
if s_type == "PLANNER_RESPONSE" or tool_calls:
|
|
145
|
+
llm_turns += 1
|
|
146
|
+
|
|
147
|
+
if isinstance(tool_calls, list):
|
|
148
|
+
total_tool_calls += len(tool_calls)
|
|
149
|
+
for tc in tool_calls:
|
|
150
|
+
if isinstance(tc, dict):
|
|
151
|
+
t_name = tc.get("name") or tc.get("tool") or "unknown"
|
|
152
|
+
tool_counts[t_name] = tool_counts.get(t_name, 0) + 1
|
|
153
|
+
if "tokensafe" in t_name.lower():
|
|
154
|
+
tokensafe_calls += 1
|
|
155
|
+
|
|
156
|
+
content = step.get("content") or ""
|
|
157
|
+
if isinstance(content, str) and "The output was large and was saved to:" in content:
|
|
158
|
+
disk_spills += 1
|
|
159
|
+
except Exception as e:
|
|
160
|
+
return {"error": f"Failed to parse transcript: {e}"}
|
|
161
|
+
|
|
162
|
+
duration_sec = 0.0
|
|
163
|
+
if len(timestamps) >= 2:
|
|
164
|
+
duration_sec = max(0.0, (timestamps[-1] - timestamps[0]).total_seconds())
|
|
165
|
+
|
|
166
|
+
batch_factor = round(total_tool_calls / max(1, llm_turns), 2)
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
"file_path": file_path,
|
|
170
|
+
"agent": agent_type,
|
|
171
|
+
"total_steps": total_lines,
|
|
172
|
+
"llm_turns": llm_turns,
|
|
173
|
+
"total_tool_calls": total_tool_calls,
|
|
174
|
+
"tool_batch_factor": batch_factor,
|
|
175
|
+
"tool_breakdown": tool_counts,
|
|
176
|
+
"disk_spills": disk_spills,
|
|
177
|
+
"tokensafe_calls": tokensafe_calls,
|
|
178
|
+
"long_turn_gaps_gt_60s": long_turn_gaps,
|
|
179
|
+
"duration_seconds": round(duration_sec, 1)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def compare_transcripts(before_path: str, after_path: str) -> Dict[str, Any]:
|
|
184
|
+
"""
|
|
185
|
+
Compares two transcripts (A/B testing before vs after TokenSafe optimization).
|
|
186
|
+
"""
|
|
187
|
+
a = analyze_transcript(before_path)
|
|
188
|
+
b = analyze_transcript(after_path)
|
|
189
|
+
|
|
190
|
+
if "error" in a:
|
|
191
|
+
return {"error": f"Before transcript error: {a['error']}"}
|
|
192
|
+
if "error" in b:
|
|
193
|
+
return {"error": f"After transcript error: {b['error']}"}
|
|
194
|
+
|
|
195
|
+
def _delta(k: str) -> Dict[str, Any]:
|
|
196
|
+
val_a = a.get(k, 0)
|
|
197
|
+
val_b = b.get(k, 0)
|
|
198
|
+
diff = val_b - val_a
|
|
199
|
+
pct = (diff / val_a * 100) if val_a else 0.0
|
|
200
|
+
return {"before": val_a, "after": val_b, "delta": diff, "pct": round(pct, 1)}
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
"before_file": before_path,
|
|
204
|
+
"after_file": after_path,
|
|
205
|
+
"llm_turns": _delta("llm_turns"),
|
|
206
|
+
"total_tool_calls": _delta("total_tool_calls"),
|
|
207
|
+
"tool_batch_factor": _delta("tool_batch_factor"),
|
|
208
|
+
"disk_spills": _delta("disk_spills"),
|
|
209
|
+
"long_turn_gaps_gt_60s": _delta("long_turn_gaps_gt_60s"),
|
|
210
|
+
"duration_seconds": _delta("duration_seconds")
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def render_transcripts_report(results: List[Dict[str, Any]]) -> str:
|
|
215
|
+
"""Renders formatted terminal and markdown report for a list of analyzed transcripts."""
|
|
216
|
+
if not results:
|
|
217
|
+
return "No transcripts found or analyzed."
|
|
218
|
+
|
|
219
|
+
lines = []
|
|
220
|
+
lines.append("╔══════════════════════════════════════════════════════════════════════════════════════════════╗")
|
|
221
|
+
lines.append("║ 📊 TOKENSAFE TRANSCRIPT BENCHMARK ANALYZER ║")
|
|
222
|
+
lines.append("╚══════════════════════════════════════════════════════════════════════════════════════════════╝\n")
|
|
223
|
+
|
|
224
|
+
lines.append(f"{'#':<3} | {'Agent':<12} | {'Turns':<6} | {'Tools':<6} | {'Batching':<8} | {'Spills':<6} | {'Gaps >60s':<10} | {'Duration':<10} | {'Session Path'}")
|
|
225
|
+
lines.append("-" * 96)
|
|
226
|
+
|
|
227
|
+
for i, res in enumerate(results):
|
|
228
|
+
if "error" in res:
|
|
229
|
+
lines.append(f"{i+1:<3} | Error: {res['error']}")
|
|
230
|
+
continue
|
|
231
|
+
agent = res.get("agent", "unknown")[:12]
|
|
232
|
+
turns = res.get("llm_turns", 0)
|
|
233
|
+
tools = res.get("total_tool_calls", 0)
|
|
234
|
+
batch = f"{res.get('tool_batch_factor', 0.0):.2f}x"
|
|
235
|
+
spills = res.get("disk_spills", 0)
|
|
236
|
+
gaps = res.get("long_turn_gaps_gt_60s", 0)
|
|
237
|
+
dur = f"{res.get('duration_seconds', 0.0):.0f}s"
|
|
238
|
+
parts = res.get("file_path", "").split(os.sep)
|
|
239
|
+
sess_name = parts[-4] if len(parts) >= 4 and parts[-2] == "logs" else (parts[-2] if len(parts) >= 2 else "session")
|
|
240
|
+
if len(sess_name) > 18:
|
|
241
|
+
sess_name = sess_name[:15] + "..."
|
|
242
|
+
lines.append(f"{i+1:<3} | {agent:<12} | {turns:<6} | {tools:<6} | {batch:<8} | {spills:<6} | {gaps:<10} | {dur:<10} | {sess_name}")
|
|
243
|
+
|
|
244
|
+
lines.append("")
|
|
245
|
+
return "\n".join(lines)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def render_comparison_report(comp: Dict[str, Any]) -> str:
|
|
249
|
+
"""Renders before vs after comparison."""
|
|
250
|
+
if "error" in comp:
|
|
251
|
+
return f"Comparison failed: {comp['error']}"
|
|
252
|
+
|
|
253
|
+
lines = []
|
|
254
|
+
lines.append("╔══════════════════════════════════════════════════════════════════════════════════╗")
|
|
255
|
+
lines.append("║ 🏆 TOKENSAFE TRANSCRIPT A/B COMPARISON REPORT ║")
|
|
256
|
+
lines.append("╚══════════════════════════════════════════════════════════════════════════════════╝\n")
|
|
257
|
+
lines.append(f"• Baseline: {comp['before_file']}")
|
|
258
|
+
lines.append(f"• Optimized: {comp['after_file']}\n")
|
|
259
|
+
|
|
260
|
+
headers = f"{'Metric':<26} | {'Baseline':<12} | {'TokenSafe':<12} | {'Improvement':<14}"
|
|
261
|
+
lines.append(headers)
|
|
262
|
+
lines.append("-" * len(headers))
|
|
263
|
+
|
|
264
|
+
metrics = [
|
|
265
|
+
("LLM Turns", comp["llm_turns"]),
|
|
266
|
+
("Total Tool Calls", comp["total_tool_calls"]),
|
|
267
|
+
("Tool Batch Factor", comp["tool_batch_factor"]),
|
|
268
|
+
("Disk Spills (output.txt)", comp["disk_spills"]),
|
|
269
|
+
("Turn Gaps > 60s", comp["long_turn_gaps_gt_60s"]),
|
|
270
|
+
("Duration (seconds)", comp["duration_seconds"])
|
|
271
|
+
]
|
|
272
|
+
|
|
273
|
+
for label, m in metrics:
|
|
274
|
+
b_val = m["before"]
|
|
275
|
+
a_val = m["after"]
|
|
276
|
+
pct = m["pct"]
|
|
277
|
+
pct_str = f"{pct:+.1f}%" if pct != 0 else "0.0%"
|
|
278
|
+
lines.append(f"{label:<26} | {b_val:<12} | {a_val:<12} | {pct_str:<14}")
|
|
279
|
+
|
|
280
|
+
lines.append("")
|
|
281
|
+
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.
|
|
20
|
+
CURRENT_VERSION = "4.5.0"
|
|
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
|