tokensafe 4.3.3 → 4.4.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/post_tool_use.py +38 -0
- package/hooks/pre_invocation.py +18 -0
- package/hooks/pre_tool_use.py +56 -0
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +2 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +4 -2
- package/src/format_parsers/lockfiles.py +452 -0
- package/src/installer.py +4 -2
- package/src/mcp_server.py +107 -4
- package/src/mistakes.py +130 -9
- package/src/result_ledger.py +11 -2
- package/src/schema_slicer.py +245 -9
- package/src/team_cache.py +70 -3
- package/src/telemetry_sync.py +1 -1
- package/src/type_slicer.py +434 -0
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +255 -13
package/hooks/post_tool_use.py
CHANGED
|
@@ -63,6 +63,44 @@ def main():
|
|
|
63
63
|
if tracked_path:
|
|
64
64
|
from src.file_state import FileState
|
|
65
65
|
FileState.record_seen(tracked_path)
|
|
66
|
+
|
|
67
|
+
# Anti-Stuck Failure Tracking: record command or test failure
|
|
68
|
+
if tool_name in ("run_command", "Bash", "ExecuteCommand", "terminal"):
|
|
69
|
+
tool_res = (
|
|
70
|
+
payload.get("toolResponse")
|
|
71
|
+
or payload.get("tool_result")
|
|
72
|
+
or payload.get("result")
|
|
73
|
+
or payload.get("response")
|
|
74
|
+
or {}
|
|
75
|
+
)
|
|
76
|
+
exit_code = None
|
|
77
|
+
output_str = ""
|
|
78
|
+
if isinstance(tool_res, dict):
|
|
79
|
+
exit_code = tool_res.get("exitCode") if "exitCode" in tool_res else tool_res.get("exit_code")
|
|
80
|
+
output_str = str(tool_res.get("output") or tool_res.get("error") or tool_res.get("stderr") or "")
|
|
81
|
+
elif isinstance(tool_res, str):
|
|
82
|
+
output_str = tool_res
|
|
83
|
+
|
|
84
|
+
cmd = str(args.get("CommandLine") or args.get("command") or "")
|
|
85
|
+
is_failed = False
|
|
86
|
+
if exit_code is not None and int(exit_code) != 0:
|
|
87
|
+
is_failed = True
|
|
88
|
+
elif ("FAIL:" in output_str or "FAILED (" in output_str or "Traceback (most recent call last):" in output_str) and len(output_str) > 20:
|
|
89
|
+
is_failed = True
|
|
90
|
+
|
|
91
|
+
if is_failed and cmd:
|
|
92
|
+
try:
|
|
93
|
+
from src.mistakes import MistakesLedger
|
|
94
|
+
hook_cwd = str(payload.get("cwd") or os.getcwd())
|
|
95
|
+
summary = f"Command failed (exit {exit_code or 'err'}): {cmd[:60]}"
|
|
96
|
+
MistakesLedger.record_failure(
|
|
97
|
+
summary=summary,
|
|
98
|
+
source="command_failure",
|
|
99
|
+
details=output_str[:300],
|
|
100
|
+
project_root=hook_cwd
|
|
101
|
+
)
|
|
102
|
+
except Exception:
|
|
103
|
+
pass
|
|
66
104
|
except Exception:
|
|
67
105
|
pass
|
|
68
106
|
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -74,6 +74,8 @@ def _handle(payload: dict) -> dict:
|
|
|
74
74
|
|
|
75
75
|
tracker = MetricsTracker()
|
|
76
76
|
inject_steps = []
|
|
77
|
+
workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
|
|
78
|
+
hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
|
|
77
79
|
|
|
78
80
|
# 0. Asynchronous telemetry sync (detached & throttled to 20s)
|
|
79
81
|
try:
|
|
@@ -135,6 +137,22 @@ def _handle(payload: dict) -> dict:
|
|
|
135
137
|
}
|
|
136
138
|
})
|
|
137
139
|
|
|
140
|
+
# 2.5 Proactive Anti-Stuck Guard (Inject recent failure lessons from MistakesLedger)
|
|
141
|
+
try:
|
|
142
|
+
from src.mistakes import MistakesLedger
|
|
143
|
+
active_guard = MistakesLedger.get_guard_prompt(project_root=hook_cwd)
|
|
144
|
+
if active_guard:
|
|
145
|
+
inject_steps.append({
|
|
146
|
+
"systemMessage": {
|
|
147
|
+
"systemMessage": f"{active_guard}",
|
|
148
|
+
"metadata": {
|
|
149
|
+
"user_markdown": "🛡️ **TokenSafe Anti-Stuck Guard**: Active dead-end warnings injected to prevent repeating prior failures."
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
})
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
|
|
138
156
|
# 3. Multi-turn History Compaction (Paused when community quota is exceeded)
|
|
139
157
|
# Only inject into context on first fold or >= 1500 token delta so
|
|
140
158
|
# intermediate turns do not churn prefix tokens unnecessarily.
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -70,6 +70,11 @@ def _handle(payload: dict) -> dict:
|
|
|
70
70
|
# 1. Loop Detector Guard (Applies to all tools)
|
|
71
71
|
is_loop, repeat_count, loop_msg = LoopDetector.check_loop(conversation_id, tool_name, args)
|
|
72
72
|
if is_loop:
|
|
73
|
+
try:
|
|
74
|
+
from src.mistakes import MistakesLedger
|
|
75
|
+
MistakesLedger.record_from_loop(tool_name, args, repeat_count, project_root=hook_cwd)
|
|
76
|
+
except Exception:
|
|
77
|
+
pass
|
|
73
78
|
tracker.record_event(
|
|
74
79
|
session_id=conversation_id,
|
|
75
80
|
event_type="LOOP_GUARD",
|
|
@@ -140,6 +145,17 @@ def _handle(payload: dict) -> dict:
|
|
|
140
145
|
_trigger_bg_sync()
|
|
141
146
|
return {"decision": "deny", "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"}
|
|
142
147
|
|
|
148
|
+
# Anti-Stuck hybrid escalation check
|
|
149
|
+
try:
|
|
150
|
+
from src.mistakes import MistakesLedger
|
|
151
|
+
is_blocked, m_reason = MistakesLedger.should_force_ask(path or raw_path, action_type="edit_file", project_root=hook_cwd)
|
|
152
|
+
if is_blocked:
|
|
153
|
+
return {"decision": "force_ask", "reason": f"[TokenSafe Anti-Stuck Guard] {m_reason}"}
|
|
154
|
+
elif m_reason:
|
|
155
|
+
response["reason"] = m_reason
|
|
156
|
+
except Exception:
|
|
157
|
+
pass
|
|
158
|
+
|
|
143
159
|
# 3. Output Guard (shared guard_write, v3.0.0): deny wholesale overwrite of
|
|
144
160
|
# large existing files to enforce edit_file; ask on small-delta writes.
|
|
145
161
|
if tool_name == "write_file":
|
|
@@ -204,6 +220,35 @@ def _handle(payload: dict) -> dict:
|
|
|
204
220
|
except Exception:
|
|
205
221
|
pass
|
|
206
222
|
|
|
223
|
+
# Step 3-Lockfile: Intercept raw lockfile reads and redirect to generated summary
|
|
224
|
+
if path and os.path.exists(path):
|
|
225
|
+
try:
|
|
226
|
+
from src.format_parsers.lockfiles import LockfileReducer
|
|
227
|
+
if LockfileReducer.is_lockfile(path):
|
|
228
|
+
if start_line is None or end_line is None or (int(end_line) - int(start_line) > 50):
|
|
229
|
+
summary_path = LockfileReducer.generate_lockfile_summary(path)
|
|
230
|
+
if summary_path and os.path.exists(summary_path):
|
|
231
|
+
orig_size = os.path.getsize(path)
|
|
232
|
+
orig_t = max(orig_size // 4, 1000)
|
|
233
|
+
with open(summary_path, "r", encoding="utf-8", errors="ignore") as sf:
|
|
234
|
+
sum_t = count_tokens(sf.read())
|
|
235
|
+
saved = max(orig_t - sum_t, 500)
|
|
236
|
+
response["overwrite"] = {path_key: summary_path}
|
|
237
|
+
response["reason"] = (
|
|
238
|
+
f"Token Optimizer: Sliced lockfile to summary view (Saved ~{saved} tokens). "
|
|
239
|
+
f"Use query_dependency(lockfile_path, package_name) to look up specific packages."
|
|
240
|
+
)
|
|
241
|
+
tracker.record_event(
|
|
242
|
+
session_id=conversation_id,
|
|
243
|
+
event_type="LOCKFILE_SUMMARY",
|
|
244
|
+
original_tokens=orig_t,
|
|
245
|
+
optimized_tokens=sum_t,
|
|
246
|
+
details={"target_file": os.path.basename(path), "saved_tokens": saved}
|
|
247
|
+
)
|
|
248
|
+
return response
|
|
249
|
+
except Exception:
|
|
250
|
+
pass
|
|
251
|
+
|
|
207
252
|
# Step 3A: If model explicitly specified line range, respect it
|
|
208
253
|
if start_line is not None and end_line is not None:
|
|
209
254
|
return response
|
|
@@ -299,6 +344,17 @@ def _handle(payload: dict) -> dict:
|
|
|
299
344
|
elif guard_res.warning_only:
|
|
300
345
|
response["reason"] = f"⚠️ TokenSafe Guard Warning: {guard_res.reason}"
|
|
301
346
|
|
|
347
|
+
# Anti-Stuck hybrid escalation check
|
|
348
|
+
try:
|
|
349
|
+
from src.mistakes import MistakesLedger
|
|
350
|
+
is_blocked, m_reason = MistakesLedger.should_force_ask(cmd, action_type="command", project_root=hook_cwd)
|
|
351
|
+
if is_blocked:
|
|
352
|
+
return {"decision": "force_ask", "reason": f"[TokenSafe Anti-Stuck Guard] {m_reason}"}
|
|
353
|
+
elif m_reason:
|
|
354
|
+
response["reason"] = m_reason
|
|
355
|
+
except Exception:
|
|
356
|
+
pass
|
|
357
|
+
|
|
302
358
|
if is_quota_exceeded:
|
|
303
359
|
# Free tier quota reached: skip Pro diff/command optimization while Security Guards remain active
|
|
304
360
|
if LicenseManager.should_emit_quota_banner(tracker, conversation_id, every_n_turns=5) and quota.get("warning"):
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.4.1",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.4.1",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.4.1",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "assets/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/rules/AGENTS.md
CHANGED
|
@@ -41,7 +41,8 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
41
41
|
11. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage and Context Quality Score (Grade S-F). When it reports `warning`, `critical`, or Grade C/F, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (Active Goal, Last State, Next Focus) before continuing.
|
|
42
42
|
12. **Vision Image Optimization (`optimize_image`)**: When handling screenshots or visual diagrams, call `tokensafe:optimize_image` or run `tokensafe optimize-image <file>` to downscale images exceeding 1024px (-50-75% vision tokens) while preserving original disk files.
|
|
43
43
|
13. **Superseded Output Pruning (`prune_superseded`)**: In long multi-turn sessions, prune obsolete intermediate file reads via `tokensafe:prune_superseded(transcript_path)` to free up context without losing history.
|
|
44
|
-
14. **Anti-Stuck Revert Memory (`get_mistakes`)**: Consult `tokensafe:get_mistakes` to retrieve persistent records of prior dead-ends, loop guard trips, and git reverts to avoid attempting previously failed solutions.
|
|
44
|
+
14. **Anti-Stuck Revert Memory (`get_mistakes`) & Hybrid Escalation**: Consult `tokensafe:get_mistakes` to retrieve persistent records of prior dead-ends, loop guard trips, and git reverts to avoid attempting previously failed solutions. The 2-tier hybrid escalation policy issues a soft advisory warning for 1-2 failures and triggers `force_ask` if an identical action or command fails >2 times within 30 minutes, automatically broadcasting scrubbed failure summaries to the team.
|
|
45
|
+
15. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.
|
|
45
46
|
|
|
46
47
|
### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
|
|
47
48
|
At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.
|
|
6
|
+
"version": "4.4.1",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.
|
|
26
|
+
"version": "4.4.1",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.
|
|
42
|
+
"version": "4.4.1",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -80,8 +80,10 @@ Quick pointers:
|
|
|
80
80
|
|
|
81
81
|
- Search: `tokensafe:scoped_search(query, path=".", scope="code")` — safe keyword & symbol search, never raw grep.
|
|
82
82
|
- Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps. Auto-slices lockfiles, CSV/TSV, SQL dumps.
|
|
83
|
+
- External Types: `tokensafe:slice_external_type(package_name, type_name)` — extracts 3rd-party TypeScript definitions from `node_modules` without file crawling (-95% tokens, L1/L2/L3 synced).
|
|
84
|
+
- Query Dependencies: `tokensafe:query_dependency(lockfile_path, package_name)` — point lookups in npm/bun/pnpm/cargo/poetry lockfiles in <50 tokens.
|
|
83
85
|
- Expand Stash: `tokensafe:expand_ref(hash)` — restore full raw content of any folded block by its 8-char hash (e.g. 'a1b2c3d4').
|
|
84
|
-
- Web Reading: `tokensafe:read_web_page(url)` — fetch documentation/articles as clean Markdown without HTML/script junk.
|
|
86
|
+
- Web Reading: `tokensafe:read_web_page(url, force_refresh=false)` — fetch documentation/articles as clean Markdown without HTML/script junk, backed by 3-tier L1/L2/L3 team cache.
|
|
85
87
|
- Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` — 3-8 related symbols across files in one call, shared imports deduplicated.
|
|
86
88
|
- Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
|
|
87
89
|
- Directory: `tokensafe:list_dir(path, depth=2)` — clean tree, never verbose `ls -la`.
|
|
@@ -89,7 +91,7 @@ Quick pointers:
|
|
|
89
91
|
- Context: `tokensafe:compact_conversation(transcript_path)` / `tokensafe:context_budget`.
|
|
90
92
|
- Vision: `tokensafe:optimize_image(image_path, max_edge=1024)` — downscale images >1024px (-50-75% vision tokens).
|
|
91
93
|
- Prune Reads: `tokensafe:prune_superseded(transcript_path)` — drops obsolete intermediate file reads (-30-40% context).
|
|
92
|
-
- Anti-Stuck: `tokensafe:get_mistakes(project_root)` — persistent memory of prior dead-ends and git reverts.
|
|
94
|
+
- Anti-Stuck: `tokensafe:get_mistakes(project_root)` — persistent memory of prior dead-ends and git reverts, backed by 2-tier hybrid escalation (>2 identical failures in 30m = `force_ask`, else advisory) and team broadcast.
|
|
93
95
|
|
|
94
96
|
---
|
|
95
97
|
|