@raytrace-cli/cli 0.1.0 → 0.2.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 CHANGED
@@ -1,20 +1,41 @@
1
1
  # RayTrace
2
2
 
3
- See what your coding agent actually did. RayTrace records every prompt you
4
- give Claude Code or Codex, every tool call the agent made on the way to its
5
- answer, what each step cost, and what the model had in front of it when it
6
- decided. You browse all of it in a dashboard on your own machine.
3
+ **See what your coding agent actually did.**
7
4
 
8
- Everything stays on your computer. Your sessions are not sent anywhere unless you
9
- turn on the optional AI features (see [Privacy](#privacy)).
5
+ [ npm package ](https://www.npmjs.com/package/@raytrace-cli/cli) ·
6
+ [ Quick start ](#quick-start) · [ Dashboard tour ](#dashboard-tour) ·
7
+ [ Privacy ](#privacy) · [ Report an issue ](https://github.com/Godcreatebugs/raytrace-cli/issues)
10
8
 
11
- ## Install
9
+ Your agent finished the task. Which files did it read? What commands did it run?
10
+ Where did the tokens and money go?
11
+
12
+ RayTrace turns Claude Code and Codex sessions into a dashboard you can explore
13
+ on your own machine: prompts, answers, tool calls, cost, and captured context.
14
+
15
+ ![RayTrace tool-call timeline showing commands, reported results, cost, time, and token usage](https://raw.githubusercontent.com/Godcreatebugs/raytrace-cli/main/docs/images/tool-calls.jpg)
16
+
17
+ *One real coding task: 50 model round trips, 58 tool calls, and a command-by-command record.*
18
+
19
+ - **Follow the work.** Open a prompt and trace the steps that led to its answer.
20
+ - **Inspect the evidence.** Expand tool calls to see commands and their reported output.
21
+ - **Understand the cost.** See model, token usage, time, and cost when available.
22
+ - **Explore the context.** Review earlier conversation and files brought into the task.
23
+
24
+ Session capture and the dashboard work locally. Claude Code recording needs no
25
+ OpenRouter key; optional AI summaries and the Codex launcher do. See [Privacy](#privacy)
26
+ for what those features send outside your machine.
27
+
28
+ **New: [cloud sandboxes](#cloud-sandboxes-preview) (preview).** Run your agent
29
+ in an isolated sandbox on RayTrace's servers instead of your laptop, and review
30
+ every session with your team at [app.raytracer.si](https://app.raytracer.si).
31
+
32
+ ## Quick start
12
33
 
13
34
  You need **Node.js 22.13 or newer** (`node --version`). macOS and Linux are
14
35
  supported.
15
36
 
16
37
  ```sh
17
- npm install -g @raytrace/cli
38
+ npm install -g @raytrace-cli/cli
18
39
  raytrace setup
19
40
  ```
20
41
 
@@ -24,34 +45,98 @@ raytrace setup
24
45
  `~/.claude/settings.json`. Your other settings and hooks are left as they
25
46
  are, and the previous file is kept as `settings.json.raytrace-backup`.
26
47
  2. **An OpenRouter API key** (optional, Enter to skip). It turns on one-line
27
- step summaries and `raytrace codex`. Everything else works without it.
48
+ step summaries and `raytrace codex`.
28
49
 
29
- Then it starts RayTrace and opens the dashboard at http://127.0.0.1:8797.
50
+ Then it starts RayTrace and opens the dashboard at **http://127.0.0.1:8797**.
30
51
 
31
- Install globally (`-g`) rather than running it with `npx`: the Claude Code hook
32
- runs the `raytrace` command, so it has to stay on your PATH.
52
+ Install globally (`-g`): the Claude Code hook runs the `raytrace` command, so it
53
+ has to stay on your PATH.
33
54
 
34
- ## Use
55
+ ### See your first trace
35
56
 
36
- Use Claude Code as you normally do. Each prompt shows up in the dashboard a
37
- moment after the agent answers.
57
+ Use Claude Code as you normally do. Try a small task such as:
38
58
 
39
- | Section | What it answers |
40
- |---|---|
41
- | **Prompts** | What you asked and what came back, with a year of activity at a glance |
42
- | **Tool calls** | How the agent got there: every round trip to the model and every tool call, with cost, time and tokens, as a list or a graph |
43
- | **Context** | What the model was working from: earlier prompts, files it read, and how full its context window was |
59
+ > List the files in this project and explain where the main entry point is.
44
60
 
45
- For Codex, start it through RayTrace instead of directly (needs the OpenRouter
46
- key):
61
+ After the agent answers, open **Prompts** in the dashboard. Select your prompt,
62
+ then choose **Tool calls** to follow the work or **Context** to inspect what
63
+ was brought into the task.
64
+
65
+ For Codex, add an OpenRouter key during setup and start it through RayTrace:
47
66
 
48
67
  ```sh
49
- raytrace codex # any Codex arguments work after it
68
+ raytrace codex # pass Codex arguments after this command
50
69
  ```
51
70
 
71
+ ## Dashboard tour
72
+
73
+ ### Prompts — find the conversation
74
+
75
+ Browse your prompt history, revisit answers, and see activity across the year.
76
+ Each prompt links to its tool calls and context, with model and cost information
77
+ alongside it when available.
78
+
79
+ ![RayTrace prompt history with an activity calendar and real Claude Code tasks](https://raw.githubusercontent.com/Godcreatebugs/raytrace-cli/main/docs/images/prompts.jpg)
80
+
81
+ ### Tool calls — follow each step
82
+
83
+ The timeline shows the commands the agent chose, their reported results, and
84
+ metrics for each model round trip. Expand a row for details, group similar steps,
85
+ or switch to **Graph** to follow the sequence visually.
86
+
87
+ ![RayTrace graph connecting three model requests with reported tool-call results and request metrics](https://raw.githubusercontent.com/Godcreatebugs/raytrace-cli/main/docs/images/trace-graph.jpg)
88
+
89
+ *Graph view works without AI summaries; an optional OpenRouter key adds short descriptions.*
90
+
91
+ ### Context — inspect what informed the answer
92
+
93
+ Explore earlier prompts, files read during the task, and captured internal
94
+ instructions. Open a file entry to inspect the text associated with it. Token
95
+ counts and file-use indicators help you explore what contributed to the context.
96
+
97
+ ![RayTrace context inspector showing file reads, estimated tokens, and an expanded file entry](https://raw.githubusercontent.com/Godcreatebugs/raytrace-cli/main/docs/images/context.jpg)
98
+
99
+ *Screenshots captured from RayTrace running locally in Brave with selected real
100
+ Claude Code transcript excerpts. Local paths are anonymized; prior conversation
101
+ was omitted from the screenshot dataset. Token estimates and Claude Code costs
102
+ are approximate; file reads inferred from shell commands are marked in the UI.*
103
+
104
+ ## Cloud sandboxes (preview)
105
+
106
+ A cloud sandbox is an isolated copy of your project on RayTrace's servers, with
107
+ a terminal you open from your machine. Run Claude Code or Codex inside it: what
108
+ the agent asked, the tool calls it made, and the commands that actually ran are
109
+ recorded for your organization.
110
+
111
+ ```sh
112
+ raytrace auth login # sign in once; a code opens in your browser
113
+ cd your-project # any Git repository
114
+ raytrace sandbox create # upload it to a new sandbox
115
+ raytrace sandbox shell # a terminal in the sandbox: run claude or codex there
116
+ ```
117
+
118
+ Then open **[app.raytracer.si](https://app.raytracer.si)** and sign in with the
119
+ same account to see your organization's prompts, sandboxes and tool calls.
120
+
121
+ - **What is uploaded:** the files Git would track in the repository (including
122
+ new files it does not ignore), without `.git`, dependencies such as
123
+ `node_modules`, build output, `.env*` files, private keys (`.pem`, `.key`,
124
+ `.p12`, `.pfx`) and common credential files (`.npmrc`, `.netrc`, `id_rsa`, …).
125
+ The upload is limited to 256 MiB. Review your project for secrets inside other
126
+ files before you upload.
127
+ - **Signing in to your agent:** sign in to Claude Code inside the sandbox as
128
+ you would on your machine. That sign-in stays in the sandbox until you
129
+ destroy it.
130
+ - **When you are done:** `raytrace sandbox stop` keeps the files;
131
+ `raytrace sandbox destroy` deletes them and any sign-in made inside. The
132
+ recorded sessions are kept for your organization.
133
+
134
+ Cloud sandboxes are a preview and may change; please
135
+ [report issues](https://github.com/Godcreatebugs/raytrace-cli/issues) you run into.
136
+
52
137
  ## Commands
53
138
 
54
- | Command | |
139
+ | Command | What it does |
55
140
  |---|---|
56
141
  | `raytrace setup` | one-time setup; run it again to change settings |
57
142
  | `raytrace start` | start recording in the background |
@@ -61,6 +146,12 @@ raytrace codex # any Codex arguments work after it
61
146
  | `raytrace doctor` | check the install without changing anything |
62
147
  | `raytrace codex [args]` | run Codex through RayTrace |
63
148
  | `raytrace uninstall` | remove the Claude Code hook; `--purge` also deletes recorded data |
149
+ | `raytrace auth login` | sign in to RayTrace (needed for cloud sandboxes); `status`, `logout` |
150
+ | `raytrace sandbox create` | upload this Git repository to a new cloud sandbox; `--name <name>` |
151
+ | `raytrace sandbox list` | your cloud sandboxes |
152
+ | `raytrace sandbox shell [id]` | open a terminal in a sandbox |
153
+ | `raytrace sandbox start\|stop [id]` | start or stop a sandbox; stopping keeps its files |
154
+ | `raytrace sandbox destroy [id]` | delete a sandbox; its recorded sessions are kept |
64
155
 
65
156
  ## Getting the most out of it
66
157
 
@@ -91,11 +182,23 @@ RayTrace at the same sessions and the records line up run for run.
91
182
  OpenRouter's public list of models once. That request carries none of your
92
183
  data.
93
184
 
185
+ Cloud sandboxes are different by design: they run on RayTrace's servers.
186
+
187
+ - `raytrace sandbox create` uploads your project (see
188
+ [what is uploaded](#cloud-sandboxes-preview)) to RayTrace.
189
+ - Inside a sandbox, the prompts, model requests and answers, tool calls and the
190
+ commands that run are recorded on RayTrace's servers for your organization.
191
+ Members of your organization can see them at app.raytracer.si; other
192
+ organizations cannot.
193
+ - `raytrace auth login` keeps your sign-in in the macOS Keychain or the Linux
194
+ secret service (a file readable only by you where neither is available), and
195
+ `raytrace auth logout` removes it.
196
+
94
197
  ## Uninstall
95
198
 
96
199
  ```sh
97
200
  raytrace uninstall --purge # removes the hook and ~/.raytrace
98
- npm uninstall -g @raytrace/cli
201
+ npm uninstall -g @raytrace-cli/cli
99
202
  ```
100
203
 
101
204
  ## Troubleshooting
@@ -106,6 +209,9 @@ background process logs to `~/.raytrace/logs/proxy.log`.
106
209
  - **Nothing shows up for Claude Code:** check `raytrace status` says
107
210
  "recording", and that `raytrace` is on your PATH (`which raytrace`). Sessions
108
211
  appear when the agent finishes a step, not while it is typing.
212
+ - **`Cannot reach RayTrace at https://api.raytracer.si`:** check your
213
+ connection. Networks that inspect HTTPS, such as some company Wi-Fi, can
214
+ block it; try another network.
109
215
  - **Port 8797 is in use:** set `RAYTACE_PORT=<port>` in `~/.raytrace/config.env`,
110
216
  then `raytrace stop && raytrace start`.
111
217
 
package/bin/raytrace.mjs CHANGED
@@ -15,10 +15,19 @@ Usage: raytrace <command>
15
15
  doctor check the install without changing anything
16
16
  codex [...] run Codex through RayTrace (needs an OpenRouter key)
17
17
  uninstall remove the Claude Code hook, optionally all recorded data
18
+ auth ... sign in to RayTrace: login, status, logout
19
+ sandbox ... cloud sandboxes: create, list, shell, start, stop, destroy
18
20
 
19
21
  Options for setup: --yes --no-claude-code --no-start --openrouter-key <key>
20
22
  Options for uninstall: --yes --purge (also delete ~/.raytrace)
21
23
 
24
+ Sandboxes (preview; sign in first with raytrace auth login):
25
+ raytrace sandbox create [--name <name>] upload this Git repository to a new sandbox
26
+ raytrace sandbox list
27
+ raytrace sandbox shell [id] a terminal in it; run claude or codex there
28
+ raytrace sandbox start|stop [id]
29
+ raytrace sandbox destroy [id] [--yes] delete it; recorded evidence is kept
30
+
22
31
  Data and settings live in ~/.raytrace (override with RAYTRACE_HOME).`;
23
32
 
24
33
  // node:sqlite, which the recorder stores everything in, needs 22.13.
@@ -48,6 +57,38 @@ const commands = await import('../src/commands.mjs');
48
57
  // `codex` passes everything after it straight to Codex.
49
58
  if (command === 'codex') { await commands.codex(rest); process.exit(); }
50
59
 
60
+ if (command === 'auth') {
61
+ const auth = await import('../src/auth.mjs');
62
+ const sub = rest[0];
63
+ const action = { login: auth.login, status: auth.status, logout: auth.logout }[sub];
64
+ if (!action) { console.error(`Usage: raytrace auth login | status | logout`); process.exit(2); }
65
+ try { await action(); process.exit(0); }
66
+ catch (error) { console.error(`raytrace auth ${sub}: ${error.message}`); process.exit(1); }
67
+ }
68
+
69
+ if (command === 'sandbox') {
70
+ const sandbox = await import('../src/sandbox.mjs');
71
+ let parsed;
72
+ try {
73
+ parsed = parseArgs({ args: rest, strict: true, allowPositionals: true, options: {
74
+ yes: { type: 'boolean', short: 'y' },
75
+ name: { type: 'string' },
76
+ } });
77
+ } catch (error) { console.error(`${error.message}\n\nRun \`raytrace help\` for usage.`); process.exit(2); }
78
+ const [sub, id] = parsed.positionals;
79
+ const action = {
80
+ create: () => sandbox.create(parsed.values),
81
+ list: () => sandbox.list(),
82
+ shell: () => sandbox.shell(id),
83
+ start: () => sandbox.start(id),
84
+ stop: () => sandbox.stop(id),
85
+ destroy: () => sandbox.destroy(id, parsed.values),
86
+ }[sub];
87
+ if (!action) { console.error(`Unknown sandbox command: ${sub ?? '(none)'}\n\n${HELP}`); process.exit(2); }
88
+ try { await action(); process.exit(0); }
89
+ catch (error) { console.error(`raytrace sandbox ${sub}: ${error.message}`); process.exit(1); }
90
+ }
91
+
51
92
  let flags;
52
93
  try {
53
94
  ({ values: flags } = parseArgs({ args: rest, strict: true, options: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "See what your coding agent did: traces, tool calls, cost and step-by-step evidence for Claude Code and Codex.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/auth.mjs ADDED
@@ -0,0 +1,153 @@
1
+ // `raytrace auth`: sign in to RayTrace with WorkOS's device login.
2
+ //
3
+ // `login` asks WorkOS for a short code, opens the approval page, and polls
4
+ // until the code is approved. The tokens never touch a file in plain text:
5
+ // they go in the macOS Keychain or the Linux secret service, and only fall
6
+ // back to a file readable by you alone (with a warning) where neither exists.
7
+ // The client id is public by design: a CLI cannot keep a secret.
8
+ import { spawn, spawnSync } from 'node:child_process';
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { hostname } from 'node:os';
11
+ import { join } from 'node:path';
12
+ import { paths } from './paths.mjs';
13
+
14
+ const say = (line = '') => console.log(line);
15
+ const WORKOS = 'https://api.workos.com/user_management';
16
+ export const CLIENT_ID = process.env.RAYTRACE_WORKOS_CLIENT_ID || 'client_01M4BC8GZZ9HG67EAV65SBRCPX';
17
+ const SERVICE = 'raytrace-cli';
18
+ const ACCOUNT = 'raytrace';
19
+ const FILE = join(paths.home, 'credentials.json');
20
+
21
+ // ------------------------------------------------------------- storage
22
+
23
+ function save(session) {
24
+ const value = Buffer.from(JSON.stringify(session)).toString('base64');
25
+ if (process.platform === 'darwin') {
26
+ // `security -i` reads its command from stdin, so the token never shows in a process list.
27
+ const result = spawnSync('security', ['-i'], { input: `add-generic-password -U -a ${ACCOUNT} -s ${SERVICE} -l "RayTrace CLI" -w ${value}\n`, encoding: 'utf8' });
28
+ if (result.status === 0 && !/error/i.test(result.stderr)) return 'the macOS Keychain';
29
+ } else if (spawnSync('secret-tool', ['--version']).status === 0) {
30
+ const result = spawnSync('secret-tool', ['store', '--label=RayTrace CLI', 'service', SERVICE, 'account', ACCOUNT], { input: value });
31
+ if (result.status === 0) return 'the system keyring';
32
+ }
33
+ mkdirSync(paths.home, { recursive: true });
34
+ writeFileSync(FILE, value, { mode: 0o600 });
35
+ chmodSync(FILE, 0o600);
36
+ return `${FILE} (no keychain found; readable only by you)`;
37
+ }
38
+
39
+ function load() {
40
+ let value = '';
41
+ if (process.platform === 'darwin') {
42
+ const result = spawnSync('security', ['find-generic-password', '-a', ACCOUNT, '-s', SERVICE, '-w'], { encoding: 'utf8' });
43
+ if (result.status === 0) value = result.stdout.trim();
44
+ } else if (spawnSync('secret-tool', ['--version']).status === 0) {
45
+ const result = spawnSync('secret-tool', ['lookup', 'service', SERVICE, 'account', ACCOUNT], { encoding: 'utf8' });
46
+ if (result.status === 0) value = result.stdout.trim();
47
+ }
48
+ if (!value && existsSync(FILE)) value = readFileSync(FILE, 'utf8').trim();
49
+ if (!value) return null;
50
+ try { return JSON.parse(Buffer.from(value, 'base64').toString('utf8')); } catch { return null; }
51
+ }
52
+
53
+ function forget() {
54
+ if (process.platform === 'darwin') spawnSync('security', ['delete-generic-password', '-a', ACCOUNT, '-s', SERVICE]);
55
+ else if (spawnSync('secret-tool', ['--version']).status === 0) spawnSync('secret-tool', ['clear', 'service', SERVICE, 'account', ACCOUNT]);
56
+ rmSync(FILE, { force: true });
57
+ }
58
+
59
+ // ------------------------------------------------------------- tokens
60
+
61
+ /** The access token's claims, read without verifying: RayTrace's API verifies. */
62
+ function claims(token) {
63
+ try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8')); } catch { return {}; }
64
+ }
65
+
66
+ async function workos(path, form) {
67
+ const response = await fetch(`${WORKOS}${path}`, {
68
+ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form),
69
+ });
70
+ return { status: response.status, data: await response.json().catch(() => ({})) };
71
+ }
72
+
73
+ function keep(data) {
74
+ return {
75
+ access_token: data.access_token, refresh_token: data.refresh_token,
76
+ user: { id: data.user?.id, email: data.user?.email, name: [data.user?.first_name, data.user?.last_name].filter(Boolean).join(' ') },
77
+ organization_id: data.organization_id ?? null,
78
+ };
79
+ }
80
+
81
+ /** A current access token, refreshed when it is about to expire; null when signed out. */
82
+ export async function accessToken() {
83
+ const session = load();
84
+ if (!session?.access_token) return null;
85
+ const { exp = 0 } = claims(session.access_token);
86
+ if (exp * 1000 - Date.now() > 60_000) return session.access_token;
87
+ if (!session.refresh_token) return null;
88
+ const { status, data } = await workos('/authenticate', {
89
+ grant_type: 'refresh_token', refresh_token: session.refresh_token, client_id: CLIENT_ID,
90
+ ...(session.organization_id ? { organization_id: session.organization_id } : {}),
91
+ });
92
+ if (status !== 200 || !data.access_token) {
93
+ throw new Error(`Your RayTrace sign-in expired and could not be renewed (${data.error_description || data.error || data.message || `HTTP ${status}`}). Run: raytrace auth login`);
94
+ }
95
+ save(keep(data));
96
+ return data.access_token;
97
+ }
98
+
99
+ // ------------------------------------------------------------- commands
100
+
101
+ function openUrl(url) {
102
+ const [command, args] = process.platform === 'darwin' ? ['open', [url]]
103
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
104
+ spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
105
+ }
106
+
107
+ export async function login() {
108
+ const start = await workos('/authorize/device', { client_id: CLIENT_ID });
109
+ if (start.status !== 200 || !start.data.device_code) {
110
+ throw new Error(`WorkOS refused to start the sign-in: ${start.data.error_description || start.data.message || `HTTP ${start.status}`}`);
111
+ }
112
+ const { device_code, user_code, verification_uri, verification_uri_complete } = start.data;
113
+ let interval = (start.data.interval || 5) * 1000;
114
+ const deadline = Date.now() + (start.data.expires_in || 300) * 1000;
115
+ say(`Your sign-in code: ${user_code}`);
116
+ say(`Opening ${verification_uri} to approve it (or open it yourself on any device).`);
117
+ openUrl(verification_uri_complete || verification_uri);
118
+ say('Waiting for approval...');
119
+ while (Date.now() < deadline) {
120
+ await new Promise((resolve) => setTimeout(resolve, interval));
121
+ const { status, data } = await workos('/authenticate', {
122
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code', device_code, client_id: CLIENT_ID,
123
+ device_id: hostname().slice(0, 100),
124
+ });
125
+ if (status === 200 && data.access_token) {
126
+ const where = save(keep(data));
127
+ say(`\nSigned in as ${data.user?.email}. Your sign-in is kept in ${where}.`);
128
+ return;
129
+ }
130
+ if (data.error === 'authorization_pending') continue;
131
+ if (data.error === 'slow_down') { interval += 5000; continue; }
132
+ if (data.error === 'access_denied') throw new Error('The sign-in was declined.');
133
+ if (data.error === 'expired_token') break;
134
+ throw new Error(`Sign-in failed: ${data.error_description || data.error || `HTTP ${status}`}`);
135
+ }
136
+ throw new Error('The code expired before it was approved. Run raytrace auth login again.');
137
+ }
138
+
139
+ export async function status() {
140
+ const session = load();
141
+ if (!session) { say('Not signed in. Run: raytrace auth login'); return; }
142
+ const { exp = 0, org_id: org } = claims(session.access_token);
143
+ say(`Signed in as ${session.user?.email}${session.user?.name ? ` (${session.user.name})` : ''}`);
144
+ say(`Organization: ${org || session.organization_id || 'personal'}`);
145
+ const left = Math.round((exp * 1000 - Date.now()) / 60000);
146
+ say(left > 0 ? `Access token valid for ${left} more min; renewed automatically.` : 'Access token expired; it is renewed on the next command.');
147
+ }
148
+
149
+ export async function logout() {
150
+ if (!load()) { say('Not signed in.'); return; }
151
+ forget();
152
+ say('Signed out: your RayTrace sign-in was removed from this machine.');
153
+ }
@@ -0,0 +1,178 @@
1
+ // `raytrace sandbox`: cloud sandboxes, through RayTrace's API
2
+ // (https://api.raytracer.si; RAYTRACE_API_URL points elsewhere).
3
+ //
4
+ // The project is packed here, so files that must stay on this machine never
5
+ // leave it, then uploaded once; RayTrace creates an isolated sandbox from it
6
+ // that records its Claude Code sessions. Requests carry your `raytrace auth
7
+ // login` token; RAYTRACE_API_KEY overrides it for a server running without
8
+ // accounts (development).
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { lstatSync } from 'node:fs';
11
+ import { request as httpRequest } from 'node:http';
12
+ import { request as httpsRequest } from 'node:https';
13
+ import { basename, join } from 'node:path';
14
+ import { accessToken } from './auth.mjs';
15
+ import { readConfig } from './config.mjs';
16
+ import { ask, interactive } from './prompt.mjs';
17
+
18
+ const say = (line = '') => console.log(line);
19
+ const MAX_BYTES = 256 * 1024 * 1024;
20
+ const ID = /^rtp-[a-f0-9]{32}$/;
21
+ const API = 'https://api.raytracer.si';
22
+ const unreachable = (url) => new Error(`Cannot reach RayTrace at ${url.origin}. Check your connection; `
23
+ + 'networks that inspect HTTPS (some company Wi-Fi) may block it.');
24
+
25
+ // Never packed: version control, dependencies and build output (rebuilt in the
26
+ // sandbox), and files that usually hold credentials.
27
+ const EXCLUDED = new Set(['.git', '.raytace', '.raytrace', '.ssh', '.aws', '.azure', '.config', 'node_modules', '.venv',
28
+ '__pycache__', '.next', '.vinext', 'dist', 'coverage', '.wrangler', '.DS_Store']);
29
+ const SECRET_NAMES = new Set(['.npmrc', '.netrc', '.pypirc', 'credentials', 'auth.json', 'id_rsa', 'id_ed25519']);
30
+ const SECRET_EXTENSIONS = /\.(pem|key|p12|pfx)$/i;
31
+
32
+ export function packable(path) {
33
+ const parts = path.split('/');
34
+ const name = parts.at(-1);
35
+ return !parts.some((part) => EXCLUDED.has(part) || part === '..') && !path.startsWith('/')
36
+ && !name.startsWith('.env') && !SECRET_EXTENSIONS.test(name) && !SECRET_NAMES.has(name);
37
+ }
38
+
39
+ async function api() {
40
+ const config = readConfig();
41
+ const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
42
+ const key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
43
+ if (!key) throw new Error('Not signed in. Run: raytrace auth login');
44
+ return { url: new URL(url), key };
45
+ }
46
+
47
+ async function call(method, path, { body, headers = {} } = {}) {
48
+ const { url, key } = await api();
49
+ let response;
50
+ try {
51
+ response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
52
+ } catch {
53
+ throw unreachable(url);
54
+ }
55
+ const data = await response.json().catch(() => ({}));
56
+ if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
57
+ return data;
58
+ }
59
+
60
+ /** The project's files git would track, minus what must not leave this machine. */
61
+ function projectFiles(root) {
62
+ const listed = spawnSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { maxBuffer: 256 * 1024 * 1024 });
63
+ if (listed.status !== 0) throw new Error(`${root} is not a Git repository. Run this from inside one.`);
64
+ const files = []; const skipped = []; let total = 0;
65
+ for (const name of [...new Set(listed.stdout.toString().split('\0').filter(Boolean))].sort()) {
66
+ let stat;
67
+ try { stat = lstatSync(join(root, name)); } catch { continue; } // deleted, still in the index
68
+ if (!packable(name) || !stat.isFile()) { skipped.push(name); continue; } // symlinks too
69
+ total += stat.size;
70
+ if (total > MAX_BYTES) throw new Error('The project is over 256 MiB; add large generated files to .gitignore first.');
71
+ files.push(name);
72
+ }
73
+ return { files, skipped, total };
74
+ }
75
+
76
+ function pack(root, files) {
77
+ return new Promise((resolve, reject) => {
78
+ // Extended attributes stay here: macOS tags nearly every file (com.apple.provenance),
79
+ // and bsdtar would also add AppleDouble files for them.
80
+ const mac = process.platform === 'darwin' ? ['--no-mac-metadata', '--no-xattrs'] : [];
81
+ const tar = spawn('tar', ['-czf', '-', ...mac, '--no-recursion', '--null', '-T', '-'],
82
+ { cwd: root, env: { ...process.env, COPYFILE_DISABLE: '1' }, stdio: ['pipe', 'pipe', 'pipe'] });
83
+ const chunks = []; let error = '';
84
+ tar.stdout.on('data', (chunk) => chunks.push(chunk));
85
+ tar.stderr.on('data', (chunk) => { error += chunk; });
86
+ tar.on('error', reject);
87
+ tar.on('close', (code) => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`tar failed: ${error.trim()}`)));
88
+ tar.stdin.end(files.map((name) => `${name}\0`).join(''));
89
+ });
90
+ }
91
+
92
+ async function pickId(id) {
93
+ if (id) {
94
+ if (!ID.test(id)) throw new Error(`Not a sandbox id: ${id}`);
95
+ return id;
96
+ }
97
+ const live = (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
98
+ if (live.length === 1) return live[0].id;
99
+ throw new Error(live.length ? 'More than one sandbox; name one (raytrace sandbox list).' : 'No sandboxes yet: raytrace sandbox create');
100
+ }
101
+
102
+ export async function create(flags) {
103
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' });
104
+ if (top.status !== 0) throw new Error('Run this from inside a Git repository.');
105
+ const root = top.stdout.trim();
106
+ const name = flags.name || basename(root);
107
+ const { files, skipped, total } = projectFiles(root);
108
+ if (!files.length) throw new Error('Nothing to upload.');
109
+ say(`Packing ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}`);
110
+ if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
111
+ const archive = await pack(root, files);
112
+ say('Creating the sandbox (the first one on a host takes a little longer)...');
113
+ const box = await call('POST', '/v1/sandboxes', {
114
+ body: archive, headers: { 'content-type': 'application/gzip', 'x-raytrace-name': name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) },
115
+ });
116
+ say(`\nSandbox ${box.id} is running.`);
117
+ say(box.transcripts ? 'Claude Code sessions in it are recorded.'
118
+ : `Claude Code transcripts are off: ${box.transcripts_off}. Commands are still recorded.`);
119
+ say(`Open it: raytrace sandbox shell ${box.id}`);
120
+ }
121
+
122
+ export async function list() {
123
+ const boxes = (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
124
+ if (!boxes.length) { say('No sandboxes. Create one from a Git repository: raytrace sandbox create'); return; }
125
+ for (const box of boxes) {
126
+ // The sandbox's creation time (seconds), or its container's once that is known.
127
+ const created = typeof box.created === 'number' ? box.created * 1000 : Date.parse(box.created);
128
+ const age = Math.round((Date.now() - created) / 60000);
129
+ say(`${box.id} ${String(box.status).padEnd(8)} ${box.name} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
130
+ }
131
+ }
132
+
133
+ export async function start(id) { const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/start`); say(`${box.id} running`); }
134
+ export async function stop(id) { const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/stop`); say(`${box.id} stopped; its files are kept`); }
135
+
136
+ export async function destroy(id, flags) {
137
+ id = await pickId(id);
138
+ if (!flags.yes) {
139
+ if (!interactive()) throw new Error('Pass --yes to destroy without a prompt.');
140
+ say(`This deletes ${id}: its files, and any sign-in made inside it. Recorded evidence is kept.`);
141
+ if ((await ask('Type the sandbox id to confirm: ')) !== id) { say('Not destroyed.'); return; }
142
+ }
143
+ await call('DELETE', `/v1/sandboxes/${id}`);
144
+ say(`${id} destroyed.`);
145
+ }
146
+
147
+ /** An interactive terminal in the sandbox, carried over one upgraded HTTP request. */
148
+ export async function shell(id) {
149
+ id = await pickId(id);
150
+ if (!interactive()) throw new Error('raytrace sandbox shell needs a terminal.');
151
+ const { url, key } = await api();
152
+ const { stdin, stdout } = process;
153
+ const path = `/v1/sandboxes/${id}/shell?rows=${stdout.rows || 24}&cols=${stdout.columns || 80}`;
154
+ await new Promise((resolve, reject) => {
155
+ const target = new URL(path, url);
156
+ const request = target.protocol === 'https:' ? httpsRequest : httpRequest;
157
+ const req = request(target, { headers: { authorization: `Bearer ${key}`, connection: 'Upgrade', upgrade: 'raytrace-shell' } });
158
+ req.on('response', (response) => {
159
+ let text = '';
160
+ response.on('data', (chunk) => { text += chunk; });
161
+ response.on('end', () => { try { reject(new Error(JSON.parse(text).error)); } catch { reject(new Error(`HTTP ${response.statusCode}`)); } });
162
+ });
163
+ req.on('upgrade', (_response, socket, head) => {
164
+ say(`Connected to ${id}. Run \`claude\` (or codex) here; exit to leave. The sandbox keeps running.\n`);
165
+ if (head.length) stdout.write(head);
166
+ stdin.setRawMode(true);
167
+ stdin.resume();
168
+ stdin.pipe(socket);
169
+ socket.pipe(stdout);
170
+ const done = () => { stdin.unpipe(socket); stdin.setRawMode(false); stdin.pause(); resolve(); };
171
+ socket.on('close', done);
172
+ socket.on('error', done);
173
+ });
174
+ req.on('error', () => reject(unreachable(url)));
175
+ req.end();
176
+ });
177
+ say(`\nLeft ${id}. It is still running: raytrace sandbox stop ${id}`);
178
+ }