@raytrace-cli/cli 0.22.3 → 0.22.5

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/bin/raytrace.mjs CHANGED
@@ -30,9 +30,16 @@ Get started in the cloud (preview):
30
30
 
31
31
  Cloud sandboxes:
32
32
  raytrace auth login|status|logout your RayTrace sign-in
33
- raytrace sandbox create [--name <name>] [--size small|medium|large]
33
+ raytrace sandbox create [--name <name>] [--size small|medium|large] [--from-master <name>] [--env-profile <name>]
34
34
  upload this Git repository to a new sandbox
35
- (up to 200 MiB, 25 MiB a file, 20,000 files; default: small)
35
+ (up to 200 MiB, 25 MiB a file, 20,000 files; default: small;
36
+ or --master --name <name> for an org master sandbox)
37
+ raytrace sandbox masters | publish <master> | delete-master <master> [--yes]
38
+ list, publish, or delete org master sandboxes (/opt/env)
39
+ raytrace sandbox env-profile [id] [<name> | --detach]
40
+ view, attach, or detach a cloud sandbox's env profile
41
+ raytrace env-profile list | create <name> | delete <id-or-name>
42
+ manage encrypted org env profiles (cloud, org admins)
36
43
  raytrace sandbox create --connect [--repo owner/name]
37
44
  the same, then make it a clone of the repository's
38
45
  GitHub origin (or --repo) that its agent can fetch
@@ -233,9 +240,17 @@ if (command === 'sandbox') {
233
240
  repo: { type: 'string' },
234
241
  add: { type: 'string', multiple: true },
235
242
  remove: { type: 'string', multiple: true },
243
+ 'env-profile': { type: 'string' },
244
+ detach: { type: 'boolean' },
245
+ master: { type: 'boolean' },
246
+ 'from-master': { type: 'string' },
247
+ 'default-env-profile': { type: 'string' },
248
+ description: { type: 'string' },
249
+ empty: { type: 'boolean' },
250
+ 'no-wait': { type: 'boolean' },
236
251
  } });
237
252
  } catch (error) { console.error(`${error.message}\n\nRun \`raytrace help\` for usage.`); process.exit(2); }
238
- const [sub, id] = parsed.positionals;
253
+ const [sub, id, extraArg] = parsed.positionals;
239
254
  if (sub === 'destroy' && parsed.values['delete-logs'] && parsed.values['keep-logs']) {
240
255
  console.error('raytrace sandbox destroy: Pick one: --delete-logs or --keep-logs.'); process.exit(2);
241
256
  }
@@ -249,6 +264,10 @@ if (command === 'sandbox') {
249
264
  destroy: () => sandbox.destroy(id, parsed.values),
250
265
  files: () => sandbox.files(id, parsed.values),
251
266
  repos: () => sandbox.repos(id, parsed.values),
267
+ 'env-profile': () => sandbox.envProfile(id, extraArg, parsed.values),
268
+ masters: async () => (await import('../src/master.mjs')).listMasters(),
269
+ publish: async () => (await import('../src/master.mjs')).publishMaster(id, parsed.values),
270
+ 'delete-master': async () => (await import('../src/master.mjs')).deleteMaster(id, parsed.values),
252
271
  };
253
272
  const action = actions[sub];
254
273
  if (!sub) { console.error(SANDBOX_HELP); process.exit(2); }
@@ -257,6 +276,37 @@ if (command === 'sandbox') {
257
276
  catch (error) { console.error(`raytrace sandbox ${sub}: ${error.message}`); process.exit(1); }
258
277
  }
259
278
 
279
+ if (command === 'env-profile') {
280
+ const usage = 'Usage: raytrace env-profile list | create <name> [--from-file <path>] [--var KEY=VALUE ...] [--description <text>] [--admin-only] | delete <id-or-name> [--yes]';
281
+ let parsed;
282
+ try {
283
+ parsed = parseArgs({ args: rest, strict: true, allowPositionals: true, options: {
284
+ yes: { type: 'boolean', short: 'y' },
285
+ description: { type: 'string' },
286
+ 'admin-only': { type: 'boolean' },
287
+ 'from-file': { type: 'string' },
288
+ var: { type: 'string', multiple: true },
289
+ local: { type: 'boolean' },
290
+ } });
291
+ } catch (error) { console.error(`${error.message}\n\n${usage}`); process.exit(2); }
292
+ if (parsed.values.local) {
293
+ console.error('raytrace env-profile: Env profiles require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
294
+ process.exit(2);
295
+ }
296
+ const [sub, target, ...extra] = parsed.positionals;
297
+ if (!sub || extra.length) { console.error(usage); process.exit(2); }
298
+ const envMod = await import('../src/env-profile.mjs');
299
+ const actions = {
300
+ list: () => envMod.listEnvProfiles(),
301
+ create: () => envMod.createEnvProfile(target, parsed.values),
302
+ delete: () => envMod.deleteEnvProfile(target, parsed.values),
303
+ };
304
+ const action = actions[sub];
305
+ if (!action) { console.error(unknownCommand(sub, Object.keys(actions), 'env-profile')); process.exit(2); }
306
+ try { await action(); process.exit(0); }
307
+ catch (error) { console.error(`raytrace env-profile ${sub}: ${error.message}`); process.exit(1); }
308
+ }
309
+
260
310
  if (command === 'upload') {
261
311
  let parsed;
262
312
  try {
@@ -404,7 +454,7 @@ const actions = {
404
454
  const run = actions[command];
405
455
 
406
456
  if (!run) {
407
- const names = [...Object.keys(actions), 'auth', 'code', 'codex', 'connect', 'export', 'help', 'hook', 'key', 'mcp', 'report', 'sandbox', 'share', 'upload'];
457
+ const names = [...Object.keys(actions), 'auth', 'code', 'codex', 'connect', 'env-profile', 'export', 'help', 'hook', 'key', 'mcp', 'report', 'sandbox', 'share', 'upload'];
408
458
  console.error(unknownCommand(command, names)); process.exit(2);
409
459
  }
410
460
  try { await run(); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/cli",
3
- "version": "0.22.3",
3
+ "version": "0.22.5",
4
4
  "mcpName": "io.github.Godcreatebugs/raytrace",
5
5
  "description": "See what your coding agent did: traces, tool calls, cost and step-by-step evidence for Claude Code and Codex.",
6
6
  "license": "MIT",
@@ -0,0 +1,108 @@
1
+ // `raytrace env-profile`: manage encrypted org-scoped Env Profiles on RayTrace cloud.
2
+ // Secrets live in the control plane, are injected only at command/shell exec time,
3
+ // and are scrubbed from recorded traces and command output.
4
+ import { readFileSync } from 'node:fs';
5
+ import { call } from './api.mjs';
6
+ import { ask, askSecret, confirm, interactive } from './prompt.mjs';
7
+
8
+ const say = (line = '') => console.log(line);
9
+ const JSON_HEADERS = { 'content-type': 'application/json' };
10
+ const PROFILE_ID = /^envp-[a-f0-9]{32}$/;
11
+
12
+ /** Parses KEY=VALUE lines from a .env-style file (ignores blank lines and # comments). */
13
+ export function parseEnvFile(text) {
14
+ const vars = {};
15
+ for (const rawLine of String(text || '').split(/\r?\n/)) {
16
+ const line = rawLine.trim();
17
+ if (!line || line.startsWith('#')) continue;
18
+ const stripped = line.startsWith('export ') ? line.slice(7).trim() : line;
19
+ const eq = stripped.indexOf('=');
20
+ if (eq <= 0) throw new Error(`Invalid env line (expected KEY=VALUE): ${line.slice(0, 60)}`);
21
+ const key = stripped.slice(0, eq).trim();
22
+ let value = stripped.slice(eq + 1);
23
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
24
+ value = value.slice(1, -1);
25
+ }
26
+ vars[key] = value;
27
+ }
28
+ return vars;
29
+ }
30
+
31
+ /** Parses repeated `--var KEY=VALUE` flags into `{KEY: VALUE}`. */
32
+ export function parseVarPairs(pairs = []) {
33
+ const vars = {};
34
+ for (const pair of pairs) {
35
+ const eq = String(pair).indexOf('=');
36
+ if (eq <= 0) throw new Error(`Invalid --var "${pair}" (expected KEY=VALUE).`);
37
+ const key = pair.slice(0, eq).trim();
38
+ vars[key] = pair.slice(eq + 1);
39
+ }
40
+ return vars;
41
+ }
42
+
43
+ export async function listEnvProfiles() {
44
+ const res = await call('GET', '/v1/env-profiles');
45
+ const profiles = res.profiles || [];
46
+ if (!profiles.length) {
47
+ say('No env profiles yet. Create one: raytrace env-profile create <name> --from-file .env');
48
+ return;
49
+ }
50
+ for (const p of profiles) {
51
+ const access = p.member_usable ? 'members' : 'admins-only';
52
+ const keys = (p.keys || []).length ? p.keys.join(', ') : '(empty)';
53
+ say(`${p.id} ${p.name.padEnd(20)} ${access.padEnd(11)} ${p.key_count} var${p.key_count === 1 ? '' : 's'} [${keys}]`);
54
+ }
55
+ }
56
+
57
+ export async function createEnvProfile(name, flags = {}) {
58
+ if (!name) throw new Error('Usage: raytrace env-profile create <name> [--from-file <path>] [--var KEY=VALUE ...] [--description <text>] [--admin-only]');
59
+ let variables = {};
60
+ if (flags['from-file']) {
61
+ variables = { ...variables, ...parseEnvFile(readFileSync(flags['from-file'], 'utf8')) };
62
+ }
63
+ if (flags.var?.length) {
64
+ variables = { ...variables, ...parseVarPairs(flags.var) };
65
+ }
66
+ if (!Object.keys(variables).length && interactive()) {
67
+ say('Enter variables (blank key name to finish; values are not echoed):');
68
+ while (true) {
69
+ const key = (await ask(' KEY (blank to finish): ')).trim();
70
+ if (!key) break;
71
+ const value = await askSecret(` Value for ${key}: `);
72
+ variables[key] = value;
73
+ }
74
+ }
75
+ const created = await call('POST', '/v1/env-profiles', {
76
+ headers: JSON_HEADERS,
77
+ body: JSON.stringify({
78
+ name,
79
+ description: flags.description || '',
80
+ member_usable: !flags['admin-only'],
81
+ variables,
82
+ }),
83
+ });
84
+ say(`Created env profile ${created.name} (${created.id}) with ${created.key_count} variable${created.key_count === 1 ? '' : 's'}.`);
85
+ say('Values are encrypted at rest and scrubbed from recorded traces and command output.');
86
+ }
87
+
88
+ async function resolveProfileId(ref) {
89
+ if (PROFILE_ID.test(ref)) return ref;
90
+ const res = await call('GET', '/v1/env-profiles');
91
+ const match = (res.profiles || []).find((p) => p.name.toLowerCase() === ref.toLowerCase());
92
+ if (!match) throw new Error(`Env profile "${ref}" was not found. List available profiles: raytrace env-profile list`);
93
+ return match.id;
94
+ }
95
+
96
+ export async function deleteEnvProfile(ref, flags = {}) {
97
+ if (!ref) throw new Error('Usage: raytrace env-profile delete <id-or-name> [--yes]');
98
+ const id = await resolveProfileId(ref);
99
+ if (!flags.yes) {
100
+ if (!interactive()) throw new Error('Pass --yes to delete an env profile without a prompt.');
101
+ if (!(await confirm(`Delete env profile ${ref} (${id})? Any sandboxes using it will be detached.`, false))) {
102
+ say('Not deleted.');
103
+ return;
104
+ }
105
+ }
106
+ const result = await call('DELETE', `/v1/env-profiles/${id}`);
107
+ say(`Deleted env profile ${id}${result.detached_sandboxes ? ` (detached from ${result.detached_sandboxes} sandbox${result.detached_sandboxes === 1 ? '' : 'es'})` : ''}.`);
108
+ }
package/src/master.mjs ADDED
@@ -0,0 +1,116 @@
1
+ // `raytrace sandbox masters | publish | create --master`: manage org Master Sandboxes.
2
+ // Master Sandboxes hold reusable dependencies in /opt/env (no personal credentials or
3
+ // project code) so employees can create sandboxes with pre-installed packages in <1s.
4
+ import { call } from './api.mjs';
5
+ import { confirm, interactive } from './prompt.mjs';
6
+
7
+ const say = (line = '') => console.log(line);
8
+ const JSON_HEADERS = { 'content-type': 'application/json' };
9
+ const MASTER_ID = /^mst-[a-f0-9]{32}$/;
10
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
11
+
12
+ const formatBytes = (bytes) => {
13
+ if (bytes == null) return '—';
14
+ const mib = bytes / (1024 * 1024);
15
+ return mib >= 1024 ? `${(mib / 1024).toFixed(1)} GiB` : `${mib.toFixed(mib < 10 ? 1 : 0)} MiB`;
16
+ };
17
+
18
+ function depSummary(deps) {
19
+ if (!deps || typeof deps !== 'object') return '';
20
+ const parts = [];
21
+ if (Array.isArray(deps.pypi) && deps.pypi.length) parts.push(`${deps.pypi.length} PyPI`);
22
+ if (Array.isArray(deps.npm) && deps.npm.length) parts.push(`${deps.npm.length} npm`);
23
+ if (Array.isArray(deps.binaries) && deps.binaries.length) parts.push(`${deps.binaries.length} CLI`);
24
+ return parts.length ? ` [${parts.join(' · ')}]` : '';
25
+ }
26
+
27
+ export async function listMasters() {
28
+ const res = await call('GET', '/v1/masters');
29
+ const masters = res.masters || [];
30
+ if (!masters.length) {
31
+ say('No master sandboxes yet. Admins can create one: raytrace sandbox create --master --name <name>');
32
+ return;
33
+ }
34
+ for (const m of masters) {
35
+ const snap = m.latest_snapshot || null;
36
+ const ver = m.active_version ? `v${m.active_version}` : 'draft';
37
+ const status = snap?.status || (m.active_version ? 'ready' : 'draft');
38
+ const size = formatBytes(snap?.size_bytes);
39
+ const deps = depSummary(snap?.dependencies);
40
+ say(`${m.id} ${m.name.padEnd(20)} ${ver.padEnd(6)} ${status.padEnd(10)} ${size.padEnd(9)}${deps}`);
41
+ if (m.setup_sandbox_id) say(` setup sandbox: ${m.setup_sandbox_id} (edit: raytrace connect ${m.setup_sandbox_id})`);
42
+ }
43
+ }
44
+
45
+ export async function createMaster(flags = {}) {
46
+ if (flags.local) throw new Error('Master sandboxes require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
47
+ const name = flags.name;
48
+ if (!name) throw new Error('Master sandboxes require a name: raytrace sandbox create --master --name <name>');
49
+ const body = {
50
+ name,
51
+ description: flags.description || '',
52
+ ...(flags.size ? { size: flags.size } : {}),
53
+ ...(flags['default-env-profile'] ? { default_env_profile: flags['default-env-profile'] } : {}),
54
+ };
55
+ say(`Creating master sandbox "${name}"...`);
56
+ const created = await call('POST', '/v1/masters', { headers: JSON_HEADERS, body: JSON.stringify(body) });
57
+ say(`\nMaster sandbox "${created.name}" (${created.id}) created.`);
58
+ if (created.setup_sandbox_id) {
59
+ say(`Setup sandbox: ${created.setup_sandbox_id} (running)`);
60
+ say(`1. Open it and install dependencies into /opt/env (pip, npm -g, CLIs):`);
61
+ say(` raytrace connect ${created.setup_sandbox_id}`);
62
+ say(`2. When ready, publish an immutable snapshot for your organization:`);
63
+ say(` raytrace sandbox publish ${created.name}`);
64
+ }
65
+ }
66
+
67
+ async function resolveMasterId(ref) {
68
+ if (MASTER_ID.test(ref)) return ref;
69
+ const res = await call('GET', '/v1/masters');
70
+ const match = (res.masters || []).find((m) => m.name.toLowerCase() === ref.toLowerCase());
71
+ if (!match) throw new Error(`Master sandbox "${ref}" was not found. List available masters: raytrace sandbox masters`);
72
+ return match.id;
73
+ }
74
+
75
+ export async function publishMaster(ref, flags = {}) {
76
+ if (flags.local) throw new Error('Master sandboxes apply to cloud sandboxes only; omit --local.');
77
+ if (!ref) throw new Error('Usage: raytrace sandbox publish <master-id-or-name>');
78
+ const id = await resolveMasterId(ref);
79
+ say(`Publishing snapshot for master sandbox "${ref}" (${id})...`);
80
+ const job = await call('POST', `/v1/masters/${id}/publish`, { headers: JSON_HEADERS, body: '{}' });
81
+ const version = job.version;
82
+ if (flags['no-wait']) {
83
+ say(`Publish job queued: ${id} v${version} (status: ${job.status}).`);
84
+ return;
85
+ }
86
+ const pollMs = Math.max(50, Number(process.env.RAYTRACE_PUBLISH_POLL_MS) || 1500);
87
+ const deadline = Date.now() + 10 * 60_000;
88
+ let current = job;
89
+ while (['queued', 'publishing'].includes(current.status) && Date.now() < deadline) {
90
+ await sleep(pollMs);
91
+ current = await call('GET', `/v1/masters/${id}/versions/${version}`);
92
+ }
93
+ if (current.status === 'failed') {
94
+ throw new Error(`Master publish failed: ${current.error || 'unknown error'}`);
95
+ }
96
+ if (current.status !== 'ready') {
97
+ throw new Error(`Timed out waiting for ${id} v${version} to publish (last status: ${current.status}).`);
98
+ }
99
+ say(`\nPublished master "${ref}" v${version} (${formatBytes(current.size_bytes)})${depSummary(current.dependencies)}.`);
100
+ say(`Create a sandbox from it: raytrace sandbox create --from-master ${ref}`);
101
+ }
102
+
103
+ export async function deleteMaster(ref, flags = {}) {
104
+ if (flags.local) throw new Error('Master sandboxes apply to cloud sandboxes only; omit --local.');
105
+ if (!ref) throw new Error('Usage: raytrace sandbox delete-master <master-id-or-name> [--yes]');
106
+ const id = await resolveMasterId(ref);
107
+ if (!flags.yes) {
108
+ if (!interactive()) throw new Error('Pass --yes to delete a master sandbox without a prompt.');
109
+ if (!(await confirm(`Delete master sandbox "${ref}" (${id}) and its setup sandbox? Existing sandboxes created from it keep working.`, false))) {
110
+ say('Not deleted.');
111
+ return;
112
+ }
113
+ }
114
+ await call('DELETE', `/v1/masters/${id}`);
115
+ say(`Deleted master sandbox "${ref}" (${id}).`);
116
+ }
package/src/mcp.mjs CHANGED
@@ -87,6 +87,8 @@ const TOOLS = [
87
87
  agent: agentSchema,
88
88
  github: { type: 'boolean', description: "Cloud only: also make the sandbox a clone of the project's GitHub repository (its origin), on a branch its agent may push to. Needs the RayTrace GitHub App connected for the user's organization." },
89
89
  github_repo: { type: 'string', description: 'With github: the GitHub repository to connect to instead of the origin, as owner/name.' },
90
+ master: { type: 'string', description: 'Cloud only: initialize /opt/env dependencies from a published organization master sandbox (by ID or name).' },
91
+ env_profile: { type: 'string', description: 'Cloud only: attach an encrypted organization env profile (by ID or name). Values are injected only at command/shell exec time and scrubbed from recorded traces.' },
90
92
  without_beta_credit: { type: 'boolean', description: "Create a regular sandbox, not the user's free beta sandbox. Only after the user agrees, when create_sandbox reported their free beta sandbox expired or already created." },
91
93
  },
92
94
  additionalProperties: false,
@@ -344,9 +346,11 @@ function githubTarget(root, wanted, named) {
344
346
  }
345
347
 
346
348
  async function createSandbox({ path, name, local = false, install_lima: installLima = false, connect = true, agent = 'claude',
347
- github: wantGithub = false, github_repo: namedRepo, without_beta_credit: plain = false }, step) {
349
+ github: wantGithub = false, github_repo: namedRepo, master, env_profile: envProfile, without_beta_credit: plain = false }, step) {
348
350
  if (!AGENTS[agent]) throw new ToolError(`agent must be one of: ${Object.keys(AGENTS).join(', ')}.`);
349
351
  if (local && (wantGithub || namedRepo !== undefined)) throw new ToolError('GitHub repositories connect to cloud sandboxes only; leave out github for a local sandbox.');
352
+ if (local && master !== undefined && master !== '') throw new ToolError('Master sandboxes apply to cloud sandboxes only; leave out master for a local sandbox.');
353
+ if (local && envProfile !== undefined && envProfile !== '') throw new ToolError('Env profiles apply to cloud sandboxes only; leave out env_profile for a local sandbox.');
350
354
  const root = await projectRoot(path);
351
355
  if (local) return createLocal(root, name, installLima, connect && agent, step);
352
356
  const github = githubTarget(root, wantGithub, namedRepo);
@@ -365,7 +369,7 @@ async function createSandbox({ path, name, local = false, install_lima: installL
365
369
  step('Creating the sandbox');
366
370
  let box;
367
371
  try {
368
- box = await upload(archive, name || basename(root), useCredit);
372
+ box = await upload(archive, name || basename(root), useCredit, null, envProfile || null, master || null);
369
373
  } catch (error) {
370
374
  if (!useCredit || !isCreditRefusal(error)) throw error;
371
375
  throw new ToolError(`No sandbox was created: the user's free beta sandbox ${error.status === 410 ? 'expired before it was created' : 'was already created'}. `
package/src/sandbox.mjs CHANGED
@@ -171,10 +171,56 @@ export function formatActionError(error) {
171
171
  return error;
172
172
  }
173
173
 
174
- /** Create a cloud sandbox from a packed project. A credit refusal comes back
175
- * as an ApiError (see isCreditRefusal) for the caller to decide on. */
176
- export function upload(archive, name, useCredit, size = null) {
177
- const headers = { 'content-type': 'application/gzip', 'x-raytrace-name': name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) };
174
+ /** Builds a multipart/form-data payload carrying JSON `metadata` and `.tar.gz` `archive`. */
175
+ export function buildMultipartUpload(metadata, archive) {
176
+ const boundary = `----RayTraceBoundary${randomBytes(12).toString('hex')}`;
177
+ const head1 = Buffer.from(
178
+ `--${boundary}\r\n`
179
+ + 'Content-Disposition: form-data; name="metadata"; filename="metadata.json"\r\n'
180
+ + 'Content-Type: application/json\r\n\r\n'
181
+ + JSON.stringify(metadata)
182
+ + '\r\n',
183
+ 'utf8',
184
+ );
185
+ const head2 = Buffer.from(
186
+ `--${boundary}\r\n`
187
+ + 'Content-Disposition: form-data; name="archive"; filename="project.tar.gz"\r\n'
188
+ + 'Content-Type: application/gzip\r\n\r\n',
189
+ 'utf8',
190
+ );
191
+ const tail = Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8');
192
+ return {
193
+ contentType: `multipart/form-data; boundary=${boundary}`,
194
+ body: Buffer.concat([head1, head2, Buffer.from(archive), tail]),
195
+ };
196
+ }
197
+
198
+ /** Create a cloud sandbox from a packed project (or empty JSON body when `archive` is null
199
+ * and `master` is provided). A credit refusal comes back as an ApiError. */
200
+ export function upload(archive, name, useCredit, size = null, envProfile = null, master = null) {
201
+ const cleanName = name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100);
202
+ if (!archive) {
203
+ const metadata = {
204
+ name: cleanName,
205
+ ...(size ? { size } : {}),
206
+ ...(master ? { master } : {}),
207
+ ...(envProfile ? { env_profile: envProfile } : {}),
208
+ ...(useCredit ? { beta_credit: true } : {}),
209
+ };
210
+ return call('POST', '/v1/sandboxes', { body: JSON.stringify(metadata), headers: JSON_HEADERS });
211
+ }
212
+ if (envProfile || master) {
213
+ const metadata = {
214
+ name: cleanName,
215
+ ...(size ? { size } : {}),
216
+ ...(master ? { master } : {}),
217
+ ...(envProfile ? { env_profile: envProfile } : {}),
218
+ ...(useCredit ? { beta_credit: true } : {}),
219
+ };
220
+ const { contentType, body } = buildMultipartUpload(metadata, archive);
221
+ return call('POST', '/v1/sandboxes', { body, headers: { 'content-type': contentType } });
222
+ }
223
+ const headers = { 'content-type': 'application/gzip', 'x-raytrace-name': cleanName };
178
224
  if (size) headers['x-raytrace-size'] = size;
179
225
  if (useCredit) headers['x-raytrace-beta-credit'] = '1';
180
226
  return call('POST', '/v1/sandboxes', { body: archive, headers });
@@ -270,29 +316,68 @@ export async function repos(id, flags = {}) {
270
316
  say(pushRule(targetId));
271
317
  }
272
318
 
319
+ /** `raytrace sandbox env-profile [id] [<profile-name-or-id> | --detach]` */
320
+ export async function envProfile(id, profileRef, flags = {}) {
321
+ if (flags.local || (id && local.isLocal(id))) {
322
+ throw new Error('Env profiles require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
323
+ }
324
+ // Allow `raytrace sandbox env-profile <profile-name>` when there is a single cloud sandbox? Keep explicit:
325
+ // If id is not an rtp-... id and no profileRef was given, treat id as sandbox id so pickId/checkId gives a clear error.
326
+ const targetId = await pickId(id);
327
+ if (flags.detach) {
328
+ await call('PUT', `/v1/sandboxes/${targetId}/env-profile`, { headers: JSON_HEADERS, body: JSON.stringify({ env_profile: null }) });
329
+ say(`Detached env profile from ${targetId}. New shells and commands will run without it.`);
330
+ return;
331
+ }
332
+ const wanted = profileRef ?? flags['env-profile'];
333
+ if (wanted) {
334
+ const res = await call('PUT', `/v1/sandboxes/${targetId}/env-profile`, {
335
+ headers: JSON_HEADERS,
336
+ body: JSON.stringify({ env_profile: wanted }),
337
+ });
338
+ const prof = res.env_profile;
339
+ say(`Attached env profile "${prof?.name || wanted}" to ${targetId} (${prof?.key_count ?? 0} vars). New shells and commands will use it.`);
340
+ return;
341
+ }
342
+ const current = await call('GET', `/v1/sandboxes/${targetId}/env-profile`);
343
+ if (!current.env_profile) {
344
+ say(`No env profile attached to ${targetId}. Attach one: raytrace sandbox env-profile ${targetId} <profile-name>`);
345
+ return;
346
+ }
347
+ const prof = current.env_profile;
348
+ say(`Env profile on ${targetId}: ${prof.name} (${prof.id}) · keys: ${(prof.keys || []).join(', ') || '(empty)'}`);
349
+ }
350
+
273
351
  export async function create(flags) {
352
+ if (flags.master) {
353
+ const masterMod = await import('./master.mjs');
354
+ return masterMod.createMaster(flags);
355
+ }
356
+ const masterRef = flags['from-master'] || null;
274
357
  if (flags.repo && !flags.connect) throw new Error('--repo names the GitHub repository to connect to: use it with --connect.');
275
358
  if (flags.connect && flags.local) throw new Error('GitHub repositories connect to cloud sandboxes only.');
276
- const root = repoRoot();
277
- if (!root) throw new Error('Run this from inside a Git repository.');
278
- const name = flags.name || basename(root);
359
+ if (flags['env-profile'] && flags.local) throw new Error('Env profiles require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
360
+ if (masterRef && flags.local) throw new Error('Master sandboxes require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
361
+ const root = flags.empty ? null : repoRoot();
362
+ if (!root && !masterRef) throw new Error('Run this from inside a Git repository (or pass --from-master <name> to start with an empty workspace).');
363
+ const name = flags.name || (root ? basename(root) : `${masterRef}-sandbox`);
279
364
  // Which GitHub repository to connect to, worked out before anything is uploaded.
280
365
  let connecting = null;
281
366
  if (flags.connect) {
282
- const repo = flags.repo ? githubRepo(flags.repo) : localRepo(root).repo;
367
+ const repo = flags.repo ? githubRepo(flags.repo) : (root ? localRepo(root).repo : null);
283
368
  if (!repo) {
284
369
  throw new Error(flags.repo ? `Not a GitHub repository: ${flags.repo} (use owner/name)`
285
370
  : "This repository's origin is not on GitHub. Name the one to connect to: --repo owner/name");
286
371
  }
287
- connecting = { repo, ...hereFor(repo) };
372
+ connecting = { repo, ...(root ? hereFor(repo) : {}) };
288
373
  }
289
374
  const requestedSize = flags.local ? null : validateSize(flags.size);
290
375
  // What the machine lacks is said before the project is read, and Lima fetched if agreed.
291
376
  const localName = flags.local ? local.sandboxName(flags, root) : null;
292
377
  if (flags.local) await local.preflight(flags, { confirm, interactive });
293
- const { files, skipped, total } = listProject(root);
378
+ const project = root ? listProject(root) : null;
294
379
  // The same files, packed the same way, as a cloud sandbox gets: only the copy stays here.
295
- if (flags.local) return local.create(localName, { root, files, skipped, total, archive: await pack(root, files) });
380
+ if (flags.local) return local.create(localName, { root, ...project, archive: await pack(root, project.files) });
296
381
 
297
382
  // A local sandbox never uses the beta grant.
298
383
  const { plan, beta } = await creditPlan();
@@ -304,13 +389,17 @@ export async function create(flags) {
304
389
  say(`This is your free beta sandbox${betaEnds(beta) ? `, until ${formatCreditDeadline(betaEnds(beta))}` : ''}.`);
305
390
  }
306
391
  const useCredit = plan === 'use';
307
- say(`Packing ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}`);
308
- if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
309
- const archive = await packArchive(root, files);
310
- say(`Creating the ${requestedSize || 'small'} sandbox (the first one on a host takes a little longer)...`);
392
+ let archive = null;
393
+ if (project) {
394
+ say(`Packing ${project.files.length} files (${(project.total / 1048576).toFixed(1)} MiB) from ${root}`);
395
+ if (project.skipped.length) say(`Not uploaded (${project.skipped.length}): ${project.skipped.slice(0, 8).join(', ')}${project.skipped.length > 8 ? ', ...' : ''}`);
396
+ archive = await packArchive(root, project.files);
397
+ }
398
+ say(`Creating the ${requestedSize || 'small'} sandbox${masterRef ? ` from master "${masterRef}"` : ''} (the first one on a host takes a little longer)...`);
399
+ const envProfileName = flags['env-profile'] || null;
311
400
  let box;
312
401
  try {
313
- box = await upload(archive, name, useCredit, requestedSize);
402
+ box = await upload(archive, name, useCredit, requestedSize, envProfileName, masterRef);
314
403
  } catch (error) {
315
404
  if (!useCredit || !isCreditRefusal(error)) throw formatActionError(error);
316
405
  say(error.status === 410 ? 'Your free beta sandbox expired before it was created.'
@@ -319,13 +408,19 @@ export async function create(flags) {
319
408
  throw new Error('Not created as your free beta sandbox; no sandbox was created.');
320
409
  }
321
410
  try {
322
- box = await upload(archive, name, false, requestedSize);
411
+ box = await upload(archive, name, false, requestedSize, envProfileName, masterRef);
323
412
  } catch (retryError) {
324
413
  throw formatActionError(retryError);
325
414
  }
326
415
  }
327
416
  const actualSize = box.size || requestedSize;
328
417
  say(`\nSandbox ${box.id}${actualSize ? ` (${actualSize})` : ''} is running.`);
418
+ if (box.master_name) {
419
+ say(`Master environment: ${box.master_name}${box.master_version ? ` v${box.master_version}` : ''} (/opt/env pre-loaded).`);
420
+ }
421
+ if (box.env_profile_name) {
422
+ say(`Env profile attached: ${box.env_profile_name} (injected at command/shell exec time; values scrubbed from traces).`);
423
+ }
329
424
  if (box.credit_applied) {
330
425
  say(`Your free beta sandbox${betaEnds(box) ? `, until ${formatCreditDeadline(betaEnds(box))}` : ''}. It shows as Beta in the dashboard.`);
331
426
  }
@@ -358,8 +453,10 @@ export async function list(flags = {}) {
358
453
  const age = Math.round((Date.now() - created) / 60000);
359
454
  const status = box.restoring ? 'restoring' : String(box.status);
360
455
  const size = box.size ? ` ${String(box.size).padEnd(6)}` : '';
456
+ const masterTag = box.master_name ? ` master:${box.master_name}${box.master_version ? `@v${box.master_version}` : ''}` : '';
457
+ const envTag = box.env_profile_name ? ` env:${box.env_profile_name}` : '';
361
458
  const beta = box.beta ? ` Beta${betaEnds(box) ? ` (until ${formatCreditDeadline(betaEnds(box))})` : ''}` : '';
362
- say(`${box.id} ${status.padEnd(9)}${size} ${box.name}${beta} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
459
+ say(`${box.id} ${status.padEnd(9)}${size} ${box.name}${masterTag}${envTag}${beta} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
363
460
  }
364
461
  }
365
462
 
@@ -36,20 +36,21 @@ Unless noted, a function raises `ValueError` on bad input and
36
36
  2. `/etc/raytace/image`;
37
37
  3. `raytace-gvisor-agent`.
38
38
  - `bridge()`: the bridge URL sandboxes are given, as `RAYTRACE_BROKER`.
39
- - `container_args(name, labels, limits=None, image_name=None)`: the one container
39
+ - `container_args(name, labels, limits=None, image_name=None, env_volume=False)`: the one container
40
40
  configuration used for projects and forks. It sets:
41
41
  - the `raytace-gvisor` runtime and the `raytace-egress` network;
42
42
  - no capabilities, `no-new-privileges`, and user 1000;
43
- - the two volumes and the host resolver;
43
+ - the workspace and home volumes (plus `<name>-env` at `/opt/env` when `env_volume=True`) and the host resolver;
44
44
  - the session environment.
45
- - `create_container(name, labels, limits=None, image_name=None)`: makes the
46
- volumes and the container, without starting it. Returns the container id.
45
+ - `seed_volume(volume_name, source_dir)`: populates a Docker volume from a host directory using `cp -a --reflink=auto`.
46
+ - `create_container(name, labels, limits=None, image_name=None, env_volume=False, seed_env_dir=None)`: makes the
47
+ volumes (seeding `<name>-env` when `seed_env_dir` is given) and the container, without starting it. Returns the container id.
47
48
 
48
49
  ### Lifecycle
49
50
  - `preflight()`: the collector and resolver must be running, otherwise
50
51
  `SystemExit`. It then runs `network.py`.
51
- - `create(sid, archive, limits=None, expect_release=None)`: creates a project
52
- sandbox from a staged `/tmp/<sid>.tar.gz` and returns its container id.
52
+ - `create(sid, archive=None, limits=None, expect_release=None, env_volume=False, seed_env_dir=None)`: creates a project
53
+ sandbox, optionally importing a staged `/tmp/<sid>.tar.gz` and/or seeding `/opt/env`, and returns its container id.
53
54
  - With `expect_release`, it holds `core.release.lock(shared=True)` from the
54
55
  check until the container exists.
55
56
  - It raises `SystemExit` if the active release is a different one, before
@@ -67,8 +68,9 @@ Unless noted, a function raises `ValueError` on bad input and
67
68
  3. Lock its restricted files while it is stopped.
68
69
  4. Put back its hook and lists from the host's copies.
69
70
  5. Call `remember()`.
70
- - `shell(sid, agent=None)`: an interactive bash in a started sandbox, optionally
71
- starting `claude` or `codex` first. Returns its exit code.
71
+ - `shell(sid, agent=None, env_file=None)`: an interactive bash in a started sandbox,
72
+ optionally starting `claude` or `codex` first and/or passing a host `--env-file`
73
+ to `docker exec` for this session only. Returns its exit code.
72
74
  - `stop(sid)`.
73
75
  - `delete(sid, forget_evidence=False)`: the sandbox must be stopped. Removes:
74
76
  - the container;
@@ -5,10 +5,29 @@ ARG CLAUDE_CODE_VERSION
5
5
  ARG CODEX_VERSION
6
6
  RUN test -n "$CLAUDE_CODE_VERSION" && test -n "$CODEX_VERSION" \
7
7
  || { echo "CLAUDE_CODE_VERSION and CODEX_VERSION are required" >&2; exit 1; }
8
- RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates python3 curl ripgrep \
8
+ RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates python3 python3-venv python3-pip curl ripgrep \
9
9
  && rm -rf /var/lib/apt/lists/*
10
10
  RUN npm install -g "@openai/codex@${CODEX_VERSION}" "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}"
11
- RUN mkdir /workspace && chown node:node /workspace
11
+ RUN mkdir -p /workspace /opt/env/bin /opt/env/npm /opt/env/pnpm /opt/env/cargo /opt/env/rustup /opt/env/go /opt/env/playwright /opt/env/cache/uv /opt/env/cache/pip \
12
+ && python3 -m venv /opt/env/venv \
13
+ && chown -R node:node /workspace /opt/env
12
14
  USER node
13
15
  WORKDIR /workspace
14
- ENV HOME=/home/node CODEX_HOME=/home/node/.codex
16
+ # Keep user-installed runtimes/packages in /opt/env (mounted as a volume when
17
+ # persisted across sandboxes) while pinning credential config files to /home/node.
18
+ ENV HOME=/home/node \
19
+ CODEX_HOME=/home/node/.codex \
20
+ VIRTUAL_ENV=/opt/env/venv \
21
+ NPM_CONFIG_PREFIX=/opt/env/npm \
22
+ PNPM_HOME=/opt/env/pnpm \
23
+ CARGO_HOME=/opt/env/cargo \
24
+ RUSTUP_HOME=/opt/env/rustup \
25
+ GOPATH=/opt/env/go \
26
+ PLAYWRIGHT_BROWSERS_PATH=/opt/env/playwright \
27
+ UV_CACHE_DIR=/opt/env/cache/uv \
28
+ PIP_CACHE_DIR=/opt/env/cache/pip \
29
+ NPM_CONFIG_USERCONFIG=/home/node/.npmrc \
30
+ PIP_CONFIG_FILE=/home/node/.config/pip/pip.conf \
31
+ NETRC=/home/node/.netrc \
32
+ DOCKER_CONFIG=/home/node/.docker \
33
+ PATH=/opt/env/venv/bin:/opt/env/npm/bin:/opt/env/pnpm:/opt/env/bin:/opt/env/cargo/bin:/opt/env/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
@@ -296,17 +296,22 @@ def start_container(name):
296
296
  below; starting one that already runs is a no-op."""
297
297
  run('docker', 'start', name, stdout=subprocess.DEVNULL)
298
298
 
299
- def container_args(name, labels, limits=None, image_name=None):
299
+ def container_args(name, labels, limits=None, image_name=None, env_volume=False):
300
300
  """`docker create` arguments for one sandbox: gVisor, the sandbox network,
301
- no capabilities, the agent user, the given limits, its two volumes and the
301
+ no capabilities, the agent user, the given limits, its volumes and the
302
302
  host's resolver. Projects and forks are made the same way."""
303
303
  limits = limits or DEFAULT_LIMITS
304
+ mounts = [
305
+ '--mount=type=volume,src='+name+'-workspace,dst=/workspace',
306
+ '--mount=type=volume,src='+name+'-home,dst=/home/node',
307
+ ]
308
+ if env_volume:
309
+ mounts.append('--mount=type=volume,src='+name+'-env,dst=/opt/env')
304
310
  return ['docker', 'create', '--name', name, *labels, '--runtime=raytace-gvisor',
305
311
  '--label', 'io.raytace.storage=volumes-v1',
306
312
  '--network=raytace-egress', '--cap-drop=ALL', '--security-opt=no-new-privileges',
307
313
  '--user=1000:1000', *limits.args(),
308
- '--mount=type=volume,src='+name+'-workspace,dst=/workspace',
309
- '--mount=type=volume,src='+name+'-home,dst=/home/node',
314
+ *mounts,
310
315
  '--mount=type=bind,src=/etc/raytace/resolv.conf,dst=/etc/resolv.conf,readonly',
311
316
  # Session marker on PID 1: env is inherited across fork/exec, so
312
317
  # every process in this sandbox carries it without the collector
@@ -318,11 +323,33 @@ def container_args(name, labels, limits=None, image_name=None):
318
323
  '--workdir=/workspace', '--entrypoint=/bin/sleep',
319
324
  image_name or image(), 'infinity']
320
325
 
321
- def create_container(name, labels, limits=None, image_name=None):
322
- """The sandbox's two volumes and its container (not started); its container id."""
323
- for suffix in ('workspace', 'home'):
326
+
327
+ def seed_volume(volume_name, source_dir):
328
+ """Populates a freshly created Docker volume from a host directory using
329
+ reflink Copy-on-Write when the filesystem supports it (`cp -a --reflink=auto`)."""
330
+ src = Path(source_dir)
331
+ if not src.is_dir():
332
+ raise ValueError(f'Seed directory does not exist: {source_dir}')
333
+ mountpoint = subprocess.check_output(
334
+ ['docker', 'volume', 'inspect', '-f', '{{.Mountpoint}}', volume_name],
335
+ text=True, timeout=20,
336
+ ).strip()
337
+ if not mountpoint or not Path(mountpoint).is_dir():
338
+ raise ValueError(f'Volume mountpoint missing for {volume_name}')
339
+ run('cp', '-a', '--reflink=auto', f'{src}/.', mountpoint)
340
+
341
+
342
+ def create_container(name, labels, limits=None, image_name=None, env_volume=False, seed_env_dir=None):
343
+ """The sandbox's volumes (workspace, home, and optionally env) and its container
344
+ (not started); returns its container id."""
345
+ if seed_env_dir is not None:
346
+ env_volume = True
347
+ suffixes = ('workspace', 'home', 'env') if env_volume else ('workspace', 'home')
348
+ for suffix in suffixes:
324
349
  run('docker', 'volume', 'create', *labels, name+'-'+suffix, stdout=subprocess.DEVNULL)
325
- return subprocess.check_output(container_args(name, labels, limits, image_name), text=True).strip()
350
+ if seed_env_dir is not None:
351
+ seed_volume(name+'-env', seed_env_dir)
352
+ return subprocess.check_output(container_args(name, labels, limits, image_name, env_volume=env_volume), text=True).strip()
326
353
 
327
354
  def fork_container(fork, parent, limits=None, image_name=None):
328
355
  """A sandbox like the project's own, for one Playground fork: same image,
@@ -529,8 +556,10 @@ def read_snapshot(project, running):
529
556
  except subprocess.CalledProcessError:
530
557
  raise SystemExit("RayTrace: this sandbox's snapshot history could not be read.") from None
531
558
 
532
- def create(sid, archive, limits=None, expect_release=None):
533
- """A new project sandbox from a staged import archive; its container id.
559
+ def create(sid, archive=None, limits=None, expect_release=None, env_volume=False, seed_env_dir=None):
560
+ """A new project sandbox, optionally importing a staged import archive into
561
+ /workspace. When `env_volume=True` (or `seed_env_dir` is given), mounts a
562
+ third `<sid>-env` volume at `/opt/env` and seeds it via reflink when given.
534
563
 
535
564
  With `expect_release`, the sandbox is made only from that active release
536
565
  (core/release.py): the release lock is held, shared, from the check until
@@ -538,23 +567,26 @@ def create(sid, archive, limits=None, expect_release=None):
538
567
  and the container is made from that release's image."""
539
568
  if not re.fullmatch(PROJECT_ID, sid):
540
569
  raise ValueError('Invalid sandbox ID')
541
- if not archive or not re.fullmatch(r'/tmp/rtp-[a-f0-9]{32}\.tar\.gz', archive):
542
- raise ValueError('Expected staged import archive')
543
- validate_archive(archive)
570
+ if archive is not None:
571
+ if not archive or not re.fullmatch(r'/tmp/rtp-[a-f0-9]{32}\.tar\.gz', archive):
572
+ raise ValueError('Expected staged import archive')
573
+ validate_archive(archive)
544
574
  preflight()
545
575
  if expect_release is None:
546
- return finish_create(sid, archive, create_container(sid, ['--label', LABEL+'='+sid], limits))
576
+ cid = create_container(sid, ['--label', LABEL+'='+sid], limits, env_volume=env_volume, seed_env_dir=seed_env_dir)
577
+ return finish_create(sid, archive, cid)
547
578
  with release.lock(shared=True):
548
579
  active = release.active()
549
580
  if not active or active.get('id') != expect_release:
550
581
  raise SystemExit(f'RayTrace: this host runs release {(active or {}).get("id") or "none"}, '
551
582
  f'not {expect_release}; no sandbox was created.')
552
583
  cid = create_container(sid, ['--label', LABEL+'='+sid, '--label', release.LABEL+'='+expect_release],
553
- limits, active['image'])
584
+ limits, active['image'], env_volume=env_volume, seed_env_dir=seed_env_dir)
554
585
  return finish_create(sid, archive, cid)
555
586
 
556
587
  def finish_create(sid, archive, cid):
557
- import_archive(cid, archive)
588
+ if archive is not None:
589
+ import_archive(cid, archive)
558
590
  remember(sid)
559
591
  return cid
560
592
 
@@ -716,15 +748,17 @@ def start(sid):
716
748
  guardrails(sid, inspect(sid))
717
749
  remember(sid)
718
750
 
719
- def shell(sid, agent=None):
751
+ def shell(sid, agent=None, env_file=None):
720
752
  """An interactive shell in a started sandbox (start() first); with `agent`,
721
- that agent first, without approval prompts. Returns the shell's exit code.
722
- Exiting never stops or removes the sandbox."""
753
+ that agent first, without approval prompts. With `env_file`, passes that
754
+ host file to `docker exec --env-file` for this session only. Returns the
755
+ shell's exit code. Exiting never stops or removes the sandbox."""
723
756
  line = 'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; '
724
757
  if agent:
725
758
  name, command = AGENTS[agent]
726
759
  line += f'cd /workspace 2>/dev/null; if command -v {agent} >/dev/null; then {command}; else echo "{name} is not installed in this sandbox."; fi; '
727
- return subprocess.run(['docker', 'exec', '-it', sid, '/bin/bash', '-c', line+'exec /bin/bash'], check=False).returncode
760
+ env_args = ['--env-file', str(env_file)] if env_file else []
761
+ return subprocess.run(['docker', 'exec', '-it', *env_args, sid, '/bin/bash', '-c', line+'exec /bin/bash'], check=False).returncode
728
762
 
729
763
  def stop(sid):
730
764
  inspect(sid)
@@ -758,7 +792,7 @@ def delete(sid, forget_evidence=False):
758
792
  (GUARDRAILS / (sid+'.json')).unlink(missing_ok=True)
759
793
  for cleanup in DELETE_CLEANUP:
760
794
  cleanup(sid)
761
- for suffix in ('workspace', 'home'):
795
+ for suffix in ('workspace', 'home', 'env'):
762
796
  volume = sid+'-'+suffix
763
797
  result = subprocess.run(['docker', 'volume', 'inspect', volume], capture_output=True, text=True)
764
798
  if result.returncode == 0: