tokensafe 4.15.0 → 4.16.0
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/tokensafe-acp.js +38 -0
- package/hooks/claude_code_hook.py +26 -0
- package/hooks/post_tool_use.py +10 -0
- package/hooks/pre_invocation.py +44 -11
- package/hooks/pre_tool_use.py +22 -1
- package/kimi.plugin.json +1 -1
- package/package.json +3 -2
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +157 -3
- package/src/angular_cli.py +181 -0
- package/src/auto_inject.py +36 -2
- package/src/backend_release.py +1 -1
- package/src/batch_editor.py +119 -2
- package/src/bench/driver.py +54 -6
- package/src/bench/runner.py +58 -8
- package/src/build_parsers.py +35 -2
- package/src/burn_monitor.py +69 -1
- package/src/cache_normalizer.py +1 -1
- package/src/cli.py +109 -4
- package/src/command_sanitizer.py +21 -5
- package/src/dashboard.py +26 -0
- package/src/delegation.py +253 -0
- package/src/format_parsers/game_assets.py +259 -0
- package/src/fts_index.py +1 -1
- package/src/governor.py +54 -8
- package/src/installer.py +1 -1
- package/src/license_manager.py +128 -1
- package/src/mcp_server.py +318 -39
- package/src/metrics.py +313 -29
- package/src/savings.py +9 -4
- package/src/skeletonizer.py +51 -0
- package/src/telemetry_sync.py +1 -1
- package/src/usage_ledger.py +333 -0
- package/src/version_checker.py +1 -1
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Subagent delegation: fold the child's rollout into a digest for the parent.
|
|
2
|
+
|
|
3
|
+
A delegated task returns a report, and the orchestrator then re-reads the same
|
|
4
|
+
files to "check" — the burn audit measured 3.0M dead tokens from exactly that
|
|
5
|
+
loop. The child's rollout is already on disk (Claude writes
|
|
6
|
+
``<project>/<session>/subagents/*.jsonl``), so the hook folds it into a State
|
|
7
|
+
Ledger, names the files it already read, and seeds the content cache so a
|
|
8
|
+
repeat read costs no slicing.
|
|
9
|
+
|
|
10
|
+
Honesty: the parent never received the child's tool payloads, so this module
|
|
11
|
+
seeds the *content* layer only. It never marks those bytes as delivered, and a
|
|
12
|
+
pointer is therefore not offered — the model is told to skip the read, not told
|
|
13
|
+
it already has the text.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any, Dict, List, Optional
|
|
20
|
+
|
|
21
|
+
_MAX_DIGEST_CHARS = 1200
|
|
22
|
+
_MAX_SEED_FILES = 20
|
|
23
|
+
_CHILD_TTL_SECONDS = 15 * 60
|
|
24
|
+
_READ_TOOL_NAMES = {"read", "read_file", "view_file", "smart_read_file", "readfile", "cat"}
|
|
25
|
+
_AGENT_TOOL_NAMES = {"task", "agent", "subagent", "dispatch_agent", "delegate", "spawn_agent"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def digest_path(session_id: str) -> str:
|
|
29
|
+
from src.paths import resolve_data_dir
|
|
30
|
+
import hashlib
|
|
31
|
+
|
|
32
|
+
digest = hashlib.sha256(str(session_id or "").encode("utf-8")).hexdigest()[:16]
|
|
33
|
+
return os.path.join(resolve_data_dir(), "subagent_digests", f"{digest}.json")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _session_id(payload: Dict[str, Any]) -> str:
|
|
37
|
+
for key in ("conversationId", "conversation_id", "session_id", "sessionId"):
|
|
38
|
+
value = payload.get(key)
|
|
39
|
+
if isinstance(value, str) and value.strip():
|
|
40
|
+
return value.strip()
|
|
41
|
+
return "default_session"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _transcript_path(payload: Dict[str, Any]) -> str:
|
|
45
|
+
for key in ("transcriptPath", "transcript_path"):
|
|
46
|
+
value = payload.get(key)
|
|
47
|
+
if isinstance(value, str) and value.strip():
|
|
48
|
+
return value.strip()
|
|
49
|
+
return ""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _tool_name(payload: Dict[str, Any]) -> str:
|
|
53
|
+
tool_call = payload.get("toolCall") if isinstance(payload.get("toolCall"), dict) else {}
|
|
54
|
+
for value in (tool_call.get("name"), payload.get("tool_name"), payload.get("toolName")):
|
|
55
|
+
if isinstance(value, str) and value.strip():
|
|
56
|
+
return value.strip()
|
|
57
|
+
return ""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def is_agent_tool(tool_name: str) -> bool:
|
|
61
|
+
name = str(tool_name or "").strip().lower()
|
|
62
|
+
if not name:
|
|
63
|
+
return False
|
|
64
|
+
return name in _AGENT_TOOL_NAMES or name.startswith("subagent") or name.startswith("task_")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def find_child_transcript(parent_transcript: str) -> Optional[str]:
|
|
68
|
+
"""Newest subagent rollout owned by the parent's session, if any."""
|
|
69
|
+
parent = str(parent_transcript or "").strip()
|
|
70
|
+
if not parent or not os.path.isfile(parent):
|
|
71
|
+
return None
|
|
72
|
+
base = os.path.splitext(os.path.abspath(parent))[0]
|
|
73
|
+
candidates: List[str] = []
|
|
74
|
+
for root in (os.path.join(base, "subagents"), os.path.join(os.path.dirname(os.path.abspath(parent)), "subagents")):
|
|
75
|
+
if not os.path.isdir(root):
|
|
76
|
+
continue
|
|
77
|
+
try:
|
|
78
|
+
for name in os.listdir(root):
|
|
79
|
+
if name.endswith(".jsonl"):
|
|
80
|
+
candidates.append(os.path.join(root, name))
|
|
81
|
+
except OSError:
|
|
82
|
+
continue
|
|
83
|
+
if not candidates:
|
|
84
|
+
return None
|
|
85
|
+
newest = max(candidates, key=lambda p: os.path.getmtime(p))
|
|
86
|
+
try:
|
|
87
|
+
if time.time() - os.path.getmtime(newest) > _CHILD_TTL_SECONDS:
|
|
88
|
+
return None
|
|
89
|
+
except OSError:
|
|
90
|
+
return None
|
|
91
|
+
return newest
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _iter_jsonl(path: str):
|
|
95
|
+
try:
|
|
96
|
+
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
|
97
|
+
for line in handle:
|
|
98
|
+
line = line.strip()
|
|
99
|
+
if not line:
|
|
100
|
+
continue
|
|
101
|
+
try:
|
|
102
|
+
yield json.loads(line)
|
|
103
|
+
except Exception:
|
|
104
|
+
continue
|
|
105
|
+
except OSError:
|
|
106
|
+
return
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def extract_read_files(child_transcript: str) -> List[str]:
|
|
110
|
+
"""Absolute paths the child received in full (read-tool inputs), capped."""
|
|
111
|
+
seen: List[str] = []
|
|
112
|
+
for entry in _iter_jsonl(child_transcript):
|
|
113
|
+
if not isinstance(entry, dict):
|
|
114
|
+
continue
|
|
115
|
+
message = entry.get("message") if isinstance(entry.get("message"), dict) else entry
|
|
116
|
+
blocks = message.get("content") if isinstance(message.get("content"), list) else []
|
|
117
|
+
tool_calls = message.get("tool_calls") if isinstance(message.get("tool_calls"), list) else []
|
|
118
|
+
tool_call = message.get("toolCall") if isinstance(message.get("toolCall"), dict) else {}
|
|
119
|
+
if tool_call:
|
|
120
|
+
tool_calls = [tool_call]
|
|
121
|
+
for block in list(blocks) + list(tool_calls):
|
|
122
|
+
if not isinstance(block, dict):
|
|
123
|
+
continue
|
|
124
|
+
name = str(block.get("name") or block.get("tool_name") or "").strip().lower()
|
|
125
|
+
args = block.get("input") if isinstance(block.get("input"), dict) else (
|
|
126
|
+
block.get("args") if isinstance(block.get("args"), dict) else {}
|
|
127
|
+
)
|
|
128
|
+
if name not in _READ_TOOL_NAMES or not isinstance(args, dict):
|
|
129
|
+
continue
|
|
130
|
+
for key in ("file_path", "path", "FilePath", "TargetFile"):
|
|
131
|
+
value = args.get(key)
|
|
132
|
+
if isinstance(value, str) and value.strip():
|
|
133
|
+
candidate = os.path.abspath(value.strip())
|
|
134
|
+
if candidate not in seen:
|
|
135
|
+
seen.append(candidate)
|
|
136
|
+
break
|
|
137
|
+
if len(seen) >= _MAX_SEED_FILES:
|
|
138
|
+
return seen
|
|
139
|
+
return seen
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def build_digest(child_transcript: str) -> Dict[str, Any]:
|
|
143
|
+
"""Folds the child rollout into a State Ledger plus the files it read."""
|
|
144
|
+
digest = ""
|
|
145
|
+
try:
|
|
146
|
+
from src.history_compactor import HistoryCompactor
|
|
147
|
+
|
|
148
|
+
ledger, _orig, _folded, _stats = HistoryCompactor.fold_transcript(child_transcript, 3)
|
|
149
|
+
digest = str(ledger or "").strip()
|
|
150
|
+
except Exception:
|
|
151
|
+
digest = ""
|
|
152
|
+
if len(digest) > _MAX_DIGEST_CHARS:
|
|
153
|
+
digest = digest[:_MAX_DIGEST_CHARS].rstrip() + " ..."
|
|
154
|
+
return {
|
|
155
|
+
"digest": digest,
|
|
156
|
+
"files": extract_read_files(child_transcript),
|
|
157
|
+
"child": os.path.basename(child_transcript),
|
|
158
|
+
"created_at": int(time.time()),
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _write_atomic(path: str, text: str) -> None:
|
|
163
|
+
from src.atomic_io import write_text_atomic
|
|
164
|
+
|
|
165
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
166
|
+
write_text_atomic(path, text)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def remember(session_id: str, digest: Dict[str, Any]) -> None:
|
|
170
|
+
if not digest.get("digest") and not digest.get("files"):
|
|
171
|
+
return
|
|
172
|
+
try:
|
|
173
|
+
_write_atomic(digest_path(session_id), json.dumps(digest, ensure_ascii=False))
|
|
174
|
+
except Exception:
|
|
175
|
+
pass
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def take(session_id: str) -> Optional[Dict[str, Any]]:
|
|
179
|
+
"""Returns the pending digest and consumes it (one injection per delegation)."""
|
|
180
|
+
path = digest_path(session_id)
|
|
181
|
+
try:
|
|
182
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
183
|
+
data = json.load(handle)
|
|
184
|
+
except Exception:
|
|
185
|
+
return None
|
|
186
|
+
try:
|
|
187
|
+
os.unlink(path)
|
|
188
|
+
except Exception:
|
|
189
|
+
pass
|
|
190
|
+
if not isinstance(data, dict):
|
|
191
|
+
return None
|
|
192
|
+
return data
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def seed_cache(session_id: str, files: List[str], tracker: Any = None) -> int:
|
|
196
|
+
"""Caches the child's full reads under the parent session (content only)."""
|
|
197
|
+
if not files:
|
|
198
|
+
return 0
|
|
199
|
+
try:
|
|
200
|
+
from src.agent_firewall import AgentFirewall
|
|
201
|
+
|
|
202
|
+
seeded = 0
|
|
203
|
+
for path in files[:_MAX_SEED_FILES]:
|
|
204
|
+
if not os.path.isfile(path):
|
|
205
|
+
continue
|
|
206
|
+
try:
|
|
207
|
+
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
|
208
|
+
content = handle.read(AgentFirewall._MAX_CONTENT_CHARS + 1)
|
|
209
|
+
except OSError:
|
|
210
|
+
continue
|
|
211
|
+
if not content or len(content) > AgentFirewall._MAX_CONTENT_CHARS:
|
|
212
|
+
continue
|
|
213
|
+
AgentFirewall.record_cache(
|
|
214
|
+
session_id=session_id,
|
|
215
|
+
file_path=path,
|
|
216
|
+
content=content,
|
|
217
|
+
symbol="",
|
|
218
|
+
tracker=tracker,
|
|
219
|
+
)
|
|
220
|
+
seeded += 1
|
|
221
|
+
return seeded
|
|
222
|
+
except Exception:
|
|
223
|
+
return 0
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def record_from_hook(payload: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
227
|
+
"""Hook entry point: called once a delegated tool call returns."""
|
|
228
|
+
if not isinstance(payload, dict) or not is_agent_tool(_tool_name(payload)):
|
|
229
|
+
return None
|
|
230
|
+
session_id = _session_id(payload)
|
|
231
|
+
child = find_child_transcript(_transcript_path(payload))
|
|
232
|
+
if not child:
|
|
233
|
+
return None
|
|
234
|
+
digest = build_digest(child)
|
|
235
|
+
remember(session_id, digest)
|
|
236
|
+
seed_cache(session_id, digest.get("files") or [])
|
|
237
|
+
return digest
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def render(digest: Dict[str, Any]) -> str:
|
|
241
|
+
"""The text injected into the parent's next turn."""
|
|
242
|
+
lines: List[str] = ["🧩 **Delegation result** (from the subagent's own rollout):"]
|
|
243
|
+
body = str(digest.get("digest") or "").strip()
|
|
244
|
+
if body:
|
|
245
|
+
lines.append(body)
|
|
246
|
+
files = [os.path.basename(path) for path in (digest.get("files") or [])][:12]
|
|
247
|
+
if files:
|
|
248
|
+
lines.append(
|
|
249
|
+
"Already read by the subagent — do not re-read unless you need a full body: "
|
|
250
|
+
+ ", ".join(files)
|
|
251
|
+
)
|
|
252
|
+
lines.append("If the digest answers the question, continue; do not re-run the subagent's work.")
|
|
253
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Game-asset slicers: Godot scenes/resources, Unity YAML assets and .meta files.
|
|
2
|
+
|
|
3
|
+
These files are declarative trees, not code: a 4,000-line `.tscn` is 100% payload
|
|
4
|
+
and AST folding cannot help. The slicer returns a structural digest (node tree or
|
|
5
|
+
document list) and, with a symbol, the exact block for one node/object — the same
|
|
6
|
+
contract as the other `format_parsers` reducers. No engine is executed; the
|
|
7
|
+
syntax is stable text (Godot 4 `[section]` documents, Unity 2019+ YAML).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
13
|
+
|
|
14
|
+
GODOT_SCENE_EXTS = (".tscn",)
|
|
15
|
+
GODOT_RESOURCE_EXTS = (".tres",)
|
|
16
|
+
UNITY_ASSET_EXTS = (".unity", ".prefab")
|
|
17
|
+
UNITY_META_EXTS = (".meta",)
|
|
18
|
+
GAME_ASSET_EXTS = GODOT_SCENE_EXTS + GODOT_RESOURCE_EXTS + UNITY_ASSET_EXTS + UNITY_META_EXTS
|
|
19
|
+
|
|
20
|
+
_GODOT_HEADER_RE = re.compile(r"^\[(gd_scene|gd_resource)([^\]]*)\]", re.MULTILINE)
|
|
21
|
+
_GODOT_SECTION_RE = re.compile(r"^\[(ext_resource|sub_resource|node|resource)([^\]]*)\]", re.MULTILINE)
|
|
22
|
+
_ATTR_RE = re.compile(r'(\w+)="([^"]*)"')
|
|
23
|
+
_GODOT_SCRIPT_LINE_RE = re.compile(r'^script\s*=\s*ExtResource\("([^"]+)"\)', re.MULTILINE)
|
|
24
|
+
|
|
25
|
+
_UNITY_DOC_RE = re.compile(r"^--- !u!(\d+) &(\d+)", re.MULTILINE)
|
|
26
|
+
_UNITY_NAME_RE = re.compile(r"^\s*m_Name:\s*(.+?)\s*$", re.MULTILINE)
|
|
27
|
+
_UNITY_SCRIPT_RE = re.compile(r"m_Script:\s*\{[^}]*guid:\s*([0-9a-fA-F]+)")
|
|
28
|
+
_UNITY_GUID_RE = re.compile(r"^guid:\s*([0-9a-fA-F]+)\s*$", re.MULTILINE)
|
|
29
|
+
_UNITY_TOP_KEY_RE = re.compile(r"^([A-Za-z_][\w]*):", re.MULTILINE)
|
|
30
|
+
|
|
31
|
+
# Unity class ids worth naming in a digest (the rest collapse into a count).
|
|
32
|
+
_UNITY_CLASS_NAMES = {
|
|
33
|
+
"1": "GameObject",
|
|
34
|
+
"4": "Transform",
|
|
35
|
+
"224": "RectTransform",
|
|
36
|
+
"114": "MonoBehaviour",
|
|
37
|
+
"33": "MeshFilter",
|
|
38
|
+
"23": "MeshRenderer",
|
|
39
|
+
"212": "SpriteRenderer",
|
|
40
|
+
"222": "CanvasRenderer",
|
|
41
|
+
"223": "Canvas",
|
|
42
|
+
"2": "Component",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class GameAssetSlicer:
|
|
47
|
+
"""Structural digest + symbol slices for game-engine asset text formats."""
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def detect(path: str) -> Optional[str]:
|
|
51
|
+
lower = (path or "").lower()
|
|
52
|
+
if lower.endswith(GODOT_SCENE_EXTS):
|
|
53
|
+
return "godot_scene"
|
|
54
|
+
if lower.endswith(GODOT_RESOURCE_EXTS):
|
|
55
|
+
return "godot_resource"
|
|
56
|
+
if lower.endswith(UNITY_ASSET_EXTS):
|
|
57
|
+
return "unity_asset"
|
|
58
|
+
if lower.endswith(UNITY_META_EXTS):
|
|
59
|
+
return "unity_meta"
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def slice_file(path: str, symbol: str = "") -> Tuple[str, Dict[str, Any]]:
|
|
64
|
+
kind = GameAssetSlicer.detect(path)
|
|
65
|
+
if not kind:
|
|
66
|
+
return "", {}
|
|
67
|
+
try:
|
|
68
|
+
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
|
69
|
+
content = handle.read()
|
|
70
|
+
except OSError:
|
|
71
|
+
return "", {}
|
|
72
|
+
info: Dict[str, Any] = {"kind": kind, "mode": "symbol" if symbol else "overview"}
|
|
73
|
+
if kind in ("godot_scene", "godot_resource"):
|
|
74
|
+
text, stats = GameAssetSlicer.slice_godot(content, kind, symbol)
|
|
75
|
+
elif kind == "unity_asset":
|
|
76
|
+
text, stats = GameAssetSlicer.slice_unity(content, symbol)
|
|
77
|
+
else:
|
|
78
|
+
text, stats = GameAssetSlicer.slice_unity_meta(content, symbol)
|
|
79
|
+
info.update(stats)
|
|
80
|
+
return text, info
|
|
81
|
+
|
|
82
|
+
# --- Godot -----------------------------------------------------------
|
|
83
|
+
@staticmethod
|
|
84
|
+
def _godot_blocks(content: str) -> List[Tuple[str, str, Dict[str, str], str]]:
|
|
85
|
+
"""Splits a Godot text file into (section, raw_block, attrs, body) tuples."""
|
|
86
|
+
lines = content.splitlines()
|
|
87
|
+
starts: List[Tuple[int, str, str]] = []
|
|
88
|
+
for index, line in enumerate(lines):
|
|
89
|
+
match = _GODOT_SECTION_RE.match(line)
|
|
90
|
+
if match:
|
|
91
|
+
starts.append((index, match.group(1), match.group(2)))
|
|
92
|
+
blocks: List[Tuple[str, str, Dict[str, str], str]] = []
|
|
93
|
+
for pos, (start, section, attrs_text) in enumerate(starts):
|
|
94
|
+
end = starts[pos + 1][0] if pos + 1 < len(starts) else len(lines)
|
|
95
|
+
raw = "\n".join(lines[start:end]).rstrip()
|
|
96
|
+
body = "\n".join(lines[start + 1:end])
|
|
97
|
+
blocks.append((section, raw, dict(_ATTR_RE.findall(attrs_text)), body))
|
|
98
|
+
return blocks
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def slice_godot(content: str, kind: str, symbol: str = "") -> Tuple[str, Dict[str, Any]]:
|
|
102
|
+
blocks = GameAssetSlicer._godot_blocks(content)
|
|
103
|
+
header_match = _GODOT_HEADER_RE.search(content)
|
|
104
|
+
header_attrs = dict(_ATTR_RE.findall(header_match.group(2))) if header_match else {}
|
|
105
|
+
ext_resources = [(attrs.get("type", "?"), attrs.get("path", ""), attrs.get("id", ""))
|
|
106
|
+
for section, _raw, attrs, _body in blocks if section == "ext_resource"]
|
|
107
|
+
nodes = [(attrs.get("name", "?"), attrs.get("type", ""), attrs.get("parent", ""), raw, body)
|
|
108
|
+
for section, raw, attrs, body in blocks if section == "node"]
|
|
109
|
+
sub_resources = [attrs.get("type", "?") for section, _raw, attrs, _body in blocks
|
|
110
|
+
if section == "sub_resource"]
|
|
111
|
+
|
|
112
|
+
if symbol:
|
|
113
|
+
wanted = symbol.strip()
|
|
114
|
+
for section, raw, attrs, body in blocks:
|
|
115
|
+
if section == "node" and attrs.get("name") == wanted:
|
|
116
|
+
return raw, {"nodes": len(nodes), "matched": "node"}
|
|
117
|
+
if section in ("sub_resource", "resource") and attrs.get("id") == wanted:
|
|
118
|
+
return raw, {"nodes": len(nodes), "matched": section}
|
|
119
|
+
for prop, _raw, _attrs, body in [(m.group(1), None, None, None)
|
|
120
|
+
for m in re.finditer(r"^(\w+)\s*=", content, re.MULTILINE)]:
|
|
121
|
+
if prop == wanted:
|
|
122
|
+
line = next(ln for ln in content.splitlines() if ln.strip().startswith(f"{prop} "))
|
|
123
|
+
return line.strip(), {"nodes": len(nodes), "matched": "property"}
|
|
124
|
+
return f"(no node, sub-resource or property named '{wanted}' in this {kind})", {
|
|
125
|
+
"nodes": len(nodes), "matched": None,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
script_by_id = {}
|
|
129
|
+
for rtype, rpath, rid in ext_resources:
|
|
130
|
+
if rtype == "Script":
|
|
131
|
+
script_by_id[rid] = rpath
|
|
132
|
+
|
|
133
|
+
out: List[str] = []
|
|
134
|
+
out.append(f"// [TokenSafe Game Asset Slice: {kind} | {len(nodes)} nodes, "
|
|
135
|
+
f"{len(ext_resources)} ext resources, {len(sub_resources)} sub resources]")
|
|
136
|
+
head = f"{kind}"
|
|
137
|
+
if header_attrs.get("format"):
|
|
138
|
+
head += f" format={header_attrs['format']}"
|
|
139
|
+
if header_attrs.get("load_steps"):
|
|
140
|
+
head += f" load_steps={header_attrs['load_steps']}"
|
|
141
|
+
if header_attrs.get("type"):
|
|
142
|
+
head += f" type={header_attrs['type']}"
|
|
143
|
+
out.append(head)
|
|
144
|
+
if ext_resources:
|
|
145
|
+
out.append("ext_resources:")
|
|
146
|
+
for rtype, rpath, rid in ext_resources[:8]:
|
|
147
|
+
out.append(f" - {rtype} {rpath} (id {rid})")
|
|
148
|
+
if len(ext_resources) > 8:
|
|
149
|
+
out.append(f" ... (+{len(ext_resources) - 8} more external resources)")
|
|
150
|
+
if sub_resources:
|
|
151
|
+
counts: Dict[str, int] = {}
|
|
152
|
+
for rtype in sub_resources:
|
|
153
|
+
counts[rtype] = counts.get(rtype, 0) + 1
|
|
154
|
+
summary = ", ".join(f"{count}x {rtype}" for rtype, count in sorted(counts.items()))
|
|
155
|
+
out.append(f"sub_resources: {summary}")
|
|
156
|
+
if kind == "godot_resource" or not nodes:
|
|
157
|
+
resource_body = next((body for section, _raw, _attrs, body in blocks if section == "resource"), "")
|
|
158
|
+
props = [ln.strip() for ln in resource_body.splitlines() if ln.strip() and not ln.strip().startswith("[")]
|
|
159
|
+
if props:
|
|
160
|
+
out.append("resource properties:")
|
|
161
|
+
for prop in props[:12]:
|
|
162
|
+
out.append(f" {prop[:110]}")
|
|
163
|
+
if len(props) > 12:
|
|
164
|
+
out.append(f" ... (+{len(props) - 12} more properties)")
|
|
165
|
+
if nodes:
|
|
166
|
+
out.append("node tree:")
|
|
167
|
+
depth_of: Dict[str, int] = {}
|
|
168
|
+
for name, ntype, parent, _raw, body in nodes:
|
|
169
|
+
if parent in ("", "."):
|
|
170
|
+
depth = 0
|
|
171
|
+
else:
|
|
172
|
+
depth = depth_of.get(parent, 0) + 1
|
|
173
|
+
depth_of[name] = depth
|
|
174
|
+
script_match = _GODOT_SCRIPT_LINE_RE.search(body)
|
|
175
|
+
script = script_by_id.get(script_match.group(1), script_match.group(1)) if script_match else ""
|
|
176
|
+
label = f"{name} [{ntype}]" if ntype else name
|
|
177
|
+
if script:
|
|
178
|
+
label += f" script={script}"
|
|
179
|
+
out.append(" " * depth + f"- {label}")
|
|
180
|
+
if len(nodes) > 40:
|
|
181
|
+
keep = out[: 12 + 40]
|
|
182
|
+
out = keep + [f"... (+{len(nodes) - 40} more nodes folded)"]
|
|
183
|
+
return "\n".join(out), {"nodes": len(nodes), "ext_resources": len(ext_resources)}
|
|
184
|
+
|
|
185
|
+
# --- Unity -----------------------------------------------------------
|
|
186
|
+
@staticmethod
|
|
187
|
+
def _unity_documents(content: str) -> List[Tuple[str, str, str]]:
|
|
188
|
+
"""Returns (class_id, anchor_id, raw_document) tuples."""
|
|
189
|
+
matches = list(_UNITY_DOC_RE.finditer(content))
|
|
190
|
+
docs: List[Tuple[str, str, str]] = []
|
|
191
|
+
for pos, match in enumerate(matches):
|
|
192
|
+
end = matches[pos + 1].start() if pos + 1 < len(matches) else len(content)
|
|
193
|
+
docs.append((match.group(1), match.group(2), content[match.start():end].rstrip()))
|
|
194
|
+
return docs
|
|
195
|
+
|
|
196
|
+
@staticmethod
|
|
197
|
+
def slice_unity(content: str, symbol: str = "") -> Tuple[str, Dict[str, Any]]:
|
|
198
|
+
docs = GameAssetSlicer._unity_documents(content)
|
|
199
|
+
names: Dict[str, str] = {}
|
|
200
|
+
for class_id, _anchor, raw in docs:
|
|
201
|
+
if class_id == "1":
|
|
202
|
+
name_match = _UNITY_NAME_RE.search(raw)
|
|
203
|
+
if name_match:
|
|
204
|
+
names[name_match.group(1).strip()] = raw
|
|
205
|
+
if symbol:
|
|
206
|
+
wanted = symbol.strip()
|
|
207
|
+
raw = names.get(wanted)
|
|
208
|
+
if raw:
|
|
209
|
+
return raw, {"documents": len(docs), "matched": "GameObject"}
|
|
210
|
+
return f"(no GameObject named '{wanted}' in this asset)", {"documents": len(docs), "matched": None}
|
|
211
|
+
|
|
212
|
+
counts: Dict[str, int] = {}
|
|
213
|
+
for class_id, _anchor, _raw in docs:
|
|
214
|
+
label = _UNITY_CLASS_NAMES.get(class_id, f"!u!{class_id}")
|
|
215
|
+
counts[label] = counts.get(label, 0) + 1
|
|
216
|
+
summary = ", ".join(f"{count}x {label}" for label, count in sorted(counts.items(), key=lambda kv: -kv[1]))
|
|
217
|
+
out: List[str] = [
|
|
218
|
+
f"// [TokenSafe Game Asset Slice: unity_asset | {len(docs)} documents: {summary or 'none'}]"
|
|
219
|
+
]
|
|
220
|
+
for class_id, anchor, raw in docs[:40]:
|
|
221
|
+
label = _UNITY_CLASS_NAMES.get(class_id, f"!u!{class_id}")
|
|
222
|
+
line = f"- &{anchor} {label}"
|
|
223
|
+
name_match = _UNITY_NAME_RE.search(raw) if class_id in ("1", "4", "224", "114") else None
|
|
224
|
+
if name_match:
|
|
225
|
+
line += f" \"{name_match.group(1).strip()}\""
|
|
226
|
+
script_match = _UNITY_SCRIPT_RE.search(raw)
|
|
227
|
+
if script_match:
|
|
228
|
+
line += f" script=guid:{script_match.group(1)[:12]}"
|
|
229
|
+
out.append(line)
|
|
230
|
+
if len(docs) > 40:
|
|
231
|
+
out.append(f"... (+{len(docs) - 40} more YAML documents folded)")
|
|
232
|
+
return "\n".join(out), {"documents": len(docs), "game_objects": len(names)}
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
def slice_unity_meta(content: str, symbol: str = "") -> Tuple[str, Dict[str, Any]]:
|
|
236
|
+
guid_match = _UNITY_GUID_RE.search(content)
|
|
237
|
+
top_keys = _UNITY_TOP_KEY_RE.findall(content)
|
|
238
|
+
importers = [key for key in top_keys if key.endswith("Importer")]
|
|
239
|
+
if symbol:
|
|
240
|
+
wanted = symbol.strip()
|
|
241
|
+
for line in content.splitlines():
|
|
242
|
+
if line.strip().startswith(f"{wanted}:"):
|
|
243
|
+
return line.strip(), {"matched": wanted}
|
|
244
|
+
return f"(no '{wanted}' key in this .meta)", {"matched": None}
|
|
245
|
+
out = [
|
|
246
|
+
"// [TokenSafe Game Asset Slice: unity_meta | "
|
|
247
|
+
f"guid={guid_match.group(1) if guid_match else '?'} | importer={importers[0] if importers else '?'}]"
|
|
248
|
+
]
|
|
249
|
+
for key in top_keys:
|
|
250
|
+
if key in ("fileFormatVersion", "guid") or key.endswith("Importer"):
|
|
251
|
+
for line in content.splitlines():
|
|
252
|
+
if line.startswith(f"{key}:"):
|
|
253
|
+
out.append(line.strip()[:120])
|
|
254
|
+
break
|
|
255
|
+
settings = [key for key in top_keys if key not in ("fileFormatVersion", "guid") and not key.endswith("Importer")]
|
|
256
|
+
if settings:
|
|
257
|
+
out.append(f"settings: {', '.join(settings[:12])}"
|
|
258
|
+
+ (f" ... (+{len(settings) - 12} more)" if len(settings) > 12 else ""))
|
|
259
|
+
return "\n".join(out), {"keys": len(top_keys)}
|
package/src/fts_index.py
CHANGED
|
@@ -36,7 +36,7 @@ IGNORED_EXTS = {
|
|
|
36
36
|
CODE_EXTS = {
|
|
37
37
|
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
|
|
38
38
|
".py", ".pyw", ".go", ".rs", ".java", ".cpp", ".cc", ".c", ".h", ".hpp",
|
|
39
|
-
".php", ".rb", ".vue", ".svelte", ".swift", ".kt", ".kts", ".cs",
|
|
39
|
+
".php", ".rb", ".vue", ".svelte", ".swift", ".kt", ".kts", ".cs", ".gd",
|
|
40
40
|
".json", ".toml", ".yaml", ".yml", ".md", ".sql", ".sh", ".bash"
|
|
41
41
|
}
|
|
42
42
|
|
package/src/governor.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
"""
|
|
2
2
|
TokenSafe Context Window Governor & Epoch Rollover Engine.
|
|
3
3
|
Operates in Append-Only Epoch mode by default so historical turns remain
|
|
4
|
-
byte-identical for LLM KV-cache hits until context reaches
|
|
5
|
-
window,
|
|
4
|
+
byte-identical for LLM KV-cache hits until context reaches the fold band of the
|
|
5
|
+
model window (70%), capped by an absolute cost ceiling (`TOKENSAFE_CONTEXT_CEILING`,
|
|
6
|
+
default 200k), at which point an atomic Epoch Rollover consolidates deep history
|
|
6
7
|
into a Consolidated State Ledger.
|
|
7
8
|
"""
|
|
8
9
|
|
|
@@ -19,7 +20,7 @@ from src.metrics import MetricsTracker
|
|
|
19
20
|
class ContextGovernor:
|
|
20
21
|
"""Monitors and enforces context ceilings with cache-safe Append-Only Epochs."""
|
|
21
22
|
|
|
22
|
-
EPOCH_WINDOW_RATIO = 0.80
|
|
23
|
+
EPOCH_WINDOW_RATIO = 0.80 # legacy percentage; the fold policy lives in ContextBudget.effective_limit
|
|
23
24
|
DEFAULT_MAX_TURN_TOKENS = int(os.environ.get("TOKENSAFE_MAX_TURN_TOKENS", "16000"))
|
|
24
25
|
DEFAULT_TARGET_TURN_TOKENS = int(os.environ.get("TOKENSAFE_TARGET_TURN_TOKENS", "10000"))
|
|
25
26
|
|
|
@@ -27,9 +28,12 @@ class ContextGovernor:
|
|
|
27
28
|
|
|
28
29
|
@classmethod
|
|
29
30
|
def resolve_epoch_limit(cls, model: str = "", window_tokens: Optional[int] = None) -> int:
|
|
30
|
-
"""
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
"""Epoch ceiling: the fold band of the model window, capped by the cost ceiling.
|
|
32
|
+
|
|
33
|
+
A pure percentage policy folds a 1M-token window at 800k, which is late by
|
|
34
|
+
both price and attention; the effective limit is min(band * window, ceiling).
|
|
35
|
+
"""
|
|
36
|
+
return ContextBudget.effective_limit(model, window_tokens)
|
|
33
37
|
|
|
34
38
|
@staticmethod
|
|
35
39
|
def _calculate_total_tokens(msgs: List[Dict[str, Any]]) -> int:
|
|
@@ -302,6 +306,36 @@ class ContextBudget:
|
|
|
302
306
|
]
|
|
303
307
|
DEFAULT_WINDOW = 200_000
|
|
304
308
|
|
|
309
|
+
# Fold policy: a percentage of the model window, capped by an absolute
|
|
310
|
+
# ceiling. Percent-only is wrong for 1M-token models (80% = 800k), and the
|
|
311
|
+
# ceiling keeps the HUD honest even when a caller passes window_tokens.
|
|
312
|
+
DEFAULT_FOLD_BAND = 0.70
|
|
313
|
+
DEFAULT_CEILING = 200_000
|
|
314
|
+
|
|
315
|
+
@classmethod
|
|
316
|
+
def fold_band(cls) -> float:
|
|
317
|
+
raw = os.environ.get("TOKENSAFE_FOLD_BAND", "")
|
|
318
|
+
try:
|
|
319
|
+
band = float(raw) if raw.strip() else cls.DEFAULT_FOLD_BAND
|
|
320
|
+
except ValueError:
|
|
321
|
+
band = cls.DEFAULT_FOLD_BAND
|
|
322
|
+
return min(0.95, max(0.25, band))
|
|
323
|
+
|
|
324
|
+
@classmethod
|
|
325
|
+
def context_ceiling(cls) -> int:
|
|
326
|
+
raw = os.environ.get("TOKENSAFE_CONTEXT_CEILING", "")
|
|
327
|
+
try:
|
|
328
|
+
ceiling = int(raw) if raw.strip() else cls.DEFAULT_CEILING
|
|
329
|
+
except ValueError:
|
|
330
|
+
ceiling = cls.DEFAULT_CEILING
|
|
331
|
+
return ceiling if ceiling > 0 else cls.DEFAULT_CEILING
|
|
332
|
+
|
|
333
|
+
@classmethod
|
|
334
|
+
def effective_limit(cls, model: str = "", window_tokens: Optional[int] = None) -> int:
|
|
335
|
+
"""Token budget at which folding starts: min(band * window, ceiling)."""
|
|
336
|
+
window = cls.resolve_window(model, window_tokens)
|
|
337
|
+
return max(1, int(min(window * cls.fold_band(), cls.context_ceiling())))
|
|
338
|
+
|
|
305
339
|
@classmethod
|
|
306
340
|
def resolve_window(cls, model: str = "", window_tokens: Optional[int] = None) -> int:
|
|
307
341
|
"""Explicit window > env override > model-family default."""
|
|
@@ -430,12 +464,16 @@ class ContextBudget:
|
|
|
430
464
|
return "healthy", "Context budget healthy."
|
|
431
465
|
|
|
432
466
|
estimate_used = sum(breakdown.values())
|
|
467
|
+
effective_limit = cls.effective_limit(model, window_tokens)
|
|
433
468
|
if measured is not None:
|
|
434
469
|
used: Optional[int] = measured
|
|
435
470
|
pct: Optional[float] = round(measured / window * 100.0, 1) if window > 0 else 0.0
|
|
471
|
+
budget_pct: Optional[float] = (
|
|
472
|
+
round(measured / effective_limit * 100.0, 1) if effective_limit > 0 else 0.0
|
|
473
|
+
)
|
|
436
474
|
measurement = "measured"
|
|
437
475
|
used_source = measured_source
|
|
438
|
-
threshold, recommendation = _band(
|
|
476
|
+
threshold, recommendation = _band(budget_pct or 0.0)
|
|
439
477
|
caveat = (
|
|
440
478
|
"Measured: prompt tokens of the last request, read from the agent "
|
|
441
479
|
"transcript usage block."
|
|
@@ -443,9 +481,12 @@ class ContextBudget:
|
|
|
443
481
|
elif estimate_used > 0:
|
|
444
482
|
used = estimate_used
|
|
445
483
|
pct = round(estimate_used / window * 100.0, 1) if window > 0 else 0.0
|
|
484
|
+
budget_pct = (
|
|
485
|
+
round(estimate_used / effective_limit * 100.0, 1) if effective_limit > 0 else 0.0
|
|
486
|
+
)
|
|
446
487
|
measurement = "estimated"
|
|
447
488
|
used_source = "instrumented_events"
|
|
448
|
-
threshold, recommendation = _band(
|
|
489
|
+
threshold, recommendation = _band(budget_pct)
|
|
449
490
|
if threshold in ("critical", "warning"):
|
|
450
491
|
threshold = "notice"
|
|
451
492
|
recommendation = (
|
|
@@ -463,6 +504,7 @@ class ContextBudget:
|
|
|
463
504
|
else:
|
|
464
505
|
used = None
|
|
465
506
|
pct = None
|
|
507
|
+
budget_pct = None
|
|
466
508
|
measurement = "unknown"
|
|
467
509
|
used_source = ""
|
|
468
510
|
threshold = "unknown"
|
|
@@ -477,6 +519,10 @@ class ContextBudget:
|
|
|
477
519
|
"used_estimated": used if used is not None else 0,
|
|
478
520
|
"used_pct": pct,
|
|
479
521
|
"used_pct_is_estimate": measurement != "measured",
|
|
522
|
+
"effective_limit_tokens": effective_limit,
|
|
523
|
+
"budget_pct": budget_pct,
|
|
524
|
+
"fold_band": cls.fold_band(),
|
|
525
|
+
"ceiling_tokens": cls.context_ceiling(),
|
|
480
526
|
"measurement": measurement,
|
|
481
527
|
"used_source": used_source,
|
|
482
528
|
"measured_from": measured_from,
|
package/src/installer.py
CHANGED
|
@@ -60,7 +60,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
60
60
|
"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"
|
|
61
61
|
"`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
|
|
62
62
|
"11. **Proof-of-Savings Turn Footer (strictly English)**: Append on tool-using turns:\n"
|
|
63
|
-
"`⚡ **TokenSafe
|
|
63
|
+
"`⚡ **TokenSafe**: +<tokens> tokens / <steps> steps | Total <total> tokens`\n"
|
|
64
64
|
"12. **Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Angular, Go/Gin+Chi, FastAPI/Starlette, Express/Fastify, Next.js, Elysia on Bun, Spring Boot, Laravel/Symfony, ASP.NET Core; Flask/Django mount explicitly as WSGI), "
|
|
65
65
|
"ALWAYS prefer `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` BEFORE full file crawls, raw curls, or browser checks — "
|
|
66
66
|
"static OUMV works offline on read/edit tasks too (verify answers a labelled static subset without a runtime), and `tokensafe dev` starts zero-footprint live Vite RPC without touching repo files. "
|