tokensafe 4.7.4 → 4.7.7
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 +17 -13
- package/bin/tokensafe.js +41 -39
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/auto_inject.py +248 -8
- package/src/batch_editor.py +12 -2
- package/src/bench/go_target.py +135 -14
- package/src/cli.py +1 -1
- package/src/installer.py +5 -23
- package/src/mcp_server.py +315 -21
- package/src/oumv_gateway.py +8 -3
- package/src/retrofit.py +154 -16
- package/src/session_brief.py +4 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/README.md
CHANGED
|
@@ -240,26 +240,30 @@ Full matrix and details: [docs/OUMV.md](docs/OUMV.md).
|
|
|
240
240
|
|
|
241
241
|
## Benchmarks
|
|
242
242
|
|
|
243
|
-
### Measured agent matrix (Go, DeepSeek — 3 tasks × 5 runs × 3 arms)
|
|
243
|
+
### Measured agent matrix v5 (Go, DeepSeek — 3 tasks × 5 runs × 3 arms, 200-file target)
|
|
244
244
|
|
|
245
245
|
Real 12-assertion oracle re-run after every step; tokens and cost from the provider's `usage`
|
|
246
246
|
payload. `baseline` = file/search/command tools, `tokensafe` = this product's MCP server
|
|
247
|
-
(`
|
|
248
|
-
OUMV protocol runtime
|
|
247
|
+
(`smart_read_file(endpoint="POST /api/…")` in one call → `apply_edits` with the hunk and inline
|
|
248
|
+
`verify="auto"`), `oumv` = the OUMV protocol runtime (`observe L3` on the endpoint →
|
|
249
|
+
`applyEdit mode=patch`). The sandbox is the benchmark module plus **200 generated service
|
|
250
|
+
files**; all three arms solve every session.
|
|
249
251
|
|
|
250
252
|
| Arm | Solved | Mean steps | Mean input | Mean output | Cost/run |
|
|
251
253
|
| :--- | ---: | ---: | ---: | ---: | ---: |
|
|
252
|
-
| `baseline` | 15/15 |
|
|
253
|
-
| `tokensafe` | 15/15 |
|
|
254
|
-
| `oumv` | 15/15 |
|
|
255
|
-
|
|
256
|
-
**vs baseline: −
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
this sample size):
|
|
254
|
+
| `baseline` | 15/15 | 5.6 | 26,412 | 1,670 | $0.0044 |
|
|
255
|
+
| `tokensafe` | 15/15 | **3.1** | **8,177** | **414** | **$0.0012** |
|
|
256
|
+
| `oumv` | 15/15 | 3.7 | 9,553 | 521 | $0.0014 |
|
|
257
|
+
|
|
258
|
+
**vs baseline: −69.0% input tokens, −75.2% output tokens, −73.3% cost.** Tree size is the
|
|
259
|
+
lever: on the same tasks with a 69-file tree the file-tool arm costs 22,356 input tokens per
|
|
260
|
+
run and the two endpoint-keyed arms 8,823 / 9,756 — growing the tree by 200 files moves only
|
|
261
|
+
`baseline` (+18%). Full method, per-task table, the small-target comparison, artifacts and
|
|
262
|
+
limits (one model, ±5% run-to-run noise at this sample size):
|
|
263
|
+
[`OUMV_AGENT_MATRIX_V5.md`](https://github.com/tokensafe-dev/tokensafe-backend/blob/main/go/benchmark/OUMV_AGENT_MATRIX_V5.md)
|
|
261
264
|
in the backend repo, generated from the run JSON by
|
|
262
|
-
`go/benchmark/render_agent_matrix.py`.
|
|
265
|
+
`go/benchmark/render_agent_matrix.py`. The previous measured run is
|
|
266
|
+
[`OUMV_AGENT_MATRIX_V4.md`](https://github.com/tokensafe-dev/tokensafe-backend/blob/main/go/benchmark/OUMV_AGENT_MATRIX_V4.md).
|
|
263
267
|
|
|
264
268
|
### Agent Usability Benchmarks (AUB) — Full-Stack Agent Velocity
|
|
265
269
|
|
package/bin/tokensafe.js
CHANGED
|
@@ -353,14 +353,16 @@ function printInstallGuidance() {
|
|
|
353
353
|
console.error('Managed runtime downloads can be disabled: TOKENSAFE_NO_DOWNLOAD=1\n');
|
|
354
354
|
}
|
|
355
355
|
|
|
356
|
-
async function findPython() {
|
|
356
|
+
async function findPython(options = {}) {
|
|
357
|
+
const { allowProvision = true, requireDeps = true } = options;
|
|
357
358
|
const pinned = (process.env.TOKENSAFE_PYTHON || '').trim();
|
|
358
359
|
if (pinned) {
|
|
359
360
|
if (probePython(pinned, true)) return pinned;
|
|
360
|
-
if (probePython(pinned, false)) {
|
|
361
|
+
if (requireDeps && probePython(pinned, false)) {
|
|
361
362
|
const bootstrapped = bootstrapDependencies(pinned);
|
|
362
363
|
if (bootstrapped) return bootstrapped;
|
|
363
364
|
}
|
|
365
|
+
if (!requireDeps && probePython(pinned, false)) return pinned;
|
|
364
366
|
fail(`TOKENSAFE_PYTHON=${pinned} is not a usable CPython ${MIN_PYTHON[0]}.${MIN_PYTHON[1]}+ with 'cryptography'.`);
|
|
365
367
|
}
|
|
366
368
|
|
|
@@ -369,6 +371,15 @@ async function findPython() {
|
|
|
369
371
|
if (fs.existsSync(venvPy)) candidates.push(venvPy);
|
|
370
372
|
candidates.push('python3', 'python');
|
|
371
373
|
|
|
374
|
+
if (!requireDeps) {
|
|
375
|
+
// `help` only prints: a bare interpreter is enough, and a dependency
|
|
376
|
+
// bootstrap there would turn a two-line reference into a pip install.
|
|
377
|
+
for (const cmd of candidates) {
|
|
378
|
+
if (probePython(cmd, false)) return cmd;
|
|
379
|
+
}
|
|
380
|
+
return allowProvision ? await ensureManagedRuntime() : null;
|
|
381
|
+
}
|
|
382
|
+
|
|
372
383
|
for (const cmd of candidates) {
|
|
373
384
|
if (probePython(cmd, true)) return cmd;
|
|
374
385
|
}
|
|
@@ -379,54 +390,45 @@ async function findPython() {
|
|
|
379
390
|
}
|
|
380
391
|
}
|
|
381
392
|
|
|
382
|
-
return await ensureManagedRuntime();
|
|
393
|
+
return allowProvision ? await ensureManagedRuntime() : null;
|
|
383
394
|
}
|
|
384
395
|
|
|
385
396
|
const firstArg = args[0] || '';
|
|
386
|
-
|
|
387
|
-
|
|
397
|
+
const wantsHelp = firstArg === 'help' || firstArg === '--help' || firstArg === '-h';
|
|
398
|
+
|
|
399
|
+
// The command reference lives in src/cli.py:_print_help(). This launcher used
|
|
400
|
+
// to carry its own copy and fell behind: `dev`, `inject`, `adapters` and
|
|
401
|
+
// `bench-oumv` were missing, so `tokensafe help` advertised a subset of the
|
|
402
|
+
// real dispatcher. Help is forwarded to the Python CLI now, so one list feeds
|
|
403
|
+
// both entrypoints. This fallback only prints when no interpreter exists yet.
|
|
404
|
+
function printHelpFallback() {
|
|
388
405
|
console.log(`
|
|
389
406
|
⚡ TokenSafe - Local-First AI Coding Guardrails & Context Optimizer
|
|
390
407
|
Website: https://tokensafe.dev
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
tokensafe
|
|
403
|
-
tokensafe expand-ref <hash> Restore folded tool/command/file result by its 8-char hash
|
|
404
|
-
tokensafe wrap <command> Run command with compact output folding (e.g. tests/logs)
|
|
405
|
-
tokensafe web <url> Fetch web page/docs and print clean compact Markdown
|
|
406
|
-
tokensafe doctor Audit MCP servers & skills context token tax
|
|
407
|
-
tokensafe providers List active LLM distillation models & keys
|
|
408
|
-
tokensafe benchmark Run zero-loss verification benchmark suite
|
|
409
|
-
tokensafe mcp Manage MCP servers (list, disable <name>, enable <name>)
|
|
410
|
-
tokensafe proxy [port] Start Transparent Local AI Proxy (default: 8765)
|
|
411
|
-
tokensafe graph Analyze repository God Nodes & dependency topology
|
|
412
|
-
tokensafe map Generate tokensafe-out/API_SURFACE.md interface snapshot
|
|
413
|
-
tokensafe vacuum Compact SQLite metrics database storage
|
|
414
|
-
tokensafe prune Prune granular telemetry events into lifetime rollup
|
|
415
|
-
tokensafe digest Preview or send weekly team ROI digest email
|
|
416
|
-
tokensafe tests Run the unit test suite (compact failure report)
|
|
417
|
-
tokensafe activate <key> Activate commercial Solo or Team seat license key
|
|
418
|
-
tokensafe license Show current license status and active tier
|
|
419
|
-
tokensafe update One-click self-update for npm, pip & all AI agent rules
|
|
420
|
-
tokensafe install Interactive installer for Cursor, Antigravity, Claude, etc.
|
|
421
|
-
tokensafe uninstall Uninstall TokenSafe from AI agents, unwire proxy & clean rules
|
|
422
|
-
tokensafe --help Show this help screen
|
|
408
|
+
Docs: https://tokensafe.dev/docs
|
|
409
|
+
|
|
410
|
+
The command reference is printed by the Python CLI, which is not available yet.
|
|
411
|
+
Install CPython ${MIN_PYTHON[0]}.${MIN_PYTHON[1]}+ once and rerun 'tokensafe help':
|
|
412
|
+
macOS: brew install python3
|
|
413
|
+
Debian/Ubuntu: sudo apt-get install python3 python3-venv
|
|
414
|
+
Fedora: sudo dnf install python3
|
|
415
|
+
Windows: winget install Python.Python.3.12
|
|
416
|
+
|
|
417
|
+
No interpreter at hand? The launcher can provision a pinned build on the first
|
|
418
|
+
real command (network required), or accept an existing one:
|
|
419
|
+
TOKENSAFE_PYTHON=/path/to/python3 tokensafe help
|
|
423
420
|
`);
|
|
424
|
-
process.exit(0);
|
|
425
421
|
}
|
|
426
422
|
|
|
427
423
|
async function main() {
|
|
428
|
-
|
|
424
|
+
// Help must never trigger the managed-runtime download: it is a print, not a
|
|
425
|
+
// run. Probe what is already installed; the fallback covers the rest.
|
|
426
|
+
const python = await findPython({ allowProvision: !wantsHelp, requireDeps: !wantsHelp });
|
|
429
427
|
if (!python) {
|
|
428
|
+
if (wantsHelp) {
|
|
429
|
+
printHelpFallback();
|
|
430
|
+
process.exit(0);
|
|
431
|
+
}
|
|
430
432
|
printInstallGuidance();
|
|
431
433
|
process.exit(1);
|
|
432
434
|
}
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.7.
|
|
3
|
+
"version": "4.7.7",
|
|
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.7.
|
|
4
|
+
"version": "4.7.7",
|
|
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.7.
|
|
4
|
+
"version": "4.7.7",
|
|
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.7.
|
|
6
|
+
"version": "4.7.7",
|
|
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.7.
|
|
26
|
+
"version": "4.7.7",
|
|
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.7.
|
|
42
|
+
"version": "4.7.7",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
package/src/auto_inject.py
CHANGED
|
@@ -233,7 +233,17 @@ def go_patch_state(workspace: str) -> Dict[str, Any]:
|
|
|
233
233
|
|
|
234
234
|
|
|
235
235
|
_GO_MODULE = "github.com/tokensafe-dev/tokensafe-backend/go"
|
|
236
|
-
|
|
236
|
+
# Keep in step with the backend release tag (go/vX.Y.Z): injection must never
|
|
237
|
+
# downgrade an adapter that is already newer than this pin.
|
|
238
|
+
_GO_MODULE_VERSION = "v0.6.0"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _version_tuple(tag: str):
|
|
242
|
+
"""`v1.2.3` -> (1, 2, 3); raises ValueError when the tag is not semver."""
|
|
243
|
+
parts = tag.lstrip("v").split(".")
|
|
244
|
+
if len(parts) < 2:
|
|
245
|
+
raise ValueError(tag)
|
|
246
|
+
return tuple(int(part) for part in parts[:3] + ["0"] * (3 - len(parts[:3])))
|
|
237
247
|
|
|
238
248
|
|
|
239
249
|
def _ensure_go_dependency(workspace: str) -> Optional[str]:
|
|
@@ -247,10 +257,10 @@ def _ensure_go_dependency(workspace: str) -> Optional[str]:
|
|
|
247
257
|
except OSError as exc:
|
|
248
258
|
return f"cannot read go.mod: {exc}"
|
|
249
259
|
|
|
250
|
-
#
|
|
251
|
-
#
|
|
260
|
+
# Never downgrade: a project already on a newer go/v* tag keeps it, and an
|
|
261
|
+
# older requirement is raised to the pin.
|
|
252
262
|
match = re.search(re.escape(_GO_MODULE) + r"\s+v([0-9][\w.+-]*)", content)
|
|
253
|
-
if match and f"v{match.group(1)}"
|
|
263
|
+
if match and _version_tuple(f"v{match.group(1)}") >= _version_tuple(_GO_MODULE_VERSION):
|
|
254
264
|
return None
|
|
255
265
|
|
|
256
266
|
go_bin = shutil.which("go")
|
|
@@ -502,6 +512,181 @@ def revert_go_patch(workspace: str) -> Dict[str, Any]:
|
|
|
502
512
|
# Plan / apply / revert for the CLI and the first-prompt hook
|
|
503
513
|
# --------------------------------------------------------------------------- #
|
|
504
514
|
|
|
515
|
+
def _find_node_entrypoint(workspace: str) -> Optional[str]:
|
|
516
|
+
"""Finds the Node entry file that creates the framework app."""
|
|
517
|
+
candidates: List[str] = []
|
|
518
|
+
pkg_path = os.path.join(workspace, "package.json")
|
|
519
|
+
try:
|
|
520
|
+
with open(pkg_path, "r", encoding="utf-8") as f:
|
|
521
|
+
pkg = json.load(f)
|
|
522
|
+
main = pkg.get("main")
|
|
523
|
+
if isinstance(main, str) and main:
|
|
524
|
+
candidates.append(main)
|
|
525
|
+
except Exception:
|
|
526
|
+
pass
|
|
527
|
+
candidates += ["src/index.js", "src/server.js", "src/app.js", "index.js", "server.js", "app.js"]
|
|
528
|
+
for rel in candidates:
|
|
529
|
+
path = os.path.join(workspace, rel)
|
|
530
|
+
if os.path.isfile(path):
|
|
531
|
+
return path
|
|
532
|
+
return None
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _node_framework_of(workspace: str) -> Optional[str]:
|
|
536
|
+
try:
|
|
537
|
+
with open(os.path.join(workspace, "package.json"), "r", encoding="utf-8") as f:
|
|
538
|
+
pkg = json.load(f)
|
|
539
|
+
deps = {**(pkg.get("dependencies") or {}), **(pkg.get("devDependencies") or {})}
|
|
540
|
+
except Exception:
|
|
541
|
+
return None
|
|
542
|
+
if "fastify" in deps:
|
|
543
|
+
return "fastify"
|
|
544
|
+
if "express" in deps:
|
|
545
|
+
return "express"
|
|
546
|
+
return None
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def node_patch_state(workspace: str) -> Dict[str, Any]:
|
|
550
|
+
"""Reports whether the one-line OUMV mount is already in the Node entrypoint."""
|
|
551
|
+
path = _find_node_entrypoint(workspace)
|
|
552
|
+
if not path:
|
|
553
|
+
return {"entrypoint": None, "patched": False, "framework": _node_framework_of(workspace)}
|
|
554
|
+
try:
|
|
555
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
556
|
+
source = f.read()
|
|
557
|
+
except OSError:
|
|
558
|
+
return {"entrypoint": path, "patched": False, "framework": _node_framework_of(workspace)}
|
|
559
|
+
return {
|
|
560
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
561
|
+
"patched": _MARK_BEGIN in source and _MARK_END in source,
|
|
562
|
+
"framework": _node_framework_of(workspace),
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
|
|
567
|
+
"""Inserts one mount line between tokensafe markers, with a byte-exact backup."""
|
|
568
|
+
framework = _node_framework_of(workspace)
|
|
569
|
+
path = _find_node_entrypoint(workspace)
|
|
570
|
+
if framework not in ("express", "fastify"):
|
|
571
|
+
return {"status": "skipped", "reason": "no supported Node framework (express/fastify) found"}
|
|
572
|
+
if not path:
|
|
573
|
+
return {"status": "skipped", "reason": "no Node entrypoint found"}
|
|
574
|
+
|
|
575
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
576
|
+
source = f.read()
|
|
577
|
+
if _MARK_BEGIN in source:
|
|
578
|
+
return {"status": "already_patched", "entrypoint": os.path.relpath(path, workspace)}
|
|
579
|
+
|
|
580
|
+
if framework == "express":
|
|
581
|
+
pattern = re.compile(r"(?m)^(?P<indent>[ \t]*)(?:const|let|var)\s+\w+\s*=\s*express\(\)[ \t]*;?[ \t]*$")
|
|
582
|
+
mount = (
|
|
583
|
+
f"{_MARK_BEGIN}\n"
|
|
584
|
+
"require('tokensafe-backend-node').mountTokensafe(app);\n"
|
|
585
|
+
f"{_MARK_END}\n"
|
|
586
|
+
)
|
|
587
|
+
else:
|
|
588
|
+
pattern = re.compile(r"(?m)^(?P<indent>[ \t]*)(?:const|let|var)\s+(?P<var>\w+)\s*=\s*(?:Fastify|fastify)\([^)]*\)[ \t]*;?[ \t]*$")
|
|
589
|
+
mount = (
|
|
590
|
+
f"{_MARK_BEGIN}\n"
|
|
591
|
+
"void require('tokensafe-backend-node').registerTokensafe(app);\n"
|
|
592
|
+
f"{_MARK_END}\n"
|
|
593
|
+
)
|
|
594
|
+
|
|
595
|
+
found = pattern.search(source)
|
|
596
|
+
if not found:
|
|
597
|
+
return {
|
|
598
|
+
"status": "skipped",
|
|
599
|
+
"reason": f"could not find `{framework}(...)` assignment in {os.path.relpath(path, workspace)}",
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
line_end = source.find("\n", found.end())
|
|
603
|
+
insert_at = len(source) if line_end < 0 else line_end + 1
|
|
604
|
+
patched = source[:insert_at] + mount + source[insert_at:]
|
|
605
|
+
|
|
606
|
+
if dry_run:
|
|
607
|
+
return {"status": "dry_run", "entrypoint": os.path.relpath(path, workspace), "preview": mount.strip()}
|
|
608
|
+
|
|
609
|
+
backup_dir = _inject_dir(workspace)
|
|
610
|
+
os.makedirs(backup_dir, exist_ok=True)
|
|
611
|
+
backup_path = os.path.join(backup_dir, os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak")
|
|
612
|
+
shutil.copy2(path, backup_path)
|
|
613
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
614
|
+
f.write(patched)
|
|
615
|
+
with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as f:
|
|
616
|
+
json.dump({"entrypoint": path, "backup": backup_path, "framework": framework, "mode": "node_mount"}, f, indent=2)
|
|
617
|
+
return {
|
|
618
|
+
"status": "patched",
|
|
619
|
+
"entrypoint": os.path.relpath(path, workspace),
|
|
620
|
+
"framework": framework,
|
|
621
|
+
"mode": "node_mount",
|
|
622
|
+
"backup": backup_path,
|
|
623
|
+
"line": mount.splitlines()[1],
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def revert_node_patch(workspace: str) -> Dict[str, Any]:
|
|
628
|
+
manifest_path = os.path.join(_inject_dir(workspace), "manifest.json")
|
|
629
|
+
if not os.path.isfile(manifest_path):
|
|
630
|
+
return {"status": "clean", "reason": "no Node patch manifest"}
|
|
631
|
+
try:
|
|
632
|
+
with open(manifest_path, "r", encoding="utf-8") as f:
|
|
633
|
+
manifest = json.load(f)
|
|
634
|
+
except Exception as exc:
|
|
635
|
+
return {"status": "error", "reason": f"cannot read manifest: {exc}"}
|
|
636
|
+
if manifest.get("mode") != "node_mount":
|
|
637
|
+
return {"status": "clean", "reason": "manifest is not a Node patch"}
|
|
638
|
+
entrypoint = manifest.get("entrypoint")
|
|
639
|
+
backup = manifest.get("backup")
|
|
640
|
+
if not (entrypoint and backup and os.path.isfile(backup)):
|
|
641
|
+
return {"status": "error", "reason": "backup missing; restore manually"}
|
|
642
|
+
shutil.copy2(backup, entrypoint)
|
|
643
|
+
os.unlink(manifest_path)
|
|
644
|
+
return {"status": "reverted", "entrypoint": os.path.relpath(entrypoint, workspace)}
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _sidecar_cache_dir() -> str:
|
|
648
|
+
return os.path.join(_tokensafe_home(), "sidecars")
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
|
|
652
|
+
"""Copies OumvSpring.java / oumv-php into ~/.tokensafe/sidecars.
|
|
653
|
+
|
|
654
|
+
Prefers a local backend checkout (OUMV_BACKEND_REPO or a sibling directory);
|
|
655
|
+
returns (path, note) where path is None when the source is not available.
|
|
656
|
+
"""
|
|
657
|
+
source_map = {
|
|
658
|
+
"spring": ("java/src/dev/tokensafe/oumv/OumvSpring.java", "OumvSpring.java"),
|
|
659
|
+
"php": ("php/bin/oumv-php", "oumv-php"),
|
|
660
|
+
}
|
|
661
|
+
if kind not in source_map:
|
|
662
|
+
return None, f"unknown sidecar {kind!r}"
|
|
663
|
+
rel_source, filename = source_map[kind]
|
|
664
|
+
|
|
665
|
+
repo_candidates = []
|
|
666
|
+
env_repo = os.environ.get("OUMV_BACKEND_REPO")
|
|
667
|
+
if env_repo:
|
|
668
|
+
repo_candidates.append(env_repo)
|
|
669
|
+
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
670
|
+
repo_candidates += [
|
|
671
|
+
os.path.join(os.path.dirname(here), "tokensafe-backend"),
|
|
672
|
+
os.path.join(here, "..", "tokensafe-backend"),
|
|
673
|
+
]
|
|
674
|
+
for repo in repo_candidates:
|
|
675
|
+
candidate = os.path.join(os.path.abspath(repo), rel_source)
|
|
676
|
+
if os.path.isfile(candidate):
|
|
677
|
+
cache_dir = _sidecar_cache_dir()
|
|
678
|
+
os.makedirs(cache_dir, exist_ok=True)
|
|
679
|
+
target = os.path.join(cache_dir, filename)
|
|
680
|
+
shutil.copy2(candidate, target)
|
|
681
|
+
if kind == "php":
|
|
682
|
+
os.chmod(target, 0o755)
|
|
683
|
+
return target, f"cached from {candidate}"
|
|
684
|
+
return None, (
|
|
685
|
+
"sidecar source not found: set OUMV_BACKEND_REPO to a tokensafe-backend "
|
|
686
|
+
"checkout or clone it next to this one"
|
|
687
|
+
)
|
|
688
|
+
|
|
689
|
+
|
|
505
690
|
def plan(workspace: str) -> Dict[str, Any]:
|
|
506
691
|
"""Describes what apply would do, without touching anything."""
|
|
507
692
|
stack = detect_project_stack(workspace)
|
|
@@ -523,8 +708,15 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
523
708
|
backend = stack.get("backend")
|
|
524
709
|
if backend:
|
|
525
710
|
provider = backend.get("provider")
|
|
526
|
-
entry_id =
|
|
711
|
+
entry_id = {
|
|
712
|
+
"fastapi": "backend/fastapi",
|
|
713
|
+
"go": "backend/go",
|
|
714
|
+
"node": "backend/node",
|
|
715
|
+
"spring": "backend/spring",
|
|
716
|
+
"php": "backend/php",
|
|
717
|
+
}.get(provider, "backend/go")
|
|
527
718
|
entry = catalog.get(entry_id, {})
|
|
719
|
+
install = entry.get("technology", {}).get("package", {}).get("install")
|
|
528
720
|
if provider == "fastapi":
|
|
529
721
|
actions.append({
|
|
530
722
|
"kind": "python_autoload",
|
|
@@ -532,7 +724,7 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
532
724
|
"framework": "fastapi",
|
|
533
725
|
"writes_repo": False,
|
|
534
726
|
"description": "sitecustomize patches uvicorn; mount_tokensafe(app) runs on import",
|
|
535
|
-
"install":
|
|
727
|
+
"install": install or 'pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"',
|
|
536
728
|
"run": python_run_hint(workspace),
|
|
537
729
|
})
|
|
538
730
|
elif provider == "go":
|
|
@@ -545,7 +737,36 @@ def plan(workspace: str) -> Dict[str, Any]:
|
|
|
545
737
|
"already_patched": state["patched"],
|
|
546
738
|
"entrypoint": state["entrypoint"],
|
|
547
739
|
"description": "one AutoMount() line between tokensafe markers; byte-exact backup + --revert",
|
|
548
|
-
"install":
|
|
740
|
+
"install": install,
|
|
741
|
+
})
|
|
742
|
+
elif provider == "node":
|
|
743
|
+
state = node_patch_state(workspace)
|
|
744
|
+
actions.append({
|
|
745
|
+
"kind": "node_one_line_patch",
|
|
746
|
+
"profile": "backend",
|
|
747
|
+
"framework": state.get("framework") or backend.get("framework"),
|
|
748
|
+
"writes_repo": True,
|
|
749
|
+
"already_patched": state["patched"],
|
|
750
|
+
"entrypoint": state["entrypoint"],
|
|
751
|
+
"description": "one mountTokensafe(app)/registerTokensafe(app) line between tokensafe markers; byte-exact backup + --revert",
|
|
752
|
+
"install": install or "npm install tokensafe-backend-node",
|
|
753
|
+
})
|
|
754
|
+
elif provider in ("spring", "php"):
|
|
755
|
+
sidecar_path, note = ensure_sidecar(provider)
|
|
756
|
+
command = (
|
|
757
|
+
f"tokensafe run-backend java {sidecar_path}"
|
|
758
|
+
if provider == "spring" and sidecar_path
|
|
759
|
+
else (f"tokensafe run-backend {sidecar_path}" if sidecar_path else None)
|
|
760
|
+
)
|
|
761
|
+
actions.append({
|
|
762
|
+
"kind": "sidecar",
|
|
763
|
+
"profile": "backend",
|
|
764
|
+
"framework": backend.get("framework", provider),
|
|
765
|
+
"writes_repo": False,
|
|
766
|
+
"sidecar": sidecar_path,
|
|
767
|
+
"install": note,
|
|
768
|
+
"run": command,
|
|
769
|
+
"description": "static route scan + OCC edits + verify through the single-file sidecar; nothing is written into the project",
|
|
549
770
|
})
|
|
550
771
|
else:
|
|
551
772
|
actions.append({
|
|
@@ -595,9 +816,28 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
|
|
|
595
816
|
|
|
596
817
|
if backend.get("provider") == "go" and include_go:
|
|
597
818
|
results["actions"].append({"kind": "go_one_line_patch", **apply_go_patch(workspace, dry_run=dry_run)})
|
|
819
|
+
elif backend.get("provider") == "node":
|
|
820
|
+
results["actions"].append({"kind": "node_one_line_patch", **apply_node_patch(workspace, dry_run=dry_run)})
|
|
821
|
+
elif backend.get("provider") in ("spring", "php"):
|
|
822
|
+
sidecar_path, note = ensure_sidecar(backend["provider"])
|
|
823
|
+
results["actions"].append({
|
|
824
|
+
"kind": "sidecar",
|
|
825
|
+
"status": "ready" if sidecar_path else "needs-source",
|
|
826
|
+
"sidecar": sidecar_path,
|
|
827
|
+
"note": note,
|
|
828
|
+
"run": (
|
|
829
|
+
f"tokensafe run-backend java {sidecar_path}"
|
|
830
|
+
if backend["provider"] == "spring" and sidecar_path
|
|
831
|
+
else (f"tokensafe run-backend {sidecar_path}" if sidecar_path else None)
|
|
832
|
+
),
|
|
833
|
+
})
|
|
598
834
|
|
|
599
835
|
return results
|
|
600
836
|
|
|
601
837
|
|
|
602
838
|
def revert(workspace: str) -> Dict[str, Any]:
|
|
603
|
-
return {
|
|
839
|
+
return {
|
|
840
|
+
"workspace": workspace,
|
|
841
|
+
"go": revert_go_patch(workspace),
|
|
842
|
+
"node": revert_node_patch(workspace),
|
|
843
|
+
}
|
package/src/batch_editor.py
CHANGED
|
@@ -320,7 +320,12 @@ def _apply_hunk_to_text(
|
|
|
320
320
|
occ.append(str(s_idx + sub_text.count("\n", 0, pos) + 1))
|
|
321
321
|
scan = pos + 1
|
|
322
322
|
locs = f" (near lines {', '.join(occ)})" if occ else ""
|
|
323
|
-
|
|
323
|
+
retry = ""
|
|
324
|
+
if occ:
|
|
325
|
+
first = int(occ[0])
|
|
326
|
+
span = max(1, target.count("\n") + 1)
|
|
327
|
+
retry = f" Retry with start_line={first}, end_line={first + span - 1}."
|
|
328
|
+
return None, f"Target occurs {count} times within lines {s_idx+1}..{e_idx}{locs}.{retry} Or set replace_all=True."
|
|
324
329
|
prepared_replacement = _normalize_eol(replacement, nl)
|
|
325
330
|
new_sub = sub_text.replace(match_target, prepared_replacement) if replace_all else sub_text.replace(match_target, prepared_replacement, 1)
|
|
326
331
|
new_lines = lines[:s_idx] + [new_sub] + lines[e_idx:]
|
|
@@ -339,7 +344,12 @@ def _apply_hunk_to_text(
|
|
|
339
344
|
if match_target in l:
|
|
340
345
|
occ_lines.append(str(i + 1))
|
|
341
346
|
locs = f"lines {', '.join(occ_lines[:5])}" if occ_lines else "multiple locations"
|
|
342
|
-
|
|
347
|
+
retry = ""
|
|
348
|
+
if occ_lines:
|
|
349
|
+
first = int(occ_lines[0])
|
|
350
|
+
span = max(1, target.count("\n") + 1)
|
|
351
|
+
retry = f" Retry with start_line={first}, end_line={first + span - 1}."
|
|
352
|
+
return None, f"Target occurs {count} times (near {locs}).{retry} Or set replace_all=True."
|
|
343
353
|
|
|
344
354
|
prepared_replacement = _normalize_eol(replacement, nl)
|
|
345
355
|
new_content = content.replace(match_target, prepared_replacement) if replace_all else content.replace(match_target, prepared_replacement, 1)
|