tokensafe 4.6.0 → 4.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/src/batch_editor.py +174 -48
- package/src/batch_search.py +124 -26
- package/src/mcp_server.py +144 -65
- package/src/snapshot.py +98 -27
- package/src/telemetry_sync.py +1 -1
- package/src/transcript_analyzer.py +59 -36
- package/src/version_checker.py +1 -1
package/src/snapshot.py
CHANGED
|
@@ -1,22 +1,29 @@
|
|
|
1
1
|
"""
|
|
2
2
|
TokenSafe Workspace Snapshot Generator (v3.5.0).
|
|
3
3
|
|
|
4
|
-
Produces a deterministic, token-efficient workspace snapshot (<=1.4 KB)
|
|
5
|
-
in
|
|
6
|
-
it eliminates the cold-start exploration phase
|
|
7
|
-
waste 45+ seconds running exploratory `ls`,
|
|
4
|
+
Produces a deterministic, token-efficient workspace snapshot (<=1.4 KB) on
|
|
5
|
+
SessionStart in roughly 50-150 ms depending on repo size. Injected once as a
|
|
6
|
+
persistent systemMessage, it eliminates the cold-start exploration phase
|
|
7
|
+
(turns 1-3) where agents waste 45+ seconds running exploratory `ls`,
|
|
8
|
+
`git status`, and script lookups.
|
|
9
|
+
|
|
10
|
+
Truthfulness rules: a failed git call is reported as "unknown" (never
|
|
11
|
+
"clean"), non-existent paths are never invented, gitignored entries are
|
|
12
|
+
filtered out, and a truncated snapshot is explicitly marked as truncated.
|
|
8
13
|
"""
|
|
9
14
|
|
|
10
15
|
import os
|
|
11
16
|
import re
|
|
12
17
|
import json
|
|
13
18
|
import shutil
|
|
19
|
+
import fnmatch
|
|
14
20
|
import subprocess
|
|
15
21
|
from typing import Dict, Any, List, Optional, Set
|
|
16
22
|
|
|
17
23
|
HARDENED_GIT_BASE_ARGS = [
|
|
18
24
|
"--no-optional-locks",
|
|
19
25
|
"-c", "core.fsmonitor=false",
|
|
26
|
+
"-c", "core.quotePath=false",
|
|
20
27
|
"-c", "diff.external=",
|
|
21
28
|
"-c", "gpg.program=false",
|
|
22
29
|
"--no-pager"
|
|
@@ -58,8 +65,27 @@ def _is_system_or_home_root(p: str) -> bool:
|
|
|
58
65
|
return False
|
|
59
66
|
|
|
60
67
|
|
|
61
|
-
def
|
|
62
|
-
"""Extracts
|
|
68
|
+
def _parse_porcelain_paths(status_raw: str, limit: int = 6) -> List[str]:
|
|
69
|
+
"""Extracts display paths from `git status --porcelain=v1` output.
|
|
70
|
+
|
|
71
|
+
Porcelain v1 is "XY <path>": the 2 status columns are fixed-width, so the
|
|
72
|
+
line must not be stripped before slicing (that shifted every path by two
|
|
73
|
+
characters and reported e.g. " M src/a.py" as "rc/a.py").
|
|
74
|
+
"""
|
|
75
|
+
paths: List[str] = []
|
|
76
|
+
status_lines = [l for l in status_raw.splitlines() if l.strip()]
|
|
77
|
+
for line in status_lines[:limit]:
|
|
78
|
+
path = line[3:].strip() if len(line) > 3 else line.strip()
|
|
79
|
+
if " -> " in path: # renames: "R old -> new"
|
|
80
|
+
path = path.split(" -> ", 1)[1]
|
|
81
|
+
if len(path) >= 2 and path.startswith('"') and path.endswith('"'):
|
|
82
|
+
path = path[1:-1]
|
|
83
|
+
paths.append(path)
|
|
84
|
+
return paths
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _get_git_summary(workspace_dir: str, timeout_sec: float = 2.0) -> Optional[str]:
|
|
88
|
+
"""Extracts git branch, working tree status, and last 3 commits (bounded, truthful)."""
|
|
63
89
|
git_bin = shutil.which("git")
|
|
64
90
|
if not git_bin:
|
|
65
91
|
return None
|
|
@@ -68,42 +94,48 @@ def _get_git_summary(workspace_dir: str, timeout_sec: float = 0.5) -> Optional[s
|
|
|
68
94
|
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
69
95
|
env["GIT_PAGER"] = "cat"
|
|
70
96
|
|
|
71
|
-
def _run_git(args: List[str]) -> Optional[str]:
|
|
97
|
+
def _run_git(args: List[str], optional_locks: bool = True) -> Optional[str]:
|
|
98
|
+
# --no-optional-locks blocks the index refresh shortcut, which makes
|
|
99
|
+
# `git status` far slower on large trees; allow locks where it matters.
|
|
100
|
+
base_args = HARDENED_GIT_BASE_ARGS if optional_locks else [
|
|
101
|
+
a for a in HARDENED_GIT_BASE_ARGS if a != "--no-optional-locks"
|
|
102
|
+
]
|
|
72
103
|
try:
|
|
73
104
|
res = subprocess.run(
|
|
74
|
-
[git_bin, *
|
|
105
|
+
[git_bin, *base_args, *args],
|
|
75
106
|
cwd=workspace_dir,
|
|
107
|
+
stdin=subprocess.DEVNULL,
|
|
76
108
|
stdout=subprocess.PIPE,
|
|
77
109
|
stderr=subprocess.PIPE,
|
|
78
110
|
text=True,
|
|
79
111
|
timeout=timeout_sec,
|
|
80
112
|
env=env
|
|
81
113
|
)
|
|
82
|
-
return res.stdout
|
|
114
|
+
return res.stdout if res.returncode == 0 else None
|
|
83
115
|
except Exception:
|
|
84
116
|
return None
|
|
85
117
|
|
|
86
118
|
branch = _run_git(["rev-parse", "--abbrev-ref", "HEAD"])
|
|
87
119
|
if not branch:
|
|
88
120
|
return None
|
|
121
|
+
branch = branch.strip()
|
|
89
122
|
|
|
90
|
-
status_raw = _run_git(["status", "--porcelain=v1"])
|
|
91
|
-
log_raw = _run_git(["log", "-n", "3", "--format=%h %s"])
|
|
123
|
+
status_raw = _run_git(["status", "--porcelain=v1"], optional_locks=False)
|
|
124
|
+
log_raw = _run_git(["log", "-n", "3", "--format=%h %s"])
|
|
92
125
|
|
|
93
126
|
parts = [f"Git: branch `{branch}`"]
|
|
94
127
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
parts.append("Working tree: clean")
|
|
128
|
+
if status_raw is None:
|
|
129
|
+
# A failed/timed-out status must never be reported as a clean tree.
|
|
130
|
+
parts.append("Working tree: unknown (git status unavailable)")
|
|
99
131
|
else:
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
file_items
|
|
105
|
-
|
|
106
|
-
|
|
132
|
+
total = len([l for l in status_raw.splitlines() if l.strip()])
|
|
133
|
+
if total == 0:
|
|
134
|
+
parts.append("Working tree: clean")
|
|
135
|
+
else:
|
|
136
|
+
file_items = _parse_porcelain_paths(status_raw)
|
|
137
|
+
more = f" (+{total - len(file_items)} more)" if total > len(file_items) else ""
|
|
138
|
+
parts.append(f"Working tree: {total} modified ({', '.join(file_items)}{more})")
|
|
107
139
|
|
|
108
140
|
# Recent commits
|
|
109
141
|
if log_raw:
|
|
@@ -115,12 +147,39 @@ def _get_git_summary(workspace_dir: str, timeout_sec: float = 0.5) -> Optional[s
|
|
|
115
147
|
|
|
116
148
|
|
|
117
149
|
def _get_layout_summary(workspace_dir: str, max_depth: int = 2) -> Optional[str]:
|
|
118
|
-
"""Generates a compact 2-level directory tree without noise."""
|
|
150
|
+
"""Generates a compact 2-level directory tree without noise or gitignored paths."""
|
|
119
151
|
try:
|
|
120
152
|
entries = sorted(os.listdir(workspace_dir))
|
|
121
153
|
except Exception:
|
|
122
154
|
return None
|
|
123
155
|
|
|
156
|
+
# Reuse the guard's .gitignore parser instead of injecting ignored/generated
|
|
157
|
+
# directories (build output, local dumps) into the system prompt. The guard's
|
|
158
|
+
# own matcher drops the trailing slash from "dir/" patterns via relpath, so
|
|
159
|
+
# directory matching is done here.
|
|
160
|
+
is_ignored = None
|
|
161
|
+
try:
|
|
162
|
+
from src.guard import TokenSafeGuard
|
|
163
|
+
patterns = TokenSafeGuard._load_gitignore_patterns(workspace_dir)
|
|
164
|
+
|
|
165
|
+
def is_ignored(p: str) -> bool: # type: ignore[misc]
|
|
166
|
+
rel = os.path.relpath(p, workspace_dir).replace("\\", "/")
|
|
167
|
+
name = os.path.basename(p)
|
|
168
|
+
is_dir = os.path.isdir(p)
|
|
169
|
+
for pat in patterns:
|
|
170
|
+
if pat.endswith("/"):
|
|
171
|
+
base = pat.rstrip("/")
|
|
172
|
+
if is_dir and (rel == base or rel.startswith(base + "/")):
|
|
173
|
+
return True
|
|
174
|
+
continue
|
|
175
|
+
if fnmatch.fnmatch(name, pat) or fnmatch.fnmatch(rel, pat):
|
|
176
|
+
return True
|
|
177
|
+
if "/" not in pat and (rel == pat or rel.startswith(pat + "/")):
|
|
178
|
+
return True
|
|
179
|
+
return False
|
|
180
|
+
except Exception:
|
|
181
|
+
is_ignored = None
|
|
182
|
+
|
|
124
183
|
top_dirs = []
|
|
125
184
|
top_files = []
|
|
126
185
|
|
|
@@ -128,6 +187,8 @@ def _get_layout_summary(workspace_dir: str, max_depth: int = 2) -> Optional[str]
|
|
|
128
187
|
if name.startswith(".") or name in SKIP_SNAPSHOT_DIRS:
|
|
129
188
|
continue
|
|
130
189
|
full_p = os.path.join(workspace_dir, name)
|
|
190
|
+
if is_ignored is not None and is_ignored(full_p):
|
|
191
|
+
continue
|
|
131
192
|
if os.path.isdir(full_p):
|
|
132
193
|
top_dirs.append(name)
|
|
133
194
|
elif os.path.isfile(full_p):
|
|
@@ -144,7 +205,11 @@ def _get_layout_summary(workspace_dir: str, max_depth: int = 2) -> Optional[str]
|
|
|
144
205
|
continue
|
|
145
206
|
try:
|
|
146
207
|
sub = sorted(os.listdir(d_path))
|
|
147
|
-
sub_files = [
|
|
208
|
+
sub_files = [
|
|
209
|
+
s for s in sub
|
|
210
|
+
if not s.startswith(".") and s not in SKIP_SNAPSHOT_DIRS
|
|
211
|
+
and not (is_ignored is not None and is_ignored(os.path.join(d_path, s)))
|
|
212
|
+
][:6]
|
|
148
213
|
has_more = len(sub) > len(sub_files)
|
|
149
214
|
more_str = f" +{len(sub) - len(sub_files)}" if has_more else ""
|
|
150
215
|
lines.append(f" {d}/ ({', '.join(sub_files)}{more_str})")
|
|
@@ -244,6 +309,12 @@ def build_workspace_snapshot(workspace_dir: str, max_bytes: int = 1400) -> Optio
|
|
|
244
309
|
if len(combined_bytes) <= max_bytes:
|
|
245
310
|
return combined
|
|
246
311
|
|
|
247
|
-
# Safe truncation
|
|
248
|
-
truncated
|
|
249
|
-
|
|
312
|
+
# Safe truncation: cut at the last newline that fits AND mark it, so a
|
|
313
|
+
# truncated snapshot never masquerades as a complete one.
|
|
314
|
+
marker = "\n… (truncated)"
|
|
315
|
+
budget = max_bytes - len(marker.encode("utf-8"))
|
|
316
|
+
truncated = combined_bytes[:budget].decode("utf-8", errors="ignore")
|
|
317
|
+
cut = truncated.rfind("\n")
|
|
318
|
+
if cut > 0:
|
|
319
|
+
truncated = truncated[:cut]
|
|
320
|
+
return truncated.rstrip() + marker
|
package/src/telemetry_sync.py
CHANGED
|
@@ -249,7 +249,7 @@ class TelemetrySync:
|
|
|
249
249
|
current_last_id = last_id
|
|
250
250
|
headers = {
|
|
251
251
|
"Content-Type": "application/json",
|
|
252
|
-
"User-Agent": "TokenSafe-Sync/4.6.
|
|
252
|
+
"User-Agent": "TokenSafe-Sync/4.6.1"
|
|
253
253
|
}
|
|
254
254
|
if active_key:
|
|
255
255
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -98,10 +98,9 @@ def discover_transcript_paths(
|
|
|
98
98
|
if ag in ("auto", "zcode", "z.ai"):
|
|
99
99
|
_add_glob("zcode", os.path.join(home, ".zcode", "cli", "rollout", "model-io-*.jsonl"))
|
|
100
100
|
|
|
101
|
-
# 3. Claude Code transcripts
|
|
101
|
+
# 3. Claude Code transcripts (subagent rollouts live in <uuid>/subagents/)
|
|
102
102
|
if ag in ("auto", "claude", "claude_code"):
|
|
103
|
-
_add_glob("claude", os.path.join(home, ".claude", "projects", "
|
|
104
|
-
_add_glob("claude", os.path.join(home, ".claude", "projects", "*", "*.jsonl"))
|
|
103
|
+
_add_glob("claude", os.path.join(home, ".claude", "projects", "**", "*.jsonl"), recursive=True)
|
|
105
104
|
_add_glob("claude", os.path.join(home, ".claude", "sessions", "*.jsonl"))
|
|
106
105
|
|
|
107
106
|
# 4. Codex transcripts
|
|
@@ -136,9 +135,9 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
136
135
|
return {"error": f"File not found: {file_path}"}
|
|
137
136
|
|
|
138
137
|
detected_agent = agent_type
|
|
139
|
-
if detected_agent in ("auto", "
|
|
138
|
+
if detected_agent in ("auto", ""):
|
|
140
139
|
p_agent = _detect_agent_from_path(file_path)
|
|
141
|
-
detected_agent = p_agent if p_agent != "auto" else "
|
|
140
|
+
detected_agent = p_agent if p_agent != "auto" else "unknown"
|
|
142
141
|
|
|
143
142
|
total_lines = 0
|
|
144
143
|
llm_turns = 0
|
|
@@ -146,6 +145,8 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
146
145
|
tool_counts: Dict[str, int] = {}
|
|
147
146
|
disk_spills = 0
|
|
148
147
|
tokensafe_calls = 0
|
|
148
|
+
schema_matched = False
|
|
149
|
+
seen_claude_messages = set()
|
|
149
150
|
|
|
150
151
|
timestamps: List[datetime.datetime] = []
|
|
151
152
|
long_turn_gaps = 0
|
|
@@ -195,7 +196,8 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
195
196
|
|
|
196
197
|
# ZCode model-io schema
|
|
197
198
|
if step.get("type") == "model_io" or ("request" in step and "response" in step and "model" in step):
|
|
198
|
-
|
|
199
|
+
schema_matched = True
|
|
200
|
+
if detected_agent in ("antigravity", "unknown"):
|
|
199
201
|
detected_agent = "zcode"
|
|
200
202
|
llm_turns += 1
|
|
201
203
|
_track_ts(_parse_iso_ts(step.get("startedAt") or step.get("completedAt")))
|
|
@@ -253,27 +255,36 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
253
255
|
# Claude Code / Kimi JSONL schema
|
|
254
256
|
msg = step.get("message") if isinstance(step.get("message"), dict) else None
|
|
255
257
|
if msg is not None:
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
if
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
if
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
258
|
+
schema_matched = True
|
|
259
|
+
# Claude Code writes one JSONL line per content block, all sharing
|
|
260
|
+
# the same message.id and repeating the identical usage object.
|
|
261
|
+
# Count the turn and its tokens once per message id.
|
|
262
|
+
msg_key = str(msg.get("id") or step.get("uuid") or "")
|
|
263
|
+
first_sighting = not msg_key or msg_key not in seen_claude_messages
|
|
264
|
+
if msg_key:
|
|
265
|
+
seen_claude_messages.add(msg_key)
|
|
266
|
+
if first_sighting:
|
|
267
|
+
_track_ts(_parse_iso_ts(step.get("timestamp") or step.get("created_at")))
|
|
268
|
+
m_id = str(msg.get("model") or step.get("model") or "")
|
|
269
|
+
if m_id:
|
|
270
|
+
if prev_model and m_id != prev_model:
|
|
271
|
+
model_switches += 1
|
|
272
|
+
prev_model = m_id
|
|
273
|
+
if msg.get("role") == "assistant" or step.get("type") == "assistant":
|
|
274
|
+
llm_turns += 1
|
|
275
|
+
u = msg.get("usage")
|
|
276
|
+
if isinstance(u, dict):
|
|
277
|
+
raw_in = int(u.get("input_tokens") or 0)
|
|
278
|
+
cr = int(u.get("cache_read_input_tokens") or 0)
|
|
279
|
+
cw = int(u.get("cache_creation_input_tokens") or 0)
|
|
280
|
+
out_t = int(u.get("output_tokens") or 0)
|
|
281
|
+
tot_in = raw_in + cr + cw
|
|
282
|
+
if tot_in > 0:
|
|
283
|
+
last_in, last_cr, last_out = tot_in, cr, out_t
|
|
284
|
+
total_input += tot_in
|
|
285
|
+
total_cache_read += cr
|
|
286
|
+
total_cache_write += cw
|
|
287
|
+
total_output += out_t
|
|
277
288
|
content = msg.get("content")
|
|
278
289
|
if isinstance(content, list):
|
|
279
290
|
for blk in content:
|
|
@@ -288,9 +299,10 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
288
299
|
# Codex event schema
|
|
289
300
|
payload = step.get("payload") if isinstance(step.get("payload"), dict) else {}
|
|
290
301
|
if step.get("type") == "event_msg" and payload.get("type") == "token_count":
|
|
291
|
-
|
|
302
|
+
schema_matched = True
|
|
292
303
|
last_u = (payload.get("info") or {}).get("last_token_usage") or {}
|
|
293
|
-
if isinstance(last_u, dict):
|
|
304
|
+
if isinstance(last_u, dict) and last_u:
|
|
305
|
+
_track_ts(_parse_iso_ts(step.get("timestamp")))
|
|
294
306
|
llm_turns += 1
|
|
295
307
|
in_t = int(last_u.get("input_tokens") or 0)
|
|
296
308
|
cr = int(last_u.get("cached_input_tokens") or 0)
|
|
@@ -304,15 +316,19 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
304
316
|
|
|
305
317
|
# Antigravity schema
|
|
306
318
|
s_type = step.get("type")
|
|
307
|
-
_track_ts(_parse_iso_ts(step.get("created_at") or step.get("timestamp")))
|
|
308
319
|
tool_calls = step.get("tool_calls") or []
|
|
309
|
-
if s_type
|
|
310
|
-
|
|
320
|
+
if s_type or tool_calls or "created_at" in step:
|
|
321
|
+
schema_matched = True
|
|
322
|
+
if s_type == "PLANNER_RESPONSE" or tool_calls:
|
|
323
|
+
llm_turns += 1
|
|
324
|
+
# Timestamps only on real turns: status/heartbeat steps would
|
|
325
|
+
# otherwise fabricate "gaps" during long tool executions.
|
|
326
|
+
_track_ts(_parse_iso_ts(step.get("created_at") or step.get("timestamp")))
|
|
311
327
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
328
|
+
if isinstance(tool_calls, list):
|
|
329
|
+
for tc in tool_calls:
|
|
330
|
+
if isinstance(tc, dict):
|
|
331
|
+
_track_tool(str(tc.get("name") or tc.get("tool") or "unknown"))
|
|
316
332
|
|
|
317
333
|
content = step.get("content") or ""
|
|
318
334
|
if isinstance(content, str) and "The output was large and was saved to:" in content:
|
|
@@ -344,9 +360,16 @@ def analyze_transcript(file_path: str, agent_type: str = "antigravity") -> Dict[
|
|
|
344
360
|
"rate_limit_hits": {},
|
|
345
361
|
})
|
|
346
362
|
|
|
363
|
+
schema_warning = None
|
|
364
|
+
if not schema_matched:
|
|
365
|
+
schema_warning = "no recognized transcript schema matched; all metrics are zero"
|
|
366
|
+
if detected_agent in ("auto", "", "antigravity"):
|
|
367
|
+
detected_agent = "unknown"
|
|
368
|
+
|
|
347
369
|
return {
|
|
348
370
|
"file_path": file_path,
|
|
349
371
|
"agent": detected_agent,
|
|
372
|
+
"schema_warning": schema_warning,
|
|
350
373
|
"model": prev_model,
|
|
351
374
|
"total_steps": total_lines,
|
|
352
375
|
"llm_turns": llm_turns,
|
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.1"
|
|
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
|