tokensafe 4.4.9 → 4.5.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 (65) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +44 -15
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +24 -1
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -21
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -76
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +403 -0
  22. package/src/batch_search.py +428 -0
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +85 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +232 -52
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_proxy.py +13 -7
  43. package/src/mcp_server.py +758 -26
  44. package/src/metrics.py +10 -1
  45. package/src/mistakes.py +4 -2
  46. package/src/oumv_gateway.py +81 -7
  47. package/src/paths.py +4 -1
  48. package/src/proxy.py +302 -123
  49. package/src/result_ledger.py +39 -1
  50. package/src/schema_slicer.py +40 -18
  51. package/src/scoped_search.py +66 -23
  52. package/src/skeletonizer.py +22 -11
  53. package/src/slicer.py +6 -4
  54. package/src/snapshot.py +249 -0
  55. package/src/stash.py +37 -7
  56. package/src/superseded.py +42 -23
  57. package/src/syntax_guard.py +86 -0
  58. package/src/team_cache.py +3 -0
  59. package/src/telemetry_sync.py +66 -53
  60. package/src/thinking_fold.py +50 -12
  61. package/src/transcript_analyzer.py +483 -0
  62. package/src/treesitter_backend.py +2 -0
  63. package/src/type_slicer.py +60 -18
  64. package/src/version_checker.py +1 -1
  65. package/src/web_reader.py +55 -22
package/src/installer.py CHANGED
@@ -46,41 +46,36 @@ def _app_data_dir(*parts: str) -> str:
46
46
 
47
47
  UNIFIED_TOKENSAFE_RULE = (
48
48
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
49
- "Always use `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
50
- "1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard. To search for text, symbols, or functions across unknown files, ALWAYS call `tokensafe:scoped_search(query, path='.', scope='code')`. The `path` parameter accepts the project root or subfolder (`'.'`), and `scope` accepts categories (`'code'`, `'config'`, `'all'`), extensions (`'go'`, `'ts'`), or subfolders (`'internal/promo'`).\n"
51
- "2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `'src/service.ts'` or absolute) and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).\n"
52
- "3. **Repeat Read Deduplication**: Never repeatedly re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`); pass `force_full=true` only if context was compacted or you are a fresh subagent.\n"
53
- "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler, courtesy preambles, and sign-offs. Provide concise bullet prose. Never reprint full unmodified files or lengthy boilerplate; link to file line ranges (`file.ts#L10-L25`) and output surgical diffs.\n"
54
- "5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` to inspect project God Nodes and key dependency hubs in < 250 tokens before reading individual files or searching (pass target project's absolute path in multi-repo setups).\n"
55
- "6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map without crawling files (pass target project's absolute path in multi-repo setups).\n"
56
- "7. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path='.', depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path='src'`).\n"
57
- "8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `git push` --no-progress, `git commit` hook protection, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build/typecheck commands like `npm run build`, `vite build`, `next build`, `cargo build`, `tsc`, `tsc --noEmit`, `npm run typecheck`, `npx eslint`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, `go test`) via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 1-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest`/`bun` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
58
- "9. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
59
- "10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage and Context Quality Score (Grade S-F); when it reports `warning` or `critical` (or Grade C/F), call `tokensafe:compact_conversation(transcript_path=...)` to fold history into a State Ledger with a 3-line Post-Compaction Orientation Digest before continuing.\n"
60
- "11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
61
- "Never hardcode real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Whenever a secret fallback attempt is blocked, state:\n"
49
+ "Always use `tokensafe` MCP tools (`smart_read_file`, `scoped_search`, `apply_edits`, `repo_map`, `session_context`, `oumv`, `run_helper`) over default raw file reads or high-output terminal executions.\n\n"
50
+ "1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). Use `tokensafe:scoped_search(query, path='.', scope='code')` for single searches (`mode='auto'|'text'|'regex'|'glob'|'fuzzy'|'git'`) or `queries=[...]` for up to 20 concurrent queries in one call.\n"
51
+ "2. **Mandatory Symbol, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
52
+ "3. **Repeat Read Deduplication**: Never re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`).\n"
53
+ "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`.\n"
54
+ "5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For any codebase inquiry or refactor, FIRST call `tokensafe:repo_map(view='graph', project_path=...)` for God Nodes (<250 tokens). Use `view='api'` for exported types/interfaces and `view='tree'` instead of `ls -la`.\n"
55
+ "6. **Utilities (`run_helper`)**: Use `tokensafe:run_helper(action=...)` for rare/auxiliary operations: `'sanitize'` (rewrite shell/test commands), `'guard'` (pre-flight secret/safety audit), `'diff'` (slice diff), `'deps'` (lockfile point lookup), `'web'` (fetch clean Markdown), `'expand'` (restore `#hash`), `'image'` (downscale >1024px), and `'compress'` (TOCP prompt).\n"
56
+ "7. **Compact Tests & Build Output**: Run noisy commands, builds, and test suites via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]` (clean 1-line summary on pass, full trace on failure; never leave `vitest`/`jest`/`bun` in watch mode).\n"
57
+ "8. **Styles & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `smart_read_file` preserves design tokens (`:root`, `@theme`, CSS variables) in full.\n"
58
+ "9. **Session & Context Hygiene (`session_context`)**: Call `tokensafe:session_context(action='budget', model=...)` before large tasks. On `warning`/`critical` or Grade C/F, call `action='compact'` (with `transcript_path`). Use `action='prune'` for superseded reads, `action='mistakes'` for anti-stuck memory, and `action='metrics'` for savings analytics.\n"
59
+ "10. **Secret Leak Prevention (Zero Hardcoded Fallbacks)**: Never hardcode real private keys, API secrets, or webhook secrets as fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. Whenever blocked, state:\n"
62
60
  "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
63
- "12. **Proof-of-Savings Turn Footer (strictly English)**:\n"
64
- "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer. The ENTIRE footer is product-facing copy — 100% English, including the savings breakdown in parentheses, regardless of the chat language:\n"
61
+ "11. **Proof-of-Savings Turn Footer (strictly English)**: Append on tool-using turns:\n"
65
62
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
66
- "13. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.\n"
67
- "14. **Universal OUMV Protocol (Runtime Introspection & Verification)**: For live Frontend (ports 5173/3000) and Backend (ports 8080/8000) services, inspect connectivity via `tokensafe:oumv_status()`. Observe state progressively: `tokensafe:oumv_observe(level='L0')` for pulse (~20 tokens), `L1` for endpoints/models surface (~150 tokens), `L2` for target contracts or DTO schemas. Never guess state flows — query runtime causality via `tokensafe:oumv_understand(query='causality')` or `why_state`. Verify actions in-memory inside transactional sandboxes with automatic DB rollback via `tokensafe:oumv_verify(target='POST /api/...', payload={...})` instead of heavy browser runs or blind shell curls.\n"
63
+ "12. **Universal OUMV Protocol (`oumv`)**: Inspect live Frontend/Backend runtimes via `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` instead of headless browsers or blind shell curls.\n"
68
64
  )
69
65
 
70
66
  # Short pointer written into PROJECT-level rule files when the full protocol is
71
67
  # already installed at the agent-global level (~/.zcode/AGENTS.md etc.).
72
- # Keeps every session's meta-context lean: ~110 tokens instead of ~850.
68
+ # Keeps every session's meta-context lean: ~100 tokens instead of ~700.
73
69
  POINTER_RULE = (
74
70
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
75
- "The full 14-point protocol is installed globally in the agent-level instructions "
71
+ "The full protocol is installed globally in the agent-level instructions "
76
72
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
77
- "Core rules: never raw grep/find or `ls -la` — use `tokensafe:get_architecture_graph(project_path)` first for God Nodes, "
78
- "`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:slice_external_type`, `tokensafe:query_dependency`, "
79
- "`tokensafe:smart_bundle` and `tokensafe:list_dir`; "
80
- "use `tokensafe:oumv_status`, `tokensafe:oumv_observe(L0/L1/L2)`, `tokensafe:oumv_understand` and `tokensafe:oumv_verify` for live runtime introspection; "
81
- "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
82
- "before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
83
- "fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
73
+ "Core tools: `tokensafe:repo_map(view='graph'|'api'|'tree')` for architecture & directory trees, "
74
+ "`tokensafe:scoped_search` (single or `queries` batch, never raw grep/find), `tokensafe:smart_read_file` (symbol, `targets` bundle, or `.d.ts` `package_name`), "
75
+ "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` for live runtime introspection/verification, "
76
+ "`tokensafe:session_context(action='budget'|'compact'|'prune'|'mistakes')` for context & anti-stuck hygiene, and "
77
+ "`tokensafe:run_helper(action='sanitize'|'guard'|'diff'|'deps'|'web'|'expand'|'image'|'compress')`; "
78
+ "never hardcode secret fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
84
79
  )
85
80
 
86
81
  AGENTS_REGISTRY = {
@@ -261,14 +256,22 @@ class AgentInstaller:
261
256
  return f'[[hooks]]\nevent = "{event}"\n{m}command = {toml_hook_cmd}\ntimeout = 10\n'
262
257
 
263
258
  if "kimi_hook.py" in content:
264
- # Migration: older installs lack the PostToolUse output-compaction hook.
265
- if 'event = "PostToolUse"' in content:
259
+ # Migration: older installs lack PostToolUse, PreToolUse Edit matcher, or Stop.
260
+ migrated = False
261
+ if 'event = "PostToolUse"' not in content:
262
+ content = content.rstrip() + "\n\n# TokenSafe PostToolUse stdout compaction (migration)\n" + _kimi_section("PostToolUse")
263
+ migrated = True
264
+ if 'matcher = "Edit"' not in content:
265
+ content = content.rstrip() + "\n\n# TokenSafe PreToolUse Edit guard (migration)\n" + _kimi_section("PreToolUse", "Edit")
266
+ migrated = True
267
+ if 'event = "Stop"' not in content:
268
+ content = content.rstrip() + "\n\n# TokenSafe Stop telemetry/fold (migration)\n" + _kimi_section("Stop")
269
+ migrated = True
270
+ if not migrated:
266
271
  return True, "TokenSafe Kimi Code hooks already registered in config.toml"
267
- post_section = "\n# TokenSafe PostToolUse stdout compaction (migration)\n" + _kimi_section("PostToolUse")
268
- content = content.rstrip() + "\n" + post_section
269
272
  with open(config_file, "w", encoding="utf-8") as f:
270
273
  f.write(content)
271
- return True, "PostToolUse hook migrated in ~/.kimi-code/config.toml (stdout compaction)"
274
+ return True, "Kimi Code hooks migrated in ~/.kimi-code/config.toml (Edit/PostToolUse/Stop)"
272
275
 
273
276
  hook_sections = (
274
277
  '\n# TokenSafe Lifecycle Hooks\n'
@@ -276,8 +279,10 @@ class AgentInstaller:
276
279
  + _kimi_section("UserPromptSubmit") + "\n"
277
280
  + _kimi_section("PreToolUse", "Bash") + "\n"
278
281
  + _kimi_section("PreToolUse", "Write") + "\n"
282
+ + _kimi_section("PreToolUse", "Edit") + "\n"
279
283
  + _kimi_section("PreToolUse", "Read") + "\n"
280
- + _kimi_section("PostToolUse")
284
+ + _kimi_section("PostToolUse") + "\n"
285
+ + _kimi_section("Stop")
281
286
  )
282
287
  content = (content.rstrip() + "\n" + hook_sections) if content.strip() else hook_sections.lstrip()
283
288
  with open(config_file, "w", encoding="utf-8") as f:
@@ -294,6 +299,7 @@ class AgentInstaller:
294
299
  prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
295
300
  bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
296
301
  write_entry = {"matcher": "Write", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
302
+ read_entry = {"matcher": "Read", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
297
303
  session_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
298
304
  post_bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
299
305
  # Stale-edit guard: PreToolUse asks on externally-changed targets;
@@ -337,6 +343,7 @@ class AgentInstaller:
337
343
  _sync_claude_event("UserPromptSubmit", prompt_entry),
338
344
  _sync_claude_event("PreToolUse", bash_entry),
339
345
  _sync_claude_event("PreToolUse", write_entry),
346
+ _sync_claude_event("PreToolUse", read_entry),
340
347
  _sync_claude_event("PreToolUse", stale_edit_entry),
341
348
  _sync_claude_event("PostToolUse", post_bash_entry),
342
349
  _sync_claude_event("PostToolUse", post_track_entry),
@@ -354,24 +361,26 @@ class AgentInstaller:
354
361
  if err or data is None:
355
362
  return False, err or f"Failed to parse {config_file}"
356
363
  # ZCode configuration-file hooks are disabled by default and only run
357
- # with enabled=true. The bundled hook scripts already speak the ZCode
358
- # contract (injectSteps/systemMessage outputs + decision/reason), so
359
- # registration is pure plumbing — no adapter shim needed.
364
+ # with enabled=true. Register the dedicated zcode_hook.py adapter
365
+ # (Claude-Code-compatible PreToolUse/PostToolUse/SessionStart contract
366
+ # + live burn alerts) and upgrade any legacy Antigravity script entries.
360
367
  hooks_block = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
361
368
  hooks_block["enabled"] = True
362
369
  events = hooks_block.get("events") if isinstance(hooks_block.get("events"), dict) else {}
363
370
 
364
- def _zcode_entry(script_name: str) -> dict:
371
+ legacy_scripts = ("session_start.py", "pre_invocation.py", "pre_tool_use.py", "post_tool_use.py", "stop_hook.py")
372
+ expected = os.path.join(PROJECT_ROOT, "hooks", "zcode_hook.py")
373
+
374
+ def _zcode_entry() -> dict:
365
375
  return {"hooks": [{
366
376
  "type": "process",
367
377
  "command": PYTHON_BIN,
368
- "args": [os.path.join(PROJECT_ROOT, "hooks", script_name)],
378
+ "args": [expected],
369
379
  "timeoutMs": 10000,
370
380
  }]}
371
381
 
372
- def _sync_zcode_event(event_name: str, script_name: str) -> bool:
373
- entry = _zcode_entry(script_name)
374
- expected = os.path.join(PROJECT_ROOT, "hooks", script_name)
382
+ def _sync_zcode_event(event_name: str) -> bool:
383
+ entry = _zcode_entry()
375
384
  entries = events.get(event_name)
376
385
  if not isinstance(entries, list):
377
386
  events[event_name] = [entry]
@@ -384,9 +393,10 @@ class AgentInstaller:
384
393
  args = h.get("args") if isinstance(h, dict) else None
385
394
  if not isinstance(args, list):
386
395
  continue
387
- if any(isinstance(a, str) and a.endswith(script_name) for a in args):
396
+ if any(isinstance(a, str) and (a.endswith("zcode_hook.py") or any(a.endswith(s) for s in legacy_scripts)) for a in args):
388
397
  seen = True
389
- if args[-1] != expected:
398
+ if args[-1] != expected or h.get("command") != PYTHON_BIN:
399
+ h["command"] = PYTHON_BIN
390
400
  args[-1] = expected
391
401
  dirty = True
392
402
  if not seen:
@@ -395,11 +405,11 @@ class AgentInstaller:
395
405
  return dirty
396
406
 
397
407
  changed = any([
398
- _sync_zcode_event("SessionStart", "session_start.py"),
399
- _sync_zcode_event("UserPromptSubmit", "pre_invocation.py"),
400
- _sync_zcode_event("PreToolUse", "pre_tool_use.py"),
401
- _sync_zcode_event("PostToolUse", "post_tool_use.py"),
402
- _sync_zcode_event("Stop", "stop_hook.py"),
408
+ _sync_zcode_event("SessionStart"),
409
+ _sync_zcode_event("UserPromptSubmit"),
410
+ _sync_zcode_event("PreToolUse"),
411
+ _sync_zcode_event("PostToolUse"),
412
+ _sync_zcode_event("Stop"),
403
413
  ])
404
414
  if changed:
405
415
  hooks_block["events"] = events
@@ -438,7 +448,10 @@ class AgentInstaller:
438
448
  changed = any([
439
449
  _sync_cursor_event("beforeShellExecution"),
440
450
  _sync_cursor_event("beforeReadFile"),
451
+ _sync_cursor_event("beforeEditFile"),
441
452
  _sync_cursor_event("beforeSubmitPrompt"),
453
+ _sync_cursor_event("afterFileEdit"),
454
+ _sync_cursor_event("stop"),
442
455
  ])
443
456
  if not changed:
444
457
  return True, "TokenSafe Cursor hooks already registered"
@@ -548,7 +561,7 @@ class AgentInstaller:
548
561
  if not isinstance(events, dict):
549
562
  return True, "No events in ZCode hooks"
550
563
 
551
- tokensafe_scripts = ("session_start.py", "pre_invocation.py", "pre_tool_use.py", "post_tool_use.py", "stop_hook.py")
564
+ tokensafe_scripts = ("zcode_hook.py", "session_start.py", "pre_invocation.py", "pre_tool_use.py", "post_tool_use.py", "stop_hook.py")
552
565
  changed = False
553
566
  for event_name in list(events.keys()):
554
567
  entries = events.get(event_name)
@@ -5,6 +5,7 @@ Compatible with Stripe webhook lifecycle and B2B on-premise proxy deployments.
5
5
  """
6
6
 
7
7
  import os
8
+ import re
8
9
  import sys
9
10
  import json
10
11
  import time
@@ -233,7 +234,7 @@ class LicenseManager:
233
234
  with urllib.request.urlopen(req, timeout=2.5, context=shared_ssl_context()) as resp:
234
235
  data = json.loads(resp.read().decode("utf-8") or "{}")
235
236
  license_key = str(data.get("license_key", "") or "")
236
- if resp.status != 200 or not data.get("success") or not license_key:
237
+ if resp.status != 200 or not (data.get("success") or data.get("ok")) or not license_key:
237
238
  raise ValueError(str(data.get("error") or "empty community license response"))
238
239
 
239
240
  ok, msg = cls.save_license(license_key)
@@ -479,7 +480,7 @@ class LicenseManager:
479
480
 
480
481
  if best_valid is not None:
481
482
  return (best_valid[1], best_valid[2]), best_valid[1]
482
- return None, (best_raw[1] if best_raw is not None else "")
483
+ return None, ""
483
484
 
484
485
  @classmethod
485
486
  def get_active_license(cls) -> Tuple[str, Dict[str, Any]]:
@@ -555,7 +556,7 @@ class LicenseManager:
555
556
  with urllib.request.urlopen(req, timeout=3.5, context=shared_ssl_context()) as resp:
556
557
  data = json.loads(resp.read().decode("utf-8") or "{}")
557
558
  new_key = data.get("license_key", "")
558
- if resp.status == 200 and data.get("success") and new_key:
559
+ if resp.status == 200 and (data.get("success") or data.get("ok")) and new_key:
559
560
  ok, msg = cls.save_license(new_key, device_token=device_token)
560
561
  return ok, msg
561
562
  return False, str(data.get("error") or "refresh_failed")
@@ -582,47 +583,77 @@ class LicenseManager:
582
583
  "saved_at": int(time.time())
583
584
  }
584
585
 
586
+ wrote_any = False
587
+ last_err = None
585
588
  for target_file in cls._candidate_license_files():
586
589
  target_dir = os.path.dirname(target_file)
590
+ tmp_path = f"{target_file}.tmp.{os.getpid()}.{threading.get_ident()}"
587
591
  try:
588
592
  if target_dir:
589
593
  os.makedirs(target_dir, exist_ok=True)
590
- tmp_path = f"{target_file}.tmp.{os.getpid()}"
591
594
  with open(tmp_path, "w", encoding="utf-8") as f:
592
595
  json.dump(record, f, indent=2)
593
596
  os.replace(tmp_path, target_file)
594
- except Exception:
595
- pass
597
+ wrote_any = True
598
+ except Exception as exc:
599
+ last_err = exc
600
+ try:
601
+ if os.path.exists(tmp_path):
602
+ os.unlink(tmp_path)
603
+ except OSError:
604
+ pass
605
+
606
+ if not wrote_any:
607
+ return False, f"Failed to write license file: {last_err}"
596
608
 
597
609
  tier_name = payload.get("tier", "").upper()
598
610
  trial_note = " (7-Day Trial)" if payload.get("trial") else ""
599
611
  return True, f"Successfully activated TokenSafe {tier_name}{trial_note}!"
600
612
 
613
+ @staticmethod
614
+ def _tracker_state_dir(tracker: Optional[Any] = None) -> Optional[str]:
615
+ if tracker is not None:
616
+ from pathlib import PurePath
617
+ db_p = getattr(tracker, "db_path", None)
618
+ if isinstance(db_p, (str, PurePath)) and str(db_p).strip():
619
+ try:
620
+ return os.path.dirname(os.path.abspath(str(db_p)))
621
+ except Exception:
622
+ return None
623
+ return None
624
+
601
625
  @classmethod
602
626
  def _get_server_quota_floor(cls, tracker: Optional[Any] = None) -> int:
603
627
  """Reads server-verified quota floor from mirror ledger (.qledger.json) within 30-day window."""
604
628
  if tracker and hasattr(tracker, "get_server_quota_floor"):
605
629
  try:
606
- floor = int(tracker.get_server_quota_floor() or 0)
607
- if floor > 0:
608
- return floor
630
+ raw_floor = tracker.get_server_quota_floor()
631
+ if isinstance(raw_floor, (int, float)):
632
+ floor = int(raw_floor)
633
+ if floor > 0:
634
+ return floor
609
635
  except Exception:
610
636
  pass
611
637
  try:
612
638
  mirror_paths = []
613
639
  if tracker and hasattr(tracker, "_quota_mirror_path"):
614
640
  try:
615
- mirror_paths.append(tracker._quota_mirror_path())
641
+ from pathlib import PurePath
642
+ mp = tracker._quota_mirror_path()
643
+ if isinstance(mp, (str, PurePath)):
644
+ mirror_paths.append(str(mp))
616
645
  except Exception:
617
646
  pass
618
- base_dir = os.environ.get("TOKENSAFE_DATA_DIR") or (
647
+ tracker_dir = cls._tracker_state_dir(tracker)
648
+ base_dir = tracker_dir or os.environ.get("TOKENSAFE_DATA_DIR") or (
619
649
  os.path.dirname(os.environ["TOKENSAFE_DB_PATH"]) if os.environ.get("TOKENSAFE_DB_PATH") else None
620
650
  )
621
651
  if base_dir:
622
652
  mirror_paths.append(os.path.join(base_dir, ".qledger.json"))
623
653
  else:
624
- mirror_paths.append(os.path.join(os.path.dirname(DATA_DIR), ".qledger.json"))
625
- mirror_paths.append(os.path.join(DATA_DIR, ".qledger.json"))
654
+ cur_data_dir = resolve_data_dir()
655
+ mirror_paths.append(os.path.join(os.path.dirname(cur_data_dir), ".qledger.json"))
656
+ mirror_paths.append(os.path.join(cur_data_dir, ".qledger.json"))
626
657
 
627
658
  for mirror_path in mirror_paths:
628
659
  if os.path.exists(mirror_path):
@@ -695,11 +726,11 @@ class LicenseManager:
695
726
  local_saved = tracker.get_monthly_saved_tokens() if tracker else 0
696
727
  server_floor = cls._get_server_quota_floor(tracker)
697
728
 
698
- # Guest state backup floor (prevents simple metrics.db deletion within same calendar month)
729
+ # Guest state backup floor (scoped to tracker dir when explicit db_path is provided)
699
730
  guest_floor = 0
700
731
  if tier == "guest":
701
732
  try:
702
- data_dir = resolve_data_dir()
733
+ data_dir = cls._tracker_state_dir(tracker) or resolve_data_dir()
703
734
  gstate_file = os.path.join(data_dir, "guest_state.json")
704
735
  cur_month = time.strftime("%Y-%m")
705
736
  if os.path.exists(gstate_file):
@@ -709,8 +740,10 @@ class LicenseManager:
709
740
  guest_floor = int(gdata.get("saved_tokens", 0) or 0)
710
741
  if local_saved > guest_floor:
711
742
  os.makedirs(data_dir, exist_ok=True)
712
- with open(gstate_file, "w", encoding="utf-8") as gf:
743
+ tmp_gf = f"{gstate_file}.tmp.{os.getpid()}.{threading.get_ident()}"
744
+ with open(tmp_gf, "w", encoding="utf-8") as gf:
713
745
  json.dump({"month": cur_month, "saved_tokens": local_saved}, gf)
746
+ os.replace(tmp_gf, gstate_file)
714
747
  except Exception:
715
748
  pass
716
749
 
package/src/live_relay.py CHANGED
@@ -52,8 +52,8 @@ class LiveRelay:
52
52
  try:
53
53
  ev = {
54
54
  "type": str(event_type or "session")[:40],
55
- "saved_tokens": min(10_000_000, max(0, int(data.get("saved_tokens") or data.get("tokens_saved") or 0))),
56
- "usd_saved": min(10000.0, max(0.0, float(data.get("usd_saved") or data.get("usd") or 0.0))),
55
+ "saved_tokens": min(10_000_000, max(0, int(data.get("saved_tokens") or data.get("tokens_saved") or data.get("total_saved_tokens") or 0))),
56
+ "usd_saved": min(10000.0, max(0.0, float(data.get("usd_saved") or data.get("usd") or data.get("total_usd_saved") or 0.0))),
57
57
  "model": str(data.get("model") or "")[:40],
58
58
  "machine": str(data.get("machine") or _machine_hash())[:64],
59
59
  "ts": time.time(),
@@ -67,16 +67,16 @@ class LiveRelay:
67
67
  self.flush_async()
68
68
 
69
69
  def flush_async(self) -> None:
70
- if self._flushing:
71
- return
72
- self._flushing = True
70
+ with self._lock:
71
+ if self._flushing:
72
+ return
73
+ self._flushing = True
73
74
  threading.Thread(target=self._flush, daemon=True).start()
74
75
 
75
76
  def _flush(self) -> None:
76
77
  try:
77
78
  with self._lock:
78
- batch = list(self._ring)
79
- self._ring.clear()
79
+ batch = [self._ring.popleft() for _ in range(min(100, len(self._ring)))]
80
80
  self._last_flush = time.time()
81
81
  if not batch:
82
82
  return
@@ -100,7 +100,8 @@ class LiveRelay:
100
100
  except Exception:
101
101
  pass # live telemetry is best-effort and must never block the proxy
102
102
  finally:
103
- self._flushing = False
103
+ with self._lock:
104
+ self._flushing = False
104
105
 
105
106
 
106
107
  LIVE_RELAY = LiveRelay()
package/src/mcp_proxy.py CHANGED
@@ -21,33 +21,39 @@ from src.stash import stash_block
21
21
 
22
22
  MAX_UNFOLDED_CHARS = 1500
23
23
  MAX_UNFOLDED_LINES = 35
24
+ MAX_UNFOLDED_BYTES = 8800
24
25
  HEAD_LINES = 15
25
26
  TAIL_LINES = 10
26
27
 
27
28
 
28
29
  def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
29
- """Folds oversized text and returns (folded_text, was_folded)."""
30
+ """Folds oversized text and returns (folded_text, was_folded).
31
+ Strictly enforces MAX_UNFOLDED_BYTES (8800 bytes) to prevent disk spills."""
30
32
  if not text:
31
33
  return text, False
32
34
  from src.format_parsers.ansi import strip_ansi
33
35
  text = strip_ansi(text)
34
- if len(text) <= MAX_UNFOLDED_CHARS:
35
- return text, False
36
-
36
+ raw_bytes = len(text.encode("utf-8"))
37
37
  lines = text.splitlines()
38
- if len(lines) <= MAX_UNFOLDED_LINES:
38
+
39
+ if raw_bytes <= MAX_UNFOLDED_BYTES and len(text) <= MAX_UNFOLDED_CHARS and len(lines) <= MAX_UNFOLDED_LINES:
39
40
  return text, False
40
41
 
41
42
  hash8, marker = stash_block(text, source=f"mcp:{tool_name}")
42
43
  head = lines[:HEAD_LINES]
43
44
  tail = lines[-TAIL_LINES:]
44
- omitted = len(lines) - (HEAD_LINES + TAIL_LINES)
45
+ omitted = max(0, len(lines) - (len(head) + len(tail)))
45
46
 
46
47
  folded_lines = head + [
47
48
  f"... [{omitted} lines folded by TokenSafe MCP Proxy] ...",
48
49
  ] + tail + [marker]
50
+ folded_res = "\n".join(folded_lines)
51
+
52
+ if len(folded_res.encode("utf-8")) > MAX_UNFOLDED_BYTES:
53
+ allowed = MAX_UNFOLDED_BYTES - len(marker.encode("utf-8")) - 100
54
+ folded_res = text.encode("utf-8")[:allowed].decode("utf-8", errors="ignore") + f"\n... [folded]\n{marker}"
49
55
 
50
- return "\n".join(folded_lines), True
56
+ return folded_res, True
51
57
 
52
58
 
53
59
  def compact_mcp_response(resp: Dict[str, Any]) -> Dict[str, Any]: