tokensafe 4.5.0 → 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.
- package/.codex-plugin/plugin.json +1 -1
- package/bin/agy-tokens +10 -1
- package/bin/tokensafe.js +2 -1
- package/hooks/claude_code_hook.py +38 -126
- package/hooks/cursor_hook.py +45 -1
- package/hooks/kimi_hook.py +46 -90
- package/hooks/pre_invocation.py +23 -4
- package/hooks/pre_tool_use.py +40 -22
- package/hooks/session_start.py +28 -10
- package/hooks/zcode_hook.py +95 -0
- package/hooks.json +1 -1
- package/kimi.plugin.json +17 -1
- package/mcp_config.json +10 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +24 -24
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +61 -86
- package/skills/token-optimizer/references/mcp-tools.md +32 -132
- package/src/adapter_core.py +231 -7
- package/src/batch_editor.py +73 -22
- package/src/batch_search.py +31 -11
- package/src/burn_monitor.py +581 -0
- package/src/cache_normalizer.py +2 -0
- package/src/cli.py +34 -4
- package/src/compactor.py +1 -1
- package/src/dashboard.py +17 -9
- package/src/diff_slicer.py +1 -1
- package/src/distiller.py +11 -1
- package/src/environment_auditor.py +30 -6
- package/src/format_parsers/ansi.py +1 -1
- package/src/format_parsers/lockfiles.py +22 -17
- package/src/format_parsers/tabular.py +6 -3
- package/src/fts_index.py +26 -20
- package/src/governor.py +2 -2
- package/src/graph_engine.py +31 -9
- package/src/guard.py +3 -3
- package/src/image_downscale.py +26 -0
- package/src/installer.py +61 -48
- package/src/license_manager.py +49 -16
- package/src/live_relay.py +9 -8
- package/src/mcp_server.py +487 -48
- package/src/metrics.py +10 -1
- package/src/mistakes.py +4 -2
- package/src/paths.py +4 -1
- package/src/proxy.py +302 -123
- package/src/result_ledger.py +39 -1
- package/src/schema_slicer.py +40 -18
- package/src/scoped_search.py +66 -23
- package/src/skeletonizer.py +22 -11
- package/src/slicer.py +6 -4
- package/src/stash.py +37 -7
- package/src/superseded.py +42 -23
- package/src/syntax_guard.py +2 -0
- package/src/team_cache.py +3 -0
- package/src/telemetry_sync.py +66 -53
- package/src/thinking_fold.py +50 -12
- package/src/transcript_analyzer.py +270 -68
- package/src/treesitter_backend.py +2 -0
- package/src/type_slicer.py +60 -18
- package/src/version_checker.py +1 -1
- 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
|
|
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`).
|
|
51
|
-
"2. **Mandatory Symbol &
|
|
52
|
-
"3. **Repeat Read Deduplication**: Never
|
|
53
|
-
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler
|
|
54
|
-
"5. **
|
|
55
|
-
"6. **
|
|
56
|
-
"7. **
|
|
57
|
-
"8. **
|
|
58
|
-
"9. **
|
|
59
|
-
"10. **
|
|
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
|
-
"
|
|
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
|
-
"
|
|
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: ~
|
|
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
|
|
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
|
|
78
|
-
"`tokensafe:scoped_search
|
|
79
|
-
"`tokensafe:
|
|
80
|
-
"
|
|
81
|
-
"
|
|
82
|
-
"
|
|
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
|
|
265
|
-
|
|
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, "
|
|
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.
|
|
358
|
-
#
|
|
359
|
-
#
|
|
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
|
-
|
|
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": [
|
|
378
|
+
"args": [expected],
|
|
369
379
|
"timeoutMs": 10000,
|
|
370
380
|
}]}
|
|
371
381
|
|
|
372
|
-
def _sync_zcode_event(event_name: str
|
|
373
|
-
entry = _zcode_entry(
|
|
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(
|
|
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"
|
|
399
|
-
_sync_zcode_event("UserPromptSubmit"
|
|
400
|
-
_sync_zcode_event("PreToolUse"
|
|
401
|
-
_sync_zcode_event("PostToolUse"
|
|
402
|
-
_sync_zcode_event("Stop"
|
|
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)
|
package/src/license_manager.py
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
595
|
-
|
|
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
|
-
|
|
607
|
-
if
|
|
608
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
625
|
-
mirror_paths.append(os.path.join(
|
|
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 (
|
|
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
|
-
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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 =
|
|
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.
|
|
103
|
+
with self._lock:
|
|
104
|
+
self._flushing = False
|
|
104
105
|
|
|
105
106
|
|
|
106
107
|
LIVE_RELAY = LiveRelay()
|