tokensafe 4.16.0 → 4.16.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/.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/batch_editor.py +62 -22
- package/src/cli.py +96 -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/graph_engine.py
CHANGED
|
@@ -2197,6 +2197,54 @@ class CodeGraph:
|
|
|
2197
2197
|
return hits, {"scanned_files": scanned, "total_files": total, "partial": True}
|
|
2198
2198
|
return hits, {"scanned_files": scanned, "total_files": total, "partial": scanned < total}
|
|
2199
2199
|
|
|
2200
|
+
def get_import_neighborhood(self, rel_path: str, limit: int = 40) -> Dict[str, Any]:
|
|
2201
|
+
"""Direct importers and imported files for one file (file-level edges).
|
|
2202
|
+
|
|
2203
|
+
Answers "who breaks if I rename/move this?" without a full impact walk,
|
|
2204
|
+
and "what does this file pull in?" without re-reading its imports.
|
|
2205
|
+
"""
|
|
2206
|
+
raw = (rel_path or "").strip().replace("\\", "/")
|
|
2207
|
+
if not raw:
|
|
2208
|
+
return {"file": "", "importers": [], "imports": [], "counts": {"importers": 0, "imports": 0}}
|
|
2209
|
+
if os.path.isabs(raw):
|
|
2210
|
+
try:
|
|
2211
|
+
raw = os.path.relpath(raw, self.root_dir)
|
|
2212
|
+
except ValueError:
|
|
2213
|
+
pass
|
|
2214
|
+
raw = os.path.normpath(raw).replace("\\", "/")
|
|
2215
|
+
while raw.startswith("./"):
|
|
2216
|
+
raw = raw[2:]
|
|
2217
|
+
raw = raw.lstrip("/")
|
|
2218
|
+
key = f"file:{raw}"
|
|
2219
|
+
|
|
2220
|
+
def _files(values: Set[str]) -> List[str]:
|
|
2221
|
+
out = []
|
|
2222
|
+
for value in values or set():
|
|
2223
|
+
if isinstance(value, str) and value.startswith("file:"):
|
|
2224
|
+
out.append(value[5:])
|
|
2225
|
+
return sorted(set(out))
|
|
2226
|
+
|
|
2227
|
+
importers = _files(self.rev_edges.get(key, set()))
|
|
2228
|
+
imports = _files(self.edges.get(key, set()))
|
|
2229
|
+
|
|
2230
|
+
def _describe(paths: List[str]) -> List[Dict[str, Any]]:
|
|
2231
|
+
rows = []
|
|
2232
|
+
for path in paths[: max(1, int(limit or 40))]:
|
|
2233
|
+
rows.append({
|
|
2234
|
+
"file": path,
|
|
2235
|
+
"symbols": len(self.file_symbols.get(path, [])),
|
|
2236
|
+
"endpoints": len(self.file_endpoints.get(path, [])),
|
|
2237
|
+
})
|
|
2238
|
+
return rows
|
|
2239
|
+
|
|
2240
|
+
return {
|
|
2241
|
+
"file": raw,
|
|
2242
|
+
"importers": _describe(importers),
|
|
2243
|
+
"imports": _describe(imports),
|
|
2244
|
+
"counts": {"importers": len(importers), "imports": len(imports)},
|
|
2245
|
+
"provenance": "static",
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2200
2248
|
def get_static_impact(self, target: str, max_depth: int = 3) -> Dict[str, Any]:
|
|
2201
2249
|
"""
|
|
2202
2250
|
Static impact analysis over the AST graph: reverse-dependency walk
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Per-host capability matrix for TokenSafe features.
|
|
2
|
+
|
|
3
|
+
One table answers "what can this host actually enforce?" so the installer
|
|
4
|
+
registers only events the host contract supports and ``tokensafe doctor`` can
|
|
5
|
+
report the truth instead of a wish list.
|
|
6
|
+
|
|
7
|
+
Feature keys
|
|
8
|
+
------------
|
|
9
|
+
hooks Lifecycle-hook surface installed by TokenSafe.
|
|
10
|
+
precompact Host emits a PreCompact event we can hook.
|
|
11
|
+
postcompact Host emits a PostCompact event we can hook.
|
|
12
|
+
session_injection SessionStart can carry additional context.
|
|
13
|
+
prompt_injection UserPromptSubmit can carry additional context.
|
|
14
|
+
statusline Host exposes a status-line surface.
|
|
15
|
+
transcript Transcript file exists and is parseable by the engine.
|
|
16
|
+
compaction_fallback The usage ledger can infer a compaction from prompt shrink.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any, Dict, List
|
|
22
|
+
|
|
23
|
+
HOST_CAPABILITIES: Dict[str, Dict[str, Any]] = {
|
|
24
|
+
"claude_code": {
|
|
25
|
+
"name": "Claude Code CLI",
|
|
26
|
+
"hooks": True,
|
|
27
|
+
"precompact": True,
|
|
28
|
+
"postcompact": True,
|
|
29
|
+
"session_injection": True,
|
|
30
|
+
"prompt_injection": True,
|
|
31
|
+
"statusline": True,
|
|
32
|
+
"transcript": True,
|
|
33
|
+
"compaction_fallback": True,
|
|
34
|
+
},
|
|
35
|
+
"zcode": {
|
|
36
|
+
"name": "ZCode (Z.ai Code)",
|
|
37
|
+
"hooks": True,
|
|
38
|
+
"precompact": False,
|
|
39
|
+
"postcompact": False,
|
|
40
|
+
"session_injection": True,
|
|
41
|
+
"prompt_injection": True,
|
|
42
|
+
"statusline": False,
|
|
43
|
+
"transcript": True,
|
|
44
|
+
"compaction_fallback": True,
|
|
45
|
+
},
|
|
46
|
+
"kimi": {
|
|
47
|
+
"name": "Kimi Code",
|
|
48
|
+
"hooks": True,
|
|
49
|
+
"precompact": False,
|
|
50
|
+
"postcompact": False,
|
|
51
|
+
"session_injection": True,
|
|
52
|
+
"prompt_injection": True,
|
|
53
|
+
"statusline": False,
|
|
54
|
+
"transcript": True,
|
|
55
|
+
"compaction_fallback": True,
|
|
56
|
+
},
|
|
57
|
+
"antigravity": {
|
|
58
|
+
"name": "Google Antigravity",
|
|
59
|
+
"hooks": True,
|
|
60
|
+
"precompact": False,
|
|
61
|
+
"postcompact": False,
|
|
62
|
+
"session_injection": True,
|
|
63
|
+
"prompt_injection": True,
|
|
64
|
+
"statusline": False,
|
|
65
|
+
"transcript": True,
|
|
66
|
+
"compaction_fallback": True,
|
|
67
|
+
},
|
|
68
|
+
"cursor": {
|
|
69
|
+
"name": "Cursor",
|
|
70
|
+
"hooks": True,
|
|
71
|
+
"precompact": False,
|
|
72
|
+
"postcompact": False,
|
|
73
|
+
"session_injection": False,
|
|
74
|
+
"prompt_injection": False,
|
|
75
|
+
"statusline": False,
|
|
76
|
+
"transcript": True,
|
|
77
|
+
"compaction_fallback": True,
|
|
78
|
+
},
|
|
79
|
+
"codex": {
|
|
80
|
+
"name": "OpenAI Codex",
|
|
81
|
+
"hooks": False,
|
|
82
|
+
"precompact": False,
|
|
83
|
+
"postcompact": False,
|
|
84
|
+
"session_injection": False,
|
|
85
|
+
"prompt_injection": False,
|
|
86
|
+
"statusline": False,
|
|
87
|
+
"transcript": True,
|
|
88
|
+
"compaction_fallback": True,
|
|
89
|
+
},
|
|
90
|
+
"claude_desktop": {
|
|
91
|
+
"name": "Claude Desktop",
|
|
92
|
+
"hooks": False,
|
|
93
|
+
"precompact": False,
|
|
94
|
+
"postcompact": False,
|
|
95
|
+
"session_injection": False,
|
|
96
|
+
"prompt_injection": False,
|
|
97
|
+
"statusline": False,
|
|
98
|
+
"transcript": False,
|
|
99
|
+
"compaction_fallback": False,
|
|
100
|
+
},
|
|
101
|
+
"windsurf": {
|
|
102
|
+
"name": "Windsurf",
|
|
103
|
+
"hooks": False,
|
|
104
|
+
"precompact": False,
|
|
105
|
+
"postcompact": False,
|
|
106
|
+
"session_injection": False,
|
|
107
|
+
"prompt_injection": False,
|
|
108
|
+
"statusline": False,
|
|
109
|
+
"transcript": False,
|
|
110
|
+
"compaction_fallback": False,
|
|
111
|
+
},
|
|
112
|
+
"cline": {
|
|
113
|
+
"name": "Cline / Roo Code",
|
|
114
|
+
"hooks": False,
|
|
115
|
+
"precompact": False,
|
|
116
|
+
"postcompact": False,
|
|
117
|
+
"session_injection": False,
|
|
118
|
+
"prompt_injection": False,
|
|
119
|
+
"statusline": False,
|
|
120
|
+
"transcript": False,
|
|
121
|
+
"compaction_fallback": False,
|
|
122
|
+
},
|
|
123
|
+
"copilot": {
|
|
124
|
+
"name": "GitHub Copilot",
|
|
125
|
+
"hooks": False,
|
|
126
|
+
"precompact": False,
|
|
127
|
+
"postcompact": False,
|
|
128
|
+
"session_injection": False,
|
|
129
|
+
"prompt_injection": False,
|
|
130
|
+
"statusline": False,
|
|
131
|
+
"transcript": False,
|
|
132
|
+
"compaction_fallback": False,
|
|
133
|
+
},
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
# Aliases used by hooks and CLI entry points.
|
|
137
|
+
ALIASES = {
|
|
138
|
+
"claude": "claude_code",
|
|
139
|
+
"claude-code": "claude_code",
|
|
140
|
+
"kimi_code": "kimi",
|
|
141
|
+
"kimi-code": "kimi",
|
|
142
|
+
"agy": "antigravity",
|
|
143
|
+
"roo": "cline",
|
|
144
|
+
"roo_code": "cline",
|
|
145
|
+
"cline_roo": "cline",
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def canonical(host: str) -> str:
|
|
150
|
+
key = (host or "").strip().lower().replace(" ", "_")
|
|
151
|
+
return ALIASES.get(key, key)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def capabilities(host: str) -> Dict[str, Any]:
|
|
155
|
+
"""Capability dict for a host; unknown hosts answer all-False."""
|
|
156
|
+
return dict(HOST_CAPABILITIES.get(canonical(host), {}))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def supports(host: str, feature: str) -> bool:
|
|
160
|
+
return bool(capabilities(host).get(feature, False))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def matrix_rows() -> List[Dict[str, Any]]:
|
|
164
|
+
"""Stable rows for doctor/README rendering."""
|
|
165
|
+
rows = []
|
|
166
|
+
for key, caps in HOST_CAPABILITIES.items():
|
|
167
|
+
rows.append({"host": key, **caps})
|
|
168
|
+
return rows
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def summarize(host: str) -> str:
|
|
172
|
+
"""One-line human summary used by `tokensafe doctor`."""
|
|
173
|
+
caps = capabilities(host)
|
|
174
|
+
if not caps:
|
|
175
|
+
return f"{host}: unknown host"
|
|
176
|
+
enabled = [name for name in (
|
|
177
|
+
"precompact", "postcompact", "session_injection", "prompt_injection",
|
|
178
|
+
"statusline", "transcript", "compaction_fallback",
|
|
179
|
+
) if caps.get(name)]
|
|
180
|
+
return f"{caps.get('name', host)}: hooks={bool(caps.get('hooks'))} · " + ", ".join(enabled)
|
package/src/installer.py
CHANGED
|
@@ -399,7 +399,8 @@ class AgentInstaller:
|
|
|
399
399
|
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
400
400
|
if agent_key == "codex":
|
|
401
401
|
return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
|
|
402
|
-
|
|
402
|
+
from src.host_capabilities import supports
|
|
403
|
+
if not supports(agent_key, "hooks"):
|
|
403
404
|
return False, "hooks not applicable for this agent"
|
|
404
405
|
|
|
405
406
|
claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
|
|
@@ -475,6 +476,24 @@ class AgentInstaller:
|
|
|
475
476
|
data, err = cls._load_json_with_backup(config_file)
|
|
476
477
|
if err or data is None:
|
|
477
478
|
return False, err or f"Failed to parse {config_file}"
|
|
479
|
+
# Zero-token savings statusline: register only when the field is free
|
|
480
|
+
# or already ours; a user's custom statusline is left untouched.
|
|
481
|
+
status_cmd = quote_hook_command([
|
|
482
|
+
PYTHON_BIN,
|
|
483
|
+
os.path.join(PROJECT_ROOT, "bin", "tokensafe"),
|
|
484
|
+
"statusline",
|
|
485
|
+
])
|
|
486
|
+
current_status = data.get("statusLine")
|
|
487
|
+
status_owned = (
|
|
488
|
+
isinstance(current_status, dict)
|
|
489
|
+
and "tokensafe" in str(current_status.get("command", "")).lower()
|
|
490
|
+
)
|
|
491
|
+
status_changed = False
|
|
492
|
+
if (not current_status or status_owned) and (
|
|
493
|
+
not isinstance(current_status, dict) or current_status.get("command") != status_cmd
|
|
494
|
+
):
|
|
495
|
+
data["statusLine"] = {"type": "command", "command": status_cmd, "padding": 0}
|
|
496
|
+
status_changed = True
|
|
478
497
|
hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
|
|
479
498
|
prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
480
499
|
bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
@@ -490,6 +509,11 @@ class AgentInstaller:
|
|
|
490
509
|
# transcript (opt-in via TOKENSAFE_FOLD_AT_REST=1; the hook itself
|
|
491
510
|
# is a no-op while the flag is off).
|
|
492
511
|
stop_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 15}]}
|
|
512
|
+
# Compaction survival: PreCompact arms the marker, PostCompact
|
|
513
|
+
# injects the recovery digest (one-shot). Hosts without these events
|
|
514
|
+
# fall back to the usage-ledger prompt-shrink detector.
|
|
515
|
+
precompact_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
516
|
+
postcompact_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
493
517
|
|
|
494
518
|
def _sync_claude_event(event_name: str, default_entry: dict) -> bool:
|
|
495
519
|
entries = hooks.get(event_name)
|
|
@@ -527,13 +551,15 @@ class AgentInstaller:
|
|
|
527
551
|
_sync_claude_event("PreToolUse", stale_edit_entry),
|
|
528
552
|
_sync_claude_event("PostToolUse", post_bash_entry),
|
|
529
553
|
_sync_claude_event("PostToolUse", post_track_entry),
|
|
554
|
+
_sync_claude_event("PreCompact", precompact_entry),
|
|
555
|
+
_sync_claude_event("PostCompact", postcompact_entry),
|
|
530
556
|
_sync_claude_event("Stop", stop_entry),
|
|
531
|
-
])
|
|
557
|
+
]) or status_changed
|
|
532
558
|
if not changed:
|
|
533
559
|
return True, "TokenSafe Claude Code hooks already registered"
|
|
534
560
|
data["hooks"] = hooks
|
|
535
561
|
cls._atomic_write_json(config_file, data)
|
|
536
|
-
return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write/stale + PostToolUse compact/tracking + Stop fold-at-rest)"
|
|
562
|
+
return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write/stale + PostToolUse compact/tracking + PreCompact/PostCompact recovery + Stop fold-at-rest)"
|
|
537
563
|
|
|
538
564
|
if agent_key == "zcode":
|
|
539
565
|
config_file = os.path.join(HOME, ".zcode", "cli", "config.json")
|
|
@@ -689,8 +715,16 @@ class AgentInstaller:
|
|
|
689
715
|
data, err = cls._load_json_with_backup(config_file)
|
|
690
716
|
if err or data is None:
|
|
691
717
|
return False, err or f"Failed to parse {config_file}"
|
|
718
|
+
status_changed = False
|
|
719
|
+
current_status = data.get("statusLine")
|
|
720
|
+
if isinstance(current_status, dict) and "tokensafe" in str(current_status.get("command", "")).lower():
|
|
721
|
+
data.pop("statusLine", None)
|
|
722
|
+
status_changed = True
|
|
692
723
|
hooks = data.get("hooks")
|
|
693
724
|
if not isinstance(hooks, dict):
|
|
725
|
+
if status_changed:
|
|
726
|
+
cls._atomic_write_json(config_file, data)
|
|
727
|
+
return True, "Removed TokenSafe status line from Claude Code settings.json"
|
|
694
728
|
return True, "No hooks in Claude Code settings.json"
|
|
695
729
|
|
|
696
730
|
changed = False
|
|
@@ -718,13 +752,13 @@ class AgentInstaller:
|
|
|
718
752
|
hooks.pop(event_name, None)
|
|
719
753
|
changed = True
|
|
720
754
|
|
|
721
|
-
if changed:
|
|
755
|
+
if changed or status_changed:
|
|
722
756
|
if not hooks:
|
|
723
757
|
data.pop("hooks", None)
|
|
724
758
|
else:
|
|
725
759
|
data["hooks"] = hooks
|
|
726
760
|
cls._atomic_write_json(config_file, data)
|
|
727
|
-
return True, "Removed TokenSafe hooks from Claude Code settings.json"
|
|
761
|
+
return True, "Removed TokenSafe hooks/status line from Claude Code settings.json"
|
|
728
762
|
return True, "No TokenSafe hooks found in Claude Code settings.json"
|
|
729
763
|
|
|
730
764
|
if agent_key == "zcode":
|
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.1"
|
|
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.1"
|
|
315
315
|
}
|
|
316
316
|
if active_key:
|
|
317
317
|
headers["Authorization"] = f"Bearer {active_key}"
|