@raytrace-cli/cli 0.5.0 → 0.7.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.
Files changed (59) hide show
  1. package/README.md +54 -2
  2. package/bin/raytrace.mjs +81 -2
  3. package/dist/dashboard/assets/{index-jyV5iYHJ.js → index-Dc3LTk8b.js} +4 -4
  4. package/dist/dashboard/index.html +1 -1
  5. package/package.json +2 -1
  6. package/proxy/agent-intent-schema.test.mjs +142 -0
  7. package/proxy/call-assessment.test.mjs +167 -0
  8. package/proxy/capture.mjs +11 -4
  9. package/proxy/capture.test.mjs +49 -0
  10. package/proxy/claude-code-adapter.mjs +19 -0
  11. package/proxy/claude-code-hook.mjs +3 -1
  12. package/proxy/codex-config.mjs +5 -0
  13. package/proxy/codex.mjs +3 -2
  14. package/proxy/evidence-schema.test.mjs +233 -0
  15. package/proxy/evidence-store.mjs +91 -22
  16. package/proxy/evidence-store.test.mjs +304 -0
  17. package/proxy/exec-narrative.test.mjs +262 -0
  18. package/proxy/execution-correlation.test.mjs +146 -0
  19. package/proxy/execution-runner.test.mjs +38 -0
  20. package/proxy/experiment-engine.test.mjs +93 -0
  21. package/proxy/explanations.test.mjs +20 -0
  22. package/proxy/gvisor-forwarder.test.mjs +368 -0
  23. package/proxy/init-evidence-db.mjs +30 -0
  24. package/proxy/local-token.mjs +30 -0
  25. package/proxy/playground-recovery.test.mjs +130 -0
  26. package/proxy/playground.mjs +31 -3
  27. package/proxy/prompt-traces.test.mjs +32 -0
  28. package/proxy/providers.test.mjs +76 -0
  29. package/proxy/proxy.integration.test.mjs +135 -0
  30. package/proxy/raytace-proxy.mjs +58 -18
  31. package/proxy/request-metrics.test.mjs +19 -0
  32. package/proxy/request-policy.mjs +45 -0
  33. package/proxy/request-policy.test.mjs +47 -0
  34. package/proxy/sandbox-bridge.mjs +3 -0
  35. package/proxy/search.test.mjs +161 -0
  36. package/proxy/smoke.test.mjs +93 -0
  37. package/proxy/step-lab.test.mjs +38 -0
  38. package/proxy/summaries.test.mjs +69 -0
  39. package/proxy/tool-metadata.test.mjs +38 -0
  40. package/proxy/trace-view.mjs +50 -18
  41. package/proxy/trace-view.test.mjs +72 -0
  42. package/proxy/typesafe.test.mjs +39 -0
  43. package/src/api.mjs +57 -0
  44. package/src/auth.mjs +35 -1
  45. package/src/beta.mjs +96 -0
  46. package/src/claude-code.mjs +38 -1
  47. package/src/commands.mjs +69 -25
  48. package/src/config.mjs +16 -7
  49. package/src/export.mjs +200 -0
  50. package/src/lima.mjs +42 -1
  51. package/src/local-sandbox.mjs +19 -4
  52. package/src/paths.mjs +8 -8
  53. package/src/proxy-process.mjs +26 -3
  54. package/src/sandbox.mjs +73 -40
  55. package/src/upload.mjs +198 -0
  56. package/worker/sandbox/claude-hook.mjs +50 -17
  57. package/worker/sandbox/projects.py +3 -2
  58. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  59. package/worker/sandbox/viewer.py +21 -2
@@ -0,0 +1,39 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { typesafeConfig, systemOne } from './typesafe.mjs';
4
+
5
+ const reply = (status, body = {}, headers = {}) => new Response(JSON.stringify(body), { status, headers });
6
+
7
+ test('disabled without a key; defaults to jev-latest', () => {
8
+ assert.equal(typesafeConfig({}).enabled, false);
9
+ const config = typesafeConfig({ TYPESAFE_API_KEY: ' k ', RAYTACE_TYPESAFE_URL: 'http://x/' });
10
+ assert.deepEqual(config, { enabled: true, apiKey: 'k', model: 'jev-latest', url: 'http://x' });
11
+ });
12
+
13
+ test('sends the documented request shape with a bearer key', async () => {
14
+ let seen;
15
+ const fetchImpl = async (url, init) => { seen = { url, init }; return reply(200, { model: 'jev-1.13.0', answers: {}, usage: { input_tokens: 10 } }); };
16
+ const config = typesafeConfig({ TYPESAFE_API_KEY: 'k' });
17
+ const result = await systemOne(config, { state: { a: 1 }, questions: { q: { type: 'noul', instructions: 'x?' } } }, { fetchImpl });
18
+ assert.equal(seen.url, 'https://api.typesafe.ai/v1/systemone');
19
+ assert.equal(seen.init.headers.authorization, 'Bearer k');
20
+ assert.deepEqual(JSON.parse(seen.init.body), { model: 'jev-latest', state: { a: 1 }, questions: { q: { type: 'noul', instructions: 'x?' } } });
21
+ assert.equal(result.model, 'jev-1.13.0');
22
+ });
23
+
24
+ test('retries 429 and 529, but not other errors', async () => {
25
+ const config = typesafeConfig({ TYPESAFE_API_KEY: 'k' });
26
+ let calls = 0;
27
+ const flaky = async () => (++calls < 3 ? reply(calls === 1 ? 429 : 529, {}, { 'retry-after': '0.01' }) : reply(200, { answers: {} }));
28
+ await systemOne(config, { state: '', questions: {} }, { fetchImpl: flaky });
29
+ assert.equal(calls, 3);
30
+
31
+ calls = 0;
32
+ const invalid = async () => { calls += 1; return reply(422, { detail: 'bad question' }); };
33
+ await assert.rejects(systemOne(config, { state: '', questions: {} }, { fetchImpl: invalid }), (error) => error.status === 422 && /bad question/.test(error.message));
34
+ assert.equal(calls, 1);
35
+ });
36
+
37
+ test('refuses to call without a key', async () => {
38
+ await assert.rejects(systemOne(typesafeConfig({}), { state: '', questions: {} }), /TYPESAFE_API_KEY/);
39
+ });
package/src/api.mjs ADDED
@@ -0,0 +1,57 @@
1
+ // Shared client for RayTrace's cloud API (https://api.raytracer.si;
2
+ // RAYTRACE_API_URL points elsewhere). Requests carry your `raytrace auth
3
+ // login` token; RAYTRACE_API_KEY overrides it for a server running without
4
+ // accounts (development).
5
+ import { accessToken, consumeIdleNotice, login } from './auth.mjs';
6
+ import { readConfig } from './config.mjs';
7
+ import { interactive } from './prompt.mjs';
8
+
9
+ const say = (line = '') => console.log(line);
10
+ const API = 'https://api.raytracer.si';
11
+
12
+ export const unreachable = (url) => new Error(`Cannot reach RayTrace at ${url.origin}. Check your connection; `
13
+ + 'networks that inspect HTTPS (some company Wi-Fi) may block it.');
14
+
15
+ export class ApiError extends Error {
16
+ constructor(message, { status = null, data = {} } = {}) {
17
+ super(message);
18
+ this.name = 'ApiError';
19
+ this.status = status;
20
+ this.data = data;
21
+ }
22
+ }
23
+
24
+ /** True when a development API key overrides the signed-in account. */
25
+ export function hasApiKeyOverride() {
26
+ return Boolean(process.env.RAYTRACE_API_KEY || readConfig().RAYTRACE_API_KEY);
27
+ }
28
+
29
+ export async function api({ autoLogin = true } = {}) {
30
+ const config = readConfig();
31
+ const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
32
+ let key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
33
+ if (!key) {
34
+ if (!autoLogin || !interactive()) throw new Error('Not signed in. Run: raytrace auth login');
35
+ say(consumeIdleNotice()
36
+ ? 'You have not used RayTrace cloud for 2 days, so you need to sign in again.'
37
+ : 'You are not signed in to RayTrace yet.');
38
+ await login();
39
+ key = await accessToken();
40
+ if (!key) throw new Error('Not signed in. Run: raytrace auth login');
41
+ say();
42
+ }
43
+ return { url: new URL(url), key };
44
+ }
45
+
46
+ export async function call(method, path, { body, headers = {}, autoLogin = true } = {}) {
47
+ const { url, key } = await api({ autoLogin });
48
+ let response;
49
+ try {
50
+ response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
51
+ } catch {
52
+ throw unreachable(url);
53
+ }
54
+ const data = await response.json().catch(() => ({}));
55
+ if (!response.ok) throw new ApiError(data.error || `HTTP ${response.status}`, { status: response.status, data });
56
+ return data;
57
+ }
package/src/auth.mjs CHANGED
@@ -75,15 +75,42 @@ function keep(data) {
75
75
  access_token: data.access_token, refresh_token: data.refresh_token,
76
76
  user: { id: data.user?.id, email: data.user?.email, name: [data.user?.first_name, data.user?.last_name].filter(Boolean).join(' ') },
77
77
  organization_id: data.organization_id ?? null,
78
+ last_used_at: Date.now(),
78
79
  };
79
80
  }
80
81
 
82
+ // Cloud use asks for a fresh sign-in after 2 idle days (sliding: any cloud
83
+ // command resets the clock). Local recording never consults this.
84
+ export const CLOUD_IDLE_LIMIT_MS = 2 * 86_400_000;
85
+ const TOUCH_EVERY_MS = 3_600_000; // last_used_at is rewritten at most hourly
86
+ let idleNotice = false;
87
+
88
+ export const isIdleExpired = (session, now = Date.now()) =>
89
+ Boolean(session?.last_used_at && now - session.last_used_at > CLOUD_IDLE_LIMIT_MS);
90
+
91
+ /** True once after accessToken() dropped a session for idleness. */
92
+ export function consumeIdleNotice() { const was = idleNotice; idleNotice = false; return was; }
93
+
81
94
  /** A current access token, refreshed when it is about to expire; null when signed out. */
82
95
  export async function accessToken() {
83
96
  const session = load();
84
97
  if (!session?.access_token) return null;
98
+ if (isIdleExpired(session)) {
99
+ // Idle too long: drop the session so the cloud path starts a fresh
100
+ // sign-in and continues (it says why via consumeIdleNotice()).
101
+ forget();
102
+ idleNotice = true;
103
+ return null;
104
+ }
85
105
  const { exp = 0 } = claims(session.access_token);
86
- if (exp * 1000 - Date.now() > 60_000) return session.access_token;
106
+ if (exp * 1000 - Date.now() > 60_000) {
107
+ // Sliding window: cloud use resets the idle clock (throttled writes;
108
+ // sessions saved before this field existed start their clock now).
109
+ if (!session.last_used_at || Date.now() - session.last_used_at > TOUCH_EVERY_MS) {
110
+ try { save({ ...session, last_used_at: Date.now() }); } catch { /* the token still works */ }
111
+ }
112
+ return session.access_token;
113
+ }
87
114
  if (!session.refresh_token) return null;
88
115
  const { status, data } = await workos('/authenticate', {
89
116
  grant_type: 'refresh_token', refresh_token: session.refresh_token, client_id: CLIENT_ID,
@@ -154,6 +181,13 @@ export async function status() {
154
181
  say(`Organization: ${org || session.organization_id || 'personal'}`);
155
182
  const left = Math.round((exp * 1000 - Date.now()) / 60000);
156
183
  say(left > 0 ? `Access token valid for ${left} more min; renewed automatically.` : 'Access token expired; it is renewed on the next command.');
184
+ // Beta is a cloud entitlement, separate from any local licence tier.
185
+ try {
186
+ const { betaStatus, formatCreditDeadline } = await import('./beta.mjs');
187
+ const beta = await betaStatus();
188
+ if (beta?.sandbox_consumed) say(`Beta: $10 credit used${beta.credited_sandbox_id ? ` on ${beta.credited_sandbox_id}` : ''}.`);
189
+ else if (beta?.entitled) say(`Beta: $${beta.credit_usd ?? 10} credit available${beta.credit_expires_at ? ` until ${formatCreditDeadline(beta.credit_expires_at)}` : ''} (raytrace sandbox create).`);
190
+ } catch { /* no beta entitlement, old backend, or offline: nothing to add */ }
157
191
  }
158
192
 
159
193
  export async function logout() {
package/src/beta.mjs ADDED
@@ -0,0 +1,96 @@
1
+ // `raytrace --code <code>`: redeem a single-use beta code handed out by
2
+ // RayTrace. Sign-in (`raytrace auth login`) is a prerequisite — this command
3
+ // never starts a sign-in flow and never sends the code anywhere until a
4
+ // signed-in account is known. The backend is the source of truth: on a
5
+ // successful redeem it deletes the code irreversibly and binds a $10
6
+ // OpenRouter credit (hard 3-day limit) to the signed-in account. Nothing
7
+ // about the code or entitlement is stored on this machine.
8
+ import { accessToken, consumeIdleNotice } from './auth.mjs';
9
+ import { call, hasApiKeyOverride } from './api.mjs';
10
+
11
+ const say = (line = '') => console.log(line);
12
+
13
+ export const normalizeBetaCode = (code) => String(code ?? '').trim().toUpperCase().replace(/\s+/g, '');
14
+
15
+ // Codes are minted only in the backend repo (raytrace:
16
+ // worker/gvisor/mint_beta_codes.py), which stores SHA-256 hashes of the
17
+ // normalized code in `beta_codes` and deletes the row on redemption. The
18
+ // shared contract: RTB-XXXX-XXXX-XXXX (Crockford Base32), normalized as
19
+ // above, 3-day expiry. This CLI only presents a code; it never mints one.
20
+
21
+ export function formatCreditDeadline(iso, now = Date.now()) {
22
+ if (!iso) return '';
23
+ const when = new Date(iso);
24
+ if (Number.isNaN(when.getTime())) return '';
25
+ const label = when.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
26
+ const ms = when.getTime() - now;
27
+ if (ms <= 0) return `${label} (expired)`;
28
+ const hours = Math.round(ms / 3_600_000);
29
+ return `${label} (about ${hours <= 1 ? '1 hour' : `${hours} hours`} left)`;
30
+ }
31
+
32
+ /** Signed-in check that never starts a login flow and never touches a code. */
33
+ export async function ensureSignedIn(getToken = accessToken) {
34
+ if (hasApiKeyOverride()) return;
35
+ const token = await getToken();
36
+ if (!token) {
37
+ throw new Error(consumeIdleNotice()
38
+ ? 'You have not used RayTrace cloud for 2 days, so you need to sign in again. Run: raytrace auth login, then re-run: raytrace --code <your-code>'
39
+ : 'Not signed in. Run: raytrace auth login, then re-run: raytrace --code <your-code>');
40
+ }
41
+ }
42
+
43
+ export async function betaStatus(apiCall = call) {
44
+ return apiCall('GET', '/v1/beta/status', { autoLogin: false });
45
+ }
46
+
47
+ function redeemError(error) {
48
+ switch (error?.status) {
49
+ case 401: return new Error('Not signed in. Run: raytrace auth login, then re-run: raytrace --code <your-code>');
50
+ case 422: return new Error("That code isn't valid. Check it and try again, or ask RayTrace for a new one.");
51
+ case 410: return new Error('That code has expired (codes must be redeemed within 3 days). Ask RayTrace for a new one.');
52
+ case 409: return new Error('This account already has beta credit, so this code was not used. '
53
+ + 'It can still be given to someone else until it expires.');
54
+ case 429: return new Error('Too many code attempts. Wait a while and try again.');
55
+ default: return null;
56
+ }
57
+ }
58
+
59
+ export async function redeemBetaCode(rawCode, { ensure = ensureSignedIn, apiCall = call, log = say } = {}) {
60
+ const code = normalizeBetaCode(rawCode);
61
+ if (!code) throw new Error('Usage: raytrace --code <code>');
62
+ // Prerequisite first: an unauthenticated attempt must not consume,
63
+ // validate, or delete the code on the backend.
64
+ await ensure();
65
+ let data;
66
+ try {
67
+ data = await apiCall('POST', '/v1/beta/redeem', {
68
+ body: JSON.stringify({ code }),
69
+ headers: { 'content-type': 'application/json' },
70
+ autoLogin: false,
71
+ });
72
+ } catch (error) {
73
+ const mapped = redeemError(error);
74
+ if (mapped) throw mapped;
75
+ // The code is deleted on success, so a lost response looks like a
76
+ // failure here while the entitlement already exists. Check before
77
+ // reporting failure; the entitlement is what the user needs.
78
+ try {
79
+ const status = await betaStatus(apiCall);
80
+ if (status?.entitled) {
81
+ log("You're already good for beta testing: this account has its beta credit.");
82
+ if (status.credit_expires_at) log(`Use it by ${formatCreditDeadline(status.credit_expires_at)}: raytrace sandbox create`);
83
+ return status;
84
+ }
85
+ } catch { /* fall through to the original error */ }
86
+ throw error;
87
+ }
88
+ const credit = data?.credit_usd ?? 10;
89
+ log(`You're good for beta testing: $${credit} of Claude Code credit (via OpenRouter) is on this account.`);
90
+ log('Your account now shows as Beta in the RayTrace dashboard.');
91
+ if (data?.credit_expires_at) {
92
+ log(`Hard limit: create your sandbox and use the credit by ${formatCreditDeadline(data.credit_expires_at)}. Unused credit expires.`);
93
+ }
94
+ log('Next, from a Git repository: raytrace sandbox create');
95
+ return data;
96
+ }
@@ -33,7 +33,44 @@ function allHooks(settings) {
33
33
  export function hookState() {
34
34
  const settings = readSettings();
35
35
  const hooks = allHooks(settings);
36
- return { file: settingsFile(), installed: EVENTS.every((event) => (settings.hooks?.[event] ?? []).some((group) => (group.hooks ?? []).some(isOurs))), repoHook: hooks.some(isRepoHook) };
36
+ const repoHook = hooks.some(isRepoHook);
37
+
38
+ const missingEvents = [];
39
+ let invalidType = false;
40
+ let invalidMatcher = false;
41
+ let duplicates = false;
42
+
43
+ for (const event of EVENTS) {
44
+ const groups = settings.hooks?.[event] ?? [];
45
+ let count = 0;
46
+
47
+ for (const group of groups) {
48
+ for (const hook of group.hooks ?? []) {
49
+ if (isOurs(hook)) {
50
+ count += 1;
51
+ if (hook.type !== 'command') invalidType = true;
52
+ if (event === 'PostToolUse' && group.matcher && group.matcher !== '*') invalidMatcher = true;
53
+ }
54
+ }
55
+ }
56
+
57
+ if (count === 0) missingEvents.push(event);
58
+ else if (count > 1) duplicates = true;
59
+ }
60
+
61
+ const installed = missingEvents.length === 0;
62
+ const valid = installed && !invalidType && !invalidMatcher && !duplicates;
63
+
64
+ return {
65
+ file: settingsFile(),
66
+ installed,
67
+ valid,
68
+ missingEvents,
69
+ invalidType,
70
+ invalidMatcher,
71
+ duplicates,
72
+ repoHook
73
+ };
37
74
  }
38
75
 
39
76
  /** Installs (or with remove, removes) the hook. Returns the settings file. */
package/src/commands.mjs CHANGED
@@ -4,7 +4,7 @@ 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
9
  import { askSecret, confirm, interactive } from './prompt.mjs';
10
10
 
@@ -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.
@@ -80,7 +80,8 @@ export async function startCommand({ open = false } = {}) {
80
80
  : result.started ? `RayTrace is running: ${url}` : `RayTrace was already running: ${url}`);
81
81
  if (!result.started && !result.pid) say(' (started outside this CLI, e.g. from the RayTrace repo; `raytrace stop` will not stop it)');
82
82
  say(` Logs: ${paths.proxyLog}`);
83
- if (open) openUrl(url);
83
+ if (open) openUrl(await dashboardLink(result.port));
84
+ else say(' Open the dashboard with: raytrace open');
84
85
  }
85
86
 
86
87
  export async function stopCommand() {
@@ -101,7 +102,8 @@ export async function statusCommand() {
101
102
  export async function openCommand() {
102
103
  const state = await status();
103
104
  if (!state.healthy) { say('RayTrace is not running. Start it with `raytrace start`.'); process.exitCode = 1; return; }
104
- openUrl(state.url);
105
+ if (state.pid && await proxyApi(state.port) < PROXY_API) await start();
106
+ openUrl(await dashboardLink(state.port));
105
107
  say(`Opening ${state.url}`);
106
108
  }
107
109
 
@@ -160,40 +162,82 @@ export async function keyCommand(which, flags) {
160
162
  export async function doctor() {
161
163
  let problems = 0;
162
164
  const line = (ok, label, detail) => { if (ok === false) problems += 1; say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}`); };
163
- const config = readConfig();
165
+ let config;
166
+ try { config = readConfig(); } catch (err) { config = {}; line(false, 'settings', `malformed config: ${err.message}`); }
164
167
  const port = portOf(config);
165
168
 
166
169
  line(true, 'node', process.version);
167
170
  if (!existsSync(paths.config)) line(false, 'settings', `missing; run \`raytrace setup\``);
168
171
  else {
169
- const mode = statSync(paths.config).mode & 0o777;
170
- line(process.platform === 'win32' || (mode & 0o077) === 0, 'settings', `${paths.config}${(mode & 0o077) && process.platform !== 'win32' ? ` is readable by others (chmod 600 it)` : ''}`);
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
+ }
171
178
  }
172
179
  line(existsSync(paths.dashboard) ? true : false, 'dashboard', existsSync(paths.dashboard) ? 'built' : `missing from ${paths.dashboard}; reinstall`);
173
- line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : 'no: Claude Code\'s hook cannot run it (npm install -g @raytrace/cli)');
174
-
175
- const hooks = hookState();
176
- line(hooks.installed ? true : null, 'claude code hook', hooks.installed ? `installed in ${hooks.file}` : 'not installed (raytrace setup)');
177
- if (hooks.repoHook) line(null, 'repo hook', 'the RayTrace repo\'s hook is also installed; sessions are reported twice');
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)');
181
+
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
+ }
178
200
 
179
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)');
180
202
 
181
- const pid = runningPid();
182
- if (await healthy(port)) line(true, 'proxy', `running on :${port}${pid ? ` (pid ${pid})` : ' (started outside this CLI)'}`);
183
- else if (await portInUse(port)) line(false, 'proxy', `port ${port} is held by something that is not RayTrace`);
184
- else line(null, 'proxy', `stopped (port ${port} free)`);
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
+ }
211
+
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
+ }
224
+
185
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');
186
226
 
187
227
  // Local sandboxes are optional: what they lack is shown, not counted as a problem.
188
228
  say('\nLocal sandboxes (raytrace sandbox create --local):');
189
- const { checks } = await import('./lima.mjs');
190
- const { vmStatus } = await import('./local-sandbox.mjs');
191
- let vm = null;
192
- try { vm = vmStatus(); } catch { /* no Lima yet */ }
193
- const rows = await checks({ vmRunning: vm === 'Running' });
194
- for (const { ok, label, detail, fix } of rows) say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}${fix ? `\n ${''.padEnd(22)} fix: ${fix}` : ''}`);
195
- if (vm) say(`· ${'vm'.padEnd(22)} raytrace: ${vm.toLowerCase()}`);
196
- else if (rows.every((row) => row.ok !== false)) say(`· ${'vm'.padEnd(22)} not created yet; the first local sandbox makes it`);
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
+ }
197
241
 
198
242
  say(problems ? `\n${problems} problem${problems === 1 ? '' : 's'} found.` : '\nNo problems found.');
199
243
  if (problems) process.exitCode = 1;
@@ -237,5 +281,5 @@ export async function uninstall(flags) {
237
281
  }
238
282
  else say(`Kept ${paths.home}.`);
239
283
  }
240
- say('To remove the command itself: npm uninstall -g @raytrace/cli');
284
+ say('To remove the command itself: npm uninstall -g @raytrace-cli/cli');
241
285
  }
package/src/config.mjs CHANGED
@@ -11,19 +11,28 @@ export function readConfig() {
11
11
  }
12
12
 
13
13
  export function writeConfig(values) {
14
- mkdirSync(paths.home, { recursive: true });
15
- const lines = Object.entries(values)
14
+ const entries = Object.entries(values)
16
15
  .filter(([, value]) => value !== undefined && value !== '')
17
- .map(([key, value]) => `${key}=${quote(String(value))}`);
18
- writeFileSync(paths.config, `# RayTrace settings. Restart with \`raytrace stop && raytrace start\` after editing.\n${lines.join('\n')}\n`, { mode: 0o600 });
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
- // Single quotes are taken literally by parseEnv, so JSON values (a custom
23
- // RAYTACE_OPENROUTER_MODELS) survive a round trip; double quotes otherwise.
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
- return value.includes("'") ? `"${value}"` : `'${value}'`;
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);