tokensafe 4.14.0 → 4.15.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.
Files changed (45) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/hooks/claude_code_hook.py +8 -2
  3. package/hooks/cursor_hook.py +2 -1
  4. package/hooks/kimi_hook.py +2 -1
  5. package/hooks/post_tool_use.py +15 -1
  6. package/hooks/pre_invocation.py +22 -7
  7. package/hooks/pre_tool_use.py +13 -6
  8. package/hooks/session_start.py +7 -2
  9. package/hooks/stop_hook.py +2 -1
  10. package/hooks/zcode_hook.py +2 -1
  11. package/kimi.plugin.json +1 -1
  12. package/package.json +1 -1
  13. package/plugin.json +1 -1
  14. package/server.json +3 -3
  15. package/src/acp/server.py +5 -0
  16. package/src/adapter_core.py +6 -2
  17. package/src/auto_inject.py +6 -2
  18. package/src/cli.py +12 -2
  19. package/src/command_sanitizer.py +1 -1
  20. package/src/context_index.py +954 -0
  21. package/src/file_state.py +4 -3
  22. package/src/fts_index.py +12 -32
  23. package/src/graph_engine.py +43 -95
  24. package/src/guard.py +1 -1
  25. package/src/installer.py +65 -5
  26. package/src/license_manager.py +194 -1
  27. package/src/mcp_proxy.py +3 -0
  28. package/src/mcp_server.py +103 -5
  29. package/src/metrics.py +133 -26
  30. package/src/mistakes.py +45 -21
  31. package/src/oumv_gateway.py +17 -13
  32. package/src/paths.py +5 -12
  33. package/src/project_memory.py +264 -0
  34. package/src/result_ledger.py +40 -0
  35. package/src/retrofit.py +9 -4
  36. package/src/savings.py +9 -4
  37. package/src/scoped_search.py +93 -53
  38. package/src/session_brief.py +14 -3
  39. package/src/skeletonizer.py +44 -2
  40. package/src/snapshot.py +17 -1
  41. package/src/stdio_io.py +50 -0
  42. package/src/telemetry_sync.py +1 -1
  43. package/src/version_checker.py +1 -1
  44. package/src/win_paths.py +172 -0
  45. package/src/workspace_roots.py +2 -6
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.14.0",
2
+ "version": "4.15.1",
3
3
  "name": "tokensafe",
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
  "author": {
@@ -64,7 +64,12 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
64
64
  start_cwd = str(payload.get("cwd") or os.getcwd())
65
65
  if is_project_root(start_cwd):
66
66
  from src.graph_engine import GraphEngine
67
- banner = GraphEngine.get_instance(start_cwd).format_topology_banner()
67
+ # A warm index answers without a rescan; only a repo that has
68
+ # never been indexed pays the one-time crawl (the banner is the product).
69
+ graph = GraphEngine.get_cached(start_cwd)
70
+ if graph is None:
71
+ graph = GraphEngine.get_instance(start_cwd)
72
+ banner = graph.format_topology_banner()
68
73
  if banner:
69
74
  extra = (
70
75
  f"{extra}\n\n{banner}\n"
@@ -304,7 +309,8 @@ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
304
309
 
305
310
  def main():
306
311
  try:
307
- raw = sys.stdin.read()
312
+ from src.stdio_io import read_stdin_text
313
+ raw = read_stdin_text()
308
314
  payload = json.loads(raw) if raw.strip() else {}
309
315
  if not isinstance(payload, dict):
310
316
  payload = {}
@@ -126,7 +126,8 @@ def handle(event: str, payload: dict) -> dict:
126
126
 
127
127
  def main():
128
128
  try:
129
- raw = sys.stdin.read()
129
+ from src.stdio_io import read_stdin_text
130
+ raw = read_stdin_text()
130
131
  payload = json.loads(raw) if raw.strip() else {}
131
132
  if not isinstance(payload, dict):
132
133
  payload = {}
@@ -214,7 +214,8 @@ def handle(event: str, payload: dict) -> dict:
214
214
 
215
215
  def main():
216
216
  try:
217
- raw = sys.stdin.read()
217
+ from src.stdio_io import read_stdin_text
218
+ raw = read_stdin_text()
218
219
  payload = json.loads(raw) if raw.strip() else {}
219
220
  if not isinstance(payload, dict):
220
221
  payload = {}
@@ -35,7 +35,8 @@ def _should_skip_fast() -> bool:
35
35
  def main():
36
36
  raw = ""
37
37
  try:
38
- raw = sys.stdin.read()
38
+ from src.stdio_io import read_stdin_text
39
+ raw = read_stdin_text()
39
40
  except Exception:
40
41
  raw = ""
41
42
 
@@ -101,6 +102,19 @@ def main():
101
102
  )
102
103
  except Exception:
103
104
  pass
105
+
106
+ # Known-good commands: remember what actually passed here.
107
+ if cmd:
108
+ try:
109
+ from src.project_memory import ProjectMemory
110
+ hook_cwd = str(payload.get("cwd") or os.getcwd())
111
+ ProjectMemory(hook_cwd).record_command(
112
+ cmd,
113
+ cwd=hook_cwd,
114
+ exit_code=int(exit_code) if exit_code is not None else (1 if is_failed else 0),
115
+ )
116
+ except Exception:
117
+ pass
104
118
  except Exception:
105
119
  pass
106
120
 
@@ -21,7 +21,6 @@ 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 src.agent import context as kernel
25
24
  from src.adapter_core import TOKENSAFE_DIRECTIVES as PROTOCOL_DIRECTIVES, resolve_event_model
26
25
  from src.license_manager import LicenseManager
27
26
  from src.metrics import MetricsTracker
@@ -71,6 +70,19 @@ def _handle(payload: dict) -> dict:
71
70
  pass
72
71
 
73
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 = {}
74
86
  inject_steps = []
75
87
  workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
76
88
  hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
@@ -100,6 +112,7 @@ def _handle(payload: dict) -> dict:
100
112
  }
101
113
  })
102
114
  elif last_user_input and len(last_user_input.strip()) >= 5 and not _proxy_is_active():
115
+ from src.agent import context as kernel
103
116
  compaction = kernel.compact_prompt(last_user_input)
104
117
  saved_tokens = compaction["saved_tokens"]
105
118
  reduction_pct = compaction["reduction_pct"]
@@ -158,12 +171,13 @@ def _handle(payload: dict) -> dict:
158
171
  fresh_fold = False
159
172
  orig_hist_tokens = 0
160
173
  if not is_quota_exceeded and invocation_num >= 3 and transcript_path:
174
+ from src.agent import context as kernel
161
175
  folded_text, orig_hist_tokens, folded_tokens, stats = kernel.fold_history(
162
176
  transcript_path, invocation_num
163
177
  )
164
178
  if folded_text and stats.get("saved_tokens", 0) > 0:
165
179
  # Prevent quadratic double-counting: only record incremental new history mass
166
- prev_event = tracker.get_last_event(session_id=conversation_id, event_type="HISTORY_FOLD")
180
+ prev_event = recent_events.get("HISTORY_FOLD")
167
181
  prev_orig = 0
168
182
  if prev_event and isinstance(prev_event.get("details"), dict):
169
183
  prev_orig = prev_event["details"].get("total_accum_orig", 0) or prev_event.get("original_tokens", 0)
@@ -208,10 +222,10 @@ def _handle(payload: dict) -> dict:
208
222
  history_mass = kernel.measure_transcript(transcript_path)
209
223
 
210
224
  # 4. Adaptive Protocol Enforcement Reminder (Guard-triggered or fresh fold only)
211
- recent_guard = tracker.get_last_event(conversation_id, "GUARD_RAW_CODE_SEARCH")
225
+ recent_guard = recent_events.get("GUARD_RAW_CODE_SEARCH")
212
226
  guard_unreminded = False
213
227
  if isinstance(recent_guard, dict):
214
- last_remind = tracker.get_last_event(conversation_id, "PROTOCOL_REMINDER")
228
+ last_remind = recent_events.get("PROTOCOL_REMINDER")
215
229
  is_valid_remind = isinstance(last_remind, dict) and last_remind.get("event_type") == "PROTOCOL_REMINDER"
216
230
  if not is_valid_remind:
217
231
  guard_unreminded = True
@@ -255,7 +269,7 @@ def _handle(payload: dict) -> dict:
255
269
  used_pct = budget.get("used_pct")
256
270
  if (budget.get("measurement") == "measured"
257
271
  and used_pct is not None and used_pct >= 80):
258
- already = tracker.get_last_event(conversation_id, "BUDGET_WARNING")
272
+ already = recent_events.get("BUDGET_WARNING")
259
273
  if not already:
260
274
  if transcript_path:
261
275
  action = (f"Call tokensafe:session_context(action='compact', transcript_path='{transcript_path}') "
@@ -290,7 +304,7 @@ def _handle(payload: dict) -> dict:
290
304
  try:
291
305
  last_input = str(payload.get("lastUserInput") or payload.get("prompt") or "").strip()
292
306
  if invocation_num >= 2 and not last_input:
293
- if not tracker.get_last_event(conversation_id, "NOTIFICATION_TURN"):
307
+ if not recent_events.get("NOTIFICATION_TURN"):
294
308
  inject_steps.append({
295
309
  "systemMessage": {
296
310
  "systemMessage": "",
@@ -335,7 +349,8 @@ def _handle(payload: dict) -> dict:
335
349
 
336
350
  def main():
337
351
  try:
338
- raw_input = sys.stdin.read()
352
+ from src.stdio_io import read_stdin_text
353
+ raw_input = read_stdin_text()
339
354
  if not raw_input.strip():
340
355
  print(json.dumps({}))
341
356
  return
@@ -76,13 +76,10 @@ def _handle(payload: dict) -> dict:
76
76
  except Exception:
77
77
  pass
78
78
 
79
- tracker = MetricsTracker()
80
- quota = LicenseManager.check_quota(tracker)
81
- is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
82
-
83
- # 1. Loop Detector Guard (Applies to all tools)
79
+ # 1. Loop Detector Guard (Applies to all tools; one JSON file, cheap)
84
80
  is_loop, repeat_count, loop_msg = LoopDetector.check_loop(conversation_id, tool_name, args)
85
81
  if is_loop:
82
+ tracker = MetricsTracker()
86
83
  try:
87
84
  from src.mistakes import MistakesLedger
88
85
  MistakesLedger.record_from_loop(tool_name, args, repeat_count, project_root=hook_cwd)
@@ -100,6 +97,15 @@ def _handle(payload: dict) -> dict:
100
97
 
101
98
  response: dict = {"decision": "allow"}
102
99
 
100
+ # Search/list/other tools only ever answer "allow"; quota checks and event
101
+ # recording are skipped for them. The guarded set is read/write/edit/bash.
102
+ if canon_tool not in ("read", "write", "edit", "bash"):
103
+ return response
104
+
105
+ tracker = MetricsTracker()
106
+ quota = LicenseManager.check_quota(tracker)
107
+ is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
108
+
103
109
  # 1.5 Stale-file edit guard: when the target changed on disk since the
104
110
  # model last saw it (build output, linters, another session), the edit
105
111
  # either corrupts content or fails and forces a costly full re-read.
@@ -431,7 +437,8 @@ def _handle(payload: dict) -> dict:
431
437
 
432
438
  def main():
433
439
  try:
434
- raw_input = sys.stdin.read()
440
+ from src.stdio_io import read_stdin_text
441
+ raw_input = read_stdin_text()
435
442
  if not raw_input.strip():
436
443
  print(json.dumps({"decision": "allow"}))
437
444
  return
@@ -71,7 +71,8 @@ def _guest_pitch_step(quota: dict):
71
71
 
72
72
  def main():
73
73
  try:
74
- raw_input = sys.stdin.read()
74
+ from src.stdio_io import read_stdin_text
75
+ raw_input = read_stdin_text()
75
76
  if not raw_input.strip():
76
77
  print(json.dumps({}))
77
78
  return
@@ -105,7 +106,11 @@ def main():
105
106
  try:
106
107
  if workspace_paths:
107
108
  from src.graph_engine import GraphEngine
108
- graph = GraphEngine.get_instance(workspace_root)
109
+ # A warm index answers without a rescan; only a repo that has never
110
+ # been indexed pays the one-time crawl (the banner is the product).
111
+ graph = GraphEngine.get_cached(workspace_root)
112
+ if graph is None:
113
+ graph = GraphEngine.get_instance(workspace_root)
109
114
  banner = graph.format_topology_banner()
110
115
  extra = []
111
116
  if banner:
@@ -34,7 +34,8 @@ BUDGET_NUDGE_REASON = (
34
34
 
35
35
  def main():
36
36
  try:
37
- raw_input = sys.stdin.read()
37
+ from src.stdio_io import read_stdin_text
38
+ raw_input = read_stdin_text()
38
39
  if not raw_input.strip():
39
40
  print(json.dumps({}))
40
41
  return
@@ -58,7 +58,8 @@ def handle(event: str, payload: dict) -> dict:
58
58
 
59
59
  def main():
60
60
  try:
61
- raw = sys.stdin.read()
61
+ from src.stdio_io import read_stdin_text
62
+ raw = read_stdin_text()
62
63
  payload = json.loads(raw) if raw.strip() else {}
63
64
  if not isinstance(payload, dict):
64
65
  payload = {}
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.14.0",
3
+ "version": "4.15.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,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.14.0",
4
+ "version": "4.15.1",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.14.0",
4
+ "version": "4.15.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",
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.14.0",
6
+ "version": "4.15.1",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.14.0",
26
+ "version": "4.15.1",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.14.0",
42
+ "version": "4.15.1",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
package/src/acp/server.py CHANGED
@@ -440,6 +440,11 @@ def _version() -> str:
440
440
 
441
441
 
442
442
  def run_acp_server(provider_factory: Optional[Callable[[str, str], Provider]] = None) -> None:
443
+ # Windows pipes default to the ANSI code page; agent responses routinely
444
+ # carry non-Latin-1 text.
445
+ from src.stdio_io import ensure_utf8_stdio
446
+
447
+ ensure_utf8_stdio()
443
448
  # Editors expect the prompt; headless harnesses set off|all explicitly.
444
449
  policy = os.environ.get("TOKENSAFE_ACP_PERMISSIONS", "writes")
445
450
  server = AcpServer(sys.stdin, sys.stdout, provider_factory=provider_factory, permission_policy=policy)
@@ -740,13 +740,17 @@ def format_cumulative_banner(tracker: Optional[Any] = None) -> str:
740
740
  saved = int(s.get("total_saved_tokens") or 0)
741
741
  if saved <= 0:
742
742
  return ""
743
- usd = float(s.get("total_usd_saved") or 0.0)
743
+ steps = int(s.get("total_events") or 0)
744
744
  if saved >= 1_000_000:
745
745
  tok_str = f"{saved / 1_000_000:.2f}M"
746
746
  elif saved >= 1_000:
747
747
  tok_str = f"{saved / 1_000:.1f}K"
748
748
  else:
749
749
  tok_str = f"{saved:,}"
750
- return f"[TokenSafe Cumulative: {tok_str} tokens saved (~${usd:.2f} approx)]"
750
+ # Tokens and steps only: no dollar estimate is shown, since a saved
751
+ # token is a counterfactual delta whose price depends on the provider
752
+ # (cache hit vs miss vs output) and is not knowable locally.
753
+ suffix = f" | {steps:,} step" + ("" if steps == 1 else "s") if steps else ""
754
+ return f"[TokenSafe Cumulative: {tok_str} tokens saved{suffix}]"
751
755
  except Exception:
752
756
  return ""
@@ -893,6 +893,8 @@ def _node_package_dir(workspace: str, entrypoint: str) -> str:
893
893
 
894
894
  def _node_install_command(package_dir: str) -> Tuple[List[str], str]:
895
895
  """(argv, manager) for an exact install of the Node adapter package."""
896
+ from src.win_paths import resolve_executable
897
+
896
898
  package = f"{_NODE_PACKAGE}@{BACKEND_NPM_VERSION}"
897
899
  markers = (
898
900
  ("bun.lock", ["bun", "add"], "bun"),
@@ -903,8 +905,10 @@ def _node_install_command(package_dir: str) -> Tuple[List[str], str]:
903
905
  )
904
906
  for marker, prefix, manager in markers:
905
907
  if os.path.isfile(os.path.join(package_dir, marker)):
906
- return [*prefix, package], manager
907
- return ["npm", "install", "--save-exact", package], "npm"
908
+ binary = resolve_executable(prefix[0]) or prefix[0]
909
+ return [binary, *prefix[1:], package], manager
910
+ binary = resolve_executable("npm") or "npm"
911
+ return [binary, "install", "--save-exact", package], "npm"
908
912
 
909
913
 
910
914
  def _node_package_installed(package_dir: str) -> bool:
package/src/cli.py CHANGED
@@ -364,8 +364,8 @@ def main(argv: Optional[List[str]] = None):
364
364
  print(f" Data dir: {report['data_dir']}")
365
365
  print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
366
366
  print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
367
- print(f" Saved (pruned+sync): {report['pruned_synced_saved_tokens']:,} tokens")
368
- print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens (≈${report['usd_saved_approx']:.2f})")
367
+ print(f" Synced to cloud: {report['pruned_synced_saved_tokens']:,} tokens (subset of live)")
368
+ print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens")
369
369
  if last:
370
370
  print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
371
371
  print()
@@ -889,6 +889,9 @@ def main(argv: Optional[List[str]] = None):
889
889
  from src.retrofit import run_doctor
890
890
  if "--prune" in args[2:]:
891
891
  from src.oumv_gateway import OUMVGateway
892
+ from src.context_index import ContextIndex
893
+ from src.skeletonizer import Skeletonizer
894
+ from src.result_ledger import prune_archives
892
895
  removed = OUMVGateway.prune_stale_descriptors(os.getcwd())
893
896
  if removed:
894
897
  print("removed stale OUMV descriptors:")
@@ -896,6 +899,13 @@ def main(argv: Optional[List[str]] = None):
896
899
  print(f" - {path}")
897
900
  else:
898
901
  print("no stale OUMV descriptors to remove")
902
+ index_stats = ContextIndex.prune()
903
+ print(
904
+ f"pruned context indexes: {index_stats['removed']} "
905
+ f"({index_stats['freed_bytes'] // 1024} KB freed); "
906
+ f"skeletons: {Skeletonizer.prune()}; "
907
+ f"ledger archives: {prune_archives()}"
908
+ )
899
909
  return
900
910
  doc = run_doctor(os.getcwd())
901
911
  print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV DOCTOR ⚡\033[0m\n")
@@ -205,7 +205,7 @@ class CommandSanitizer:
205
205
  @classmethod
206
206
  def _split_tokens_safe(cls, stage: str) -> List[str]:
207
207
  try:
208
- return shlex.split(stage)
208
+ return shlex.split(stage, posix=(os.name != "nt"))
209
209
  except ValueError:
210
210
  return stage.split()
211
211