@raytrace-cli/cli 0.1.0 → 0.3.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,105 @@ 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 connect # 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. You
120
+ can also create a sandbox there by dropping a project folder on the Sandboxes
121
+ page; it shows the command to open it, `raytrace connect <sandbox-id>`, which
122
+ signs you in first if you are not. Sandboxes belong to the account that made
123
+ them: `raytrace auth status` says which one the CLI is using.
124
+
125
+ - **What is uploaded:** the files Git would track in the repository (including
126
+ new files it does not ignore), without `.git`, dependencies such as
127
+ `node_modules`, build output, `.env*` files, private keys (`.pem`, `.key`,
128
+ `.p12`, `.pfx`) and common credential files (`.npmrc`, `.netrc`, `id_rsa`, …).
129
+ Review your project for secrets inside other files before you upload.
130
+ - **Limits:** a project may be up to 200 MiB and 20,000 files, each file up to
131
+ 25 MiB (100 MiB once packed). A project over a limit is refused, with the
132
+ files named, and nothing is uploaded; add them to `.gitignore`. You can have
133
+ three sandboxes at a time.
134
+ - **Signing in to your agent:** sign in to Claude Code inside the sandbox as
135
+ you would on your machine. That sign-in stays in the sandbox until you
136
+ destroy it.
137
+ - **When you are done:** `raytrace sandbox stop` keeps the files;
138
+ `raytrace sandbox destroy` deletes them and any sign-in made inside. The
139
+ recorded sessions are kept for your organization.
140
+
141
+ Cloud sandboxes are a preview and may change; please
142
+ [report issues](https://github.com/Godcreatebugs/raytrace-cli/issues) you run into.
143
+
52
144
  ## Commands
53
145
 
54
- | Command | |
146
+ | Command | What it does |
55
147
  |---|---|
56
148
  | `raytrace setup` | one-time setup; run it again to change settings |
57
149
  | `raytrace start` | start recording in the background |
@@ -61,6 +153,12 @@ raytrace codex # any Codex arguments work after it
61
153
  | `raytrace doctor` | check the install without changing anything |
62
154
  | `raytrace codex [args]` | run Codex through RayTrace |
63
155
  | `raytrace uninstall` | remove the Claude Code hook; `--purge` also deletes recorded data |
156
+ | `raytrace auth login` | sign in to RayTrace (needed for cloud sandboxes); `status`, `logout` |
157
+ | `raytrace sandbox create` | upload this Git repository to a new cloud sandbox; `--name <name>` |
158
+ | `raytrace sandbox list` | your cloud sandboxes |
159
+ | `raytrace connect [id]` | open a terminal in a sandbox, signing in first if needed (also `raytrace sandbox shell [id]`) |
160
+ | `raytrace sandbox start\|stop [id]` | start or stop a sandbox; stopping keeps its files |
161
+ | `raytrace sandbox destroy [id]` | delete a sandbox; its recorded sessions are kept |
64
162
 
65
163
  ## Getting the most out of it
66
164
 
@@ -91,11 +189,23 @@ RayTrace at the same sessions and the records line up run for run.
91
189
  OpenRouter's public list of models once. That request carries none of your
92
190
  data.
93
191
 
192
+ Cloud sandboxes are different by design: they run on RayTrace's servers.
193
+
194
+ - `raytrace sandbox create` uploads your project (see
195
+ [what is uploaded](#cloud-sandboxes-preview)) to RayTrace.
196
+ - Inside a sandbox, the prompts, model requests and answers, tool calls and the
197
+ commands that run are recorded on RayTrace's servers for your organization.
198
+ Members of your organization can see them at app.raytracer.si; other
199
+ organizations cannot.
200
+ - `raytrace auth login` keeps your sign-in in the macOS Keychain or the Linux
201
+ secret service (a file readable only by you where neither is available), and
202
+ `raytrace auth logout` removes it.
203
+
94
204
  ## Uninstall
95
205
 
96
206
  ```sh
97
207
  raytrace uninstall --purge # removes the hook and ~/.raytrace
98
- npm uninstall -g @raytrace/cli
208
+ npm uninstall -g @raytrace-cli/cli
99
209
  ```
100
210
 
101
211
  ## Troubleshooting
@@ -106,6 +216,9 @@ background process logs to `~/.raytrace/logs/proxy.log`.
106
216
  - **Nothing shows up for Claude Code:** check `raytrace status` says
107
217
  "recording", and that `raytrace` is on your PATH (`which raytrace`). Sessions
108
218
  appear when the agent finishes a step, not while it is typing.
219
+ - **`Cannot reach RayTrace at https://api.raytracer.si`:** check your
220
+ connection. Networks that inspect HTTPS, such as some company Wi-Fi, can
221
+ block it; try another network.
109
222
  - **Port 8797 is in use:** set `RAYTACE_PORT=<port>` in `~/.raytrace/config.env`,
110
223
  then `raytrace stop && raytrace start`.
111
224
 
package/bin/raytrace.mjs CHANGED
@@ -15,10 +15,22 @@ 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
+ connect <id> open a terminal in a cloud sandbox (signs you in if needed)
20
+ sandbox ... cloud sandboxes: create, list, shell, start, stop, destroy
18
21
 
19
22
  Options for setup: --yes --no-claude-code --no-start --openrouter-key <key>
20
23
  Options for uninstall: --yes --purge (also delete ~/.raytrace)
21
24
 
25
+ Sandboxes (preview):
26
+ raytrace sandbox create [--name <name>] upload this Git repository to a new sandbox
27
+ (up to 200 MiB, 25 MiB a file, 20,000 files)
28
+ raytrace sandbox list
29
+ raytrace connect [id] a terminal in it; run claude or codex there
30
+ (same as: raytrace sandbox shell [id])
31
+ raytrace sandbox start|stop [id]
32
+ raytrace sandbox destroy [id] [--yes] delete it; recorded evidence is kept
33
+
22
34
  Data and settings live in ~/.raytrace (override with RAYTRACE_HOME).`;
23
35
 
24
36
  // node:sqlite, which the recorder stores everything in, needs 22.13.
@@ -48,6 +60,46 @@ const commands = await import('../src/commands.mjs');
48
60
  // `codex` passes everything after it straight to Codex.
49
61
  if (command === 'codex') { await commands.codex(rest); process.exit(); }
50
62
 
63
+ if (command === 'auth') {
64
+ const auth = await import('../src/auth.mjs');
65
+ const sub = rest[0];
66
+ const action = { login: auth.login, status: auth.status, logout: auth.logout }[sub];
67
+ if (!action) { console.error(`Usage: raytrace auth login | status | logout`); process.exit(2); }
68
+ try { await action(); process.exit(0); }
69
+ catch (error) { console.error(`raytrace auth ${sub}: ${error.message}`); process.exit(1); }
70
+ }
71
+
72
+ // `raytrace connect <id>`: the sandbox's terminal, by the id the dashboard shows.
73
+ if (command === 'connect') {
74
+ if (rest.length > 1 || rest[0]?.startsWith('-')) { console.error('Usage: raytrace connect [sandbox-id]'); process.exit(2); }
75
+ const sandbox = await import('../src/sandbox.mjs');
76
+ try { await sandbox.shell(rest[0]); process.exit(0); }
77
+ catch (error) { console.error(`raytrace connect: ${error.message}`); process.exit(1); }
78
+ }
79
+
80
+ if (command === 'sandbox') {
81
+ const sandbox = await import('../src/sandbox.mjs');
82
+ let parsed;
83
+ try {
84
+ parsed = parseArgs({ args: rest, strict: true, allowPositionals: true, options: {
85
+ yes: { type: 'boolean', short: 'y' },
86
+ name: { type: 'string' },
87
+ } });
88
+ } catch (error) { console.error(`${error.message}\n\nRun \`raytrace help\` for usage.`); process.exit(2); }
89
+ const [sub, id] = parsed.positionals;
90
+ const action = {
91
+ create: () => sandbox.create(parsed.values),
92
+ list: () => sandbox.list(),
93
+ shell: () => sandbox.shell(id),
94
+ start: () => sandbox.start(id),
95
+ stop: () => sandbox.stop(id),
96
+ destroy: () => sandbox.destroy(id, parsed.values),
97
+ }[sub];
98
+ if (!action) { console.error(`Unknown sandbox command: ${sub ?? '(none)'}\n\n${HELP}`); process.exit(2); }
99
+ try { await action(); process.exit(0); }
100
+ catch (error) { console.error(`raytrace sandbox ${sub}: ${error.message}`); process.exit(1); }
101
+ }
102
+
51
103
  let flags;
52
104
  try {
53
105
  ({ 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.3.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,156 @@
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
+ /** The signed-in account's email, for messages that need to say whose workspace this is; null when signed out. */
140
+ export function account() { return load()?.user?.email || null; }
141
+
142
+ export async function status() {
143
+ const session = load();
144
+ if (!session) { say('Not signed in. Run: raytrace auth login'); return; }
145
+ const { exp = 0, org_id: org } = claims(session.access_token);
146
+ say(`Signed in as ${session.user?.email}${session.user?.name ? ` (${session.user.name})` : ''}`);
147
+ say(`Organization: ${org || session.organization_id || 'personal'}`);
148
+ const left = Math.round((exp * 1000 - Date.now()) / 60000);
149
+ say(left > 0 ? `Access token valid for ${left} more min; renewed automatically.` : 'Access token expired; it is renewed on the next command.');
150
+ }
151
+
152
+ export async function logout() {
153
+ if (!load()) { say('Not signed in.'); return; }
154
+ forget();
155
+ say('Signed out: your RayTrace sign-in was removed from this machine.');
156
+ }
@@ -0,0 +1,208 @@
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, account, login } 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
+ // What one project upload may be. RayTrace's API holds the dashboard's folder
20
+ // upload to the same numbers and checks them again; saying so here saves the upload.
21
+ const MIB = 1024 * 1024;
22
+ const MAX_FILE = 25 * MIB; // any one file
23
+ const MAX_BYTES = 200 * MIB; // all files, before compression
24
+ const MAX_FILES = 20_000;
25
+ const MAX_ARCHIVE = 100 * MIB; // the packed upload
26
+ const ID = /^rtp-[a-f0-9]{32}$/;
27
+ const API = 'https://api.raytracer.si';
28
+ const unreachable = (url) => new Error(`Cannot reach RayTrace at ${url.origin}. Check your connection; `
29
+ + 'networks that inspect HTTPS (some company Wi-Fi) may block it.');
30
+
31
+ // Never packed: version control, dependencies and build output (rebuilt in the
32
+ // sandbox), and files that usually hold credentials.
33
+ const EXCLUDED = new Set(['.git', '.raytace', '.raytrace', '.ssh', '.aws', '.azure', '.config', 'node_modules', '.venv',
34
+ '__pycache__', '.next', '.vinext', 'dist', 'coverage', '.wrangler', '.DS_Store']);
35
+ const SECRET_NAMES = new Set(['.npmrc', '.netrc', '.pypirc', 'credentials', 'auth.json', 'id_rsa', 'id_ed25519']);
36
+ const SECRET_EXTENSIONS = /\.(pem|key|p12|pfx)$/i;
37
+
38
+ export function packable(path) {
39
+ const parts = path.split('/');
40
+ const name = parts.at(-1);
41
+ return !parts.some((part) => EXCLUDED.has(part) || part === '..') && !path.startsWith('/')
42
+ && !name.startsWith('.env') && !SECRET_EXTENSIONS.test(name) && !SECRET_NAMES.has(name);
43
+ }
44
+
45
+ async function api() {
46
+ const config = readConfig();
47
+ const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
48
+ let key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
49
+ if (!key) {
50
+ if (!interactive()) throw new Error('Not signed in. Run: raytrace auth login');
51
+ say('You are not signed in to RayTrace yet.');
52
+ await login();
53
+ key = await accessToken();
54
+ if (!key) throw new Error('Not signed in. Run: raytrace auth login');
55
+ say();
56
+ }
57
+ return { url: new URL(url), key };
58
+ }
59
+
60
+ async function call(method, path, { body, headers = {} } = {}) {
61
+ const { url, key } = await api();
62
+ let response;
63
+ try {
64
+ response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
65
+ } catch {
66
+ throw unreachable(url);
67
+ }
68
+ const data = await response.json().catch(() => ({}));
69
+ if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
70
+ return data;
71
+ }
72
+
73
+ /** The project's files git would track, minus what must not leave this machine. */
74
+ function projectFiles(root) {
75
+ const listed = spawnSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { maxBuffer: 256 * 1024 * 1024 });
76
+ if (listed.status !== 0) throw new Error(`${root} is not a Git repository. Run this from inside one.`);
77
+ const files = []; const skipped = []; const large = []; let total = 0;
78
+ for (const name of [...new Set(listed.stdout.toString().split('\0').filter(Boolean))].sort()) {
79
+ let stat;
80
+ try { stat = lstatSync(join(root, name)); } catch { continue; } // deleted, still in the index
81
+ if (!packable(name) || !stat.isFile()) { skipped.push(name); continue; } // symlinks too
82
+ if (stat.size > MAX_FILE) { large.push(`${name} (${Math.round(stat.size / MIB)} MiB)`); continue; }
83
+ total += stat.size;
84
+ files.push(name);
85
+ }
86
+ // Refused, never trimmed: a project missing its large files would not be the project.
87
+ if (large.length) {
88
+ throw new Error(`${large.length === 1 ? 'This file is' : 'These files are'} over ${MAX_FILE / MIB} MiB, the most one file may be:\n `
89
+ + `${large.slice(0, 10).join('\n ')}${large.length > 10 ? `\n ... and ${large.length - 10} more` : ''}\nAdd ${large.length === 1 ? 'it' : 'them'} to .gitignore (or remove ${large.length === 1 ? 'it' : 'them'}), then try again.`);
90
+ }
91
+ if (files.length > MAX_FILES) throw new Error(`The project has ${files.length.toLocaleString()} files; the most is ${MAX_FILES.toLocaleString()}. Add generated files to .gitignore first.`);
92
+ if (total > MAX_BYTES) throw new Error(`The project is ${Math.round(total / MIB)} MiB; the most is ${MAX_BYTES / MIB} MiB. Add large generated files to .gitignore first.`);
93
+ return { files, skipped, total };
94
+ }
95
+
96
+ function pack(root, files) {
97
+ return new Promise((resolve, reject) => {
98
+ // Extended attributes stay here: macOS tags nearly every file (com.apple.provenance),
99
+ // and bsdtar would also add AppleDouble files for them.
100
+ const mac = process.platform === 'darwin' ? ['--no-mac-metadata', '--no-xattrs'] : [];
101
+ const tar = spawn('tar', ['-czf', '-', ...mac, '--no-recursion', '--null', '-T', '-'],
102
+ { cwd: root, env: { ...process.env, COPYFILE_DISABLE: '1' }, stdio: ['pipe', 'pipe', 'pipe'] });
103
+ const chunks = []; let error = '';
104
+ tar.stdout.on('data', (chunk) => chunks.push(chunk));
105
+ tar.stderr.on('data', (chunk) => { error += chunk; });
106
+ tar.on('error', reject);
107
+ tar.on('close', (code) => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`tar failed: ${error.trim()}`)));
108
+ tar.stdin.end(files.map((name) => `${name}\0`).join(''));
109
+ });
110
+ }
111
+
112
+ async function pickId(id) {
113
+ if (id) {
114
+ if (!ID.test(id)) throw new Error(`Not a sandbox id: ${id}`);
115
+ return id;
116
+ }
117
+ const live = (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
118
+ if (live.length === 1) return live[0].id;
119
+ throw new Error(live.length ? 'More than one sandbox; name one (raytrace sandbox list).'
120
+ : `No sandboxes${account() ? ` in ${account()}'s workspace` : ''} yet: raytrace sandbox create`);
121
+ }
122
+
123
+ export async function create(flags) {
124
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' });
125
+ if (top.status !== 0) throw new Error('Run this from inside a Git repository.');
126
+ const root = top.stdout.trim();
127
+ const name = flags.name || basename(root);
128
+ const { files, skipped, total } = projectFiles(root);
129
+ if (!files.length) throw new Error('Nothing to upload.');
130
+ say(`Packing ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}`);
131
+ if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
132
+ const archive = await pack(root, files);
133
+ if (archive.length > MAX_ARCHIVE) throw new Error(`The packed project is ${Math.round(archive.length / MIB)} MiB; the most is ${MAX_ARCHIVE / MIB} MiB.`);
134
+ say('Creating the sandbox (the first one on a host takes a little longer)...');
135
+ const box = await call('POST', '/v1/sandboxes', {
136
+ body: archive, headers: { 'content-type': 'application/gzip', 'x-raytrace-name': name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) },
137
+ });
138
+ say(`\nSandbox ${box.id} is running.`);
139
+ say(box.transcripts ? 'Claude Code sessions in it are recorded.'
140
+ : `Claude Code transcripts are off: ${box.transcripts_off}. Commands are still recorded.`);
141
+ say(`Open it: raytrace connect ${box.id}`);
142
+ }
143
+
144
+ export async function list() {
145
+ const boxes = (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
146
+ if (!boxes.length) { say('No sandboxes. Create one from a Git repository: raytrace sandbox create'); return; }
147
+ for (const box of boxes) {
148
+ // The sandbox's creation time (seconds), or its container's once that is known.
149
+ const created = typeof box.created === 'number' ? box.created * 1000 : Date.parse(box.created);
150
+ const age = Math.round((Date.now() - created) / 60000);
151
+ say(`${box.id} ${String(box.status).padEnd(8)} ${box.name} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
152
+ }
153
+ }
154
+
155
+ export async function start(id) { const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/start`); say(`${box.id} running`); }
156
+ export async function stop(id) { const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/stop`); say(`${box.id} stopped; its files are kept`); }
157
+
158
+ export async function destroy(id, flags) {
159
+ id = await pickId(id);
160
+ if (!flags.yes) {
161
+ if (!interactive()) throw new Error('Pass --yes to destroy without a prompt.');
162
+ say(`This deletes ${id}: its files, and any sign-in made inside it. Recorded evidence is kept.`);
163
+ if ((await ask('Type the sandbox id to confirm: ')) !== id) { say('Not destroyed.'); return; }
164
+ }
165
+ await call('DELETE', `/v1/sandboxes/${id}`);
166
+ say(`${id} destroyed.`);
167
+ }
168
+
169
+ /** An interactive terminal in the sandbox, carried over one upgraded HTTP request.
170
+ * `raytrace connect <id>` and `raytrace sandbox shell [id]` are the same thing. */
171
+ export async function shell(id) {
172
+ if (!interactive()) throw new Error('Connecting to a sandbox needs a terminal.');
173
+ id = await pickId(id);
174
+ const { url, key } = await api();
175
+ const { stdin, stdout } = process;
176
+ const path = `/v1/sandboxes/${id}/shell?rows=${stdout.rows || 24}&cols=${stdout.columns || 80}`;
177
+ await new Promise((resolve, reject) => {
178
+ const target = new URL(path, url);
179
+ const request = target.protocol === 'https:' ? httpsRequest : httpRequest;
180
+ const req = request(target, { headers: { authorization: `Bearer ${key}`, connection: 'Upgrade', upgrade: 'raytrace-shell' } });
181
+ req.on('response', (response) => {
182
+ let text = '';
183
+ response.on('data', (chunk) => { text += chunk; });
184
+ response.on('end', () => {
185
+ // The API does not say whether another account has this sandbox; the likely mix-up is worth naming.
186
+ if (response.statusCode === 404 && account()) {
187
+ return reject(new Error(`No sandbox ${id} in ${account()}'s workspace. If it was made under another account `
188
+ + '(for example in the dashboard), sign in as that one: raytrace auth login'));
189
+ }
190
+ try { reject(new Error(JSON.parse(text).error)); } catch { reject(new Error(`HTTP ${response.statusCode}`)); }
191
+ });
192
+ });
193
+ req.on('upgrade', (_response, socket, head) => {
194
+ say(`Connected to ${id}. Run \`claude\` (or codex) here; exit to leave. The sandbox keeps running.\n`);
195
+ if (head.length) stdout.write(head);
196
+ stdin.setRawMode(true);
197
+ stdin.resume();
198
+ stdin.pipe(socket);
199
+ socket.pipe(stdout);
200
+ const done = () => { stdin.unpipe(socket); stdin.setRawMode(false); stdin.pause(); resolve(); };
201
+ socket.on('close', done);
202
+ socket.on('error', done);
203
+ });
204
+ req.on('error', () => reject(unreachable(url)));
205
+ req.end();
206
+ });
207
+ say(`\nLeft ${id}. It is still running. Back in: raytrace connect ${id} Stop it: raytrace sandbox stop ${id}`);
208
+ }