@raytrace-cli/cli 0.1.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/LICENSE +21 -0
- package/README.md +132 -0
- package/bin/raytrace.mjs +74 -0
- package/dist/dashboard/assets/index-BQ9_JxGq.js +27 -0
- package/dist/dashboard/assets/index-L5cUAvhE.css +1 -0
- package/dist/dashboard/favicon.svg +6 -0
- package/dist/dashboard/index.html +15 -0
- package/package.json +45 -0
- package/proxy/claude-code-adapter.mjs +239 -0
- package/proxy/claude-code-hook.mjs +20 -0
- package/proxy/codex-config.mjs +31 -0
- package/proxy/codex.mjs +13 -0
- package/proxy/evidence-store.mjs +285 -0
- package/proxy/execution-runner.mjs +89 -0
- package/proxy/experiment-engine.mjs +192 -0
- package/proxy/explanations.mjs +36 -0
- package/proxy/init-evidence-db.mjs +72 -0
- package/proxy/prompt-context.mjs +273 -0
- package/proxy/prompt-traces.mjs +34 -0
- package/proxy/providers.mjs +65 -0
- package/proxy/raytace-proxy.mjs +608 -0
- package/proxy/request-metrics.mjs +13 -0
- package/proxy/schema/agent_intent.sql +101 -0
- package/proxy/schema/auxiliary.sql +43 -0
- package/proxy/schema/shared_storage.sql +21 -0
- package/proxy/step-lab.mjs +78 -0
- package/proxy/summaries.mjs +151 -0
- package/proxy/tool-metadata.mjs +75 -0
- package/src/claude-code.mjs +56 -0
- package/src/commands.mjs +173 -0
- package/src/config.mjs +40 -0
- package/src/paths.mjs +26 -0
- package/src/prompt.mjs +42 -0
- package/src/proxy-process.mjs +101 -0
package/src/commands.mjs
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { accessSync, constants, existsSync, mkdirSync, rmSync, statSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { delimiter, join } from 'node:path';
|
|
5
|
+
import { paths } from './paths.mjs';
|
|
6
|
+
import { portOf, proxyEnv, readConfig, writeConfig } from './config.mjs';
|
|
7
|
+
import { healthy, portInUse, runningPid, start, status, stop } from './proxy-process.mjs';
|
|
8
|
+
import { HOOK_COMMAND, hookState, setHook } from './claude-code.mjs';
|
|
9
|
+
import { askSecret, confirm, interactive } from './prompt.mjs';
|
|
10
|
+
|
|
11
|
+
const say = (line = '') => console.log(line);
|
|
12
|
+
|
|
13
|
+
/** Whether `name` resolves on PATH: the Claude Code hook calls `raytrace` by name. */
|
|
14
|
+
function onPath(name) {
|
|
15
|
+
const exts = process.platform === 'win32' ? ['.cmd', '.exe', ''] : [''];
|
|
16
|
+
return (process.env.PATH || '').split(delimiter).some((dir) => exts.some((ext) => {
|
|
17
|
+
try { accessSync(join(dir, name + ext), constants.X_OK); return true; } catch { return false; }
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function openUrl(url) {
|
|
22
|
+
const [command, args] = process.platform === 'darwin' ? ['open', [url]]
|
|
23
|
+
: process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
|
|
24
|
+
spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => say(`Open ${url} in your browser.`)).unref();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const claudeCodePresent = () => onPath('claude') || existsSync(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'));
|
|
28
|
+
|
|
29
|
+
// ------------------------------------------------------------------ setup
|
|
30
|
+
|
|
31
|
+
export async function setup(flags) {
|
|
32
|
+
const yes = flags.yes || !interactive();
|
|
33
|
+
mkdirSync(paths.home, { recursive: true });
|
|
34
|
+
const config = readConfig();
|
|
35
|
+
say(`RayTrace setup. Settings go in ${paths.config}.\n`);
|
|
36
|
+
|
|
37
|
+
// Claude Code: recorded through its hook, no proxy routing needed.
|
|
38
|
+
const hooks = hookState();
|
|
39
|
+
let hookClaude = !flags['no-claude-code'];
|
|
40
|
+
if (hookClaude && !yes) hookClaude = await confirm(hooks.installed ? 'Keep recording Claude Code sessions?' : 'Record Claude Code sessions?', true);
|
|
41
|
+
else if (hookClaude && !claudeCodePresent()) hookClaude = false;
|
|
42
|
+
if (hookClaude) { const file = setHook(); say(` Claude Code: hook ${hooks.installed ? 'kept' : 'added'} in ${file}`); }
|
|
43
|
+
else if (hooks.installed) { setHook({ remove: true }); say(' Claude Code: hook removed'); }
|
|
44
|
+
else say(' Claude Code: not recorded');
|
|
45
|
+
if (hooks.repoHook) say(' Note: the RayTrace repo\'s own Claude Code hook is also installed; sessions will be reported by both.');
|
|
46
|
+
|
|
47
|
+
// OpenRouter powers step summaries and `raytrace codex`.
|
|
48
|
+
// Without it the proxy runs native: traces still record, those features are off.
|
|
49
|
+
let openrouter = flags['openrouter-key'] ?? config.OPENROUTER_API_KEY ?? '';
|
|
50
|
+
if (!yes && flags['openrouter-key'] === undefined) {
|
|
51
|
+
say('\n OpenRouter key: turns on step summaries and `raytrace codex`.');
|
|
52
|
+
const entered = await askSecret(` Paste it${openrouter ? ' (Enter keeps the current one)' : ' (Enter to skip)'}: `);
|
|
53
|
+
if (entered) openrouter = entered;
|
|
54
|
+
}
|
|
55
|
+
writeConfig({
|
|
56
|
+
...config,
|
|
57
|
+
RAYTACE_PROVIDER: openrouter ? 'openrouter' : 'native',
|
|
58
|
+
OPENROUTER_API_KEY: openrouter,
|
|
59
|
+
});
|
|
60
|
+
say(`\n Settings saved (only you can read ${paths.config}).`);
|
|
61
|
+
|
|
62
|
+
if (hookClaude && !onPath('raytrace')) {
|
|
63
|
+
say(`\n Warning: \`raytrace\` is not on your PATH, and Claude Code's hook runs \`${HOOK_COMMAND}\`.`);
|
|
64
|
+
say(' Install it globally so the hook can find it: npm install -g @raytrace/cli');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// A proxy this CLI started is restarted so the new settings apply.
|
|
68
|
+
const port = portOf(readConfig());
|
|
69
|
+
if (runningPid()) { await stop(); say('\nRestarting RayTrace with the new settings.'); await startCommand(); return; }
|
|
70
|
+
if (await healthy(port)) { say(`\nA RayTrace proxy started outside this CLI is answering on :${port}; stop it to use these settings.`); return; }
|
|
71
|
+
if (flags['no-start'] || (!yes && !(await confirm('\nStart RayTrace now?', true)))) { say('\nRun `raytrace start` when you are ready.'); return; }
|
|
72
|
+
await startCommand({ open: !yes });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// --------------------------------------------------------- start / stop / status
|
|
76
|
+
|
|
77
|
+
export async function startCommand({ open = false } = {}) {
|
|
78
|
+
const result = await start();
|
|
79
|
+
const url = `http://127.0.0.1:${result.port}`;
|
|
80
|
+
say(result.started ? `RayTrace is running: ${url}` : `RayTrace was already running: ${url}`);
|
|
81
|
+
if (!result.started && !result.pid) say(' (started outside this CLI, e.g. from the RayTrace repo; `raytrace stop` will not stop it)');
|
|
82
|
+
say(` Logs: ${paths.proxyLog}`);
|
|
83
|
+
if (open) openUrl(url);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function stopCommand() {
|
|
87
|
+
const result = await stop();
|
|
88
|
+
if (result.stopped) say(`RayTrace stopped (pid ${result.pid}).`);
|
|
89
|
+
else if (result.foreign) say(`A RayTrace proxy not started by this CLI is answering on :${result.port}. Stop it where it was started.`);
|
|
90
|
+
else say('RayTrace is not running.');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function statusCommand() {
|
|
94
|
+
const state = await status();
|
|
95
|
+
const hooks = hookState();
|
|
96
|
+
say(`proxy ${state.healthy ? `running ${state.url}${state.pid ? ` (pid ${state.pid})` : ' (started outside this CLI)'}` : state.pid ? `pid ${state.pid}, not answering` : 'stopped'}`);
|
|
97
|
+
say(`claude code ${hooks.installed ? 'recording' : 'not recorded (raytrace setup)'}`);
|
|
98
|
+
say(`data ${paths.home}`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function openCommand() {
|
|
102
|
+
const state = await status();
|
|
103
|
+
if (!state.healthy) { say('RayTrace is not running. Start it with `raytrace start`.'); process.exitCode = 1; return; }
|
|
104
|
+
openUrl(state.url);
|
|
105
|
+
say(`Opening ${state.url}`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ------------------------------------------------------------------ doctor
|
|
109
|
+
|
|
110
|
+
export async function doctor() {
|
|
111
|
+
let problems = 0;
|
|
112
|
+
const line = (ok, label, detail) => { if (ok === false) problems += 1; say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}`); };
|
|
113
|
+
const config = readConfig();
|
|
114
|
+
const port = portOf(config);
|
|
115
|
+
|
|
116
|
+
line(true, 'node', process.version);
|
|
117
|
+
if (!existsSync(paths.config)) line(false, 'settings', `missing; run \`raytrace setup\``);
|
|
118
|
+
else {
|
|
119
|
+
const mode = statSync(paths.config).mode & 0o777;
|
|
120
|
+
line(process.platform === 'win32' || (mode & 0o077) === 0, 'settings', `${paths.config}${(mode & 0o077) && process.platform !== 'win32' ? ` is readable by others (chmod 600 it)` : ''}`);
|
|
121
|
+
}
|
|
122
|
+
line(existsSync(paths.dashboard) ? true : false, 'dashboard', existsSync(paths.dashboard) ? 'built' : `missing from ${paths.dashboard}; reinstall`);
|
|
123
|
+
line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : 'no: Claude Code\'s hook cannot run it (npm install -g @raytrace/cli)');
|
|
124
|
+
|
|
125
|
+
const hooks = hookState();
|
|
126
|
+
line(hooks.installed ? true : null, 'claude code hook', hooks.installed ? `installed in ${hooks.file}` : 'not installed (raytrace setup)');
|
|
127
|
+
if (hooks.repoHook) line(null, 'repo hook', 'the RayTrace repo\'s hook is also installed; sessions are reported twice');
|
|
128
|
+
|
|
129
|
+
line(config.OPENROUTER_API_KEY ? true : null, 'openrouter', config.OPENROUTER_API_KEY ? 'key set: summaries and codex on' : 'no key: summaries and codex off');
|
|
130
|
+
|
|
131
|
+
const pid = runningPid();
|
|
132
|
+
if (await healthy(port)) line(true, 'proxy', `running on :${port}${pid ? ` (pid ${pid})` : ' (started outside this CLI)'}`);
|
|
133
|
+
else if (await portInUse(port)) line(false, 'proxy', `port ${port} is held by something that is not RayTrace`);
|
|
134
|
+
else line(null, 'proxy', `stopped (port ${port} free)`);
|
|
135
|
+
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');
|
|
136
|
+
|
|
137
|
+
say(problems ? `\n${problems} problem${problems === 1 ? '' : 's'} found.` : '\nNo problems found.');
|
|
138
|
+
if (problems) process.exitCode = 1;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ------------------------------------------------------------------ codex
|
|
142
|
+
|
|
143
|
+
export async function codex(args) {
|
|
144
|
+
const config = readConfig();
|
|
145
|
+
if (!config.OPENROUTER_API_KEY) { say('`raytrace codex` routes Codex through OpenRouter. Add a key with `raytrace setup` first.'); process.exitCode = 1; return; }
|
|
146
|
+
if (!(await healthy(portOf(config)))) await startCommand();
|
|
147
|
+
const child = spawn(process.execPath, [paths.codex, ...args], { stdio: 'inherit', env: proxyEnv(config) });
|
|
148
|
+
await new Promise((done) => child.on('exit', (code, signal) => { process.exitCode = code ?? (signal ? 1 : 0); done(); }));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ------------------------------------------------------------------ hook
|
|
152
|
+
|
|
153
|
+
/** Called by Claude Code on each hook event; must stay fast and silent. */
|
|
154
|
+
export async function hook(agent) {
|
|
155
|
+
if (agent !== 'claude-code') return;
|
|
156
|
+
try { process.env.RAYTACE_PORT = String(portOf(readConfig())); } catch { /* default port */ }
|
|
157
|
+
await import(paths.hook);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ------------------------------------------------------------------ uninstall
|
|
161
|
+
|
|
162
|
+
export async function uninstall(flags) {
|
|
163
|
+
const yes = flags.yes || !interactive();
|
|
164
|
+
const stopped = await stop();
|
|
165
|
+
if (stopped.stopped) say('Stopped RayTrace.');
|
|
166
|
+
if (hookState().installed) say(`Removed the Claude Code hook from ${setHook({ remove: true })}.`);
|
|
167
|
+
if (existsSync(paths.home)) {
|
|
168
|
+
const purge = flags.purge || (!yes && await confirm(`Delete ${paths.home} (recorded sessions and settings)?`, false));
|
|
169
|
+
if (purge) { rmSync(paths.home, { recursive: true, force: true }); say(`Deleted ${paths.home}.`); }
|
|
170
|
+
else say(`Kept ${paths.home}.`);
|
|
171
|
+
}
|
|
172
|
+
say('To remove the command itself: npm uninstall -g @raytrace/cli');
|
|
173
|
+
}
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// ~/.raytrace/config.env: the same KEY=value settings the proxy has always
|
|
2
|
+
// read from .env, kept in one place readable only by the user since it holds
|
|
3
|
+
// API keys.
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { parseEnv } from 'node:util';
|
|
6
|
+
import { DEFAULT_PORT, paths } from './paths.mjs';
|
|
7
|
+
|
|
8
|
+
export function readConfig() {
|
|
9
|
+
if (!existsSync(paths.config)) return {};
|
|
10
|
+
return parseEnv(readFileSync(paths.config, 'utf8'));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function writeConfig(values) {
|
|
14
|
+
mkdirSync(paths.home, { recursive: true });
|
|
15
|
+
const lines = Object.entries(values)
|
|
16
|
+
.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 });
|
|
19
|
+
chmodSync(paths.config, 0o600); // the mode above only applies when the file is new
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Single quotes are taken literally by parseEnv, so JSON values (a custom
|
|
23
|
+
// RAYTACE_OPENROUTER_MODELS) survive a round trip; double quotes otherwise.
|
|
24
|
+
function quote(value) {
|
|
25
|
+
if (!/[\s#"'`]/.test(value)) return value;
|
|
26
|
+
return value.includes("'") ? `"${value}"` : `'${value}'`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const portOf = (config) => Number(config.RAYTACE_PORT || DEFAULT_PORT);
|
|
30
|
+
|
|
31
|
+
/** The environment the proxy and the Codex launcher run with. */
|
|
32
|
+
export function proxyEnv(config = readConfig()) {
|
|
33
|
+
return {
|
|
34
|
+
...process.env,
|
|
35
|
+
...config,
|
|
36
|
+
RAYTACE_PORT: String(portOf(config)),
|
|
37
|
+
RAYTACE_DATA_DIR: paths.home,
|
|
38
|
+
RAYTACE_DASHBOARD_DIR: paths.dashboard,
|
|
39
|
+
};
|
|
40
|
+
}
|
package/src/paths.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Where everything lives. The package's own files are found relative to this
|
|
2
|
+
// one; the user's data in ~/.raytrace (RAYTRACE_HOME overrides it, which is
|
|
3
|
+
// also how to run a second, throwaway install side by side).
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const root = fileURLToPath(new URL('..', import.meta.url));
|
|
9
|
+
const home = process.env.RAYTRACE_HOME || join(homedir(), '.raytrace');
|
|
10
|
+
|
|
11
|
+
export const paths = {
|
|
12
|
+
root,
|
|
13
|
+
proxy: join(root, 'proxy', 'raytace-proxy.mjs'),
|
|
14
|
+
codex: join(root, 'proxy', 'codex.mjs'),
|
|
15
|
+
hook: join(root, 'proxy', 'claude-code-hook.mjs'),
|
|
16
|
+
dashboard: join(root, 'dist', 'dashboard'),
|
|
17
|
+
home,
|
|
18
|
+
config: join(home, 'config.env'),
|
|
19
|
+
logs: join(home, 'logs'),
|
|
20
|
+
proxyLog: join(home, 'logs', 'proxy.log'),
|
|
21
|
+
run: join(home, 'run'),
|
|
22
|
+
proxyPid: join(home, 'run', 'proxy.pid'),
|
|
23
|
+
database: join(home, 'evidence.db'),
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_PORT = 8797;
|
package/src/prompt.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Terminal questions for `raytrace setup`. Secrets are read with echo off so
|
|
2
|
+
// an API key never lands in the scrollback.
|
|
3
|
+
import { createInterface } from 'node:readline/promises';
|
|
4
|
+
|
|
5
|
+
export const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
6
|
+
|
|
7
|
+
export async function ask(question, fallback = '') {
|
|
8
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
9
|
+
try { return (await rl.question(question)).trim() || fallback; } finally { rl.close(); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function confirm(question, fallback = true) {
|
|
13
|
+
const answer = (await ask(`${question} ${fallback ? '[Y/n]' : '[y/N]'} `)).toLowerCase();
|
|
14
|
+
return answer ? answer.startsWith('y') : fallback;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function askSecret(question) {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
const { stdin, stdout } = process;
|
|
20
|
+
let value = '';
|
|
21
|
+
stdout.write(question);
|
|
22
|
+
stdin.setRawMode(true);
|
|
23
|
+
stdin.resume();
|
|
24
|
+
stdin.setEncoding('utf8');
|
|
25
|
+
const done = (error) => {
|
|
26
|
+
stdin.setRawMode(false);
|
|
27
|
+
stdin.pause();
|
|
28
|
+
stdin.off('data', onData);
|
|
29
|
+
stdout.write('\n');
|
|
30
|
+
if (error) reject(error); else resolve(value.trim());
|
|
31
|
+
};
|
|
32
|
+
const onData = (chunk) => {
|
|
33
|
+
for (const char of chunk) {
|
|
34
|
+
if (char === '\r' || char === '\n') return done();
|
|
35
|
+
if (char === '\u0003') return done(new Error('Cancelled.')); // Ctrl-C
|
|
36
|
+
if (char === '\u007f' || char === '\b') { if (value) { value = value.slice(0, -1); stdout.write('\b \b'); } continue; }
|
|
37
|
+
if (char >= ' ') { value += char; stdout.write('*'); }
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
stdin.on('data', onData);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Starting, stopping and checking the background proxy. What scripts/lib.sh
|
|
2
|
+
// did in the repo, in Node so it needs neither bash nor curl.
|
|
3
|
+
//
|
|
4
|
+
// Health is an answered HTTP probe, never "a process exists": a wedged proxy,
|
|
5
|
+
// or a port held by something unrelated, both have a pid.
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, closeSync } from 'node:fs';
|
|
8
|
+
import { createConnection } from 'node:net';
|
|
9
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
10
|
+
import { paths } from './paths.mjs';
|
|
11
|
+
import { portOf, proxyEnv, readConfig } from './config.mjs';
|
|
12
|
+
|
|
13
|
+
export async function healthy(port) {
|
|
14
|
+
try {
|
|
15
|
+
const response = await fetch(`http://127.0.0.1:${port}/raytace/models`, { signal: AbortSignal.timeout(2000) });
|
|
16
|
+
return response.ok;
|
|
17
|
+
} catch { return false; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** True when anything at all is listening on the port. */
|
|
21
|
+
export function portInUse(port) {
|
|
22
|
+
return new Promise((done) => {
|
|
23
|
+
const socket = createConnection({ host: '127.0.0.1', port });
|
|
24
|
+
socket.once('connect', () => { socket.destroy(); done(true); });
|
|
25
|
+
socket.once('error', () => done(false));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function alive(pid) {
|
|
30
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The pid this CLI started, if that process is still running. */
|
|
34
|
+
export function runningPid() {
|
|
35
|
+
if (!existsSync(paths.proxyPid)) return null;
|
|
36
|
+
const pid = Number(readFileSync(paths.proxyPid, 'utf8').trim());
|
|
37
|
+
if (Number.isInteger(pid) && pid > 0 && alive(pid)) return pid;
|
|
38
|
+
rmSync(paths.proxyPid, { force: true });
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function status() {
|
|
43
|
+
const port = portOf(readConfig());
|
|
44
|
+
const pid = runningPid();
|
|
45
|
+
const ok = await healthy(port);
|
|
46
|
+
return { port, pid, healthy: ok, url: `http://127.0.0.1:${port}` };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function tail(file, lines = 8) {
|
|
50
|
+
try { return readFileSync(file, 'utf8').trimEnd().split('\n').slice(-lines).join('\n'); } catch { return ''; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Starts the proxy detached, logging to ~/.raytrace/logs/proxy.log, and waits
|
|
55
|
+
* until it answers. A healthy proxy already on the port is reused, whoever
|
|
56
|
+
* started it.
|
|
57
|
+
*/
|
|
58
|
+
export async function start() {
|
|
59
|
+
const config = readConfig();
|
|
60
|
+
const port = portOf(config);
|
|
61
|
+
if (await healthy(port)) return { started: false, port, pid: runningPid() };
|
|
62
|
+
if (await portInUse(port)) throw new Error(`Port ${port} is in use by something that is not answering as RayTrace. Free it, or set RAYTACE_PORT in ${paths.config}.`);
|
|
63
|
+
if (!existsSync(paths.dashboard)) throw new Error(`The dashboard is missing from ${paths.dashboard}. Reinstall @raytrace/cli.`);
|
|
64
|
+
|
|
65
|
+
mkdirSync(paths.logs, { recursive: true });
|
|
66
|
+
mkdirSync(paths.run, { recursive: true });
|
|
67
|
+
const log = openSync(paths.proxyLog, 'a');
|
|
68
|
+
writeFileSync(log, `\n=== ${new Date().toISOString()} starting on :${port} ===\n`);
|
|
69
|
+
// cwd is the data folder, so the proxy's own .env lookup finds nothing there
|
|
70
|
+
// and every setting comes from config.env through the environment.
|
|
71
|
+
const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', paths.proxy], {
|
|
72
|
+
cwd: paths.home, env: proxyEnv(config), detached: true, stdio: ['ignore', log, log],
|
|
73
|
+
});
|
|
74
|
+
closeSync(log);
|
|
75
|
+
let exited = null;
|
|
76
|
+
child.once('exit', (code) => { exited = code ?? 1; });
|
|
77
|
+
child.unref();
|
|
78
|
+
writeFileSync(paths.proxyPid, `${child.pid}\n`);
|
|
79
|
+
|
|
80
|
+
for (let waited = 0; waited < 20_000; waited += 250) {
|
|
81
|
+
if (exited !== null) break;
|
|
82
|
+
if (await healthy(port)) return { started: true, port, pid: child.pid };
|
|
83
|
+
await sleep(250);
|
|
84
|
+
}
|
|
85
|
+
if (exited === null) try { process.kill(child.pid); } catch { /* already gone */ }
|
|
86
|
+
rmSync(paths.proxyPid, { force: true });
|
|
87
|
+
throw new Error(`The proxy did not come up. Last lines of ${paths.proxyLog}:\n${tail(paths.proxyLog)}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function stop() {
|
|
91
|
+
const pid = runningPid();
|
|
92
|
+
if (!pid) {
|
|
93
|
+
const { port, healthy: up } = await status();
|
|
94
|
+
return { stopped: false, foreign: up, port };
|
|
95
|
+
}
|
|
96
|
+
process.kill(pid, 'SIGTERM');
|
|
97
|
+
for (let waited = 0; waited < 5000 && alive(pid); waited += 100) await sleep(100);
|
|
98
|
+
if (alive(pid)) process.kill(pid, 'SIGKILL');
|
|
99
|
+
rmSync(paths.proxyPid, { force: true });
|
|
100
|
+
return { stopped: true, pid };
|
|
101
|
+
}
|