tokensafe 4.7.11 → 4.7.13

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.7.11",
2
+ "version": "4.7.13",
3
3
  "name": "tokensafe",
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
  "author": {
package/README.md CHANGED
@@ -222,7 +222,11 @@ You install TokenSafe, open a project in your agent, and the first turn does the
222
222
  * FastAPI — a global `~/.tokensafe/pyhooks/sitecustomize.py` mounts `mount_tokensafe(app)`
223
223
  when the server runs through `tokensafe run-backend uvicorn ...`;
224
224
  * Go — one `AutoMount()` line between `tokensafe:oumv` markers, byte-exact backup in
225
- `~/.tokensafe/inject/`, `go build` validated, `tokensafe inject --revert` restores it.
225
+ `~/.tokensafe/inject/`, `go build` validated, `tokensafe inject --revert` restores it;
226
+ * Node (Express/Fastify) — one `mountTokensafe(app)` / `registerTokensafe(app)` line, same
227
+ markers and byte-exact revert; ASP.NET Core — one `AddTokensafe()`/`UseTokensafe()` pair;
228
+ * Next.js (App Router) — one generated `app/api/tokensafe/route.ts` Route Handler
229
+ (`createNextRouteHandlers`), server profile; `--revert` deletes the file.
226
230
  3. **Brief the agent** — a short routing block (hook context and MCP `instructions`) says which
227
231
  stack is worked through OUMV and which through the TokenSafe tools. Nothing is written into
228
232
  the repository by the brief.
@@ -500,9 +504,9 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
500
504
  | `compact_conversation` | Folds a long agent transcript into a compact state ledger |
501
505
  | `get_token_savings_metrics` | Cumulative token and cost savings analytics |
502
506
  | `oumv_status` | Status, capabilities, and connection health of frontend/backend OUMV runtimes with hybrid fallback mode |
503
- | `oumv_observe` | Progressive runtime observation (L0 pulse, L1 surface, L2 detail) with out-of-the-box static AST fallback |
507
+ | `oumv_observe` | Progressive runtime observation (L0 pulse, L1 surface, L2 detail) with out-of-the-box static AST fallback. `path=<file>` observes that file offline: its symbols plus `file.version` (the OCC token) |
504
508
  | `oumv_understand` | Query runtime causality, state dependencies, and backend route mappings |
505
- | `oumv_mutate` | OCC-guarded source edits (mandatory `expectedVersion`, path jail, syntax pre-flight, backup) |
509
+ | `oumv_mutate` | OCC-guarded source edits (`expectedVersion` from `observe` → `file.version`, path jail, syntax pre-flight, backup). A `symbol` edit splices that declaration only, with or without a live runtime |
506
510
  | `oumv_verify` | Transactional verification and state invariant assertions |
507
511
  </details>
508
512
 
package/bin/tokensafe.js CHANGED
@@ -244,7 +244,23 @@ function download(url, dest, expectedSize, redirects) {
244
244
 
245
245
  function extractArchive(archive, destDir) {
246
246
  fs.mkdirSync(destDir, { recursive: true });
247
- const res = spawnSync('tar', ['-xzf', archive, '-C', destDir], { encoding: 'utf-8', stdio: 'pipe', timeout: 600000 });
247
+ // Windows: GNU tar (the one Git for Windows ships) reads `D:\...` as a remote
248
+ // host and fails with "Cannot connect to D:". Copying the archive next to the
249
+ // target and extracting it by relative name keeps the drive letter out of the
250
+ // argument list, which works for both GNU tar and bsdtar.
251
+ const localArchive = path.join(destDir, `.runtime${path.extname(archive) || '.tgz'}`);
252
+ fs.copyFileSync(archive, localArchive);
253
+ const res = spawnSync('tar', ['-xzf', path.basename(localArchive)], {
254
+ cwd: destDir,
255
+ encoding: 'utf-8',
256
+ stdio: 'pipe',
257
+ timeout: 600000,
258
+ });
259
+ try {
260
+ fs.rmSync(localArchive, { force: true });
261
+ } catch (_) {
262
+ /* the extraction verdict matters more than the leftover */
263
+ }
248
264
  if (res.status !== 0) {
249
265
  const detail = ((res.stderr || '') || (res.error && res.error.message) || '').trim();
250
266
  throw new Error(`failed to extract the runtime archive${detail ? `: ${detail}` : ''}`);
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.11",
3
+ "version": "4.7.13",
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.11",
4
+ "version": "4.7.13",
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.11",
4
+ "version": "4.7.13",
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.11",
6
+ "version": "4.7.13",
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.11",
26
+ "version": "4.7.13",
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.11",
42
+ "version": "4.7.13",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -141,6 +141,8 @@ TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to i
141
141
 
142
142
  5. **OPTIMISTIC CONCURRENCY MUTATIONS (`oumv(action="mutate")`)**:
143
143
  - Submits surgical edits verified against `expectedVersion` with built-in Babel AST TSX/JSX syntax guards and security leak prevention.
144
+ - **Offline (no live runtime)**: `tokensafe:oumv(action="observe", level="L1", path="<file>")` returns that file's symbols and `file.version`; pass it as `expectedVersion`. A `symbol` edit splices only that declaration (other declarations stay), an unknown symbol is refused, and a stale token returns `-32001`.
145
+ - For a non-declaration range use `apply_edits` with `start_line`/`end_line`; for an unsupported stack (Bun/Elysia, worker, Node without an adapter) `oumv(action="status")` lists the package as `oumvSupported: false` instead of hiding it.
144
146
 
145
147
  ---
146
148
 
package/src/__init__.py CHANGED
@@ -2,5 +2,5 @@
2
2
  TokenSafe: Local-first AI coding guardrails, context slicing, and team ROI telemetry for AI coding agents.
3
3
  """
4
4
 
5
- __version__ = "1.3.12"
5
+ __version__ = __import__("src.version_checker", fromlist=["CURRENT_VERSION"]).CURRENT_VERSION
6
6
  __author__ = "TokenSafe Team"
@@ -281,7 +281,7 @@ def go_patch_state(workspace: str) -> Dict[str, Any]:
281
281
  _GO_MODULE = "github.com/tokensafe-dev/tokensafe-backend/go"
282
282
  # Keep in step with the backend release tag (go/vX.Y.Z): injection must never
283
283
  # downgrade an adapter that is already newer than this pin.
284
- _GO_MODULE_VERSION = "v0.9.2"
284
+ _GO_MODULE_VERSION = "v0.11.0"
285
285
 
286
286
 
287
287
  def _version_tuple(tag: str):
@@ -675,6 +675,113 @@ def revert_node_patch(workspace: str) -> Dict[str, Any]:
675
675
  return {"status": "reverted", "entrypoint": os.path.relpath(entrypoint, workspace)}
676
676
 
677
677
 
678
+
679
+ # Next.js App Router: the adapter is a Route Handler created by the npm package.
680
+ # Nothing is patched inside app components — one generated file mounts the
681
+ # runtime, and `revert` deletes it, so the worktree returns to its old shape.
682
+ _NEXT_ROUTE_REL = os.path.join("app", "api", "tokensafe", "route.ts")
683
+ _NEXT_ROUTE_SOURCE = """// TokenSafe OUMV Route Handler (App Router, wire 1.6.0).
684
+ // Generated by `tokensafe inject`; delete this file (or run `tokensafe inject --revert`) to unmount.
685
+ import { createNextRouteHandlers } from 'tokensafe-backend-node';
686
+
687
+ const handlers = createNextRouteHandlers({
688
+ workspaceDir: process.cwd(),
689
+ publicUrl: `${process.env.TOKENSAFE_OUMV_PUBLIC_URL ?? 'http://127.0.0.1:3000'}/__oumv/rpc`,
690
+ });
691
+
692
+ export const POST = handlers.POST;
693
+ export const GET = handlers.GET;
694
+ """
695
+
696
+
697
+ def next_route_path(workspace: str) -> str:
698
+ return os.path.join(workspace, _NEXT_ROUTE_REL)
699
+
700
+
701
+ def next_patch_state(workspace: str) -> Dict[str, Any]:
702
+ path = next_route_path(workspace)
703
+ return {"entrypoint": path if os.path.isfile(path) else None, "patched": os.path.isfile(path)}
704
+
705
+
706
+ def apply_next_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
707
+ path = next_route_path(workspace)
708
+ if os.path.isfile(path):
709
+ return {"status": "already_patched", "entrypoint": path}
710
+ if dry_run:
711
+ return {"status": "dry_run", "entrypoint": path, "would_create": path}
712
+ os.makedirs(os.path.dirname(path), exist_ok=True)
713
+ with open(path, "w", encoding="utf-8") as handle:
714
+ handle.write(_NEXT_ROUTE_SOURCE)
715
+ _write_manifest(workspace, "next", {"entrypoint": path, "framework": "nextjs", "mode": "next_route"})
716
+ return {"status": "patched", "entrypoint": path}
717
+
718
+
719
+ def revert_next_patch(workspace: str) -> Dict[str, Any]:
720
+ manifest = _read_manifest(workspace, "next", ("next_route",))
721
+ if not manifest:
722
+ return {"status": "nothing-to-revert"}
723
+ entrypoint = manifest.get("entrypoint")
724
+ if entrypoint and os.path.isfile(entrypoint):
725
+ os.remove(entrypoint)
726
+ parent = os.path.dirname(entrypoint)
727
+ try:
728
+ os.removedirs(parent) # only removes the directories this adapter created
729
+ except OSError:
730
+ pass
731
+ _delete_manifest(manifest)
732
+ return {"status": "reverted", "entrypoint": entrypoint}
733
+
734
+
735
+ def detect_orm(workspace: str) -> Dict[str, Any]:
736
+ """Static ORM hint for the inject plan (the .NET AddDbContext scan is the model).
737
+
738
+ It reads manifests and imports, never runs the app: `sandbox` says whether the
739
+ adapter can adopt the engine on its own (`auto`), needs an explicit argument
740
+ (`manual`), or has no engine to sandbox (`none`).
741
+ """
742
+ deps: Dict[str, str] = {}
743
+ sources: List[str] = []
744
+ package_json = os.path.join(workspace, "package.json")
745
+ if os.path.isfile(package_json):
746
+ try:
747
+ with open(package_json, "r", encoding="utf-8") as handle:
748
+ data = json.load(handle)
749
+ for key in ("dependencies", "devDependencies"):
750
+ deps.update({str(k): str(v) for k, v in (data.get(key) or {}).items()})
751
+ except Exception:
752
+ pass
753
+ for name in ("pyproject.toml", "requirements.txt", "go.mod"):
754
+ candidate = os.path.join(workspace, name)
755
+ if os.path.isfile(candidate):
756
+ try:
757
+ with open(candidate, "r", encoding="utf-8") as handle:
758
+ sources.append(handle.read().lower())
759
+ except Exception:
760
+ pass
761
+ python_text = " ".join(sources)
762
+
763
+ if "@prisma/client" in deps or "prisma" in deps:
764
+ return {"orm": "prisma", "sandbox": "auto", "how": "Prisma $transaction detected from the app's prisma client (app.locals.prisma / fastify decorator)"}
765
+ if "knex" in deps:
766
+ return {"orm": "knex", "sandbox": "manual", "how": "pass sandbox.db.run: knex.transaction + rollback"}
767
+ if "drizzle-orm" in deps:
768
+ return {"orm": "drizzle", "sandbox": "manual", "how": "pass sandbox.db.run: db.transaction + rollback"}
769
+ if "pg" in deps or "mysql2" in deps or "better-sqlite3" in deps:
770
+ return {"orm": "database/sql", "sandbox": "manual", "how": "pass sandbox.db.run around a transaction"}
771
+ if "sqlalchemy" in python_text:
772
+ return {"orm": "sqlalchemy", "sandbox": "auto", "how": "Engine on app.state (or dependency override) is adopted by mount_tokensafe"}
773
+ if "django" in python_text:
774
+ return {"orm": "django-orm", "sandbox": "manual", "how": "atomic block + forced rollback; not auto-detected"}
775
+ if "gorm.io/gorm" in python_text:
776
+ return {"orm": "gorm", "sandbox": "manual", "how": "rt.SetDBSandbox(db.NewSandbox(sqlDB))"}
777
+ if "database/sql" in python_text:
778
+ return {"orm": "database/sql", "sandbox": "manual", "how": "rt.SetDBSandbox(db.NewSandbox(sqlDB)) or gin/chi Options{DB}"}
779
+ if "microsoft.entityframeworkcore" in python_text or "@prisma" in deps:
780
+ return {"orm": "ef-core", "sandbox": "auto", "how": "AddDbContext is discovered by AddTokensafe()"}
781
+ if "entityframework" in python_text:
782
+ return {"orm": "ef-core", "sandbox": "auto", "how": "AddDbContext is discovered by AddTokensafe()"}
783
+ return {"orm": None, "sandbox": "none", "how": "no ORM detected"}
784
+
678
785
  def _sidecar_cache_dir() -> str:
679
786
  return os.path.join(_tokensafe_home(), "sidecars")
680
787
 
@@ -689,7 +796,7 @@ def _sidecar_cache_dir() -> str:
689
796
  _DOTNET_MARK_BEGIN = "// tokensafe:oumv:begin"
690
797
  _DOTNET_MARK_END = "// tokensafe:oumv:end"
691
798
  _DOTNET_PACKAGE = "TokenSafe.Oumv.AspNetCore"
692
- _DOTNET_PACKAGE_VERSION = "0.1.1"
799
+ _DOTNET_PACKAGE_VERSION = "0.2.0"
693
800
 
694
801
 
695
802
 
@@ -1024,7 +1131,8 @@ def plan(workspace: str) -> Dict[str, Any]:
1024
1131
  actions: List[Dict[str, Any]] = []
1025
1132
 
1026
1133
  frontend = stack.get("frontend")
1027
- if frontend:
1134
+ is_next = bool(frontend and frontend.get("framework") == "nextjs")
1135
+ if frontend and not is_next:
1028
1136
  actions.append({
1029
1137
  "kind": "frontend_zero_footprint",
1030
1138
  "profile": "frontend",
@@ -1034,6 +1142,19 @@ def plan(workspace: str) -> Dict[str, Any]:
1034
1142
  "run": "tokensafe dev",
1035
1143
  "install": catalog.get("frontend/react", {}).get("technology", {}).get("package", {}).get("install"),
1036
1144
  })
1145
+ if is_next:
1146
+ next_state = next_patch_state(workspace)
1147
+ actions.append({
1148
+ "kind": "next_route_handler",
1149
+ "profile": "backend",
1150
+ "framework": "nextjs",
1151
+ "writes_repo": True,
1152
+ "already_patched": next_state["patched"],
1153
+ "entrypoint": next_state["entrypoint"] or next_route_path(workspace),
1154
+ "description": "one App Router Route Handler (app/api/tokensafe/route.ts) calling createNextRouteHandlers; server profile only — delete the file or --revert to unmount",
1155
+ "install": "npm install --save-dev tokensafe-backend-node",
1156
+ "run": "next dev",
1157
+ })
1037
1158
 
1038
1159
  backend = stack.get("backend")
1039
1160
  if backend:
@@ -1118,6 +1239,10 @@ def plan(workspace: str) -> Dict[str, Any]:
1118
1239
  "description": "no OUMV adapter for this stack yet — use tokensafe tools instead",
1119
1240
  })
1120
1241
 
1242
+ db = detect_orm(workspace)
1243
+ for action in actions:
1244
+ action.setdefault("db", db)
1245
+
1121
1246
  return {
1122
1247
  "workspace": workspace,
1123
1248
  "profiles": [p for p in ("frontend", "backend") if stack.get(p)],
@@ -1140,13 +1265,16 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
1140
1265
  }
1141
1266
 
1142
1267
  stack = detect_project_stack(workspace)
1143
- if stack.get("frontend"):
1268
+ frontend = stack.get("frontend") or {}
1269
+ if frontend and frontend.get("framework") != "nextjs":
1144
1270
  results["actions"].append({
1145
1271
  "kind": "frontend_zero_footprint",
1146
1272
  "status": "ready",
1147
1273
  "run": "tokensafe dev",
1148
1274
  "note": "no repository files are written; the bridge lives in the dev-server wrapper",
1149
1275
  })
1276
+ if frontend.get("framework") == "nextjs":
1277
+ results["actions"].append({"kind": "next_route_handler", **apply_next_patch(workspace, dry_run=dry_run)})
1150
1278
 
1151
1279
  backend = stack.get("backend") or {}
1152
1280
  if backend.get("provider") == "fastapi":
@@ -1181,4 +1309,5 @@ def revert(workspace: str) -> Dict[str, Any]:
1181
1309
  "go": revert_go_patch(workspace),
1182
1310
  "node": revert_node_patch(workspace),
1183
1311
  "dotnet": revert_dotnet_patch(workspace),
1312
+ "next": revert_next_patch(workspace),
1184
1313
  }
@@ -204,6 +204,19 @@ def validate_verify_command(
204
204
  )
205
205
 
206
206
 
207
+ def _target_occurrence_lines(content: str, target: str, limit: int = 5) -> List[str]:
208
+ """Start lines of the first `limit` occurrences of `target` in `content`."""
209
+ out: List[str] = []
210
+ scan = 0
211
+ while len(out) < limit:
212
+ pos = content.find(target, scan)
213
+ if pos < 0:
214
+ break
215
+ out.append(str(content.count("\n", 0, pos) + 1))
216
+ scan = pos + 1
217
+ return out
218
+
219
+
207
220
  def _find_closest_line_hint(target: str, content: str, max_lines_preview: int = 5) -> str:
208
221
  """Finds closest matching snippet in content to provide actionable line-drift retry guidance."""
209
222
  target_first = target.splitlines()[0].strip() if target.splitlines() else target.strip()
@@ -306,19 +319,37 @@ def _apply_hunk_to_text(
306
319
  sub_text = "".join(lines[s_idx:e_idx])
307
320
  match_target, nl = _prepare_match(sub_text)
308
321
  if match_target not in sub_text:
309
- hint = _find_closest_line_hint(target, sub_text)
310
- return None, f"Target not found in lines {s_idx+1}..{e_idx}: {hint}"
322
+ # start_line/end_line disambiguate *where* a snippet lives; they are not a
323
+ # hard constraint on its span. A window one line short of a multi-line
324
+ # target used to fail the whole batch even when the snippet was unique in
325
+ # the file (the caller had simply mis-measured end_line).
326
+ full_target, full_nl = _prepare_match(content)
327
+ full_count = content.count(full_target) if full_target else 0
328
+ if full_count == 1:
329
+ prepared_replacement = _normalize_eol(replacement, full_nl)
330
+ return content.replace(full_target, prepared_replacement, 1), None
331
+ if full_count > 1:
332
+ occ = _target_occurrence_lines(content, full_target)
333
+ retry = ""
334
+ if occ:
335
+ first = int(occ[0])
336
+ span = max(1, full_target.count("\n") + 1)
337
+ retry = (
338
+ f" Retry with start_line={first}, end_line={first + span - 1}, "
339
+ f"or drop start_line/end_line."
340
+ )
341
+ return None, (
342
+ f"Target not found in lines {s_idx+1}..{e_idx}, but it occurs {full_count} times "
343
+ f"elsewhere in the file (near lines {', '.join(occ)}).{retry}"
344
+ )
345
+ hint = _find_closest_line_hint(target, content)
346
+ return None, f"Target not found in lines {s_idx+1}..{e_idx} nor anywhere in the file: {hint}"
311
347
  count = sub_text.count(match_target)
312
348
  if count > 1 and not replace_all:
313
349
  # Report where: the caller just narrowed to a window and needs the exact
314
350
  # sub-range (or a longer unique snippet) to finish the edit in one retry.
315
- occ, scan = [], 0
316
- while len(occ) < 5:
317
- pos = sub_text.find(match_target, scan)
318
- if pos < 0:
319
- break
320
- occ.append(str(s_idx + sub_text.count("\n", 0, pos) + 1))
321
- scan = pos + 1
351
+ occ = _target_occurrence_lines(sub_text, match_target)
352
+ occ = [str(int(o) + s_idx) for o in occ]
322
353
  locs = f" (near lines {', '.join(occ)})" if occ else ""
323
354
  retry = ""
324
355
  if occ: