@raytrace-cli/cli 0.4.0 → 0.6.0
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/README.md +155 -123
- package/bin/raytrace.mjs +110 -22
- package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- package/dist/dashboard/assets/index-Dc3LTk8b.js +38 -0
- package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
- package/dist/dashboard/index.html +2 -2
- package/package.json +4 -1
- package/proxy/agent-intent-schema.test.mjs +142 -0
- package/proxy/call-assessment.mjs +385 -0
- package/proxy/call-assessment.test.mjs +167 -0
- package/proxy/call-category.mjs +461 -0
- package/proxy/capture.mjs +38 -0
- package/proxy/capture.test.mjs +49 -0
- package/proxy/claude-code-adapter.mjs +65 -3
- package/proxy/claude-code-hook.mjs +3 -1
- package/proxy/codex-config.mjs +5 -0
- package/proxy/codex.mjs +3 -2
- package/proxy/evidence-schema.test.mjs +233 -0
- package/proxy/evidence-store.mjs +704 -33
- package/proxy/evidence-store.test.mjs +304 -0
- package/proxy/exec-narrative.mjs +625 -0
- package/proxy/exec-narrative.test.mjs +262 -0
- package/proxy/execution-correlation.mjs +185 -0
- package/proxy/execution-correlation.test.mjs +146 -0
- package/proxy/execution-runner.test.mjs +38 -0
- package/proxy/experiment-engine.mjs +7 -4
- package/proxy/experiment-engine.test.mjs +93 -0
- package/proxy/explanations.test.mjs +20 -0
- package/proxy/failure-signature.mjs +56 -0
- package/proxy/gvisor-forwarder.mjs +454 -0
- package/proxy/gvisor-forwarder.test.mjs +368 -0
- package/proxy/init-evidence-db.mjs +166 -12
- package/proxy/local-sandboxes.mjs +94 -0
- package/proxy/local-token.mjs +30 -0
- package/proxy/playground-recovery.test.mjs +130 -0
- package/proxy/playground.mjs +439 -0
- package/proxy/prompt-context.mjs +12 -7
- package/proxy/prompt-traces.mjs +6 -0
- package/proxy/prompt-traces.test.mjs +32 -0
- package/proxy/providers.test.mjs +76 -0
- package/proxy/proxy.integration.test.mjs +135 -0
- package/proxy/raytace-proxy.mjs +512 -188
- package/proxy/request-metrics.test.mjs +19 -0
- package/proxy/request-policy.mjs +45 -0
- package/proxy/request-policy.test.mjs +47 -0
- package/proxy/run-recap.mjs +139 -0
- package/proxy/runtime-attribution.mjs +110 -0
- package/proxy/sandbox-bridge.mjs +49 -0
- package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
- package/proxy/schema/auxiliary.sql +48 -1
- package/proxy/schema/classification.sql +89 -0
- package/proxy/schema/file_context.sql +53 -0
- package/proxy/schema/runtime_evidence.sql +201 -0
- package/proxy/schema/search.sql +66 -0
- package/proxy/search.mjs +418 -0
- package/proxy/search.test.mjs +161 -0
- package/proxy/smoke.test.mjs +93 -0
- package/proxy/step-attribution.mjs +380 -0
- package/proxy/step-lab.test.mjs +38 -0
- package/proxy/summaries.test.mjs +69 -0
- package/proxy/tool-metadata.mjs +36 -0
- package/proxy/tool-metadata.test.mjs +38 -0
- package/proxy/trace-view.mjs +308 -0
- package/proxy/trace-view.test.mjs +72 -0
- package/proxy/typesafe.mjs +63 -0
- package/proxy/typesafe.test.mjs +39 -0
- package/src/claude-code.mjs +38 -1
- package/src/commands.mjs +133 -20
- package/src/config.mjs +16 -7
- package/src/export.mjs +200 -0
- package/src/lima.mjs +176 -0
- package/src/local-sandbox.mjs +339 -0
- package/src/paths.mjs +8 -8
- package/src/proxy-process.mjs +45 -3
- package/src/sandbox.mjs +37 -9
- package/src/upload.mjs +198 -0
- package/worker/sandbox/Dockerfile +8 -0
- package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- package/worker/sandbox/claude-hook.mjs +364 -0
- package/worker/sandbox/collector.py +357 -0
- package/worker/sandbox/dns_forwarder.py +255 -0
- package/worker/sandbox/engine.py +940 -0
- package/worker/sandbox/file_scan.py +491 -0
- package/worker/sandbox/lima.yaml +29 -0
- package/worker/sandbox/network.py +90 -0
- package/worker/sandbox/projects.py +679 -0
- package/worker/sandbox/setup.py +159 -0
- package/worker/sandbox/syscall_catalog.sql +985 -0
- package/worker/sandbox/transcript-delivery.test.mjs +153 -0
- package/worker/sandbox/viewer.py +151 -0
- package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
- package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
package/src/commands.mjs
CHANGED
|
@@ -4,9 +4,9 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import { delimiter, join } from 'node:path';
|
|
5
5
|
import { paths } from './paths.mjs';
|
|
6
6
|
import { portOf, proxyEnv, readConfig, writeConfig } from './config.mjs';
|
|
7
|
-
import { healthy, portInUse, runningPid, start, status, stop } from './proxy-process.mjs';
|
|
7
|
+
import { checkRunningPid, dashboardLink, healthy, portInUse, PROXY_API, proxyApi, runningPid, start, status, stop } from './proxy-process.mjs';
|
|
8
8
|
import { HOOK_COMMAND, hookState, setHook } from './claude-code.mjs';
|
|
9
|
-
import { confirm, interactive } from './prompt.mjs';
|
|
9
|
+
import { askSecret, confirm, interactive } from './prompt.mjs';
|
|
10
10
|
|
|
11
11
|
const say = (line = '') => console.log(line);
|
|
12
12
|
const CLOUD_URL = 'https://app.raytracer.si';
|
|
@@ -60,7 +60,7 @@ export async function setup(flags) {
|
|
|
60
60
|
|
|
61
61
|
if (hookClaude && !onPath('raytrace')) {
|
|
62
62
|
say(`\n Warning: \`raytrace\` is not on your PATH, and Claude Code's hook runs \`${HOOK_COMMAND}\`.`);
|
|
63
|
-
say(' Install it globally so the hook can find it: npm install -g @raytrace/cli');
|
|
63
|
+
say(' Install it globally so the hook can find it: npm install -g @raytrace-cli/cli');
|
|
64
64
|
}
|
|
65
65
|
|
|
66
66
|
// A proxy this CLI started is restarted so the new settings apply.
|
|
@@ -76,10 +76,12 @@ export async function setup(flags) {
|
|
|
76
76
|
export async function startCommand({ open = false } = {}) {
|
|
77
77
|
const result = await start();
|
|
78
78
|
const url = `http://127.0.0.1:${result.port}`;
|
|
79
|
-
say(result.
|
|
79
|
+
say(result.replaced ? `RayTrace restarted with this version (an older one was running): ${url}`
|
|
80
|
+
: result.started ? `RayTrace is running: ${url}` : `RayTrace was already running: ${url}`);
|
|
80
81
|
if (!result.started && !result.pid) say(' (started outside this CLI, e.g. from the RayTrace repo; `raytrace stop` will not stop it)');
|
|
81
82
|
say(` Logs: ${paths.proxyLog}`);
|
|
82
|
-
if (open) openUrl(
|
|
83
|
+
if (open) openUrl(await dashboardLink(result.port));
|
|
84
|
+
else say(' Open the dashboard with: raytrace open');
|
|
83
85
|
}
|
|
84
86
|
|
|
85
87
|
export async function stopCommand() {
|
|
@@ -100,39 +102,143 @@ export async function statusCommand() {
|
|
|
100
102
|
export async function openCommand() {
|
|
101
103
|
const state = await status();
|
|
102
104
|
if (!state.healthy) { say('RayTrace is not running. Start it with `raytrace start`.'); process.exitCode = 1; return; }
|
|
103
|
-
|
|
105
|
+
if (state.pid && await proxyApi(state.port) < PROXY_API) await start();
|
|
106
|
+
openUrl(await dashboardLink(state.port));
|
|
104
107
|
say(`Opening ${state.url}`);
|
|
105
108
|
}
|
|
106
109
|
|
|
110
|
+
// ------------------------------------------------------------------ keys
|
|
111
|
+
|
|
112
|
+
// The keys the dashboard's AI features run on: the user's own, kept in
|
|
113
|
+
// config.env (readable only by them) and used only by the proxy here.
|
|
114
|
+
const KEYS = {
|
|
115
|
+
openrouter: { name: 'OPENROUTER_API_KEY', label: 'OpenRouter', where: 'https://openrouter.ai/keys',
|
|
116
|
+
turnsOn: 'step summaries, command descriptions, run recaps and Chain of thought, and `raytrace codex`',
|
|
117
|
+
models: 'Qwen3 Coder (Chain of thought), gpt-oss-120b (summaries), Claude Sonnet 5.5 (recaps)' },
|
|
118
|
+
typesafe: { name: 'TYPESAFE_API_KEY', label: 'TypeSafe (Jev)', where: 'your TypeSafe account',
|
|
119
|
+
turnsOn: 'ranking Chain of thought\'s causes and rating each command\'s severity' },
|
|
120
|
+
};
|
|
121
|
+
const masked = (value) => (value ? `set (…${value.slice(-4)})` : 'not set');
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* `raytrace key` lists the keys; `raytrace key <openrouter|typesafe>` asks for
|
|
125
|
+
* one (typed without echo, or piped in) and saves it; `--remove` deletes it.
|
|
126
|
+
* The key is never taken as an argument, so it stays out of shell history.
|
|
127
|
+
*/
|
|
128
|
+
export async function keyCommand(which, flags) {
|
|
129
|
+
const config = readConfig();
|
|
130
|
+
if (!which) {
|
|
131
|
+
for (const [id, key] of Object.entries(KEYS)) say(`${id.padEnd(11)} ${masked(config[key.name])} ${key.turnsOn}`);
|
|
132
|
+
say('\nAdd one: raytrace key openrouter (or typesafe). Remove one: raytrace key openrouter --remove');
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const key = KEYS[which];
|
|
136
|
+
if (!key) throw new Error(`Unknown key "${which}". Use: raytrace key openrouter | typesafe`);
|
|
137
|
+
let value = '';
|
|
138
|
+
if (!flags.remove) {
|
|
139
|
+
if (interactive()) {
|
|
140
|
+
say(`Your ${key.label} key turns on ${key.turnsOn}. Get one at ${key.where}.`);
|
|
141
|
+
if (key.models) say(`Calls are made on your key and billed to you; models: ${key.models}.`);
|
|
142
|
+
value = await askSecret(`${key.label} key: `);
|
|
143
|
+
} else {
|
|
144
|
+
const chunks = [];
|
|
145
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
146
|
+
value = Buffer.concat(chunks).toString('utf8').trim();
|
|
147
|
+
}
|
|
148
|
+
if (!value) throw new Error('No key given; nothing changed.');
|
|
149
|
+
if (/\s/.test(value)) throw new Error('That does not look like a key (it has spaces); nothing changed.');
|
|
150
|
+
}
|
|
151
|
+
const next = { ...config, [key.name]: value };
|
|
152
|
+
if (which === 'openrouter') next.RAYTACE_PROVIDER = value ? 'openrouter' : 'native';
|
|
153
|
+
writeConfig(next);
|
|
154
|
+
say(value ? `${key.label} key saved in ${paths.config} (only you can read it).` : `${key.label} key removed.`);
|
|
155
|
+
// A proxy this CLI started is restarted so the key applies.
|
|
156
|
+
if (runningPid()) { await stop(); await start(); say('RayTrace restarted with it.'); }
|
|
157
|
+
else if (await healthy(portOf(readConfig()))) say('A RayTrace proxy started outside this CLI is running; restart it to use this.');
|
|
158
|
+
}
|
|
159
|
+
|
|
107
160
|
// ------------------------------------------------------------------ doctor
|
|
108
161
|
|
|
109
162
|
export async function doctor() {
|
|
110
163
|
let problems = 0;
|
|
111
164
|
const line = (ok, label, detail) => { if (ok === false) problems += 1; say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}`); };
|
|
112
|
-
|
|
165
|
+
let config;
|
|
166
|
+
try { config = readConfig(); } catch (err) { config = {}; line(false, 'settings', `malformed config: ${err.message}`); }
|
|
113
167
|
const port = portOf(config);
|
|
114
168
|
|
|
115
169
|
line(true, 'node', process.version);
|
|
116
170
|
if (!existsSync(paths.config)) line(false, 'settings', `missing; run \`raytrace setup\``);
|
|
117
171
|
else {
|
|
118
|
-
|
|
119
|
-
|
|
172
|
+
try {
|
|
173
|
+
const mode = statSync(paths.config).mode & 0o777;
|
|
174
|
+
line(process.platform === 'win32' || (mode & 0o077) === 0, 'settings', `${paths.config}${(mode & 0o077) && process.platform !== 'win32' ? ` is readable by others (chmod 600 it)` : ''}`);
|
|
175
|
+
} catch (err) {
|
|
176
|
+
line(false, 'settings', `cannot inspect ${paths.config}: ${err.message}`);
|
|
177
|
+
}
|
|
120
178
|
}
|
|
121
179
|
line(existsSync(paths.dashboard) ? true : false, 'dashboard', existsSync(paths.dashboard) ? 'built' : `missing from ${paths.dashboard}; reinstall`);
|
|
122
|
-
line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : 'no: Claude Code\'s hook cannot run it (npm install -g @raytrace/cli)');
|
|
180
|
+
line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : 'no: Claude Code\'s hook cannot run it (npm install -g @raytrace-cli/cli)');
|
|
123
181
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
182
|
+
try {
|
|
183
|
+
const hooks = hookState();
|
|
184
|
+
if (!hooks.installed) {
|
|
185
|
+
line(null, 'claude code hook', `not installed (${hooks.file}); run \`raytrace setup\``);
|
|
186
|
+
} else if (!hooks.valid) {
|
|
187
|
+
const issues = [];
|
|
188
|
+
if (hooks.missingEvents.length) issues.push(`missing: ${hooks.missingEvents.join(', ')}`);
|
|
189
|
+
if (hooks.invalidType) issues.push('invalid hook type (expected command)');
|
|
190
|
+
if (hooks.invalidMatcher) issues.push('restricted PostToolUse matcher (must be *)');
|
|
191
|
+
if (hooks.duplicates) issues.push('duplicate hooks detected');
|
|
192
|
+
line(false, 'claude code hook', `misconfigured in ${hooks.file} (${issues.join('; ')}); run \`raytrace setup\``);
|
|
193
|
+
} else {
|
|
194
|
+
line(true, 'claude code hook', `installed and valid in ${hooks.file}`);
|
|
195
|
+
}
|
|
196
|
+
if (hooks.repoHook) line(null, 'repo hook', 'the RayTrace repo\'s hook is also installed; sessions are reported twice');
|
|
197
|
+
} catch (error) {
|
|
198
|
+
line(false, 'claude code hook', `cannot read settings: ${error.message}`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
line(config.OPENROUTER_API_KEY ? true : null, 'openrouter', config.OPENROUTER_API_KEY ? 'key set: AI features on' : 'no key: AI features off (raytrace key openrouter)');
|
|
202
|
+
|
|
203
|
+
const pid = checkRunningPid();
|
|
204
|
+
try {
|
|
205
|
+
if (await healthy(port)) line(true, 'proxy', `running on :${port}${pid ? ` (pid ${pid})` : ' (started outside this CLI)'}`);
|
|
206
|
+
else if (await portInUse(port)) line(false, 'proxy', `port ${port} is held by something that is not RayTrace`);
|
|
207
|
+
else line(null, 'proxy', `stopped (port ${port} free)`);
|
|
208
|
+
} catch (err) {
|
|
209
|
+
line(false, 'proxy', `connectivity check failed: ${err.message}`);
|
|
210
|
+
}
|
|
127
211
|
|
|
128
|
-
|
|
212
|
+
const bridgePort = Number(process.env.RAYTRACE_BRIDGE_PORT || 8799);
|
|
213
|
+
try {
|
|
214
|
+
const res = await fetch(`http://127.0.0.1:${bridgePort}/raytace/identity`, { signal: AbortSignal.timeout(1000) });
|
|
215
|
+
if (res.ok) {
|
|
216
|
+
const info = await res.json();
|
|
217
|
+
line(true, 'sandbox bridge', `listening on :${bridgePort} (${info.service} v${info.version})`);
|
|
218
|
+
} else {
|
|
219
|
+
line(false, 'sandbox bridge', `port ${bridgePort} returned HTTP ${res.status}`);
|
|
220
|
+
}
|
|
221
|
+
} catch {
|
|
222
|
+
line(null, 'sandbox bridge', `not responding on :${bridgePort} (starts with proxy)`);
|
|
223
|
+
}
|
|
129
224
|
|
|
130
|
-
const pid = runningPid();
|
|
131
|
-
if (await healthy(port)) line(true, 'proxy', `running on :${port}${pid ? ` (pid ${pid})` : ' (started outside this CLI)'}`);
|
|
132
|
-
else if (await portInUse(port)) line(false, 'proxy', `port ${port} is held by something that is not RayTrace`);
|
|
133
|
-
else line(null, 'proxy', `stopped (port ${port} free)`);
|
|
134
225
|
line(existsSync(paths.database) ? true : null, 'database', existsSync(paths.database) ? `${paths.database} (${(statSync(paths.database).size / 1e6).toFixed(1)} MB)` : 'not created yet; it is made on first start');
|
|
135
226
|
|
|
227
|
+
// Local sandboxes are optional: what they lack is shown, not counted as a problem.
|
|
228
|
+
say('\nLocal sandboxes (raytrace sandbox create --local):');
|
|
229
|
+
try {
|
|
230
|
+
const { checks } = await import('./lima.mjs');
|
|
231
|
+
const { vmStatus, inVm } = await import('./local-sandbox.mjs');
|
|
232
|
+
let vm = null;
|
|
233
|
+
try { vm = vmStatus(); } catch { /* no Lima yet */ }
|
|
234
|
+
const rows = await checks({ vmRunning: vm === 'Running', runInVm: inVm });
|
|
235
|
+
for (const { ok, label, detail, fix } of rows) say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}${fix ? `\n ${''.padEnd(22)} fix: ${fix}` : ''}`);
|
|
236
|
+
if (vm) say(`· ${'vm'.padEnd(22)} raytrace: ${vm.toLowerCase()}`);
|
|
237
|
+
else if (rows.every((row) => row.ok !== false)) say(`· ${'vm'.padEnd(22)} not created yet; the first local sandbox makes it`);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
say(`· ${'vm checks'.padEnd(22)} skipped (${err.message})`);
|
|
240
|
+
}
|
|
241
|
+
|
|
136
242
|
say(problems ? `\n${problems} problem${problems === 1 ? '' : 's'} found.` : '\nNo problems found.');
|
|
137
243
|
if (problems) process.exitCode = 1;
|
|
138
244
|
}
|
|
@@ -165,8 +271,15 @@ export async function uninstall(flags) {
|
|
|
165
271
|
if (hookState().installed) say(`Removed the Claude Code hook from ${setHook({ remove: true })}.`);
|
|
166
272
|
if (existsSync(paths.home)) {
|
|
167
273
|
const purge = flags.purge || (!yes && await confirm(`Delete ${paths.home} (recorded sessions and settings)?`, false));
|
|
168
|
-
if (purge) {
|
|
274
|
+
if (purge) {
|
|
275
|
+
// Before the folder goes: the Lima that RayTrace downloaded, which removes the VM, is in it.
|
|
276
|
+
const { deleteVm } = await import('./local-sandbox.mjs');
|
|
277
|
+
try { if (deleteVm()) say('Deleted the local sandbox VM (raytrace) and its sandboxes.'); }
|
|
278
|
+
catch (error) { say(`The local sandbox VM was not deleted (${error.message.split('\n')[0]}); limactl delete --force raytrace removes it.`); }
|
|
279
|
+
rmSync(paths.home, { recursive: true, force: true });
|
|
280
|
+
say(`Deleted ${paths.home}.`);
|
|
281
|
+
}
|
|
169
282
|
else say(`Kept ${paths.home}.`);
|
|
170
283
|
}
|
|
171
|
-
say('To remove the command itself: npm uninstall -g @raytrace/cli');
|
|
284
|
+
say('To remove the command itself: npm uninstall -g @raytrace-cli/cli');
|
|
172
285
|
}
|
package/src/config.mjs
CHANGED
|
@@ -11,19 +11,28 @@ export function readConfig() {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
export function writeConfig(values) {
|
|
14
|
-
|
|
15
|
-
const lines = Object.entries(values)
|
|
14
|
+
const entries = Object.entries(values)
|
|
16
15
|
.filter(([, value]) => value !== undefined && value !== '')
|
|
17
|
-
.map(([key, value]) =>
|
|
18
|
-
|
|
16
|
+
.map(([key, value]) => [key, String(value)]);
|
|
17
|
+
const lines = entries.map(([key, value]) => `${key}=${quote(value)}`);
|
|
18
|
+
const text = `# RayTrace settings. Restart with \`raytrace stop && raytrace start\` after editing.\n${lines.join('\n')}\n`;
|
|
19
|
+
const parsed = parseEnv(text);
|
|
20
|
+
// Validate before touching the existing settings. dotenv has no general
|
|
21
|
+
// quote-escaping syntax, so some values cannot be represented losslessly.
|
|
22
|
+
for (const [key, value] of entries) {
|
|
23
|
+
if (parsed[key] !== value) throw new Error(`Cannot save setting ${key} without changing its value.`);
|
|
24
|
+
}
|
|
25
|
+
mkdirSync(paths.home, { recursive: true });
|
|
26
|
+
writeFileSync(paths.config, text, { mode: 0o600 });
|
|
19
27
|
chmodSync(paths.config, 0o600); // the mode above only applies when the file is new
|
|
20
28
|
}
|
|
21
29
|
|
|
22
|
-
//
|
|
23
|
-
//
|
|
30
|
+
// Choose a delimiter absent from the value. Backslash does not escape a
|
|
31
|
+
// delimiter in parseEnv; double quotes also expand literal backslash-n.
|
|
24
32
|
function quote(value) {
|
|
25
33
|
if (!/[\s#"'`]/.test(value)) return value;
|
|
26
|
-
|
|
34
|
+
const delimiter = ["'", '`', '"'].find((candidate) => !value.includes(candidate));
|
|
35
|
+
return delimiter ? `${delimiter}${value}${delimiter}` : value;
|
|
27
36
|
}
|
|
28
37
|
|
|
29
38
|
export const portOf = (config) => Number(config.RAYTACE_PORT || DEFAULT_PORT);
|
package/src/export.mjs
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { existsSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { paths } from './paths.mjs';
|
|
4
|
+
import { openEvidenceStore } from '../proxy/evidence-store.mjs';
|
|
5
|
+
import { readTraces } from '../proxy/trace-view.mjs';
|
|
6
|
+
|
|
7
|
+
const VERSION = '1.0.0';
|
|
8
|
+
|
|
9
|
+
function escapeHtml(str) {
|
|
10
|
+
if (typeof str !== 'string') return '';
|
|
11
|
+
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function safeCodeBlock(content, lang = '') {
|
|
15
|
+
const text = String(content ?? '');
|
|
16
|
+
const matches = text.match(/`+/g) || [];
|
|
17
|
+
let maxBackticks = 3;
|
|
18
|
+
for (const m of matches) {
|
|
19
|
+
if (m.length >= maxBackticks) maxBackticks = m.length + 1;
|
|
20
|
+
}
|
|
21
|
+
const fence = '`'.repeat(maxBackticks);
|
|
22
|
+
return `${fence}${lang}\n${text}\n${fence}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function formatTraceJson(trace) {
|
|
26
|
+
const exported = {
|
|
27
|
+
version: VERSION,
|
|
28
|
+
exported_at: new Date().toISOString(),
|
|
29
|
+
trace: {
|
|
30
|
+
id: trace.id,
|
|
31
|
+
provider: trace.provider,
|
|
32
|
+
model: trace.model,
|
|
33
|
+
status: trace.status ?? 'unknown',
|
|
34
|
+
title: trace.title ?? null,
|
|
35
|
+
prompt: trace.promptRaw ?? null,
|
|
36
|
+
answer: trace.answer ?? null,
|
|
37
|
+
started_at: trace.startedAt ?? null,
|
|
38
|
+
ended_at: trace.endedAt ?? null,
|
|
39
|
+
sandbox_id: trace.sandboxId ?? null,
|
|
40
|
+
fork_id: trace.forkId ?? null,
|
|
41
|
+
requests: (trace.requests ?? []).map((r) => ({
|
|
42
|
+
id: r.id,
|
|
43
|
+
model: r.model,
|
|
44
|
+
started_at: r.startedAt,
|
|
45
|
+
completed_at: r.completedAt,
|
|
46
|
+
cost: r.cost ?? null,
|
|
47
|
+
input_tokens: r.input_tokens ?? null,
|
|
48
|
+
output_tokens: r.output_tokens ?? null,
|
|
49
|
+
})),
|
|
50
|
+
events: (trace.events ?? []).map((e) => {
|
|
51
|
+
let raw = null;
|
|
52
|
+
if (e.raw) {
|
|
53
|
+
try { raw = typeof e.raw === 'string' ? JSON.parse(e.raw) : e.raw; } catch { raw = e.raw; }
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
kind: e.kind,
|
|
57
|
+
title: e.title,
|
|
58
|
+
status: e.status,
|
|
59
|
+
timestamp: e.timestamp,
|
|
60
|
+
raw,
|
|
61
|
+
};
|
|
62
|
+
}),
|
|
63
|
+
evidence: trace.evidence ?? [],
|
|
64
|
+
call_verifications: trace.callVerifications ?? [],
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
return JSON.stringify(exported, null, 2);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function formatTraceMarkdown(trace) {
|
|
71
|
+
const lines = [];
|
|
72
|
+
lines.push(`# Trace ${trace.id}`);
|
|
73
|
+
lines.push('');
|
|
74
|
+
lines.push(`- **Exported:** ${new Date().toISOString()}`);
|
|
75
|
+
lines.push(`- **Format Version:** ${VERSION}`);
|
|
76
|
+
lines.push(`- **Status:** \`${trace.status ?? 'unknown'}\``);
|
|
77
|
+
lines.push(`- **Model:** \`${trace.model ?? 'unknown'}\``);
|
|
78
|
+
lines.push(`- **Provider:** \`${trace.provider ?? 'unknown'}\``);
|
|
79
|
+
lines.push(`- **Started At:** ${trace.startedAt ?? 'unknown'}`);
|
|
80
|
+
lines.push(`- **Ended At:** ${trace.endedAt ?? 'unknown'}`);
|
|
81
|
+
|
|
82
|
+
let totalCost = null;
|
|
83
|
+
let totalInputTokens = 0;
|
|
84
|
+
let totalOutputTokens = 0;
|
|
85
|
+
let hasTokenData = false;
|
|
86
|
+
|
|
87
|
+
for (const r of trace.requests ?? []) {
|
|
88
|
+
if (r.cost != null) totalCost = (totalCost ?? 0) + r.cost;
|
|
89
|
+
if (r.input_tokens != null) { totalInputTokens += r.input_tokens; hasTokenData = true; }
|
|
90
|
+
if (r.output_tokens != null) { totalOutputTokens += r.output_tokens; hasTokenData = true; }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
lines.push(`- **Cost:** \`${totalCost != null ? `$${totalCost.toFixed(4)}` : 'unknown'}\``);
|
|
94
|
+
if (hasTokenData) {
|
|
95
|
+
lines.push(`- **Tokens:** ${totalInputTokens} input · ${totalOutputTokens} output`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
lines.push('');
|
|
99
|
+
lines.push('## Prompt');
|
|
100
|
+
lines.push('');
|
|
101
|
+
lines.push(escapeHtml(trace.promptRaw || trace.title || '(no prompt recorded)'));
|
|
102
|
+
lines.push('');
|
|
103
|
+
|
|
104
|
+
if (trace.answer) {
|
|
105
|
+
lines.push('## Final Answer');
|
|
106
|
+
lines.push('');
|
|
107
|
+
lines.push(escapeHtml(trace.answer));
|
|
108
|
+
lines.push('');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
lines.push('## Timeline & Tool Calls');
|
|
112
|
+
lines.push('');
|
|
113
|
+
|
|
114
|
+
if (!trace.events || !trace.events.length) {
|
|
115
|
+
lines.push('*(No events recorded)*');
|
|
116
|
+
} else {
|
|
117
|
+
for (const ev of trace.events) {
|
|
118
|
+
lines.push(`### ${escapeHtml(ev.title)}`);
|
|
119
|
+
lines.push(`- **Kind:** \`${ev.kind}\``);
|
|
120
|
+
lines.push(`- **Status:** \`${ev.status || 'unknown'}\``);
|
|
121
|
+
lines.push(`- **Timestamp:** ${ev.timestamp || 'unknown'}`);
|
|
122
|
+
|
|
123
|
+
let rawObj = null;
|
|
124
|
+
if (ev.raw) {
|
|
125
|
+
try { rawObj = typeof ev.raw === 'string' ? JSON.parse(ev.raw) : ev.raw; } catch { rawObj = ev.raw; }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (rawObj?.call_id) {
|
|
129
|
+
lines.push(`- **Call ID:** \`${rawObj.call_id}\``);
|
|
130
|
+
}
|
|
131
|
+
if (rawObj?.output !== undefined) {
|
|
132
|
+
lines.push('');
|
|
133
|
+
lines.push('**Output:**');
|
|
134
|
+
lines.push(safeCodeBlock(rawObj.output));
|
|
135
|
+
} else if (rawObj?.arguments || rawObj?.input) {
|
|
136
|
+
lines.push('');
|
|
137
|
+
lines.push('**Arguments:**');
|
|
138
|
+
lines.push(safeCodeBlock(rawObj.arguments || rawObj.input, 'json'));
|
|
139
|
+
}
|
|
140
|
+
lines.push('');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (trace.callVerifications && trace.callVerifications.length) {
|
|
145
|
+
lines.push('## Observed Execution');
|
|
146
|
+
lines.push('');
|
|
147
|
+
for (const v of trace.callVerifications) {
|
|
148
|
+
lines.push(`- **${escapeHtml(v.name || 'tool')}** (\`${v.call_id}\`): ` +
|
|
149
|
+
`status=\`${v.status || (v.verified ? 'verified' : 'unverified')}\`` +
|
|
150
|
+
`${v.proposed ? ` · proposed: \`${escapeHtml(v.proposed)}\`` : ''}` +
|
|
151
|
+
`${v.error ? ` · error: \`${escapeHtml(v.error)}\`` : ''}`);
|
|
152
|
+
}
|
|
153
|
+
lines.push('');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return lines.join('\n');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function exportCommand(traceId, { format = 'markdown', output = null } = {}) {
|
|
160
|
+
if (!traceId || !traceId.trim()) {
|
|
161
|
+
throw new Error('Trace ID is required. Usage: raytrace export <trace-id> [--format json|markdown] [--output <file>]');
|
|
162
|
+
}
|
|
163
|
+
const cleanId = traceId.trim();
|
|
164
|
+
const cleanFormat = format?.toLowerCase() ?? 'markdown';
|
|
165
|
+
if (cleanFormat !== 'markdown' && cleanFormat !== 'json') {
|
|
166
|
+
throw new Error(`Invalid format: ${format}. Expected 'markdown' or 'json'.`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const dbPath = paths.database;
|
|
170
|
+
if (!existsSync(dbPath)) {
|
|
171
|
+
throw new Error(`No evidence database found at ${dbPath}. Has raytrace been started?`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const store = openEvidenceStore(dbPath, { readOnly: true });
|
|
175
|
+
let trace;
|
|
176
|
+
try {
|
|
177
|
+
const traces = await readTraces(store, { turnId: cleanId, includeHistory: true, evidence: true });
|
|
178
|
+
trace = traces.find((t) => t.id === cleanId) || traces[0];
|
|
179
|
+
} finally {
|
|
180
|
+
store.close();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (!trace) {
|
|
184
|
+
throw new Error(`Trace not found: ${cleanId}`);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const content = cleanFormat === 'json' ? formatTraceJson(trace) : formatTraceMarkdown(trace);
|
|
188
|
+
|
|
189
|
+
if (output) {
|
|
190
|
+
const outPath = resolve(output);
|
|
191
|
+
if (existsSync(outPath)) {
|
|
192
|
+
throw new Error(`File already exists: ${outPath}. Refusing to overwrite.`);
|
|
193
|
+
}
|
|
194
|
+
writeFileSync(outPath, content, { mode: 0o600 });
|
|
195
|
+
return content;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
console.log(content);
|
|
199
|
+
return content;
|
|
200
|
+
}
|
package/src/lima.mjs
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// Lima, which runs the Linux VM local sandboxes live in, and the checks made
|
|
2
|
+
// before one is created (`raytrace sandbox create --local`, `raytrace doctor`).
|
|
3
|
+
//
|
|
4
|
+
// A Lima the user installed is used when it is recent enough. Otherwise
|
|
5
|
+
// RayTrace downloads Lima's own release for this OS and CPU into
|
|
6
|
+
// ~/.raytrace/lima/<version>, after asking: no admin rights, nothing outside
|
|
7
|
+
// that folder. The archive is checked against the checksum pinned here, not
|
|
8
|
+
// one fetched beside it, so a changed release is refused. Lima keeps its VMs
|
|
9
|
+
// in ~/.lima either way.
|
|
10
|
+
//
|
|
11
|
+
// What cannot be downloaded is named with the command that installs it: QEMU
|
|
12
|
+
// on Linux (and on macOS before 13.5) comes from the system's package manager.
|
|
13
|
+
import { spawnSync } from 'node:child_process';
|
|
14
|
+
import { createHash } from 'node:crypto';
|
|
15
|
+
import { accessSync, constants, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { totalmem } from 'node:os';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
import { paths } from './paths.mjs';
|
|
19
|
+
import { portInUse } from './proxy-process.mjs';
|
|
20
|
+
|
|
21
|
+
export const LIMA_VERSION = '2.2.1';
|
|
22
|
+
// Lima's release archives for each host, and their SHA-256 from the release's SHA256SUMS.
|
|
23
|
+
const RELEASES = {
|
|
24
|
+
'darwin-arm64': ['Darwin-arm64', '9e9eacce88f37e185c346bad73aa6136f738d8cdf8c3bb23cd42b071824bc66e'],
|
|
25
|
+
'darwin-x64': ['Darwin-x86_64', '6b776e4bc41f358e6ee01fefcc78e2eb26f11635a0fcff632234af77a566c6c4'],
|
|
26
|
+
'linux-arm64': ['Linux-aarch64', 'fbcf4d127936666aa2cf6013b663c250431f2a59394757b404070f8d6a160e10'],
|
|
27
|
+
'linux-x64': ['Linux-x86_64', 'b391ac7fcac2b2a5a1628107756463188ded4d18d3104a40a66a8bb6fec01bcb'],
|
|
28
|
+
};
|
|
29
|
+
// The oldest Lima of the user's own that is used; an older one is left alone and the managed one used.
|
|
30
|
+
const MINIMUM = [2, 0];
|
|
31
|
+
const MANAGED = join(paths.home, 'lima', LIMA_VERSION);
|
|
32
|
+
const MANAGED_LIMACTL = join(MANAGED, 'bin', 'limactl');
|
|
33
|
+
// What the sandbox VM forwards to this machine: the evidence viewer.
|
|
34
|
+
const VIEWER_PORT = 8798;
|
|
35
|
+
|
|
36
|
+
function version(binary) {
|
|
37
|
+
const result = spawnSync(binary, ['--version'], { encoding: 'utf8' });
|
|
38
|
+
if (result.error || result.status !== 0) return null;
|
|
39
|
+
const match = /(\d+)\.(\d+)\.(\d+)/.exec(result.stdout);
|
|
40
|
+
return match ? match.slice(1).map(Number) : null;
|
|
41
|
+
}
|
|
42
|
+
const atLeast = (have, want) => have[0] > want[0] || (have[0] === want[0] && have[1] >= want[1]);
|
|
43
|
+
const onPath = (name) => !spawnSync(process.platform === 'win32' ? 'where' : 'which', [name], { stdio: 'ignore' }).status;
|
|
44
|
+
|
|
45
|
+
/** The limactl to run, and where it came from; null when there is none yet. */
|
|
46
|
+
export function findLima() {
|
|
47
|
+
const own = version('limactl');
|
|
48
|
+
if (own && atLeast(own, MINIMUM)) return { binary: 'limactl', version: own.join('.'), source: 'installed' };
|
|
49
|
+
if (existsSync(MANAGED_LIMACTL) && version(MANAGED_LIMACTL)) return { binary: MANAGED_LIMACTL, version: LIMA_VERSION, source: 'managed', old: own?.join('.') };
|
|
50
|
+
return own ? { binary: null, old: own.join('.') } : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const canDownload = () => Boolean(RELEASES[`${process.platform}-${process.arch}`]);
|
|
54
|
+
|
|
55
|
+
/** Lima's release for this machine, downloaded, checked and unpacked into ~/.raytrace/lima. */
|
|
56
|
+
export async function downloadLima(say) {
|
|
57
|
+
const [name, sha256] = RELEASES[`${process.platform}-${process.arch}`];
|
|
58
|
+
const url = `https://github.com/lima-vm/lima/releases/download/v${LIMA_VERSION}/lima-${LIMA_VERSION}-${name}.tar.gz`;
|
|
59
|
+
say(`Downloading Lima ${LIMA_VERSION} for ${name}...`);
|
|
60
|
+
let response;
|
|
61
|
+
try { response = await fetch(url, { signal: AbortSignal.timeout(300_000) }); } catch (error) {
|
|
62
|
+
throw new Error(`Could not download Lima (${error.message}). Check your connection, or install Lima yourself: https://lima-vm.io/docs/installation/`);
|
|
63
|
+
}
|
|
64
|
+
if (!response.ok) throw new Error(`Could not download Lima: HTTP ${response.status} from ${url}`);
|
|
65
|
+
const archive = Buffer.from(await response.arrayBuffer());
|
|
66
|
+
if (createHash('sha256').update(archive).digest('hex') !== sha256) {
|
|
67
|
+
throw new Error(`The Lima download did not match its pinned checksum, so it was not used. Install Lima yourself: https://lima-vm.io/docs/installation/`);
|
|
68
|
+
}
|
|
69
|
+
// Unpacked beside the final folder and moved over, so a half-unpacked one is never used.
|
|
70
|
+
const staging = `${MANAGED}.partial`;
|
|
71
|
+
rmSync(staging, { recursive: true, force: true });
|
|
72
|
+
mkdirSync(staging, { recursive: true });
|
|
73
|
+
const file = join(staging, 'lima.tar.gz');
|
|
74
|
+
writeFileSync(file, archive);
|
|
75
|
+
const unpacked = spawnSync('tar', ['-xzf', file, '-C', staging], { encoding: 'utf8' });
|
|
76
|
+
if (unpacked.status !== 0) throw new Error(`Could not unpack Lima: ${unpacked.stderr || unpacked.error?.message}`);
|
|
77
|
+
rmSync(file);
|
|
78
|
+
rmSync(MANAGED, { recursive: true, force: true });
|
|
79
|
+
renameSync(staging, MANAGED);
|
|
80
|
+
if (!version(MANAGED_LIMACTL)) throw new Error(`The downloaded Lima does not run on this machine (${MANAGED_LIMACTL}).`);
|
|
81
|
+
say(`Lima ${LIMA_VERSION} is in ${MANAGED}`);
|
|
82
|
+
return { binary: MANAGED_LIMACTL, version: LIMA_VERSION, source: 'managed' };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function macVersion() {
|
|
86
|
+
const shown = spawnSync('sw_vers', ['-productVersion'], { encoding: 'utf8' }).stdout?.trim() ?? '';
|
|
87
|
+
return shown.split('.').map(Number);
|
|
88
|
+
}
|
|
89
|
+
const qemu = () => (process.arch === 'arm64' ? 'qemu-system-aarch64' : 'qemu-system-x86_64');
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* What stands between this machine and a local sandbox, as rows of
|
|
93
|
+
* {ok: true | false | null (a warning), label, detail, fix?}. Lima itself is
|
|
94
|
+
* reported, not fetched: create offers the download.
|
|
95
|
+
*/
|
|
96
|
+
/** What the VM's firewall leaves a sandbox able to reach beyond the bridge
|
|
97
|
+
* (:8799). Lima maps its host address to this machine's localhost, so these
|
|
98
|
+
* rules are all that keeps a sandbox off the proxy. */
|
|
99
|
+
export function sandboxReach(rules) {
|
|
100
|
+
const lines = rules.split('\n').filter((line) => line.includes('-i br-raytace'));
|
|
101
|
+
if (!lines.some((line) => line.includes('-d 192.168.0.0/16') && line.includes('-j REJECT'))) return ['every local port'];
|
|
102
|
+
return lines.filter((line) => line.includes('-j ACCEPT') && !line.includes('--dport 8799')).map((line) => line.match(/--dport (\d+)/)?.[1] ?? 'every local port');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function checks({ vmRunning = false, runInVm = null } = {}) {
|
|
106
|
+
const rows = [];
|
|
107
|
+
const row = (ok, label, detail, fix) => rows.push({ ok, label, detail, fix });
|
|
108
|
+
const platform = process.platform;
|
|
109
|
+
|
|
110
|
+
if (platform === 'win32') row(null, 'platform', 'Windows: local sandboxes are experimental here (Lima on Windows is)');
|
|
111
|
+
else if (platform !== 'darwin' && platform !== 'linux') row(false, 'platform', `${platform} is not supported for local sandboxes`);
|
|
112
|
+
|
|
113
|
+
const lima = findLima();
|
|
114
|
+
if (lima?.binary) row(true, 'lima', `${lima.version} (${lima.source === 'managed' ? `downloaded by RayTrace, ${MANAGED}` : 'installed'})`);
|
|
115
|
+
else if (canDownload()) {
|
|
116
|
+
row(null, 'lima', `${lima?.old ? `${lima.old} is older than ${MINIMUM.join('.')}` : 'not installed'}; RayTrace downloads Lima ${LIMA_VERSION} on the first \`raytrace sandbox create --local\``);
|
|
117
|
+
} else {
|
|
118
|
+
row(false, 'lima', lima?.old ? `${lima.old} is older than ${MINIMUM.join('.')}` : 'not installed', 'install Lima: https://lima-vm.io/docs/installation/');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (platform === 'darwin') {
|
|
122
|
+
const [major, minor = 0] = macVersion();
|
|
123
|
+
// Lima uses Apple's own virtualization (vz) from macOS 13.5; before that, QEMU.
|
|
124
|
+
if (major > 13 || (major === 13 && minor >= 5)) row(true, 'virtualization', `macOS ${major}.${minor}: Apple Virtualization, nothing to install`);
|
|
125
|
+
else if (onPath(qemu())) row(true, 'virtualization', `macOS ${major}.${minor}: QEMU`);
|
|
126
|
+
else row(false, 'virtualization', `macOS ${major}.${minor} needs QEMU for the VM`, 'brew install qemu');
|
|
127
|
+
} else if (platform === 'linux') {
|
|
128
|
+
row(onPath(qemu()) ? true : false, 'qemu', onPath(qemu()) ? qemu() : `${qemu()} not found`,
|
|
129
|
+
'install QEMU: sudo apt install qemu-system (Fedora: sudo dnf install qemu-kvm; Arch: sudo pacman -S qemu-full)');
|
|
130
|
+
if (!existsSync('/dev/kvm')) row(null, 'kvm', 'no /dev/kvm: the VM will be very slow (turn on virtualization, or nested virtualization in a VM)');
|
|
131
|
+
else {
|
|
132
|
+
try { accessSync('/dev/kvm', constants.R_OK | constants.W_OK); row(true, 'kvm', '/dev/kvm'); }
|
|
133
|
+
catch { row(false, 'kvm', 'no access to /dev/kvm', 'sudo usermod -aG kvm $USER, then log out and in again'); }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The VM forwards the evidence viewer here; while it runs, the port is its own.
|
|
138
|
+
if (!vmRunning && await portInUse(VIEWER_PORT)) {
|
|
139
|
+
row(false, 'port 8798', 'in use; the evidence viewer needs it', 'stop what holds it (another Lima VM? limactl list)');
|
|
140
|
+
}
|
|
141
|
+
const gib = totalmem() / 1024 ** 3;
|
|
142
|
+
if (gib < 8) row(null, 'memory', `${gib.toFixed(0)} GiB; the VM takes 4 GiB while it runs`);
|
|
143
|
+
|
|
144
|
+
if (vmRunning && typeof runInVm === 'function') {
|
|
145
|
+
try {
|
|
146
|
+
const docker = runInVm(['docker', 'info', '--format', '{{json .Runtimes}}'], { check: false });
|
|
147
|
+
if (docker?.status === 0) {
|
|
148
|
+
row(true, 'docker (in VM)', 'responding');
|
|
149
|
+
const hasGvisor = typeof docker.stdout === 'string' && docker.stdout.includes('raytace-gvisor');
|
|
150
|
+
row(hasGvisor ? true : false, 'raytace-gvisor', hasGvisor ? 'runtime registered' : 'runtime missing from Docker', 'run setup in VM');
|
|
151
|
+
} else {
|
|
152
|
+
row(false, 'docker (in VM)', 'not responding or daemon down', 'sudo systemctl restart docker in VM');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const runsc = runInVm(['/usr/local/bin/runsc', '--version'], { check: false });
|
|
156
|
+
row(runsc?.status === 0 ? true : false, 'runsc (in VM)', runsc?.status === 0 ? String(runsc.stdout).trim().split('\n')[0] : 'missing from /usr/local/bin/runsc');
|
|
157
|
+
|
|
158
|
+
for (const svc of ['collector', 'viewer', 'dns']) {
|
|
159
|
+
const active = runInVm(['systemctl', 'is-active', `raytace-${svc}`], { check: false });
|
|
160
|
+
const isOk = active?.status === 0 && String(active.stdout).trim() === 'active';
|
|
161
|
+
row(isOk ? true : false, `raytace-${svc}`, isOk ? 'active' : `inactive (${String(active?.stdout ?? '').trim() || 'failed'})`, `sudo systemctl restart raytace-${svc}`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const sock = runInVm(['test', '-S', '/run/raytace/events.sock'], { check: false });
|
|
165
|
+
row(sock?.status === 0 ? true : false, 'collector socket', sock?.status === 0 ? '/run/raytace/events.sock exists' : 'missing /run/raytace/events.sock');
|
|
166
|
+
|
|
167
|
+
const firewall = runInVm(['sudo', 'iptables', '-S', 'DOCKER-USER'], { check: false });
|
|
168
|
+
const open = firewall?.status === 0 ? sandboxReach(String(firewall.stdout)) : null;
|
|
169
|
+
row(open?.length === 0, 'sandbox firewall', !open ? 'could not read the rules' : open.length ? `sandboxes can reach ${open.join(', ')} on this machine` : 'sandboxes reach only the bridge', 'sudo python3 /opt/raytace/network.py in VM');
|
|
170
|
+
} catch (err) {
|
|
171
|
+
row(false, 'vm diagnostics', `could not inspect VM: ${err.message}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return rows;
|
|
176
|
+
}
|