@raytrace-cli/cli 0.22.2 → 0.22.4
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 +41 -3
- package/package.json +1 -1
- package/proxy/runtime-attribution.test.mjs +17 -1
- package/src/env-profile.mjs +108 -0
- package/src/mcp.mjs +4 -2
- package/src/sandbox.mjs +73 -5
- package/worker/sandbox/CORE_API.md +3 -2
- package/worker/sandbox/core/mechanics.py +6 -4
- package/worker/sandbox/engine.py +56 -28
- package/worker/sandbox/viewer.py +34 -17
package/bin/raytrace.mjs
CHANGED
|
@@ -30,9 +30,13 @@ 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] [--env-profile <name>]
|
|
34
34
|
upload this Git repository to a new sandbox
|
|
35
35
|
(up to 200 MiB, 25 MiB a file, 20,000 files; default: small)
|
|
36
|
+
raytrace sandbox env-profile [id] [<name> | --detach]
|
|
37
|
+
view, attach, or detach a cloud sandbox's env profile
|
|
38
|
+
raytrace env-profile list | create <name> | delete <id-or-name>
|
|
39
|
+
manage encrypted org env profiles (cloud, org admins)
|
|
36
40
|
raytrace sandbox create --connect [--repo owner/name]
|
|
37
41
|
the same, then make it a clone of the repository's
|
|
38
42
|
GitHub origin (or --repo) that its agent can fetch
|
|
@@ -233,9 +237,11 @@ if (command === 'sandbox') {
|
|
|
233
237
|
repo: { type: 'string' },
|
|
234
238
|
add: { type: 'string', multiple: true },
|
|
235
239
|
remove: { type: 'string', multiple: true },
|
|
240
|
+
'env-profile': { type: 'string' },
|
|
241
|
+
detach: { type: 'boolean' },
|
|
236
242
|
} });
|
|
237
243
|
} catch (error) { console.error(`${error.message}\n\nRun \`raytrace help\` for usage.`); process.exit(2); }
|
|
238
|
-
const [sub, id] = parsed.positionals;
|
|
244
|
+
const [sub, id, extraArg] = parsed.positionals;
|
|
239
245
|
if (sub === 'destroy' && parsed.values['delete-logs'] && parsed.values['keep-logs']) {
|
|
240
246
|
console.error('raytrace sandbox destroy: Pick one: --delete-logs or --keep-logs.'); process.exit(2);
|
|
241
247
|
}
|
|
@@ -249,6 +255,7 @@ if (command === 'sandbox') {
|
|
|
249
255
|
destroy: () => sandbox.destroy(id, parsed.values),
|
|
250
256
|
files: () => sandbox.files(id, parsed.values),
|
|
251
257
|
repos: () => sandbox.repos(id, parsed.values),
|
|
258
|
+
'env-profile': () => sandbox.envProfile(id, extraArg, parsed.values),
|
|
252
259
|
};
|
|
253
260
|
const action = actions[sub];
|
|
254
261
|
if (!sub) { console.error(SANDBOX_HELP); process.exit(2); }
|
|
@@ -257,6 +264,37 @@ if (command === 'sandbox') {
|
|
|
257
264
|
catch (error) { console.error(`raytrace sandbox ${sub}: ${error.message}`); process.exit(1); }
|
|
258
265
|
}
|
|
259
266
|
|
|
267
|
+
if (command === 'env-profile') {
|
|
268
|
+
const usage = 'Usage: raytrace env-profile list | create <name> [--from-file <path>] [--var KEY=VALUE ...] [--description <text>] [--admin-only] | delete <id-or-name> [--yes]';
|
|
269
|
+
let parsed;
|
|
270
|
+
try {
|
|
271
|
+
parsed = parseArgs({ args: rest, strict: true, allowPositionals: true, options: {
|
|
272
|
+
yes: { type: 'boolean', short: 'y' },
|
|
273
|
+
description: { type: 'string' },
|
|
274
|
+
'admin-only': { type: 'boolean' },
|
|
275
|
+
'from-file': { type: 'string' },
|
|
276
|
+
var: { type: 'string', multiple: true },
|
|
277
|
+
local: { type: 'boolean' },
|
|
278
|
+
} });
|
|
279
|
+
} catch (error) { console.error(`${error.message}\n\n${usage}`); process.exit(2); }
|
|
280
|
+
if (parsed.values.local) {
|
|
281
|
+
console.error('raytrace env-profile: Env profiles require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
|
|
282
|
+
process.exit(2);
|
|
283
|
+
}
|
|
284
|
+
const [sub, target, ...extra] = parsed.positionals;
|
|
285
|
+
if (!sub || extra.length) { console.error(usage); process.exit(2); }
|
|
286
|
+
const envMod = await import('../src/env-profile.mjs');
|
|
287
|
+
const actions = {
|
|
288
|
+
list: () => envMod.listEnvProfiles(),
|
|
289
|
+
create: () => envMod.createEnvProfile(target, parsed.values),
|
|
290
|
+
delete: () => envMod.deleteEnvProfile(target, parsed.values),
|
|
291
|
+
};
|
|
292
|
+
const action = actions[sub];
|
|
293
|
+
if (!action) { console.error(unknownCommand(sub, Object.keys(actions), 'env-profile')); process.exit(2); }
|
|
294
|
+
try { await action(); process.exit(0); }
|
|
295
|
+
catch (error) { console.error(`raytrace env-profile ${sub}: ${error.message}`); process.exit(1); }
|
|
296
|
+
}
|
|
297
|
+
|
|
260
298
|
if (command === 'upload') {
|
|
261
299
|
let parsed;
|
|
262
300
|
try {
|
|
@@ -404,7 +442,7 @@ const actions = {
|
|
|
404
442
|
const run = actions[command];
|
|
405
443
|
|
|
406
444
|
if (!run) {
|
|
407
|
-
const names = [...Object.keys(actions), 'auth', 'code', 'codex', 'connect', 'export', 'help', 'hook', 'key', 'mcp', 'report', 'sandbox', 'share', 'upload'];
|
|
445
|
+
const names = [...Object.keys(actions), 'auth', 'code', 'codex', 'connect', 'env-profile', 'export', 'help', 'hook', 'key', 'mcp', 'report', 'sandbox', 'share', 'upload'];
|
|
408
446
|
console.error(unknownCommand(command, names)); process.exit(2);
|
|
409
447
|
}
|
|
410
448
|
try { await run(); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@raytrace-cli/cli",
|
|
3
|
-
"version": "0.22.
|
|
3
|
+
"version": "0.22.4",
|
|
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",
|
|
@@ -198,7 +198,23 @@ test('isolated Edit (no Bash) is verified=true from file fact without kernel_con
|
|
|
198
198
|
assert.equal(readCall.verified, false);
|
|
199
199
|
assert.equal(readCall.kernel_confirmed, false);
|
|
200
200
|
assert.equal(readCall.file_confirmed, false);
|
|
201
|
-
assert.equal(readCall.status, 'in_agent', 'Read
|
|
201
|
+
assert.equal(readCall.status, 'in_agent', 'Read without a file fact stays in_agent, not a missing command');
|
|
202
|
+
|
|
203
|
+
// When engine.py emits a confirmed read fact for an announced Read (#156), Read becomes verified=true without kernel_confirmed.
|
|
204
|
+
const dbWithReadFact = {
|
|
205
|
+
...store,
|
|
206
|
+
activityFactsForCalls: async (callIds) => new Map([
|
|
207
|
+
...(callIds.includes('toolu_read_1') ? [['toolu_read_1', [{ kind: 'file', subject: 'slugify.py', effect: 'read', call_from: 'tool_report', pid: 741, process: 'claude.exe' }]]] : []),
|
|
208
|
+
...(callIds.includes('toolu_edit_1') ? [['toolu_edit_1', [{ kind: 'file', subject: 'slugify.py', effect: 'changed', call_from: 'tool_report', pid: 741, process: 'claude.exe' }]]] : []),
|
|
209
|
+
]),
|
|
210
|
+
};
|
|
211
|
+
const [traceWithRead] = await readTraces(dbWithReadFact, { includeHistory: true });
|
|
212
|
+
const verifiedRead = traceWithRead.callVerifications.find((c) => c.call_id === 'toolu_read_1');
|
|
213
|
+
assert.equal(verifiedRead.verified, true);
|
|
214
|
+
assert.equal(verifiedRead.file_confirmed, true);
|
|
215
|
+
assert.equal(verifiedRead.kernel_confirmed, false);
|
|
216
|
+
assert.equal(verifiedRead.source, 'file_fact');
|
|
217
|
+
assert.equal(verifiedRead.match_basis, 'tool_report');
|
|
202
218
|
}));
|
|
203
219
|
|
|
204
220
|
test('command call with an activity fact carrying call_id reports join_pending instead of not_executed (#151)', () => withStore(async (store) => {
|
|
@@ -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/mcp.mjs
CHANGED
|
@@ -87,6 +87,7 @@ 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
|
+
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
91
|
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
92
|
},
|
|
92
93
|
additionalProperties: false,
|
|
@@ -344,9 +345,10 @@ function githubTarget(root, wanted, named) {
|
|
|
344
345
|
}
|
|
345
346
|
|
|
346
347
|
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) {
|
|
348
|
+
github: wantGithub = false, github_repo: namedRepo, env_profile: envProfile, without_beta_credit: plain = false }, step) {
|
|
348
349
|
if (!AGENTS[agent]) throw new ToolError(`agent must be one of: ${Object.keys(AGENTS).join(', ')}.`);
|
|
349
350
|
if (local && (wantGithub || namedRepo !== undefined)) throw new ToolError('GitHub repositories connect to cloud sandboxes only; leave out github for a local sandbox.');
|
|
351
|
+
if (local && envProfile !== undefined && envProfile !== '') throw new ToolError('Env profiles apply to cloud sandboxes only; leave out env_profile for a local sandbox.');
|
|
350
352
|
const root = await projectRoot(path);
|
|
351
353
|
if (local) return createLocal(root, name, installLima, connect && agent, step);
|
|
352
354
|
const github = githubTarget(root, wantGithub, namedRepo);
|
|
@@ -365,7 +367,7 @@ async function createSandbox({ path, name, local = false, install_lima: installL
|
|
|
365
367
|
step('Creating the sandbox');
|
|
366
368
|
let box;
|
|
367
369
|
try {
|
|
368
|
-
box = await upload(archive, name || basename(root), useCredit);
|
|
370
|
+
box = await upload(archive, name || basename(root), useCredit, null, envProfile || null);
|
|
369
371
|
} catch (error) {
|
|
370
372
|
if (!useCredit || !isCreditRefusal(error)) throw error;
|
|
371
373
|
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,40 @@ export function formatActionError(error) {
|
|
|
171
171
|
return error;
|
|
172
172
|
}
|
|
173
173
|
|
|
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
|
+
|
|
174
198
|
/** Create a cloud sandbox from a packed project. A credit refusal comes back
|
|
175
199
|
* as an ApiError (see isCreditRefusal) for the caller to decide on. */
|
|
176
|
-
export function upload(archive, name, useCredit, size = null) {
|
|
177
|
-
const
|
|
200
|
+
export function upload(archive, name, useCredit, size = null, envProfile = null) {
|
|
201
|
+
const cleanName = name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100);
|
|
202
|
+
if (envProfile) {
|
|
203
|
+
const metadata = { name: cleanName, ...(size ? { size } : {}), env_profile: envProfile, ...(useCredit ? { beta_credit: true } : {}) };
|
|
204
|
+
const { contentType, body } = buildMultipartUpload(metadata, archive);
|
|
205
|
+
return call('POST', '/v1/sandboxes', { body, headers: { 'content-type': contentType } });
|
|
206
|
+
}
|
|
207
|
+
const headers = { 'content-type': 'application/gzip', 'x-raytrace-name': cleanName };
|
|
178
208
|
if (size) headers['x-raytrace-size'] = size;
|
|
179
209
|
if (useCredit) headers['x-raytrace-beta-credit'] = '1';
|
|
180
210
|
return call('POST', '/v1/sandboxes', { body: archive, headers });
|
|
@@ -270,9 +300,42 @@ export async function repos(id, flags = {}) {
|
|
|
270
300
|
say(pushRule(targetId));
|
|
271
301
|
}
|
|
272
302
|
|
|
303
|
+
/** `raytrace sandbox env-profile [id] [<profile-name-or-id> | --detach]` */
|
|
304
|
+
export async function envProfile(id, profileRef, flags = {}) {
|
|
305
|
+
if (flags.local || (id && local.isLocal(id))) {
|
|
306
|
+
throw new Error('Env profiles require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
|
|
307
|
+
}
|
|
308
|
+
// Allow `raytrace sandbox env-profile <profile-name>` when there is a single cloud sandbox? Keep explicit:
|
|
309
|
+
// If id is not an rtp-... id and no profileRef was given, treat id as sandbox id so pickId/checkId gives a clear error.
|
|
310
|
+
const targetId = await pickId(id);
|
|
311
|
+
if (flags.detach) {
|
|
312
|
+
await call('PUT', `/v1/sandboxes/${targetId}/env-profile`, { headers: JSON_HEADERS, body: JSON.stringify({ env_profile: null }) });
|
|
313
|
+
say(`Detached env profile from ${targetId}. New shells and commands will run without it.`);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const wanted = profileRef ?? flags['env-profile'];
|
|
317
|
+
if (wanted) {
|
|
318
|
+
const res = await call('PUT', `/v1/sandboxes/${targetId}/env-profile`, {
|
|
319
|
+
headers: JSON_HEADERS,
|
|
320
|
+
body: JSON.stringify({ env_profile: wanted }),
|
|
321
|
+
});
|
|
322
|
+
const prof = res.env_profile;
|
|
323
|
+
say(`Attached env profile "${prof?.name || wanted}" to ${targetId} (${prof?.key_count ?? 0} vars). New shells and commands will use it.`);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const current = await call('GET', `/v1/sandboxes/${targetId}/env-profile`);
|
|
327
|
+
if (!current.env_profile) {
|
|
328
|
+
say(`No env profile attached to ${targetId}. Attach one: raytrace sandbox env-profile ${targetId} <profile-name>`);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
const prof = current.env_profile;
|
|
332
|
+
say(`Env profile on ${targetId}: ${prof.name} (${prof.id}) · keys: ${(prof.keys || []).join(', ') || '(empty)'}`);
|
|
333
|
+
}
|
|
334
|
+
|
|
273
335
|
export async function create(flags) {
|
|
274
336
|
if (flags.repo && !flags.connect) throw new Error('--repo names the GitHub repository to connect to: use it with --connect.');
|
|
275
337
|
if (flags.connect && flags.local) throw new Error('GitHub repositories connect to cloud sandboxes only.');
|
|
338
|
+
if (flags['env-profile'] && flags.local) throw new Error('Env profiles require a hosted RayTrace account and apply to cloud sandboxes only; omit --local.');
|
|
276
339
|
const root = repoRoot();
|
|
277
340
|
if (!root) throw new Error('Run this from inside a Git repository.');
|
|
278
341
|
const name = flags.name || basename(root);
|
|
@@ -308,9 +371,10 @@ export async function create(flags) {
|
|
|
308
371
|
if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
|
|
309
372
|
const archive = await packArchive(root, files);
|
|
310
373
|
say(`Creating the ${requestedSize || 'small'} sandbox (the first one on a host takes a little longer)...`);
|
|
374
|
+
const envProfileName = flags['env-profile'] || null;
|
|
311
375
|
let box;
|
|
312
376
|
try {
|
|
313
|
-
box = await upload(archive, name, useCredit, requestedSize);
|
|
377
|
+
box = await upload(archive, name, useCredit, requestedSize, envProfileName);
|
|
314
378
|
} catch (error) {
|
|
315
379
|
if (!useCredit || !isCreditRefusal(error)) throw formatActionError(error);
|
|
316
380
|
say(error.status === 410 ? 'Your free beta sandbox expired before it was created.'
|
|
@@ -319,13 +383,16 @@ export async function create(flags) {
|
|
|
319
383
|
throw new Error('Not created as your free beta sandbox; no sandbox was created.');
|
|
320
384
|
}
|
|
321
385
|
try {
|
|
322
|
-
box = await upload(archive, name, false, requestedSize);
|
|
386
|
+
box = await upload(archive, name, false, requestedSize, envProfileName);
|
|
323
387
|
} catch (retryError) {
|
|
324
388
|
throw formatActionError(retryError);
|
|
325
389
|
}
|
|
326
390
|
}
|
|
327
391
|
const actualSize = box.size || requestedSize;
|
|
328
392
|
say(`\nSandbox ${box.id}${actualSize ? ` (${actualSize})` : ''} is running.`);
|
|
393
|
+
if (box.env_profile_name) {
|
|
394
|
+
say(`Env profile attached: ${box.env_profile_name} (injected at command/shell exec time; values scrubbed from traces).`);
|
|
395
|
+
}
|
|
329
396
|
if (box.credit_applied) {
|
|
330
397
|
say(`Your free beta sandbox${betaEnds(box) ? `, until ${formatCreditDeadline(betaEnds(box))}` : ''}. It shows as Beta in the dashboard.`);
|
|
331
398
|
}
|
|
@@ -358,8 +425,9 @@ export async function list(flags = {}) {
|
|
|
358
425
|
const age = Math.round((Date.now() - created) / 60000);
|
|
359
426
|
const status = box.restoring ? 'restoring' : String(box.status);
|
|
360
427
|
const size = box.size ? ` ${String(box.size).padEnd(6)}` : '';
|
|
428
|
+
const envTag = box.env_profile_name ? ` env:${box.env_profile_name}` : '';
|
|
361
429
|
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)`);
|
|
430
|
+
say(`${box.id} ${status.padEnd(9)}${size} ${box.name}${envTag}${beta} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
|
|
363
431
|
}
|
|
364
432
|
}
|
|
365
433
|
|
|
@@ -67,8 +67,9 @@ Unless noted, a function raises `ValueError` on bad input and
|
|
|
67
67
|
3. Lock its restricted files while it is stopped.
|
|
68
68
|
4. Put back its hook and lists from the host's copies.
|
|
69
69
|
5. Call `remember()`.
|
|
70
|
-
- `shell(sid, agent=None)`: an interactive bash in a started sandbox,
|
|
71
|
-
starting `claude` or `codex` first
|
|
70
|
+
- `shell(sid, agent=None, env_file=None)`: an interactive bash in a started sandbox,
|
|
71
|
+
optionally starting `claude` or `codex` first and/or passing a host `--env-file`
|
|
72
|
+
to `docker exec` for this session only. Returns its exit code.
|
|
72
73
|
- `stop(sid)`.
|
|
73
74
|
- `delete(sid, forget_evidence=False)`: the sandbox must be stopped. Removes:
|
|
74
75
|
- the container;
|
|
@@ -716,15 +716,17 @@ def start(sid):
|
|
|
716
716
|
guardrails(sid, inspect(sid))
|
|
717
717
|
remember(sid)
|
|
718
718
|
|
|
719
|
-
def shell(sid, agent=None):
|
|
719
|
+
def shell(sid, agent=None, env_file=None):
|
|
720
720
|
"""An interactive shell in a started sandbox (start() first); with `agent`,
|
|
721
|
-
that agent first, without approval prompts.
|
|
722
|
-
|
|
721
|
+
that agent first, without approval prompts. With `env_file`, passes that
|
|
722
|
+
host file to `docker exec --env-file` for this session only. Returns the
|
|
723
|
+
shell's exit code. Exiting never stops or removes the sandbox."""
|
|
723
724
|
line = 'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; '
|
|
724
725
|
if agent:
|
|
725
726
|
name, command = AGENTS[agent]
|
|
726
727
|
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
|
-
|
|
728
|
+
env_args = ['--env-file', str(env_file)] if env_file else []
|
|
729
|
+
return subprocess.run(['docker', 'exec', '-it', *env_args, sid, '/bin/bash', '-c', line+'exec /bin/bash'], check=False).returncode
|
|
728
730
|
|
|
729
731
|
def stop(sid):
|
|
730
732
|
inspect(sid)
|
package/worker/sandbox/engine.py
CHANGED
|
@@ -268,7 +268,7 @@ def project_path(event):
|
|
|
268
268
|
def dist_info_from_path(path):
|
|
269
269
|
"""If `path` is a Python package metadata file inside a `*.dist-info`
|
|
270
270
|
folder anywhere in the container (including `/tmp/venv`), return
|
|
271
|
-
`('pip', package, version)`; else None."""
|
|
271
|
+
`('pip', package, version, site_dir)`; else None."""
|
|
272
272
|
if not path:
|
|
273
273
|
return None
|
|
274
274
|
folder, leaf = posixpath.split(path)
|
|
@@ -280,7 +280,8 @@ def dist_info_from_path(path):
|
|
|
280
280
|
package, _, version = dist[:-len('.dist-info')].rpartition('-')
|
|
281
281
|
if not package or not version or package.startswith('.'):
|
|
282
282
|
return None
|
|
283
|
-
|
|
283
|
+
site_dir = posixpath.dirname(folder) or '/'
|
|
284
|
+
return ('pip', package[:200], version[:80], site_dir[:300])
|
|
284
285
|
|
|
285
286
|
|
|
286
287
|
def is_package_manager(argv):
|
|
@@ -331,18 +332,24 @@ def package_prefixes(argv):
|
|
|
331
332
|
return found
|
|
332
333
|
|
|
333
334
|
|
|
334
|
-
def _scan_pip_site(found, volume, site):
|
|
335
|
+
def _scan_pip_site(found, volume, site, container_site):
|
|
335
336
|
for name in names_inside(volume, site):
|
|
336
337
|
if name.endswith('.dist-info') and '-' in name:
|
|
337
338
|
package, _, version = name[:-len('.dist-info')].rpartition('-')
|
|
338
339
|
if package and version:
|
|
339
|
-
found[('pip', package[:200], version[:80])] = None
|
|
340
|
+
found[('pip', package[:200], version[:80], container_site[:300])] = None
|
|
340
341
|
|
|
341
342
|
|
|
342
343
|
def installed(workspace, home, extra_prefixes=()):
|
|
343
|
-
"""{(manager, name, version): where it came from} as the package
|
|
344
|
-
own records on the host-mounted volumes have it. The agent can
|
|
345
|
-
files, so a fact drawn from them is `reported`, not seen.
|
|
344
|
+
"""{(manager, name, version, site_dir): where it came from} as the package
|
|
345
|
+
managers' own records on the host-mounted volumes have it. The agent can
|
|
346
|
+
write those files, so a fact drawn from them is `reported`, not seen.
|
|
347
|
+
|
|
348
|
+
Keys include `site_dir` (the container path of the site-packages or
|
|
349
|
+
node_modules directory) so installing the same `(name, version)` into a
|
|
350
|
+
second environment (e.g. `/tmp/venv` after `/tmp/pylibs`) is not dropped,
|
|
351
|
+
while volume scans and `opened()` observations of the same prefix still
|
|
352
|
+
deduplicate cleanly.
|
|
346
353
|
|
|
347
354
|
`extra_prefixes` may name container prefixes (e.g. `/workspace/custom-env`
|
|
348
355
|
or `/home/node/myenv`) extracted from package-manager argv; only prefixes
|
|
@@ -354,6 +361,7 @@ def installed(workspace, home, extra_prefixes=()):
|
|
|
354
361
|
roots = [''] + [name for name in names_inside(workspace, '') if name not in SKIPPED and not name.startswith('.')][:50]
|
|
355
362
|
for root in roots:
|
|
356
363
|
modules = posixpath.join(root, 'node_modules')
|
|
364
|
+
container_modules = posixpath.normpath(WORKSPACE + modules)
|
|
357
365
|
lock = read_inside(workspace, posixpath.join(modules, '.package-lock.json'), 32 * 1024 * 1024)
|
|
358
366
|
try:
|
|
359
367
|
listed = json.loads(lock)['packages'] if lock else None
|
|
@@ -362,7 +370,7 @@ def installed(workspace, home, extra_prefixes=()):
|
|
|
362
370
|
if isinstance(listed, dict):
|
|
363
371
|
for key, entry in listed.items():
|
|
364
372
|
if isinstance(key, str) and isinstance(entry, dict) and isinstance(entry.get('version'), str):
|
|
365
|
-
found[('npm', key.rsplit('node_modules/', 1)[-1][:200], entry['version'][:80])] = str(entry.get('resolved') or '')[:300] or None
|
|
373
|
+
found[('npm', key.rsplit('node_modules/', 1)[-1][:200], entry['version'][:80], container_modules[:300])] = str(entry.get('resolved') or '')[:300] or None
|
|
366
374
|
continue
|
|
367
375
|
# No npm record (yarn, pnpm, bun): the packages at the top of node_modules.
|
|
368
376
|
for name in names_inside(workspace, modules)[:1000]:
|
|
@@ -374,9 +382,12 @@ def installed(workspace, home, extra_prefixes=()):
|
|
|
374
382
|
except (ValueError, KeyError, TypeError):
|
|
375
383
|
version = None
|
|
376
384
|
if isinstance(version, str):
|
|
377
|
-
found[('node', package[:200], version[:80])] = None
|
|
378
|
-
sites = ([(workspace, posixpath.join(env, 'lib')) for env in ('.venv', 'venv')] if workspace else [])
|
|
385
|
+
found[('node', package[:200], version[:80], container_modules[:300])] = None
|
|
386
|
+
sites = ([(workspace, posixpath.join(env, 'lib'), posixpath.normpath(WORKSPACE + posixpath.join(env, 'lib'))) for env in ('.venv', 'venv')] if workspace else []) \
|
|
387
|
+
+ ([(home, '.local/lib', '/home/node/.local/lib')] if home else [])
|
|
379
388
|
direct_sites = []
|
|
389
|
+
seen_sites = {(v, lib) for v, lib, _ in sites}
|
|
390
|
+
seen_direct = set()
|
|
380
391
|
for prefix in extra_prefixes or ():
|
|
381
392
|
if not isinstance(prefix, str) or not prefix:
|
|
382
393
|
continue
|
|
@@ -384,24 +395,30 @@ def installed(workspace, home, extra_prefixes=()):
|
|
|
384
395
|
if workspace and (norm == WORKSPACE.rstrip('/') or norm.startswith(WORKSPACE)):
|
|
385
396
|
rel = norm[len(WORKSPACE):] if norm.startswith(WORKSPACE) else ''
|
|
386
397
|
lib = posixpath.join(rel, 'lib') if rel else 'lib'
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
398
|
+
container_lib = posixpath.join(norm, 'lib')
|
|
399
|
+
if (workspace, lib) not in seen_sites:
|
|
400
|
+
seen_sites.add((workspace, lib))
|
|
401
|
+
sites.append((workspace, lib, container_lib))
|
|
402
|
+
if rel and (workspace, rel) not in seen_direct:
|
|
403
|
+
seen_direct.add((workspace, rel))
|
|
404
|
+
direct_sites.append((workspace, rel, norm))
|
|
391
405
|
elif home and norm.startswith('/home/'):
|
|
392
406
|
parts = PurePosixPath(norm).parts # ('/', 'home', '<user>', ...)
|
|
393
407
|
if len(parts) >= 4:
|
|
394
408
|
rel = posixpath.join(*parts[3:])
|
|
395
409
|
lib = posixpath.join(rel, 'lib')
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
410
|
+
container_lib = posixpath.join(norm, 'lib')
|
|
411
|
+
if (home, lib) not in seen_sites:
|
|
412
|
+
seen_sites.add((home, lib))
|
|
413
|
+
sites.append((home, lib, container_lib))
|
|
414
|
+
if (home, rel) not in seen_direct:
|
|
415
|
+
seen_direct.add((home, rel))
|
|
416
|
+
direct_sites.append((home, rel, norm))
|
|
417
|
+
for volume, lib, container_lib in sites:
|
|
401
418
|
for python in names_inside(volume, lib)[:10]:
|
|
402
|
-
_scan_pip_site(found, volume, posixpath.join(lib, python, 'site-packages'))
|
|
403
|
-
for volume, site in direct_sites:
|
|
404
|
-
_scan_pip_site(found, volume, site)
|
|
419
|
+
_scan_pip_site(found, volume, posixpath.join(lib, python, 'site-packages'), posixpath.join(container_lib, python, 'site-packages'))
|
|
420
|
+
for volume, site, container_site in direct_sites:
|
|
421
|
+
_scan_pip_site(found, volume, site, container_site)
|
|
405
422
|
return found
|
|
406
423
|
|
|
407
424
|
|
|
@@ -940,6 +957,15 @@ class Engine(threading.Thread):
|
|
|
940
957
|
if guard is None:
|
|
941
958
|
if writing and not errno and box.guarded:
|
|
942
959
|
box.aliases.append({'path': path, 'who': who, 'at_ns': at_ns, 'syscall': self.calls.get(event.get('sysno'), ('open', 'open'))[0]})
|
|
960
|
+
elif not writing and not errno and not who.get('own'):
|
|
961
|
+
announced_who = self.called(box, who, path, at_ns)
|
|
962
|
+
if announced_who.get('call_from') == 'tool_report':
|
|
963
|
+
call = self.calls.get(event.get('sysno'), ('open', 'open'))[0]
|
|
964
|
+
self.fact(box, 'file', (path, 'read'), announced_who,
|
|
965
|
+
{'path': path, 'guard': None, 'effect': 'read', 'certainty': 'confirmed',
|
|
966
|
+
'basis': {'syscall': call, 'flags': flags, 'resolution': 'lexical',
|
|
967
|
+
'note': 'opened for reading; the bytes read are not captured'}}, at_ns)
|
|
968
|
+
return
|
|
943
969
|
return self.counted(box, who, top, at_ns)
|
|
944
970
|
who = self.called(box, who, path, at_ns)
|
|
945
971
|
call = self.calls.get(event.get('sysno'), ('open', 'open'))[0]
|
|
@@ -953,7 +979,9 @@ class Engine(threading.Thread):
|
|
|
953
979
|
if not writing:
|
|
954
980
|
# Reads of ordinary files are counted, as before: a test run reads hundreds.
|
|
955
981
|
# So is the snapshot hook reading every file after each tool call.
|
|
956
|
-
|
|
982
|
+
# An explicit agent Read tool call announced by the hook (`call_from=tool_report`)
|
|
983
|
+
# is recorded as a confirmed read fact from the kernel open syscall (#156).
|
|
984
|
+
if (guard == 'project' and who.get('call_from') != 'tool_report') or who.get('own'):
|
|
957
985
|
return self.counted(box, who, top, at_ns)
|
|
958
986
|
self.fact(box, 'file', (path, 'read'), who, {'path': path, 'guard': guard, 'effect': 'read', 'certainty': 'confirmed',
|
|
959
987
|
'basis': {**basis, 'note': 'opened for reading; the bytes read are not captured'}}, at_ns)
|
|
@@ -1324,13 +1352,13 @@ class Engine(threading.Thread):
|
|
|
1324
1352
|
who = box.package_who or {}
|
|
1325
1353
|
# Seen reaching a registry about then: the list is the manager's own word, with that beside it.
|
|
1326
1354
|
certainty = 'corroborated' if self.clock() - box.registry_at < 300 else 'reported'
|
|
1327
|
-
for manager in sorted({key[0] for key in fresh}):
|
|
1328
|
-
mine = [key for key in fresh if key[0] == manager]
|
|
1329
|
-
fact = self.fact(box, 'package', (manager,), who, {'manager': manager, 'packages': [], 'total': 0, 'effect': 'installed',
|
|
1355
|
+
for manager, site_dir in sorted({(key[0], key[3]) for key in fresh}):
|
|
1356
|
+
mine = [key for key in fresh if key[0] == manager and key[3] == site_dir]
|
|
1357
|
+
fact = self.fact(box, 'package', (manager, site_dir), who, {'manager': manager, 'prefix': site_dir, 'packages': [], 'total': 0, 'effect': 'installed',
|
|
1330
1358
|
'basis': {'note': "read from the package manager's own records in the sandbox after it ran; the agent can write those files"}},
|
|
1331
1359
|
time.time_ns())
|
|
1332
1360
|
fact['certainty'] = certainty
|
|
1333
1361
|
fact['total'] += len(mine)
|
|
1334
1362
|
room = MAX_PACKAGES - len(fact['packages'])
|
|
1335
|
-
fact['packages'] += [{'name': name, 'version': version, **({'source': now[(manager, name, version)]} if now[(manager, name, version)] else {})}
|
|
1336
|
-
for _, name, version in mine[:max(0, room)]]
|
|
1363
|
+
fact['packages'] += [{'name': name, 'version': version, **({'source': now[(manager, name, version, site_dir)]} if now[(manager, name, version, site_dir)] else {})}
|
|
1364
|
+
for _, name, version, _ in mine[:max(0, room)]]
|
package/worker/sandbox/viewer.py
CHANGED
|
@@ -55,19 +55,29 @@ def event_page(db, query):
|
|
|
55
55
|
clauses.append("kind IN ('exec_succeeded','exec_failed','process_exit','collection_gap','collection_error','collector_connected','collector_disconnected')")
|
|
56
56
|
where = ' WHERE ' + ' AND '.join(clauses) if clauses else ''
|
|
57
57
|
order = 'ASC' if 'after' in query else 'DESC'
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
58
|
+
# Hold a single SQLite read snapshot across the event select and
|
|
59
|
+
# coverage_page() so a process_exit written in between can never advance
|
|
60
|
+
# coverage.latest past the returned rows and make the forwarder skip it (#157).
|
|
61
|
+
started_tx = not db.in_transaction
|
|
62
|
+
if started_tx:
|
|
63
|
+
db.execute('BEGIN')
|
|
64
|
+
try:
|
|
65
|
+
rows = db.execute('SELECT id,body,container_id FROM runtime_events'+where+' ORDER BY id '+order+' LIMIT ?', (*params, limit+1)).fetchall()
|
|
66
|
+
events = []
|
|
67
|
+
for identifier, body, bound_container in rows[:limit]:
|
|
68
|
+
event=json.loads(body); event.pop('raw_packet_base64',None)
|
|
69
|
+
event['event_id']=identifier; event['container_id']=bound_container; events.append(event)
|
|
70
|
+
page = {'events':events,'next_before':None if 'after' in query else (rows[limit-1][0] if len(rows)>limit else None)}
|
|
71
|
+
if 'after' in query:
|
|
72
|
+
page['next_after'] = rows[limit-1][0] if len(rows) > limit else None
|
|
73
|
+
# Metadata comes from the same selected container and time interval,
|
|
74
|
+
# independently of pagination or the processes-only display filter.
|
|
75
|
+
page['coverage'] = coverage_page(db, query)
|
|
76
|
+
page['gaps'] = page['coverage']['gaps']
|
|
77
|
+
return page
|
|
78
|
+
finally:
|
|
79
|
+
if started_tx and db.in_transaction:
|
|
80
|
+
db.execute('COMMIT')
|
|
71
81
|
|
|
72
82
|
|
|
73
83
|
def coverage_page(db, query):
|
|
@@ -113,10 +123,17 @@ def fact_page(db, query):
|
|
|
113
123
|
clauses, params = ['id > ?'], [after]
|
|
114
124
|
if container:
|
|
115
125
|
clauses.append('container_id = ?'); params.append(container)
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
126
|
+
started_tx = not db.in_transaction
|
|
127
|
+
if started_tx:
|
|
128
|
+
db.execute('BEGIN')
|
|
129
|
+
try:
|
|
130
|
+
rows = db.execute('SELECT id, body FROM facts WHERE ' + ' AND '.join(clauses) + ' ORDER BY id LIMIT ?', (*params, limit + 1)).fetchall()
|
|
131
|
+
facts = [{**json.loads(body), 'id': identifier} for identifier, body in rows[:limit]]
|
|
132
|
+
latest = db.execute("SELECT seq FROM sqlite_sequence WHERE name = 'facts'").fetchone()
|
|
133
|
+
return {'facts': facts, 'next_after': facts[-1]['id'] if len(rows) > limit else None, 'latest': latest[0] if latest else 0}
|
|
134
|
+
finally:
|
|
135
|
+
if started_tx and db.in_transaction:
|
|
136
|
+
db.execute('COMMIT')
|
|
120
137
|
|
|
121
138
|
PAGE = '''<!doctype html><meta charset="utf-8"><title>RayTrace runtime evidence</title>
|
|
122
139
|
<style>body{font:15px system-ui;background:#111827;color:#e5e7eb;margin:32px}table{width:100%;border-collapse:collapse}td,th{text-align:left;padding:10px;border-bottom:1px solid #374151}code{white-space:pre-wrap}select{padding:8px} .note{color:#fbbf24}</style>
|