tokensafe 4.13.2 → 4.14.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/README.md +12 -2
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +1 -1
- package/src/atomic_io.py +74 -0
- package/src/auto_inject.py +42 -3
- package/src/backend_release.py +3 -3
- package/src/batch_editor.py +2 -14
- package/src/cache_normalizer.py +1 -1
- package/src/cli.py +4 -0
- package/src/graph_engine.py +19 -0
- package/src/installer.py +4 -4
- package/src/mcp_server.py +124 -38
- package/src/oumv_gateway.py +221 -6
- package/src/retrofit.py +13 -7
- package/src/scoped_search.py +15 -7
- package/src/session_brief.py +171 -78
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/README.md
CHANGED
|
@@ -233,11 +233,21 @@ You install TokenSafe, open a project in your agent, and the first turn does the
|
|
|
233
233
|
older Next gets the two route files plus a manual snippet. `--revert` deletes
|
|
234
234
|
exactly the files it created and restores a pre-existing v1 route it upgraded;
|
|
235
235
|
* Elysia (Bun) — one `app.use(oumv())` line before `app.listen()`
|
|
236
|
-
(`tokensafe-backend-node/elysia`), same markers and byte-exact revert
|
|
236
|
+
(`tokensafe-backend-node/elysia`), same markers and byte-exact revert;
|
|
237
|
+
* Flask / Django — certified WSGI adapters mounted explicitly: `mount_tokensafe(app)` in the
|
|
238
|
+
app factory (wraps `app.wsgi_app`) or `mount_tokensafe(application)` in `wsgi.py`;
|
|
239
|
+
`tokensafe inject --status` prints the recipe and writes nothing, because the WSGI
|
|
240
|
+
application is yours to wrap.
|
|
237
241
|
3. **Brief the agent** — a short routing block (hook context and MCP `instructions`) says which
|
|
238
242
|
stack is worked through OUMV and which through the TokenSafe tools. Nothing is written into
|
|
239
243
|
the repository by the brief.
|
|
240
244
|
|
|
245
|
+
Without a live runtime `oumv` stays useful and says what it did: `observe`/`understand`/`index`
|
|
246
|
+
answer from the static graph, `verify` answers a labelled static subset (`OFFLINE_STATIC_VERIFY`:
|
|
247
|
+
file exists, syntax, OCC version, symbol/route presence) instead of failing, and `observe` on a
|
|
248
|
+
file at L1+ returns the same skeleton a read would and seeds the read cache — a later
|
|
249
|
+
`smart_read_file` on that file returns a pointer instead of the body again.
|
|
250
|
+
|
|
241
251
|
```bash
|
|
242
252
|
tokensafe inject --status # what would be wired, and where
|
|
243
253
|
tokensafe inject --dry-run # same, but explicit
|
|
@@ -256,7 +266,7 @@ Full matrix and details: [docs/OUMV.md](docs/OUMV.md).
|
|
|
256
266
|
Real 12-assertion oracle re-run after every step; tokens and cost from the provider's `usage`
|
|
257
267
|
payload. `baseline` = file/search/command tools, `tokensafe` = this product's MCP server
|
|
258
268
|
(`smart_read_file(endpoint="POST /api/…")` in one call → `apply_edits` with the hunk and inline
|
|
259
|
-
`verify="auto"`), `oumv` = the OUMV runtime
|
|
269
|
+
`verify="auto"`), `oumv` = the OUMV runtime measured in November 2026 (`observe L3` returns the handler, its
|
|
260
270
|
version and the same-package callees; `applyEdit mode=patch` carries an inline `verify` probe and
|
|
261
271
|
an actionable `-32009`). The Go sandbox is the benchmark module plus **200 generated service
|
|
262
272
|
files**; the React sandbox is a TaskManager store + component whose declared `npm test` is the
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.14.0",
|
|
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.
|
|
4
|
+
"version": "4.14.0",
|
|
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.
|
|
4
|
+
"version": "4.14.0",
|
|
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.
|
|
6
|
+
"version": "4.14.0",
|
|
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.
|
|
26
|
+
"version": "4.14.0",
|
|
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.
|
|
42
|
+
"version": "4.14.0",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
package/src/adapter_core.py
CHANGED
|
@@ -45,7 +45,7 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
45
45
|
"• When context budget reports warning/critical or Grade C/F: call 'tokensafe:session_context(action=\"compact\", transcript_path=...)' to fold history before continuing.\n"
|
|
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
|
-
"• 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).
|
|
48
|
+
"• Universal OUMV Protocol (Mandatory When Supported): If the workspace reports an OUMV-supported stack (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), 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 and verify answers a labelled static subset without a runtime; use 'tokensafe dev' for zero-footprint live Vite RPC). Stacks without an adapter (Nest/Hono/Koa, Svelte, Go/Echo) use repo_map/smart_read_file/scoped_search.\n"
|
|
49
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
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."
|
|
51
51
|
)
|
package/src/atomic_io.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Crash-safe file writes.
|
|
2
|
+
|
|
3
|
+
A process killed between ``open()`` and the final rename would leave a
|
|
4
|
+
truncated file, and a power loss after ``os.replace`` can lose the rename
|
|
5
|
+
unless the directory entry is fsynced. OUMV mutations and ``apply_edits`` are
|
|
6
|
+
the two places where a half-written source file is unacceptable, so both go
|
|
7
|
+
through this helper: same-directory temp file -> flush + fsync -> chmod ->
|
|
8
|
+
``os.replace`` -> directory fsync on POSIX. Windows has no directory fsync;
|
|
9
|
+
``os.replace`` there is still atomic against a process crash.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import stat
|
|
16
|
+
import tempfile
|
|
17
|
+
from typing import Optional, Union
|
|
18
|
+
|
|
19
|
+
__all__ = ["write_atomic", "write_text_atomic"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _fsync_directory(directory: str) -> None:
|
|
23
|
+
if os.name != "posix" or not hasattr(os, "O_DIRECTORY"):
|
|
24
|
+
return
|
|
25
|
+
try:
|
|
26
|
+
fd = os.open(directory, os.O_DIRECTORY)
|
|
27
|
+
except OSError:
|
|
28
|
+
return
|
|
29
|
+
try:
|
|
30
|
+
os.fsync(fd)
|
|
31
|
+
finally:
|
|
32
|
+
os.close(fd)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def write_atomic(path: str, data: Union[bytes, str], *, mode: Optional[int] = None,
|
|
36
|
+
fsync: bool = True) -> str:
|
|
37
|
+
"""Writes ``data`` to ``path`` atomically and durably.
|
|
38
|
+
|
|
39
|
+
``mode`` defaults to the target's current permission bits (a new file keeps
|
|
40
|
+
the ``mkstemp`` 0600). Returns the path.
|
|
41
|
+
"""
|
|
42
|
+
abs_path = os.path.abspath(path)
|
|
43
|
+
directory = os.path.dirname(abs_path) or "."
|
|
44
|
+
os.makedirs(directory, exist_ok=True)
|
|
45
|
+
if mode is None and os.path.exists(abs_path):
|
|
46
|
+
try:
|
|
47
|
+
mode = stat.S_IMODE(os.stat(abs_path).st_mode)
|
|
48
|
+
except OSError:
|
|
49
|
+
mode = None
|
|
50
|
+
|
|
51
|
+
payload = data.encode("utf-8") if isinstance(data, str) else data
|
|
52
|
+
fd, tmp_path = tempfile.mkstemp(prefix=".tokensafe_atomic_", dir=directory)
|
|
53
|
+
try:
|
|
54
|
+
with os.fdopen(fd, "wb") as handle:
|
|
55
|
+
handle.write(payload)
|
|
56
|
+
handle.flush()
|
|
57
|
+
if fsync:
|
|
58
|
+
os.fsync(handle.fileno())
|
|
59
|
+
os.chmod(tmp_path, mode if mode is not None else 0o600)
|
|
60
|
+
os.replace(tmp_path, abs_path)
|
|
61
|
+
except BaseException:
|
|
62
|
+
try:
|
|
63
|
+
os.unlink(tmp_path)
|
|
64
|
+
except OSError:
|
|
65
|
+
pass
|
|
66
|
+
raise
|
|
67
|
+
if fsync:
|
|
68
|
+
_fsync_directory(directory)
|
|
69
|
+
return abs_path
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def write_text_atomic(path: str, text: str, *, mode: Optional[int] = None,
|
|
73
|
+
fsync: bool = True) -> str:
|
|
74
|
+
return write_atomic(path, text, mode=mode, fsync=fsync)
|
package/src/auto_inject.py
CHANGED
|
@@ -51,6 +51,18 @@ mux.Mount("/__oumv/rpc")
|
|
|
51
51
|
// oumv "github.com/tokensafe-dev/tokensafe-backend/go/pkg/oumv"
|
|
52
52
|
// oumvstdhttp "github.com/tokensafe-dev/tokensafe-backend/go/pkg/adapters/stdhttp"'''
|
|
53
53
|
|
|
54
|
+
# WSGI hosts (Flask, Django) are certified adapters but mount explicitly: the
|
|
55
|
+
# adapter wraps the WSGI application, so there is no app factory or mux line to
|
|
56
|
+
# patch safely. The plan shows the recipe and apply() writes nothing.
|
|
57
|
+
_PY_MANUAL_SNIPPETS = {
|
|
58
|
+
"flask": '''# in the app factory, after `app = Flask(__name__)`
|
|
59
|
+
from tokensafe_python.adapters.flask import mount_tokensafe
|
|
60
|
+
mount_tokensafe(app) # wraps app.wsgi_app; routes come from app.url_map''',
|
|
61
|
+
"django": '''# in <project>/wsgi.py, after `application = get_wsgi_application()`
|
|
62
|
+
from tokensafe_python.adapters.django import mount_tokensafe
|
|
63
|
+
application = mount_tokensafe(application)''',
|
|
64
|
+
}
|
|
65
|
+
|
|
54
66
|
_GO_ADAPTERS = {
|
|
55
67
|
"gin": (
|
|
56
68
|
"oumvgin",
|
|
@@ -1921,12 +1933,12 @@ _SIDECARS = {
|
|
|
1921
1933
|
"spring": (
|
|
1922
1934
|
"java/src/dev/tokensafe/oumv/OumvSpring.java",
|
|
1923
1935
|
"OumvSpring.java",
|
|
1924
|
-
"
|
|
1936
|
+
"edcb33b5c250ef6a087f20efe4fd9ebd8519f03e2f6f2f8484ff26835cf06694",
|
|
1925
1937
|
),
|
|
1926
1938
|
"php": (
|
|
1927
1939
|
"php/bin/oumv-php",
|
|
1928
1940
|
"oumv-php",
|
|
1929
|
-
"
|
|
1941
|
+
"ed61eabc1cd92b775a014a380f393922a3046a476ef9ed24d63a083623efefb2",
|
|
1930
1942
|
),
|
|
1931
1943
|
}
|
|
1932
1944
|
|
|
@@ -2216,7 +2228,21 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
2216
2228
|
continue
|
|
2217
2229
|
|
|
2218
2230
|
install = _backend_install(catalog, provider)
|
|
2219
|
-
if provider in ("fastapi", "python") and framework in ("
|
|
2231
|
+
if provider in ("fastapi", "python") and framework in ("flask", "django"):
|
|
2232
|
+
actions.append({
|
|
2233
|
+
"kind": "python_manual_mount",
|
|
2234
|
+
"profile": "backend",
|
|
2235
|
+
"app": root,
|
|
2236
|
+
"framework": framework,
|
|
2237
|
+
"writes_repo": False,
|
|
2238
|
+
"status": "manual",
|
|
2239
|
+
"snippet": _PY_MANUAL_SNIPPETS[framework],
|
|
2240
|
+
"reason": info.get("note") or (
|
|
2241
|
+
"WSGI host: the adapter wraps the WSGI application, so inject cannot patch it"
|
|
2242
|
+
),
|
|
2243
|
+
"install": install,
|
|
2244
|
+
})
|
|
2245
|
+
elif provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
|
|
2220
2246
|
actions.append({
|
|
2221
2247
|
"kind": "python_autoload",
|
|
2222
2248
|
"profile": "backend",
|
|
@@ -2389,6 +2415,19 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
|
|
|
2389
2415
|
})
|
|
2390
2416
|
continue
|
|
2391
2417
|
|
|
2418
|
+
if provider in ("fastapi", "python") and framework in ("flask", "django"):
|
|
2419
|
+
results["actions"].append({
|
|
2420
|
+
"kind": "python_manual_mount",
|
|
2421
|
+
"profile": "backend",
|
|
2422
|
+
"app": root,
|
|
2423
|
+
"status": "manual",
|
|
2424
|
+
"framework": framework,
|
|
2425
|
+
"writes_repo": False,
|
|
2426
|
+
"snippet": _PY_MANUAL_SNIPPETS[framework],
|
|
2427
|
+
"reason": "WSGI host: mount_tokensafe() wraps the WSGI application; inject writes nothing",
|
|
2428
|
+
})
|
|
2429
|
+
continue
|
|
2430
|
+
|
|
2392
2431
|
if provider in ("fastapi", "python") and framework in ("fastapi", "starlette"):
|
|
2393
2432
|
if dry_run:
|
|
2394
2433
|
action = {
|
package/src/backend_release.py
CHANGED
|
@@ -10,7 +10,7 @@ from __future__ import annotations
|
|
|
10
10
|
|
|
11
11
|
# Backend tag (`vX.Y.Z`); the Go module resolves against the matching `go/vX.Y.Z`,
|
|
12
12
|
# which the backend release workflow creates alongside it.
|
|
13
|
-
BACKEND_RELEASE_TAG = "v0.
|
|
13
|
+
BACKEND_RELEASE_TAG = "v0.21.0"
|
|
14
14
|
|
|
15
15
|
# Wire version that tag speaks. Printed in briefs so an agent never mixes a
|
|
16
16
|
# backend release with an older protocol line.
|
|
@@ -19,9 +19,9 @@ BACKEND_WIRE_VERSION = "1.8.0"
|
|
|
19
19
|
# npm release of `tokensafe-backend-node` that ships the same adapters. The
|
|
20
20
|
# package has its own semver line (`node/package.json`), so it is pinned
|
|
21
21
|
# separately from the Go tag; `tokensafe inject` installs exactly this version.
|
|
22
|
-
BACKEND_NPM_VERSION = "0.
|
|
22
|
+
BACKEND_NPM_VERSION = "0.16.0"
|
|
23
23
|
|
|
24
24
|
# NuGet release of `TokenSafe.Oumv.AspNetCore`. It has its own semver line too
|
|
25
25
|
# (`dotnet/src/TokenSafe.Oumv/TokenSafe.Oumv.csproj`), so tying it to the Go tag
|
|
26
26
|
# would ask NuGet for a version that does not exist.
|
|
27
|
-
BACKEND_DOTNET_VERSION = "0.
|
|
27
|
+
BACKEND_DOTNET_VERSION = "0.8.0"
|
package/src/batch_editor.py
CHANGED
|
@@ -304,20 +304,8 @@ def _normalize_eol(text: str, newline: str) -> str:
|
|
|
304
304
|
def _write_atomic(abs_path: str, content: str, mode: Optional[int]) -> None:
|
|
305
305
|
"""Writes through a same-directory temp file + os.replace, so a failed write
|
|
306
306
|
never leaves a truncated target. Preserves `mode` when provided."""
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
try:
|
|
310
|
-
with os.fdopen(fd, "w", encoding="utf-8", newline="") as f:
|
|
311
|
-
f.write(content)
|
|
312
|
-
if mode is not None:
|
|
313
|
-
os.chmod(tmp_path, stat.S_IMODE(mode))
|
|
314
|
-
os.replace(tmp_path, abs_path)
|
|
315
|
-
except BaseException:
|
|
316
|
-
try:
|
|
317
|
-
os.unlink(tmp_path)
|
|
318
|
-
except OSError:
|
|
319
|
-
pass
|
|
320
|
-
raise
|
|
307
|
+
from src.atomic_io import write_text_atomic
|
|
308
|
+
write_text_atomic(abs_path, content, mode=stat.S_IMODE(mode) if mode is not None else None)
|
|
321
309
|
|
|
322
310
|
|
|
323
311
|
def _apply_hunk_to_text(
|
package/src/cache_normalizer.py
CHANGED
|
@@ -117,7 +117,7 @@ class PromptCacheNormalizer:
|
|
|
117
117
|
re.compile(r"Generated locally at \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", re.IGNORECASE),
|
|
118
118
|
re.compile(r"⚡ \*\*TokenSafe Turn Savings\*\*:.*?(?=\n|$)", re.IGNORECASE),
|
|
119
119
|
re.compile(r"\(TokenSafe: compacted ~?\d[\d,]* prompt tokens.*?\)", re.IGNORECASE),
|
|
120
|
-
re.compile(r"\[TokenSafe
|
|
120
|
+
re.compile(r"\[TokenSafe(?: Subagent Firewall)?: Pointer Hit .*?\]", re.IGNORECASE),
|
|
121
121
|
re.compile(r"Community Edition limit reached.*?(?=\n|$)", re.IGNORECASE),
|
|
122
122
|
]
|
|
123
123
|
|
package/src/cli.py
CHANGED
|
@@ -866,6 +866,10 @@ def main(argv: Optional[List[str]] = None):
|
|
|
866
866
|
print(f" run: {action['run']}")
|
|
867
867
|
if action.get("reason"):
|
|
868
868
|
print(f" reason: {action['reason']}")
|
|
869
|
+
if action.get("snippet"):
|
|
870
|
+
print(" snippet:")
|
|
871
|
+
for line in action["snippet"].splitlines():
|
|
872
|
+
print(f" {line}")
|
|
869
873
|
print()
|
|
870
874
|
|
|
871
875
|
elif command in ("adapters", "adapter"):
|
package/src/graph_engine.py
CHANGED
|
@@ -2626,6 +2626,25 @@ class GraphEngine:
|
|
|
2626
2626
|
# graph instead of stacking a second crawl behind it.
|
|
2627
2627
|
return graph
|
|
2628
2628
|
|
|
2629
|
+
@classmethod
|
|
2630
|
+
def get_cached(cls, root_dir: str = ".") -> Optional[CodeGraph]:
|
|
2631
|
+
"""Warm instance or the on-disk index — never starts a repository crawl.
|
|
2632
|
+
|
|
2633
|
+
``scoped_search`` used to deserialize the graph SQLite cache twice per
|
|
2634
|
+
identifier query and never saw the instance ``oumv index``/``observe``
|
|
2635
|
+
had already warmed. Returns None when no index exists for this root.
|
|
2636
|
+
"""
|
|
2637
|
+
root_abs = os.path.abspath(root_dir)
|
|
2638
|
+
with cls._instances_lock:
|
|
2639
|
+
graph = cls._instances.get(root_abs)
|
|
2640
|
+
if graph is not None:
|
|
2641
|
+
return graph
|
|
2642
|
+
try:
|
|
2643
|
+
graph = CodeGraph(root_abs, use_disk_cache=True)
|
|
2644
|
+
except Exception:
|
|
2645
|
+
return None
|
|
2646
|
+
return graph if graph.symbols else None
|
|
2647
|
+
|
|
2629
2648
|
@classmethod
|
|
2630
2649
|
def warm_async(cls, root_dir: str = ".") -> bool:
|
|
2631
2650
|
"""Starts one background crawl per root so the first graph tool call is warm.
|
package/src/installer.py
CHANGED
|
@@ -60,10 +60,10 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
60
60
|
"`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
|
|
61
61
|
"11. **Proof-of-Savings Turn Footer (strictly English)**: Append on tool-using turns:\n"
|
|
62
62
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
|
63
|
-
"12. **Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Angular, Go, FastAPI, Express/Fastify, Next.js, Elysia on Bun, ASP.NET Core), "
|
|
63
|
+
"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), "
|
|
64
64
|
"ALWAYS prefer `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` BEFORE full file crawls, raw curls, or browser checks — "
|
|
65
|
-
"static OUMV works offline on read/edit tasks too, and `tokensafe dev` starts zero-footprint live Vite RPC without touching repo files. "
|
|
66
|
-
"In mixed monorepos
|
|
65
|
+
"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. "
|
|
66
|
+
"In mixed monorepos use `oumv` on supported profiles and `repo_map`/`smart_read_file`/`scoped_search` on stacks without an adapter (Nest/Hono/Koa, Svelte, Go/Echo).\n"
|
|
67
67
|
"13. **String Catalogs (`dict`)**: NEVER read a whole i18n catalog (`messages/<locale>/*.ts`, `locales/*.json`) to review or edit translations. A catalog is 100% payload, so reading 18 files per locale is the most expensive way to work, and fanning out one subagent per locale that each re-reads the English oracle multiplies it. Start with `tokensafe:run_helper(action='dict', command='lint --locale <l> --base en --json')` (CLI: `tokensafe dict lint --locale <l>`), which returns only suspect keys: untranslated, missing, orphan, placeholder drift, English leakage, brand loss. Patch with `dict apply --locale <l> --patch patch.json`, after `--dry-run`: it writes byte-preserving edits. `smart_read_file` on a catalog returns a digest on purpose; `dict show --keys a.b` returns exact values.\n"
|
|
68
68
|
)
|
|
69
69
|
|
|
@@ -76,7 +76,7 @@ POINTER_RULE = (
|
|
|
76
76
|
"(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
|
|
77
77
|
"Core tools: `tokensafe:repo_map(view='graph'|'api'|'tree')` for architecture & directory trees, "
|
|
78
78
|
"`tokensafe:scoped_search` (single or `queries` batch, never raw grep/find), `tokensafe:smart_read_file` (symbol, `targets` bundle, or `.d.ts` `package_name`), "
|
|
79
|
-
"`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Go/FastAPI
|
|
79
|
+
"`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Solid/Angular/Next, Go/Gin+Chi, FastAPI/Starlette/Flask/Django, Express/Fastify/Elysia, Spring/Laravel, ASP.NET Core — live or static offline; check `status` in mixed monorepos), "
|
|
80
80
|
"`tokensafe:session_context(action='budget'|'compact'|'prune'|'mistakes')` for context & anti-stuck hygiene, and "
|
|
81
81
|
"`tokensafe:run_helper(action='sanitize'|'guard'|'diff'|'deps'|'web'|'expand'|'image'|'compress'|'dict')` "
|
|
82
82
|
"(string catalogs: `dict lint --locale <l>`, then `dict apply`, never read whole catalogs); "
|
package/src/mcp_server.py
CHANGED
|
@@ -46,7 +46,7 @@ from src.session_context import current_root, current_session_id
|
|
|
46
46
|
|
|
47
47
|
SERVER_INFO = {
|
|
48
48
|
"name": "tokensafe-mcp",
|
|
49
|
-
"version": "4.
|
|
49
|
+
"version": "4.14.0"
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -548,7 +548,8 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
548
548
|
{ 'annotations': {'readOnlyHint': True},
|
|
549
549
|
'description': 'Instantly verifies actions in memory (UI synthetic actions, React reducers/Zustand/Redux '
|
|
550
550
|
'actions, Context updaters, or Backend transactional sandbox) with structured state and surface '
|
|
551
|
-
'diffs.'
|
|
551
|
+
'diffs. Without a live runtime it answers a labelled static subset instead of failing: file '
|
|
552
|
+
'existence, syntax, OCC version, and symbol/route presence (mode OFFLINE_STATIC_VERIFY).',
|
|
552
553
|
'inputSchema': { 'properties': { 'action': { 'default': 'invoke',
|
|
553
554
|
'description': 'Action name (invoke, click, submit, or '
|
|
554
555
|
'store action)',
|
|
@@ -865,12 +866,15 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
865
866
|
'transcript_path': {'type': 'string'}}}},
|
|
866
867
|
{'name': 'oumv',
|
|
867
868
|
'annotations': {'readOnlyHint': False},
|
|
868
|
-
'description': "
|
|
869
|
-
"
|
|
870
|
-
"
|
|
871
|
-
"
|
|
872
|
-
"
|
|
873
|
-
"
|
|
869
|
+
'description': "Call this FIRST on an OUMV-supported stack: status/brief/observe before grep or full-file "
|
|
870
|
+
"reads. OUMV runtime: 'status'|'observe' L0-L4 (a file target at L1+ returns the same skeleton a "
|
|
871
|
+
"read would and seeds the read cache: a later smart_read_file returns a pointer)|'brief' (skeleton + "
|
|
872
|
+
"call sites + props + module state in one call)|'understand'|'verify'|'mutate' (OCC edit)|'graph'|"
|
|
873
|
+
"'index' (repo-wide symbol search: query, kinds?, limit?)|'preview' (dry-run diff, no write)|'build' "
|
|
874
|
+
"(run the runtime's build/test command, §14.3)|'cancel' (cooperative, by requestId). Offline the "
|
|
875
|
+
"static graph answers observe/understand/index and a labelled verify subset (exists/syntax/OCC/"
|
|
876
|
+
"symbol/route presence). Observation is free on every plan; the write actions (verify, mutate, "
|
|
877
|
+
"preview, build) need Solo or higher and are refused with a read-only notice on guest/free.",
|
|
874
878
|
'inputSchema': {'type': 'object',
|
|
875
879
|
'properties': {'action': {'type': 'string',
|
|
876
880
|
'enum': ['status',
|
|
@@ -904,8 +908,13 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
904
908
|
'description': 'preview: batch edits envelope (wire 1.5.0+)'},
|
|
905
909
|
'timeout_ms': {'type': 'integer',
|
|
906
910
|
'description': 'preview/build: per-call budget (§3/§14.3)'},
|
|
907
|
-
'verify_action': {'type': 'string'
|
|
908
|
-
|
|
911
|
+
'verify_action': {'type': 'string',
|
|
912
|
+
'enum': ['invoke', 'click', 'submit'],
|
|
913
|
+
'description': 'verify: action kind to verify (default invoke)'},
|
|
914
|
+
'payload': {'type': 'object',
|
|
915
|
+
'description': 'verify: request body/action payload; may carry '
|
|
916
|
+
"expectedVersion and symbol for the offline static "
|
|
917
|
+
'checks'},
|
|
909
918
|
'requestId': {'type': 'string',
|
|
910
919
|
'description': 'cancel: the requestId echoed by the target call'},
|
|
911
920
|
'workspace_dir': {'type': 'string',
|
|
@@ -1246,9 +1255,10 @@ _GRAPH_TOOLS = {
|
|
|
1246
1255
|
}
|
|
1247
1256
|
|
|
1248
1257
|
|
|
1249
|
-
def _fallback_error(tool_name: str, reason: str) -> dict:
|
|
1258
|
+
def _fallback_error(tool_name: str, reason: str, hint: str = "") -> dict:
|
|
1250
1259
|
"""Returns a non-blocking, actionable error telling the AI model to try another approach."""
|
|
1251
1260
|
clean_reason = (reason or "unknown error").strip()
|
|
1261
|
+
tail = f" Hint: {hint.strip()}" if hint and hint.strip() else ""
|
|
1252
1262
|
return {
|
|
1253
1263
|
"isError": True,
|
|
1254
1264
|
"content": [{
|
|
@@ -1258,6 +1268,7 @@ def _fallback_error(tool_name: str, reason: str) -> dict:
|
|
|
1258
1268
|
"Try an alternative approach instead of repeating this exact call: "
|
|
1259
1269
|
"narrow the target 'path'/'project_path' or 'depth', inspect a specific file with 'smart_read_file', "
|
|
1260
1270
|
"or fall back to standard 'read_file' / bounded 'run_command'."
|
|
1271
|
+
+ tail
|
|
1261
1272
|
)
|
|
1262
1273
|
}]
|
|
1263
1274
|
}
|
|
@@ -1932,6 +1943,82 @@ def _repo_fingerprint(graph) -> str:
|
|
|
1932
1943
|
return h.hexdigest()[:40]
|
|
1933
1944
|
|
|
1934
1945
|
|
|
1946
|
+
def _default_read_text(abs_path: str):
|
|
1947
|
+
"""Render the symbol-less read: AST skeleton, else bounded raw text.
|
|
1948
|
+
|
|
1949
|
+
Returns (text, original_tokens, skeleton_tokens, source) with source being
|
|
1950
|
+
"skeleton" or "raw". `oumv observe` calls this too, so the text it delivers
|
|
1951
|
+
(and seeds into the read cache) is byte-identical to a real read.
|
|
1952
|
+
"""
|
|
1953
|
+
try:
|
|
1954
|
+
skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(abs_path, target_symbol=None)
|
|
1955
|
+
if skel_path and os.path.exists(skel_path):
|
|
1956
|
+
with open(skel_path, "r", encoding="utf-8", errors="replace") as f:
|
|
1957
|
+
return f.read(), orig_t, skel_t, "skeleton"
|
|
1958
|
+
except Exception:
|
|
1959
|
+
pass
|
|
1960
|
+
try:
|
|
1961
|
+
size = os.path.getsize(abs_path)
|
|
1962
|
+
except OSError:
|
|
1963
|
+
return "", 0, 0, "raw"
|
|
1964
|
+
try:
|
|
1965
|
+
prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(abs_path)
|
|
1966
|
+
except Exception:
|
|
1967
|
+
prefetch_block = ""
|
|
1968
|
+
max_raw_bytes = 512 * 1024
|
|
1969
|
+
with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
|
|
1970
|
+
content = f.read(max_raw_bytes) if size > max_raw_bytes else f.read()
|
|
1971
|
+
if size > max_raw_bytes:
|
|
1972
|
+
content += f"\n// [TokenSafe: file truncated at 512KB ({size:,} bytes total). Use start_line/end_line or symbol to inspect specific sections.]\n"
|
|
1973
|
+
return (prefetch_block or "") + content, 0, 0, "raw"
|
|
1974
|
+
|
|
1975
|
+
|
|
1976
|
+
def _observe_seed_read_cache(res, level, target, path_arg, workspace_dir) -> None:
|
|
1977
|
+
"""Hand the file text `oumv observe` just delivered to the read cache.
|
|
1978
|
+
|
|
1979
|
+
A pointer is only honest when the content reached the model: observe attaches
|
|
1980
|
+
the same skeleton a read would return (``file.skeleton``), records it in the
|
|
1981
|
+
firewall cache and marks it delivered. A later `smart_read_file(path)` then
|
|
1982
|
+
answers with a ~40-token pointer instead of the body. L0 stays a pulse.
|
|
1983
|
+
"""
|
|
1984
|
+
if not isinstance(res, dict) or str(level or "").upper() == "L0":
|
|
1985
|
+
return
|
|
1986
|
+
if res.get("targetKind") != "file" or not res.get("targetResolved"):
|
|
1987
|
+
return
|
|
1988
|
+
ws = workspace_dir or _oumv_default_workspace() or os.getcwd()
|
|
1989
|
+
candidates = []
|
|
1990
|
+
for raw in (target, path_arg):
|
|
1991
|
+
raw = str(raw or "").strip()
|
|
1992
|
+
if raw:
|
|
1993
|
+
candidates.append(raw if os.path.isabs(raw) else os.path.join(ws, raw))
|
|
1994
|
+
file_info = res.get("file") or {}
|
|
1995
|
+
rel = str(file_info.get("path") or "").strip()
|
|
1996
|
+
if rel:
|
|
1997
|
+
candidates.append(rel if os.path.isabs(rel) else os.path.join(ws, rel))
|
|
1998
|
+
abs_path = next((os.path.abspath(c) for c in candidates if c and os.path.isfile(c)), None)
|
|
1999
|
+
if not abs_path:
|
|
2000
|
+
return
|
|
2001
|
+
content, _orig_t, _skel_t, source = _default_read_text(abs_path)
|
|
2002
|
+
if not content or len(content) > AgentFirewall._MAX_CONTENT_CHARS:
|
|
2003
|
+
return
|
|
2004
|
+
file_info = res.setdefault("file", {})
|
|
2005
|
+
file_info["skeleton"] = content
|
|
2006
|
+
file_info["skeletonSource"] = source
|
|
2007
|
+
cur_hash = AgentFirewall._file_content_hash(abs_path)
|
|
2008
|
+
if cur_hash:
|
|
2009
|
+
_IN_PROCESS_DELIVERED[(abs_path, "", "signature")] = (cur_hash, _EPOCH_GEN)
|
|
2010
|
+
try:
|
|
2011
|
+
AgentFirewall.record_cache(
|
|
2012
|
+
session_id=_mcp_session_id(),
|
|
2013
|
+
file_path=abs_path,
|
|
2014
|
+
content=content,
|
|
2015
|
+
symbol="",
|
|
2016
|
+
tracker=_get_safe_tracker(),
|
|
2017
|
+
)
|
|
2018
|
+
except Exception:
|
|
2019
|
+
pass
|
|
2020
|
+
|
|
2021
|
+
|
|
1935
2022
|
def handle_tool_call(name: str, args: dict) -> dict:
|
|
1936
2023
|
if args is None or not isinstance(args, dict):
|
|
1937
2024
|
args = {}
|
|
@@ -2555,32 +2642,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2555
2642
|
header = f"// [TOCP Targeted Window: lines {s_line}-{e_line} for '{symbol}']\n"
|
|
2556
2643
|
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + (content or "")}]}
|
|
2557
2644
|
|
|
2558
|
-
#
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
return {"content": [{"type": "text", "text": content}]}
|
|
2572
|
-
|
|
2573
|
-
# Default bounded read (avoid dumping multi-MB files raw)
|
|
2574
|
-
prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
|
|
2575
|
-
max_raw_bytes = 512 * 1024
|
|
2576
|
-
if st.st_size > max_raw_bytes:
|
|
2577
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
2578
|
-
content = f.read(max_raw_bytes)
|
|
2579
|
-
content += f"\n// [TokenSafe: file truncated at 512KB ({st.st_size:,} bytes total). Use start_line/end_line or symbol to inspect specific sections.]\n"
|
|
2580
|
-
else:
|
|
2581
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
2582
|
-
content = f.read()
|
|
2583
|
-
return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
|
|
2645
|
+
# AST skeleton or bounded raw, rendered by the same helper `oumv observe`
|
|
2646
|
+
# uses to seed the read cache — one renderer means a pointer always refers
|
|
2647
|
+
# to text the model actually received.
|
|
2648
|
+
content, orig_t, skel_t, source = _default_read_text(path)
|
|
2649
|
+
if source == "skeleton" and orig_t > skel_t:
|
|
2650
|
+
tracker.record_event(
|
|
2651
|
+
session_id=_mcp_session_id(),
|
|
2652
|
+
event_type="AST_SKELETON",
|
|
2653
|
+
original_tokens=orig_t,
|
|
2654
|
+
optimized_tokens=skel_t,
|
|
2655
|
+
details={"target_file": os.path.basename(path), "saved_tokens": orig_t - skel_t}
|
|
2656
|
+
)
|
|
2657
|
+
return {"content": [{"type": "text", "text": content}]}
|
|
2584
2658
|
|
|
2585
2659
|
elif name == "smart_bundle":
|
|
2586
2660
|
targets = args.get("targets")
|
|
@@ -3586,6 +3660,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3586
3660
|
if ws_err:
|
|
3587
3661
|
return _fallback_error("oumv_observe", ws_err)
|
|
3588
3662
|
res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path)
|
|
3663
|
+
try:
|
|
3664
|
+
_observe_seed_read_cache(res, lvl, tgt, raw_path, ws)
|
|
3665
|
+
except Exception:
|
|
3666
|
+
pass
|
|
3589
3667
|
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
3590
3668
|
except Exception as e:
|
|
3591
3669
|
return _fallback_error("oumv_observe", f"failed to observe OUMV runtime: {e}")
|
|
@@ -3649,7 +3727,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3649
3727
|
res = OUMVGateway.verify(target=tgt, action=act, payload=payload, runtime=rt, workspace_dir=ws, sandbox=sandbox)
|
|
3650
3728
|
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
3651
3729
|
except Exception as e:
|
|
3652
|
-
return _fallback_error(
|
|
3730
|
+
return _fallback_error(
|
|
3731
|
+
"oumv_verify",
|
|
3732
|
+
f"failed to verify OUMV action: {e}",
|
|
3733
|
+
hint=(
|
|
3734
|
+
"static verify answers without a live runtime (file exists, syntax, OCC version, "
|
|
3735
|
+
"symbol/route presence); if this errored, call oumv(action='verify', target=<file or route>) "
|
|
3736
|
+
"again or use oumv(action='observe', path=<file>) for the static surface."
|
|
3737
|
+
),
|
|
3738
|
+
)
|
|
3653
3739
|
|
|
3654
3740
|
elif name == "oumv_graph":
|
|
3655
3741
|
try:
|