tokensafe 4.7.3 → 4.7.4

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.3",
2
+ "version": "4.7.4",
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
@@ -69,6 +69,13 @@ curl -fsSL https://tokensafe.dev/install.sh | bash
69
69
 
70
70
  The installer detects which agents live on your machine, registers the TokenSafe MCP server, injects project rules, and wires lifecycle hooks where the agent supports them.
71
71
 
72
+ ### Runtime requirements
73
+
74
+ - **CPython 3.10+** (3.11+ recommended). If no suitable interpreter is found, the npm launcher provisions a pinned, SHA-256-verified CPython 3.12 build into `~/.tokensafe/runtime` and installs the dependencies there, so TokenSafe works on a machine without Python. One-time download: 25 MB on macOS, 47 MB on Windows, 53-68 MB on Linux. Opt out with `TOKENSAFE_NO_DOWNLOAD=1`, force a specific interpreter with `TOKENSAFE_PYTHON=/path/to/python3`, relocate the whole tree with `TOKENSAFE_HOME`.
75
+ - **`cryptography>=42.0`** is the only required Python dependency (Ed25519 license checks, under 1 ms per validation).
76
+ - **Optional accelerators**, installed by default but not required: `tree-sitter` plus grammar wheels for AST-accurate slicing across 10 languages (without them the slicer falls back to stdlib heuristics; disable with `TOKENSAFE_TREESITTER=off`), and `Pillow` for cross-platform image downscaling (macOS falls back to `sips`).
77
+ - The managed runtime is pinned in [`bin/python-runtime.json`](bin/python-runtime.json): CPython 3.12.16 from `astral-sh/python-build-standalone`, five platform builds, every archive verified against a hardcoded SHA-256 before extraction.
78
+
72
79
  | Agent | Integration |
73
80
  |---|---|
74
81
  | **Google Antigravity** | Plugin symlink + hooks + skills + MCP (loaded automatically on startup) |
@@ -604,7 +611,7 @@ More documentation: [docs/OUMV.md](docs/OUMV.md) · [docs/AGENT_SETUP.md](docs/A
604
611
 
605
612
  ## Development and License
606
613
 
607
- The client runs on Python 3.10+ with `cryptography>=42.0` as its sole runtime dependency for Ed25519 license checks; all AST slicing, SQLite metrics, MCP tooling, and guardrails run on the standard library ([details](docs/AGENT_SETUP.md#6-runtime-dependency-cryptography)).
614
+ The client runs on CPython 3.10+ with `cryptography>=42.0` as its only *required* runtime dependency for Ed25519 license checks and fail-closed RS256 session verification. `tree-sitter` grammars and `Pillow` are optional accelerators with stdlib fallbacks, so the engine still slices, guards, and records metrics when they are absent. If no Python 3.10+ exists, the npm launcher downloads a pinned, SHA-256-verified CPython into `~/.tokensafe/runtime`; all AST slicing, SQLite metrics, MCP tooling, and guardrails run on the standard library ([details](docs/AGENT_SETUP.md#6-runtime-dependencies)).
608
615
 
609
616
  ```bash
610
617
  # Run the unit test suite (compact failure report; full: --traceback / -v)
@@ -0,0 +1,34 @@
1
+ {
2
+ "schema": 1,
3
+ "python": "3.12.16",
4
+ "release": "20261124",
5
+ "source": "astral-sh/python-build-standalone",
6
+ "base_url": "https://github.com/astral-sh/python-build-standalone/releases/download",
7
+ "targets": {
8
+ "darwin-arm64": {
9
+ "asset": "cpython-3.12.16+20261124-aarch64-apple-darwin-install_only.tar.gz",
10
+ "sha256": "431b99a9c2cdd37ad9b06e425be0e520d2dbce0552abe454257abef592fe3634",
11
+ "size": 25399370
12
+ },
13
+ "darwin-x64": {
14
+ "asset": "cpython-3.12.16+20261124-x86_64-apple-darwin-install_only.tar.gz",
15
+ "sha256": "ccce24cfd3f56f62561d2c9480fcc567ca3a9bac68450cd73e11aeb631befa1f",
16
+ "size": 25113881
17
+ },
18
+ "linux-x64": {
19
+ "asset": "cpython-3.12.16+20261124-x86_64-unknown-linux-gnu-install_only.tar.gz",
20
+ "sha256": "6774c7f49ee21c1723f7ac91961a5bf9f3ee3ae6e4d82ff58bd358958b546461",
21
+ "size": 68209387
22
+ },
23
+ "linux-arm64": {
24
+ "asset": "cpython-3.12.16+20261124-aarch64-unknown-linux-gnu-install_only.tar.gz",
25
+ "sha256": "2e6b3576f96d5b8861e4c265ea6db3d19eb24027bbd6c22f044544989444b20b",
26
+ "size": 53286223
27
+ },
28
+ "win32-x64": {
29
+ "asset": "cpython-3.12.16+20261124-x86_64-pc-windows-msvc-install_only.tar.gz",
30
+ "sha256": "8152ff5b6c6c044ddbbaa3531dda59cb9ce5bd6cb670d4c9ac2e3ab91afa8778",
31
+ "size": 47497711
32
+ }
33
+ }
34
+ }
package/bin/tokensafe.js CHANGED
@@ -9,12 +9,25 @@ const { spawn, spawnSync } = require('child_process');
9
9
  const path = require('path');
10
10
  const fs = require('fs');
11
11
  const os = require('os');
12
+ const crypto = require('crypto');
13
+ const https = require('https');
12
14
 
13
15
  const ROOT_DIR = path.resolve(__dirname, '..');
14
16
  const args = process.argv.slice(2);
15
- const VENV_DIR = path.join(os.homedir(), '.tokensafe', 'venv');
16
- const CORE_DEPS = [
17
- 'cryptography>=42.0',
17
+
18
+ const TOKENSAFE_HOME = process.env.TOKENSAFE_HOME
19
+ ? path.resolve(process.env.TOKENSAFE_HOME)
20
+ : path.join(os.homedir(), '.tokensafe');
21
+ const VENV_DIR = path.join(TOKENSAFE_HOME, 'venv');
22
+ const RUNTIME_ROOT = path.join(TOKENSAFE_HOME, 'runtime');
23
+ const MANIFEST_PATH = path.join(__dirname, 'python-runtime.json');
24
+ const MIN_PYTHON = [3, 10];
25
+
26
+ // Only `cryptography` is required: license verification imports it on every
27
+ // guarded call. tree-sitter grammars and Pillow are accelerators - the AST
28
+ // backend falls back to stdlib heuristics when they are missing.
29
+ const REQUIRED_DEPS = ['cryptography>=42.0'];
30
+ const OPTIONAL_DEPS = [
18
31
  'tree-sitter>=0.23',
19
32
  'tree-sitter-python',
20
33
  'tree-sitter-javascript',
@@ -32,75 +45,341 @@ const CORE_DEPS = [
32
45
  'Pillow>=10.0.0'
33
46
  ];
34
47
 
35
- function checkPython(cmd, requireDeps) {
36
- const probe = requireDeps
37
- ? 'import sys, cryptography, tree_sitter; assert sys.version_info >= (3, 10)'
38
- : 'import sys; assert sys.version_info >= (3, 10)';
48
+ function note(message) {
49
+ console.error(`⚡ TokenSafe: ${message}`);
50
+ }
51
+
52
+ function fail(message) {
53
+ console.error(`\n❌ ${message}\n`);
54
+ process.exit(1);
55
+ }
56
+
57
+ function loadManifest() {
58
+ try {
59
+ return JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'));
60
+ } catch (_) {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ function venvPythonPath() {
66
+ return process.platform === 'win32'
67
+ ? path.join(VENV_DIR, 'Scripts', 'python.exe')
68
+ : path.join(VENV_DIR, 'bin', 'python3');
69
+ }
70
+
71
+ /**
72
+ * Returns the interpreter's own path when it is a usable CPython >= 3.10,
73
+ * optionally requiring importable runtime dependencies. null otherwise.
74
+ */
75
+ function probePython(cmd, requireDeps) {
76
+ const imports = requireDeps ? 'import sys, cryptography' : 'import sys';
77
+ const probe = `${imports}; assert sys.version_info >= (${MIN_PYTHON[0]}, ${MIN_PYTHON[1]}); print(sys.executable)`;
78
+ try {
79
+ const res = spawnSync(cmd, ['-c', probe], { encoding: 'utf-8', stdio: 'pipe', timeout: 20000 });
80
+ if (res.status !== 0) return null;
81
+ return (res.stdout || '').trim() || cmd;
82
+ } catch (_) {
83
+ return null;
84
+ }
85
+ }
86
+
87
+ function moduleAvailable(cmd, name) {
39
88
  try {
40
- const res = spawnSync(cmd, ['-c', probe], { encoding: 'utf-8', stdio: 'pipe' });
41
- return res.status === 0;
89
+ return spawnSync(cmd, ['-c', `import ${name}`], { stdio: 'pipe', timeout: 20000 }).status === 0;
42
90
  } catch (_) {
43
91
  return false;
44
92
  }
45
93
  }
46
94
 
47
- function bootstrapDependencies(basePython) {
48
- console.error('⚡ Installing TokenSafe dependencies (cryptography & tree-sitter AST grammars)...');
49
- // 1. Try user-site pip first (respects normal user environments)
50
- const userPip = spawnSync(
51
- basePython,
52
- ['-m', 'pip', 'install', '--user', '--quiet', '--disable-pip-version-check', ...CORE_DEPS],
53
- { encoding: 'utf-8', stdio: 'pipe' }
95
+ function pipInstall(python, packages, extraArgs) {
96
+ if (!packages.length) return true;
97
+ const res = spawnSync(
98
+ python,
99
+ ['-m', 'pip', 'install', '--quiet', '--disable-pip-version-check', '--no-warn-script-location', ...(extraArgs || []), ...packages],
100
+ { encoding: 'utf-8', stdio: 'pipe', timeout: 900000 }
54
101
  );
55
- if (userPip.status === 0 && checkPython(basePython, true)) {
56
- return basePython;
102
+ return res.status === 0;
103
+ }
104
+
105
+ /**
106
+ * Installs dependencies for an interpreter that exists but lacks them.
107
+ * `isolated` targets the interpreter's own prefix (managed runtime / venv),
108
+ * otherwise pip --user keeps the system interpreter untouched.
109
+ */
110
+ function installDeps(python, isolated) {
111
+ const scope = isolated ? [] : ['--user'];
112
+ if (!pipInstall(python, REQUIRED_DEPS, scope)) {
113
+ if (!probePython(python, true)) return false;
114
+ }
115
+ if (!pipInstall(python, OPTIONAL_DEPS, scope)) {
116
+ note('optional accelerators (tree-sitter grammars, Pillow) were not installed — stdlib fallbacks stay active');
57
117
  }
118
+ return probePython(python, true) !== null;
119
+ }
58
120
 
59
- // 2. Fallback to isolated ~/.tokensafe/venv (handles PEP 668 externally-managed Python on macOS/Ubuntu)
60
- fs.mkdirSync(path.dirname(VENV_DIR), { recursive: true });
61
- const venvPy = process.platform === 'win32'
62
- ? path.join(VENV_DIR, 'Scripts', 'python.exe')
63
- : path.join(VENV_DIR, 'bin', 'python3');
121
+ function bootstrapDependencies(basePython) {
122
+ note('installing Python dependencies (cryptography, tree-sitter grammars)...');
123
+ if (installDeps(basePython, false)) return basePython;
64
124
 
125
+ // PEP 668 externally-managed environments (macOS Homebrew, modern Ubuntu)
126
+ // reject --user installs; fall back to a private venv.
127
+ fs.mkdirSync(path.dirname(VENV_DIR), { recursive: true });
128
+ const venvPy = venvPythonPath();
65
129
  if (!fs.existsSync(venvPy)) {
66
- const mk = spawnSync(basePython, ['-m', 'venv', VENV_DIR], { encoding: 'utf-8', stdio: 'pipe' });
130
+ const mk = spawnSync(basePython, ['-m', 'venv', VENV_DIR], { encoding: 'utf-8', stdio: 'pipe', timeout: 300000 });
67
131
  if (mk.status !== 0) return null;
68
132
  }
69
- const venvPip = spawnSync(
70
- venvPy,
71
- ['-m', 'pip', 'install', '--quiet', '--disable-pip-version-check', ...CORE_DEPS],
72
- { encoding: 'utf-8', stdio: 'pipe' }
73
- );
74
- if (venvPip.status === 0 && checkPython(venvPy, true)) {
75
- return venvPy;
133
+ return installDeps(venvPy, true) ? venvPy : null;
134
+ }
135
+
136
+ function platformKey() {
137
+ const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
138
+ if (!arch) return null;
139
+ if (process.platform === 'darwin') return `darwin-${arch}`;
140
+ if (process.platform === 'win32') return arch === 'x64' ? 'win32-x64' : null;
141
+ if (process.platform === 'linux') {
142
+ if (!hasGlibc()) return null; // Alpine/musl: no compatible build pinned
143
+ return arch === 'x64' ? 'linux-x64' : arch === 'arm64' ? 'linux-arm64' : null;
76
144
  }
77
145
  return null;
78
146
  }
79
147
 
80
- // Locate Python 3.10+ interpreter with required dependencies
81
- function findPython() {
82
- const venvPy = process.platform === 'win32'
83
- ? path.join(VENV_DIR, 'Scripts', 'python.exe')
84
- : path.join(VENV_DIR, 'bin', 'python3');
85
- const candidates = [venvPy, 'python3', 'python'];
148
+ function hasGlibc() {
149
+ try {
150
+ const report = process.report && process.report.getReport ? process.report.getReport() : null;
151
+ if (report && report.header) return Boolean(report.header.glibcVersionRuntime);
152
+ } catch (_) {
153
+ /* fall through */
154
+ }
155
+ try {
156
+ return fs.existsSync('/lib/ld-linux-x86-64.so.2') || fs.existsSync('/lib/ld-linux-aarch64.so.1');
157
+ } catch (_) {
158
+ return false;
159
+ }
160
+ }
86
161
 
87
- for (const cmd of candidates) {
88
- if (cmd === venvPy && !fs.existsSync(venvPy)) continue;
89
- if (checkPython(cmd, true)) return cmd;
162
+ const RUNTIME_PYTHON_LAYOUT = [
163
+ ['python', 'bin', 'python3'],
164
+ ['python', 'bin', 'python'],
165
+ ['python', 'python.exe'],
166
+ ['bin', 'python3'],
167
+ ['python3']
168
+ ];
169
+
170
+ /** Removes runtime directories this launcher created for an older pin. */
171
+ function pruneStaleRuntimes(keepDir) {
172
+ try {
173
+ for (const entry of fs.readdirSync(RUNTIME_ROOT)) {
174
+ const candidate = path.join(RUNTIME_ROOT, entry);
175
+ if (candidate === keepDir) continue;
176
+ if (!fs.existsSync(path.join(candidate, '.complete'))) continue;
177
+ if (fs.statSync(candidate).isDirectory()) fs.rmSync(candidate, { recursive: true, force: true });
178
+ }
179
+ } catch (_) {
180
+ /* best effort */
181
+ }
182
+ }
183
+
184
+ function findRuntimePython(dir) {
185
+ for (const parts of RUNTIME_PYTHON_LAYOUT) {
186
+ const candidate = path.join(dir, ...parts);
187
+ if (fs.existsSync(candidate)) return candidate;
188
+ }
189
+ return null;
190
+ }
191
+
192
+ function sha256File(file) {
193
+ return new Promise((resolve, reject) => {
194
+ const hash = crypto.createHash('sha256');
195
+ const stream = fs.createReadStream(file);
196
+ stream.on('error', reject);
197
+ stream.on('data', (chunk) => hash.update(chunk));
198
+ stream.on('end', () => resolve(hash.digest('hex')));
199
+ });
200
+ }
201
+
202
+ function download(url, dest, expectedSize, redirects) {
203
+ const hops = redirects || 0;
204
+ return new Promise((resolve, reject) => {
205
+ const request = https.get(url, { headers: { 'user-agent': 'tokensafe-launcher' }, timeout: 120000 }, (res) => {
206
+ if ([301, 302, 303, 307, 308].includes(res.statusCode)) {
207
+ res.resume();
208
+ if (hops >= 6 || !res.headers.location) return reject(new Error('too many redirects'));
209
+ return download(res.headers.location, dest, expectedSize, hops + 1).then(resolve, reject);
210
+ }
211
+ if (res.statusCode !== 200) {
212
+ res.resume();
213
+ return reject(new Error(`HTTP ${res.statusCode} for ${url}`));
214
+ }
215
+
216
+ const total = Number(res.headers['content-length'] || expectedSize || 0);
217
+ let received = 0;
218
+ let lastReported = -1;
219
+ const out = fs.createWriteStream(dest);
220
+
221
+ res.on('data', (chunk) => {
222
+ received += chunk.length;
223
+ if (total > 0 && process.stderr.isTTY) {
224
+ const pct = Math.floor((received / total) * 100);
225
+ if (pct >= lastReported + 10) {
226
+ lastReported = pct;
227
+ const mb = (n) => Math.round(n / 1048576);
228
+ process.stderr.write(`\r⚡ TokenSafe: downloading managed CPython... ${pct}% (${mb(received)}/${mb(total)} MB)`);
229
+ }
230
+ }
231
+ });
232
+ res.pipe(out);
233
+ res.on('error', reject);
234
+ out.on('error', reject);
235
+ out.on('finish', () => {
236
+ if (process.stderr.isTTY && total > 0) process.stderr.write('\r\x1b[K');
237
+ resolve(received);
238
+ });
239
+ });
240
+ request.on('timeout', () => request.destroy(new Error('download timed out')));
241
+ request.on('error', reject);
242
+ });
243
+ }
244
+
245
+ function extractArchive(archive, destDir) {
246
+ fs.mkdirSync(destDir, { recursive: true });
247
+ const res = spawnSync('tar', ['-xzf', archive, '-C', destDir], { encoding: 'utf-8', stdio: 'pipe', timeout: 600000 });
248
+ if (res.status !== 0) {
249
+ const detail = ((res.stderr || '') || (res.error && res.error.message) || '').trim();
250
+ throw new Error(`failed to extract the runtime archive${detail ? `: ${detail}` : ''}`);
251
+ }
252
+ }
253
+
254
+ async function provisionManagedRuntime(manifest, target, dir) {
255
+ fs.mkdirSync(RUNTIME_ROOT, { recursive: true });
256
+ const url = `${manifest.base_url}/${manifest.release}/${encodeURIComponent(target.asset)}`;
257
+ const archive = path.join(RUNTIME_ROOT, `.${target.asset}.part`);
258
+
259
+ note(`no Python 3.10+ found — provisioning managed CPython ${manifest.python} (~${Math.round((target.size || 0) / 1048576)} MB, one time)`);
260
+
261
+ try {
262
+ const received = await download(url, archive, target.size);
263
+ if (target.size && received !== target.size) {
264
+ throw new Error(`truncated download (${received} of ${target.size} bytes)`);
265
+ }
266
+ const digest = await sha256File(archive);
267
+ if (digest.toLowerCase() !== target.sha256.toLowerCase()) {
268
+ throw new Error(`SHA-256 mismatch for ${target.asset} (got ${digest}, expected ${target.sha256})`);
269
+ }
270
+
271
+ if (fs.existsSync(dir) && dir.startsWith(RUNTIME_ROOT + path.sep)) {
272
+ fs.rmSync(dir, { recursive: true, force: true });
273
+ }
274
+ extractArchive(archive, dir);
275
+ fs.writeFileSync(path.join(dir, '.complete'), `${target.sha256}\n${target.asset}\n`);
276
+
277
+ const python = findRuntimePython(dir);
278
+ if (!python) throw new Error('runtime archive did not contain a python interpreter');
279
+
280
+ if (!probePython(python, false)) {
281
+ throw new Error(`the downloaded interpreter does not run on this system (${platformKey()})`);
282
+ }
283
+
284
+ if (!probePython(python, true) && !installDeps(python, true)) {
285
+ throw new Error('could not install cryptography into the managed runtime');
286
+ }
287
+
288
+ const grammars = moduleAvailable(python, 'tree_sitter')
289
+ ? 'with tree-sitter grammars'
290
+ : 'stdlib fallbacks only (tree-sitter unavailable)';
291
+ pruneStaleRuntimes(dir);
292
+ note(`managed CPython ${manifest.python} ready at ${python} — ${grammars}`);
293
+ return python;
294
+ } finally {
295
+ try {
296
+ if (fs.existsSync(archive)) fs.unlinkSync(archive);
297
+ } catch (_) {
298
+ /* best effort */
299
+ }
90
300
  }
301
+ }
302
+
303
+ async function ensureManagedRuntime() {
304
+ const manifest = loadManifest();
305
+ if (!manifest) return null;
91
306
 
307
+ const key = platformKey();
308
+ const target = key && manifest.targets ? manifest.targets[key] : null;
309
+ if (!target) {
310
+ note(`no pinned CPython build for ${process.platform}-${process.arch}`);
311
+ return null;
312
+ }
313
+
314
+ const dir = path.join(RUNTIME_ROOT, `${manifest.python}-${manifest.release}`);
315
+ const marker = path.join(dir, '.complete');
316
+ const existing = findRuntimePython(dir);
317
+ if (existing && fs.existsSync(marker)) {
318
+ let markerOk = false;
319
+ try {
320
+ markerOk = fs.readFileSync(marker, 'utf8').trim().split('\n')[0].toLowerCase() === target.sha256.toLowerCase();
321
+ } catch (_) {
322
+ markerOk = false;
323
+ }
324
+ if (markerOk && probePython(existing, false)) {
325
+ if (!probePython(existing, true) && !installDeps(existing, true)) return null;
326
+ return existing;
327
+ }
328
+ }
329
+
330
+ if (String(process.env.TOKENSAFE_NO_DOWNLOAD || '').trim() === '1') {
331
+ note('TOKENSAFE_NO_DOWNLOAD=1 — skipping the managed CPython download');
332
+ return null;
333
+ }
334
+
335
+ try {
336
+ return await provisionManagedRuntime(manifest, target, dir);
337
+ } catch (err) {
338
+ note(`managed runtime provisioning failed: ${err.message}`);
339
+ return null;
340
+ }
341
+ }
342
+
343
+ function printInstallGuidance() {
344
+ console.error('\n❌ TokenSafe requires CPython 3.10+ and no managed runtime could be provisioned.');
345
+ console.error('Install Python once, then re-run `tokensafe`:');
346
+ console.error(' macOS: brew install python3');
347
+ console.error(' Debian/Ubuntu: sudo apt-get install python3 python3-venv');
348
+ console.error(' Fedora: sudo dnf install python3');
349
+ console.error(' Windows: winget install Python.Python.3.12');
350
+ console.error(' Any platform: https://www.python.org/downloads/\n');
351
+ console.error('Or point TokenSafe at an existing interpreter:');
352
+ console.error(' TOKENSAFE_PYTHON=/path/to/python3 tokensafe\n');
353
+ console.error('Managed runtime downloads can be disabled: TOKENSAFE_NO_DOWNLOAD=1\n');
354
+ }
355
+
356
+ async function findPython() {
357
+ const pinned = (process.env.TOKENSAFE_PYTHON || '').trim();
358
+ if (pinned) {
359
+ if (probePython(pinned, true)) return pinned;
360
+ if (probePython(pinned, false)) {
361
+ const bootstrapped = bootstrapDependencies(pinned);
362
+ if (bootstrapped) return bootstrapped;
363
+ }
364
+ fail(`TOKENSAFE_PYTHON=${pinned} is not a usable CPython ${MIN_PYTHON[0]}.${MIN_PYTHON[1]}+ with 'cryptography'.`);
365
+ }
366
+
367
+ const candidates = [];
368
+ const venvPy = venvPythonPath();
369
+ if (fs.existsSync(venvPy)) candidates.push(venvPy);
370
+ candidates.push('python3', 'python');
371
+
372
+ for (const cmd of candidates) {
373
+ if (probePython(cmd, true)) return cmd;
374
+ }
92
375
  for (const cmd of candidates) {
93
- if (cmd === venvPy && !fs.existsSync(venvPy)) continue;
94
- if (checkPython(cmd, false)) {
376
+ if (probePython(cmd, false)) {
95
377
  const bootstrapped = bootstrapDependencies(cmd);
96
378
  if (bootstrapped) return bootstrapped;
97
- console.error("\n❌ TokenSafe requires Python 3.10+ and 'cryptography>=42.0'.");
98
- console.error("Install dependencies manually via:");
99
- console.error(" pip install 'cryptography>=42.0' 'tree-sitter>=0.23' 'tree-sitter-python'\n");
100
- process.exit(1);
101
379
  }
102
380
  }
103
- return null;
381
+
382
+ return await ensureManagedRuntime();
104
383
  }
105
384
 
106
385
  const firstArg = args[0] || '';
@@ -145,16 +424,14 @@ Commands:
145
424
  process.exit(0);
146
425
  }
147
426
 
148
- const python = findPython();
149
- if (!python) {
150
- console.error('\n❌ TokenSafe requires Python 3.10+ installed on your system.');
151
- console.error('Please install Python from https://python.org or via your package manager:');
152
- console.error(' macOS: brew install python3');
153
- console.error(' Debian: sudo apt-get install python3\n');
154
- process.exit(1);
155
- }
427
+ async function main() {
428
+ const python = await findPython();
429
+ if (!python) {
430
+ printInstallGuidance();
431
+ process.exit(1);
432
+ }
156
433
 
157
- const candidateTokensafe = path.join(ROOT_DIR, 'bin', 'tokensafe');
434
+ const candidateTokensafe = path.join(ROOT_DIR, 'bin', 'tokensafe');
158
435
  const candidateAgy = path.join(ROOT_DIR, 'bin', 'agy-tokens');
159
436
  const scriptPath = fs.existsSync(candidateTokensafe) ? candidateTokensafe : candidateAgy;
160
437
  if (!fs.existsSync(scriptPath)) {
@@ -178,10 +455,33 @@ child.on('error', (err) => {
178
455
  process.exit(1);
179
456
  });
180
457
 
181
- child.on('exit', (code, signal) => {
182
- if (signal) {
183
- process.kill(process.pid, signal);
184
- } else {
185
- process.exit(code || 0);
186
- }
187
- });
458
+ child.on('exit', (code, signal) => {
459
+ if (signal) {
460
+ process.kill(process.pid, signal);
461
+ } else {
462
+ process.exit(code || 0);
463
+ }
464
+ });
465
+ }
466
+
467
+ if (require.main === module) {
468
+ main().catch((err) => {
469
+ console.error(`TokenSafe: ${err && err.message ? err.message : err}`);
470
+ process.exit(1);
471
+ });
472
+ } else {
473
+ module.exports = {
474
+ TOKENSAFE_HOME,
475
+ RUNTIME_ROOT,
476
+ REQUIRED_DEPS,
477
+ OPTIONAL_DEPS,
478
+ loadManifest,
479
+ platformKey,
480
+ probePython,
481
+ findRuntimePython,
482
+ sha256File,
483
+ installDeps,
484
+ ensureManagedRuntime,
485
+ findPython
486
+ };
487
+ }
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.3",
3
+ "version": "4.7.4",
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.3",
4
+ "version": "4.7.4",
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": {
@@ -11,6 +11,7 @@
11
11
  "bin/tokensafe.js",
12
12
  "bin/tokensafe",
13
13
  "bin/agy-tokens",
14
+ "bin/python-runtime.json",
14
15
  "src/",
15
16
  "!src/cloud_backend.py",
16
17
  "!src/mailer.py",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.7.3",
4
+ "version": "4.7.4",
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.3",
6
+ "version": "4.7.4",
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.3",
26
+ "version": "4.7.4",
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.3",
42
+ "version": "4.7.4",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -13,6 +13,7 @@ from __future__ import annotations
13
13
 
14
14
  import json
15
15
  import os
16
+ import time
16
17
  import urllib.error
17
18
  import urllib.request
18
19
  from dataclasses import dataclass, field
@@ -83,17 +84,21 @@ class BudgetExceeded(RuntimeError):
83
84
 
84
85
 
85
86
  class DeepSeekClient:
87
+ _RETRY_STATUS = frozenset({408, 429, 500, 502, 503, 504})
88
+
86
89
  def __init__(
87
90
  self,
88
91
  model: str = "deepseek-chat",
89
92
  temperature: float = 0.0,
90
93
  base_url: Optional[str] = None,
91
- timeout: float = 120.0,
94
+ timeout: float = 300.0,
95
+ retries: int = 4,
92
96
  ):
93
97
  self.model = model
94
98
  self.temperature = temperature
95
99
  self.base_url = (base_url or os.environ.get("DEEPSEEK_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
96
100
  self.timeout = timeout
101
+ self.retries = max(1, int(retries))
97
102
  self.api_key = resolve_api_key()
98
103
  if not self.api_key:
99
104
  raise RuntimeError(
@@ -101,6 +106,11 @@ class DeepSeekClient:
101
106
  "into ~/.tokensafe/data/config.json"
102
107
  )
103
108
 
109
+ @staticmethod
110
+ def _backoff(attempt: int) -> float:
111
+ # 5s, 15s, 30s: a paid matrix must survive a flaky read, not restart.
112
+ return min(30.0, 5.0 * (3 ** (attempt - 1)))
113
+
104
114
  def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
105
115
  body: Dict[str, Any] = {
106
116
  "model": self.model,
@@ -110,18 +120,35 @@ class DeepSeekClient:
110
120
  if tools:
111
121
  body["tools"] = tools
112
122
  body["tool_choice"] = "auto"
113
- req = urllib.request.Request(
114
- f"{self.base_url}/chat/completions",
115
- data=json.dumps(body).encode(),
116
- headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"},
117
- method="POST",
118
- )
119
- try:
120
- with urllib.request.urlopen(req, timeout=self.timeout) as resp:
121
- payload = json.loads(resp.read().decode())
122
- except urllib.error.HTTPError as exc:
123
- raise RuntimeError(f"provider HTTP {exc.code}: {exc.read().decode()[:300]}") from exc
124
- return payload["choices"][0]["message"], payload.get("usage") or {}
123
+ data = json.dumps(body).encode()
124
+ last_error = ""
125
+ for attempt in range(1, self.retries + 1):
126
+ req = urllib.request.Request(
127
+ f"{self.base_url}/chat/completions",
128
+ data=data,
129
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"},
130
+ method="POST",
131
+ )
132
+ try:
133
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
134
+ payload = json.loads(resp.read().decode())
135
+ return payload["choices"][0]["message"], payload.get("usage") or {}
136
+ except urllib.error.HTTPError as exc:
137
+ last_error = f"provider HTTP {exc.code}: {exc.read().decode()[:300]}"
138
+ if exc.code not in self._RETRY_STATUS or attempt == self.retries:
139
+ raise RuntimeError(last_error) from exc
140
+ except (TimeoutError, urllib.error.URLError, ConnectionResetError, json.JSONDecodeError) as exc:
141
+ # A long generation can outlive the socket read, and a truncated body is
142
+ # not valid JSON. Both are transient and must not kill a paid matrix
143
+ # mid-run: the first v5 attempt died after ~$0.14 with 45 sessions
144
+ # collected and nothing written.
145
+ last_error = f"{type(exc).__name__}: {exc}"
146
+ if attempt == self.retries:
147
+ raise RuntimeError(
148
+ f"provider call failed after {self.retries} attempts — {last_error}"
149
+ ) from exc
150
+ time.sleep(self._backoff(attempt))
151
+ raise RuntimeError(f"provider call failed — {last_error}")
125
152
 
126
153
 
127
154
  ToolFn = Callable[..., Any]
@@ -75,11 +75,54 @@ def _run(cmd: List[str], cwd: Path, timeout: float = 240.0, env: Optional[Dict[s
75
75
  return subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True, timeout=timeout, env=env)
76
76
 
77
77
 
78
+ _FILLER_VERBS = ("List", "Create", "Pay", "Ship", "Cancel", "Get", "Update", "Delete")
79
+ _FILLER_NOUNS = ("Products", "Orders", "Carts", "Invoices", "Users", "Coupons")
80
+
81
+
82
+ def _generate_filler(root: Path, count: int) -> None:
83
+ """`count` generated service files so discovery competes with a real tree.
84
+
85
+ The oracle and the broken handler are untouched: only the amount of code a
86
+ workspace search or a read has to get through grows, which is the variable
87
+ matrix v4 could not measure on 69 files. Generated at copy time, never
88
+ committed — the product repo stays clean and the target is reproducible from
89
+ `--files N` alone.
90
+ """
91
+ pkg = root / "benchmark" / "sandboxes" / "gen"
92
+ pkg.mkdir(parents=True, exist_ok=True)
93
+ for idx in range(count):
94
+ noun = _FILLER_NOUNS[idx % len(_FILLER_NOUNS)]
95
+ verb = _FILLER_VERBS[(idx // len(_FILLER_NOUNS)) % len(_FILLER_VERBS)]
96
+ name = f"Svc{idx:03d}"
97
+ route = f"/api/{noun.lower()}"
98
+ (pkg / f"svc{idx:03d}.go").write_text(
99
+ f'''package gen
100
+
101
+ // Generated benchmark fixture — an unrelated service that mirrors the
102
+ // {noun.lower()} API surface ({verb}{noun} -> {route}) and mentions
103
+ // StatusCreated / StatusConflict / CONFLICT: so a status-code search has to
104
+ // distinguish a placeholder from the real handler.
105
+
106
+ import "net/http"
107
+
108
+ // {name} is not mounted anywhere; it exists so discovery has real competition.
109
+ type {name} struct{{}}
110
+
111
+ // {verb}{noun} is a placeholder for {route}.
112
+ func (h {name}) {verb}{noun}(w http.ResponseWriter, r *http.Request) {{
113
+ \tw.WriteHeader(http.StatusOK)
114
+ }}
115
+ ''',
116
+ encoding="utf-8",
117
+ )
118
+
119
+
78
120
  class GoWorkspace:
79
- def __init__(self, task_id: str):
121
+ def __init__(self, task_id: str, files: int = 0):
80
122
  if task_id not in TASKS:
81
123
  raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
82
124
  self.task_id = task_id
125
+ self.files = int(files or 0)
83
126
  self.dir = Path(tempfile.mkdtemp(prefix=f"oumv-bench-{task_id}-")) / "go"
84
127
  self.dir.mkdir(parents=True)
85
128
  for item in COPY_ITEMS:
@@ -89,6 +132,8 @@ class GoWorkspace:
89
132
  shutil.copytree(src, dst)
90
133
  else:
91
134
  shutil.copy2(src, dst)
135
+ if self.files:
136
+ _generate_filler(self.dir, self.files)
92
137
  # The runtime must serve the *workspace* code: build the helper inside the
93
138
  # copied module and rebuild it when an edit changes the sources, otherwise
94
139
  # oumv/verify would keep reporting the pristine app's behaviour.
@@ -471,18 +516,33 @@ OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
471
516
  "name": "oumv_applyEdit",
472
517
  "description": (
473
518
  "OUMV guarded edit: applies only if `expectedVersion` matches the file on disk. "
474
- "mode='symbol' replaces one declaration (cheaper than the whole file)."
519
+ "mode='patch' splices hunks (cheapest — the file is never re-sent); mode='symbol' "
520
+ "replaces one declaration; mode='replace' rewrites the whole file."
475
521
  ),
476
522
  "parameters": {
477
523
  "type": "object",
478
524
  "properties": {
479
525
  "path": {"type": "string"},
480
- "replacement": {"type": "string", "description": "New file content, or the new declaration body for mode='symbol'"},
481
- "expectedVersion": {"type": "string", "description": "sha256 version from oumv_getSource"},
482
- "mode": {"type": "string", "enum": ["replace", "symbol"]},
526
+ "expectedVersion": {"type": "string", "description": "version from oumv_observe L3 or oumv_getSource"},
527
+ "mode": {"type": "string", "enum": ["patch", "symbol", "replace"]},
528
+ "hunks": {
529
+ "type": "array",
530
+ "description": "mode='patch': exact snippets to splice, applied in order",
531
+ "items": {
532
+ "type": "object",
533
+ "properties": {
534
+ "target": {"type": "string", "description": "Exact snippet from the source"},
535
+ "replacement": {"type": "string", "description": "Replacement snippet"},
536
+ "startLine": {"type": "integer"},
537
+ "endLine": {"type": "integer"},
538
+ },
539
+ "required": ["target", "replacement"],
540
+ },
541
+ },
542
+ "replacement": {"type": "string", "description": "New content, or the new declaration body for mode='symbol'"},
483
543
  "symbol": {"type": "string", "description": "Declaration to replace when mode='symbol'"},
484
544
  },
485
- "required": ["path", "replacement", "expectedVersion"],
545
+ "required": ["path", "expectedVersion"],
486
546
  },
487
547
  },
488
548
  },
@@ -587,14 +647,15 @@ def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
587
647
  tools.update({
588
648
  "oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
589
649
  "oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
590
- "oumv_applyEdit": lambda path, replacement, expectedVersion, mode="", symbol="": ws.oumv(
650
+ "oumv_applyEdit": lambda path, expectedVersion, mode="", replacement="", symbol="", hunks=None: ws.oumv(
591
651
  "oumv/applyEdit",
592
652
  {
593
653
  "path": path,
594
- "replacement": replacement,
595
654
  "expectedVersion": expectedVersion,
596
655
  **({"mode": mode} if mode else {}),
656
+ **({"replacement": replacement} if replacement else {}),
597
657
  **({"symbol": symbol} if symbol else {}),
658
+ **({"hunks": hunks} if hunks else {}),
598
659
  },
599
660
  ),
600
661
  "oumv_verify": lambda target, payload=None: ws.oumv(
@@ -630,12 +691,15 @@ SYSTEM_OUMV = (
630
691
  "You are a senior Go engineer working in a small Go module that exposes the OUMV runtime. "
631
692
  "The bug report includes a repro; use it to go straight to the right handler instead of guessing payloads. "
632
693
  "Use this loop and stop as soon as the oracle passes: (1) oumv_observe L3 with the failing endpoint target "
633
- "(e.g. \"POST /api/products\") — it returns the handler body, its workspace path and the sha256 OCC version; "
634
- "(2) oumv_getSource for that path once to get the full file bytes; (3) oumv_applyEdit with the fixed file and "
635
- "the version from step 1 or 2 (it rejects a stale version); (4) confirm with oumv_verify when the repro is a "
636
- "single request. When the failure needs state created by earlier requests, run the oracle with run_command "
637
- "instead — oumv_verify intentionally starts a fresh app per call. Do not call list_files/read_file unless an "
638
- "OUMV tool returns an error. Tests are read-only."
694
+ "(e.g. \"POST /api/products\") — ONE call returns the handler source, its workspace path, startLine/endLine and "
695
+ "the sha256 OCC version; (2) oumv_applyEdit with that path + expectedVersion and mode=\"patch\", "
696
+ "hunks=[{target: the exact line(s) you change, replacement: the fix, startLine: the line number from step 1, "
697
+ "endLine: the same line}] — scoping the hunk keeps it unique when the snippet appears elsewhere in the file; "
698
+ "the file is never re-sent and the edit is rejected on a "
699
+ "stale version; (3) if the result is an error, read the reported reason and repeat (2); (4) run_command to run "
700
+ "the oracle (oumv_verify starts a fresh app per call, so use it only for a single stateless request). "
701
+ "Do not fetch whole files with getSource and do not use write_file: the patch IS the edit. Do not call "
702
+ "list_files/read_file unless an OUMV tool returns an error. Tests are read-only."
639
703
  )
640
704
 
641
705
 
@@ -18,8 +18,9 @@ def run_one(
18
18
  model: str = "deepseek-chat",
19
19
  max_steps: int = 14,
20
20
  budget_usd: float = 1.0,
21
+ files: int = 0,
21
22
  ) -> Dict[str, Any]:
22
- ws = go_target.GoWorkspace(task_id)
23
+ ws = go_target.GoWorkspace(task_id, files=files)
23
24
  started = time.time()
24
25
  try:
25
26
  before = ws.oracle()
@@ -62,6 +63,58 @@ def run_one(
62
63
  ws.cleanup()
63
64
 
64
65
 
66
+ def _matrix_report(
67
+ tasks: List[str],
68
+ arms: List[str],
69
+ runs: int,
70
+ model: str,
71
+ budget_usd: float,
72
+ files: int,
73
+ results: List[Dict[str, Any]],
74
+ spent: float,
75
+ aborted: Optional[str],
76
+ ) -> Dict[str, Any]:
77
+ return {
78
+ "target": "go",
79
+ "sandbox_files": files,
80
+ "tasks": tasks,
81
+ "arms": arms,
82
+ "runs": runs,
83
+ "model": model,
84
+ "budget_usd": budget_usd,
85
+ "spent_usd": round(spent, 6),
86
+ "aborted": aborted,
87
+ "results": results,
88
+ "provenance": _provenance("go", tasks, arms),
89
+ "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
90
+ }
91
+
92
+
93
+ def checkpoint_path(files: int = 0) -> Path:
94
+ from src.paths import resolve_data_dir
95
+
96
+ label = f"go-{files}f" if files else "go"
97
+ return Path(resolve_data_dir()) / "bench" / f"{label}-checkpoint.json"
98
+
99
+
100
+ def _write_checkpoint(files: int, report: Dict[str, Any]) -> None:
101
+ """Persist every finished session immediately.
102
+
103
+ The first v5 attempt spent ~$0.14 and lost all 45 rows to a socket timeout in
104
+ the last provider call, because the artifact was only written once at the end.
105
+ A checkpoint per row costs nothing and makes a crash resumable by reading the
106
+ finished rows instead of paying for them twice.
107
+ """
108
+ path = checkpoint_path(files)
109
+ try:
110
+ path.parent.mkdir(parents=True, exist_ok=True)
111
+ tmp = path.with_suffix(".tmp")
112
+ tmp.write_text(json.dumps({**report, "partial": True}, indent=2, ensure_ascii=False), encoding="utf-8")
113
+ tmp.replace(path)
114
+ except OSError:
115
+ pass
116
+
117
+
65
118
  def run_matrix(
66
119
  tasks: List[str],
67
120
  arms: List[str],
@@ -69,6 +122,7 @@ def run_matrix(
69
122
  model: str = "deepseek-chat",
70
123
  max_steps: int = 14,
71
124
  budget_usd: float = 1.0,
125
+ files: int = 0,
72
126
  ) -> Dict[str, Any]:
73
127
  results: List[Dict[str, Any]] = []
74
128
  spent = 0.0
@@ -80,27 +134,18 @@ def run_matrix(
80
134
  aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
81
135
  break
82
136
  per_run_budget = max(budget_usd - spent, 0.01)
83
- row = run_one(arm, task_id, model=model, max_steps=max_steps, budget_usd=per_run_budget)
137
+ row = run_one(arm, task_id, model=model, max_steps=max_steps,
138
+ budget_usd=per_run_budget, files=files)
84
139
  row["run"] = run_idx
85
140
  results.append(row)
86
141
  spent += float((row.get("usage") or {}).get("usd") or 0.0)
142
+ _write_checkpoint(files, _matrix_report(tasks, arms, runs, model, budget_usd, files,
143
+ results, spent, aborted))
87
144
  if aborted:
88
145
  break
89
146
  if aborted:
90
147
  break
91
- return {
92
- "target": "go",
93
- "tasks": tasks,
94
- "arms": arms,
95
- "runs": runs,
96
- "model": model,
97
- "budget_usd": budget_usd,
98
- "spent_usd": round(spent, 6),
99
- "aborted": aborted,
100
- "results": results,
101
- "provenance": _provenance("go", tasks, arms),
102
- "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
103
- }
148
+ return _matrix_report(tasks, arms, runs, model, budget_usd, files, results, spent, aborted)
104
149
 
105
150
 
106
151
 
@@ -260,6 +305,12 @@ def render_markdown(report: Dict[str, Any]) -> str:
260
305
  else "the real 12-assertion oracle (`go test ./benchmark -run TestGroundTruthOracleVanilla`)"
261
306
  )
262
307
  sandbox = "the `agent-dom` React benchmark sandbox" if target == "react" else "the `tokensafe-backend/go` module"
308
+ files = int(report.get("sandbox_files") or 0)
309
+ sandbox_line = (
310
+ f"- Each arm starts from a throwaway copy of {sandbox} with one deliberate regression"
311
+ + (f", plus {files} generated service files so discovery competes with a realistic tree" if files else "")
312
+ + "."
313
+ )
263
314
  lines = [
264
315
  f"# OUMV benchmark — {target} sandbox (measured)",
265
316
  "",
@@ -268,10 +319,12 @@ def render_markdown(report: Dict[str, Any]) -> str:
268
319
  "",
269
320
  "## Methodology",
270
321
  "",
271
- f"- Each arm starts from a throwaway copy of {sandbox} with one deliberate regression.",
322
+ sandbox_line,
272
323
  f"- Correctness is {oracle}, re-run after every agent step.",
273
324
  "- Token and cost numbers come from the provider `usage` payload; prices are a pinned snapshot printed in the JSON artifact.",
274
- "- `baseline` uses file/command tools only; `oumv` gets the same tools plus observe/getSource/applyEdit/understand served by the shipped OUMV adapter.",
325
+ "- `baseline` uses file/command tools only; `tokensafe` adds the shipped MCP tools (`smart_read_file` with "
326
+ "`endpoint=`, `scoped_search`, `apply_edits` with inline verify); `oumv` adds observe L3 (endpoint → handler "
327
+ "source + version) and `applyEdit` `mode=patch` (hunks) served by the shipped OUMV adapter.",
275
328
  "",
276
329
  "## Results",
277
330
  "",
@@ -324,8 +377,15 @@ def write_artifacts(report: Dict[str, Any], out_dir: Optional[Path] = None) -> D
324
377
  base.mkdir(parents=True, exist_ok=True)
325
378
  stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
326
379
  target = report.get("target", "go")
327
- json_path = base / f"{target}-{stamp}.json"
328
- md_path = base / f"{target}-{stamp}.md"
380
+ files = int(report.get("sandbox_files") or 0)
381
+ label = f"{target}-{files}f" if files else target
382
+ json_path = base / f"{label}-{stamp}.json"
383
+ md_path = base / f"{label}-{stamp}.md"
329
384
  json_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
330
385
  md_path.write_text(render_markdown(report), encoding="utf-8")
386
+ # The final artifact supersedes the per-row checkpoint.
387
+ try:
388
+ checkpoint_path(files).unlink()
389
+ except OSError:
390
+ pass
331
391
  return {"json": str(json_path), "markdown": str(md_path)}
package/src/cli.py CHANGED
@@ -952,21 +952,25 @@ def main(argv: Optional[List[str]] = None):
952
952
  budget = float(_flag("--budget", "1.0"))
953
953
  model = _flag("--model", "deepseek-chat")
954
954
  max_steps = int(_flag("--max-steps", "14"))
955
+ files = int(_flag("--files", "0"))
955
956
 
956
957
  if "--dry-run" in args:
957
958
  from src.bench.driver import PRICES
958
959
 
959
960
  sessions = len(task_ids) * len(arms) * runs
960
- print(f"\n dry run: {target} · tasks={task_ids} · arms={arms} · runs={runs} → {sessions} sessions")
961
+ print(f"\n dry run: {target} · tasks={task_ids} · arms={arms} · runs={runs} → {sessions} sessions"
962
+ + (f" · sandbox_files={files} (generated)" if files and target == "go" else ""))
961
963
  print(f" model={model} prices={PRICES.get(model)} budget=${budget}")
962
964
  print(" no provider call was made\n")
963
965
  return
964
966
 
965
- print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}\n")
967
+ print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}"
968
+ + (f" sandbox_files={files}" if files and target == "go" else "") + "\n")
966
969
  if target == "react":
967
970
  report = run_react_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
968
971
  else:
969
- report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
972
+ report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget,
973
+ files=files)
970
974
  paths = write_artifacts(report)
971
975
  if "--json" in args:
972
976
  import json as _json
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.3"
47
+ "version": "4.7.4"
48
48
  }
49
49
 
50
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -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.3"
314
+ "User-Agent": "TokenSafe-Sync/4.7.4"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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.3"
20
+ CURRENT_VERSION = "4.7.4"
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