tokensafe 4.16.3 → 5.0.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/bin/agy-tokens +1 -1
- package/bin/tokensafe +1 -1
- package/bin/tokensafe-acp.js +1 -1
- package/bin/tokensafe-mcp +1 -1
- package/bin/tokensafe.js +1 -1
- package/hooks/claude_code_hook.py +49 -45
- package/hooks/cursor_hook.py +8 -8
- package/hooks/kimi_hook.py +23 -23
- package/hooks/post_tool_use.py +6 -6
- package/hooks/pre_invocation.py +21 -17
- package/hooks/pre_tool_use.py +27 -27
- package/hooks/session_start.py +17 -17
- package/hooks/stop_hook.py +3 -3
- package/hooks/zcode_hook.py +2 -2
- package/kimi.plugin.json +2 -2
- package/mcp_config.json +1 -1
- package/package.json +5 -4
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/__init__.py +9 -5
- package/src/cli.py +11 -2487
- package/src/mcp_server.py +11 -5437
- package/src/proxy.py +11 -1834
- package/tokensafe/__init__.py +6 -0
- package/{src → tokensafe}/acp/__init__.py +2 -2
- package/{src → tokensafe}/acp/server.py +5 -5
- package/{src → tokensafe}/adapter_core.py +21 -18
- package/{src → tokensafe}/agent/__init__.py +1 -1
- package/{src → tokensafe}/agent/context.py +4 -4
- package/{src → tokensafe}/agent/loop.py +4 -4
- package/{src → tokensafe}/agent/providers.py +2 -2
- package/{src → tokensafe}/agent/tools.py +2 -2
- package/{src → tokensafe}/agent_firewall.py +51 -10
- package/{src → tokensafe}/angular_cli.py +4 -4
- package/{src → tokensafe}/auto_inject.py +37 -5
- package/{src → tokensafe}/batch_editor.py +185 -28
- package/tokensafe/batch_search.py +1191 -0
- package/{src → tokensafe}/bench/go_target.py +1 -1
- package/{src → tokensafe}/bench/mechanics.py +1 -1
- package/{src → tokensafe}/bench/react_target.py +1 -1
- package/{src → tokensafe}/bench/runner.py +4 -4
- package/{src → tokensafe}/benchmark.py +12 -12
- package/{src → tokensafe}/benchmark_real.py +18 -18
- package/{src → tokensafe}/build_parsers.py +3 -3
- package/{src → tokensafe}/bundle_probe.py +1 -1
- package/{src → tokensafe}/burn_monitor.py +3 -3
- package/{src → tokensafe}/cache_normalizer.py +1 -1
- package/tokensafe/cli.py +2490 -0
- package/{src → tokensafe}/command_sanitizer.py +94 -26
- package/{src → tokensafe}/compaction_recovery.py +5 -5
- package/{src → tokensafe}/compactor.py +148 -95
- package/{src → tokensafe}/context_index.py +194 -28
- package/{src → tokensafe}/cross_stack.py +2 -2
- package/{src → tokensafe}/dashboard.py +3 -3
- package/{src → tokensafe}/delegation.py +4 -4
- package/{src → tokensafe}/dependency_prefetcher.py +1 -1
- package/{src → tokensafe}/diff_slicer.py +2 -2
- package/{src → tokensafe}/distiller.py +7 -7
- package/{src → tokensafe}/distiller_cache.py +3 -3
- package/{src → tokensafe}/egress_counter.py +1 -1
- package/{src → tokensafe}/environment_auditor.py +7 -7
- package/{src → tokensafe}/file_state.py +2 -2
- package/{src → tokensafe}/format_invariants.py +1 -1
- package/tokensafe/format_parsers/__init__.py +20 -0
- package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
- package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
- package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
- package/{src → tokensafe}/format_parsers/json_log.py +1 -1
- package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
- package/{src → tokensafe}/format_parsers/tabular.py +1 -1
- package/{src → tokensafe}/fts_index.py +20 -11
- package/{src → tokensafe}/governor.py +143 -31
- package/{src → tokensafe}/graph_engine.py +729 -126
- package/{src → tokensafe}/guard.py +80 -25
- package/{src → tokensafe}/history_compactor.py +407 -133
- package/{src → tokensafe}/i18n_catalog.py +39 -14
- package/{src → tokensafe}/image_downscale.py +1 -1
- package/{src → tokensafe}/ingress_staging.py +9 -9
- package/{src → tokensafe}/installer.py +118 -61
- package/{src → tokensafe}/license_manager.py +9 -67
- package/{src → tokensafe}/live_relay.py +2 -2
- package/{src → tokensafe}/loop_detector.py +2 -2
- package/{src → tokensafe}/mcp_config_manager.py +2 -2
- package/{src → tokensafe}/mcp_proxy.py +4 -4
- package/tokensafe/mcp_server.py +5664 -0
- package/{src → tokensafe}/metrics.py +56 -21
- package/{src → tokensafe}/mistakes.py +4 -4
- package/{src → tokensafe}/oumv_brief.py +21 -3
- package/{src → tokensafe}/oumv_gateway.py +146 -49
- package/{src → tokensafe}/oumv_policy.py +1 -1
- package/{src → tokensafe}/paths.py +1 -1
- package/{src → tokensafe}/project_memory.py +4 -4
- package/tokensafe/proxy.py +2075 -0
- package/{src → tokensafe}/quality_score.py +4 -4
- package/{src → tokensafe}/read_baseline.py +1 -1
- package/{src → tokensafe}/repo_compute.py +1 -1
- package/{src → tokensafe}/result_ledger.py +19 -19
- package/{src → tokensafe}/retrofit.py +6 -6
- package/{src → tokensafe}/savings.py +3 -3
- package/tokensafe/schema_slicer.py +1087 -0
- package/{src → tokensafe}/scoped_search.py +144 -6
- package/{src → tokensafe}/secret_redactor.py +22 -0
- package/{src → tokensafe}/session_brief.py +8 -8
- package/{src → tokensafe}/skeletonizer.py +89 -26
- package/{src → tokensafe}/slicer.py +3 -2
- package/{src → tokensafe}/snapshot.py +1 -1
- package/{src → tokensafe}/stash.py +1 -1
- package/{src → tokensafe}/statusline.py +1 -1
- package/{src → tokensafe}/superseded.py +22 -4
- package/{src → tokensafe}/team_cache.py +3 -3
- package/{src → tokensafe}/telemetry_sync.py +63 -11
- package/{src → tokensafe}/test_parsers.py +3 -3
- package/{src → tokensafe}/thinking_fold.py +3 -3
- package/{src → tokensafe}/tokenizer.py +37 -1
- package/{src → tokensafe}/tool_pruner.py +3 -3
- package/{src → tokensafe}/transcript_analyzer.py +1 -1
- package/{src → tokensafe}/transcript_recall.py +8 -8
- package/{src → tokensafe}/type_slicer.py +3 -3
- package/{src → tokensafe}/usage_ledger.py +4 -4
- package/{src → tokensafe}/version_checker.py +6 -6
- package/{src → tokensafe}/web_reader.py +86 -8
- package/{src → tokensafe}/workspace_roots.py +2 -2
- package/src/batch_search.py +0 -589
- package/src/format_parsers/__init__.py +0 -20
- package/src/schema_slicer.py +0 -578
- /package/{src → tokensafe}/agent/pricing.py +0 -0
- /package/{src → tokensafe}/atomic_io.py +0 -0
- /package/{src → tokensafe}/backend_release.py +0 -0
- /package/{src → tokensafe}/bench/__init__.py +0 -0
- /package/{src → tokensafe}/bench/driver.py +0 -0
- /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
- /package/{src → tokensafe}/bench_scenarios.json +0 -0
- /package/{src → tokensafe}/competitors.py +0 -0
- /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
- /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
- /package/{src → tokensafe}/globmatch.py +0 -0
- /package/{src → tokensafe}/host_capabilities.py +0 -0
- /package/{src → tokensafe}/json_repair.py +0 -0
- /package/{src → tokensafe}/route_index.py +0 -0
- /package/{src → tokensafe}/scaffold.py +0 -0
- /package/{src → tokensafe}/session_context.py +0 -0
- /package/{src → tokensafe}/ssl_context.py +0 -0
- /package/{src → tokensafe}/stdio_io.py +0 -0
- /package/{src → tokensafe}/syntax_guard.py +0 -0
- /package/{src → tokensafe}/toml_mcp_config.py +0 -0
- /package/{src → tokensafe}/treesitter_backend.py +0 -0
- /package/{src → tokensafe}/win_paths.py +0 -0
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"name": "tokensafe",
|
|
10
10
|
"source": "./",
|
|
11
11
|
"description": "Enforced context optimization for Claude Code: blocking guards, PostToolUse output compaction, symbol/AST slicing, post-compaction recovery, and measured savings.",
|
|
12
|
-
"version": "
|
|
12
|
+
"version": "5.0.0"
|
|
13
13
|
}
|
|
14
14
|
]
|
|
15
15
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.0",
|
|
4
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
5
|
"author": {
|
|
6
6
|
"name": "TokenSafe",
|
package/README.md
CHANGED
|
@@ -365,7 +365,7 @@ TokenSafe combines two multiplicative savings layers rather than relying on AST
|
|
|
365
365
|
|
|
366
366
|
### Real-Repository Benchmark (measured on live clones)
|
|
367
367
|
|
|
368
|
-
No modeling: fifteen popular repositories across 10 languages (Python, TypeScript, JavaScript, Go, Rust, Java, Ruby, PHP, C#, Swift, C) cloned at HEAD, scenarios **pre-registered before measurement** ([`
|
|
368
|
+
No modeling: fifteen popular repositories across 10 languages (Python, TypeScript, JavaScript, Go, Rust, Java, Ruby, PHP, C#, Swift, C) cloned at HEAD, scenarios **pre-registered before measurement** ([`tokensafe/bench_scenarios.json`](tokensafe/bench_scenarios.json)), every token counted on real bytes, and deterministic zero-loss gates that disqualify any scenario they fail. Curated rows (all rows in [docs/BENCHMARK_REAL.md](docs/BENCHMARK_REAL.md)):
|
|
369
369
|
|
|
370
370
|
| Repo (language) | Scenario | Baseline tok | TokenSafe tok | Reduction | Gates |
|
|
371
371
|
|---|---|---:|---:|---:|:---|
|
package/bin/agy-tokens
CHANGED
|
@@ -20,7 +20,7 @@ if os.path.exists(_venv_py) and os.path.realpath(sys.executable) != os.path.real
|
|
|
20
20
|
except ImportError:
|
|
21
21
|
os.execv(_venv_py, [_venv_py, __file__, *sys.argv[1:]])
|
|
22
22
|
|
|
23
|
-
from
|
|
23
|
+
from tokensafe.cli import main
|
|
24
24
|
|
|
25
25
|
if __name__ == "__main__":
|
|
26
26
|
main()
|
package/bin/tokensafe
CHANGED
|
@@ -21,7 +21,7 @@ if os.path.exists(_venv_py) and os.path.realpath(sys.executable) != os.path.real
|
|
|
21
21
|
except ImportError:
|
|
22
22
|
os.execv(_venv_py, [_venv_py, __file__, *sys.argv[1:]])
|
|
23
23
|
|
|
24
|
-
from
|
|
24
|
+
from tokensafe.cli import main
|
|
25
25
|
|
|
26
26
|
if __name__ == "__main__":
|
|
27
27
|
main()
|
package/bin/tokensafe-acp.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* ACP (Agent Client Protocol) entry point for editors that spawn a Node command.
|
|
5
5
|
*
|
|
6
|
-
* The protocol server itself is Python (
|
|
6
|
+
* The protocol server itself is Python (tokensafe/acp/server.py): it owns the session
|
|
7
7
|
* kernel, the tool guard and the permission prompts. This shim exists only so an
|
|
8
8
|
* editor config can name a Node executable — it reuses the main launcher's
|
|
9
9
|
* runtime resolution (system CPython, ~/.tokensafe/venv, then the pinned managed
|
package/bin/tokensafe-mcp
CHANGED
|
@@ -14,4 +14,4 @@ if ! command -v "$PY" >/dev/null 2>&1; then
|
|
|
14
14
|
echo "tokensafe: python3 not found; install TokenSafe with 'tokensafe install' or curl -fsSL https://tokensafe.dev/install.sh | bash" >&2
|
|
15
15
|
exit 1
|
|
16
16
|
fi
|
|
17
|
-
PYTHONPATH="$ROOT${PYTHONPATH:+:$PYTHONPATH}" exec "$PY" "$ROOT/
|
|
17
|
+
PYTHONPATH="$ROOT${PYTHONPATH:+:$PYTHONPATH}" exec "$PY" "$ROOT/tokensafe/mcp_server.py"
|
package/bin/tokensafe.js
CHANGED
|
@@ -441,7 +441,7 @@ async function findPython(options = {}) {
|
|
|
441
441
|
const firstArg = args[0] || '';
|
|
442
442
|
const wantsHelp = firstArg === 'help' || firstArg === '--help' || firstArg === '-h';
|
|
443
443
|
|
|
444
|
-
// The command reference lives in
|
|
444
|
+
// The command reference lives in tokensafe/cli.py:_print_help(). This launcher used
|
|
445
445
|
// to carry its own copy and fell behind: `dev`, `inject`, `adapters` and
|
|
446
446
|
// `bench-oumv` were missing, so `tokensafe help` advertised a subset of the
|
|
447
447
|
// real dispatcher. Help is forwarded to the Python CLI now, so one list feeds
|
|
@@ -22,7 +22,7 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
|
22
22
|
if PROJECT_ROOT not in sys.path:
|
|
23
23
|
sys.path.insert(0, PROJECT_ROOT)
|
|
24
24
|
|
|
25
|
-
from
|
|
25
|
+
from tokensafe.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, evaluate_cc_pre_tool_use
|
|
26
26
|
|
|
27
27
|
AGENT = "claude_code"
|
|
28
28
|
|
|
@@ -34,8 +34,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
34
34
|
if event == "PreCompact":
|
|
35
35
|
# Arm the one-shot digest while the pre-compaction turns still exist.
|
|
36
36
|
try:
|
|
37
|
-
from
|
|
38
|
-
from
|
|
37
|
+
from tokensafe.transcript_recall import remember_session
|
|
38
|
+
from tokensafe.compaction_recovery import mark_pending
|
|
39
39
|
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
40
40
|
mark_pending(session_id, transcript_path, agent=agent, reason=str(payload.get("trigger") or "pre_compact"))
|
|
41
41
|
except Exception:
|
|
@@ -46,8 +46,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
46
46
|
# The host already rewrote the prompt; hand the model the pointers it
|
|
47
47
|
# would otherwise reconstruct by re-reading files.
|
|
48
48
|
try:
|
|
49
|
-
from
|
|
50
|
-
from
|
|
49
|
+
from tokensafe.transcript_recall import remember_session
|
|
50
|
+
from tokensafe.compaction_recovery import consume_digest
|
|
51
51
|
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
52
52
|
digest = consume_digest(session_id, transcript_path, agent)
|
|
53
53
|
if digest:
|
|
@@ -67,21 +67,21 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
67
67
|
# No matcher on `source` — inject for startup/resume/clear/compact.
|
|
68
68
|
# Well under the 10k-char additionalContext cap.
|
|
69
69
|
try:
|
|
70
|
-
from
|
|
70
|
+
from tokensafe.version_checker import VersionChecker
|
|
71
71
|
VersionChecker.notify_os_update_background()
|
|
72
72
|
except Exception:
|
|
73
73
|
pass
|
|
74
74
|
extra = TOKENSAFE_DIRECTIVES
|
|
75
75
|
try:
|
|
76
|
-
from
|
|
77
|
-
from
|
|
76
|
+
from tokensafe.metrics import MetricsTracker
|
|
77
|
+
from tokensafe.license_manager import LicenseManager
|
|
78
78
|
quota = LicenseManager.check_quota(MetricsTracker())
|
|
79
79
|
if quota.get("warning"):
|
|
80
80
|
extra = f"{extra}\n\n{quota['warning']}"
|
|
81
81
|
except Exception:
|
|
82
82
|
pass
|
|
83
83
|
try:
|
|
84
|
-
from
|
|
84
|
+
from tokensafe.mistakes import MistakesLedger
|
|
85
85
|
guard = MistakesLedger.get_guard_prompt(project_root=str(payload.get("cwd") or os.getcwd()))
|
|
86
86
|
if guard:
|
|
87
87
|
extra = f"{extra}\n\n{guard}"
|
|
@@ -91,10 +91,10 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
91
91
|
# parity with the Antigravity SessionStart hook. Non-project cwd
|
|
92
92
|
# (plain chats, plugin/system dirs) stays banner-free.
|
|
93
93
|
try:
|
|
94
|
-
from
|
|
94
|
+
from tokensafe.paths import is_project_root
|
|
95
95
|
start_cwd = str(payload.get("cwd") or os.getcwd())
|
|
96
96
|
if is_project_root(start_cwd):
|
|
97
|
-
from
|
|
97
|
+
from tokensafe.graph_engine import GraphEngine
|
|
98
98
|
# A warm index answers without a rescan; only a repo that has
|
|
99
99
|
# never been indexed pays the one-time crawl (the banner is the product).
|
|
100
100
|
graph = GraphEngine.get_cached(start_cwd)
|
|
@@ -112,8 +112,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
112
112
|
# Routing brief: which stack is worked through OUMV vs TokenSafe tools.
|
|
113
113
|
# Hosts that report several roots get all of them classified, not just cwd.
|
|
114
114
|
try:
|
|
115
|
-
from
|
|
116
|
-
from
|
|
115
|
+
from tokensafe.paths import is_project_root as _is_project_root
|
|
116
|
+
from tokensafe.session_brief import (
|
|
117
117
|
build_workspace_brief,
|
|
118
118
|
workspace_roots_from_env,
|
|
119
119
|
workspace_roots_from_payload,
|
|
@@ -130,7 +130,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
130
130
|
except Exception:
|
|
131
131
|
pass
|
|
132
132
|
try:
|
|
133
|
-
from
|
|
133
|
+
from tokensafe.burn_monitor import get_burn_warnings
|
|
134
134
|
burn_warn = get_burn_warnings(
|
|
135
135
|
agent=agent,
|
|
136
136
|
session_id=session_id,
|
|
@@ -141,7 +141,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
141
141
|
except Exception:
|
|
142
142
|
pass
|
|
143
143
|
try:
|
|
144
|
-
from
|
|
144
|
+
from tokensafe.adapter_core import format_cumulative_banner
|
|
145
145
|
cum_banner = format_cumulative_banner()
|
|
146
146
|
if cum_banner:
|
|
147
147
|
extra = f"{extra}\n\n{cum_banner}"
|
|
@@ -152,8 +152,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
152
152
|
# the host starts a session from a compaction (or a fallback detector
|
|
153
153
|
# armed a marker on the previous Stop).
|
|
154
154
|
try:
|
|
155
|
-
from
|
|
156
|
-
from
|
|
155
|
+
from tokensafe.transcript_recall import remember_session
|
|
156
|
+
from tokensafe.compaction_recovery import sweep_stale, mark_pending, consume_digest
|
|
157
157
|
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
158
158
|
sweep_stale()
|
|
159
159
|
if str(payload.get("source") or "").strip().lower() == "compact":
|
|
@@ -176,8 +176,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
176
176
|
quota = {"is_quota_exceeded": False, "warning": None}
|
|
177
177
|
tracker = None
|
|
178
178
|
try:
|
|
179
|
-
from
|
|
180
|
-
from
|
|
179
|
+
from tokensafe.metrics import MetricsTracker
|
|
180
|
+
from tokensafe.license_manager import LicenseManager
|
|
181
181
|
tracker = MetricsTracker()
|
|
182
182
|
quota = LicenseManager.check_quota(tracker)
|
|
183
183
|
except Exception:
|
|
@@ -185,7 +185,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
185
185
|
|
|
186
186
|
if quota.get("is_quota_exceeded"):
|
|
187
187
|
try:
|
|
188
|
-
from
|
|
188
|
+
from tokensafe.license_manager import LicenseManager
|
|
189
189
|
if LicenseManager.should_emit_quota_banner(tracker, session_id, every_n_turns=5) and quota.get("warning"):
|
|
190
190
|
parts.append(quota["warning"])
|
|
191
191
|
except Exception:
|
|
@@ -213,7 +213,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
213
213
|
# undefined `extra` and was swallowed by its own except: reviving it
|
|
214
214
|
# would re-send ~1 KB on every prompt, so it stays out.
|
|
215
215
|
try:
|
|
216
|
-
from
|
|
216
|
+
from tokensafe.burn_monitor import get_burn_warnings
|
|
217
217
|
burn_warn = get_burn_warnings(
|
|
218
218
|
agent=agent,
|
|
219
219
|
session_id=session_id,
|
|
@@ -225,11 +225,13 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
225
225
|
pass
|
|
226
226
|
if transcript_path:
|
|
227
227
|
try:
|
|
228
|
-
from
|
|
229
|
-
from
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
228
|
+
from tokensafe.agent import context as kernel
|
|
229
|
+
from tokensafe.metrics import MetricsTracker
|
|
230
|
+
from tokensafe.history_compactor import HistoryCompactor
|
|
231
|
+
# Reads only what was appended since the previous prompt
|
|
232
|
+
# (state persisted across hook processes); the fold below
|
|
233
|
+
# reuses the same in-process state.
|
|
234
|
+
turn = HistoryCompactor.transcript_turns(transcript_path, persist=True)
|
|
233
235
|
if turn >= 3:
|
|
234
236
|
folded, orig_hist, folded_tok, stats = kernel.fold_history(
|
|
235
237
|
transcript_path, turn
|
|
@@ -244,19 +246,21 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
244
246
|
delta_orig = max(0, orig_hist - prev_orig)
|
|
245
247
|
if prev_event is None or delta_orig >= 1500:
|
|
246
248
|
inc_orig = orig_hist if prev_event is None else delta_orig
|
|
247
|
-
|
|
249
|
+
# The digest is ADDED to the context; the history it
|
|
250
|
+
# summarizes stays there. Record the injected mass
|
|
251
|
+
# with zero savings (see METRICS.md, HISTORY_FOLD).
|
|
248
252
|
tracker.record_event(
|
|
249
253
|
session_id=session_id,
|
|
250
254
|
event_type="HISTORY_FOLD",
|
|
251
|
-
original_tokens=
|
|
255
|
+
original_tokens=folded_tok,
|
|
252
256
|
optimized_tokens=folded_tok,
|
|
253
|
-
details={"turns": turn, "total_accum_orig": orig_hist, "agent": agent
|
|
257
|
+
details={"turns": turn, "total_accum_orig": orig_hist, "agent": agent,
|
|
258
|
+
"history_tokens": inc_orig, "injected": True},
|
|
254
259
|
)
|
|
255
260
|
parts.append(
|
|
256
261
|
f"{folded}\n"
|
|
257
|
-
f"(TokenSafe History Compactor:
|
|
258
|
-
f"
|
|
259
|
-
f"Estimated per METRICS.md.)"
|
|
262
|
+
f"(TokenSafe History Compactor: digest of {orig_hist:,} tokens of previous "
|
|
263
|
+
f"turns, +{folded_tok:,} tokens; the history itself is unchanged.)"
|
|
260
264
|
)
|
|
261
265
|
except Exception:
|
|
262
266
|
pass
|
|
@@ -264,7 +268,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
264
268
|
# Delegated task digest: the child already read these files (one injection
|
|
265
269
|
# per delegation; the digest file is consumed on read).
|
|
266
270
|
try:
|
|
267
|
-
from
|
|
271
|
+
from tokensafe.delegation import render as _render_delegation, take as _take_delegation
|
|
268
272
|
_delegated = _take_delegation(session_id)
|
|
269
273
|
if _delegated:
|
|
270
274
|
parts.append(_render_delegation(_delegated))
|
|
@@ -274,8 +278,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
274
278
|
# One-shot post-compaction recovery (PreCompact/PostCompact marker or a
|
|
275
279
|
# fallback detection on the previous Stop).
|
|
276
280
|
try:
|
|
277
|
-
from
|
|
278
|
-
from
|
|
281
|
+
from tokensafe.transcript_recall import remember_session
|
|
282
|
+
from tokensafe.compaction_recovery import consume_digest
|
|
279
283
|
remember_session(session_id, transcript_path, agent=agent, cwd=str(payload.get("cwd") or ""))
|
|
280
284
|
digest = consume_digest(session_id, transcript_path, agent)
|
|
281
285
|
if digest:
|
|
@@ -302,7 +306,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
302
306
|
tool = str(payload.get("tool_name") or "")
|
|
303
307
|
compacted, orig, new = None, 0, 0
|
|
304
308
|
try:
|
|
305
|
-
from
|
|
309
|
+
from tokensafe.command_sanitizer import CommandSanitizer
|
|
306
310
|
res = CommandSanitizer.compact_tool_output(tool, payload.get("tool_response"))
|
|
307
311
|
if res:
|
|
308
312
|
compacted, orig, new = res
|
|
@@ -310,8 +314,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
310
314
|
compacted = None
|
|
311
315
|
if compacted:
|
|
312
316
|
try:
|
|
313
|
-
from
|
|
314
|
-
from
|
|
317
|
+
from tokensafe.metrics import MetricsTracker
|
|
318
|
+
from tokensafe.tokenizer import count_tokens
|
|
315
319
|
MetricsTracker().record_event(
|
|
316
320
|
session_id=session_id,
|
|
317
321
|
event_type="TOOL_OUTPUT_COMPACT",
|
|
@@ -338,14 +342,14 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
338
342
|
if isinstance(ti, dict):
|
|
339
343
|
track_fp = str(ti.get("file_path") or ti.get("Path") or ti.get("path") or ti.get("FilePath") or "")
|
|
340
344
|
if track_fp:
|
|
341
|
-
from
|
|
345
|
+
from tokensafe.file_state import FileState
|
|
342
346
|
FileState.record_seen(track_fp)
|
|
343
347
|
except Exception:
|
|
344
348
|
pass
|
|
345
349
|
# A delegated task returned: fold the child's rollout into a digest for the
|
|
346
350
|
# next turn instead of letting the orchestrator re-read its files.
|
|
347
351
|
try:
|
|
348
|
-
from
|
|
352
|
+
from tokensafe.delegation import is_agent_tool, record_from_hook
|
|
349
353
|
if is_agent_tool(tool):
|
|
350
354
|
record_from_hook(payload)
|
|
351
355
|
except Exception:
|
|
@@ -361,10 +365,10 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
361
365
|
try:
|
|
362
366
|
rest_tp = str(payload.get("transcript_path") or "")
|
|
363
367
|
if rest_tp:
|
|
364
|
-
from
|
|
368
|
+
from tokensafe.superseded import SupersededPruner
|
|
365
369
|
res = SupersededPruner.fold_at_rest(rest_tp)
|
|
366
370
|
if res.get("success") and res.get("pruned_count", 0) > 0:
|
|
367
|
-
from
|
|
371
|
+
from tokensafe.metrics import MetricsTracker
|
|
368
372
|
MetricsTracker().record_event(
|
|
369
373
|
session_id=session_id,
|
|
370
374
|
event_type="FOLD_AT_REST",
|
|
@@ -383,7 +387,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
383
387
|
try:
|
|
384
388
|
usage_tp = str(payload.get("transcript_path") or "")
|
|
385
389
|
if usage_tp and session_id:
|
|
386
|
-
from
|
|
390
|
+
from tokensafe.usage_ledger import update_from_transcript
|
|
387
391
|
update_from_transcript(usage_tp, agent=agent, session_id=session_id)
|
|
388
392
|
except Exception:
|
|
389
393
|
pass
|
|
@@ -394,7 +398,7 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
394
398
|
|
|
395
399
|
def main():
|
|
396
400
|
try:
|
|
397
|
-
from
|
|
401
|
+
from tokensafe.stdio_io import read_stdin_text
|
|
398
402
|
raw = read_stdin_text()
|
|
399
403
|
payload = json.loads(raw) if raw.strip() else {}
|
|
400
404
|
if not isinstance(payload, dict):
|
|
@@ -412,7 +416,7 @@ def main():
|
|
|
412
416
|
response = {}
|
|
413
417
|
if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"):
|
|
414
418
|
try:
|
|
415
|
-
from
|
|
419
|
+
from tokensafe.telemetry_sync import TelemetrySync
|
|
416
420
|
TelemetrySync.sync_background(throttle_seconds=0.0 if event == "Stop" else 20.0)
|
|
417
421
|
except Exception:
|
|
418
422
|
pass
|
package/hooks/cursor_hook.py
CHANGED
|
@@ -29,7 +29,7 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
|
29
29
|
if PROJECT_ROOT not in sys.path:
|
|
30
30
|
sys.path.insert(0, PROJECT_ROOT)
|
|
31
31
|
|
|
32
|
-
from
|
|
32
|
+
from tokensafe.adapter_core import extract_write_content, guard_command, guard_file_content, guard_read
|
|
33
33
|
|
|
34
34
|
AGENT = "cursor"
|
|
35
35
|
|
|
@@ -47,7 +47,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
47
47
|
# Loop guard across Cursor pre-tool hooks
|
|
48
48
|
if event in ("beforeShellExecution", "beforeReadFile", "beforeEditFile"):
|
|
49
49
|
try:
|
|
50
|
-
from
|
|
50
|
+
from tokensafe.loop_detector import LoopDetector
|
|
51
51
|
is_loop, _cnt, loop_msg = LoopDetector.check_loop(session_id, event, payload)
|
|
52
52
|
if is_loop:
|
|
53
53
|
if event == "beforeShellExecution":
|
|
@@ -64,7 +64,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
64
64
|
if verdict["decision"] == "ask":
|
|
65
65
|
return {"permission": "ask", "agent_message": verdict["reason"]}
|
|
66
66
|
try:
|
|
67
|
-
from
|
|
67
|
+
from tokensafe.mistakes import MistakesLedger
|
|
68
68
|
is_blocked, m_reason = MistakesLedger.should_force_ask(command, action_type="command", project_root=cwd or os.getcwd())
|
|
69
69
|
if is_blocked:
|
|
70
70
|
return {"permission": "ask", "agent_message": f"[TokenSafe Anti-Stuck Guard] {m_reason}"}
|
|
@@ -91,7 +91,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
91
91
|
if verdict["decision"] == "deny":
|
|
92
92
|
return {"permission": "deny", "user_message": verdict["reason"]}
|
|
93
93
|
try:
|
|
94
|
-
from
|
|
94
|
+
from tokensafe.mistakes import MistakesLedger
|
|
95
95
|
is_blocked, m_reason = MistakesLedger.should_force_ask(edit_path, action_type="edit_file", project_root=cwd or os.getcwd())
|
|
96
96
|
if is_blocked:
|
|
97
97
|
return {"permission": "deny", "user_message": f"[TokenSafe Anti-Stuck Guard] {m_reason}"}
|
|
@@ -108,11 +108,11 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
108
108
|
try:
|
|
109
109
|
fp = str(payload.get("file_path") or payload.get("path") or "")
|
|
110
110
|
if fp:
|
|
111
|
-
from
|
|
111
|
+
from tokensafe.file_state import FileState
|
|
112
112
|
FileState.record_seen(fp)
|
|
113
113
|
err_txt = str(payload.get("error") or payload.get("stderr") or "").strip()
|
|
114
114
|
if err_txt and fp:
|
|
115
|
-
from
|
|
115
|
+
from tokensafe.mistakes import MistakesLedger
|
|
116
116
|
MistakesLedger.record_failure(summary=err_txt[:140], file_path=fp, source="cursor_hook", project_root=cwd or os.getcwd())
|
|
117
117
|
except Exception:
|
|
118
118
|
pass
|
|
@@ -126,7 +126,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
126
126
|
|
|
127
127
|
def main():
|
|
128
128
|
try:
|
|
129
|
-
from
|
|
129
|
+
from tokensafe.stdio_io import read_stdin_text
|
|
130
130
|
raw = read_stdin_text()
|
|
131
131
|
payload = json.loads(raw) if raw.strip() else {}
|
|
132
132
|
if not isinstance(payload, dict):
|
|
@@ -144,7 +144,7 @@ def main():
|
|
|
144
144
|
response = _allow(event)
|
|
145
145
|
if event in ("beforeShellExecution", "beforeEditFile", "beforeReadFile", "beforeSubmitPrompt", "stop"):
|
|
146
146
|
try:
|
|
147
|
-
from
|
|
147
|
+
from tokensafe.telemetry_sync import TelemetrySync
|
|
148
148
|
TelemetrySync.sync_background(throttle_seconds=0.0 if event == "stop" else 20.0)
|
|
149
149
|
except Exception:
|
|
150
150
|
pass
|
package/hooks/kimi_hook.py
CHANGED
|
@@ -21,7 +21,7 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
|
21
21
|
if PROJECT_ROOT not in sys.path:
|
|
22
22
|
sys.path.insert(0, PROJECT_ROOT)
|
|
23
23
|
|
|
24
|
-
from
|
|
24
|
+
from tokensafe.adapter_core import (
|
|
25
25
|
TOKENSAFE_DIRECTIVES,
|
|
26
26
|
compact_for_injection,
|
|
27
27
|
evaluate_cc_pre_tool_use,
|
|
@@ -42,20 +42,20 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
42
42
|
if event == "SessionStart":
|
|
43
43
|
extra = TOKENSAFE_DIRECTIVES
|
|
44
44
|
try:
|
|
45
|
-
from
|
|
45
|
+
from tokensafe.version_checker import VersionChecker
|
|
46
46
|
VersionChecker.notify_os_update_background()
|
|
47
47
|
except Exception:
|
|
48
48
|
pass
|
|
49
49
|
try:
|
|
50
|
-
from
|
|
51
|
-
from
|
|
50
|
+
from tokensafe.metrics import MetricsTracker
|
|
51
|
+
from tokensafe.license_manager import LicenseManager
|
|
52
52
|
quota = LicenseManager.check_quota(MetricsTracker())
|
|
53
53
|
if quota.get("warning"):
|
|
54
54
|
extra = f"{extra}\n\n{quota['warning']}"
|
|
55
55
|
except Exception:
|
|
56
56
|
pass
|
|
57
57
|
try:
|
|
58
|
-
from
|
|
58
|
+
from tokensafe.mistakes import MistakesLedger
|
|
59
59
|
guard = MistakesLedger.get_guard_prompt(project_root=str(payload.get("cwd") or os.getcwd()))
|
|
60
60
|
if guard:
|
|
61
61
|
extra = f"{extra}\n\n{guard}"
|
|
@@ -63,8 +63,8 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
63
63
|
pass
|
|
64
64
|
# Routing brief: every open folder is classified, not only cwd.
|
|
65
65
|
try:
|
|
66
|
-
from
|
|
67
|
-
from
|
|
66
|
+
from tokensafe.paths import is_project_root as _is_project_root
|
|
67
|
+
from tokensafe.session_brief import (
|
|
68
68
|
build_workspace_brief,
|
|
69
69
|
workspace_roots_from_env,
|
|
70
70
|
workspace_roots_from_payload,
|
|
@@ -81,7 +81,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
81
81
|
except Exception:
|
|
82
82
|
pass
|
|
83
83
|
try:
|
|
84
|
-
from
|
|
84
|
+
from tokensafe.burn_monitor import get_burn_warnings
|
|
85
85
|
burn_warn = get_burn_warnings(
|
|
86
86
|
agent=AGENT,
|
|
87
87
|
session_id=session_id,
|
|
@@ -92,15 +92,15 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
92
92
|
except Exception:
|
|
93
93
|
pass
|
|
94
94
|
try:
|
|
95
|
-
from
|
|
95
|
+
from tokensafe.adapter_core import format_cumulative_banner
|
|
96
96
|
cum_banner = format_cumulative_banner()
|
|
97
97
|
if cum_banner:
|
|
98
98
|
extra = f"{extra}\n\n{cum_banner}"
|
|
99
99
|
except Exception:
|
|
100
100
|
pass
|
|
101
101
|
try:
|
|
102
|
-
from
|
|
103
|
-
from
|
|
102
|
+
from tokensafe.transcript_recall import remember_session
|
|
103
|
+
from tokensafe.compaction_recovery import consume_digest
|
|
104
104
|
_tp = str(payload.get("transcript_path") or "")
|
|
105
105
|
remember_session(session_id, _tp, agent=AGENT, cwd=str(payload.get("cwd") or ""))
|
|
106
106
|
digest = consume_digest(session_id, _tp, AGENT)
|
|
@@ -121,8 +121,8 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
121
121
|
quota = {"is_quota_exceeded": False, "warning": None}
|
|
122
122
|
tracker = None
|
|
123
123
|
try:
|
|
124
|
-
from
|
|
125
|
-
from
|
|
124
|
+
from tokensafe.metrics import MetricsTracker
|
|
125
|
+
from tokensafe.license_manager import LicenseManager
|
|
126
126
|
tracker = MetricsTracker()
|
|
127
127
|
quota = LicenseManager.check_quota(tracker)
|
|
128
128
|
except Exception:
|
|
@@ -130,7 +130,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
130
130
|
|
|
131
131
|
if quota.get("is_quota_exceeded"):
|
|
132
132
|
try:
|
|
133
|
-
from
|
|
133
|
+
from tokensafe.license_manager import LicenseManager
|
|
134
134
|
if LicenseManager.should_emit_quota_banner(tracker, session_id, every_n_turns=5) and quota.get("warning"):
|
|
135
135
|
parts.append(quota["warning"])
|
|
136
136
|
except Exception:
|
|
@@ -155,7 +155,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
155
155
|
# per-turn copy here targeted an undefined `extra` and died in its own
|
|
156
156
|
# except. It stays dead: re-sending ~1 KB every prompt is pure tax.
|
|
157
157
|
try:
|
|
158
|
-
from
|
|
158
|
+
from tokensafe.burn_monitor import get_burn_warnings
|
|
159
159
|
burn_warn = get_burn_warnings(
|
|
160
160
|
agent=AGENT,
|
|
161
161
|
session_id=session_id,
|
|
@@ -167,8 +167,8 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
167
167
|
pass
|
|
168
168
|
|
|
169
169
|
try:
|
|
170
|
-
from
|
|
171
|
-
from
|
|
170
|
+
from tokensafe.transcript_recall import remember_session
|
|
171
|
+
from tokensafe.compaction_recovery import consume_digest
|
|
172
172
|
_tp = str(payload.get("transcript_path") or "")
|
|
173
173
|
remember_session(session_id, _tp, agent=AGENT, cwd=str(payload.get("cwd") or ""))
|
|
174
174
|
digest = consume_digest(session_id, _tp, AGENT)
|
|
@@ -193,7 +193,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
193
193
|
tool = str(payload.get("tool_name") or "")
|
|
194
194
|
compacted, orig, new = None, 0, 0
|
|
195
195
|
try:
|
|
196
|
-
from
|
|
196
|
+
from tokensafe.command_sanitizer import CommandSanitizer
|
|
197
197
|
res = CommandSanitizer.compact_tool_output(tool, payload.get("tool_response"))
|
|
198
198
|
if res:
|
|
199
199
|
compacted, orig, new = res
|
|
@@ -201,8 +201,8 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
201
201
|
compacted = None
|
|
202
202
|
if compacted:
|
|
203
203
|
try:
|
|
204
|
-
from
|
|
205
|
-
from
|
|
204
|
+
from tokensafe.metrics import MetricsTracker
|
|
205
|
+
from tokensafe.tokenizer import count_tokens
|
|
206
206
|
MetricsTracker().record_event(
|
|
207
207
|
session_id=session_id,
|
|
208
208
|
event_type="TOOL_OUTPUT_COMPACT",
|
|
@@ -226,7 +226,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
226
226
|
if isinstance(ti, dict):
|
|
227
227
|
track_fp = str(ti.get("file_path") or ti.get("Path") or ti.get("path") or ti.get("FilePath") or "")
|
|
228
228
|
if track_fp:
|
|
229
|
-
from
|
|
229
|
+
from tokensafe.file_state import FileState
|
|
230
230
|
FileState.record_seen(track_fp)
|
|
231
231
|
except Exception:
|
|
232
232
|
pass
|
|
@@ -241,7 +241,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
241
241
|
|
|
242
242
|
def main():
|
|
243
243
|
try:
|
|
244
|
-
from
|
|
244
|
+
from tokensafe.stdio_io import read_stdin_text
|
|
245
245
|
raw = read_stdin_text()
|
|
246
246
|
payload = json.loads(raw) if raw.strip() else {}
|
|
247
247
|
if not isinstance(payload, dict):
|
|
@@ -259,7 +259,7 @@ def main():
|
|
|
259
259
|
response = {}
|
|
260
260
|
if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"):
|
|
261
261
|
try:
|
|
262
|
-
from
|
|
262
|
+
from tokensafe.telemetry_sync import TelemetrySync
|
|
263
263
|
TelemetrySync.sync_background(throttle_seconds=0.0 if event == "Stop" else 20.0)
|
|
264
264
|
except Exception:
|
|
265
265
|
pass
|
package/hooks/post_tool_use.py
CHANGED
|
@@ -35,7 +35,7 @@ def _should_skip_fast() -> bool:
|
|
|
35
35
|
def main():
|
|
36
36
|
raw = ""
|
|
37
37
|
try:
|
|
38
|
-
from
|
|
38
|
+
from tokensafe.stdio_io import read_stdin_text
|
|
39
39
|
raw = read_stdin_text()
|
|
40
40
|
except Exception:
|
|
41
41
|
raw = ""
|
|
@@ -62,14 +62,14 @@ def main():
|
|
|
62
62
|
tracked_path = val
|
|
63
63
|
break
|
|
64
64
|
if tracked_path:
|
|
65
|
-
from
|
|
65
|
+
from tokensafe.file_state import FileState
|
|
66
66
|
FileState.record_seen(tracked_path)
|
|
67
67
|
|
|
68
68
|
# A delegated task returned: fold the child's own rollout into a digest
|
|
69
69
|
# for the next turn instead of letting the orchestrator re-read its
|
|
70
70
|
# files (the largest measured leak in the burn audit).
|
|
71
71
|
try:
|
|
72
|
-
from
|
|
72
|
+
from tokensafe.delegation import is_agent_tool, record_from_hook
|
|
73
73
|
if is_agent_tool(tool_name):
|
|
74
74
|
record_from_hook(payload)
|
|
75
75
|
except Exception:
|
|
@@ -101,7 +101,7 @@ def main():
|
|
|
101
101
|
|
|
102
102
|
if is_failed and cmd:
|
|
103
103
|
try:
|
|
104
|
-
from
|
|
104
|
+
from tokensafe.mistakes import MistakesLedger
|
|
105
105
|
hook_cwd = str(payload.get("cwd") or os.getcwd())
|
|
106
106
|
summary = f"Command failed (exit {exit_code or 'err'}): {cmd[:60]}"
|
|
107
107
|
MistakesLedger.record_failure(
|
|
@@ -116,7 +116,7 @@ def main():
|
|
|
116
116
|
# Known-good commands: remember what actually passed here.
|
|
117
117
|
if cmd:
|
|
118
118
|
try:
|
|
119
|
-
from
|
|
119
|
+
from tokensafe.project_memory import ProjectMemory
|
|
120
120
|
hook_cwd = str(payload.get("cwd") or os.getcwd())
|
|
121
121
|
ProjectMemory(hook_cwd).record_command(
|
|
122
122
|
cmd,
|
|
@@ -131,7 +131,7 @@ def main():
|
|
|
131
131
|
# Non-blocking telemetry sync trigger (detached background process)
|
|
132
132
|
if not _should_skip_fast():
|
|
133
133
|
try:
|
|
134
|
-
from
|
|
134
|
+
from tokensafe.telemetry_sync import TelemetrySync
|
|
135
135
|
TelemetrySync.sync_background(throttle_seconds=20.0)
|
|
136
136
|
except Exception:
|
|
137
137
|
pass
|