tokensafe 4.7.2 → 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.2",
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) |
@@ -472,7 +479,7 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
472
479
  |---|---|
473
480
  | `get_architecture_graph` | Architectural hotspots, dependency topology, and God Nodes detection before multi-file reading (persisted in SQLite cache) |
474
481
  | `get_api_surface` | Compact markdown map of all exported interfaces, classes, and types |
475
- | `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; OpenAPI/Prisma/GraphQL/SQL auto-slice; lockfiles/CSV/TSV/SQL dump auto-reduction with reversible stash |
482
+ | `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; `endpoint="POST /api/x"` resolves route → handler body + path + line range + whole-file version in one call; OpenAPI/Prisma/GraphQL/SQL auto-slice; lockfiles/CSV/TSV/SQL dump auto-reduction with reversible stash |
476
483
  | `smart_bundle` | 3–8 related symbols across files in one call: merged skeletons, deduplicated shared imports, unified 1-hop signatures |
477
484
  | `scoped_search` | Sub-millisecond keyword and symbol search powered by native SQLite FTS5 trigram index with BM25 relevance ranking (<1ms) |
478
485
  | `expand_ref` | Reversible stash expansion: recovers original un-truncated content by its 8-char hex hash anchor (`#a1b2c3d4`) without re-running tools |
@@ -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.2",
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.2",
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.2",
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.2",
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.2",
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.2",
42
+ "version": "4.7.4",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -25,6 +25,9 @@ class AgentFirewall:
25
25
  _PRUNE_INTERVAL = 3600.0 # amortized hourly prune of the persistent layer
26
26
  _PRUNE_KEEP = 500
27
27
  _last_prune = 0.0
28
+ # Render revision for cached symbol slices (see _cache_symbol): bump when the
29
+ # shape of a slice changes, so unchanged bytes do not serve the old shape.
30
+ _SLICE_REVISION = "r3"
28
31
  # Content this process has actually delivered. The cache is keyed by session_id,
29
32
  # and host session ids like "mcp:<client>" outlive one process — so a DB hit alone
30
33
  # does not mean the caller already has the bytes in context, and saying "reused
@@ -61,6 +64,19 @@ class AgentFirewall:
61
64
  conn.execute("CREATE INDEX IF NOT EXISTS idx_subagent_hash ON subagent_file_cache(file_path, symbol, content_hash);")
62
65
  cls._INITIALIZED_DBS.add(tracker.db_path)
63
66
 
67
+ @staticmethod
68
+ def _cache_symbol(symbol: str) -> str:
69
+ """Namespace the cached slice by its render revision.
70
+
71
+ The cache is content-addressed by file bytes, which says nothing about
72
+ the *shape* of the answer: changing how a symbol slice is rendered (the
73
+ v1.3 headers, inlined cross-file declarations) must not serve the old
74
+ shape for unchanged bytes. Bump the revision instead of truncating the
75
+ table, so whole-file skeleton entries stay valid.
76
+ """
77
+ key = (symbol or "").strip()
78
+ return f"{key}#{AgentFirewall._SLICE_REVISION}" if key else ""
79
+
64
80
  @staticmethod
65
81
  def _file_content_hash(file_path: str) -> str:
66
82
  """sha256 of the file's RAW bytes — streamed in 64KB chunks."""
@@ -126,7 +142,7 @@ class AgentFirewall:
126
142
  return False, None, 0
127
143
 
128
144
  abs_path = os.path.abspath(file_path)
129
- symbol_key = (symbol or "").strip()
145
+ symbol_key = cls._cache_symbol(symbol)
130
146
  current_hash = ""
131
147
 
132
148
  hit_data = None
@@ -259,7 +275,7 @@ class AgentFirewall:
259
275
  mtime = time.time()
260
276
 
261
277
  abs_path = os.path.abspath(file_path)
262
- symbol_key = (symbol or "").strip()
278
+ symbol_key = cls._cache_symbol(symbol)
263
279
  tokens = count_tokens(content)
264
280
  now = int(time.time())
265
281
  content_hash = cls._file_content_hash(abs_path)