tokensafe 4.12.1 → 4.12.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/.codex-plugin/plugin.json +1 -1
- package/hooks/pre_invocation.py +27 -0
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -1
- package/src/acp/server.py +137 -11
- package/src/adapter_core.py +2 -1
- package/src/agent/loop.py +18 -0
- package/src/burn_monitor.py +32 -1
- package/src/cli.py +53 -0
- package/src/format_parsers/i18n_strings.py +445 -0
- package/src/i18n_catalog.py +671 -0
- package/src/installer.py +3 -1
- package/src/mcp_config_manager.py +29 -2
- package/src/mcp_proxy.py +73 -25
- package/src/mcp_server.py +93 -3
- package/src/proxy.py +72 -6
- package/src/result_ledger.py +96 -0
- package/src/session_brief.py +12 -0
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/hooks/pre_invocation.py
CHANGED
|
@@ -280,6 +280,33 @@ def _handle(payload: dict) -> dict:
|
|
|
280
280
|
except Exception:
|
|
281
281
|
pass
|
|
282
282
|
|
|
283
|
+
# 5.5 Notification turns: no user text at all in this invocation means a
|
|
284
|
+
# subagent completion woke the orchestrator. A status ack at a 170k
|
|
285
|
+
# context costs more than the work it describes, so say so once.
|
|
286
|
+
try:
|
|
287
|
+
last_input = str(payload.get("lastUserInput") or payload.get("prompt") or "").strip()
|
|
288
|
+
if invocation_num >= 2 and not last_input:
|
|
289
|
+
if not tracker.get_last_event(conversation_id, "NOTIFICATION_TURN"):
|
|
290
|
+
inject_steps.append({
|
|
291
|
+
"systemMessage": {
|
|
292
|
+
"systemMessage": "",
|
|
293
|
+
"metadata": {"user_markdown": (
|
|
294
|
+
"⏳ **Notification turn:** no new user message in this invocation — a task "
|
|
295
|
+
"notification woke you. Reply in at most two lines, call no tools, and do not "
|
|
296
|
+
"re-read files. Batch the remaining notifications."
|
|
297
|
+
)},
|
|
298
|
+
}
|
|
299
|
+
})
|
|
300
|
+
tracker.record_event(
|
|
301
|
+
session_id=conversation_id,
|
|
302
|
+
event_type="NOTIFICATION_TURN",
|
|
303
|
+
original_tokens=0,
|
|
304
|
+
optimized_tokens=0,
|
|
305
|
+
details={"invocation_num": invocation_num},
|
|
306
|
+
)
|
|
307
|
+
except Exception:
|
|
308
|
+
pass
|
|
309
|
+
|
|
283
310
|
# 6. Multi-Agent Live Burn Monitor (rate-limited, only fires on real burn spikes)
|
|
284
311
|
if invocation_num >= 2 or transcript_path:
|
|
285
312
|
try:
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.12.
|
|
3
|
+
"version": "4.12.2",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "Apache-2.0",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.12.
|
|
4
|
+
"version": "4.12.2",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.12.
|
|
4
|
+
"version": "4.12.2",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
7
7
|
"logo": "assets/logo.png",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.12.
|
|
6
|
+
"version": "4.12.2",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.12.
|
|
26
|
+
"version": "4.12.2",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.12.
|
|
42
|
+
"version": "4.12.2",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -61,6 +61,12 @@ folds multi-turn conversation history, guards against secret leaks, and standard
|
|
|
61
61
|
- Run unit tests via `tokensafe tests [cmd]` or `tokensafe wrap '<cmd>'` (1-line summary on pass, full traceback on failure).
|
|
62
62
|
- Never load raw screenshots into long (>150k) sessions; delegate visual inspection to a subagent returning text-only findings.
|
|
63
63
|
|
|
64
|
+
9. **STRING CATALOGS / i18n (`dict`)**:
|
|
65
|
+
- NEVER read a whole `messages/<locale>/*.ts` (or `locales/*.json`) catalog to review or edit translations: it is 100% payload, and one subagent per locale that each re-reads the English oracle is the single most expensive workflow we know.
|
|
66
|
+
- Get only the suspect keys: `tokensafe dict lint --locale <l> --base en --json` (MCP: `run_helper(action="dict", command="lint --locale <l>")`). Reasons: `identical`, `missing`, `orphan`, `placeholder_mismatch`, `contains_english`, `glossary:<term>`, `length_ratio`, `duplicate`, `calque`.
|
|
67
|
+
- Write back with `tokensafe dict apply --locale <l> --patch patch.json --dry-run`, then without `--dry-run`. Edits are byte-preserving: formatting, comments and key order stay untouched.
|
|
68
|
+
- `smart_read_file` on a catalog returns a digest on purpose; `tokensafe dict show --locale <l> --keys a.b,c.d` returns exact values, and `expand_ref` restores the raw file.
|
|
69
|
+
|
|
64
70
|
---
|
|
65
71
|
|
|
66
72
|
## Core MCP Tools (`tokensafe` — 7 Consolidated Tools)
|
|
@@ -76,7 +82,7 @@ Quick reference:
|
|
|
76
82
|
- `tokensafe:repo_map(view="graph"|"api"|"tree", project_path=".")`
|
|
77
83
|
- `tokensafe:session_context(action="budget"|"compact"|"prune"|"mistakes"|"metrics", ...)`
|
|
78
84
|
- `tokensafe:oumv(action="status"|"observe"|"understand"|"verify"|"mutate"|"graph", ...)`
|
|
79
|
-
- `tokensafe:run_helper(action="sanitize"|"guard"|"diff"|"deps"|"web"|"expand"|"image"|"compress", ...)`
|
|
85
|
+
- `tokensafe:run_helper(action="sanitize"|"guard"|"diff"|"deps"|"web"|"expand"|"image"|"compress"|"dict", ...)`
|
|
80
86
|
|
|
81
87
|
---
|
|
82
88
|
|
package/src/acp/server.py
CHANGED
|
@@ -8,11 +8,17 @@ this adapter gives TokenSafe a native agent inside those editors without
|
|
|
8
8
|
anyone building an editor.
|
|
9
9
|
|
|
10
10
|
Scope of this server: sessions, prompts, streaming updates, tool call
|
|
11
|
-
visibility and cancellation. Embedded context (text
|
|
12
|
-
images are rejected with an explanation because the loop
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
11
|
+
visibility, client permission prompts and cancellation. Embedded context (text
|
|
12
|
+
blocks) is accepted; images are rejected with an explanation because the loop
|
|
13
|
+
has no vision path.
|
|
14
|
+
|
|
15
|
+
Permission prompts (ACP ``session/request_permission``) are a policy layer, not
|
|
16
|
+
a sandbox: by default the write-capable tools (``apply_edits``, the OUMV write
|
|
17
|
+
actions, ``run_helper(image)``) ask the editor, read-only tools proceed, and
|
|
18
|
+
``TOKENSAFE_ACP_PERMISSIONS=all|off`` widens or removes the layer. ``allow_always``
|
|
19
|
+
and ``reject_always`` are cached per session and tool name. Even without a
|
|
20
|
+
prompt, tool calls still run under the same guard as the MCP server (destructive
|
|
21
|
+
commands and secret reads are refused).
|
|
16
22
|
"""
|
|
17
23
|
|
|
18
24
|
from __future__ import annotations
|
|
@@ -21,18 +27,47 @@ import json
|
|
|
21
27
|
import os
|
|
22
28
|
import sys
|
|
23
29
|
import threading
|
|
30
|
+
import time
|
|
24
31
|
import uuid
|
|
25
32
|
from dataclasses import dataclass, field
|
|
26
|
-
from typing import Any, Callable, Dict, IO, List, Optional
|
|
33
|
+
from typing import Any, Callable, Dict, IO, List, Optional, Set
|
|
27
34
|
|
|
28
35
|
from src.agent.loop import DEFAULT_SYSTEM_PROMPT, AgentConfig, AgentLoop, RunResult
|
|
29
|
-
from src.agent.providers import Provider, ProviderError, resolve_provider
|
|
36
|
+
from src.agent.providers import Provider, ProviderError, ToolCall, resolve_provider
|
|
37
|
+
from src.agent.tools import tool_kind
|
|
30
38
|
|
|
31
39
|
PROTOCOL_VERSION = 1
|
|
32
40
|
SERVER_NAME = "tokensafe-agent"
|
|
33
41
|
|
|
34
42
|
_STOP_REASONS = {"end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled"}
|
|
35
43
|
|
|
44
|
+
_PERMISSION_POLICIES = frozenset({"off", "writes", "all"})
|
|
45
|
+
|
|
46
|
+
# ACP §session/request_permission option set. The agent decides which tools ask;
|
|
47
|
+
# the client decides the answer, and "always" answers are cached per session.
|
|
48
|
+
_PERMISSION_OPTIONS = [
|
|
49
|
+
{"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"},
|
|
50
|
+
{"optionId": "allow_always", "name": "Always allow this tool in this session", "kind": "allow_always"},
|
|
51
|
+
{"optionId": "reject_once", "name": "Reject once", "kind": "reject_once"},
|
|
52
|
+
{"optionId": "reject_always", "name": "Always reject this tool in this session", "kind": "reject_always"},
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
_OUMV_WRITE_ACTIONS = frozenset({"mutate", "preview", "verify", "build"})
|
|
56
|
+
_RUN_HELPER_WRITE_ACTIONS = frozenset({"image"})
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _requires_permission(name: str, arguments: Any) -> bool:
|
|
60
|
+
"""Tools whose default policy is "ask first": they write files or state."""
|
|
61
|
+
if name == "apply_edits":
|
|
62
|
+
return True
|
|
63
|
+
if isinstance(arguments, dict):
|
|
64
|
+
action = str(arguments.get("action") or "").strip().lower()
|
|
65
|
+
if name == "oumv" and action in _OUMV_WRITE_ACTIONS:
|
|
66
|
+
return True
|
|
67
|
+
if name == "run_helper" and action in _RUN_HELPER_WRITE_ACTIONS:
|
|
68
|
+
return True
|
|
69
|
+
return False
|
|
70
|
+
|
|
36
71
|
|
|
37
72
|
def _map_stop(reason: str) -> str:
|
|
38
73
|
if reason in _STOP_REASONS:
|
|
@@ -50,6 +85,15 @@ class _Session:
|
|
|
50
85
|
root: str
|
|
51
86
|
loop: AgentLoop
|
|
52
87
|
cancel: threading.Event = field(default_factory=threading.Event)
|
|
88
|
+
# Per-session "always" answers, keyed by tool name; a prompt is not repeated.
|
|
89
|
+
allow_always: Set[str] = field(default_factory=set)
|
|
90
|
+
reject_always: Set[str] = field(default_factory=set)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class _PendingPermission:
|
|
95
|
+
event: threading.Event = field(default_factory=threading.Event)
|
|
96
|
+
option_id: str = ""
|
|
53
97
|
|
|
54
98
|
|
|
55
99
|
class AcpServer:
|
|
@@ -65,6 +109,8 @@ class AcpServer:
|
|
|
65
109
|
writer: IO[str],
|
|
66
110
|
provider_factory: Optional[Callable[[str, str], Provider]] = None,
|
|
67
111
|
client_name: str = "",
|
|
112
|
+
permission_policy: str = "writes",
|
|
113
|
+
permission_timeout: float = 300.0,
|
|
68
114
|
):
|
|
69
115
|
self._reader = reader
|
|
70
116
|
self._writer = writer
|
|
@@ -73,6 +119,12 @@ class AcpServer:
|
|
|
73
119
|
self._workers: List[threading.Thread] = []
|
|
74
120
|
self._provider_factory = provider_factory or _default_provider
|
|
75
121
|
self._client_name = client_name
|
|
122
|
+
policy = str(permission_policy or "writes").strip().lower()
|
|
123
|
+
self._permission_policy = policy if policy in _PERMISSION_POLICIES else "writes"
|
|
124
|
+
self._permission_timeout = max(0.0, float(permission_timeout))
|
|
125
|
+
self._pending: Dict[str, _PendingPermission] = {}
|
|
126
|
+
self._pending_lock = threading.Lock()
|
|
127
|
+
self._request_seq = 0
|
|
76
128
|
|
|
77
129
|
# -- io ----------------------------------------------------------------
|
|
78
130
|
|
|
@@ -119,7 +171,10 @@ class AcpServer:
|
|
|
119
171
|
def handle(self, message: Dict[str, Any]) -> None:
|
|
120
172
|
method = message.get("method")
|
|
121
173
|
if not isinstance(method, str):
|
|
122
|
-
|
|
174
|
+
# A client response to an agent request (session/request_permission).
|
|
175
|
+
if message.get("id") is not None and ("result" in message or "error" in message):
|
|
176
|
+
self._resolve_client_response(message)
|
|
177
|
+
return
|
|
123
178
|
request_id = message.get("id")
|
|
124
179
|
params = message.get("params") if isinstance(message.get("params"), dict) else {}
|
|
125
180
|
|
|
@@ -151,6 +206,70 @@ class AcpServer:
|
|
|
151
206
|
# Client notifications we do not model (fs/terminal capability updates)
|
|
152
207
|
# are ignored rather than answered: notifications must never get a reply.
|
|
153
208
|
|
|
209
|
+
# -- permission prompts ------------------------------------------------
|
|
210
|
+
|
|
211
|
+
def _resolve_client_response(self, message: Dict[str, Any]) -> None:
|
|
212
|
+
request_id = str(message.get("id"))
|
|
213
|
+
with self._pending_lock:
|
|
214
|
+
pending = self._pending.pop(request_id, None)
|
|
215
|
+
if pending is None:
|
|
216
|
+
return
|
|
217
|
+
option_id = ""
|
|
218
|
+
result = message.get("result")
|
|
219
|
+
if isinstance(result, dict):
|
|
220
|
+
outcome = result.get("outcome")
|
|
221
|
+
if isinstance(outcome, dict) and outcome.get("outcome") == "selected":
|
|
222
|
+
option_id = str(outcome.get("optionId") or "")
|
|
223
|
+
pending.option_id = option_id
|
|
224
|
+
pending.event.set()
|
|
225
|
+
|
|
226
|
+
def _request_permission(self, session: _Session, call: ToolCall) -> bool:
|
|
227
|
+
"""Ask the editor before a write-capable tool runs; block the worker."""
|
|
228
|
+
if self._permission_policy == "off":
|
|
229
|
+
return True
|
|
230
|
+
if self._permission_policy != "all" and not _requires_permission(call.name, call.arguments):
|
|
231
|
+
return True
|
|
232
|
+
if call.name in session.reject_always:
|
|
233
|
+
return False
|
|
234
|
+
if call.name in session.allow_always:
|
|
235
|
+
return True
|
|
236
|
+
|
|
237
|
+
with self._pending_lock:
|
|
238
|
+
self._request_seq += 1
|
|
239
|
+
request_id = f"perm-{session.session_id}-{self._request_seq}"
|
|
240
|
+
pending = _PendingPermission()
|
|
241
|
+
self._pending[request_id] = pending
|
|
242
|
+
self._write(
|
|
243
|
+
{
|
|
244
|
+
"jsonrpc": "2.0",
|
|
245
|
+
"id": request_id,
|
|
246
|
+
"method": "session/request_permission",
|
|
247
|
+
"params": {
|
|
248
|
+
"sessionId": session.session_id,
|
|
249
|
+
"toolCall": {
|
|
250
|
+
"toolCallId": call.id,
|
|
251
|
+
"title": _tool_title(call.name, call.arguments),
|
|
252
|
+
"kind": tool_kind(call.name),
|
|
253
|
+
"status": "pending",
|
|
254
|
+
"rawInput": call.arguments,
|
|
255
|
+
},
|
|
256
|
+
"options": _PERMISSION_OPTIONS,
|
|
257
|
+
},
|
|
258
|
+
}
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
deadline = time.time() + self._permission_timeout
|
|
262
|
+
while not pending.event.wait(0.05):
|
|
263
|
+
if session.cancel.is_set() or time.time() >= deadline:
|
|
264
|
+
with self._pending_lock:
|
|
265
|
+
self._pending.pop(request_id, None)
|
|
266
|
+
return False
|
|
267
|
+
if pending.option_id == "allow_always":
|
|
268
|
+
session.allow_always.add(call.name)
|
|
269
|
+
elif pending.option_id == "reject_always":
|
|
270
|
+
session.reject_always.add(call.name)
|
|
271
|
+
return pending.option_id.startswith("allow")
|
|
272
|
+
|
|
154
273
|
# -- methods -----------------------------------------------------------
|
|
155
274
|
|
|
156
275
|
def _initialize(self, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
@@ -174,12 +293,16 @@ class AcpServer:
|
|
|
174
293
|
root = os.path.realpath(cwd) if cwd and os.path.isdir(cwd) else os.path.realpath(os.getcwd())
|
|
175
294
|
session_id = f"acp-{uuid.uuid4().hex[:12]}"
|
|
176
295
|
provider = self._provider_factory(root, session_id)
|
|
296
|
+
# The loop asks this before a write-capable tool runs; the session object
|
|
297
|
+
# is created first because the callback needs its allow/reject cache.
|
|
298
|
+
session = _Session(session_id=session_id, root=root, loop=None) # type: ignore[arg-type]
|
|
177
299
|
config = AgentConfig(
|
|
178
300
|
system_prompt=(
|
|
179
301
|
DEFAULT_SYSTEM_PROMPT
|
|
180
302
|
+ f"\n\nActive workspace: {root}\n"
|
|
181
303
|
+ "All paths are resolved against this root. Absolute paths outside it are refused."
|
|
182
|
-
)
|
|
304
|
+
),
|
|
305
|
+
permission_handler=lambda call: self._request_permission(session, call),
|
|
183
306
|
)
|
|
184
307
|
loop = AgentLoop(
|
|
185
308
|
root=root,
|
|
@@ -188,7 +311,8 @@ class AcpServer:
|
|
|
188
311
|
config=config,
|
|
189
312
|
event_sink=lambda event: self._forward_update(session_id, event),
|
|
190
313
|
)
|
|
191
|
-
|
|
314
|
+
session.loop = loop
|
|
315
|
+
self._sessions[session_id] = session
|
|
192
316
|
return {"sessionId": session_id}
|
|
193
317
|
|
|
194
318
|
def _start_prompt(self, request_id: Any, params: Dict[str, Any]) -> None:
|
|
@@ -316,7 +440,9 @@ def _version() -> str:
|
|
|
316
440
|
|
|
317
441
|
|
|
318
442
|
def run_acp_server(provider_factory: Optional[Callable[[str, str], Provider]] = None) -> None:
|
|
319
|
-
|
|
443
|
+
# Editors expect the prompt; headless harnesses set off|all explicitly.
|
|
444
|
+
policy = os.environ.get("TOKENSAFE_ACP_PERMISSIONS", "writes")
|
|
445
|
+
server = AcpServer(sys.stdin, sys.stdout, provider_factory=provider_factory, permission_policy=policy)
|
|
320
446
|
server.serve()
|
|
321
447
|
|
|
322
448
|
|
package/src/adapter_core.py
CHANGED
|
@@ -46,7 +46,8 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
46
46
|
"• Prohibited File Edits: NEVER use 'sed -i', 'perl -i', or stream editors to modify source files; ALWAYS use 'edit_file' with exact string targets. NEVER suppress errors with '2>/dev/null'.\n"
|
|
47
47
|
"• Prefer 'edit_file' over 'write_file' for existing files.\n"
|
|
48
48
|
"• Universal OUMV Protocol (Mandatory When Supported): If the workspace reports an OUMV-supported stack (React+Vite, Vue, Solid, Angular, Go, FastAPI, Express/Fastify, Next.js, Elysia on Bun, ASP.NET Core), ALWAYS prefer the 'oumv' MCP tool (status/observe/understand/verify) before full file crawls, raw curl, or browser checks — even when only reading/editing files (static AST OUMV works offline; use 'tokensafe dev' for zero-footprint live Vite RPC). Check capability boundaries in mixed monorepos (for unsupported stacks like backend/node Express/Fastify/Nest, use repo_map/smart_read_file/scoped_search).\n"
|
|
49
|
-
"• Multi-Root Sessions: the OUMV routing brief is classified PER workspace root (hosts that report several folders get every root listed). A single-root verdict never describes another repo — before editing a repo outside the listed roots, call 'oumv' with workspace_dir='<that repo>'; never conclude 'OUMV is unavailable' from one root's line
|
|
49
|
+
"• Multi-Root Sessions: the OUMV routing brief is classified PER workspace root (hosts that report several folders get every root listed). A single-root verdict never describes another repo — before editing a repo outside the listed roots, call 'oumv' with workspace_dir='<that repo>'; never conclude 'OUMV is unavailable' from one root's line.\n"
|
|
50
|
+
"• String Catalogs (i18n): NEVER read a whole messages/<locale>/*.ts catalog, and never spawn one subagent per locale that each re-reads the English files. Run 'tokensafe dict lint --locale <l> --base en' (MCP: run_helper(action='dict', command='lint --locale <l>')) to get only the suspect keys, then patch them with 'tokensafe dict apply --locale <l> --patch patch.json' (add --dry-run first). smart_read_file on a catalog returns a digest by design; 'dict show --keys a.b' returns exact values."
|
|
50
51
|
)
|
|
51
52
|
|
|
52
53
|
# High-precision deny patterns: secrets and irreversible destruction only.
|
package/src/agent/loop.py
CHANGED
|
@@ -56,6 +56,10 @@ class AgentConfig:
|
|
|
56
56
|
tool_names: Sequence[str] = DEFAULT_TOOL_NAMES
|
|
57
57
|
compact_prompt_intake: bool = False
|
|
58
58
|
max_tool_result_chars: int = 24000
|
|
59
|
+
# Asked before a tool runs; False turns the call into a failed tool result.
|
|
60
|
+
# The ACP server uses it for client permission prompts, and keeping it on the
|
|
61
|
+
# config means the loop itself stays transport-agnostic.
|
|
62
|
+
permission_handler: Optional[Callable[[ToolCall], bool]] = None
|
|
59
63
|
|
|
60
64
|
|
|
61
65
|
@dataclass
|
|
@@ -304,6 +308,20 @@ class AgentLoop:
|
|
|
304
308
|
f"arguments for '{call.name}'."
|
|
305
309
|
),
|
|
306
310
|
)
|
|
311
|
+
if self.config.permission_handler is not None:
|
|
312
|
+
try:
|
|
313
|
+
allowed = bool(self.config.permission_handler(call))
|
|
314
|
+
except Exception:
|
|
315
|
+
allowed = False
|
|
316
|
+
if not allowed:
|
|
317
|
+
return ToolResult(
|
|
318
|
+
name=call.name,
|
|
319
|
+
ok=False,
|
|
320
|
+
text=(
|
|
321
|
+
f"Tool call rejected: the client did not grant permission for '{call.name}'. "
|
|
322
|
+
"The call was not executed; explain the refusal instead of retrying it unchanged."
|
|
323
|
+
),
|
|
324
|
+
)
|
|
307
325
|
return dispatch_tool(call.name, call.arguments)
|
|
308
326
|
|
|
309
327
|
def _compact_intake(self, prompt: str) -> str:
|
package/src/burn_monitor.py
CHANGED
|
@@ -225,6 +225,8 @@ def _scan_zcode_tail(home: str, session_id: str = "", explicit_path: str = "") -
|
|
|
225
225
|
zero_usage = 0
|
|
226
226
|
tool_schema_tokens = 0
|
|
227
227
|
turns = 0
|
|
228
|
+
prev_ts: Optional[float] = None
|
|
229
|
+
max_gap_s = 0.0
|
|
228
230
|
|
|
229
231
|
for ln in lines[-20:]:
|
|
230
232
|
try:
|
|
@@ -232,6 +234,11 @@ def _scan_zcode_tail(home: str, session_id: str = "", explicit_path: str = "") -
|
|
|
232
234
|
except Exception:
|
|
233
235
|
continue
|
|
234
236
|
turns += 1
|
|
237
|
+
ts = _parse_iso(obj.get("startedAt") or obj.get("created_at") or obj.get("timestamp"))
|
|
238
|
+
if ts is not None:
|
|
239
|
+
if prev_ts is not None:
|
|
240
|
+
max_gap_s = max(max_gap_s, ts - prev_ts)
|
|
241
|
+
prev_ts = ts
|
|
235
242
|
m_info = obj.get("model")
|
|
236
243
|
m_id = (m_info.get("modelId") or m_info.get("id") or "") if isinstance(m_info, dict) else str(m_info or "")
|
|
237
244
|
if m_id:
|
|
@@ -297,6 +304,7 @@ def _scan_zcode_tail(home: str, session_id: str = "", explicit_path: str = "") -
|
|
|
297
304
|
"tool_schema_tokens": tool_schema_tokens,
|
|
298
305
|
"active_parallel_sessions": active_parallel,
|
|
299
306
|
"rate_limit_hits": rate_limit_hits,
|
|
307
|
+
"max_gap_seconds": round(max_gap_s, 1),
|
|
300
308
|
}
|
|
301
309
|
|
|
302
310
|
|
|
@@ -447,7 +455,10 @@ def evaluate_burn_warnings(
|
|
|
447
455
|
model = str(snapshot.get("model") or "")
|
|
448
456
|
m_lower = model.lower()
|
|
449
457
|
in_tok = int(snapshot.get("last_input_tokens") or 0)
|
|
450
|
-
|
|
458
|
+
# A measured 0% cache hit must stay 0 — `or 100.0` used to swallow the
|
|
459
|
+
# exact case the cache_crash / cold_restart warnings exist to catch.
|
|
460
|
+
cache_hit_raw = snapshot.get("cache_hit_pct")
|
|
461
|
+
cache_hit = float(cache_hit_raw) if cache_hit_raw is not None else 100.0
|
|
451
462
|
turns = int(snapshot.get("turns_sampled") or 0)
|
|
452
463
|
switches = int(snapshot.get("model_switches") or 0)
|
|
453
464
|
parallel = int(snapshot.get("active_parallel_sessions") or 0)
|
|
@@ -455,6 +466,7 @@ def evaluate_burn_warnings(
|
|
|
455
466
|
vis_c = int(snapshot.get("visible_chars") or 0)
|
|
456
467
|
tool_tok = int(snapshot.get("tool_schema_tokens") or 0)
|
|
457
468
|
rl_hits = snapshot.get("rate_limit_hits") or {}
|
|
469
|
+
max_gap = float(snapshot.get("max_gap_seconds") or 0.0)
|
|
458
470
|
|
|
459
471
|
if in_tok >= 120000:
|
|
460
472
|
warnings.append({
|
|
@@ -465,6 +477,25 @@ def evaluate_burn_warnings(
|
|
|
465
477
|
),
|
|
466
478
|
})
|
|
467
479
|
|
|
480
|
+
if max_gap >= 180 and in_tok >= 100000:
|
|
481
|
+
warnings.append({
|
|
482
|
+
"code": "cache_ttl_idle",
|
|
483
|
+
"message": (
|
|
484
|
+
f"{int(max_gap)}s of silence at a {in_tok:,}-token context: the provider's prompt cache "
|
|
485
|
+
f"has almost certainly expired, so the next turn is billed fully uncached. "
|
|
486
|
+
f"Compact before you resume."
|
|
487
|
+
),
|
|
488
|
+
})
|
|
489
|
+
|
|
490
|
+
if turns >= 2 and in_tok >= 50000 and cache_hit <= 0.0:
|
|
491
|
+
warnings.append({
|
|
492
|
+
"code": "cold_restart",
|
|
493
|
+
"message": (
|
|
494
|
+
f"The last turn re-sent {in_tok:,} tokens with a 0% cache hit — the provider re-billed "
|
|
495
|
+
f"the whole history at full price. Start a fresh session or compact now."
|
|
496
|
+
),
|
|
497
|
+
})
|
|
498
|
+
|
|
468
499
|
if turns >= 2 and in_tok >= 20000 and cache_hit < 50.0:
|
|
469
500
|
extra = " (triggered by mid-session model switch)" if switches > 0 else ""
|
|
470
501
|
warnings.append({
|
package/src/cli.py
CHANGED
|
@@ -109,6 +109,7 @@ def _print_help():
|
|
|
109
109
|
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
110
110
|
print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
|
|
111
111
|
print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
|
|
112
|
+
print(" dict lint|coverage|show|apply String catalogs: suspect keys only, byte-preserving write-back")
|
|
112
113
|
print(" status One-screen health check: hooks, weekly savings, tier, sync")
|
|
113
114
|
print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
|
|
114
115
|
print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
|
|
@@ -964,6 +965,58 @@ def main(argv: Optional[List[str]] = None):
|
|
|
964
965
|
proc = subprocess.run(cmd, cwd=target_dir, env=oumv_policy.spawn_env())
|
|
965
966
|
sys.exit(proc.returncode)
|
|
966
967
|
|
|
968
|
+
elif command in ("dict", "i18n"):
|
|
969
|
+
# Deterministic string-catalog audit: lint suspects only, write back
|
|
970
|
+
# without reformatting. Replaces "read 18 catalog files per locale".
|
|
971
|
+
from src import i18n_catalog as _dict
|
|
972
|
+
|
|
973
|
+
def _dflag(name: str, default: str = "") -> str:
|
|
974
|
+
for i, arg in enumerate(args):
|
|
975
|
+
if arg == name and i + 1 < len(args):
|
|
976
|
+
return args[i + 1]
|
|
977
|
+
if arg.startswith(name + "="):
|
|
978
|
+
return arg.split("=", 1)[1]
|
|
979
|
+
return default
|
|
980
|
+
|
|
981
|
+
sub = args[1] if len(args) > 1 and not args[1].startswith("-") else ""
|
|
982
|
+
if not sub or sub in ("help", "--help", "-h"):
|
|
983
|
+
print(
|
|
984
|
+
"\n tokensafe dict lint --locale ru [--base en] [--severity high|all] [--limit N] [--json]"
|
|
985
|
+
"\n tokensafe dict coverage [--base en] [--json]"
|
|
986
|
+
"\n tokensafe dict show --locale ru --keys a.b,c.d [--json]"
|
|
987
|
+
"\n tokensafe dict apply --locale ru --patch patch.json [--dry-run]"
|
|
988
|
+
"\n"
|
|
989
|
+
"\n Lint lists only suspect keys — untranslated, missing, orphan, placeholder"
|
|
990
|
+
"\n drift, English leakage, brand loss, length outliers, calque smells."
|
|
991
|
+
"\n apply writes values back in place: formatting, comments and key order"
|
|
992
|
+
"\n are preserved byte-for-byte. --root picks the project (default: cwd).\n"
|
|
993
|
+
)
|
|
994
|
+
return
|
|
995
|
+
|
|
996
|
+
root = _dflag("--root") or os.getcwd()
|
|
997
|
+
messages_dir = _dict.resolve_messages_dir(root)
|
|
998
|
+
if not messages_dir:
|
|
999
|
+
print(f"\n no message catalog found under {root}\n pass --root <project>\n")
|
|
1000
|
+
sys.exit(1)
|
|
1001
|
+
flags = {
|
|
1002
|
+
"locale": _dflag("--locale") or _dflag("--l"),
|
|
1003
|
+
"base": _dflag("--base", "en"),
|
|
1004
|
+
"keys": _dflag("--keys"),
|
|
1005
|
+
"patch": _dflag("--patch"),
|
|
1006
|
+
"severity": _dflag("--severity", "all"),
|
|
1007
|
+
"limit": _dflag("--limit", "0"),
|
|
1008
|
+
"dry_run": "1" if "--dry-run" in args else _dflag("--dry-run"),
|
|
1009
|
+
}
|
|
1010
|
+
try:
|
|
1011
|
+
text, payload = _dict.run_command(messages_dir, sub, flags)
|
|
1012
|
+
except (ValueError, json.JSONDecodeError) as exc:
|
|
1013
|
+
print(f"\n dict {sub}: {exc}\n")
|
|
1014
|
+
sys.exit(1)
|
|
1015
|
+
if "--json" in args:
|
|
1016
|
+
print(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
1017
|
+
else:
|
|
1018
|
+
print(text)
|
|
1019
|
+
|
|
967
1020
|
elif command in ("bench-oumv", "bench_oumv"):
|
|
968
1021
|
# Measured, agent-driven benchmark (DeepSeek by default): real oracle,
|
|
969
1022
|
# provider-side token accounting, hard budget cap.
|