tokensafe 4.7.4 → 4.7.5
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/batch_editor.py +12 -2
- package/src/bench/go_target.py +135 -14
- package/src/installer.py +1 -1
- package/src/mcp_server.py +147 -1
- 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.5",
|
|
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.5",
|
|
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.5",
|
|
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.5",
|
|
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.5",
|
|
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.5",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
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)
|
package/src/bench/go_target.py
CHANGED
|
@@ -117,6 +117,48 @@ func (h {name}) {verb}{noun}(w http.ResponseWriter, r *http.Request) {{
|
|
|
117
117
|
)
|
|
118
118
|
|
|
119
119
|
|
|
120
|
+
def choose_scoped_hunk(
|
|
121
|
+
hunks: Optional[List[Dict[str, Any]]],
|
|
122
|
+
error: Dict[str, Any],
|
|
123
|
+
window: Optional[Tuple[int, int]],
|
|
124
|
+
) -> Optional[Tuple[List[Dict[str, Any]], Dict[str, int]]]:
|
|
125
|
+
"""Pick a scoped retry for `-32011 target_not_unique`, or None.
|
|
126
|
+
|
|
127
|
+
The retry is deterministic: it is chosen only when exactly one reported
|
|
128
|
+
occurrence falls inside the line window the agent last read. Zero or two
|
|
129
|
+
candidates mean the tool refuses to guess and hands the error back.
|
|
130
|
+
"""
|
|
131
|
+
if not isinstance(error, dict) or error.get("reason") != "target_not_unique":
|
|
132
|
+
return None
|
|
133
|
+
if not window or not isinstance(hunks, list) or not hunks:
|
|
134
|
+
return None
|
|
135
|
+
try:
|
|
136
|
+
start, end = int(window[0]), int(window[1])
|
|
137
|
+
except (TypeError, ValueError):
|
|
138
|
+
return None
|
|
139
|
+
if end < start:
|
|
140
|
+
return None
|
|
141
|
+
lines = []
|
|
142
|
+
for value in error.get("lines") or []:
|
|
143
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
144
|
+
lines.append(int(value))
|
|
145
|
+
inside = [line for line in lines if start <= line <= end]
|
|
146
|
+
if len(inside) != 1:
|
|
147
|
+
return None
|
|
148
|
+
index = error.get("hunk")
|
|
149
|
+
index = int(index) if isinstance(index, (int, float)) and not isinstance(index, bool) else 0
|
|
150
|
+
if index < 0 or index >= len(hunks):
|
|
151
|
+
return None
|
|
152
|
+
line = inside[0]
|
|
153
|
+
target = str(hunks[index].get("target") or "")
|
|
154
|
+
scope_start = max(start, line - 2)
|
|
155
|
+
scope_end = min(end, line + target.count("\n") + 2)
|
|
156
|
+
scoped = [dict(hunk) for hunk in hunks]
|
|
157
|
+
scoped[index]["startLine"] = scope_start
|
|
158
|
+
scoped[index]["endLine"] = scope_end
|
|
159
|
+
return scoped, {"hunk": index, "startLine": scope_start, "endLine": scope_end}
|
|
160
|
+
|
|
161
|
+
|
|
120
162
|
class GoWorkspace:
|
|
121
163
|
def __init__(self, task_id: str, files: int = 0):
|
|
122
164
|
if task_id not in TASKS:
|
|
@@ -140,6 +182,10 @@ class GoWorkspace:
|
|
|
140
182
|
self.helper = self.dir.parent / "benchoumv"
|
|
141
183
|
self._helper_built_at = 0.0
|
|
142
184
|
self._mcp = None
|
|
185
|
+
# Last line window the agent actually read per file (observe L3 / getSource).
|
|
186
|
+
# A hunk that repeats can be scoped to it without guessing: the caller just
|
|
187
|
+
# read those lines, so an occurrence outside them is not the one it means.
|
|
188
|
+
self._read_windows: Dict[str, Tuple[int, int]] = {}
|
|
143
189
|
self.break_build()
|
|
144
190
|
|
|
145
191
|
# ---- task setup -------------------------------------------------------
|
|
@@ -299,7 +345,78 @@ class GoWorkspace:
|
|
|
299
345
|
return {"error": f"invalid JSON from helper: {line[-1][:200]}"}
|
|
300
346
|
if payload.get("error"):
|
|
301
347
|
return {"error": payload["error"]}
|
|
302
|
-
|
|
348
|
+
result = payload.get("result")
|
|
349
|
+
if isinstance(result, dict):
|
|
350
|
+
self._remember_read_window(method, result)
|
|
351
|
+
return result
|
|
352
|
+
|
|
353
|
+
# ---- read windows & scoped retries ------------------------------------
|
|
354
|
+
def _window_key(self, path: str) -> str:
|
|
355
|
+
candidate = Path(path)
|
|
356
|
+
if not candidate.is_absolute():
|
|
357
|
+
candidate = self.dir / candidate
|
|
358
|
+
return os.path.normpath(str(candidate))
|
|
359
|
+
|
|
360
|
+
def _remember_read_window(self, method: str, result: Dict[str, Any]) -> None:
|
|
361
|
+
if method == "oumv/observe" and isinstance(result.get("data"), dict):
|
|
362
|
+
data = result["data"]
|
|
363
|
+
source = "data.source" in data
|
|
364
|
+
elif method == "oumv/getSource" and "source" in result:
|
|
365
|
+
data = result
|
|
366
|
+
source = True
|
|
367
|
+
else:
|
|
368
|
+
return
|
|
369
|
+
if not source:
|
|
370
|
+
return
|
|
371
|
+
path = data.get("path")
|
|
372
|
+
start, end = data.get("startLine"), data.get("endLine")
|
|
373
|
+
if not path or not isinstance(start, int) or not isinstance(end, int) or end < start:
|
|
374
|
+
return
|
|
375
|
+
self._read_windows[self._window_key(str(path))] = (start, end)
|
|
376
|
+
|
|
377
|
+
def apply_edit_scoped(
|
|
378
|
+
self,
|
|
379
|
+
path: str,
|
|
380
|
+
expected_version: str,
|
|
381
|
+
mode: str = "",
|
|
382
|
+
replacement: str = "",
|
|
383
|
+
symbol: str = "",
|
|
384
|
+
hunks: Optional[List[Dict[str, Any]]] = None,
|
|
385
|
+
) -> Any:
|
|
386
|
+
"""applyEdit with one deterministic recovery from -32011 target_not_unique.
|
|
387
|
+
|
|
388
|
+
If the model omitted startLine/endLine and the target repeats, the runtime
|
|
389
|
+
answers with the occurrence lines. When exactly one of them lies inside the
|
|
390
|
+
window this agent just read, retry with that window. Two candidates are
|
|
391
|
+
never resolved by guessing: the error goes back to the model instead.
|
|
392
|
+
"""
|
|
393
|
+
params: Dict[str, Any] = {
|
|
394
|
+
"path": path,
|
|
395
|
+
"expectedVersion": expected_version,
|
|
396
|
+
**({"mode": mode} if mode else {}),
|
|
397
|
+
**({"replacement": replacement} if replacement else {}),
|
|
398
|
+
**({"symbol": symbol} if symbol else {}),
|
|
399
|
+
**({"hunks": hunks} if hunks else {}),
|
|
400
|
+
}
|
|
401
|
+
result = self.oumv("oumv/applyEdit", params)
|
|
402
|
+
error = result.get("error") if isinstance(result, dict) else None
|
|
403
|
+
if mode == "patch" and isinstance(error, dict) and error.get("code") == -32011:
|
|
404
|
+
data = dict(error.get("data") or {})
|
|
405
|
+
if not data.get("reason") and "not_unique" in str(error.get("message", "")):
|
|
406
|
+
data["reason"] = "target_not_unique"
|
|
407
|
+
window = self._read_windows.get(self._window_key(path))
|
|
408
|
+
chosen = choose_scoped_hunk(hunks, data, window)
|
|
409
|
+
if chosen is not None:
|
|
410
|
+
scoped_hunks, scope = chosen
|
|
411
|
+
retry = self.oumv("oumv/applyEdit", {**params, "hunks": scoped_hunks})
|
|
412
|
+
if isinstance(retry, dict) and not retry.get("error"):
|
|
413
|
+
annotated = dict(retry)
|
|
414
|
+
annotated["autoScoped"] = {
|
|
415
|
+
**scope,
|
|
416
|
+
"source": "unique occurrence inside the last observe L3 window",
|
|
417
|
+
}
|
|
418
|
+
return annotated
|
|
419
|
+
return result
|
|
303
420
|
|
|
304
421
|
def tokensafe_tool_schemas(self) -> Optional[List[Dict[str, Any]]]:
|
|
305
422
|
"""The product's own `tools/list`, renamed to the arm's stable aliases.
|
|
@@ -527,14 +644,21 @@ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
|
|
|
527
644
|
"mode": {"type": "string", "enum": ["patch", "symbol", "replace"]},
|
|
528
645
|
"hunks": {
|
|
529
646
|
"type": "array",
|
|
530
|
-
"description":
|
|
647
|
+
"description": (
|
|
648
|
+
"mode='patch': exact snippets to splice, applied in order. Copy startLine/endLine "
|
|
649
|
+
"from the L3 slice: without them a snippet that occurs more than once is rejected "
|
|
650
|
+
"with -32011 (the error carries the occurrence lines and a scoped retry)."
|
|
651
|
+
),
|
|
531
652
|
"items": {
|
|
532
653
|
"type": "object",
|
|
533
654
|
"properties": {
|
|
534
655
|
"target": {"type": "string", "description": "Exact snippet from the source"},
|
|
535
656
|
"replacement": {"type": "string", "description": "Replacement snippet"},
|
|
536
|
-
"startLine": {
|
|
537
|
-
|
|
657
|
+
"startLine": {
|
|
658
|
+
"type": "integer",
|
|
659
|
+
"description": "1-based first line to search, from observe L3; makes a repeated target unique",
|
|
660
|
+
},
|
|
661
|
+
"endLine": {"type": "integer", "description": "1-based last line to search"},
|
|
538
662
|
},
|
|
539
663
|
"required": ["target", "replacement"],
|
|
540
664
|
},
|
|
@@ -647,16 +771,13 @@ def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
|
|
|
647
771
|
tools.update({
|
|
648
772
|
"oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
|
|
649
773
|
"oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
|
|
650
|
-
"oumv_applyEdit": lambda path, expectedVersion, mode="", replacement="", symbol="", hunks=None: ws.
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
**({"symbol": symbol} if symbol else {}),
|
|
658
|
-
**({"hunks": hunks} if hunks else {}),
|
|
659
|
-
},
|
|
774
|
+
"oumv_applyEdit": lambda path, expectedVersion, mode="", replacement="", symbol="", hunks=None: ws.apply_edit_scoped(
|
|
775
|
+
path,
|
|
776
|
+
expectedVersion,
|
|
777
|
+
mode=mode,
|
|
778
|
+
replacement=replacement,
|
|
779
|
+
symbol=symbol,
|
|
780
|
+
hunks=hunks,
|
|
660
781
|
),
|
|
661
782
|
"oumv_verify": lambda target, payload=None: ws.oumv(
|
|
662
783
|
"oumv/verify", {"target": target, "action": "probe", "payload": payload}
|
package/src/installer.py
CHANGED
|
@@ -50,7 +50,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
50
50
|
"1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). Use `tokensafe:scoped_search(query, path='.', scope='code')` for single searches (`mode='auto'|'text'|'regex'|'glob'|'fuzzy'|'git'`) or `queries=[...]` for up to 20 concurrent queries in one call.\n"
|
|
51
51
|
"2. **Mandatory Symbol, Endpoint, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). When the bug names a route, call `smart_read_file(endpoint='POST /api/orders')` FIRST: one call resolves the route registration across the repo → handler body + file path + line range + whole-file version (and names the handler's cross-file callees). `symbol` accepts an identifier, a qualified member (`Type.Method`) or an endpoint target (`'POST /api/orders'`): when the target is not a declaration in that file you get the enclosing handler body (or a tight ±window around the hit) with line numbers, plus the declaration itself when it lives in another file — that is the slice you edit, never a folded skeleton you have to re-read, and it is exact file text so it needs no confirming re-read. Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
|
|
52
52
|
"3. **Repeat Read Deduplication**: Never re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`).\n"
|
|
53
|
-
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`. For a failing test, one hunk + `verify='auto'` (the project's own declared test command) per attempt: the edit and the verdict come back in one call, so read the reported line and apply the next hunk instead of rewriting whole files.\n"
|
|
53
|
+
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`. Take `start_line`/`end_line` from the slice header (`// --- Lx-Ly`): a target that occurs more than once is rejected with its occurrence lines and a ready scoped retry, and the tool auto-scopes to the window just read when exactly one occurrence is inside it. For a failing test, one hunk + `verify='auto'` (the project's own declared test command) per attempt: the edit and the verdict come back in one call, so read the reported line and apply the next hunk instead of rewriting whole files.\n"
|
|
54
54
|
"5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For an unfamiliar repository or a broad refactor, FIRST call `tokensafe:repo_map(view='graph', project_path=...)` for God Nodes (<250 tokens). Use `view='api'` for exported types/interfaces and `view='tree'` instead of `ls -la`. Skip the map when the task already names the failing endpoint, symbol or file — go straight to `scoped_search` + `smart_read_file`.\n"
|
|
55
55
|
"6. **Utilities (`run_helper`)**: Use `tokensafe:run_helper(action=...)` for rare/auxiliary operations: `'sanitize'` (rewrite shell/test commands), `'guard'` (pre-flight secret/safety audit), `'diff'` (slice diff), `'deps'` (lockfile point lookup), `'web'` (fetch clean Markdown), `'expand'` (restore `#hash`), `'image'` (downscale >1024px), and `'compress'` (TOCP prompt).\n"
|
|
56
56
|
"7. **Compact Tests & Build Output**: Run noisy commands, builds, and test suites via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]` (clean 1-line summary on pass, full trace on failure; never leave `vitest`/`jest`/`bun` in watch mode).\n"
|
package/src/mcp_server.py
CHANGED
|
@@ -44,7 +44,7 @@ from src.session_context import current_root, current_session_id
|
|
|
44
44
|
|
|
45
45
|
SERVER_INFO = {
|
|
46
46
|
"name": "tokensafe-mcp",
|
|
47
|
-
"version": "4.7.
|
|
47
|
+
"version": "4.7.5"
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -806,6 +806,33 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
806
806
|
'max_edge': {'type': 'integer'},
|
|
807
807
|
'prompt': {'type': 'string'}}}}]
|
|
808
808
|
|
|
809
|
+
|
|
810
|
+
def _tighten_apply_edits_schema() -> None:
|
|
811
|
+
"""Put the scoping rule where the model reads it on every request.
|
|
812
|
+
|
|
813
|
+
The 2026-11-27 matrix left one outlier: the model dropped start_line/end_line,
|
|
814
|
+
got -32011 target_not_unique, and paid a re-read before retrying. The runtime
|
|
815
|
+
now answers with occurrence lines and suggested hunks, and the tool text says
|
|
816
|
+
where the range comes from, so the retry is a one-parameter fix.
|
|
817
|
+
"""
|
|
818
|
+
for tool in TOOLS:
|
|
819
|
+
if tool.get("name") != "apply_edits":
|
|
820
|
+
continue
|
|
821
|
+
hunks = tool["inputSchema"]["properties"]["edits"]["items"]["properties"]["hunks"]
|
|
822
|
+
hunks["description"] = (
|
|
823
|
+
"Replacement hunks. Copy start_line/end_line from the read slice header "
|
|
824
|
+
"(`// --- Lx-Ly`): a target that occurs more than once is rejected with the "
|
|
825
|
+
"occurrence lines and a scoped retry, and a ranged hunk is never ambiguous. "
|
|
826
|
+
"The tool auto-scopes when the last read window contains exactly one occurrence."
|
|
827
|
+
)
|
|
828
|
+
hunks["items"]["properties"]["start_line"]["description"] = (
|
|
829
|
+
"1-based first line to search; take it from the slice header (// --- Lx-Ly)"
|
|
830
|
+
)
|
|
831
|
+
hunks["items"]["properties"]["end_line"]["description"] = "1-based last line to search"
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
_tighten_apply_edits_schema()
|
|
835
|
+
|
|
809
836
|
def format_file_size(size_bytes: int) -> str:
|
|
810
837
|
if size_bytes < 1024:
|
|
811
838
|
return f"{size_bytes} B"
|
|
@@ -1141,6 +1168,113 @@ def _is_binary_file(path: str, probe_bytes: int = 4096) -> bool:
|
|
|
1141
1168
|
return False
|
|
1142
1169
|
|
|
1143
1170
|
|
|
1171
|
+
# Line windows this session actually delivered per file. A batch hunk with no
|
|
1172
|
+
# start_line/end_line can be scoped to one of them when a target repeats: the
|
|
1173
|
+
# agent just read those lines, so an occurrence outside them is not the one it
|
|
1174
|
+
# means. Only a window containing exactly one occurrence qualifies — the tool
|
|
1175
|
+
# never chooses between two candidates.
|
|
1176
|
+
_LAST_READ_WINDOWS: Dict[str, List[Tuple[int, int]]] = {}
|
|
1177
|
+
_LAST_READ_WINDOWS_LOCK = threading.Lock()
|
|
1178
|
+
_MAX_READ_WINDOWS = 8
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
def _remember_read_window(path: str, start: Any, end: Any) -> None:
|
|
1182
|
+
try:
|
|
1183
|
+
first, last = int(start), int(end)
|
|
1184
|
+
except (TypeError, ValueError):
|
|
1185
|
+
return
|
|
1186
|
+
if not path or first < 1 or last < first:
|
|
1187
|
+
return
|
|
1188
|
+
try:
|
|
1189
|
+
key = os.path.realpath(path)
|
|
1190
|
+
except OSError:
|
|
1191
|
+
key = os.path.abspath(path)
|
|
1192
|
+
with _LAST_READ_WINDOWS_LOCK:
|
|
1193
|
+
windows = _LAST_READ_WINDOWS.setdefault(key, [])
|
|
1194
|
+
entry = (first, last)
|
|
1195
|
+
if entry in windows:
|
|
1196
|
+
windows.remove(entry)
|
|
1197
|
+
windows.append(entry)
|
|
1198
|
+
del windows[:-_MAX_READ_WINDOWS]
|
|
1199
|
+
|
|
1200
|
+
|
|
1201
|
+
def _remember_rendered_windows(path: str, text: str) -> None:
|
|
1202
|
+
"""Records every `// --- Lx-Ly` slice header in a rendered read (symbol hits,
|
|
1203
|
+
cross-file inlines). The header names the file when it is not the one read."""
|
|
1204
|
+
for match in re.finditer(r"// --- L(\d+)-L(\d+)(?: \(([^,()]+),)?", text or ""):
|
|
1205
|
+
target = os.path.join(os.path.dirname(path), match.group(3)) if match.group(3) else path
|
|
1206
|
+
_remember_read_window(target, match.group(1), match.group(2))
|
|
1207
|
+
|
|
1208
|
+
|
|
1209
|
+
def _autoscope_edits(edits: Any, cwd: str) -> Tuple[Any, List[str]]:
|
|
1210
|
+
"""Scopes unambiguous hunks to the window the agent last read.
|
|
1211
|
+
|
|
1212
|
+
Returns (edits, notes). A hunk is touched only when it has no range, its
|
|
1213
|
+
target repeats in the file, and exactly one remembered window contains it.
|
|
1214
|
+
"""
|
|
1215
|
+
if not isinstance(edits, list):
|
|
1216
|
+
return edits, []
|
|
1217
|
+
notes: List[str] = []
|
|
1218
|
+
out: List[Any] = []
|
|
1219
|
+
for edit in edits:
|
|
1220
|
+
if not isinstance(edit, dict) or not isinstance(edit.get("hunks"), list) or not edit.get("path"):
|
|
1221
|
+
out.append(edit)
|
|
1222
|
+
continue
|
|
1223
|
+
rel = str(edit.get("path"))
|
|
1224
|
+
abs_path = rel if os.path.isabs(rel) else os.path.join(cwd, rel)
|
|
1225
|
+
key = os.path.realpath(abs_path)
|
|
1226
|
+
with _LAST_READ_WINDOWS_LOCK:
|
|
1227
|
+
windows = list(_LAST_READ_WINDOWS.get(key) or [])
|
|
1228
|
+
if not windows:
|
|
1229
|
+
out.append(edit)
|
|
1230
|
+
continue
|
|
1231
|
+
try:
|
|
1232
|
+
with open(abs_path, "r", encoding="utf-8", errors="replace") as handle:
|
|
1233
|
+
content = handle.read()
|
|
1234
|
+
except OSError:
|
|
1235
|
+
out.append(edit)
|
|
1236
|
+
continue
|
|
1237
|
+
lines = content.splitlines()
|
|
1238
|
+
new_hunks: List[Any] = []
|
|
1239
|
+
changed = False
|
|
1240
|
+
for hunk in edit["hunks"]:
|
|
1241
|
+
if not isinstance(hunk, dict) or not isinstance(hunk.get("target"), str) or not hunk["target"]:
|
|
1242
|
+
new_hunks.append(hunk)
|
|
1243
|
+
continue
|
|
1244
|
+
if hunk.get("start_line") is not None or hunk.get("end_line") is not None:
|
|
1245
|
+
new_hunks.append(hunk)
|
|
1246
|
+
continue
|
|
1247
|
+
target = hunk["target"]
|
|
1248
|
+
if content.count(target) <= 1:
|
|
1249
|
+
new_hunks.append(hunk)
|
|
1250
|
+
continue
|
|
1251
|
+
candidates = []
|
|
1252
|
+
for start, end in windows:
|
|
1253
|
+
if start > len(lines):
|
|
1254
|
+
continue
|
|
1255
|
+
window_text = "\n".join(lines[start - 1:min(end, len(lines))])
|
|
1256
|
+
if window_text.count(target) == 1:
|
|
1257
|
+
candidates.append((start, min(end, len(lines))))
|
|
1258
|
+
if len(candidates) == 1:
|
|
1259
|
+
scoped = dict(hunk)
|
|
1260
|
+
scoped["start_line"], scoped["end_line"] = candidates[0]
|
|
1261
|
+
new_hunks.append(scoped)
|
|
1262
|
+
changed = True
|
|
1263
|
+
notes.append(
|
|
1264
|
+
f"`{rel}`: hunk auto-scoped to lines {candidates[0][0]}-{candidates[0][1]} "
|
|
1265
|
+
"(the target repeats; it occurs once in the window last read)"
|
|
1266
|
+
)
|
|
1267
|
+
else:
|
|
1268
|
+
new_hunks.append(hunk)
|
|
1269
|
+
if changed:
|
|
1270
|
+
clone = dict(edit)
|
|
1271
|
+
clone["hunks"] = new_hunks
|
|
1272
|
+
out.append(clone)
|
|
1273
|
+
else:
|
|
1274
|
+
out.append(edit)
|
|
1275
|
+
return out, notes
|
|
1276
|
+
|
|
1277
|
+
|
|
1144
1278
|
def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[int]) -> Tuple[Optional[str], Optional[str]]:
|
|
1145
1279
|
"""Reads 1-based [start_line..end_line] using bounded iteration. Returns (content, err_msg)."""
|
|
1146
1280
|
if start_line is not None and start_line < 1:
|
|
@@ -1498,6 +1632,7 @@ def _render_endpoint_slice(
|
|
|
1498
1632
|
f"ver={version} via {hit.via}]"
|
|
1499
1633
|
)
|
|
1500
1634
|
body_lines, first, last = hit.body, hit.line, hit.end_line
|
|
1635
|
+
body_file = hit.file
|
|
1501
1636
|
if hit.handler_kind == "named" and hit.handler:
|
|
1502
1637
|
short = hit.handler.split(".")[-1]
|
|
1503
1638
|
decls = [d for d in index.get(short, []) if d[0] != hit.file] or index.get(short, [])
|
|
@@ -1507,6 +1642,7 @@ def _render_endpoint_slice(
|
|
|
1507
1642
|
with open(os.path.join(root, file), "r", encoding="utf-8", errors="replace") as handle:
|
|
1508
1643
|
src = handle.read().splitlines()
|
|
1509
1644
|
body_lines, first, last = src[start - 1:end], start, end
|
|
1645
|
+
body_file = file
|
|
1510
1646
|
head = (
|
|
1511
1647
|
f"// [TS endpoint {prefix}{verb} {route} → handler {short} in {file} "
|
|
1512
1648
|
f"L{start}-L{end} ver={route_index.file_version(os.path.join(root, file))}]"
|
|
@@ -1524,6 +1660,7 @@ def _render_endpoint_slice(
|
|
|
1524
1660
|
entries.append(f"// calls: {callees}")
|
|
1525
1661
|
entries.append(f"// --- L{first}-L{last}")
|
|
1526
1662
|
entries.extend(body_lines)
|
|
1663
|
+
_remember_read_window(os.path.join(root, body_file), first, last)
|
|
1527
1664
|
delivered = "\n".join(entries) + "\n"
|
|
1528
1665
|
if tracker is not None:
|
|
1529
1666
|
try:
|
|
@@ -1980,6 +2117,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1980
2117
|
slice_lines = (content or "").splitlines()
|
|
1981
2118
|
slice_first = start_line if start_line is not None else 1
|
|
1982
2119
|
slice_last = slice_first + len(slice_lines) - 1 if slice_lines else max(1, slice_first - 1)
|
|
2120
|
+
_remember_read_window(path, slice_first, slice_last)
|
|
1983
2121
|
range_label = f"{slice_first}-{slice_last}" if slice_lines else str(slice_first)
|
|
1984
2122
|
prefetch_block = ""
|
|
1985
2123
|
if not sym_clean or eff_dep_mode == "full":
|
|
@@ -2017,6 +2155,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2017
2155
|
scope_plan = None
|
|
2018
2156
|
if scope_plan and scope_plan["status"] in ("body_here", "absent"):
|
|
2019
2157
|
anchored = _render_symbol_scope_miss(scope_plan, path, symbol, raw_for_scope)
|
|
2158
|
+
_remember_rendered_windows(path, anchored)
|
|
2020
2159
|
tracker.record_event(
|
|
2021
2160
|
session_id=_mcp_session_id(),
|
|
2022
2161
|
event_type="SYMBOL_TEXT_ANCHOR",
|
|
@@ -3102,6 +3241,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3102
3241
|
if is_plugin_or_system_dir(cwd):
|
|
3103
3242
|
return _fallback_error("apply_edits", f"refusing to run apply_edits in system root or plugin dir '{cwd}'")
|
|
3104
3243
|
|
|
3244
|
+
# Deterministic recovery for a repeated hunk target: if the session just
|
|
3245
|
+
# read a window that contains exactly one occurrence, scope the hunk to
|
|
3246
|
+
# it instead of handing the model another round trip.
|
|
3247
|
+
edits, scope_notes = _autoscope_edits(edits, cwd)
|
|
3248
|
+
|
|
3105
3249
|
res = execute_batch_edits(
|
|
3106
3250
|
edits=edits,
|
|
3107
3251
|
best_effort=best_effort,
|
|
@@ -3137,6 +3281,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3137
3281
|
is_cr = f.get("is_create", False)
|
|
3138
3282
|
label = "created" if is_cr else f"{h_cnt} hunk(s)"
|
|
3139
3283
|
lines.append(f" - `{f.get('path')}` ({label})")
|
|
3284
|
+
for note in scope_notes:
|
|
3285
|
+
lines.append(f" ↳ {note}")
|
|
3140
3286
|
|
|
3141
3287
|
if "verify" in res:
|
|
3142
3288
|
v = res["verify"]
|
package/src/telemetry_sync.py
CHANGED
|
@@ -311,7 +311,7 @@ class TelemetrySync:
|
|
|
311
311
|
current_last_id = last_id
|
|
312
312
|
headers = {
|
|
313
313
|
"Content-Type": "application/json",
|
|
314
|
-
"User-Agent": "TokenSafe-Sync/4.7.
|
|
314
|
+
"User-Agent": "TokenSafe-Sync/4.7.5"
|
|
315
315
|
}
|
|
316
316
|
if active_key:
|
|
317
317
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.7.
|
|
20
|
+
CURRENT_VERSION = "4.7.5"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|