tokensafe 4.15.1 → 4.16.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/.claude-plugin/hooks.json +124 -0
- package/.claude-plugin/marketplace.json +15 -0
- package/.claude-plugin/plugin.json +21 -0
- package/.codex-plugin/plugin.json +1 -1
- package/.mcp.json +10 -0
- package/README.md +14 -0
- package/bin/tokensafe-acp.js +38 -0
- package/bin/tokensafe-claude-hook +18 -0
- package/bin/tokensafe-mcp +17 -0
- package/hooks/claude_code_hook.py +85 -0
- package/hooks/kimi_hook.py +27 -0
- package/hooks/post_tool_use.py +10 -0
- package/hooks/pre_invocation.py +45 -6
- package/hooks/pre_tool_use.py +22 -1
- package/hooks/session_start.py +21 -0
- package/kimi.plugin.json +1 -1
- package/package.json +7 -2
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +151 -1
- package/src/agent_firewall.py +2 -1
- package/src/angular_cli.py +189 -0
- package/src/auto_inject.py +36 -2
- package/src/backend_release.py +1 -1
- package/src/batch_editor.py +181 -24
- package/src/bench/driver.py +54 -6
- package/src/bench/runner.py +58 -8
- package/src/build_parsers.py +35 -2
- package/src/burn_monitor.py +69 -1
- package/src/cache_normalizer.py +1 -1
- package/src/cli.py +203 -2
- package/src/command_sanitizer.py +39 -11
- package/src/compaction_recovery.py +335 -0
- package/src/dashboard.py +26 -0
- package/src/delegation.py +253 -0
- package/src/format_invariants.py +158 -0
- package/src/format_parsers/game_assets.py +259 -0
- package/src/fts_index.py +1 -1
- package/src/governor.py +54 -8
- package/src/graph_engine.py +48 -0
- package/src/host_capabilities.py +180 -0
- package/src/installer.py +40 -6
- package/src/mcp_server.py +463 -45
- package/src/metrics.py +180 -3
- package/src/session_brief.py +1 -1
- package/src/skeletonizer.py +51 -0
- package/src/statusline.py +44 -0
- package/src/telemetry_sync.py +1 -1
- package/src/transcript_recall.py +565 -0
- package/src/usage_ledger.py +346 -0
- package/src/version_checker.py +1 -1
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
{
|
|
2
|
+
"description": "TokenSafe lifecycle hooks (plugin-relative launcher)",
|
|
3
|
+
"hooks": {
|
|
4
|
+
"SessionStart": [
|
|
5
|
+
{
|
|
6
|
+
"hooks": [
|
|
7
|
+
{
|
|
8
|
+
"type": "command",
|
|
9
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
10
|
+
"timeout": 10
|
|
11
|
+
}
|
|
12
|
+
]
|
|
13
|
+
}
|
|
14
|
+
],
|
|
15
|
+
"UserPromptSubmit": [
|
|
16
|
+
{
|
|
17
|
+
"hooks": [
|
|
18
|
+
{
|
|
19
|
+
"type": "command",
|
|
20
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
21
|
+
"timeout": 10
|
|
22
|
+
}
|
|
23
|
+
]
|
|
24
|
+
}
|
|
25
|
+
],
|
|
26
|
+
"PreToolUse": [
|
|
27
|
+
{
|
|
28
|
+
"matcher": "Bash",
|
|
29
|
+
"hooks": [
|
|
30
|
+
{
|
|
31
|
+
"type": "command",
|
|
32
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
33
|
+
"timeout": 10
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"matcher": "Write",
|
|
39
|
+
"hooks": [
|
|
40
|
+
{
|
|
41
|
+
"type": "command",
|
|
42
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
43
|
+
"timeout": 10
|
|
44
|
+
}
|
|
45
|
+
]
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"matcher": "Edit|MultiEdit",
|
|
49
|
+
"hooks": [
|
|
50
|
+
{
|
|
51
|
+
"type": "command",
|
|
52
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
53
|
+
"timeout": 10
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"matcher": "Read",
|
|
59
|
+
"hooks": [
|
|
60
|
+
{
|
|
61
|
+
"type": "command",
|
|
62
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
63
|
+
"timeout": 10
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
}
|
|
67
|
+
],
|
|
68
|
+
"PostToolUse": [
|
|
69
|
+
{
|
|
70
|
+
"matcher": "Bash",
|
|
71
|
+
"hooks": [
|
|
72
|
+
{
|
|
73
|
+
"type": "command",
|
|
74
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
75
|
+
"timeout": 10
|
|
76
|
+
}
|
|
77
|
+
]
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
"matcher": "Read|Edit|MultiEdit|Write",
|
|
81
|
+
"hooks": [
|
|
82
|
+
{
|
|
83
|
+
"type": "command",
|
|
84
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
85
|
+
"timeout": 10
|
|
86
|
+
}
|
|
87
|
+
]
|
|
88
|
+
}
|
|
89
|
+
],
|
|
90
|
+
"PreCompact": [
|
|
91
|
+
{
|
|
92
|
+
"hooks": [
|
|
93
|
+
{
|
|
94
|
+
"type": "command",
|
|
95
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
96
|
+
"timeout": 10
|
|
97
|
+
}
|
|
98
|
+
]
|
|
99
|
+
}
|
|
100
|
+
],
|
|
101
|
+
"PostCompact": [
|
|
102
|
+
{
|
|
103
|
+
"hooks": [
|
|
104
|
+
{
|
|
105
|
+
"type": "command",
|
|
106
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
107
|
+
"timeout": 10
|
|
108
|
+
}
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
],
|
|
112
|
+
"Stop": [
|
|
113
|
+
{
|
|
114
|
+
"hooks": [
|
|
115
|
+
{
|
|
116
|
+
"type": "command",
|
|
117
|
+
"command": "sh \"${CLAUDE_PLUGIN_ROOT}/bin/tokensafe-claude-hook\"",
|
|
118
|
+
"timeout": 15
|
|
119
|
+
}
|
|
120
|
+
]
|
|
121
|
+
}
|
|
122
|
+
]
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "tokensafe",
|
|
3
|
+
"owner": {
|
|
4
|
+
"name": "TokenSafe",
|
|
5
|
+
"url": "https://tokensafe.dev"
|
|
6
|
+
},
|
|
7
|
+
"plugins": [
|
|
8
|
+
{
|
|
9
|
+
"name": "tokensafe",
|
|
10
|
+
"source": "./",
|
|
11
|
+
"description": "Enforced context optimization for Claude Code: blocking guards, PostToolUse output compaction, symbol/AST slicing, post-compaction recovery, and measured savings.",
|
|
12
|
+
"version": "4.16.0"
|
|
13
|
+
}
|
|
14
|
+
]
|
|
15
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "tokensafe",
|
|
3
|
+
"version": "4.16.0",
|
|
4
|
+
"description": "Local runtime firewall and zero-loss context optimizer for AI coding agents: enforced tool-output compaction, symbol/AST slicing, post-compaction recovery, and measured savings.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "TokenSafe",
|
|
7
|
+
"url": "https://tokensafe.dev"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://tokensafe.dev",
|
|
10
|
+
"repository": "https://github.com/tokensafe-dev/tokensafe",
|
|
11
|
+
"license": "Apache-2.0",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"tokens",
|
|
14
|
+
"context",
|
|
15
|
+
"compaction",
|
|
16
|
+
"mcp",
|
|
17
|
+
"claude-code"
|
|
18
|
+
],
|
|
19
|
+
"hooks": "./.claude-plugin/hooks.json",
|
|
20
|
+
"mcpServers": "./.mcp.json"
|
|
21
|
+
}
|
package/.mcp.json
ADDED
package/README.md
CHANGED
|
@@ -211,6 +211,20 @@ Why TokenSafe agents ship working code on the first pass without burning quotas
|
|
|
211
211
|
|
|
212
212
|
Deeper mechanics (language matrix, AST syntax trees, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
|
|
213
213
|
|
|
214
|
+
## Context survival, recall, and host coverage
|
|
215
|
+
|
|
216
|
+
Compaction is the most expensive event in a long session: the host rewrites the prompt, re-bills it uncached, and drops turns the task still depends on. TokenSafe now survives it explicitly.
|
|
217
|
+
|
|
218
|
+
| Feature | Surface | What it does |
|
|
219
|
+
|---|---|---|
|
|
220
|
+
| **Post-compaction recovery** | Claude Code `PreCompact` / `PostCompact`; fallback detector on every host with a transcript | Reinjects a small digest: goal, last state, next focus, and up to five ranked pointers to the turns the compaction dropped. Each pointer expands with `tokensafe recall --id <session>:<index>`. |
|
|
221
|
+
| **Transcript recall** | CLI `tokensafe recall '<query>' [--sessions this\|project\|all]`, MCP `session_context(action='recall_transcript')` | BM25F search over prior Claude/Codex/Kimi/ZCode/Cursor/Antigravity transcripts. No index copy; snippets are secret-redacted and output is budget-capped. |
|
|
222
|
+
| **Zero-token statusline** | Claude Code | `tokensafe statusline` renders today's measured savings in the host status bar. The line never enters the conversation. |
|
|
223
|
+
| **Claude Code plugin** | `/plugin marketplace add <owner>/tokensafe` then `/plugin install tokensafe@tokensafe` | Marketplace manifest, nine lifecycle hooks (including compact events), and an MCP entry. The plugin fails open if the Python engine is absent. |
|
|
224
|
+
| **Host capability matrix** | `tokensafe doctor` | States exactly which host supports hooks, compact events, context injection, statusline, and transcript parsing, so partial coverage is never sold as full. |
|
|
225
|
+
|
|
226
|
+
Only hosts with a context-injection surface receive hook-injected digests (Claude Code, ZCode, Kimi Code, Antigravity). Cursor, Codex, Claude Desktop, Windsurf, Cline/Roo, and Copilot get the MCP tools, rules, transcript recall, and the fallback compaction detector; their host contracts expose no equivalent injection point today.
|
|
227
|
+
|
|
214
228
|
## What happens on the first prompt
|
|
215
229
|
|
|
216
230
|
You install TokenSafe, open a project in your agent, and the first turn does the wiring:
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* ACP (Agent Client Protocol) entry point for editors that spawn a Node command.
|
|
5
|
+
*
|
|
6
|
+
* The protocol server itself is Python (src/acp/server.py): it owns the session
|
|
7
|
+
* kernel, the tool guard and the permission prompts. This shim exists only so an
|
|
8
|
+
* editor config can name a Node executable — it reuses the main launcher's
|
|
9
|
+
* runtime resolution (system CPython, ~/.tokensafe/venv, then the pinned managed
|
|
10
|
+
* runtime) and forwards stdio unchanged, so JSON-RPC never passes through JS.
|
|
11
|
+
*
|
|
12
|
+
* tokensafe acp --print-command # prints: node "/abs/path/bin/tokensafe-acp.js"
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const { spawn } = require('child_process');
|
|
16
|
+
const path = require('path');
|
|
17
|
+
|
|
18
|
+
const ROOT_DIR = path.resolve(__dirname, '..');
|
|
19
|
+
const launcher = path.join(__dirname, 'tokensafe.js');
|
|
20
|
+
|
|
21
|
+
const child = spawn(process.execPath, [launcher, 'acp', ...process.argv.slice(2)], {
|
|
22
|
+
stdio: 'inherit',
|
|
23
|
+
cwd: ROOT_DIR,
|
|
24
|
+
env: process.env,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
child.on('error', (err) => {
|
|
28
|
+
console.error(`❌ TokenSafe ACP: failed to start the engine: ${err.message}`);
|
|
29
|
+
process.exit(1);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
child.on('exit', (code, signal) => {
|
|
33
|
+
if (signal) {
|
|
34
|
+
process.kill(process.pid, signal);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
process.exit(code === null ? 1 : code);
|
|
38
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Claude Code plugin hook launcher.
|
|
3
|
+
# Fail-open: when the Python engine is missing, emit an empty hook response so
|
|
4
|
+
# the host session continues untouched.
|
|
5
|
+
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." 2>/dev/null && pwd) || { printf '{}\n'; exit 0; }
|
|
6
|
+
PY="${TOKENSAFE_PYTHON:-}"
|
|
7
|
+
if [ -z "$PY" ]; then
|
|
8
|
+
if [ -x "$HOME/.tokensafe/venv/bin/python3" ]; then
|
|
9
|
+
PY="$HOME/.tokensafe/venv/bin/python3"
|
|
10
|
+
else
|
|
11
|
+
PY="python3"
|
|
12
|
+
fi
|
|
13
|
+
fi
|
|
14
|
+
if ! command -v "$PY" >/dev/null 2>&1; then
|
|
15
|
+
printf '{}\n'
|
|
16
|
+
exit 0
|
|
17
|
+
fi
|
|
18
|
+
exec "$PY" "$ROOT/hooks/claude_code_hook.py"
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Claude Code plugin MCP launcher (stdio).
|
|
3
|
+
# Requires the Python engine; exits with a clear message instead of a traceback.
|
|
4
|
+
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." 2>/dev/null && pwd) || exit 1
|
|
5
|
+
PY="${TOKENSAFE_PYTHON:-}"
|
|
6
|
+
if [ -z "$PY" ]; then
|
|
7
|
+
if [ -x "$HOME/.tokensafe/venv/bin/python3" ]; then
|
|
8
|
+
PY="$HOME/.tokensafe/venv/bin/python3"
|
|
9
|
+
else
|
|
10
|
+
PY="python3"
|
|
11
|
+
fi
|
|
12
|
+
fi
|
|
13
|
+
if ! command -v "$PY" >/dev/null 2>&1; then
|
|
14
|
+
echo "tokensafe: python3 not found; install TokenSafe with 'tokensafe install' or curl -fsSL https://tokensafe.dev/install.sh | bash" >&2
|
|
15
|
+
exit 1
|
|
16
|
+
fi
|
|
17
|
+
PYTHONPATH="$ROOT${PYTHONPATH:+:$PYTHONPATH}" exec "$PY" "$ROOT/src/mcp_server.py"
|
|
@@ -29,6 +29,37 @@ AGENT = "claude_code"
|
|
|
29
29
|
|
|
30
30
|
def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
31
31
|
session_id = str(payload.get("session_id") or "") or f"hook_{agent}"
|
|
32
|
+
transcript_path = str(payload.get("transcript_path") or "")
|
|
33
|
+
|
|
34
|
+
if event == "PreCompact":
|
|
35
|
+
# Arm the one-shot digest while the pre-compaction turns still exist.
|
|
36
|
+
try:
|
|
37
|
+
from src.transcript_recall import remember_session
|
|
38
|
+
from src.compaction_recovery import mark_pending
|
|
39
|
+
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
40
|
+
mark_pending(session_id, transcript_path, agent=agent, reason=str(payload.get("trigger") or "pre_compact"))
|
|
41
|
+
except Exception:
|
|
42
|
+
pass
|
|
43
|
+
return {}
|
|
44
|
+
|
|
45
|
+
if event == "PostCompact":
|
|
46
|
+
# The host already rewrote the prompt; hand the model the pointers it
|
|
47
|
+
# would otherwise reconstruct by re-reading files.
|
|
48
|
+
try:
|
|
49
|
+
from src.transcript_recall import remember_session
|
|
50
|
+
from src.compaction_recovery import consume_digest
|
|
51
|
+
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
52
|
+
digest = consume_digest(session_id, transcript_path, agent)
|
|
53
|
+
if digest:
|
|
54
|
+
return {
|
|
55
|
+
"hookSpecificOutput": {
|
|
56
|
+
"hookEventName": "PostCompact",
|
|
57
|
+
"additionalContext": digest,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
except Exception:
|
|
61
|
+
pass
|
|
62
|
+
return {}
|
|
32
63
|
|
|
33
64
|
if event == "SessionStart":
|
|
34
65
|
# One-shot session injection (mirrors the Antigravity SessionStart
|
|
@@ -116,6 +147,22 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
116
147
|
extra = f"{extra}\n\n{cum_banner}"
|
|
117
148
|
except Exception:
|
|
118
149
|
pass
|
|
150
|
+
# Compaction survival: remember where this session's transcript lives,
|
|
151
|
+
# sweep abandoned markers, and inject the one-shot recovery digest when
|
|
152
|
+
# the host starts a session from a compaction (or a fallback detector
|
|
153
|
+
# armed a marker on the previous Stop).
|
|
154
|
+
try:
|
|
155
|
+
from src.transcript_recall import remember_session
|
|
156
|
+
from src.compaction_recovery import sweep_stale, mark_pending, consume_digest
|
|
157
|
+
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
158
|
+
sweep_stale()
|
|
159
|
+
if str(payload.get("source") or "").strip().lower() == "compact":
|
|
160
|
+
mark_pending(session_id, transcript_path, agent=agent, reason="session_start_compact")
|
|
161
|
+
digest = consume_digest(session_id, transcript_path, agent)
|
|
162
|
+
if digest:
|
|
163
|
+
extra = f"{extra}\n\n{digest}"
|
|
164
|
+
except Exception:
|
|
165
|
+
pass
|
|
119
166
|
return {
|
|
120
167
|
"hookSpecificOutput": {
|
|
121
168
|
"hookEventName": "SessionStart",
|
|
@@ -214,6 +261,28 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
214
261
|
except Exception:
|
|
215
262
|
pass
|
|
216
263
|
|
|
264
|
+
# Delegated task digest: the child already read these files (one injection
|
|
265
|
+
# per delegation; the digest file is consumed on read).
|
|
266
|
+
try:
|
|
267
|
+
from src.delegation import render as _render_delegation, take as _take_delegation
|
|
268
|
+
_delegated = _take_delegation(session_id)
|
|
269
|
+
if _delegated:
|
|
270
|
+
parts.append(_render_delegation(_delegated))
|
|
271
|
+
except Exception:
|
|
272
|
+
pass
|
|
273
|
+
|
|
274
|
+
# One-shot post-compaction recovery (PreCompact/PostCompact marker or a
|
|
275
|
+
# fallback detection on the previous Stop).
|
|
276
|
+
try:
|
|
277
|
+
from src.transcript_recall import remember_session
|
|
278
|
+
from src.compaction_recovery import consume_digest
|
|
279
|
+
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
280
|
+
digest = consume_digest(session_id, transcript_path, agent)
|
|
281
|
+
if digest:
|
|
282
|
+
parts.append(digest)
|
|
283
|
+
except Exception:
|
|
284
|
+
pass
|
|
285
|
+
|
|
217
286
|
if parts:
|
|
218
287
|
return {
|
|
219
288
|
"hookSpecificOutput": {
|
|
@@ -273,6 +342,14 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
273
342
|
FileState.record_seen(track_fp)
|
|
274
343
|
except Exception:
|
|
275
344
|
pass
|
|
345
|
+
# A delegated task returned: fold the child's rollout into a digest for the
|
|
346
|
+
# next turn instead of letting the orchestrator re-read its files.
|
|
347
|
+
try:
|
|
348
|
+
from src.delegation import is_agent_tool, record_from_hook
|
|
349
|
+
if is_agent_tool(tool):
|
|
350
|
+
record_from_hook(payload)
|
|
351
|
+
except Exception:
|
|
352
|
+
pass
|
|
276
353
|
return {}
|
|
277
354
|
|
|
278
355
|
if event == "Stop":
|
|
@@ -302,6 +379,14 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
302
379
|
)
|
|
303
380
|
except Exception:
|
|
304
381
|
pass
|
|
382
|
+
# Output usage ledger: incremental offset read, provider-reported only.
|
|
383
|
+
try:
|
|
384
|
+
usage_tp = str(payload.get("transcript_path") or "")
|
|
385
|
+
if usage_tp and session_id:
|
|
386
|
+
from src.usage_ledger import update_from_transcript
|
|
387
|
+
update_from_transcript(usage_tp, agent=agent, session_id=session_id)
|
|
388
|
+
except Exception:
|
|
389
|
+
pass
|
|
305
390
|
return {}
|
|
306
391
|
|
|
307
392
|
return {}
|
package/hooks/kimi_hook.py
CHANGED
|
@@ -33,6 +33,12 @@ AGENT = "kimi_code"
|
|
|
33
33
|
def handle(event: str, payload: dict) -> dict:
|
|
34
34
|
session_id = str(payload.get("session_id") or "") or f"hook_{AGENT}"
|
|
35
35
|
|
|
36
|
+
if event in ("PreCompact", "PostCompact"):
|
|
37
|
+
# Kimi speaks the Claude Code hook contract; reuse the shared handler so
|
|
38
|
+
# compaction survival stays single-sourced.
|
|
39
|
+
from hooks.claude_code_hook import handle as _cc_handle
|
|
40
|
+
return _cc_handle(event, payload, agent=AGENT)
|
|
41
|
+
|
|
36
42
|
if event == "SessionStart":
|
|
37
43
|
extra = TOKENSAFE_DIRECTIVES
|
|
38
44
|
try:
|
|
@@ -92,6 +98,16 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
92
98
|
extra = f"{extra}\n\n{cum_banner}"
|
|
93
99
|
except Exception:
|
|
94
100
|
pass
|
|
101
|
+
try:
|
|
102
|
+
from src.transcript_recall import remember_session
|
|
103
|
+
from src.compaction_recovery import consume_digest
|
|
104
|
+
_tp = str(payload.get("transcript_path") or "")
|
|
105
|
+
remember_session(session_id, _tp, agent=AGENT, cwd=str(payload.get("cwd") or ""))
|
|
106
|
+
digest = consume_digest(session_id, _tp, AGENT)
|
|
107
|
+
if digest:
|
|
108
|
+
extra = f"{extra}\n\n{digest}"
|
|
109
|
+
except Exception:
|
|
110
|
+
pass
|
|
95
111
|
return {
|
|
96
112
|
"hookSpecificOutput": {
|
|
97
113
|
"hookEventName": "SessionStart",
|
|
@@ -150,6 +166,17 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
150
166
|
except Exception:
|
|
151
167
|
pass
|
|
152
168
|
|
|
169
|
+
try:
|
|
170
|
+
from src.transcript_recall import remember_session
|
|
171
|
+
from src.compaction_recovery import consume_digest
|
|
172
|
+
_tp = str(payload.get("transcript_path") or "")
|
|
173
|
+
remember_session(session_id, _tp, agent=AGENT, cwd=str(payload.get("cwd") or ""))
|
|
174
|
+
digest = consume_digest(session_id, _tp, AGENT)
|
|
175
|
+
if digest:
|
|
176
|
+
parts.append(digest)
|
|
177
|
+
except Exception:
|
|
178
|
+
pass
|
|
179
|
+
|
|
153
180
|
if parts:
|
|
154
181
|
return {
|
|
155
182
|
"hookSpecificOutput": {
|
package/hooks/post_tool_use.py
CHANGED
|
@@ -65,6 +65,16 @@ def main():
|
|
|
65
65
|
from src.file_state import FileState
|
|
66
66
|
FileState.record_seen(tracked_path)
|
|
67
67
|
|
|
68
|
+
# A delegated task returned: fold the child's own rollout into a digest
|
|
69
|
+
# for the next turn instead of letting the orchestrator re-read its
|
|
70
|
+
# files (the largest measured leak in the burn audit).
|
|
71
|
+
try:
|
|
72
|
+
from src.delegation import is_agent_tool, record_from_hook
|
|
73
|
+
if is_agent_tool(tool_name):
|
|
74
|
+
record_from_hook(payload)
|
|
75
|
+
except Exception:
|
|
76
|
+
pass
|
|
77
|
+
|
|
68
78
|
# Anti-Stuck Failure Tracking: record command or test failure
|
|
69
79
|
if tool_name in ("run_command", "Bash", "ExecuteCommand", "terminal"):
|
|
70
80
|
tool_res = (
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -262,13 +262,16 @@ def _handle(payload: dict) -> dict:
|
|
|
262
262
|
try:
|
|
263
263
|
budget = kernel.estimate_budget(
|
|
264
264
|
tracker, session_id=conversation_id,
|
|
265
|
-
model=_model_name(payload),
|
|
265
|
+
model=_model_name(payload) or resolve_event_model(transcript_path, conversation_id),
|
|
266
266
|
history_tokens=history_mass,
|
|
267
267
|
transcript_path=transcript_path
|
|
268
268
|
)
|
|
269
|
-
|
|
269
|
+
# The warning follows the fold budget (min(70% of the window, ceiling)),
|
|
270
|
+
# not the window percentage: on a 1M window 80% is 800k of paid context.
|
|
271
|
+
budget_pct = budget.get("budget_pct")
|
|
270
272
|
if (budget.get("measurement") == "measured"
|
|
271
|
-
and
|
|
273
|
+
and budget_pct is not None
|
|
274
|
+
and budget.get("threshold") in ("warning", "critical")):
|
|
272
275
|
already = recent_events.get("BUDGET_WARNING")
|
|
273
276
|
if not already:
|
|
274
277
|
if transcript_path:
|
|
@@ -278,8 +281,9 @@ def _handle(payload: dict) -> dict:
|
|
|
278
281
|
action = budget["recommendation"]
|
|
279
282
|
token_count = budget.get("used_tokens") or budget.get("used_estimated") or 0
|
|
280
283
|
warn = (
|
|
281
|
-
f"🧠 **Context Budget:** ~{
|
|
282
|
-
f"({token_count:,}/{budget['window_tokens']:,}
|
|
284
|
+
f"🧠 **Context Budget:** ~{budget_pct}% of the fold budget measured "
|
|
285
|
+
f"({token_count:,}/{budget.get('effective_limit_tokens', budget['window_tokens']):,} tokens; "
|
|
286
|
+
f"window {budget['window_tokens']:,}). {action}"
|
|
283
287
|
)
|
|
284
288
|
inject_steps.append({
|
|
285
289
|
"systemMessage": {
|
|
@@ -292,7 +296,9 @@ def _handle(payload: dict) -> dict:
|
|
|
292
296
|
event_type="BUDGET_WARNING",
|
|
293
297
|
original_tokens=0,
|
|
294
298
|
optimized_tokens=0,
|
|
295
|
-
details={"used_pct": used_pct, "
|
|
299
|
+
details={"used_pct": budget.get("used_pct"), "budget_pct": budget_pct,
|
|
300
|
+
"effective_limit": budget.get("effective_limit_tokens"),
|
|
301
|
+
"window": budget["window_tokens"],
|
|
296
302
|
"measurement": budget.get("measurement")}
|
|
297
303
|
)
|
|
298
304
|
except Exception:
|
|
@@ -325,6 +331,20 @@ def _handle(payload: dict) -> dict:
|
|
|
325
331
|
except Exception:
|
|
326
332
|
pass
|
|
327
333
|
|
|
334
|
+
# 5.6 Delegated result digest: consume once per delegation.
|
|
335
|
+
try:
|
|
336
|
+
from src.delegation import render as _render_delegation, take as _take_delegation
|
|
337
|
+
_delegated = _take_delegation(conversation_id)
|
|
338
|
+
if _delegated:
|
|
339
|
+
inject_steps.append({
|
|
340
|
+
"systemMessage": {
|
|
341
|
+
"systemMessage": "",
|
|
342
|
+
"metadata": {"user_markdown": _render_delegation(_delegated)}
|
|
343
|
+
}
|
|
344
|
+
})
|
|
345
|
+
except Exception:
|
|
346
|
+
pass
|
|
347
|
+
|
|
328
348
|
# 6. Multi-Agent Live Burn Monitor (rate-limited, only fires on real burn spikes)
|
|
329
349
|
if invocation_num >= 2 or transcript_path:
|
|
330
350
|
try:
|
|
@@ -344,6 +364,25 @@ def _handle(payload: dict) -> dict:
|
|
|
344
364
|
except Exception:
|
|
345
365
|
pass
|
|
346
366
|
|
|
367
|
+
# 6.5 Compaction survival: no PreCompact event on this host, so the marker
|
|
368
|
+
# comes from the usage-ledger fallback on the previous Stop.
|
|
369
|
+
try:
|
|
370
|
+
from src.transcript_recall import remember_session
|
|
371
|
+
from src.compaction_recovery import consume_digest
|
|
372
|
+
remember_session(conversation_id, transcript_path, agent="antigravity", cwd=hook_cwd)
|
|
373
|
+
_digest = consume_digest(conversation_id, transcript_path, "antigravity")
|
|
374
|
+
if _digest:
|
|
375
|
+
inject_steps.append({
|
|
376
|
+
"systemMessage": {
|
|
377
|
+
"systemMessage": _digest,
|
|
378
|
+
"metadata": {
|
|
379
|
+
"user_markdown": "♻️ **TokenSafe**: restored the context the last compaction dropped."
|
|
380
|
+
},
|
|
381
|
+
}
|
|
382
|
+
})
|
|
383
|
+
except Exception:
|
|
384
|
+
pass
|
|
385
|
+
|
|
347
386
|
return {"injectSteps": inject_steps} if inject_steps else {}
|
|
348
387
|
|
|
349
388
|
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -99,7 +99,14 @@ def _handle(payload: dict) -> dict:
|
|
|
99
99
|
|
|
100
100
|
# Search/list/other tools only ever answer "allow"; quota checks and event
|
|
101
101
|
# recording are skipped for them. The guarded set is read/write/edit/bash.
|
|
102
|
-
if canon_tool not in ("read", "write", "edit", "bash"):
|
|
102
|
+
if canon_tool not in ("read", "write", "edit", "bash", "batch_edit"):
|
|
103
|
+
return response
|
|
104
|
+
|
|
105
|
+
if canon_tool == "batch_edit":
|
|
106
|
+
from src.adapter_core import guard_batch_payload
|
|
107
|
+
verdict = guard_batch_payload(args, "antigravity", conversation_id)
|
|
108
|
+
if verdict["decision"] == "deny":
|
|
109
|
+
return {"decision": "deny", "reason": verdict["reason"]}
|
|
103
110
|
return response
|
|
104
111
|
|
|
105
112
|
tracker = MetricsTracker()
|
|
@@ -142,6 +149,20 @@ def _handle(payload: dict) -> dict:
|
|
|
142
149
|
except Exception:
|
|
143
150
|
pass
|
|
144
151
|
|
|
152
|
+
# 1.6 Edit-rewrite guard: an Edit that re-emits most of a file costs the
|
|
153
|
+
# same as a wholesale Write. Ask, never deny. Kill switch:
|
|
154
|
+
# TOKENSAFE_EDIT_REWRITE_GUARD=0.
|
|
155
|
+
if canon_tool == "edit":
|
|
156
|
+
try:
|
|
157
|
+
from src.adapter_core import guard_edit_rewrite
|
|
158
|
+
raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or args.get("file_path") or "")
|
|
159
|
+
verdict = guard_edit_rewrite(_resolve_hook_path(raw_path, hook_cwd), args, "antigravity", conversation_id)
|
|
160
|
+
if verdict["decision"] == "ask":
|
|
161
|
+
_trigger_bg_sync()
|
|
162
|
+
return {"decision": "force_ask", "reason": verdict["reason"]}
|
|
163
|
+
except Exception:
|
|
164
|
+
pass
|
|
165
|
+
|
|
145
166
|
# 2. TokenSafe Guard: Inspect file writes and edits for security violations
|
|
146
167
|
if canon_tool in ("write", "edit"):
|
|
147
168
|
from src.guard import TokenSafeGuard
|
package/hooks/session_start.py
CHANGED
|
@@ -216,6 +216,27 @@ def main():
|
|
|
216
216
|
except Exception:
|
|
217
217
|
pass
|
|
218
218
|
|
|
219
|
+
# Compaction survival (the host has no PreCompact/PostCompact event, so the
|
|
220
|
+
# marker comes from the usage-ledger fallback on the previous Stop).
|
|
221
|
+
try:
|
|
222
|
+
from src.transcript_recall import remember_session
|
|
223
|
+
from src.compaction_recovery import consume_digest
|
|
224
|
+
_sid = str(payload.get("conversationId") or "")
|
|
225
|
+
_tp = str(payload.get("transcriptPath") or "")
|
|
226
|
+
remember_session(_sid, _tp, agent="antigravity", cwd=workspace_root)
|
|
227
|
+
_digest = consume_digest(_sid, _tp, "antigravity")
|
|
228
|
+
if _digest:
|
|
229
|
+
inject_steps.append({
|
|
230
|
+
"systemMessage": {
|
|
231
|
+
"systemMessage": _digest,
|
|
232
|
+
"metadata": {
|
|
233
|
+
"user_markdown": "♻️ **TokenSafe**: restored the context the last compaction dropped."
|
|
234
|
+
},
|
|
235
|
+
}
|
|
236
|
+
})
|
|
237
|
+
except Exception:
|
|
238
|
+
pass
|
|
239
|
+
|
|
219
240
|
print(json.dumps({"injectSteps": inject_steps}))
|
|
220
241
|
|
|
221
242
|
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.16.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": "Apache-2.0",
|
package/package.json
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.16.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": {
|
|
8
|
-
"tokensafe": "bin/tokensafe.js"
|
|
8
|
+
"tokensafe": "bin/tokensafe.js",
|
|
9
|
+
"tokensafe-acp": "bin/tokensafe-acp.js"
|
|
9
10
|
},
|
|
10
11
|
"files": [
|
|
11
12
|
"bin/tokensafe.js",
|
|
12
13
|
"bin/tokensafe",
|
|
14
|
+
"bin/tokensafe-claude-hook",
|
|
15
|
+
"bin/tokensafe-mcp",
|
|
13
16
|
"bin/agy-tokens",
|
|
14
17
|
"bin/python-runtime.json",
|
|
15
18
|
"src/",
|
|
@@ -28,6 +31,8 @@
|
|
|
28
31
|
"extensions/",
|
|
29
32
|
"assets/",
|
|
30
33
|
".codex-plugin/",
|
|
34
|
+
".claude-plugin/",
|
|
35
|
+
".mcp.json",
|
|
31
36
|
"plugin.json",
|
|
32
37
|
"kimi.plugin.json",
|
|
33
38
|
"server.json",
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.16.1",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"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.",
|
|
7
7
|
"logo": "assets/logo.png",
|