tokensafe 4.15.0 → 4.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/bin/tokensafe-acp.js +38 -0
- package/hooks/claude_code_hook.py +26 -0
- package/hooks/post_tool_use.py +10 -0
- package/hooks/pre_invocation.py +44 -11
- package/hooks/pre_tool_use.py +22 -1
- package/kimi.plugin.json +1 -1
- package/package.json +3 -2
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +157 -3
- package/src/angular_cli.py +181 -0
- package/src/auto_inject.py +36 -2
- package/src/backend_release.py +1 -1
- package/src/batch_editor.py +119 -2
- 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 +109 -4
- package/src/command_sanitizer.py +21 -5
- package/src/dashboard.py +26 -0
- package/src/delegation.py +253 -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/installer.py +1 -1
- package/src/license_manager.py +128 -1
- package/src/mcp_server.py +318 -39
- package/src/metrics.py +313 -29
- package/src/savings.py +9 -4
- package/src/skeletonizer.py +51 -0
- package/src/telemetry_sync.py +1 -1
- package/src/usage_ledger.py +333 -0
- package/src/version_checker.py +1 -1
|
@@ -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
|
+
});
|
|
@@ -214,6 +214,16 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
214
214
|
except Exception:
|
|
215
215
|
pass
|
|
216
216
|
|
|
217
|
+
# Delegated task digest: the child already read these files (one injection
|
|
218
|
+
# per delegation; the digest file is consumed on read).
|
|
219
|
+
try:
|
|
220
|
+
from src.delegation import render as _render_delegation, take as _take_delegation
|
|
221
|
+
_delegated = _take_delegation(session_id)
|
|
222
|
+
if _delegated:
|
|
223
|
+
parts.append(_render_delegation(_delegated))
|
|
224
|
+
except Exception:
|
|
225
|
+
pass
|
|
226
|
+
|
|
217
227
|
if parts:
|
|
218
228
|
return {
|
|
219
229
|
"hookSpecificOutput": {
|
|
@@ -273,6 +283,14 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
273
283
|
FileState.record_seen(track_fp)
|
|
274
284
|
except Exception:
|
|
275
285
|
pass
|
|
286
|
+
# A delegated task returned: fold the child's rollout into a digest for the
|
|
287
|
+
# next turn instead of letting the orchestrator re-read its files.
|
|
288
|
+
try:
|
|
289
|
+
from src.delegation import is_agent_tool, record_from_hook
|
|
290
|
+
if is_agent_tool(tool):
|
|
291
|
+
record_from_hook(payload)
|
|
292
|
+
except Exception:
|
|
293
|
+
pass
|
|
276
294
|
return {}
|
|
277
295
|
|
|
278
296
|
if event == "Stop":
|
|
@@ -302,6 +320,14 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
|
|
|
302
320
|
)
|
|
303
321
|
except Exception:
|
|
304
322
|
pass
|
|
323
|
+
# Output usage ledger: incremental offset read, provider-reported only.
|
|
324
|
+
try:
|
|
325
|
+
usage_tp = str(payload.get("transcript_path") or "")
|
|
326
|
+
if usage_tp and session_id:
|
|
327
|
+
from src.usage_ledger import update_from_transcript
|
|
328
|
+
update_from_transcript(usage_tp, agent=agent, session_id=session_id)
|
|
329
|
+
except Exception:
|
|
330
|
+
pass
|
|
305
331
|
return {}
|
|
306
332
|
|
|
307
333
|
return {}
|
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
|
@@ -70,6 +70,19 @@ def _handle(payload: dict) -> dict:
|
|
|
70
70
|
pass
|
|
71
71
|
|
|
72
72
|
tracker = MetricsTracker()
|
|
73
|
+
# One query for every "did this already happen?" check below. The five
|
|
74
|
+
# per-type lookups ran on every invocation and each paid a round trip.
|
|
75
|
+
recent_events: dict = {}
|
|
76
|
+
try:
|
|
77
|
+
recent_events = tracker.get_last_events(conversation_id, (
|
|
78
|
+
"HISTORY_FOLD",
|
|
79
|
+
"GUARD_RAW_CODE_SEARCH",
|
|
80
|
+
"PROTOCOL_REMINDER",
|
|
81
|
+
"BUDGET_WARNING",
|
|
82
|
+
"NOTIFICATION_TURN",
|
|
83
|
+
))
|
|
84
|
+
except Exception:
|
|
85
|
+
recent_events = {}
|
|
73
86
|
inject_steps = []
|
|
74
87
|
workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
|
|
75
88
|
hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
|
|
@@ -164,7 +177,7 @@ def _handle(payload: dict) -> dict:
|
|
|
164
177
|
)
|
|
165
178
|
if folded_text and stats.get("saved_tokens", 0) > 0:
|
|
166
179
|
# Prevent quadratic double-counting: only record incremental new history mass
|
|
167
|
-
prev_event =
|
|
180
|
+
prev_event = recent_events.get("HISTORY_FOLD")
|
|
168
181
|
prev_orig = 0
|
|
169
182
|
if prev_event and isinstance(prev_event.get("details"), dict):
|
|
170
183
|
prev_orig = prev_event["details"].get("total_accum_orig", 0) or prev_event.get("original_tokens", 0)
|
|
@@ -209,10 +222,10 @@ def _handle(payload: dict) -> dict:
|
|
|
209
222
|
history_mass = kernel.measure_transcript(transcript_path)
|
|
210
223
|
|
|
211
224
|
# 4. Adaptive Protocol Enforcement Reminder (Guard-triggered or fresh fold only)
|
|
212
|
-
recent_guard =
|
|
225
|
+
recent_guard = recent_events.get("GUARD_RAW_CODE_SEARCH")
|
|
213
226
|
guard_unreminded = False
|
|
214
227
|
if isinstance(recent_guard, dict):
|
|
215
|
-
last_remind =
|
|
228
|
+
last_remind = recent_events.get("PROTOCOL_REMINDER")
|
|
216
229
|
is_valid_remind = isinstance(last_remind, dict) and last_remind.get("event_type") == "PROTOCOL_REMINDER"
|
|
217
230
|
if not is_valid_remind:
|
|
218
231
|
guard_unreminded = True
|
|
@@ -249,14 +262,17 @@ def _handle(payload: dict) -> dict:
|
|
|
249
262
|
try:
|
|
250
263
|
budget = kernel.estimate_budget(
|
|
251
264
|
tracker, session_id=conversation_id,
|
|
252
|
-
model=_model_name(payload),
|
|
265
|
+
model=_model_name(payload) or resolve_event_model(transcript_path, conversation_id),
|
|
253
266
|
history_tokens=history_mass,
|
|
254
267
|
transcript_path=transcript_path
|
|
255
268
|
)
|
|
256
|
-
|
|
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")
|
|
257
272
|
if (budget.get("measurement") == "measured"
|
|
258
|
-
and
|
|
259
|
-
|
|
273
|
+
and budget_pct is not None
|
|
274
|
+
and budget.get("threshold") in ("warning", "critical")):
|
|
275
|
+
already = recent_events.get("BUDGET_WARNING")
|
|
260
276
|
if not already:
|
|
261
277
|
if transcript_path:
|
|
262
278
|
action = (f"Call tokensafe:session_context(action='compact', transcript_path='{transcript_path}') "
|
|
@@ -265,8 +281,9 @@ def _handle(payload: dict) -> dict:
|
|
|
265
281
|
action = budget["recommendation"]
|
|
266
282
|
token_count = budget.get("used_tokens") or budget.get("used_estimated") or 0
|
|
267
283
|
warn = (
|
|
268
|
-
f"🧠 **Context Budget:** ~{
|
|
269
|
-
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}"
|
|
270
287
|
)
|
|
271
288
|
inject_steps.append({
|
|
272
289
|
"systemMessage": {
|
|
@@ -279,7 +296,9 @@ def _handle(payload: dict) -> dict:
|
|
|
279
296
|
event_type="BUDGET_WARNING",
|
|
280
297
|
original_tokens=0,
|
|
281
298
|
optimized_tokens=0,
|
|
282
|
-
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"],
|
|
283
302
|
"measurement": budget.get("measurement")}
|
|
284
303
|
)
|
|
285
304
|
except Exception:
|
|
@@ -291,7 +310,7 @@ def _handle(payload: dict) -> dict:
|
|
|
291
310
|
try:
|
|
292
311
|
last_input = str(payload.get("lastUserInput") or payload.get("prompt") or "").strip()
|
|
293
312
|
if invocation_num >= 2 and not last_input:
|
|
294
|
-
if not
|
|
313
|
+
if not recent_events.get("NOTIFICATION_TURN"):
|
|
295
314
|
inject_steps.append({
|
|
296
315
|
"systemMessage": {
|
|
297
316
|
"systemMessage": "",
|
|
@@ -312,6 +331,20 @@ def _handle(payload: dict) -> dict:
|
|
|
312
331
|
except Exception:
|
|
313
332
|
pass
|
|
314
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
|
+
|
|
315
348
|
# 6. Multi-Agent Live Burn Monitor (rate-limited, only fires on real burn spikes)
|
|
316
349
|
if invocation_num >= 2 or transcript_path:
|
|
317
350
|
try:
|
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/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.16.0",
|
|
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,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.16.0",
|
|
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",
|
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.0",
|
|
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",
|
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.16.0",
|
|
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.16.0",
|
|
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.16.0",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
package/src/adapter_core.py
CHANGED
|
@@ -17,7 +17,7 @@ import sys
|
|
|
17
17
|
import re
|
|
18
18
|
import json
|
|
19
19
|
import time
|
|
20
|
-
from typing import Dict, Any, Optional, Tuple
|
|
20
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
21
21
|
|
|
22
22
|
from src.tokenizer import count_tokens
|
|
23
23
|
|
|
@@ -38,6 +38,7 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
38
38
|
"• Deduplication & Cache Pointers: Never re-read unchanged files repeatedly; reuse earlier context or pointer references.\n"
|
|
39
39
|
"• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
|
|
40
40
|
"• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs (use apply_edits for multi-file edits and run_helper for sanitize/guard/deps/web/expand/image).\n"
|
|
41
|
+
"• apply_edits already runs the project's own test command and returns the verdict in the same call; do not re-read the edited file or run the suite again unless strict_verify=true was used.\n"
|
|
41
42
|
"• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
|
|
42
43
|
"• Mandatory Architecture Graph & God Nodes: For any codebase inquiry, navigation, or multi-component work, ALWAYS inspect God Nodes via 'tokensafe:repo_map(view=\"graph\", project_path=...)' first before diving into files (pass target project's absolute path in multi-repo setups).\n"
|
|
43
44
|
"• To inspect all exported types/interfaces or directory trees: call 'tokensafe:repo_map(view=\"api\"|\"tree\", project_path=...)'.\n"
|
|
@@ -431,6 +432,141 @@ def guard_write(file_path: str, content: str, append: bool = False, agent: str =
|
|
|
431
432
|
)
|
|
432
433
|
|
|
433
434
|
|
|
435
|
+
def _env_int(name: str, default: int) -> int:
|
|
436
|
+
try:
|
|
437
|
+
return int(os.environ.get(name, str(default)))
|
|
438
|
+
except (TypeError, ValueError):
|
|
439
|
+
return default
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _edit_replacements(tool_input: Dict[str, Any]) -> List[str]:
|
|
443
|
+
"""Collects the replacement text of Edit-like payloads (Edit/MultiEdit/
|
|
444
|
+
apply_edits/apply_patch-normalized shapes)."""
|
|
445
|
+
keys = ("new_string", "new_text", "replacement", "new_content", "content", "Content")
|
|
446
|
+
reps: List[str] = []
|
|
447
|
+
|
|
448
|
+
def _take(obj: Dict[str, Any]) -> None:
|
|
449
|
+
for key in keys:
|
|
450
|
+
val = obj.get(key)
|
|
451
|
+
if isinstance(val, str) and val:
|
|
452
|
+
reps.append(val)
|
|
453
|
+
return
|
|
454
|
+
|
|
455
|
+
_take(tool_input)
|
|
456
|
+
items = tool_input.get("edits")
|
|
457
|
+
if isinstance(items, list):
|
|
458
|
+
for item in items:
|
|
459
|
+
if isinstance(item, dict):
|
|
460
|
+
_take(item)
|
|
461
|
+
return reps
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def guard_edit_rewrite(
|
|
465
|
+
file_path: str,
|
|
466
|
+
tool_input: Dict[str, Any],
|
|
467
|
+
agent: str = "",
|
|
468
|
+
session_id: str = "",
|
|
469
|
+
transcript_path: str = "",
|
|
470
|
+
) -> Dict[str, Any]:
|
|
471
|
+
"""Edit-path twin of guard_write: an Edit that re-emits most of an existing
|
|
472
|
+
file costs the same output tokens as a wholesale Write, so it earns the same
|
|
473
|
+
ask. Only asks; never denies. Kill switch: TOKENSAFE_EDIT_REWRITE_GUARD=0."""
|
|
474
|
+
result = {"decision": "allow", "reason": "", "saved_tokens": 0}
|
|
475
|
+
if os.environ.get("TOKENSAFE_EDIT_REWRITE_GUARD", "1").strip().lower() in ("0", "false", "no"):
|
|
476
|
+
return result
|
|
477
|
+
if not file_path or not os.path.isfile(file_path):
|
|
478
|
+
return result
|
|
479
|
+
replacements = _edit_replacements(tool_input)
|
|
480
|
+
if not replacements:
|
|
481
|
+
return result
|
|
482
|
+
try:
|
|
483
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
484
|
+
existing_text = f.read()
|
|
485
|
+
except Exception:
|
|
486
|
+
return result
|
|
487
|
+
existing_lines = existing_text.splitlines()
|
|
488
|
+
if len(existing_lines) < _env_int("TOKENSAFE_EDIT_REWRITE_MIN_LINES", 40):
|
|
489
|
+
return result
|
|
490
|
+
|
|
491
|
+
replacement = "\n".join(replacements)
|
|
492
|
+
replacement_tokens = max(1, count_tokens(replacement))
|
|
493
|
+
file_tokens = max(1, count_tokens(existing_text))
|
|
494
|
+
ratio = replacement_tokens / file_tokens
|
|
495
|
+
if ratio < float(os.environ.get("TOKENSAFE_EDIT_REWRITE_RATIO", "0.6")):
|
|
496
|
+
return result
|
|
497
|
+
|
|
498
|
+
tracker = _get_tracker()
|
|
499
|
+
if tracker:
|
|
500
|
+
try:
|
|
501
|
+
tracker.record_event(
|
|
502
|
+
session_id=session_id or f"hook_{agent}",
|
|
503
|
+
event_type="OUTPUT_GUARD",
|
|
504
|
+
original_tokens=replacement_tokens,
|
|
505
|
+
optimized_tokens=max(1, replacement_tokens // 4),
|
|
506
|
+
details={
|
|
507
|
+
"agent": agent,
|
|
508
|
+
"target_file": os.path.basename(file_path),
|
|
509
|
+
"existing_lines": len(existing_lines),
|
|
510
|
+
"ratio": round(ratio, 2),
|
|
511
|
+
"decision": "ask_edit_rewrite",
|
|
512
|
+
"model": resolve_event_model(transcript_path, session_id),
|
|
513
|
+
},
|
|
514
|
+
)
|
|
515
|
+
except Exception:
|
|
516
|
+
pass
|
|
517
|
+
return {
|
|
518
|
+
"decision": "ask",
|
|
519
|
+
"reason": (
|
|
520
|
+
f"TokenSafe Output Guard: this Edit re-emits ~{ratio:.0%} of '{os.path.basename(file_path)}' "
|
|
521
|
+
f"({replacement_tokens} vs {file_tokens} tokens). Prefer apply_edits with narrow hunks "
|
|
522
|
+
f"(target + replacement); use a true rewrite only when the file really changes wholesale."
|
|
523
|
+
),
|
|
524
|
+
"saved_tokens": max(0, replacement_tokens - max(1, replacement_tokens // 4)),
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def guard_batch_payload(
|
|
529
|
+
tool_input: Dict[str, Any],
|
|
530
|
+
agent: str = "",
|
|
531
|
+
session_id: str = "",
|
|
532
|
+
transcript_path: str = "",
|
|
533
|
+
) -> Dict[str, Any]:
|
|
534
|
+
"""PreToolUse cap for apply_edits/apply_patch payloads (defense in depth:
|
|
535
|
+
batch_editor enforces the same limits at execution time)."""
|
|
536
|
+
result = {"decision": "allow", "reason": ""}
|
|
537
|
+
max_chars = _env_int("TOKENSAFE_MAX_BATCH_CHARS", 600_000)
|
|
538
|
+
max_replacement = _env_int("TOKENSAFE_MAX_REPLACEMENT_CHARS", 200_000)
|
|
539
|
+
max_hunks = _env_int("TOKENSAFE_MAX_HUNKS_PER_FILE", 200)
|
|
540
|
+
|
|
541
|
+
patch = tool_input.get("patch") or tool_input.get("input")
|
|
542
|
+
if isinstance(patch, str) and len(patch) > max_chars:
|
|
543
|
+
return {"decision": "deny", "reason": f"TokenSafe Output Guard: patch payload is {len(patch):,} chars (cap {max_chars:,})."}
|
|
544
|
+
|
|
545
|
+
items = tool_input.get("edits")
|
|
546
|
+
if not isinstance(items, list):
|
|
547
|
+
return result
|
|
548
|
+
total = 0
|
|
549
|
+
for item in items:
|
|
550
|
+
if not isinstance(item, dict):
|
|
551
|
+
continue
|
|
552
|
+
path = str(item.get("path") or "?")
|
|
553
|
+
create = item.get("create")
|
|
554
|
+
if isinstance(create, str):
|
|
555
|
+
if len(create) > max_replacement:
|
|
556
|
+
return {"decision": "deny", "reason": f"TokenSafe Output Guard: 'create' for {path} is {len(create):,} chars (cap {max_replacement:,})."}
|
|
557
|
+
total += len(create)
|
|
558
|
+
hunks = item.get("hunks")
|
|
559
|
+
if isinstance(hunks, list):
|
|
560
|
+
if len(hunks) > max_hunks:
|
|
561
|
+
return {"decision": "deny", "reason": f"TokenSafe Output Guard: {len(hunks)} hunks for {path} (cap {max_hunks})."}
|
|
562
|
+
for hunk in hunks:
|
|
563
|
+
if isinstance(hunk, dict):
|
|
564
|
+
total += len(str(hunk.get("target") or "")) + len(str(hunk.get("replacement") or ""))
|
|
565
|
+
if total > max_chars:
|
|
566
|
+
return {"decision": "deny", "reason": f"TokenSafe Output Guard: batch payload exceeds {max_chars:,} chars."}
|
|
567
|
+
return result
|
|
568
|
+
|
|
569
|
+
|
|
434
570
|
_CODE_EXTS = {
|
|
435
571
|
".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java", ".kt", ".swift",
|
|
436
572
|
".c", ".cpp", ".h", ".hpp", ".cs", ".rb", ".php", ".vue", ".svelte",
|
|
@@ -448,6 +584,11 @@ def canonical_tool_name(name: str) -> str:
|
|
|
448
584
|
return "edit"
|
|
449
585
|
if t in ("Read", "read_file", "view_file", "view_file_outline"):
|
|
450
586
|
return "read"
|
|
587
|
+
if t.lower() in (
|
|
588
|
+
"apply_edits", "tokensafe:apply_edits", "mcp__tokensafe__apply_edits",
|
|
589
|
+
"apply_patch", "applypatch",
|
|
590
|
+
):
|
|
591
|
+
return "batch_edit"
|
|
451
592
|
return t.lower()
|
|
452
593
|
|
|
453
594
|
|
|
@@ -691,6 +832,9 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
691
832
|
)
|
|
692
833
|
except Exception:
|
|
693
834
|
pass
|
|
835
|
+
rewrite = guard_edit_rewrite(file_path, tool_input, agent, session_id, transcript_path=tp)
|
|
836
|
+
if rewrite["decision"] == "ask":
|
|
837
|
+
return _cc_decision("ask", rewrite["reason"])
|
|
694
838
|
# Advisory only, and only for hosts whose PreToolUse schema documents
|
|
695
839
|
# additionalContext (Claude Code): omitting permissionDecision keeps the
|
|
696
840
|
# normal permission flow, while returning "allow" used to auto-approve edits.
|
|
@@ -706,6 +850,12 @@ def evaluate_cc_pre_tool_use(payload: Dict[str, Any], agent: str) -> Dict[str, A
|
|
|
706
850
|
}
|
|
707
851
|
return {}
|
|
708
852
|
|
|
853
|
+
if canon == "batch_edit":
|
|
854
|
+
verdict = guard_batch_payload(tool_input, agent, session_id, transcript_path=tp)
|
|
855
|
+
if verdict["decision"] == "deny":
|
|
856
|
+
return _cc_decision("deny", verdict["reason"])
|
|
857
|
+
return {}
|
|
858
|
+
|
|
709
859
|
if canon == "read":
|
|
710
860
|
file_path = _extract_path(tool_input)
|
|
711
861
|
verdict = guard_read(file_path, agent, session_id, transcript_path=tp)
|
|
@@ -740,13 +890,17 @@ def format_cumulative_banner(tracker: Optional[Any] = None) -> str:
|
|
|
740
890
|
saved = int(s.get("total_saved_tokens") or 0)
|
|
741
891
|
if saved <= 0:
|
|
742
892
|
return ""
|
|
743
|
-
|
|
893
|
+
steps = int(s.get("total_events") or 0)
|
|
744
894
|
if saved >= 1_000_000:
|
|
745
895
|
tok_str = f"{saved / 1_000_000:.2f}M"
|
|
746
896
|
elif saved >= 1_000:
|
|
747
897
|
tok_str = f"{saved / 1_000:.1f}K"
|
|
748
898
|
else:
|
|
749
899
|
tok_str = f"{saved:,}"
|
|
750
|
-
|
|
900
|
+
# Tokens and steps only: no dollar estimate is shown, since a saved
|
|
901
|
+
# token is a counterfactual delta whose price depends on the provider
|
|
902
|
+
# (cache hit vs miss vs output) and is not knowable locally.
|
|
903
|
+
suffix = f" | {steps:,} step" + ("" if steps == 1 else "s") if steps else ""
|
|
904
|
+
return f"[TokenSafe Cumulative: {tok_str} tokens saved{suffix}]"
|
|
751
905
|
except Exception:
|
|
752
906
|
return ""
|