tokensafe 4.16.0 → 4.16.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/hooks.json +124 -0
- package/.claude-plugin/marketplace.json +15 -0
- package/.claude-plugin/plugin.json +21 -0
- package/.codex-plugin/plugin.json +1 -1
- package/.mcp.json +10 -0
- package/README.md +14 -0
- package/bin/tokensafe-claude-hook +18 -0
- package/bin/tokensafe-mcp +17 -0
- package/hooks/claude_code_hook.py +59 -0
- package/hooks/kimi_hook.py +27 -0
- package/hooks/pre_invocation.py +19 -0
- package/hooks/session_start.py +21 -0
- package/kimi.plugin.json +1 -1
- package/package.json +5 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/agent_firewall.py +2 -1
- package/src/angular_cli.py +14 -6
- package/src/auto_inject.py +581 -12
- package/src/batch_editor.py +62 -22
- package/src/cli.py +104 -0
- package/src/command_sanitizer.py +19 -7
- package/src/compaction_recovery.py +335 -0
- package/src/format_invariants.py +158 -0
- package/src/graph_engine.py +48 -0
- package/src/host_capabilities.py +180 -0
- package/src/installer.py +39 -5
- package/src/mcp_server.py +146 -7
- package/src/session_brief.py +1 -1
- package/src/statusline.py +44 -0
- package/src/telemetry_sync.py +1 -1
- package/src/transcript_recall.py +565 -0
- package/src/usage_ledger.py +13 -0
- package/src/version_checker.py +1 -1
package/src/mcp_server.py
CHANGED
|
@@ -48,7 +48,7 @@ from src.session_context import current_root, current_session_id
|
|
|
48
48
|
|
|
49
49
|
SERVER_INFO = {
|
|
50
50
|
"name": "tokensafe-mcp",
|
|
51
|
-
"version": "4.16.
|
|
51
|
+
"version": "4.16.2"
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -912,6 +912,9 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
912
912
|
'dep_mode': {'type': 'string', 'enum': ['signature', 'full']},
|
|
913
913
|
'include_deps': {'type': 'boolean'},
|
|
914
914
|
'force_full': {'type': 'boolean'},
|
|
915
|
+
'if_modified_since': {'type': 'string',
|
|
916
|
+
'description': 'ISO timestamp or nanosecond mtime from a previous '
|
|
917
|
+
'response; an unchanged file returns a one-line stub'},
|
|
915
918
|
'targets': {'type': 'array',
|
|
916
919
|
'maxItems': 8,
|
|
917
920
|
'items': {'type': 'object',
|
|
@@ -986,7 +989,7 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
986
989
|
'description': "Structure without crawling: view='graph' (God Nodes), 'api' (exports) or 'tree' "
|
|
987
990
|
'(directories).',
|
|
988
991
|
'inputSchema': {'type': 'object',
|
|
989
|
-
'properties': {'view': {'type': 'string', 'enum': ['graph', 'api', 'tree']},
|
|
992
|
+
'properties': {'view': {'type': 'string', 'enum': ['graph', 'api', 'tree', 'importers']},
|
|
990
993
|
'project_path': {'type': 'string',
|
|
991
994
|
'description': 'Absolute path in multi-repo setups'},
|
|
992
995
|
'path': {'type': 'string'},
|
|
@@ -997,11 +1000,12 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
997
1000
|
'annotations': {'readOnlyHint': False},
|
|
998
1001
|
'description': "Context hygiene: 'budget' (score S-F), 'compact' (fold transcript), 'prune' (drop "
|
|
999
1002
|
"superseded reads), 'mistakes', 'metrics', 'remember' (store a decision/note/preference), "
|
|
1000
|
-
"'recall' (read project memory), 'forget' (remove one entry by id)
|
|
1003
|
+
"'recall' (read project memory), 'forget' (remove one entry by id), "
|
|
1004
|
+
"'recall_transcript' (BM25 search over prior session transcripts).",
|
|
1001
1005
|
'inputSchema': {'type': 'object',
|
|
1002
1006
|
'properties': {'action': {'type': 'string',
|
|
1003
1007
|
'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics',
|
|
1004
|
-
'remember', 'recall', 'forget']},
|
|
1008
|
+
'remember', 'recall', 'forget', 'recall_transcript']},
|
|
1005
1009
|
'model': {'type': 'string'},
|
|
1006
1010
|
'transcript_path': {'type': 'string'},
|
|
1007
1011
|
'kind': {'type': 'string',
|
|
@@ -1012,8 +1016,17 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
1012
1016
|
'files': {'type': 'array',
|
|
1013
1017
|
'items': {'type': 'string'},
|
|
1014
1018
|
'description': 'remember: files this decision touches'},
|
|
1015
|
-
'id': {'type': 'string',
|
|
1016
|
-
|
|
1019
|
+
'id': {'type': 'string',
|
|
1020
|
+
'description': 'forget: entry id; recall_transcript: <session>:<index> drill-down'},
|
|
1021
|
+
'query': {'type': 'string',
|
|
1022
|
+
'description': 'recall: optional filter; recall_transcript: search terms'},
|
|
1023
|
+
'scope': {'type': 'string',
|
|
1024
|
+
'enum': ['this', 'project', 'all'],
|
|
1025
|
+
'description': 'recall_transcript: transcript scope (default project)'},
|
|
1026
|
+
'since': {'type': 'string',
|
|
1027
|
+
'description': 'recall_transcript: ISO lower bound'},
|
|
1028
|
+
'until': {'type': 'string',
|
|
1029
|
+
'description': 'recall_transcript: ISO upper bound'},
|
|
1017
1030
|
'limit': {'type': 'integer'},
|
|
1018
1031
|
'workspace_dir': {'type': 'string'}}}},
|
|
1019
1032
|
{'name': 'oumv',
|
|
@@ -2243,6 +2256,43 @@ def _project_memory_action(action: str, args: dict) -> dict:
|
|
|
2243
2256
|
return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
|
|
2244
2257
|
|
|
2245
2258
|
|
|
2259
|
+
def _transcript_recall_action(args: dict) -> dict:
|
|
2260
|
+
"""`session_context(recall_transcript|id)` — search prior agent sessions."""
|
|
2261
|
+
from src.transcript_recall import drill_down, search
|
|
2262
|
+
|
|
2263
|
+
root = str(
|
|
2264
|
+
args.get("workspace_dir")
|
|
2265
|
+
or args.get("cwd")
|
|
2266
|
+
or args.get("project_path")
|
|
2267
|
+
or _workspace_root()
|
|
2268
|
+
or os.getcwd()
|
|
2269
|
+
)
|
|
2270
|
+
scope = str(args.get("scope") or "project").strip().lower()
|
|
2271
|
+
if scope not in ("this", "project", "all"):
|
|
2272
|
+
scope = "project"
|
|
2273
|
+
if args.get("id"):
|
|
2274
|
+
payload = drill_down(
|
|
2275
|
+
str(args.get("id") or ""),
|
|
2276
|
+
scope="all",
|
|
2277
|
+
cwd=root,
|
|
2278
|
+
session_id=_mcp_session_id(),
|
|
2279
|
+
transcript_path=str(args.get("transcript_path") or ""),
|
|
2280
|
+
)
|
|
2281
|
+
else:
|
|
2282
|
+
payload = search(
|
|
2283
|
+
query=str(args.get("query") or ""),
|
|
2284
|
+
scope=scope,
|
|
2285
|
+
cwd=root,
|
|
2286
|
+
session_id=_mcp_session_id(),
|
|
2287
|
+
transcript_path=str(args.get("transcript_path") or ""),
|
|
2288
|
+
since=str(args.get("since") or ""),
|
|
2289
|
+
until=str(args.get("until") or ""),
|
|
2290
|
+
limit=int(args.get("limit") or 10),
|
|
2291
|
+
)
|
|
2292
|
+
payload["ok"] = True
|
|
2293
|
+
return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
|
|
2294
|
+
|
|
2295
|
+
|
|
2246
2296
|
def handle_tool_call(name: str, args: dict) -> dict:
|
|
2247
2297
|
if args is None or not isinstance(args, dict):
|
|
2248
2298
|
args = {}
|
|
@@ -2315,6 +2365,7 @@ _REPO_MAP_ACTIONS = {
|
|
|
2315
2365
|
"graph": "get_architecture_graph",
|
|
2316
2366
|
"api": "get_api_surface",
|
|
2317
2367
|
"tree": "list_dir",
|
|
2368
|
+
"importers": "get_import_neighborhood",
|
|
2318
2369
|
}
|
|
2319
2370
|
_SESSION_CONTEXT_ACTIONS = {
|
|
2320
2371
|
"budget": "context_budget",
|
|
@@ -2350,6 +2401,30 @@ _HELPER_ACTIONS = {
|
|
|
2350
2401
|
}
|
|
2351
2402
|
|
|
2352
2403
|
|
|
2404
|
+
def _parse_if_modified_since(value: Any) -> Optional[int]:
|
|
2405
|
+
"""Read an ISO timestamp or a nanosecond mtime; None when unparseable."""
|
|
2406
|
+
if value is None:
|
|
2407
|
+
return None
|
|
2408
|
+
raw = str(value).strip()
|
|
2409
|
+
if not raw:
|
|
2410
|
+
return None
|
|
2411
|
+
try:
|
|
2412
|
+
if raw.isdigit():
|
|
2413
|
+
number = int(raw)
|
|
2414
|
+
# Heuristic: seconds are ~1.7e9, milliseconds ~1.7e12, ns ~1.7e18.
|
|
2415
|
+
if number > 10**15:
|
|
2416
|
+
return number
|
|
2417
|
+
if number > 10**11:
|
|
2418
|
+
return number * 1_000_000
|
|
2419
|
+
return number * 1_000_000_000
|
|
2420
|
+
from datetime import datetime
|
|
2421
|
+
|
|
2422
|
+
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
|
2423
|
+
return int(parsed.timestamp() * 1_000_000_000)
|
|
2424
|
+
except Exception:
|
|
2425
|
+
return None
|
|
2426
|
+
|
|
2427
|
+
|
|
2353
2428
|
def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
2354
2429
|
global _EPOCH_GEN
|
|
2355
2430
|
# Route consolidated tools to canonical internal handlers (zero logic duplication).
|
|
@@ -2406,17 +2481,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2406
2481
|
elif name == "repo_map":
|
|
2407
2482
|
view = str(args.get("view") or "graph").strip().lower()
|
|
2408
2483
|
if view not in _REPO_MAP_ACTIONS:
|
|
2409
|
-
return _fallback_error("repo_map", f"unknown view '{view}' (expected graph|api|tree)")
|
|
2484
|
+
return _fallback_error("repo_map", f"unknown view '{view}' (expected graph|api|tree|importers)")
|
|
2410
2485
|
mapped = _REPO_MAP_ACTIONS[view]
|
|
2411
2486
|
if view == "tree" and not args.get("path"):
|
|
2412
2487
|
args = dict(args, path=args.get("project_path") or ".")
|
|
2413
2488
|
elif view in ("graph", "api") and not args.get("project_path") and args.get("path"):
|
|
2414
2489
|
args = dict(args, project_path=args.get("path"))
|
|
2490
|
+
elif view == "importers" and not args.get("path"):
|
|
2491
|
+
return _fallback_error("repo_map", "importers needs `path` (the file to inspect)")
|
|
2415
2492
|
name = mapped
|
|
2416
2493
|
elif name == "session_context":
|
|
2417
2494
|
action = str(args.get("action") or "budget").strip().lower()
|
|
2418
2495
|
if action in ("remember", "recall", "forget"):
|
|
2419
2496
|
return _project_memory_action(action, args)
|
|
2497
|
+
if action == "recall_transcript":
|
|
2498
|
+
return _transcript_recall_action(args)
|
|
2420
2499
|
if action not in _SESSION_CONTEXT_ACTIONS:
|
|
2421
2500
|
return _fallback_error("session_context", f"unknown action '{action}'")
|
|
2422
2501
|
name = _SESSION_CONTEXT_ACTIONS[action]
|
|
@@ -2542,6 +2621,46 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2542
2621
|
except OSError as e:
|
|
2543
2622
|
return _fallback_error("smart_read_file", f"cannot stat path: {e}")
|
|
2544
2623
|
|
|
2624
|
+
# Cheap delta read: when the caller already has this file and passes the
|
|
2625
|
+
# mtime/timestamp it saw, an unchanged file answers with one line instead
|
|
2626
|
+
# of re-emitting a slice. Explicit symbol/range requests bypass this.
|
|
2627
|
+
ims_raw = args.get("if_modified_since")
|
|
2628
|
+
if ims_raw and not symbol and start_line is None and end_line is None and not force_full:
|
|
2629
|
+
since_ns = _parse_if_modified_since(ims_raw)
|
|
2630
|
+
raw_ims = str(ims_raw).strip()
|
|
2631
|
+
# ISO timestamps without a fraction are second-precision: compare
|
|
2632
|
+
# whole seconds so a 10:00:00 stamp matches mtime 10:00:00.812.
|
|
2633
|
+
second_precision = (
|
|
2634
|
+
("T" in raw_ims and "." not in raw_ims)
|
|
2635
|
+
or (raw_ims.isdigit() and len(raw_ims) <= 10)
|
|
2636
|
+
)
|
|
2637
|
+
if since_ns is not None:
|
|
2638
|
+
unchanged = (
|
|
2639
|
+
st.st_mtime_ns // 1_000_000_000 <= since_ns // 1_000_000_000
|
|
2640
|
+
if second_precision
|
|
2641
|
+
else st.st_mtime_ns <= since_ns
|
|
2642
|
+
)
|
|
2643
|
+
else:
|
|
2644
|
+
unchanged = False
|
|
2645
|
+
if unchanged:
|
|
2646
|
+
try:
|
|
2647
|
+
rel = os.path.relpath(path, active_ws) if active_ws else path
|
|
2648
|
+
except ValueError:
|
|
2649
|
+
rel = path
|
|
2650
|
+
from datetime import datetime
|
|
2651
|
+
|
|
2652
|
+
mtime_iso = datetime.fromtimestamp(st.st_mtime_ns / 1_000_000_000).isoformat(timespec="seconds")
|
|
2653
|
+
return {
|
|
2654
|
+
"content": [{
|
|
2655
|
+
"type": "text",
|
|
2656
|
+
"text": (
|
|
2657
|
+
f"// [TS: unchanged] {rel} (mtime {mtime_iso}, size {st.st_size:,})\n"
|
|
2658
|
+
"Reuse the content returned earlier; if your context was compacted, re-call "
|
|
2659
|
+
"smart_read_file without if_modified_since or with force_full=true."
|
|
2660
|
+
),
|
|
2661
|
+
}]
|
|
2662
|
+
}
|
|
2663
|
+
|
|
2545
2664
|
if _is_binary_file(path):
|
|
2546
2665
|
return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
|
|
2547
2666
|
|
|
@@ -3375,6 +3494,26 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3375
3494
|
dashboard = Dashboard(tracker)
|
|
3376
3495
|
return {"content": [{"type": "text", "text": dashboard.render_markdown()}]}
|
|
3377
3496
|
|
|
3497
|
+
elif name == "get_import_neighborhood":
|
|
3498
|
+
target_abs, err = _resolve_project_root(args)
|
|
3499
|
+
if err or not target_abs:
|
|
3500
|
+
return {
|
|
3501
|
+
"isError": True,
|
|
3502
|
+
"content": [{"type": "text", "text": err or "Error: Invalid project_path."}]
|
|
3503
|
+
}
|
|
3504
|
+
target_file = str(args.get("path") or args.get("file_path") or "").strip()
|
|
3505
|
+
if not target_file:
|
|
3506
|
+
return _fallback_error("repo_map", "importers needs `path` (the file to inspect)")
|
|
3507
|
+
graph = GraphEngine.get_instance(target_abs)
|
|
3508
|
+
limit = args.get("limit")
|
|
3509
|
+
try:
|
|
3510
|
+
limit = int(limit) if limit is not None else 40
|
|
3511
|
+
except (TypeError, ValueError):
|
|
3512
|
+
limit = 40
|
|
3513
|
+
payload = graph.get_import_neighborhood(target_file, limit=limit)
|
|
3514
|
+
payload["project_root"] = graph.root_dir
|
|
3515
|
+
return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
|
|
3516
|
+
|
|
3378
3517
|
elif name == "get_architecture_graph":
|
|
3379
3518
|
target_abs, err = _resolve_project_root(args)
|
|
3380
3519
|
if err or not target_abs:
|
package/src/session_brief.py
CHANGED
|
@@ -35,7 +35,7 @@ _FRONTEND_LINES = {
|
|
|
35
35
|
"frontend angular/{framework}: OUMV live via `tokensafe dev --framework angular` "
|
|
36
36
|
"on the Vite/Analog dev server (window.ng discovery, L0-L4, OCC edits; certified "
|
|
37
37
|
"L3 in a browser). Call tokensafe:oumv(action='observe', level='L1') before "
|
|
38
|
-
"reading files
|
|
38
|
+
"reading files. `ng serve` is supported through `tokensafe inject` (the `tokensafe-ui:dev-server` builder); the Vite/Analog path stays zero-footprint."
|
|
39
39
|
),
|
|
40
40
|
"vue": (
|
|
41
41
|
"frontend {provider}/{framework}: OUMV live via `tokensafe dev --framework vue` "
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Zero-token status line: today's measured savings for the host status bar.
|
|
2
|
+
|
|
3
|
+
The line is rendered by a host command, never injected into the conversation, so
|
|
4
|
+
it costs no tokens. It reads one aggregate row from the metrics DB and stays
|
|
5
|
+
silent (empty output) on any failure.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _human(number: int) -> str:
|
|
15
|
+
value = float(number or 0)
|
|
16
|
+
for suffix in ("", "k", "M", "B"):
|
|
17
|
+
if abs(value) < 1000 or suffix == "B":
|
|
18
|
+
if suffix == "":
|
|
19
|
+
return f"{int(value)}"
|
|
20
|
+
return f"{value:.1f}{suffix}".replace(".0", "")
|
|
21
|
+
value /= 1000.0
|
|
22
|
+
return str(int(number or 0))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def render_statusline() -> str:
|
|
26
|
+
"""One compact line, or an empty string when there is nothing to show."""
|
|
27
|
+
try:
|
|
28
|
+
from src.metrics import MetricsTracker
|
|
29
|
+
|
|
30
|
+
tracker = MetricsTracker()
|
|
31
|
+
start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).isoformat()
|
|
32
|
+
with tracker._get_connection() as conn:
|
|
33
|
+
row = conn.cursor().execute(
|
|
34
|
+
"SELECT COUNT(*) AS events, COALESCE(SUM(saved_tokens), 0) AS saved "
|
|
35
|
+
"FROM events WHERE timestamp >= ? AND saved_tokens > 0",
|
|
36
|
+
(start,),
|
|
37
|
+
).fetchone()
|
|
38
|
+
saved = int(row["saved"] or 0)
|
|
39
|
+
events = int(row["events"] or 0)
|
|
40
|
+
except Exception:
|
|
41
|
+
return ""
|
|
42
|
+
if saved <= 0:
|
|
43
|
+
return "TS · 0 saved today"
|
|
44
|
+
return f"TS ⚡ {_human(saved)} saved · {events} steps"
|
package/src/telemetry_sync.py
CHANGED
|
@@ -311,7 +311,7 @@ class TelemetrySync:
|
|
|
311
311
|
current_last_id = last_id
|
|
312
312
|
headers = {
|
|
313
313
|
"Content-Type": "application/json",
|
|
314
|
-
"User-Agent": "TokenSafe-Sync/4.16.
|
|
314
|
+
"User-Agent": "TokenSafe-Sync/4.16.2"
|
|
315
315
|
}
|
|
316
316
|
if active_key:
|
|
317
317
|
headers["Authorization"] = f"Bearer {active_key}"
|