tokensafe 4.7.3 → 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 +25 -14
- package/bin/python-runtime.json +34 -0
- package/bin/tokensafe.js +398 -96
- package/kimi.plugin.json +1 -1
- package/package.json +2 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/batch_editor.py +12 -2
- package/src/bench/driver.py +40 -13
- package/src/bench/go_target.py +207 -22
- package/src/bench/runner.py +79 -19
- package/src/cli.py +7 -3
- 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
|
@@ -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) |
|
|
@@ -233,26 +240,30 @@ Full matrix and details: [docs/OUMV.md](docs/OUMV.md).
|
|
|
233
240
|
|
|
234
241
|
## Benchmarks
|
|
235
242
|
|
|
236
|
-
### 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)
|
|
237
244
|
|
|
238
245
|
Real 12-assertion oracle re-run after every step; tokens and cost from the provider's `usage`
|
|
239
246
|
payload. `baseline` = file/search/command tools, `tokensafe` = this product's MCP server
|
|
240
|
-
(`
|
|
241
|
-
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.
|
|
242
251
|
|
|
243
252
|
| Arm | Solved | Mean steps | Mean input | Mean output | Cost/run |
|
|
244
253
|
| :--- | ---: | ---: | ---: | ---: | ---: |
|
|
245
|
-
| `baseline` | 15/15 |
|
|
246
|
-
| `tokensafe` | 15/15 |
|
|
247
|
-
| `oumv` | 15/15 |
|
|
248
|
-
|
|
249
|
-
**vs baseline: −
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
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)
|
|
254
264
|
in the backend repo, generated from the run JSON by
|
|
255
|
-
`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).
|
|
256
267
|
|
|
257
268
|
### Agent Usability Benchmarks (AUB) — Full-Stack Agent Velocity
|
|
258
269
|
|
|
@@ -604,7 +615,7 @@ More documentation: [docs/OUMV.md](docs/OUMV.md) · [docs/AGENT_SETUP.md](docs/A
|
|
|
604
615
|
|
|
605
616
|
## Development and License
|
|
606
617
|
|
|
607
|
-
The client runs on
|
|
618
|
+
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
619
|
|
|
609
620
|
```bash
|
|
610
621
|
# 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
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
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,129 +45,395 @@ const CORE_DEPS = [
|
|
|
32
45
|
'Pillow>=10.0.0'
|
|
33
46
|
];
|
|
34
47
|
|
|
35
|
-
function
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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() {
|
|
39
58
|
try {
|
|
40
|
-
|
|
41
|
-
|
|
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) {
|
|
88
|
+
try {
|
|
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
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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
|
-
|
|
56
|
-
|
|
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;
|
|
57
114
|
}
|
|
115
|
+
if (!pipInstall(python, OPTIONAL_DEPS, scope)) {
|
|
116
|
+
note('optional accelerators (tree-sitter grammars, Pillow) were not installed — stdlib fallbacks stay active');
|
|
117
|
+
}
|
|
118
|
+
return probePython(python, true) !== null;
|
|
119
|
+
}
|
|
58
120
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (
|
|
75
|
-
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function ensureManagedRuntime() {
|
|
304
|
+
const manifest = loadManifest();
|
|
305
|
+
if (!manifest) return null;
|
|
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(options = {}) {
|
|
357
|
+
const { allowProvision = true, requireDeps = true } = options;
|
|
358
|
+
const pinned = (process.env.TOKENSAFE_PYTHON || '').trim();
|
|
359
|
+
if (pinned) {
|
|
360
|
+
if (probePython(pinned, true)) return pinned;
|
|
361
|
+
if (requireDeps && probePython(pinned, false)) {
|
|
362
|
+
const bootstrapped = bootstrapDependencies(pinned);
|
|
363
|
+
if (bootstrapped) return bootstrapped;
|
|
364
|
+
}
|
|
365
|
+
if (!requireDeps && probePython(pinned, false)) return pinned;
|
|
366
|
+
fail(`TOKENSAFE_PYTHON=${pinned} is not a usable CPython ${MIN_PYTHON[0]}.${MIN_PYTHON[1]}+ with 'cryptography'.`);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const candidates = [];
|
|
370
|
+
const venvPy = venvPythonPath();
|
|
371
|
+
if (fs.existsSync(venvPy)) candidates.push(venvPy);
|
|
372
|
+
candidates.push('python3', 'python');
|
|
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;
|
|
90
381
|
}
|
|
91
382
|
|
|
92
383
|
for (const cmd of candidates) {
|
|
93
|
-
if (cmd
|
|
94
|
-
|
|
384
|
+
if (probePython(cmd, true)) return cmd;
|
|
385
|
+
}
|
|
386
|
+
for (const cmd of candidates) {
|
|
387
|
+
if (probePython(cmd, false)) {
|
|
95
388
|
const bootstrapped = bootstrapDependencies(cmd);
|
|
96
389
|
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
390
|
}
|
|
102
391
|
}
|
|
103
|
-
|
|
392
|
+
|
|
393
|
+
return allowProvision ? await ensureManagedRuntime() : null;
|
|
104
394
|
}
|
|
105
395
|
|
|
106
396
|
const firstArg = args[0] || '';
|
|
397
|
+
const wantsHelp = firstArg === 'help' || firstArg === '--help' || firstArg === '-h';
|
|
107
398
|
|
|
108
|
-
|
|
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() {
|
|
109
405
|
console.log(`
|
|
110
406
|
⚡ TokenSafe - Local-First AI Coding Guardrails & Context Optimizer
|
|
111
407
|
Website: https://tokensafe.dev
|
|
408
|
+
Docs: https://tokensafe.dev/docs
|
|
112
409
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
tokensafe
|
|
123
|
-
tokensafe test "<prompt>" Test prompt compression on custom input
|
|
124
|
-
tokensafe expand-ref <hash> Restore folded tool/command/file result by its 8-char hash
|
|
125
|
-
tokensafe wrap <command> Run command with compact output folding (e.g. tests/logs)
|
|
126
|
-
tokensafe web <url> Fetch web page/docs and print clean compact Markdown
|
|
127
|
-
tokensafe doctor Audit MCP servers & skills context token tax
|
|
128
|
-
tokensafe providers List active LLM distillation models & keys
|
|
129
|
-
tokensafe benchmark Run zero-loss verification benchmark suite
|
|
130
|
-
tokensafe mcp Manage MCP servers (list, disable <name>, enable <name>)
|
|
131
|
-
tokensafe proxy [port] Start Transparent Local AI Proxy (default: 8765)
|
|
132
|
-
tokensafe graph Analyze repository God Nodes & dependency topology
|
|
133
|
-
tokensafe map Generate tokensafe-out/API_SURFACE.md interface snapshot
|
|
134
|
-
tokensafe vacuum Compact SQLite metrics database storage
|
|
135
|
-
tokensafe prune Prune granular telemetry events into lifetime rollup
|
|
136
|
-
tokensafe digest Preview or send weekly team ROI digest email
|
|
137
|
-
tokensafe tests Run the unit test suite (compact failure report)
|
|
138
|
-
tokensafe activate <key> Activate commercial Solo or Team seat license key
|
|
139
|
-
tokensafe license Show current license status and active tier
|
|
140
|
-
tokensafe update One-click self-update for npm, pip & all AI agent rules
|
|
141
|
-
tokensafe install Interactive installer for Cursor, Antigravity, Claude, etc.
|
|
142
|
-
tokensafe uninstall Uninstall TokenSafe from AI agents, unwire proxy & clean rules
|
|
143
|
-
tokensafe --help Show this help screen
|
|
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
|
|
144
420
|
`);
|
|
145
|
-
process.exit(0);
|
|
146
421
|
}
|
|
147
422
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
423
|
+
async function main() {
|
|
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 });
|
|
427
|
+
if (!python) {
|
|
428
|
+
if (wantsHelp) {
|
|
429
|
+
printHelpFallback();
|
|
430
|
+
process.exit(0);
|
|
431
|
+
}
|
|
432
|
+
printInstallGuidance();
|
|
433
|
+
process.exit(1);
|
|
434
|
+
}
|
|
156
435
|
|
|
157
|
-
const candidateTokensafe = path.join(ROOT_DIR, 'bin', 'tokensafe');
|
|
436
|
+
const candidateTokensafe = path.join(ROOT_DIR, 'bin', 'tokensafe');
|
|
158
437
|
const candidateAgy = path.join(ROOT_DIR, 'bin', 'agy-tokens');
|
|
159
438
|
const scriptPath = fs.existsSync(candidateTokensafe) ? candidateTokensafe : candidateAgy;
|
|
160
439
|
if (!fs.existsSync(scriptPath)) {
|
|
@@ -178,10 +457,33 @@ child.on('error', (err) => {
|
|
|
178
457
|
process.exit(1);
|
|
179
458
|
});
|
|
180
459
|
|
|
181
|
-
child.on('exit', (code, signal) => {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
});
|
|
460
|
+
child.on('exit', (code, signal) => {
|
|
461
|
+
if (signal) {
|
|
462
|
+
process.kill(process.pid, signal);
|
|
463
|
+
} else {
|
|
464
|
+
process.exit(code || 0);
|
|
465
|
+
}
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
if (require.main === module) {
|
|
470
|
+
main().catch((err) => {
|
|
471
|
+
console.error(`TokenSafe: ${err && err.message ? err.message : err}`);
|
|
472
|
+
process.exit(1);
|
|
473
|
+
});
|
|
474
|
+
} else {
|
|
475
|
+
module.exports = {
|
|
476
|
+
TOKENSAFE_HOME,
|
|
477
|
+
RUNTIME_ROOT,
|
|
478
|
+
REQUIRED_DEPS,
|
|
479
|
+
OPTIONAL_DEPS,
|
|
480
|
+
loadManifest,
|
|
481
|
+
platformKey,
|
|
482
|
+
probePython,
|
|
483
|
+
findRuntimePython,
|
|
484
|
+
sha256File,
|
|
485
|
+
installDeps,
|
|
486
|
+
ensureManagedRuntime,
|
|
487
|
+
findPython
|
|
488
|
+
};
|
|
489
|
+
}
|