@raytrace-cli/cli 0.6.0 → 0.8.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 +56 -1
- package/bin/raytrace.mjs +25 -0
- package/dist/dashboard/assets/{index-Dc3LTk8b.js → index-CeIGjyFc.js} +1 -1
- package/dist/dashboard/index.html +1 -1
- package/package.json +1 -1
- package/src/api.mjs +57 -0
- package/src/auth.mjs +63 -21
- package/src/beta.mjs +96 -0
- package/src/mcp.mjs +330 -0
- package/src/sandbox.mjs +118 -53
package/README.md
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
[ npm package ](https://www.npmjs.com/package/@raytrace-cli/cli) ·
|
|
6
6
|
[ Quick start ](#quick-start) · [ Cloud sandboxes ](#cloud-sandboxes-preview) ·
|
|
7
|
+
[ Editor (MCP) ](#use-from-your-editor-mcp) ·
|
|
7
8
|
[ Local sandboxes ](#local-sandboxes) ·
|
|
8
9
|
[ Privacy ](#privacy) · [ Report an issue ](https://github.com/Godcreatebugs/raytrace-cli/issues)
|
|
9
10
|
|
|
@@ -82,6 +83,33 @@ which one the CLI is using.
|
|
|
82
83
|
Cloud sandboxes are a preview and may change; please
|
|
83
84
|
[report issues](https://github.com/Godcreatebugs/raytrace-cli/issues) you run into.
|
|
84
85
|
|
|
86
|
+
## Use from your editor (MCP)
|
|
87
|
+
|
|
88
|
+
`raytrace mcp` is an [MCP](https://modelcontextprotocol.io) server, so the agent
|
|
89
|
+
in VS Code, Cursor, Claude Code or any MCP client can create and manage cloud
|
|
90
|
+
sandboxes for you: "put this project in a sandbox", "stop my sandbox",
|
|
91
|
+
"destroy rtp-…". Nothing to install first; `npx` fetches the CLI.
|
|
92
|
+
|
|
93
|
+
- **Claude Code:** `claude mcp add raytrace -- npx -y @raytrace-cli/cli mcp`
|
|
94
|
+
- **VS Code** (`.vscode/mcp.json`):
|
|
95
|
+
```json
|
|
96
|
+
{ "servers": { "raytrace": { "command": "npx", "args": ["-y", "@raytrace-cli/cli", "mcp"] } } }
|
|
97
|
+
```
|
|
98
|
+
- **Cursor** (`~/.cursor/mcp.json`) and most other clients:
|
|
99
|
+
```json
|
|
100
|
+
{ "mcpServers": { "raytrace": { "command": "npx", "args": ["-y", "@raytrace-cli/cli", "mcp"] } } }
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Tools: `login`, `create_sandbox`, `list_sandboxes`, `sandbox_status`,
|
|
104
|
+
`start_sandbox`, `stop_sandbox`, `destroy_sandbox`. The first time, the agent
|
|
105
|
+
calls `login` and shows you a code to approve in the browser; it is the same
|
|
106
|
+
sign-in as `raytrace auth login`. `create_sandbox` uploads the Git project open
|
|
107
|
+
in your editor, with the same rules and limits as `raytrace sandbox create`.
|
|
108
|
+
`destroy_sandbox` deletes the sandbox's traces too unless the agent passes
|
|
109
|
+
`keep_traces` (paid plans), as `raytrace sandbox destroy --yes` does. To work
|
|
110
|
+
inside a sandbox, run `raytrace connect <id>` in a terminal. Local sandboxes
|
|
111
|
+
stay terminal-only for now.
|
|
112
|
+
|
|
85
113
|
## Local sandboxes
|
|
86
114
|
|
|
87
115
|
Prefer to keep your project on your own machine? Run the same sandbox locally.
|
|
@@ -185,6 +213,8 @@ raytrace key # which keys are set
|
|
|
185
213
|
| `raytrace sandbox start\|stop [id]` | start or stop a sandbox; stopping keeps its files |
|
|
186
214
|
| `raytrace sandbox destroy [id]` | delete a sandbox; its recorded sessions are kept |
|
|
187
215
|
| `raytrace auth login` | sign in to RayTrace; `status`, `logout` |
|
|
216
|
+
| `raytrace mcp` | MCP server on stdio for your editor's agent; see [Use from your editor](#use-from-your-editor-mcp) |
|
|
217
|
+
| `raytrace --code <code>` | beta invite: redeem a code RayTrace gave you (signed in first) for one $10-credit sandbox; codes are single-use, are deleted on redemption, and expire after 3 days, as does the credit |
|
|
188
218
|
| `raytrace sandbox create --local [--name <name>]` | the same sandbox in a Linux VM on this machine; offers to download Lima if needed (`--yes` skips the question) |
|
|
189
219
|
| `raytrace sandbox list --local` | your local sandboxes; their names work with `connect`, `start`, `stop` and `destroy` |
|
|
190
220
|
| `raytrace sandbox destroy <name> [--delete-logs \| --keep-logs]` | delete a local sandbox; asks whether its captured logs go too, or move to `~/.raytrace/archive` |
|
|
@@ -192,6 +222,29 @@ raytrace key # which keys are set
|
|
|
192
222
|
| `raytrace doctor` | what this machine has and lacks, local sandboxes included |
|
|
193
223
|
| `raytrace key [openrouter\|typesafe] [--remove]` | your keys for the dashboard's AI features; asked for, never taken as an argument |
|
|
194
224
|
|
|
225
|
+
## Beta invites
|
|
226
|
+
|
|
227
|
+
If RayTrace gave you a beta code, sign in first, redeem it, then create your
|
|
228
|
+
sandbox — in that order:
|
|
229
|
+
|
|
230
|
+
```sh
|
|
231
|
+
raytrace auth login
|
|
232
|
+
raytrace --code <code> # also: raytrace code <code>
|
|
233
|
+
raytrace sandbox create
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Redeeming deletes the code on RayTrace's servers; it can never be used
|
|
237
|
+
again, by anyone. Codes expire 3 days after they are issued, and the $10 of
|
|
238
|
+
OpenRouter credit expires 3 days after you redeem it, so do not sit on
|
|
239
|
+
either. Your account shows as **Beta** in the cloud dashboard until the
|
|
240
|
+
credit ends, and the credited sandbox is tagged Beta there too. Connecting
|
|
241
|
+
to a credited sandbox after its 3 days are up warns you that model calls
|
|
242
|
+
will be refused; the sandbox itself still opens.
|
|
243
|
+
|
|
244
|
+
Codes are minted only from the backend repo (`raytrace`:
|
|
245
|
+
`python3 worker/gvisor/mint_beta_codes.py`, 10 at a time); this CLI never
|
|
246
|
+
generates them.
|
|
247
|
+
|
|
195
248
|
## Exporting traces
|
|
196
249
|
|
|
197
250
|
Export a recorded session directly from local evidence, even when RayTrace and the VM are stopped:
|
|
@@ -222,7 +275,9 @@ RayTrace's servers.
|
|
|
222
275
|
organizations cannot.
|
|
223
276
|
- `raytrace auth login` keeps your sign-in in the macOS Keychain or the Linux
|
|
224
277
|
secret service (a file readable only by you where neither is available), and
|
|
225
|
-
`raytrace auth logout` removes it.
|
|
278
|
+
`raytrace auth logout` removes it. Cloud commands ask you to sign in again
|
|
279
|
+
after 2 days with no cloud use (any cloud command resets that clock); the
|
|
280
|
+
command then continues where it left off. Local recording never asks.
|
|
226
281
|
- What RayTrace records locally stays in `~/.raytrace`, readable only by you.
|
|
227
282
|
Its local API takes the token in `~/.raytrace/api-token`, so another account
|
|
228
283
|
on the machine cannot read your traces or spend your OpenRouter key through
|
package/bin/raytrace.mjs
CHANGED
|
@@ -18,11 +18,18 @@ Cloud sandboxes:
|
|
|
18
18
|
(up to 200 MiB, 25 MiB a file, 20,000 files)
|
|
19
19
|
raytrace connect [id] a terminal in it; with one sandbox the id is
|
|
20
20
|
optional (same as: raytrace sandbox shell [id])
|
|
21
|
+
raytrace --code <code> beta invite: redeem a code RayTrace gave you for one
|
|
22
|
+
$10-credit sandbox (signed in first; also: raytrace code <code>)
|
|
21
23
|
raytrace sandbox list
|
|
22
24
|
raytrace sandbox start|stop [id]
|
|
23
25
|
raytrace sandbox destroy [id] [--yes] [--keep-traces]
|
|
24
26
|
delete it; traces go too unless --keep-traces (paid plans)
|
|
25
27
|
|
|
28
|
+
Use from your editor's agent (VS Code, Cursor, Claude Code, any MCP client):
|
|
29
|
+
raytrace mcp MCP server on stdio: sign in, create, list, start,
|
|
30
|
+
stop and destroy cloud sandboxes. Add it to your
|
|
31
|
+
editor as the command: npx -y @raytrace-cli/cli mcp
|
|
32
|
+
|
|
26
33
|
Local sandboxes (your project stays on this machine):
|
|
27
34
|
raytrace sandbox create --local [--name <name>] [--yes]
|
|
28
35
|
a copy of this Git repository in a gVisor sandbox
|
|
@@ -77,8 +84,26 @@ if (command === '--version' || command === '-v') {
|
|
|
77
84
|
console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
|
|
78
85
|
process.exit(0);
|
|
79
86
|
}
|
|
87
|
+
// `raytrace mcp`: stdout belongs to the MCP protocol, so nothing else may run first.
|
|
88
|
+
if (command === 'mcp') {
|
|
89
|
+
if (rest.length) { console.error('Usage: raytrace mcp'); process.exit(2); }
|
|
90
|
+
const { serve } = await import('../src/mcp.mjs');
|
|
91
|
+
await serve();
|
|
92
|
+
process.exit(0);
|
|
93
|
+
}
|
|
94
|
+
|
|
80
95
|
if (!command || command === 'help' || command === '--help' || command === '-h') { console.log(HELP); process.exit(0); }
|
|
81
96
|
|
|
97
|
+
// `raytrace --code <code>` (also `raytrace code <code>`): redeem a beta code.
|
|
98
|
+
if (command === '--code' || command.startsWith('--code=') || command === 'code') {
|
|
99
|
+
const beta = await import('../src/beta.mjs');
|
|
100
|
+
const code = command.startsWith('--code=') ? command.slice('--code='.length) : rest[0];
|
|
101
|
+
const extra = command.startsWith('--code=') ? rest.length : rest.length - 1;
|
|
102
|
+
if (!code || extra !== 0) { console.error('Usage: raytrace --code <code>'); process.exit(2); }
|
|
103
|
+
try { await beta.redeemBetaCode(code); process.exit(0); }
|
|
104
|
+
catch (error) { console.error(`raytrace --code: ${error.message}`); process.exit(1); }
|
|
105
|
+
}
|
|
106
|
+
|
|
82
107
|
const commands = await import('../src/commands.mjs');
|
|
83
108
|
|
|
84
109
|
// `codex` passes everything after it straight to Codex.
|
|
@@ -32,7 +32,7 @@ Error generating stack: `+e.message+`
|
|
|
32
32
|
`)[0]})]}),i&&e.kind===`call`&&e.turn_id&&e.external_call_id&&(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>i(e.turn_id,e.external_call_id),children:`sandbox evidence`})]},e.id))}),(0,K.jsxs)(`div`,{className:`rt-search-pages`,children:[(0,K.jsx)(`button`,{type:`button`,className:`rt-button`,disabled:p===0,onClick:()=>m(Math.max(p-50,0)),children:`Newer`}),(0,K.jsx)(`button`,{type:`button`,className:`rt-button`,disabled:p+50>=(h.total??0),onClick:()=>m(p+50),children:`Older`})]})]})]})]}),h?.mode===`stats`&&(0,K.jsxs)(`div`,{className:`rt-search-stats`,children:[(0,K.jsx)(`div`,{className:`rt-list-head`,children:(0,K.jsxs)(`span`,{children:[h.agg===`avg_duration`?`AVG DURATION (MS)`:`COUNT`,h.by?` BY ${h.by.toUpperCase()}`:``]})}),(0,K.jsx)(`table`,{children:(0,K.jsx)(`tbody`,{children:(h.rows??[]).map((e,t)=>(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`td`,{children:String(e.key??`(none)`)}),(0,K.jsx)(`td`,{className:`rt-stat-bar`,"aria-label":String(e.value??e.count??``),children:(0,K.jsx)(`span`,{style:{width:`${Math.max(2,100*Number(e.value??e.count??0)/Math.max(...(h.rows??[]).map(e=>Number(e.value??e.count??0)),1))}%`}})}),(0,K.jsx)(`td`,{children:String(e.value??e.count??``)})]},t))})}),!(h.rows??[]).length&&(0,K.jsx)(`p`,{className:`rt-empty`,children:`No events match.`})]}),h?.mode===`timechart`&&(0,K.jsxs)(`div`,{className:`rt-search-chart`,children:[(0,K.jsx)(cD,{rows:h.rows??[],height:240,series:(h.series??[]).map((e,t)=>({key:e,label:e,color:rD[t%rD.length]}))}),(0,K.jsx)(`small`,{children:(h.series??[]).map((e,t)=>(0,K.jsxs)(`span`,{className:`rt-legend-item`,children:[(0,K.jsx)(`i`,{style:{background:rD[t%rD.length]}}),e,` `]},e))}),!(h.rows??[]).length&&(0,K.jsx)(`p`,{className:`rt-empty`,children:`No events match.`})]}),(0,K.jsxs)(`p`,{className:`rt-search-help`,children:[`Fields: `,(0,K.jsx)(`code`,{children:`outcome reported observed tool model category kind exit http file signature session after before`}),`. Pipes: `,(0,K.jsx)(`code`,{children:`| stats count by tool`}),`, `,(0,K.jsx)(`code`,{children:`| stats avg(duration) by model`}),`, `,(0,K.jsx)(`code`,{children:`| timechart count by outcome span=1d`}),`. Prefix `,(0,K.jsx)(`code`,{children:`-`}),` negates; trailing `,(0,K.jsx)(`code`,{children:`*`}),` is a prefix match.`]})]})}var uD={read:`Read`,search:`Search`,write:`Write`,edit:`Edit`,delete:`Delete / move`,run:`Run`,test:`Test`,build:`Build / install`,git:`Git`,web:`Web`,plan:`Plan`,delegate:`Delegate`,unsure:`Not sure`};function dD(e,t){let n=e.find(e=>{if(!e.title.startsWith(`Tool result:`))return!1;try{return JSON.parse(e.raw).call_id===t}catch{return!1}});if(!n)return{state:`none`,code:null,output:``};let r=``,i=!1,a=null;try{let e=JSON.parse(n.raw),t=e.output??e.content;r=typeof t==`string`?t:JSON.stringify(t??``),i=e.is_error===!0||e.status===`failed`;let o=typeof e.exit_code==`number`?e.exit_code:t&&typeof t==`object`&&typeof t.exit_code==`number`?t.exit_code:null;typeof o==`number`&&(a=o)}catch{}if(i)return{state:`failed`,code:a,output:r};if(a!==null)return{state:a===0?`ok`:`failed`,code:a,output:r};if(/Rejected\(/.test(r))return{state:`rejected`,code:null,output:r};let o=Number(r.match(/Process exited with code (\d+)/)?.[1]??NaN);return Number.isFinite(o)?{state:o===0?`ok`:`failed`,code:o,output:r}:{state:/failed/i.test(r.slice(0,80))?`failed`:`ok`,code:null,output:r}}var fD=(e,t)=>{let n=String(e??``).replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n},pD=e=>e.split(`/`).filter(Boolean).at(-1)??e,mD={delete:45,git:40,write:35,edit:35,build:30,test:28,run:22,delegate:20,web:10,plan:8,read:5,search:5,unsure:8},hD=[[/\brm\s+-[a-z]*[rf]/,`Deletes files (rm -r/-f)`],[/\bsudo\b/,`Runs with elevated privileges (sudo)`],[/\b(curl|wget)\b[^|]*\|\s*(ba|z)?sh\b/,`Pipes a download straight into a shell`],[/\bgit\s+(push|reset\s+--hard|clean\s+-[a-z]*f|checkout\s+--\s)/,`Hard-to-undo git operation`],[/\b(drop\s+(table|database)|truncate\s+table|delete\s+from)\b/i,`Deletes stored data`],[/\bkill\s+-9\b|\bmkfs\b|\bdd\s+.*of=\/dev\//,`Can destroy processes or disks`],[/\b(npm|pnpm|yarn|pip|pip3|brew|apt(-get)?)\s+(install|add|i)\b/,`Installs or changes dependencies`],[/\bchmod\s+(-R\s+)?[0-7]{3,4}\b|\bchown\s+-R\b/,`Changes file permissions or ownership`]];function gD(e){return e.snapshot?.changed?(e.snapshot.changes??[]).map(e=>e.path):[]}function _D(e,t,n){let r=gD(t[n]).map(pD).filter(e=>e.length>=3);return r.length?t.slice(n+1).filter(e=>{let t=`${e.proposed??``} ${gD(e).join(` `)}`;return r.some(e=>t.includes(e))}).length:0}function vD(e,t,n,r=e.callVerifications??[]){let i=[],a=mD[t.category??`unsure`]??8;t.category&&i.push(`${uD[t.category]} step`);let o=t.proposed??``;for(let[e,t]of hD)e.test(o)&&(a+=30,i.push(t));let s=gD(t);s.length&&(a+=Math.min(30,s.length*10),i.push(`Changed ${s.length} file${s.length===1?``:`s`}: ${s.slice(0,3).map(pD).join(`, `)}${s.length>3?`, …`:``}`));let c=dD(e.events,t.call_id);c.state===`failed`&&(a+=25,i.push(`Failed as reported to the agent${c.code==null?``:` (exit ${c.code})`}`)),c.state===`rejected`&&(a+=25,i.push(`Refused by the sandbox policy`)),t.exit_code!=null&&t.exit_code!==0&&(a+=20,i.push(`Sandbox saw exit ${t.exit_code}`)),t.reported_check&&t.reported_check!==`agrees`&&(a+=25,i.push(`What the agent was told differs from what the sandbox saw`));let l=t.descendant_count??t.descendants?.length??0;l>1&&(a+=Math.min(15,l),i.push(`Ran ${l} processes underneath it`)),(c.state===`failed`||c.state===`rejected`)&&n+1<r.length&&(a+=12,i.push(`The run changed course after this step`));let u=_D(e,r,n);return u&&(a+=Math.min(18,u*6),i.push(`${u} later step${u===1?``:`s`} built on what it produced`)),n===r.length-1&&r.length>1&&(a+=5,i.push(`Last step before the final answer`)),{score:a,reasons:i}}var yD=e=>fD((e.proposed??e.name).split(`
|
|
33
33
|
`).find(e=>e.trim())?.trim()??e.name,90);function bD(e){let t=e.callVerifications??[],n=t.map((n,r)=>({call:n,step:r+1,...vD(e,n,r,t),label:yD(n)}));if(!n.length)return[];let r=n.filter(e=>e.score>=28);return r.length>8&&(r=[...r].sort((e,t)=>t.score-e.score).slice(0,8)),r.length<3&&(r=[...n].sort((e,t)=>t.score-e.score).slice(0,Math.min(5,n.length))),r.sort((e,t)=>e.step-t.step)}function xD(e){let t=e.callVerifications??[];return t.length?t.map((n,r)=>({call:n,step:r+1,...vD(e,n,r,t),label:yD(n)})).sort((e,t)=>t.score-e.score||e.step-t.step)[0]:null}function SD(e,t){let n=e.callVerifications??[],r=n.findIndex(e=>e.call_id===t.call_id),i=r+1,a=[],o=e.events.filter(e=>e.title===`Model answer`&&e.exchange_id===t.exchange_id&&e.detail?.trim()).map(e=>e.detail).join(` `);o&&a.push({kind:`agent`,text:fD(o,300)});let s=r>0?n[r-1]:null,c=s?dD(e.events,s.call_id):null;s&&c&&(c.state!==`ok`||c.output.trim())&&a.push({kind:`result`,step:r,text:fD(c.output,260)||`Step #${r} ${c.state}`}),a.length||a.push({kind:`request`,text:fD(e.title,300)});let l=dD(e.events,t.call_id),u=[];t.exec_id||t.kernel_confirmed?u.push(`The sandbox saw it run${t.exit_code==null?``:` · exit ${t.exit_code}`}${(t.descendant_count??0)>0?` · ${t.descendant_count} child process${t.descendant_count===1?``:`es`}`:``}.`):t.snapshot?u.push(t.snapshot.changed?`The sandbox's snapshot after it shows ${t.snapshot.changes.length} file change${t.snapshot.changes.length===1?``:`s`}.`:`The sandbox's snapshot after it shows no file change.`):l.state===`rejected`?u.push(`The sandbox policy refused it; it never ran.`):e.sandboxId&&u.push(`The sandbox saw no process for this call. Missing evidence is not proof it did not run.`),l.state!==`none`&&u.push(`The agent was told: ${l.state}${l.code==null?``:` (exit ${l.code})`}${l.output.trim()?` — ${fD(l.output,180)}`:``}`),t.reported_check&&t.reported_check!==`agrees`&&u.push(`That report differs from what the sandbox observed — worth checking before trusting either.`),u.length||u.push(`No independent observation was recorded for this call.`);let d=gD(t),f=[];d.length&&f.push(`Changed ${d.map(e=>`\`${e}\``).join(`, `)}.`);let p=r>=0?_D(e,n,r):0;p&&f.push(`${p} later step${p===1?``:`s`} worked on what this produced, so later results depend on it.`);let m=r>=0?n[r+1]:void 0;m?f.push(`The next step (#${i+1}) was: ${yD(m)}.`):e.answer&&f.push(`After this, the agent answered: ${fD(e.answer,220)}`),f.length||f.push(`Nothing later in the record depends on it directly.`);let h=c&&(c.state===`failed`||c.state===`rejected`)?`Step #${r} had just ${c.state===`rejected`?`been refused`:`failed`} as the agent heard it, so this reads as a reaction to that result rather than a planned first move.`:o?`The agent said, just before proposing it: “${fD(o,180)}” That is its own account, not private reasoning.`:r<=0?`This follows directly from your request; the agent had seen nothing else yet.`:`Nothing the agent said at the time explains it beyond the sequence: it follows step #${r} and your original request.`;return{trigger:a,proposed:t.proposed??t.name,observed:u,consequence:f,why:h}}var CD={request:`Your request`,agent:`The agent said, just before`,result:`What the previous step returned`};function wD({trace:e,focusCall:t,onSelect:n,onOpenCall:r,onOpenThought:i,onOpenSandbox:a}){let o=e.callVerifications??[],s=bD(e),c=xD(e),[l,u]=(0,_.useState)(t);(0,_.useEffect)(()=>{t&&u(t)},[t]);let d=l&&o.some(e=>e.call_id===l)?l:c?.call.call_id??null,f=s.find(e=>e.call.call_id===d)??(c&&d===c.call.call_id?c:null)??s[0]??null,p=f?SD(e,f.call):null,m=(0,K.jsx)(`header`,{className:`rt-view-head`,children:(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`eyebrow`,children:`STORY`}),(0,K.jsx)(`h1`,{children:`What mattered in this run, and why`}),(0,K.jsx)(`p`,{className:`rt-muted rt-cot-caption`,children:`A timeline of the consequential steps only. Why a step happened is a reading of what the agent could see — not its private reasoning.`})]})});if(!o.length)return(0,K.jsxs)(`section`,{className:`rt-view`,children:[m,(0,K.jsx)(`p`,{className:`rt-empty`,children:`This prompt made no tool calls, so there is no story to rank. The final answer is the whole run.`})]});let h=e=>{u(e.call.call_id),n?.(e.call.call_id)},g=e=>c?.call.call_id===e.call.call_id;return(0,K.jsxs)(`section`,{className:`rt-view`,children:[m,(0,K.jsx)(YT,{trace:e,onStep:e=>{u(e),n?.(e)}}),(0,K.jsxs)(`div`,{className:`rt-story`,children:[(0,K.jsxs)(`aside`,{className:`rt-story-rail`,"aria-label":`Timeline of key moments`,children:[(0,K.jsx)(`h2`,{children:`Key moments`}),(0,K.jsxs)(`p`,{className:`rt-story-rail-note`,children:[s.length,` of `,o.length,` step`,o.length===1?``:`s`,` earned a place, ranked by files changed, failures, processes spawned, and what later steps built on.`]}),(0,K.jsx)(`ol`,{className:`rt-story-timeline`,children:s.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,"aria-label":`Step ${e.step}: ${e.label}`,className:`rt-story-node${f?.call.call_id===e.call.call_id?` active`:``}`,onClick:()=>h(e),children:[(0,K.jsx)(`span`,{className:`rt-story-dot`,"aria-hidden":!0}),(0,K.jsxs)(`span`,{className:`rt-story-node-body`,children:[(0,K.jsxs)(`span`,{className:`rt-story-node-head`,children:[(0,K.jsxs)(`span`,{className:`rt-cot-num`,children:[`#`,e.step]}),g(e)&&(0,K.jsxs)(`span`,{className:`rt-story-top`,children:[(0,K.jsx)(ye,{size:11}),` Most consequential`]}),(0,K.jsx)(`span`,{className:`rt-story-score`,title:`Consequence score, from the reasons listed for this step`,children:e.score})]}),(0,K.jsx)(`span`,{className:`rt-story-node-label`,children:e.label}),(0,K.jsx)(`span`,{className:`rt-story-node-why`,children:e.reasons[1]??e.reasons[0]??``})]})]})},e.call.call_id))}),(0,K.jsx)(`p`,{className:`rt-story-rail-note`,children:`Routine reads, searches and retries that changed nothing are in Tool calls, not here.`})]}),f&&p&&(0,K.jsxs)(`article`,{className:`rt-story-main`,"aria-label":`Story of step ${f.step}`,children:[g(f)?(0,K.jsxs)(`p`,{className:`rt-story-banner`,children:[(0,K.jsx)(ye,{size:13}),` The most consequential command of this run — the one later steps and the final answer most depend on.`]}):(0,K.jsxs)(`p`,{className:`rt-story-banner rt-story-banner-quiet`,children:[`Step #`,f.step,` of `,o.length,` · consequence score `,f.score]}),(0,K.jsxs)(`h2`,{className:`rt-story-title`,children:[`Step #`,f.step,`: `,f.label]}),(0,K.jsx)(`div`,{className:`rt-story-cmd`,children:(0,K.jsx)(Au,{text:p.proposed})}),(0,K.jsx)(`h3`,{children:`Why it did that`}),(0,K.jsx)(`p`,{className:`rt-story-why`,children:p.why}),(0,K.jsx)(`ul`,{className:`rt-story-list`,children:p.trigger.map((e,t)=>(0,K.jsxs)(`li`,{children:[(0,K.jsx)(`span`,{className:`rt-story-tag`,children:e.step?`${CD[e.kind]} (#${e.step})`:CD[e.kind]}),` `,e.text]},t))}),(0,K.jsx)(`h3`,{children:`What actually happened`}),(0,K.jsx)(`ul`,{className:`rt-story-list`,children:p.observed.map((e,t)=>(0,K.jsx)(`li`,{children:e},t))}),(0,K.jsx)(`h3`,{children:`Why it matters`}),(0,K.jsx)(`ul`,{className:`rt-story-list`,children:p.consequence.map((e,t)=>(0,K.jsx)(`li`,{children:e},t))}),(0,K.jsx)(`h3`,{children:`What earned its place`}),(0,K.jsx)(`div`,{className:`rt-chips`,children:f.reasons.map(e=>(0,K.jsx)(`span`,{className:`rt-chip rt-story-reason`,children:e},e))}),(0,K.jsxs)(`div`,{className:`rt-story-actions`,children:[r&&(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,onClick:()=>r(f.call.call_id),children:[(0,K.jsx)(we,{size:12}),` Open in Tool calls`]}),i&&(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,onClick:()=>i(f.call.call_id),children:[(0,K.jsx)(R,{size:12}),` Ranked causes`]}),a&&(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,onClick:()=>a(f.call.call_id),children:[(0,K.jsx)(ve,{size:12}),` Sandbox evidence`]})]}),(0,K.jsx)(`p`,{className:`rt-foot`,children:`Ranked from recorded facts only — files changed, exit codes, processes the sandbox saw, disagreements between the agent's report and the sandbox, and what later steps reused. No model was asked to write this.`})]})]})]})}var TD={A:`added`,M:`edited`,D:`deleted`,T:`type changed`};function ED({trace:e,onOpenCall:t}){let n=ST(e),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(``),l=e.sandboxId,u=!!(l&&n.base&&n.final&&n.files.length);async function d(t){if(l&&n.base&&n.final){o(!0),c(``);try{let r=await OT(l,n.base,n.final,t);if(!r.diff){c(`That diff came back empty, so nothing was downloaded.`);return}kT(wT(e,t),r.diff),r.truncated&&c(`Downloaded, but the diff was larger than the 500 KB the snapshot view returns: this patch is incomplete.`)}catch(e){c(`Could not build the patch: ${e instanceof Error?e.message:String(e)}`)}finally{o(!1)}}}return(0,K.jsxs)(`section`,{className:`rt-view rt-changes`,children:[(0,K.jsxs)(`header`,{className:`rt-view-head`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`eyebrow`,children:`CHANGES`}),(0,K.jsx)(`h1`,{children:`What this prompt changed`})]}),(0,K.jsx)(`div`,{className:`rt-actions`,children:(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,disabled:!u||a,onClick:()=>void d(),title:u?`One patch file with every change this prompt made, to apply in your local copy`:`Needs a sandbox run whose file snapshots were recorded`,children:[(0,K.jsx)(H,{size:14}),` `,a?`Building patch…`:`Download patch`]})})]}),l?n.hasSnapshots?n.files.length?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`dl`,{className:`rt-stats`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Files changed`}),(0,K.jsx)(`dd`,{children:n.files.length})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Lines added`}),(0,K.jsxs)(`dd`,{children:[`+`,n.added]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Lines removed`}),(0,K.jsxs)(`dd`,{children:[`−`,n.removed]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Steps that changed files`}),(0,K.jsx)(`dd`,{children:n.steps.length})]})]}),s&&(0,K.jsx)(`p`,{role:`alert`,className:`verify-error`,children:s}),(0,K.jsx)(`h2`,{children:`Across the whole prompt`}),(0,K.jsx)(`ul`,{className:`rt-files`,children:n.files.map(e=>(0,K.jsxs)(_.Fragment,{children:[(0,K.jsxs)(`li`,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`rt-file-toggle`,"aria-expanded":r===e.path,onClick:()=>i(r===e.path?null:e.path),children:[(0,K.jsx)(B,{size:12,className:`rt-caret${r===e.path?` down`:``}`}),(0,K.jsx)(`span`,{className:`rt-file-status s-${e.status}`,children:TD[e.status]??e.status}),(0,K.jsx)(`code`,{children:e.path})]}),(0,K.jsxs)(`small`,{children:[e.added==null?`binary`:`+${e.added} −${e.removed}`,` · step`,e.calls.length>1?`s`:``,` `,e.calls.map(e=>`#${e}`).join(`, `)]})]}),r===e.path&&n.base&&n.final&&(0,K.jsxs)(`li`,{className:`rt-file-diff`,children:[(0,K.jsx)(PT,{sandbox:l,from:n.base,to:n.final,path:e.path}),(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,disabled:a,onClick:()=>void d(e.path),children:[(0,K.jsx)(H,{size:13}),` `,`Download this file's patch`]})]})]},e.path))}),n.tooBig.length>0&&(0,K.jsxs)(`p`,{className:`rt-files-note`,children:[`Too big to snapshot (over 5 MB), so their changes are not in this list or the patch: `,n.tooBig.join(`, `)]}),(0,K.jsxs)(`div`,{className:`rt-changes-apply`,children:[(0,K.jsx)(`h2`,{children:`Take it into your local copy`}),(0,K.jsxs)(`p`,{children:[`Download the patch above, put it in your project folder, and check before applying:`,` `,(0,K.jsxs)(`code`,{children:[`git apply --check `,wT(e)]}),`, then `,(0,K.jsxs)(`code`,{children:[`git apply `,wT(e)]}),`. The patch is built from the sandbox's snapshots of this prompt only. It may not apply cleanly if your local copy has changed since the sandbox was created — review it like any other change.`]})]}),(0,K.jsxs)(`div`,{className:`rt-changes-steps`,children:[(0,K.jsx)(`h2`,{children:`Step by step`}),n.steps.map(({call:e,number:n})=>(0,K.jsxs)(`div`,{className:`rt-changes-step`,children:[(0,K.jsxs)(`p`,{className:`rt-files-note`,children:[`#`,n,` `,e.description??e.proposed??e.name,t&&(0,K.jsxs)(K.Fragment,{children:[` `,` `,(0,K.jsxs)(`button`,{type:`button`,className:`link-button`,onClick:()=>t(e.call_id),children:[`Open in Tool calls `,(0,K.jsx)(P,{size:12})]})]})]}),e.snapshot&&(0,K.jsx)(IT,{snapshot:e.snapshot,sandbox:l})]},e.call_id))]})]}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`No file changed during this prompt. The snapshots taken after its steps show the project exactly as it started.`}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`This run was recorded before file snapshots existed, so there is nothing to diff. Tool calls still shows what the agent reported.`}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`This prompt did not run in a sandbox, so RayTrace holds no snapshot of the project folder to diff.`})]})}var DD=e=>[...e].sort((e,t)=>{let n=e.started_ns?BigInt(e.started_ns):null,r=t.started_ns?BigInt(t.started_ns):null;return n!=null&&r!=null&&n!==r?n<r?-1:1:e.event_id-t.event_id}),OD=e=>Pu({observed:!0,status:e.exit_code!=null||e.signal?void 0:`running`,exitCode:e.exit_code,signal:e.signal});function kD({trace:e,focusCall:t,onOpenCall:n}){let{since:r,until:i}=Me(e.requests),{data:a,error:o,raw:s,setRaw:c}=Tu(e.sandboxId,r,i),[l,u]=(0,_.useState)(new Set),[d,f]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(f(null),!e.sandboxId)return;let t=!1,n,a=new AbortController,o=async()=>{try{let n=await Ww(e.sandboxId,r,i,a.signal);t||f(n)}catch{}!t&&!i&&(n=setTimeout(o,5e3))};return o(),()=>{t=!0,a.abort(),clearTimeout(n)}},[e.sandboxId,r,i]);let p=(0,_.useMemo)(()=>uT(d),[d]),m=new Set((d?.network??[]).filter(e=>e.effect===`connect`&&!e.outcomes.refused_by_policy).map(e=>`${e.host??e.ip}:${e.port}`)),h=a?.commands??[],g=a?.call_labels??{},v=e.callVerifications??[],y=new Map(v.map((e,t)=>[e.call_id,t+1])),b=new Set(h.map(e=>e.event_id)),x=new Map,S=[];for(let e of h){let t=e.parent_event_id;if(t==null||!b.has(t)){S.push(e);continue}x.set(t,[...x.get(t)??[],e])}let C=DD(S),w=C.map(OD),T=[0,1,2,3].map(e=>C.filter(t=>t.severity?.level===e).length),[E,D]=(0,_.useState)(null),O=E==null?C:C.filter(e=>e.severity?.level===E),k=e=>!!t&&e.attribution?.call_id===t,A=C.find(k),j=A?bu(A.pid,A.process_start_ns):null;(0,_.useEffect)(()=>{if(!j)return;let e=requestAnimationFrame(()=>document.getElementById(`proc-${j.replace(`:`,`-`)}`)?.scrollIntoView({block:`center`,behavior:`smooth`}));return()=>cancelAnimationFrame(e)},[j]);let M=e=>u(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});function P(e,t){let r=DD(x.get(e.event_id)??[]),i=l.has(e.event_id),a=OD(e),o=ku(e.started_ns),s=ku(e.ended_ns),c=bu(e.pid,e.process_start_ns),u=e.attribution?.call_id??null,d=e.attribution?.parent_call_id??null,f=new Map;for(let e of[...t===0&&u?p.byCall.get(u)??[]:[],...c?p.byProcess.get(c)??[]:[]])f.set(e.key,e);return(0,K.jsxs)(_.Fragment,{children:[(0,K.jsxs)(`tr`,{id:c?`proc-${c.replace(`:`,`-`)}`:void 0,className:`rt-row${t?` rt-child`:``}${a.tone===`fail`?` failed`:``}${k(e)?` rt-focus`:``}`,onClick:r.length?()=>M(e.event_id):void 0,"aria-expanded":r.length?i:void 0,children:[(0,K.jsx)(`td`,{className:`rt-time`,children:Eu(o)}),(0,K.jsxs)(`td`,{className:`rt-cmd`,children:[(0,K.jsxs)(`span`,{className:`rt-cmd-line${r.length?` rt-parent`:``}`,style:{paddingLeft:`${t*22}px`},children:[r.length?(0,K.jsx)(B,{size:14,className:`rt-caret${i?` down`:``}`,"aria-hidden":`true`}):(0,K.jsx)(`span`,{className:`rt-caret-gap`}),(0,K.jsx)(`span`,{className:`rt-cmd-text`,title:e.command,children:e.description??(0,K.jsx)(Au,{text:e.command})}),e.description_source===`model`&&(0,K.jsx)(`span`,{className:`evidence-ai`,title:`Described by a model, not derived from the command text. Treat as a reading, not an observation.`,children:`~AI`})]}),e.description&&(0,K.jsx)(`span`,{className:`rt-cmd-raw`,style:{paddingLeft:`${t*22+20}px`},title:e.command,children:(0,K.jsx)(Au,{text:e.command})}),f.size>0&&(0,K.jsxs)(`span`,{className:`rt-chips`,style:{paddingLeft:`${t*22+20}px`},children:[[...f.values()].slice(0,8).map(e=>(0,K.jsx)(`span`,{className:`rt-flag${e.fail?` rt-fail`:``}`,title:e.title,children:e.text},e.key)),f.size>8&&(0,K.jsxs)(`span`,{className:`rt-flag`,title:[...f.values()].slice(8).map(e=>e.text).join(`
|
|
34
34
|
`),children:[`+`,f.size-8]})]})]}),(0,K.jsx)(`td`,{className:`rt-pid`,children:e.pid}),(0,K.jsx)(`td`,{className:`exec-${a.tone}`,children:(0,K.jsx)(Fu,{outcome:a})}),(0,K.jsx)(`td`,{className:`rt-time`,children:Number.isFinite(o)&&Number.isFinite(s)?Ou(s-o):`—`}),(0,K.jsx)(`td`,{children:t===0?(0,K.jsx)(Cu,{severity:e.severity,flags:u?g[u]?.flags:void 0}):null}),(0,K.jsx)(`td`,{children:t>0?null:u?(0,K.jsxs)(`button`,{type:`button`,className:`link-button`,onClick:e=>{e.stopPropagation(),n(u)},children:[`#`,y.get(u)??`?`]}):d?(0,K.jsxs)(`span`,{className:`rt-muted`,children:[`under #`,y.get(d)??`?`]}):(0,K.jsx)(`span`,{className:`rt-muted`,title:`This process ran, but matched no proposed tool call.`,children:`no tool call`})})]}),i&&r.map(e=>P(e,t+1))]},e.event_id)}return(0,K.jsxs)(`section`,{className:`rt-view`,children:[(0,K.jsxs)(`header`,{className:`rt-view-head`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`eyebrow`,children:`SANDBOX EVIDENCE`}),(0,K.jsx)(`h1`,{children:`What actually ran`})]}),(0,K.jsx)(`div`,{className:`rt-actions`,children:(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,onClick:()=>n(),children:[(0,K.jsx)(N,{size:14}),` Tool calls`]})})]}),e.sandboxId?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`dl`,{className:`rt-stats`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Commands`}),(0,K.jsx)(`dd`,{children:a?C.length:`—`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Succeeded`}),(0,K.jsx)(`dd`,{className:`exec-ok`,children:a?w.filter(e=>e.tone===`ok`).length:`—`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Failed`}),(0,K.jsx)(`dd`,{className:`exec-fail`,children:a?w.filter(e=>e.tone===`fail`).length:`—`})]}),(0,K.jsxs)(`div`,{title:[...m].join(`
|
|
35
|
-
`)||void 0,children:[(0,K.jsx)(`dt`,{children:`Reached on the network`}),(0,K.jsx)(`dd`,{children:d?m.size:`—`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Severity`}),(0,K.jsx)(`dd`,{className:`rt-sev-counts`,children:[`none`,`low`,`high`,`severe`].map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,"aria-pressed":E===t,className:`severity-badge severity-${t}${E===t?` rt-sev-on`:``}${E!=null&&E!==t?` rt-sev-off`:``}`,title:E===t?`Show every severity`:`Show only ${e} commands`,onClick:()=>D(e=>e===t?null:t),children:[T[t],` `,e]},e))})]})]}),o&&(0,K.jsx)(`p`,{role:`alert`,className:`verify-error`,children:o}),!a&&!o&&(0,K.jsx)(`p`,{className:`rt-empty`,children:`Loading…`}),a&&!s&&(0,K.jsxs)(K.Fragment,{children:[E!=null&&(0,K.jsxs)(`p`,{className:`rt-foot rt-filter-note`,children:[`Showing `,O.length,` of `,C.length,` commands with `,[`none`,`low`,`high`,`severe`][E],` severity.`,` `,(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>D(null),children:`Show all`})]}),C.length?O.length?(0,K.jsx)(`div`,{className:`rt-table-wrap`,children:(0,K.jsxs)(`table`,{className:`rt-table rt-sandbox`,children:[(0,K.jsx)(`thead`,{children:(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`th`,{children:`Started`}),(0,K.jsx)(`th`,{children:`Command`}),(0,K.jsx)(`th`,{children:`pid`}),(0,K.jsx)(`th`,{children:`Result`}),(0,K.jsx)(`th`,{children:`Took`}),(0,K.jsx)(`th`,{children:`Severity`}),(0,K.jsx)(`th`,{children:`Tool call`})]})}),(0,K.jsx)(`tbody`,{children:O.map(e=>P(e,0))})]})}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`No commands with this severity.`}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`No commands were captured in the sandbox during this prompt. Missing evidence is not proof of non-execution.`}),(0,K.jsxs)(`p`,{className:`rt-foot`,children:[`Seen by the sandbox kernel layer, independent of what the agent reported. Collector gaps: `,a.gaps,`.`,` `,a.folded&&wu(a.folded)?`Folded, not shown as commands: ${wu(a.folded)}. `:``,(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>c(!0),children:`Show every raw event`})]})]}),a&&s&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`rt-foot`,children:(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>c(!1),children:`Back to commands`})}),(0,K.jsx)(`ul`,{className:`evidence-raw`,children:(a.events??[]).map(e=>(0,K.jsxs)(`li`,{children:[(0,K.jsx)(`code`,{children:e.kind===`exec_succeeded`?(e.argv??[]).join(` `):`${e.kind} exit=${e.exit_code??`unknown`}`}),(0,K.jsxs)(`small`,{children:[` pid `,e.pid,` · #`,e.event_id]})]},e.event_id))})]})]}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`This prompt did not run in a sandbox, so there is no independent evidence of what ran.`})]})}var AD=1048576,jD={file:25*AD,total:200*AD,files:2e4,archive:100*AD},MD=new Set([`.git`,`.raytace`,`.raytrace`,`.ssh`,`.aws`,`.azure`,`.config`,`node_modules`,`.venv`,`__pycache__`,`.next`,`.vinext`,`dist`,`coverage`,`.wrangler`,`.DS_Store`]),ND=new Set([`.npmrc`,`.netrc`,`.pypirc`,`credentials`,`auth.json`,`id_rsa`,`id_ed25519`]),PD=/\.(pem|key|p12|pfx)$/i,FD=e=>e.startsWith(`.env`)||PD.test(e)||ND.has(e);function ID(e,t){let n=[];for(let r of e.split(/\r?\n/)){let e=r.replace(/(?<!\\)\s+$/,``);if(!e||e.startsWith(`#`))continue;let i=e.startsWith(`!`);i&&(e=e.slice(1)),e.startsWith(`\\`)&&(e=e.slice(1));let a=e.endsWith(`/`);if(a&&(e=e.slice(0,-1)),!e)continue;let o=e.includes(`/`);e.startsWith(`/`)&&(e=e.slice(1));let s=``;for(let t=0;t<e.length;t++){let n=e[t];if(n===`*`&&e[t+1]===`*`)e[t+2]===`/`?(s+=`(?:.*/)?`,t+=2):(s+=`.*`,t+=1);else if(n===`*`)s+=`[^/]*`;else if(n===`?`)s+=`[^/]`;else if(n===`[`){let n=e.indexOf(`]`,t+2);n<0?s+=`\\[`:(s+=`[${e.slice(t+1,n).replace(/^!/,`^`).replace(/\\/g,`\\\\`)}]`,t=n)}else s+=n.replace(/[.+^${}()|\\\]]/g,`\\$&`)}try{n.push({base:t,negate:i,dirOnly:a,match:RegExp(`^${o?``:`(?:.*/)?`}${s}$`)})}catch{}}return n}function LD(e,t,n){let r=!1;for(let i of e)(!i.dirOnly||n)&&(!i.base||t.startsWith(`${i.base}/`))&&i.match.test(i.base?t.slice(i.base.length+1):t)&&(r=!i.negate);return r}function RD(e,t){let n=t.split(`/`);for(let t=1;t<n.length;t++)if(LD(e,n.slice(0,t).join(`/`),!0))return!0;return LD(e,t,!1)}function zD(e,t,n,r){let i=[],a=0,o=[];for(let e of t.sort((e,t)=>e.path.localeCompare(t.path))){if(e.file.size>jD.file){o.push(`${e.path} (${(e.file.size/AD).toFixed(0)} MiB)`);continue}i.push(e),a+=e.file.size}return o.length&&r.push(`${o.length} file${o.length===1?` is`:`s are`} over ${jD.file/AD} MiB: ${o.slice(0,5).join(`, `)}${o.length>5?`, …`:``}. Add ${o.length===1?`it`:`them`} to .gitignore, or remove ${o.length===1?`it`:`them`}.`),i.length>jD.files&&r.push(`${i.length.toLocaleString()} files; a project may have at most ${jD.files.toLocaleString()}.`),a>jD.total&&r.push(`${(a/AD).toFixed(0)} MiB in all; a project may be at most ${jD.total/AD} MiB.`),!i.length&&!r.length&&r.push(`No files to upload in this folder.`),{name:e,files:i,total:a,skipped:n,problems:r}}var BD=e=>new Promise((t,n)=>{let r=e.createReader(),i=[],a=()=>r.readEntries(e=>{e.length?(i.push(...e),a()):t(i)},n);a()}),VD=e=>new Promise((t,n)=>e.file(t,n));function HD(e){return[...e.items].map(e=>e.webkitGetAsEntry?.()??null).filter(e=>e!==null)}async function UD(e){let t={ignored:0,excluded:0,secret:[]};if(e.length!==1||!e[0].isDirectory)return{name:``,files:[],total:0,skipped:t,problems:[`Drop one project folder (not files, and not several folders).`]};let n=e[0],r=[],i=[],a=async(e,n,i)=>{let o=await BD(e),s=o.find(e=>e.isFile&&e.name===`.gitignore`),c=s?[...i,...ID(await(await VD(s)).text(),n)]:i;for(let e of o){let i=n?`${n}/${e.name}`:e.name;if(MD.has(e.name)){t.excluded+=1;continue}if(LD(c,i,e.isDirectory)){t.ignored+=1;continue}if(e.isDirectory){await a(e,i,c);continue}if(FD(e.name)){t.secret.push(i);continue}r.length>jD.files*2||r.push({path:i,file:await VD(e)})}};try{await a(n,``,[])}catch{i.push(`Some of this folder could not be read.`)}return zD(n.name,r,t,i)}async function WD(e){let t={ignored:0,excluded:0,secret:[]},n=[...e].map(e=>{let[,...t]=(e.webkitRelativePath||e.name).split(`/`);return{path:t.join(`/`)||e.name,file:e}}),r=(e[0]?.webkitRelativePath||``).split(`/`)[0]||`project`,i=new Set,a=n.filter(e=>{let t=e.path.split(`/`),n=t.findIndex(e=>MD.has(e));return n<0||(i.add(t.slice(0,n+1).join(`/`)),!1)});t.excluded=i.size;let o=a.filter(e=>e.path.split(`/`).pop()===`.gitignore`).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length),s=[];for(let e of o)s.push(...ID(await e.file.text(),e.path.split(`/`).slice(0,-1).join(`/`)));let c=[];for(let e of a){if(RD(s,e.path)){t.ignored+=1;continue}if(FD(e.path.split(`/`).pop())){t.secret.push(e.path);continue}c.push(e)}return zD(r,c,t,[])}var GD=new TextEncoder;function KD(e,t,n,r,i){let a=new Uint8Array(512),o=(e,t)=>a.set(typeof e==`string`?GD.encode(e):e,t),s=(e,t)=>e.toString(8).padStart(t-1,`0`)+`\0`;o(e,0),o(s(420,8),100),o(s(1e3,8),108),o(s(1e3,8),116),o(s(n,12),124),o(s(Math.max(0,Math.floor(r)),12),136),o(` `,148),o(i,156),o(`ustar\x0000`,257),o(`node`,265),o(`node`,297),o(t,345);let c=0;for(let e of a)c+=e;return o(c.toString(8).padStart(6,`0`)+`\0 `,148),a}function qD(e,t,n){let r=GD.encode(e),i=r.length===e.length;if(i&&r.length<=100)return[KD(r,new Uint8Array,t,n,`0`)];if(i){for(let i=e.lastIndexOf(`/`);i>0;i=e.lastIndexOf(`/`,i-1))if(i<=155&&r.length-i-1<=100)return[KD(r.slice(i+1),r.slice(0,i),t,n,`0`)]}let a=` path=${e}\n`,o=GD.encode(a).length,s=o+String(o).length;String(s).length!==String(o).length&&(s=o+String(s).length);let c=GD.encode(`${s}${a}`),l=new Uint8Array(Math.ceil(c.length/512)*512);l.set(c);let u=GD.encode(e.replace(/[^\x20-\x7e]/g,`_`).slice(-100));return[KD(GD.encode(`PaxHeader`),new Uint8Array,c.length,n,`x`),l,KD(u,new Uint8Array,t,n,`0`)]}async function JD(e){let t=[];for(let{path:n,file:r}of e){t.push(...qD(n,r.size,r.lastModified/1e3),r);let e=r.size%512;e&&t.push(new Uint8Array(512-e))}t.push(new Uint8Array(1024));let n=await new Response(new Blob(t).stream().pipeThrough(new CompressionStream(`gzip`))).blob();if(n.size>jD.archive)throw Error(`The packed project is ${(n.size/AD).toFixed(0)} MiB; the most allowed is ${jD.archive/AD} MiB.`);return n}var YD=1048576,XD=e=>e<YD?`${Math.max(1,Math.round(e/1024))} KiB`:`${(e/YD).toFixed(1)} MiB`,ZD=e=>e.replace(/[^A-Za-z0-9._ -]/g,`-`).slice(0,100),QD=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`;function $D({onCreated:e}){let[t,n]=(0,_.useState)({at:`idle`}),[r,i]=(0,_.useState)(``),[a,o]=(0,_.useState)(!1),s=(0,_.useRef)(null),c=async e=>{n({at:`reading`});try{let t=await e;i(ZD(t.name)),n({at:`preview`,project:t})}catch{n({at:`failed`,message:`That folder could not be read.`})}},l=e=>{e.preventDefault(),o(!1),c(UD(HD(e.dataTransfer)))},u=async t=>{let i=x().createSandbox;if(i)try{n({at:`working`,step:`Packing ${QD(t.files.length,`file`)}…`});let a=await JD(t.files);n({at:`working`,step:`Uploading ${XD(a.size)} and starting the sandbox. This can take a minute…`});let o=await i(r.trim(),a),s=await o.json().catch(()=>({}));if(!o.ok||!s.id)throw Error(s.error||`The sandbox could not be created (HTTP ${o.status}).`);n({at:`idle`}),e(s.id)}catch(e){n({at:`failed`,project:t,message:e instanceof Error&&e.message!==`Failed to fetch`?e.message:`RayTrace could not be reached. Check your connection and try again.`})}},d=t.at===`preview`||t.at===`failed`?t.project:void 0,f=/^[A-Za-z0-9._ -]{1,100}$/.test(r.trim());return(0,K.jsxs)(`div`,{className:`rt-new-sandbox`,children:[(t.at===`idle`||t.at===`reading`||t.at===`failed`&&!d)&&(0,K.jsxs)(`div`,{className:a?`rt-drop over`:`rt-drop`,onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:l,children:[(0,K.jsx)(re,{size:20}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:t.at===`reading`?`Reading the folder…`:`New sandbox: drop a project folder here`}),(0,K.jsxs)(`small`,{children:[`You will see what would be uploaded first. `,(0,K.jsx)(`code`,{children:`.env`}),` files, keys, `,(0,K.jsx)(`code`,{children:`node_modules`}),` and anything your `,(0,K.jsx)(`code`,{children:`.gitignore`}),` excludes stay on this machine. Up to `,jD.total/YD,` MiB, `,jD.file/YD,` MiB a file.`]}),t.at===`failed`&&(0,K.jsx)(`p`,{className:`rt-problem`,children:t.message})]}),(0,K.jsx)(`button`,{type:`button`,className:`rt-button`,disabled:t.at===`reading`,onClick:()=>s.current?.click(),children:`Choose folder`}),(0,K.jsx)(`input`,{ref:s,type:`file`,hidden:!0,multiple:!0,webkitdirectory:``,onChange:e=>{let t=e.target.files;t?.length&&c(WD(t)),e.target.value=``}})]}),d&&(0,K.jsxs)(`div`,{className:`rt-upload-preview`,children:[(0,K.jsxs)(`div`,{className:`rt-upload-head`,children:[(0,K.jsxs)(`label`,{children:[`Sandbox name`,(0,K.jsx)(`input`,{value:r,maxLength:100,onChange:e=>i(e.target.value)})]}),(0,K.jsx)(`button`,{type:`button`,className:`rt-icon-button`,"aria-label":`Cancel`,onClick:()=>n({at:`idle`}),children:(0,K.jsx)(Te,{size:15})})]}),(0,K.jsxs)(`dl`,{className:`rt-facts`,children:[(0,K.jsx)(`dt`,{children:`Will upload`}),(0,K.jsxs)(`dd`,{children:[QD(d.files.length,`file`),` · `,XD(d.total)]}),(0,K.jsx)(`dt`,{children:`Stays here`}),(0,K.jsxs)(`dd`,{children:[!d.skipped.ignored&&!d.skipped.excluded&&!d.skipped.secret.length&&`Nothing was left out.`,d.skipped.ignored>0&&(0,K.jsxs)(`span`,{children:[QD(d.skipped.ignored,`path`),` ignored by .gitignore. `]}),d.skipped.excluded>0&&(0,K.jsxs)(`span`,{children:[QD(d.skipped.excluded,`dependency or build folder`),` (node_modules, .git, dist…). `]}),d.skipped.secret.length>0&&(0,K.jsxs)(`span`,{children:[QD(d.skipped.secret.length,`credential file`),`: `,(0,K.jsxs)(`code`,{children:[d.skipped.secret.slice(0,6).join(`, `),d.skipped.secret.length>6?`, …`:``]})]})]}),(0,K.jsx)(`dt`,{children:`Files`}),(0,K.jsx)(`dd`,{className:`rt-upload-files`,children:(0,K.jsxs)(`code`,{children:[d.files.slice(0,12).map(e=>e.path).join(`
|
|
35
|
+
`)||void 0,children:[(0,K.jsx)(`dt`,{children:`Reached on the network`}),(0,K.jsx)(`dd`,{children:d?m.size:`—`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Severity`}),(0,K.jsx)(`dd`,{className:`rt-sev-counts`,children:[`none`,`low`,`high`,`severe`].map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,"aria-pressed":E===t,className:`severity-badge severity-${t}${E===t?` rt-sev-on`:``}${E!=null&&E!==t?` rt-sev-off`:``}`,title:E===t?`Show every severity`:`Show only ${e} commands`,onClick:()=>D(e=>e===t?null:t),children:[T[t],` `,e]},e))})]})]}),o&&(0,K.jsx)(`p`,{role:`alert`,className:`verify-error`,children:o}),!a&&!o&&(0,K.jsx)(`p`,{className:`rt-empty`,children:`Loading…`}),a&&!s&&(0,K.jsxs)(K.Fragment,{children:[E!=null&&(0,K.jsxs)(`p`,{className:`rt-foot rt-filter-note`,children:[`Showing `,O.length,` of `,C.length,` commands with `,[`none`,`low`,`high`,`severe`][E],` severity.`,` `,(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>D(null),children:`Show all`})]}),C.length?O.length?(0,K.jsx)(`div`,{className:`rt-table-wrap`,children:(0,K.jsxs)(`table`,{className:`rt-table rt-sandbox`,children:[(0,K.jsx)(`thead`,{children:(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`th`,{children:`Started`}),(0,K.jsx)(`th`,{children:`Command`}),(0,K.jsx)(`th`,{children:`pid`}),(0,K.jsx)(`th`,{children:`Result`}),(0,K.jsx)(`th`,{children:`Took`}),(0,K.jsx)(`th`,{children:`Severity`}),(0,K.jsx)(`th`,{children:`Tool call`})]})}),(0,K.jsx)(`tbody`,{children:O.map(e=>P(e,0))})]})}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`No commands with this severity.`}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`No commands were captured in the sandbox during this prompt. Missing evidence is not proof of non-execution.`}),(0,K.jsxs)(`p`,{className:`rt-foot`,children:[`Seen by the sandbox kernel layer, independent of what the agent reported. Collector gaps: `,a.gaps,`.`,` `,a.folded&&wu(a.folded)?`Folded, not shown as commands: ${wu(a.folded)}. `:``,(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>c(!0),children:`Show every raw event`})]})]}),a&&s&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`rt-foot`,children:(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>c(!1),children:`Back to commands`})}),(0,K.jsx)(`ul`,{className:`evidence-raw`,children:(a.events??[]).map(e=>(0,K.jsxs)(`li`,{children:[(0,K.jsx)(`code`,{children:e.kind===`exec_succeeded`?(e.argv??[]).join(` `):`${e.kind} exit=${e.exit_code??`unknown`}`}),(0,K.jsxs)(`small`,{children:[` pid `,e.pid,` · #`,e.event_id]})]},e.event_id))})]})]}):(0,K.jsx)(`p`,{className:`rt-empty`,children:`This prompt did not run in a sandbox, so there is no independent evidence of what ran.`})]})}var AD=1048576,jD={file:25*AD,total:200*AD,files:2e4,archive:100*AD},MD=new Set([`.git`,`.raytace`,`.raytrace`,`.ssh`,`.aws`,`.azure`,`.config`,`.claude`,`node_modules`,`.venv`,`__pycache__`,`.next`,`.vinext`,`dist`,`coverage`,`.wrangler`,`.DS_Store`]),ND=new Set([`.npmrc`,`.netrc`,`.pypirc`,`.htpasswd`,`.dockercfg`,`credentials`,`credentials.json`,`credentials.ini`,`auth.json`,`service-account.json`,`service_account.json`,`serviceAccountKey.json`,`client_secret.json`,`client_secrets.json`,`token.json`,`id_rsa`,`id_dsa`,`id_ecdsa`,`id_ed25519`,`id_ecdsa_sk`,`id_ed25519_sk`,`known_hosts`]),PD=/\.(pem|key|p12|pfx)$/i,FD=e=>{let t=e.toLowerCase();return t.startsWith(`.env`)||t.startsWith(`.secret`)||PD.test(e)||ND.has(t)};function ID(e,t){let n=[];for(let r of e.split(/\r?\n/)){let e=r.replace(/(?<!\\)\s+$/,``);if(!e||e.startsWith(`#`))continue;let i=e.startsWith(`!`);i&&(e=e.slice(1)),e.startsWith(`\\`)&&(e=e.slice(1));let a=e.endsWith(`/`);if(a&&(e=e.slice(0,-1)),!e)continue;let o=e.includes(`/`);e.startsWith(`/`)&&(e=e.slice(1));let s=``;for(let t=0;t<e.length;t++){let n=e[t];if(n===`*`&&e[t+1]===`*`)e[t+2]===`/`?(s+=`(?:.*/)?`,t+=2):(s+=`.*`,t+=1);else if(n===`*`)s+=`[^/]*`;else if(n===`?`)s+=`[^/]`;else if(n===`[`){let n=e.indexOf(`]`,t+2);n<0?s+=`\\[`:(s+=`[${e.slice(t+1,n).replace(/^!/,`^`).replace(/\\/g,`\\\\`)}]`,t=n)}else s+=n.replace(/[.+^${}()|\\\]]/g,`\\$&`)}try{n.push({base:t,negate:i,dirOnly:a,match:RegExp(`^${o?``:`(?:.*/)?`}${s}$`)})}catch{}}return n}function LD(e,t,n){let r=!1;for(let i of e)(!i.dirOnly||n)&&(!i.base||t.startsWith(`${i.base}/`))&&i.match.test(i.base?t.slice(i.base.length+1):t)&&(r=!i.negate);return r}function RD(e,t){let n=t.split(`/`);for(let t=1;t<n.length;t++)if(LD(e,n.slice(0,t).join(`/`),!0))return!0;return LD(e,t,!1)}function zD(e,t,n,r){let i=[],a=0,o=[];for(let e of t.sort((e,t)=>e.path.localeCompare(t.path))){if(e.file.size>jD.file){o.push(`${e.path} (${(e.file.size/AD).toFixed(0)} MiB)`);continue}i.push(e),a+=e.file.size}return o.length&&r.push(`${o.length} file${o.length===1?` is`:`s are`} over ${jD.file/AD} MiB: ${o.slice(0,5).join(`, `)}${o.length>5?`, …`:``}. Add ${o.length===1?`it`:`them`} to .gitignore, or remove ${o.length===1?`it`:`them`}.`),i.length>jD.files&&r.push(`${i.length.toLocaleString()} files; a project may have at most ${jD.files.toLocaleString()}.`),a>jD.total&&r.push(`${(a/AD).toFixed(0)} MiB in all; a project may be at most ${jD.total/AD} MiB.`),!i.length&&!r.length&&r.push(`No files to upload in this folder.`),{name:e,files:i,total:a,skipped:n,problems:r}}var BD=e=>new Promise((t,n)=>{let r=e.createReader(),i=[],a=()=>r.readEntries(e=>{e.length?(i.push(...e),a()):t(i)},n);a()}),VD=e=>new Promise((t,n)=>e.file(t,n));function HD(e){return[...e.items].map(e=>e.webkitGetAsEntry?.()??null).filter(e=>e!==null)}async function UD(e){let t={ignored:0,excluded:0,secret:[]};if(e.length!==1||!e[0].isDirectory)return{name:``,files:[],total:0,skipped:t,problems:[`Drop one project folder (not files, and not several folders).`]};let n=e[0],r=[],i=[],a=async(e,n,i)=>{let o=await BD(e),s=o.find(e=>e.isFile&&e.name===`.gitignore`),c=s?[...i,...ID(await(await VD(s)).text(),n)]:i;for(let e of o){let i=n?`${n}/${e.name}`:e.name;if(MD.has(e.name)){t.excluded+=1;continue}if(LD(c,i,e.isDirectory)){t.ignored+=1;continue}if(e.isDirectory){await a(e,i,c);continue}if(FD(e.name)){t.secret.push(i);continue}r.length>jD.files*2||r.push({path:i,file:await VD(e)})}};try{await a(n,``,[])}catch{i.push(`Some of this folder could not be read.`)}return zD(n.name,r,t,i)}async function WD(e){let t={ignored:0,excluded:0,secret:[]},n=[...e].map(e=>{let[,...t]=(e.webkitRelativePath||e.name).split(`/`);return{path:t.join(`/`)||e.name,file:e}}),r=(e[0]?.webkitRelativePath||``).split(`/`)[0]||`project`,i=new Set,a=n.filter(e=>{let t=e.path.split(`/`),n=t.findIndex(e=>MD.has(e));return n<0||(i.add(t.slice(0,n+1).join(`/`)),!1)});t.excluded=i.size;let o=a.filter(e=>e.path.split(`/`).pop()===`.gitignore`).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length),s=[];for(let e of o)s.push(...ID(await e.file.text(),e.path.split(`/`).slice(0,-1).join(`/`)));let c=[];for(let e of a){if(RD(s,e.path)){t.ignored+=1;continue}if(FD(e.path.split(`/`).pop())){t.secret.push(e.path);continue}c.push(e)}return zD(r,c,t,[])}var GD=new TextEncoder;function KD(e,t,n,r,i){let a=new Uint8Array(512),o=(e,t)=>a.set(typeof e==`string`?GD.encode(e):e,t),s=(e,t)=>e.toString(8).padStart(t-1,`0`)+`\0`;o(e,0),o(s(420,8),100),o(s(1e3,8),108),o(s(1e3,8),116),o(s(n,12),124),o(s(Math.max(0,Math.floor(r)),12),136),o(` `,148),o(i,156),o(`ustar\x0000`,257),o(`node`,265),o(`node`,297),o(t,345);let c=0;for(let e of a)c+=e;return o(c.toString(8).padStart(6,`0`)+`\0 `,148),a}function qD(e,t,n){let r=GD.encode(e),i=r.length===e.length;if(i&&r.length<=100)return[KD(r,new Uint8Array,t,n,`0`)];if(i){for(let i=e.lastIndexOf(`/`);i>0;i=e.lastIndexOf(`/`,i-1))if(i<=155&&r.length-i-1<=100)return[KD(r.slice(i+1),r.slice(0,i),t,n,`0`)]}let a=` path=${e}\n`,o=GD.encode(a).length,s=o+String(o).length;String(s).length!==String(o).length&&(s=o+String(s).length);let c=GD.encode(`${s}${a}`),l=new Uint8Array(Math.ceil(c.length/512)*512);l.set(c);let u=GD.encode(e.replace(/[^\x20-\x7e]/g,`_`).slice(-100));return[KD(GD.encode(`PaxHeader`),new Uint8Array,c.length,n,`x`),l,KD(u,new Uint8Array,t,n,`0`)]}async function JD(e){let t=[];for(let{path:n,file:r}of e){t.push(...qD(n,r.size,r.lastModified/1e3),r);let e=r.size%512;e&&t.push(new Uint8Array(512-e))}t.push(new Uint8Array(1024));let n=await new Response(new Blob(t).stream().pipeThrough(new CompressionStream(`gzip`))).blob();if(n.size>jD.archive)throw Error(`The packed project is ${(n.size/AD).toFixed(0)} MiB; the most allowed is ${jD.archive/AD} MiB.`);return n}var YD=1048576,XD=e=>e<YD?`${Math.max(1,Math.round(e/1024))} KiB`:`${(e/YD).toFixed(1)} MiB`,ZD=e=>e.replace(/[^A-Za-z0-9._ -]/g,`-`).slice(0,100),QD=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`;function $D({onCreated:e}){let[t,n]=(0,_.useState)({at:`idle`}),[r,i]=(0,_.useState)(``),[a,o]=(0,_.useState)(!1),s=(0,_.useRef)(null),c=async e=>{n({at:`reading`});try{let t=await e;i(ZD(t.name)),n({at:`preview`,project:t})}catch{n({at:`failed`,message:`That folder could not be read.`})}},l=e=>{e.preventDefault(),o(!1),c(UD(HD(e.dataTransfer)))},u=async t=>{let i=x().createSandbox;if(i)try{n({at:`working`,step:`Packing ${QD(t.files.length,`file`)}…`});let a=await JD(t.files);n({at:`working`,step:`Uploading ${XD(a.size)} and starting the sandbox. This can take a minute…`});let o=await i(r.trim(),a),s=await o.json().catch(()=>({}));if(!o.ok||!s.id)throw Error(s.error||`The sandbox could not be created (HTTP ${o.status}).`);n({at:`idle`}),e(s.id)}catch(e){n({at:`failed`,project:t,message:e instanceof Error&&e.message!==`Failed to fetch`?e.message:`RayTrace could not be reached. Check your connection and try again.`})}},d=t.at===`preview`||t.at===`failed`?t.project:void 0,f=/^[A-Za-z0-9._ -]{1,100}$/.test(r.trim());return(0,K.jsxs)(`div`,{className:`rt-new-sandbox`,children:[(t.at===`idle`||t.at===`reading`||t.at===`failed`&&!d)&&(0,K.jsxs)(`div`,{className:a?`rt-drop over`:`rt-drop`,onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:l,children:[(0,K.jsx)(re,{size:20}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:t.at===`reading`?`Reading the folder…`:`New sandbox: drop a project folder here`}),(0,K.jsxs)(`small`,{children:[`You will see what would be uploaded first. `,(0,K.jsx)(`code`,{children:`.env`}),` files, keys, `,(0,K.jsx)(`code`,{children:`node_modules`}),` and anything your `,(0,K.jsx)(`code`,{children:`.gitignore`}),` excludes stay on this machine. Up to `,jD.total/YD,` MiB, `,jD.file/YD,` MiB a file.`]}),t.at===`failed`&&(0,K.jsx)(`p`,{className:`rt-problem`,children:t.message})]}),(0,K.jsx)(`button`,{type:`button`,className:`rt-button`,disabled:t.at===`reading`,onClick:()=>s.current?.click(),children:`Choose folder`}),(0,K.jsx)(`input`,{ref:s,type:`file`,hidden:!0,multiple:!0,webkitdirectory:``,onChange:e=>{let t=e.target.files;t?.length&&c(WD(t)),e.target.value=``}})]}),d&&(0,K.jsxs)(`div`,{className:`rt-upload-preview`,children:[(0,K.jsxs)(`div`,{className:`rt-upload-head`,children:[(0,K.jsxs)(`label`,{children:[`Sandbox name`,(0,K.jsx)(`input`,{value:r,maxLength:100,onChange:e=>i(e.target.value)})]}),(0,K.jsx)(`button`,{type:`button`,className:`rt-icon-button`,"aria-label":`Cancel`,onClick:()=>n({at:`idle`}),children:(0,K.jsx)(Te,{size:15})})]}),(0,K.jsxs)(`dl`,{className:`rt-facts`,children:[(0,K.jsx)(`dt`,{children:`Will upload`}),(0,K.jsxs)(`dd`,{children:[QD(d.files.length,`file`),` · `,XD(d.total)]}),(0,K.jsx)(`dt`,{children:`Stays here`}),(0,K.jsxs)(`dd`,{children:[!d.skipped.ignored&&!d.skipped.excluded&&!d.skipped.secret.length&&`Nothing was left out.`,d.skipped.ignored>0&&(0,K.jsxs)(`span`,{children:[QD(d.skipped.ignored,`path`),` ignored by .gitignore. `]}),d.skipped.excluded>0&&(0,K.jsxs)(`span`,{children:[QD(d.skipped.excluded,`dependency or build folder`),` (node_modules, .git, dist…). `]}),d.skipped.secret.length>0&&(0,K.jsxs)(`span`,{children:[QD(d.skipped.secret.length,`credential file`),`: `,(0,K.jsxs)(`code`,{children:[d.skipped.secret.slice(0,6).join(`, `),d.skipped.secret.length>6?`, …`:``]})]})]}),(0,K.jsx)(`dt`,{children:`Files`}),(0,K.jsx)(`dd`,{className:`rt-upload-files`,children:(0,K.jsxs)(`code`,{children:[d.files.slice(0,12).map(e=>e.path).join(`
|
|
36
36
|
`),d.files.length>12?`\n… and ${(d.files.length-12).toLocaleString()} more`:``]})})]}),d.problems.map(e=>(0,K.jsx)(`p`,{className:`rt-problem`,children:e},e)),t.at===`failed`&&(0,K.jsx)(`p`,{className:`rt-problem`,children:t.message}),(0,K.jsxs)(`div`,{className:`rt-actions`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`rt-button primary`,disabled:d.problems.length>0||!f,onClick:()=>void u(d),children:[(0,K.jsx)(xe,{size:13}),` Create sandbox`]}),(0,K.jsx)(`button`,{type:`button`,className:`rt-button`,onClick:()=>n({at:`idle`}),children:`Cancel`}),!f&&(0,K.jsx)(`small`,{className:`rt-muted`,children:`Name: letters, digits, spaces, and . _ - only.`})]})]}),t.at===`working`&&(0,K.jsx)(`p`,{className:`rt-upload-working`,children:t.step})]})}var eO=e=>e.split(`
|
|
37
37
|
`).find(e=>e.trim())?.trim()??`(empty prompt)`,tO=e=>new Date(typeof e==`number`?e*1e3:e).toLocaleString(void 0,{day:`numeric`,month:`short`,hour:`numeric`,minute:`2-digit`}),nO=e=>e==null?`—`:`${(e/1048576).toFixed(e<1048576?2:1)} MiB`;function rO(e){return e===`lima`?{title:`Local VM`,detail:`Lima on this machine`}:{title:`Cloud VM ${e.split(`@`).pop()}`,detail:e}}function iO(e){return e.status===`deleted`?{label:`Destroyed`,tone:`deleted`}:e.on_host?e.status===`running`?{label:`Running`,tone:`running`}:e.status===`import_failed`?{label:`Failed to create`,tone:`deleted`}:{label:`Stopped`,tone:`stopped`}:{label:`Not connected`,tone:`unknown`}}function aO({traces:e,selectedId:t,onSelect:n,onOpenTrace:r,onOpenScan:i}){let[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(``),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(0),v=!!x().createSandbox;(0,_.useEffect)(()=>{let e=!1,t,n=async()=>{try{let t=await x().fetch(`/raytace/sandboxes`,{cache:`no-store`}),n=await t.json();if(!t.ok)throw Error(n.error||`Sandbox list unavailable`);e||(o(n.sandboxes??[]),c(null))}catch(t){e||c(t instanceof Error?t.message:`Proxy unavailable`)}e||(t=setTimeout(n,1e4))};return n(),()=>{e=!0,clearTimeout(t)}},[h]);let y=new Map;for(let t of e)t.sandboxId&&!t.forkId&&y.set(t.sandboxId,[...y.get(t.sandboxId)??[],t]);let b=[...new Set((a??[]).map(e=>e.host))].sort((e,t)=>{let n=e=>+!(a??[]).some(t=>t.host===e&&t.on_host);return n(e)-n(t)||e.localeCompare(t)}),S=e=>typeof e.created==`number`?e.created*1e3:Date.parse(e.created),C=e=>{navigator.clipboard?.writeText(e),u(e),setTimeout(()=>u(``),1500)},[w,T]=(0,_.useState)(null),E=async e=>{f(e.id),m(``);try{let t=await x().fetch(`/raytace/sandboxes/${e.id}`,{method:`DELETE`,headers:{"x-raytace-experiment":`1`}}),r=await t.json().catch(()=>({}));if(!t.ok)throw Error(r.error||`Destroy failed`);n(``),g(e=>e+1)}catch(e){m(e instanceof Error?e.message:`Destroy failed`)}finally{f(``),T(null)}};return(0,K.jsxs)(`section`,{className:`rt-view`,children:[(0,K.jsx)(`header`,{className:`rt-view-head`,children:(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`eyebrow`,children:`SANDBOXES`}),(0,K.jsx)(`h1`,{children:`Where your agents ran`})]})}),v&&(0,K.jsx)($D,{onCreated:e=>{g(e=>e+1),(i??n)(e)}}),s&&(0,K.jsx)(`p`,{className:`rt-empty`,children:s}),p&&(0,K.jsx)(`p`,{className:`rt-empty`,children:p}),!s&&a===null&&(0,K.jsx)(`p`,{className:`rt-empty`,children:`Loading…`}),!s&&a?.length===0&&(0,K.jsxs)(`p`,{className:`rt-empty`,children:[`No sandboxes yet. `,v?`Drop a project folder above, or from`:`From`,` a Git repository: `,(0,K.jsx)(`code`,{children:`raytrace sandbox create`})]}),b.map(e=>{let o=rO(e),s=(a??[]).filter(t=>t.host===e).sort((e,t)=>Number(e.status===`deleted`)-Number(t.status===`deleted`)||S(t)-S(e)),c=s.some(e=>e.on_host);return(0,K.jsxs)(`div`,{className:`rt-host`,children:[(0,K.jsxs)(`div`,{className:`rt-list-head`,children:[(0,K.jsxs)(`span`,{className:`rt-host-title`,children:[(0,K.jsx)(_e,{size:13}),` `,o.title.toUpperCase()]}),(0,K.jsxs)(`small`,{children:[o.detail,` · `,c?`connected`:`not connected now`,` · `,s.length,` sandbox`,s.length===1?``:`es`]})]}),(0,K.jsx)(`ol`,{className:`rt-prompts`,children:s.map(e=>{let a=e.id===t,s=(y.get(e.id)??[]).sort((e,t)=>t.startedAt.localeCompare(e.startedAt)),c=iO(e),u=`raytrace connect ${e.host===`lima`&&e.name?e.name:e.id}`;return(0,K.jsxs)(`li`,{className:a?`rt-prompt open`:`rt-prompt`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`rt-prompt-row`,"aria-expanded":a,onClick:()=>n(a?``:e.id),children:[(0,K.jsx)(`time`,{children:tO(e.created)}),(0,K.jsxs)(`strong`,{children:[(0,K.jsx)(`span`,{className:`rt-state s-${c.tone}`,children:c.label}),e.name]}),(0,K.jsxs)(`small`,{children:[s.length,` prompt`,s.length===1?``:`s`,` · `,e.id.slice(0,12),`…`]})]}),a&&(0,K.jsxs)(`div`,{className:`rt-prompt-detail`,children:[(0,K.jsxs)(`dl`,{className:`rt-facts`,children:[(0,K.jsx)(`dt`,{children:`Sandbox`}),(0,K.jsx)(`dd`,{children:(0,K.jsx)(`code`,{children:e.id})}),(0,K.jsx)(`dt`,{children:`Runs on`}),(0,K.jsxs)(`dd`,{children:[o.title,` `,(0,K.jsxs)(`span`,{className:`rt-muted`,children:[`(`,o.detail,`)`]})]}),(0,K.jsx)(`dt`,{children:`State`}),(0,K.jsxs)(`dd`,{children:[c.label,!e.on_host&&e.status!==`deleted`?(0,K.jsxs)(`span`,{className:`rt-muted`,children:[` — the manager is connected to another VM; last recorded: `,e.status]}):null]}),(0,K.jsx)(`dt`,{children:`Created`}),(0,K.jsxs)(`dd`,{children:[tO(e.created),e.deleted?(0,K.jsxs)(`span`,{className:`rt-muted`,children:[` · destroyed `,tO(e.deleted)]}):null]}),e.host!==`lima`&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`dt`,{children:`Uploaded`}),(0,K.jsxs)(`dd`,{children:[nO(e.imported_bytes),e.skipped_count?(0,K.jsxs)(`span`,{className:`rt-muted`,children:[` · `,e.skipped_count,` file`,e.skipped_count===1?``:`s`,` left out`]}):null]})]}),(0,K.jsx)(`dt`,{children:`Recording`}),(0,K.jsx)(`dd`,{children:e.transcripts===!1?`Commands only (no Claude Code transcripts)`:`Commands and Claude Code transcripts`}),i&&e.scan?.by_level&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`dt`,{children:`Initial scan`}),(0,K.jsxs)(`dd`,{children:[e.scan.files,` files, `,(e.scan.by_level[4]??0)+(e.scan.by_level[5]??0),` at level 4 or 5`,` `,(0,K.jsxs)(`button`,{type:`button`,className:`link-button`,onClick:()=>i(e.id),children:[(0,K.jsx)(he,{size:11}),` Open the scan`]})]})]})]}),e.status!==`deleted`&&e.on_host&&(0,K.jsxs)(`div`,{className:`rt-shell-line`,children:[(0,K.jsx)(`code`,{children:u}),(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,onClick:()=>C(u),children:[(0,K.jsx)(V,{size:13}),` `,l===u?`Copied`:`Copy`]})]}),e.host===`lima`&&(0,K.jsxs)(`div`,{className:`rt-shell-line`,children:[(0,K.jsxs)(`code`,{children:[`raytrace sandbox destroy `,e.name||e.id]}),(0,K.jsxs)(`button`,{type:`button`,className:`rt-button`,onClick:()=>C(`raytrace sandbox destroy ${e.name||e.id}`),children:[(0,K.jsx)(V,{size:13}),` `,l===`raytrace sandbox destroy ${e.name||e.id}`?`Copied`:`Copy`]})]}),e.host===`lima`&&(0,K.jsxs)(`p`,{className:`rt-foot`,children:[`Run the first command in a terminal to open this sandbox, then start `,(0,K.jsx)(`code`,{children:`claude`}),` or `,(0,K.jsx)(`code`,{children:`codex`}),` there. The second deletes it, and asks whether to delete the logs recorded in it too.`]}),e.host!==`lima`&&e.status!==`deleted`&&e.on_host&&(0,K.jsxs)(`div`,{className:`rt-shell-line`,children:[(0,K.jsx)(`code`,{children:`Destroy this sandbox and stop anything running in it. Its recorded evidence stays.`}),(0,K.jsx)(`button`,{type:`button`,className:`rt-button`,disabled:d===e.id,onClick:()=>T(e),children:d===e.id?`Destroying…`:`Destroy`})]}),e.host!==`lima`&&e.status!==`deleted`&&e.on_host&&(0,K.jsxs)(`p`,{className:`rt-foot`,children:[`Run it in a terminal to open this sandbox, then start `,(0,K.jsx)(`code`,{children:`claude`}),` or `,(0,K.jsx)(`code`,{children:`codex`}),` there. Needs the RayTrace CLI, signed in as this account: `,(0,K.jsx)(`code`,{children:`npm install -g @raytrace-cli/cli@latest`}),`. On CLI 0.2 the command is `,(0,K.jsxs)(`code`,{children:[`raytrace sandbox shell `,e.id]}),`.`]}),(0,K.jsx)(`h3`,{children:`History`}),!s.length&&(0,K.jsx)(`p`,{className:`rt-muted`,children:`No prompts recorded in this sandbox yet.`}),s.length>0&&(0,K.jsx)(`ol`,{className:`rt-history`,children:s.map(e=>{let t=e.callVerifications??[],n=t.filter(e=>e.exec_id||(e.kind?e.kind===`command`:e.proposed!=null)),i=n.filter(e=>e.exec_id).length,a=t.filter(e=>e.kind===`file`&&!e.exec_id).length;return(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,onClick:()=>r(e.id),children:[(0,K.jsx)(`time`,{dateTime:e.startedAt,children:tO(e.startedAt)}),(0,K.jsx)(`span`,{children:eO(e.title)}),(0,K.jsxs)(`small`,{className:n.length&&i===n.length?`all`:``,children:[n.length?`${i} of ${n.length} command${n.length===1?``:`s`} observed in the sandbox`:`no commands`,a>0&&` · ${a} file operation${a===1?``:`s`}`]}),(0,K.jsx)(P,{size:13})]})},e.id)})})]})]},e.id)})})]},e)}),w&&(0,K.jsxs)(`dialog`,{open:!0,className:`rt-dialog`,"aria-labelledby":`rt-destroy-title`,onCancel:e=>{e.preventDefault(),d||T(null)},children:[(0,K.jsx)(`h2`,{id:`rt-destroy-title`,children:`Destroy this sandbox?`}),(0,K.jsxs)(`p`,{children:[`“`,w.name||w.id,`” stops and is deleted. Its recorded evidence stays.`]}),(0,K.jsxs)(`div`,{className:`rt-dialog-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`rt-button`,autoFocus:!0,disabled:!!d,onClick:()=>T(null),children:`No`}),(0,K.jsx)(`button`,{type:`button`,className:`rt-button rt-danger`,disabled:!!d,onClick:()=>void E(w),children:d?`Destroying…`:`Yes, destroy`})]})]})]})}var oO=[`prompts`,`search`,`story`,`sandboxes`,`scan`,`calls`,`changes`,`sandbox`,`context`,`thought`,`playground`];function sO(e){let t=new URLSearchParams(typeof window>`u`?``:window.location.search),n=t.get(`view`),r=n===`lab`?`context`:n;return{view:r&&e.includes(r)?r:`prompts`,trace:t.get(`trace`)??``,call:t.get(`call`),step:t.get(`step`),box:t.get(`box`)??``,q:t.get(`q`)??``}}function cO(e){let t=new URLSearchParams;e.view!==`prompts`&&t.set(`view`,e.view),e.trace&&t.set(`trace`,e.trace),e.call&&t.set(`call`,e.call),e.step&&t.set(`step`,e.step),e.box&&t.set(`box`,e.box),e.view===`search`&&e.q&&t.set(`q`,e.q);let n=t.toString();window.history.pushState(null,``,n?`?${n}`:window.location.pathname)}var lO=e=>e.split(`
|
|
38
38
|
`).find(e=>e.trim())?.trim()??``,uO=e=>`${e.exchange_id}:${e.output_index}`;function dO({views:e=oO,offline:t=`PROXY OFFLINE`,footer:n=null}){let r=t=>e.includes(t),[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)({view:`prompts`,trace:``,call:null,step:null,box:``,q:``}),[f,p]=(0,_.useState)(``),m=(0,_.useRef)(null),h=Mw();(0,_.useEffect)(()=>{d(sO(e));let t=()=>d(sO(e));return window.addEventListener(`popstate`,t),()=>window.removeEventListener(`popstate`,t)},[e]);let g=(0,_.useCallback)(e=>{d(t=>{let n={...t,call:null,step:null,box:``,q:``,...e};return cO(n),n})},[]);(0,_.useEffect)(()=>{let e=!1,t,n=``,r=async()=>{try{let t=await x().fetch(`/raytace/traces?scope=history`,{cache:`no-store`,headers:n?{"if-none-match":n}:{}});if(t.status===304)e||s(!0);else{if(!t.ok)throw Error(`Proxy unavailable`);let r=await t.json();n=t.headers.get(`etag`)??``,e||(a(r.traces||[]),s(!0))}}catch{e||s(!1)}e||(l(!0),t=setTimeout(r,5e3))};return r(),()=>{e=!0,clearTimeout(t)}},[]);let[v,y]=(0,_.useState)(0),[b,S]=(0,_.useState)(0),C=e.includes(`scan`);(0,_.useEffect)(()=>{if(!C)return;let e=!1,t,n=async()=>{try{let t=await Gw();e||y(t.unseen)}catch{}e||(t=setTimeout(n,1e4))};return n(),()=>{e=!0,clearTimeout(t)}},[C,b]);let w=i.find(e=>e.id===u.trace),T=[{view:`prompts`,label:`Prompts`,icon:ce},{view:`search`,label:`Search`,icon:ge},{view:`story`,label:`Story`,icon:le},{view:`sandboxes`,label:`Sandboxes`,icon:L},{view:`scan`,label:`Initial scan`,icon:he},{view:`calls`,label:`Tool calls`,icon:we},{view:`changes`,label:`Changes`,icon:U},{view:`sandbox`,label:`Sandbox evidence`,icon:ve},{view:`context`,label:`Context`,icon:oe},{view:`thought`,label:`Chain of thought`,icon:R},{view:`playground`,label:`Playground`,icon:ie}].filter(e=>r(e.view));function E(){return!c&&u.trace?(0,K.jsx)(`section`,{className:`rt-view`,children:(0,K.jsx)(`p`,{className:`rt-empty`,children:`Loading…`})}):(0,K.jsx)(`section`,{className:`rt-view`,children:(0,K.jsxs)(`p`,{className:`rt-empty`,children:[c&&u.trace&&!w?`That prompt is no longer in the loaded history.`:`Choose a prompt first.`,` `,(0,K.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>g({view:`prompts`}),children:`Go to Prompts`})]})})}return(0,K.jsxs)(`main`,{className:`rt-shell`,ref:m,children:[(0,K.jsxs)(`aside`,{className:`nav rt-nav`,children:[(0,K.jsxs)(`div`,{className:`brand`,children:[(0,K.jsx)(Se,{size:22}),` RayTrace`]}),r(`search`)&&(0,K.jsxs)(`form`,{className:`rt-nav-search`,onSubmit:e=>{e.preventDefault(),g({view:`search`,q:f})},children:[(0,K.jsx)(ge,{size:13}),(0,K.jsx)(`input`,{value:f,onChange:e=>p(e.target.value),placeholder:`Search what agents did…`,"aria-label":`Search agent activity`,spellCheck:!1})]}),(0,K.jsx)(`nav`,{className:`nav-destinations`,children:T.map(({view:e,label:t,icon:n})=>(0,K.jsxs)(`button`,{type:`button`,className:`nav-item ${u.view===e?`active`:``}`,onClick:()=>g({view:e,trace:u.trace,...e===`scan`?{box:u.box||w?.sandboxId||``}:{}}),children:[(0,K.jsx)(n,{size:16}),` `,t,e===`scan`&&v>0&&(0,K.jsx)(`span`,{className:`rt-count`,title:`${v} unseen alert${v===1?``:`s`}`,children:v})]},e))}),w&&(0,K.jsxs)(`div`,{className:`rt-viewing`,children:[(0,K.jsx)(`span`,{className:`workspace-label`,children:`VIEWING`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>g({view:`prompts`,trace:w.id}),title:w.title,children:lO(w.title)}),(0,K.jsx)(`small`,{children:new Date(w.startedAt).toLocaleString(void 0,{day:`numeric`,month:`short`,hour:`numeric`,minute:`2-digit`})})]}),(0,K.jsxs)(`div`,{className:`nav-bottom`,children:[(0,K.jsxs)(`div`,{className:`nav-status`,children:[(0,K.jsxs)(`span`,{className:`status ${c?o?``:`offline`:`pending`}`,children:[(0,K.jsx)(`i`,{}),c?o?`CONNECTED`:t:`CONNECTING…`]}),(0,K.jsx)(`button`,{type:`button`,className:`theme-toggle`,onClick:()=>Aw(h===`light`?`dark`:`light`),"aria-pressed":h===`dark`,"aria-label":`Switch to ${h===`light`?`dark`:`light`} theme`,title:`Switch to ${h===`light`?`dark`:`light`} theme`,children:`◐`})]}),n]}),(0,K.jsx)(CE,{target:m,variable:`--nav-width`,storageKey:`raytace.nav-width`,min:180,max:480,label:`Navigation width`})]}),u.view===`prompts`&&r(`prompts`)&&(0,K.jsx)(eD,{traces:i.filter(e=>!e.forkId),loaded:c,selectedId:u.trace,onSelect:e=>g({view:`prompts`,trace:e}),onOpen:(e,t)=>g({view:e,trace:t}),onOpenStep:(e,t)=>g({view:`calls`,trace:e,call:t}),canOpen:r}),u.view===`search`&&r(`search`)&&(0,K.jsx)(lD,{initialQuery:u.q,onQuery:e=>g({view:`search`,trace:u.trace,q:e}),onOpenCall:(e,t)=>g({view:`calls`,trace:e,call:t}),onOpenTrace:e=>g({view:`prompts`,trace:e}),onOpenSandbox:r(`sandbox`)?(e,t)=>g({view:`sandbox`,trace:e,call:t}):void 0},u.q),u.view===`story`&&r(`story`)&&(w?(0,K.jsx)(wD,{trace:w,focusCall:u.call,onSelect:e=>g({view:`story`,trace:w.id,call:e}),onOpenCall:e=>g({view:`calls`,trace:w.id,call:e}),onOpenThought:r(`thought`)?e=>g({view:`thought`,trace:w.id,call:e}):void 0,onOpenSandbox:r(`sandbox`)?e=>g({view:`sandbox`,trace:w.id,call:e}):void 0},w.id):E()),u.view===`sandboxes`&&r(`sandboxes`)&&(0,K.jsx)(aO,{traces:i,selectedId:u.box,onSelect:e=>g({view:`sandboxes`,box:e}),onOpenTrace:e=>g({view:`calls`,trace:e}),onOpenScan:r(`scan`)?e=>g({view:`scan`,trace:u.trace,box:e}):void 0}),u.view===`scan`&&r(`scan`)&&(0,K.jsx)(xT,{box:u.box,traces:i,onSelect:e=>g({view:`scan`,trace:u.trace,box:e}),onOpenCall:(e,t)=>g({view:`calls`,trace:e,call:t}),onAlertsSeen:()=>S(e=>e+1)}),u.view===`calls`&&r(`calls`)&&(w?(0,K.jsx)(KT,{trace:w,traces:i,focusCall:u.call,onOpenSandbox:r(`sandbox`)?e=>g({view:`sandbox`,trace:w.id,call:e??null}):void 0,onOpenContext:r(`context`)?e=>g({view:`context`,trace:w.id,step:uO(e)}):void 0,onOpenThought:r(`thought`)?e=>g({view:`thought`,trace:w.id,call:e}):void 0,onOpenPlayground:r(`playground`)?(e,t)=>g({view:`playground`,trace:w.id,step:e,call:t??null}):void 0},w.id):E()),u.view===`changes`&&r(`changes`)&&(w?(0,K.jsx)(ED,{trace:w,onOpenCall:r(`calls`)?e=>g({view:`calls`,trace:w.id,call:e}):void 0},w.id):E()),u.view===`sandbox`&&r(`sandbox`)&&(w?(0,K.jsx)(kD,{trace:w,focusCall:u.call,onOpenCall:e=>g({view:`calls`,trace:w.id,call:e??null})},w.id):E()),u.view===`playground`&&r(`playground`)&&(w?(0,K.jsx)(GE,{trace:w,stepId:u.step,removeCall:u.call,forkTraces:i.filter(e=>e.forkId),onStep:e=>g({view:`playground`,trace:w.id,step:e}),onOpenTrace:e=>g({view:`calls`,trace:e})},`${w.id}:${u.step??``}`):E()),u.view===`context`&&r(`context`)&&(w?(0,K.jsx)(bE,{trace:w,stepKey:u.step,onStep:e=>g({view:`context`,trace:w.id,step:e}),onRerunWithout:r(`playground`)?(e,t)=>g({view:`playground`,trace:w.id,step:e,call:t}):void 0},w.id):E()),u.view===`thought`&&r(`thought`)&&(w?(0,K.jsx)(oE,{trace:w,focusCall:u.call},w.id):E())]})}var fO=[`prompts`,`search`,`story`,`sandboxes`,`calls`,`changes`,`sandbox`,`context`,`thought`,`playground`];S({fetch:(e,t)=>fetch(e,t)});var pO=4;function mO(){let[e,t]=(0,_.useState)(!1),[n,r]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{fetch(`/raytace/version`).then(e=>e.ok?e.json():{api:0}).then(e=>t((Number(e.api)||0)<pO),()=>{}),fetch(`/raytace/models`).then(e=>r(e.status===401),()=>{})},[]),!e&&!n?null:(0,K.jsx)(`div`,{role:`alert`,style:{padding:`10px 16px`,background:`light-dark(#fff4d6,#3a2f12)`,color:`light-dark(#5c4300,#ffd97a)`,fontSize:13,borderBottom:`1px solid light-dark(#f0d48a,#5c4a1c)`},children:e?(0,K.jsxs)(K.Fragment,{children:[`An older RayTrace proxy is running, so parts of this page cannot load. Restart it: `,(0,K.jsx)(`code`,{children:`raytrace stop && raytrace start`})]}):(0,K.jsxs)(K.Fragment,{children:[`This browser is not signed in to RayTrace, so nothing can load. In a terminal, run: `,(0,K.jsx)(`code`,{children:`raytrace open`})]})})}(0,v.createRoot)(document.getElementById(`root`)).render((0,K.jsxs)(_.StrictMode,{children:[(0,K.jsx)(mO,{}),(0,K.jsx)(dO,{views:fO})]}));
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
<title>RayTrace — Agent trace forensics</title>
|
|
7
7
|
<meta name="description" content="Evidence-backed traces and live counterfactual forks for coding agents." />
|
|
8
8
|
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
|
9
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-CeIGjyFc.js"></script>
|
|
10
10
|
<link rel="stylesheet" crossorigin href="/assets/index-DtV3UdEB.css">
|
|
11
11
|
</head>
|
|
12
12
|
<body class="antialiased">
|
package/package.json
CHANGED
package/src/api.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Shared client for RayTrace's cloud API (https://api.raytracer.si;
|
|
2
|
+
// RAYTRACE_API_URL points elsewhere). Requests carry your `raytrace auth
|
|
3
|
+
// login` token; RAYTRACE_API_KEY overrides it for a server running without
|
|
4
|
+
// accounts (development).
|
|
5
|
+
import { accessToken, consumeIdleNotice, login } from './auth.mjs';
|
|
6
|
+
import { readConfig } from './config.mjs';
|
|
7
|
+
import { interactive } from './prompt.mjs';
|
|
8
|
+
|
|
9
|
+
const say = (line = '') => console.log(line);
|
|
10
|
+
const API = 'https://api.raytracer.si';
|
|
11
|
+
|
|
12
|
+
export const unreachable = (url) => new Error(`Cannot reach RayTrace at ${url.origin}. Check your connection; `
|
|
13
|
+
+ 'networks that inspect HTTPS (some company Wi-Fi) may block it.');
|
|
14
|
+
|
|
15
|
+
export class ApiError extends Error {
|
|
16
|
+
constructor(message, { status = null, data = {} } = {}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'ApiError';
|
|
19
|
+
this.status = status;
|
|
20
|
+
this.data = data;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** True when a development API key overrides the signed-in account. */
|
|
25
|
+
export function hasApiKeyOverride() {
|
|
26
|
+
return Boolean(process.env.RAYTRACE_API_KEY || readConfig().RAYTRACE_API_KEY);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function api({ autoLogin = true } = {}) {
|
|
30
|
+
const config = readConfig();
|
|
31
|
+
const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
|
|
32
|
+
let key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
|
|
33
|
+
if (!key) {
|
|
34
|
+
if (!autoLogin || !interactive()) throw new Error('Not signed in. Run: raytrace auth login');
|
|
35
|
+
say(consumeIdleNotice()
|
|
36
|
+
? 'You have not used RayTrace cloud for 2 days, so you need to sign in again.'
|
|
37
|
+
: 'You are not signed in to RayTrace yet.');
|
|
38
|
+
await login();
|
|
39
|
+
key = await accessToken();
|
|
40
|
+
if (!key) throw new Error('Not signed in. Run: raytrace auth login');
|
|
41
|
+
say();
|
|
42
|
+
}
|
|
43
|
+
return { url: new URL(url), key };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function call(method, path, { body, headers = {}, autoLogin = true } = {}) {
|
|
47
|
+
const { url, key } = await api({ autoLogin });
|
|
48
|
+
let response;
|
|
49
|
+
try {
|
|
50
|
+
response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
|
|
51
|
+
} catch {
|
|
52
|
+
throw unreachable(url);
|
|
53
|
+
}
|
|
54
|
+
const data = await response.json().catch(() => ({}));
|
|
55
|
+
if (!response.ok) throw new ApiError(data.error || `HTTP ${response.status}`, { status: response.status, data });
|
|
56
|
+
return data;
|
|
57
|
+
}
|
package/src/auth.mjs
CHANGED
|
@@ -75,15 +75,42 @@ function keep(data) {
|
|
|
75
75
|
access_token: data.access_token, refresh_token: data.refresh_token,
|
|
76
76
|
user: { id: data.user?.id, email: data.user?.email, name: [data.user?.first_name, data.user?.last_name].filter(Boolean).join(' ') },
|
|
77
77
|
organization_id: data.organization_id ?? null,
|
|
78
|
+
last_used_at: Date.now(),
|
|
78
79
|
};
|
|
79
80
|
}
|
|
80
81
|
|
|
82
|
+
// Cloud use asks for a fresh sign-in after 2 idle days (sliding: any cloud
|
|
83
|
+
// command resets the clock). Local recording never consults this.
|
|
84
|
+
export const CLOUD_IDLE_LIMIT_MS = 2 * 86_400_000;
|
|
85
|
+
const TOUCH_EVERY_MS = 3_600_000; // last_used_at is rewritten at most hourly
|
|
86
|
+
let idleNotice = false;
|
|
87
|
+
|
|
88
|
+
export const isIdleExpired = (session, now = Date.now()) =>
|
|
89
|
+
Boolean(session?.last_used_at && now - session.last_used_at > CLOUD_IDLE_LIMIT_MS);
|
|
90
|
+
|
|
91
|
+
/** True once after accessToken() dropped a session for idleness. */
|
|
92
|
+
export function consumeIdleNotice() { const was = idleNotice; idleNotice = false; return was; }
|
|
93
|
+
|
|
81
94
|
/** A current access token, refreshed when it is about to expire; null when signed out. */
|
|
82
95
|
export async function accessToken() {
|
|
83
96
|
const session = load();
|
|
84
97
|
if (!session?.access_token) return null;
|
|
98
|
+
if (isIdleExpired(session)) {
|
|
99
|
+
// Idle too long: drop the session so the cloud path starts a fresh
|
|
100
|
+
// sign-in and continues (it says why via consumeIdleNotice()).
|
|
101
|
+
forget();
|
|
102
|
+
idleNotice = true;
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
85
105
|
const { exp = 0 } = claims(session.access_token);
|
|
86
|
-
if (exp * 1000 - Date.now() > 60_000)
|
|
106
|
+
if (exp * 1000 - Date.now() > 60_000) {
|
|
107
|
+
// Sliding window: cloud use resets the idle clock (throttled writes;
|
|
108
|
+
// sessions saved before this field existed start their clock now).
|
|
109
|
+
if (!session.last_used_at || Date.now() - session.last_used_at > TOUCH_EVERY_MS) {
|
|
110
|
+
try { save({ ...session, last_used_at: Date.now() }); } catch { /* the token still works */ }
|
|
111
|
+
}
|
|
112
|
+
return session.access_token;
|
|
113
|
+
}
|
|
87
114
|
if (!session.refresh_token) return null;
|
|
88
115
|
const { status, data } = await workos('/authenticate', {
|
|
89
116
|
grant_type: 'refresh_token', refresh_token: session.refresh_token, client_id: CLIENT_ID,
|
|
@@ -98,13 +125,16 @@ export async function accessToken() {
|
|
|
98
125
|
|
|
99
126
|
// ------------------------------------------------------------- commands
|
|
100
127
|
|
|
101
|
-
function openUrl(url) {
|
|
128
|
+
export function openUrl(url) {
|
|
102
129
|
const [command, args] = process.platform === 'darwin' ? ['open', [url]]
|
|
103
130
|
: process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
|
|
104
131
|
spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
|
|
105
132
|
}
|
|
106
133
|
|
|
107
|
-
|
|
134
|
+
/** Start WorkOS's device login. Returns the code and page to show at once;
|
|
135
|
+
* `done` settles when the code is approved (the session is then saved),
|
|
136
|
+
* declined, or expired. */
|
|
137
|
+
export async function startDeviceLogin() {
|
|
108
138
|
const start = await workos('/authorize/device', { client_id: CLIENT_ID });
|
|
109
139
|
if (start.status !== 200 || !start.data.device_code) {
|
|
110
140
|
throw new Error(`WorkOS refused to start the sign-in: ${start.data.error_description || start.data.message || `HTTP ${start.status}`}`);
|
|
@@ -112,29 +142,34 @@ export async function login() {
|
|
|
112
142
|
const { device_code, user_code, verification_uri, verification_uri_complete } = start.data;
|
|
113
143
|
let interval = (start.data.interval || 5) * 1000;
|
|
114
144
|
const deadline = Date.now() + (start.data.expires_in || 300) * 1000;
|
|
145
|
+
const done = (async () => {
|
|
146
|
+
while (Date.now() < deadline) {
|
|
147
|
+
await new Promise((resolve) => setTimeout(resolve, interval));
|
|
148
|
+
const { status, data } = await workos('/authenticate', {
|
|
149
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code', device_code, client_id: CLIENT_ID,
|
|
150
|
+
device_id: hostname().slice(0, 100),
|
|
151
|
+
});
|
|
152
|
+
if (status === 200 && data.access_token) return { email: data.user?.email, where: save(keep(data)) };
|
|
153
|
+
if (data.error === 'authorization_pending') continue;
|
|
154
|
+
if (data.error === 'slow_down') { interval += 5000; continue; }
|
|
155
|
+
if (data.error === 'access_denied') throw new Error('The sign-in was declined.');
|
|
156
|
+
if (data.error === 'expired_token') break;
|
|
157
|
+
throw new Error(`Sign-in failed: ${data.error_description || data.error || `HTTP ${status}`}`);
|
|
158
|
+
}
|
|
159
|
+
throw new Error('The code expired before it was approved. Run raytrace auth login again.');
|
|
160
|
+
})();
|
|
161
|
+
return { user_code, verification_uri, verification_uri_complete, done };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function login() {
|
|
165
|
+
const { user_code, verification_uri, verification_uri_complete, done } = await startDeviceLogin();
|
|
115
166
|
say(`Your sign-in code: ${user_code}`);
|
|
116
167
|
say(`Opening ${verification_uri}: sign in, or create your account, and approve the code`);
|
|
117
168
|
say('(or open it yourself on any device).');
|
|
118
169
|
openUrl(verification_uri_complete || verification_uri);
|
|
119
170
|
say('Waiting for approval...');
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const { status, data } = await workos('/authenticate', {
|
|
123
|
-
grant_type: 'urn:ietf:params:oauth:grant-type:device_code', device_code, client_id: CLIENT_ID,
|
|
124
|
-
device_id: hostname().slice(0, 100),
|
|
125
|
-
});
|
|
126
|
-
if (status === 200 && data.access_token) {
|
|
127
|
-
const where = save(keep(data));
|
|
128
|
-
say(`\nSigned in as ${data.user?.email}. Your sign-in is kept in ${where}.`);
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
if (data.error === 'authorization_pending') continue;
|
|
132
|
-
if (data.error === 'slow_down') { interval += 5000; continue; }
|
|
133
|
-
if (data.error === 'access_denied') throw new Error('The sign-in was declined.');
|
|
134
|
-
if (data.error === 'expired_token') break;
|
|
135
|
-
throw new Error(`Sign-in failed: ${data.error_description || data.error || `HTTP ${status}`}`);
|
|
136
|
-
}
|
|
137
|
-
throw new Error('The code expired before it was approved. Run raytrace auth login again.');
|
|
171
|
+
const { email, where } = await done;
|
|
172
|
+
say(`\nSigned in as ${email}. Your sign-in is kept in ${where}.`);
|
|
138
173
|
}
|
|
139
174
|
|
|
140
175
|
/** `raytrace auth login`: sign in, then say what comes next. */
|
|
@@ -154,6 +189,13 @@ export async function status() {
|
|
|
154
189
|
say(`Organization: ${org || session.organization_id || 'personal'}`);
|
|
155
190
|
const left = Math.round((exp * 1000 - Date.now()) / 60000);
|
|
156
191
|
say(left > 0 ? `Access token valid for ${left} more min; renewed automatically.` : 'Access token expired; it is renewed on the next command.');
|
|
192
|
+
// Beta is a cloud entitlement, separate from any local licence tier.
|
|
193
|
+
try {
|
|
194
|
+
const { betaStatus, formatCreditDeadline } = await import('./beta.mjs');
|
|
195
|
+
const beta = await betaStatus();
|
|
196
|
+
if (beta?.sandbox_consumed) say(`Beta: $10 credit used${beta.credited_sandbox_id ? ` on ${beta.credited_sandbox_id}` : ''}.`);
|
|
197
|
+
else if (beta?.entitled) say(`Beta: $${beta.credit_usd ?? 10} credit available${beta.credit_expires_at ? ` until ${formatCreditDeadline(beta.credit_expires_at)}` : ''} (raytrace sandbox create).`);
|
|
198
|
+
} catch { /* no beta entitlement, old backend, or offline: nothing to add */ }
|
|
157
199
|
}
|
|
158
200
|
|
|
159
201
|
export async function logout() {
|
package/src/beta.mjs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// `raytrace --code <code>`: redeem a single-use beta code handed out by
|
|
2
|
+
// RayTrace. Sign-in (`raytrace auth login`) is a prerequisite — this command
|
|
3
|
+
// never starts a sign-in flow and never sends the code anywhere until a
|
|
4
|
+
// signed-in account is known. The backend is the source of truth: on a
|
|
5
|
+
// successful redeem it deletes the code irreversibly and binds a $10
|
|
6
|
+
// OpenRouter credit (hard 3-day limit) to the signed-in account. Nothing
|
|
7
|
+
// about the code or entitlement is stored on this machine.
|
|
8
|
+
import { accessToken, consumeIdleNotice } from './auth.mjs';
|
|
9
|
+
import { call, hasApiKeyOverride } from './api.mjs';
|
|
10
|
+
|
|
11
|
+
const say = (line = '') => console.log(line);
|
|
12
|
+
|
|
13
|
+
export const normalizeBetaCode = (code) => String(code ?? '').trim().toUpperCase().replace(/\s+/g, '');
|
|
14
|
+
|
|
15
|
+
// Codes are minted only in the backend repo (raytrace:
|
|
16
|
+
// worker/gvisor/mint_beta_codes.py), which stores SHA-256 hashes of the
|
|
17
|
+
// normalized code in `beta_codes` and deletes the row on redemption. The
|
|
18
|
+
// shared contract: RTB-XXXX-XXXX-XXXX (Crockford Base32), normalized as
|
|
19
|
+
// above, 3-day expiry. This CLI only presents a code; it never mints one.
|
|
20
|
+
|
|
21
|
+
export function formatCreditDeadline(iso, now = Date.now()) {
|
|
22
|
+
if (!iso) return '';
|
|
23
|
+
const when = new Date(iso);
|
|
24
|
+
if (Number.isNaN(when.getTime())) return '';
|
|
25
|
+
const label = when.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
|
|
26
|
+
const ms = when.getTime() - now;
|
|
27
|
+
if (ms <= 0) return `${label} (expired)`;
|
|
28
|
+
const hours = Math.round(ms / 3_600_000);
|
|
29
|
+
return `${label} (about ${hours <= 1 ? '1 hour' : `${hours} hours`} left)`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Signed-in check that never starts a login flow and never touches a code. */
|
|
33
|
+
export async function ensureSignedIn(getToken = accessToken) {
|
|
34
|
+
if (hasApiKeyOverride()) return;
|
|
35
|
+
const token = await getToken();
|
|
36
|
+
if (!token) {
|
|
37
|
+
throw new Error(consumeIdleNotice()
|
|
38
|
+
? 'You have not used RayTrace cloud for 2 days, so you need to sign in again. Run: raytrace auth login, then re-run: raytrace --code <your-code>'
|
|
39
|
+
: 'Not signed in. Run: raytrace auth login, then re-run: raytrace --code <your-code>');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function betaStatus(apiCall = call) {
|
|
44
|
+
return apiCall('GET', '/v1/beta/status', { autoLogin: false });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function redeemError(error) {
|
|
48
|
+
switch (error?.status) {
|
|
49
|
+
case 401: return new Error('Not signed in. Run: raytrace auth login, then re-run: raytrace --code <your-code>');
|
|
50
|
+
case 422: return new Error("That code isn't valid. Check it and try again, or ask RayTrace for a new one.");
|
|
51
|
+
case 410: return new Error('That code has expired (codes must be redeemed within 3 days). Ask RayTrace for a new one.');
|
|
52
|
+
case 409: return new Error('This account already has beta credit, so this code was not used. '
|
|
53
|
+
+ 'It can still be given to someone else until it expires.');
|
|
54
|
+
case 429: return new Error('Too many code attempts. Wait a while and try again.');
|
|
55
|
+
default: return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function redeemBetaCode(rawCode, { ensure = ensureSignedIn, apiCall = call, log = say } = {}) {
|
|
60
|
+
const code = normalizeBetaCode(rawCode);
|
|
61
|
+
if (!code) throw new Error('Usage: raytrace --code <code>');
|
|
62
|
+
// Prerequisite first: an unauthenticated attempt must not consume,
|
|
63
|
+
// validate, or delete the code on the backend.
|
|
64
|
+
await ensure();
|
|
65
|
+
let data;
|
|
66
|
+
try {
|
|
67
|
+
data = await apiCall('POST', '/v1/beta/redeem', {
|
|
68
|
+
body: JSON.stringify({ code }),
|
|
69
|
+
headers: { 'content-type': 'application/json' },
|
|
70
|
+
autoLogin: false,
|
|
71
|
+
});
|
|
72
|
+
} catch (error) {
|
|
73
|
+
const mapped = redeemError(error);
|
|
74
|
+
if (mapped) throw mapped;
|
|
75
|
+
// The code is deleted on success, so a lost response looks like a
|
|
76
|
+
// failure here while the entitlement already exists. Check before
|
|
77
|
+
// reporting failure; the entitlement is what the user needs.
|
|
78
|
+
try {
|
|
79
|
+
const status = await betaStatus(apiCall);
|
|
80
|
+
if (status?.entitled) {
|
|
81
|
+
log("You're already good for beta testing: this account has its beta credit.");
|
|
82
|
+
if (status.credit_expires_at) log(`Use it by ${formatCreditDeadline(status.credit_expires_at)}: raytrace sandbox create`);
|
|
83
|
+
return status;
|
|
84
|
+
}
|
|
85
|
+
} catch { /* fall through to the original error */ }
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
const credit = data?.credit_usd ?? 10;
|
|
89
|
+
log(`You're good for beta testing: $${credit} of Claude Code credit (via OpenRouter) is on this account.`);
|
|
90
|
+
log('Your account now shows as Beta in the RayTrace dashboard.');
|
|
91
|
+
if (data?.credit_expires_at) {
|
|
92
|
+
log(`Hard limit: create your sandbox and use the credit by ${formatCreditDeadline(data.credit_expires_at)}. Unused credit expires.`);
|
|
93
|
+
}
|
|
94
|
+
log('Next, from a Git repository: raytrace sandbox create');
|
|
95
|
+
return data;
|
|
96
|
+
}
|
package/src/mcp.mjs
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
// `raytrace mcp`: an MCP server on stdio, so an agent in VS Code, Cursor,
|
|
2
|
+
// Claude Code or any MCP client can create, list, stop and destroy cloud
|
|
3
|
+
// sandboxes. It runs on the user's machine (the IDE starts it), which is what
|
|
4
|
+
// lets create_sandbox pack the project the IDE has open, exactly as
|
|
5
|
+
// `raytrace sandbox create` does, and reuse the `raytrace auth login` sign-in.
|
|
6
|
+
//
|
|
7
|
+
// The protocol is newline-delimited JSON-RPC 2.0 on stdin/stdout, small
|
|
8
|
+
// enough to speak here without a dependency. stdout carries protocol messages
|
|
9
|
+
// only: anything else printed there would corrupt the stream, so console
|
|
10
|
+
// output is sent to stderr while serving.
|
|
11
|
+
import { readFileSync } from 'node:fs';
|
|
12
|
+
import { basename, isAbsolute, resolve } from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { createInterface } from 'node:readline';
|
|
15
|
+
import { accessToken, account, openUrl, startDeviceLogin } from './auth.mjs';
|
|
16
|
+
import { call, hasApiKeyOverride } from './api.mjs';
|
|
17
|
+
import { formatCreditDeadline } from './beta.mjs';
|
|
18
|
+
import { checkId, creditPlan, isCreditRefusal, listProject, liveSandboxes, packArchive, repoRoot, upload } from './sandbox.mjs';
|
|
19
|
+
|
|
20
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
21
|
+
const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
22
|
+
const DASHBOARD = 'https://app.raytracer.si';
|
|
23
|
+
|
|
24
|
+
const INSTRUCTIONS = `RayTrace cloud sandboxes: isolated copies of a Git project on RayTrace's servers, where coding-agent sessions are recorded for the user's organization dashboard (${DASHBOARD}).
|
|
25
|
+
- Every tool needs a RayTrace sign-in. If a tool says the user is not signed in, call login and show the user the code and link it returns; once they approve it in the browser, retry.
|
|
26
|
+
- create_sandbox uploads the open Git project (files git tracks or would track; .env files, keys and credentials are never uploaded).
|
|
27
|
+
- To work inside a sandbox, the user runs \`raytrace connect <id>\` in a terminal.
|
|
28
|
+
- destroy_sandbox deletes the sandbox's files and any sign-in made inside it. Its recorded traces are deleted too, unless keep_traces is passed on a paid plan. Confirm with the user first, including whether to keep the traces.
|
|
29
|
+
- Cloud sandboxes only; local sandboxes (raytrace sandbox create --local) are managed from the terminal.`;
|
|
30
|
+
|
|
31
|
+
const idSchema = { type: 'string', pattern: '^rtp-[a-f0-9]{32}$', description: 'The sandbox id (rtp-...), from list_sandboxes.' };
|
|
32
|
+
|
|
33
|
+
const TOOLS = [
|
|
34
|
+
{
|
|
35
|
+
name: 'login',
|
|
36
|
+
title: 'Sign in to RayTrace',
|
|
37
|
+
description: 'Sign in to RayTrace (or create an account) in the browser. Returns a code and a link to show the user; the sign-in completes when they approve it. When already signed in, says which account.',
|
|
38
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
39
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
name: 'list_sandboxes',
|
|
43
|
+
title: 'List sandboxes',
|
|
44
|
+
description: "The signed-in workspace's cloud sandboxes: id, name, status, age and beta credit.",
|
|
45
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
46
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: 'sandbox_status',
|
|
50
|
+
title: 'Sandbox status',
|
|
51
|
+
description: "One sandbox's details, with the command that opens a terminal in it.",
|
|
52
|
+
inputSchema: { type: 'object', properties: { id: idSchema }, required: ['id'], additionalProperties: false },
|
|
53
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'create_sandbox',
|
|
57
|
+
title: 'Create a sandbox',
|
|
58
|
+
description: 'Upload a Git project to a new cloud sandbox and start it. Uploads what git tracks or would track, never .env files, keys or credentials; up to 200 MiB, 25 MiB a file, 20,000 files. Takes a minute or so.',
|
|
59
|
+
inputSchema: {
|
|
60
|
+
type: 'object',
|
|
61
|
+
properties: {
|
|
62
|
+
path: { type: 'string', description: 'A folder inside the Git project to upload; relative paths are resolved against the workspace. Defaults to the open workspace.' },
|
|
63
|
+
name: { type: 'string', description: "The sandbox's name. Defaults to the project folder's name." },
|
|
64
|
+
without_beta_credit: { type: 'boolean', description: "Create a plain sandbox, not using the user's beta credit. Only after the user agrees, when create_sandbox reported the credit expired or used." },
|
|
65
|
+
},
|
|
66
|
+
additionalProperties: false,
|
|
67
|
+
},
|
|
68
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: 'start_sandbox',
|
|
72
|
+
title: 'Start a sandbox',
|
|
73
|
+
description: 'Start a stopped sandbox.',
|
|
74
|
+
inputSchema: { type: 'object', properties: { id: idSchema }, required: ['id'], additionalProperties: false },
|
|
75
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
name: 'stop_sandbox',
|
|
79
|
+
title: 'Stop a sandbox',
|
|
80
|
+
description: 'Stop a running sandbox. Its files are kept; start_sandbox brings it back.',
|
|
81
|
+
inputSchema: { type: 'object', properties: { id: idSchema }, required: ['id'], additionalProperties: false },
|
|
82
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: 'destroy_sandbox',
|
|
86
|
+
title: 'Destroy a sandbox',
|
|
87
|
+
description: "Delete a sandbox: its files and any sign-in made inside it. Its recorded traces are deleted too unless keep_traces is true, which only paid plans honour (traces then stay until the plan's retention date). This cannot be undone; confirm with the user first.",
|
|
88
|
+
inputSchema: {
|
|
89
|
+
type: 'object',
|
|
90
|
+
properties: { id: idSchema, keep_traces: { type: 'boolean', description: "Keep the sandbox's recorded traces until the retention date (paid plans). Defaults to false." } },
|
|
91
|
+
required: ['id'],
|
|
92
|
+
additionalProperties: false,
|
|
93
|
+
},
|
|
94
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
95
|
+
},
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
// ------------------------------------------------------------- transport
|
|
99
|
+
|
|
100
|
+
const send = (message) => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);
|
|
101
|
+
const pending = new Map(); // our requests to the client, by id
|
|
102
|
+
let nextId = 1;
|
|
103
|
+
let client = { capabilities: {} };
|
|
104
|
+
|
|
105
|
+
/** Ask the client something (roots/list); null when it does not answer in time. */
|
|
106
|
+
function request(method, params, timeoutMs = 5000) {
|
|
107
|
+
const id = `raytrace-${nextId++}`;
|
|
108
|
+
return new Promise((resolve) => {
|
|
109
|
+
const timer = setTimeout(() => { pending.delete(id); resolve(null); }, timeoutMs);
|
|
110
|
+
pending.set(id, (message) => { clearTimeout(timer); resolve(message.error ? null : message.result); });
|
|
111
|
+
send({ id, method, params });
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function progress(token) {
|
|
116
|
+
let step = 0;
|
|
117
|
+
return (message) => { if (token !== undefined) send({ method: 'notifications/progress', params: { progressToken: token, progress: ++step, message } }); };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ------------------------------------------------------------- tools
|
|
121
|
+
|
|
122
|
+
const text = (body, structured) => ({ content: [{ type: 'text', text: body }], ...(structured ? { structuredContent: structured } : {}) });
|
|
123
|
+
class ToolError extends Error {}
|
|
124
|
+
|
|
125
|
+
let signIn = null; // the device login under way: { user_code, verification_uri, ..., error }
|
|
126
|
+
|
|
127
|
+
async function requireSignIn() {
|
|
128
|
+
if (hasApiKeyOverride()) return;
|
|
129
|
+
let token;
|
|
130
|
+
try { token = await accessToken(); }
|
|
131
|
+
catch (error) { throw new ToolError(`${error.message.replace(/ Run: raytrace auth login$/, '')} Call the login tool to sign in again.`); }
|
|
132
|
+
if (token) return;
|
|
133
|
+
if (signIn && !signIn.error) {
|
|
134
|
+
throw new ToolError(`Not signed in yet: waiting for the user to approve code ${signIn.user_code} at ${signIn.verification_uri_complete || signIn.verification_uri}. Retry once they have.`);
|
|
135
|
+
}
|
|
136
|
+
throw new ToolError('Not signed in to RayTrace. Call the login tool, then show the user the code and link it returns.');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function login() {
|
|
140
|
+
if (hasApiKeyOverride()) return text('Using the RAYTRACE_API_KEY development key; no sign-in needed.');
|
|
141
|
+
const token = await accessToken().catch(() => null);
|
|
142
|
+
if (token) return text(`Signed in to RayTrace as ${account() ?? 'an unknown account'}.`, { signed_in: true, account: account() });
|
|
143
|
+
if (!signIn || signIn.error) {
|
|
144
|
+
const started = await startDeviceLogin();
|
|
145
|
+
signIn = { ...started, error: null };
|
|
146
|
+
const current = signIn;
|
|
147
|
+
started.done.then(() => { if (signIn === current) signIn = null; },
|
|
148
|
+
(error) => { current.error = error.message; });
|
|
149
|
+
openUrl(started.verification_uri_complete || started.verification_uri);
|
|
150
|
+
}
|
|
151
|
+
const link = signIn.verification_uri_complete || signIn.verification_uri;
|
|
152
|
+
return text(`Show the user this, then retry their request once they have approved it:\n\n`
|
|
153
|
+
+ `Sign in to RayTrace: open ${link} (a browser tab was opened on this machine) and approve the code ${signIn.user_code}. `
|
|
154
|
+
+ 'New to RayTrace? The same page creates an account.',
|
|
155
|
+
{ signed_in: false, user_code: signIn.user_code, verification_uri: link });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function describe(box) {
|
|
159
|
+
const created = typeof box.created === 'number' ? box.created * 1000 : Date.parse(box.created);
|
|
160
|
+
const minutes = Number.isFinite(created) ? Math.round((Date.now() - created) / 60000) : null;
|
|
161
|
+
const age = minutes === null ? '' : `, ${minutes < 120 ? `${minutes} min` : `${Math.round(minutes / 60)} h`} old`;
|
|
162
|
+
const beta = box.beta && typeof box.credit_usd === 'number'
|
|
163
|
+
? `, beta credit $${Math.max(0, box.credit_usd - (box.credit_spent_usd ?? 0)).toFixed(2)} of $${box.credit_usd} left${box.credit_expires_at ? ` (ends ${formatCreditDeadline(box.credit_expires_at)})` : ''}`
|
|
164
|
+
: '';
|
|
165
|
+
return `${box.id} ${box.status} ${box.name}${age}${beta}`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function listSandboxes() {
|
|
169
|
+
const boxes = await liveSandboxes();
|
|
170
|
+
if (!boxes.length) return text('No sandboxes yet. create_sandbox makes one from the open Git project.', { sandboxes: [] });
|
|
171
|
+
return text(boxes.map(describe).join('\n'), { sandboxes: boxes });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function findSandbox(id) {
|
|
175
|
+
const box = (await liveSandboxes()).find((each) => each.id === checkId(id));
|
|
176
|
+
if (!box) throw new ToolError(`No sandbox ${id} in ${account() ? `${account()}'s` : 'this'} workspace. list_sandboxes shows the ones there are.`);
|
|
177
|
+
return box;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function sandboxStatus({ id }) {
|
|
181
|
+
const box = await findSandbox(id);
|
|
182
|
+
return text(`${describe(box)}\nOpen a terminal in it: raytrace connect ${box.id}\nRecorded sessions: ${DASHBOARD}`, { sandbox: box, connect: `raytrace connect ${box.id}` });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The folders the client has open, as paths; [] when it shares none. */
|
|
186
|
+
async function workspaceRoots() {
|
|
187
|
+
if (!client.capabilities.roots) return [];
|
|
188
|
+
const result = await request('roots/list', {});
|
|
189
|
+
return (result?.roots ?? []).filter((root) => root.uri?.startsWith('file://')).map((root) => fileURLToPath(root.uri));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function projectRoot(path) {
|
|
193
|
+
const roots = await workspaceRoots();
|
|
194
|
+
if (path) {
|
|
195
|
+
const base = roots[0] ?? process.cwd();
|
|
196
|
+
const dir = isAbsolute(path) ? path : resolve(base, path);
|
|
197
|
+
const root = repoRoot(dir);
|
|
198
|
+
if (!root) throw new ToolError(`${dir} is not inside a Git repository. A sandbox is made from one.`);
|
|
199
|
+
return root;
|
|
200
|
+
}
|
|
201
|
+
const repos = [...new Set((roots.length ? roots : [process.cwd()]).map((dir) => repoRoot(dir)).filter(Boolean))];
|
|
202
|
+
if (repos.length === 1) return repos[0];
|
|
203
|
+
if (repos.length > 1) throw new ToolError(`The workspace has more than one Git project; pass path as one of:\n${repos.join('\n')}`);
|
|
204
|
+
throw new ToolError(`No Git project in ${roots.length ? roots.join(', ') : process.cwd()}. Pass path: a folder inside the Git project to upload.`);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function createSandbox({ path, name, without_beta_credit: plain = false }, step) {
|
|
208
|
+
const root = await projectRoot(path);
|
|
209
|
+
const { plan, beta } = plain ? { plan: 'none' } : await creditPlan();
|
|
210
|
+
if (plan === 'expired') {
|
|
211
|
+
throw new ToolError('No sandbox was created: the user\'s $10 beta credit expired (its 3 days ran out; unused credit does not carry over). '
|
|
212
|
+
+ 'Ask the user whether to create a plain sandbox without beta credit; if they agree, call create_sandbox again with without_beta_credit: true.');
|
|
213
|
+
}
|
|
214
|
+
const useCredit = plan === 'use';
|
|
215
|
+
const { files, skipped, total } = listProject(root);
|
|
216
|
+
const listed = `Uploaded ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}.`
|
|
217
|
+
+ (skipped.length ? ` Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}.` : '');
|
|
218
|
+
step(`Packing ${files.length} files from ${root}`);
|
|
219
|
+
const archive = await packArchive(root, files);
|
|
220
|
+
step('Creating the sandbox');
|
|
221
|
+
let box;
|
|
222
|
+
try {
|
|
223
|
+
box = await upload(archive, name || basename(root), useCredit);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (!useCredit || !isCreditRefusal(error)) throw error;
|
|
226
|
+
throw new ToolError(`No sandbox was created: the user's beta credit ${error.status === 410 ? 'expired before the sandbox was created' : 'was already used on another sandbox'}. `
|
|
227
|
+
+ 'Ask the user whether to create a plain sandbox without beta credit; if they agree, call create_sandbox again with without_beta_credit: true.');
|
|
228
|
+
}
|
|
229
|
+
const lines = [
|
|
230
|
+
`Sandbox ${box.id} is running.`,
|
|
231
|
+
listed,
|
|
232
|
+
box.credit_applied ? `Beta credit applied: $${box.credit_usd ?? beta?.credit_usd ?? 10} (OpenRouter)${box.credit_expires_at ? `, ends ${formatCreditDeadline(box.credit_expires_at)}` : ''}.` : '',
|
|
233
|
+
box.transcripts ? 'Claude Code sessions in it are recorded.' : `Claude Code transcripts are off: ${box.transcripts_off}. Commands are still recorded.`,
|
|
234
|
+
`Open a terminal in it: raytrace connect ${box.id}`,
|
|
235
|
+
`Recorded sessions: ${DASHBOARD}`,
|
|
236
|
+
];
|
|
237
|
+
return text(lines.filter(Boolean).join('\n'), { sandbox: box, connect: `raytrace connect ${box.id}` });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function lifecycle(action, { id }) {
|
|
241
|
+
const box = await call('POST', `/v1/sandboxes/${checkId(id)}/${action}`);
|
|
242
|
+
return text(action === 'stop' ? `${box.id} stopped; its files are kept.` : `${box.id} running.`, { sandbox: box });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function destroySandbox({ id, keep_traces: keep = false }) {
|
|
246
|
+
const result = await call('DELETE', `/v1/sandboxes/${checkId(id)}${keep ? '?keep_traces=1' : ''}`);
|
|
247
|
+
const traces = result.traces_kept ? `Its traces are kept until ${new Date(result.traces_kept_until * 1000).toLocaleDateString()}.`
|
|
248
|
+
: result.traces_deleted === false ? 'Its traces could not be deleted; they may still show on the dashboard.'
|
|
249
|
+
: keep ? 'Its traces were deleted: keeping them needs a paid plan (https://raytracer.si/pricing).'
|
|
250
|
+
: 'Its traces were deleted too.';
|
|
251
|
+
return text(`${id} destroyed. ${traces}`, { id, destroyed: true, ...result });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const HANDLERS = {
|
|
255
|
+
login: () => login(),
|
|
256
|
+
list_sandboxes: () => listSandboxes(),
|
|
257
|
+
sandbox_status: (args) => sandboxStatus(args),
|
|
258
|
+
create_sandbox: (args, step) => createSandbox(args, step),
|
|
259
|
+
start_sandbox: (args) => lifecycle('start', args),
|
|
260
|
+
stop_sandbox: (args) => lifecycle('stop', args),
|
|
261
|
+
destroy_sandbox: (args) => destroySandbox(args),
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
async function callTool({ name, arguments: args = {}, _meta: meta } = {}) {
|
|
265
|
+
const handler = HANDLERS[name];
|
|
266
|
+
if (!handler) return null;
|
|
267
|
+
try {
|
|
268
|
+
if (name !== 'login') await requireSignIn();
|
|
269
|
+
return await handler(args, progress(meta?.progressToken));
|
|
270
|
+
} catch (error) {
|
|
271
|
+
// Failures go back to the agent as tool results it can act on.
|
|
272
|
+
return { ...text(error.message), isError: true };
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ------------------------------------------------------------- dispatch
|
|
277
|
+
|
|
278
|
+
async function handle(message) {
|
|
279
|
+
if (!message || typeof message !== 'object') return;
|
|
280
|
+
const { id, method, params } = message;
|
|
281
|
+
if (!method) { // a response to one of our requests
|
|
282
|
+
pending.get(id)?.(message);
|
|
283
|
+
pending.delete(id);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const respond = (result) => { if (id !== undefined) send({ id, result }); };
|
|
287
|
+
const fail = (code, error) => { if (id !== undefined) send({ id, error: { code, message: error } }); };
|
|
288
|
+
switch (method) {
|
|
289
|
+
case 'initialize': {
|
|
290
|
+
client = { capabilities: params?.capabilities ?? {}, info: params?.clientInfo };
|
|
291
|
+
const asked = params?.protocolVersion;
|
|
292
|
+
return respond({
|
|
293
|
+
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
|
|
294
|
+
capabilities: { tools: { listChanged: false } },
|
|
295
|
+
serverInfo: { name: 'raytrace', title: 'RayTrace', version: VERSION },
|
|
296
|
+
instructions: INSTRUCTIONS,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
case 'ping': return respond({});
|
|
300
|
+
case 'tools/list': return respond({ tools: TOOLS });
|
|
301
|
+
case 'tools/call': {
|
|
302
|
+
const result = await callTool(params);
|
|
303
|
+
return result ? respond(result) : fail(-32602, `Unknown tool: ${params?.name}`);
|
|
304
|
+
}
|
|
305
|
+
default:
|
|
306
|
+
if (method.startsWith('notifications/')) return; // initialized, cancelled, roots/list_changed
|
|
307
|
+
return fail(-32601, `Method not found: ${method}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export async function serve() {
|
|
312
|
+
for (const level of ['log', 'info', 'warn', 'debug']) console[level] = console.error;
|
|
313
|
+
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
314
|
+
const inFlight = new Set();
|
|
315
|
+
for await (const line of lines) {
|
|
316
|
+
if (!line.trim()) continue;
|
|
317
|
+
let message;
|
|
318
|
+
try { message = JSON.parse(line); }
|
|
319
|
+
catch { send({ id: null, error: { code: -32700, message: 'Parse error' } }); continue; }
|
|
320
|
+
// Not awaited one by one: a ping must be answered while a sandbox is being created.
|
|
321
|
+
for (const each of Array.isArray(message) ? message : [message]) {
|
|
322
|
+
const job = handle(each).catch((error) => {
|
|
323
|
+
if (each?.id !== undefined && each?.method) send({ id: each.id, error: { code: -32603, message: error.message } });
|
|
324
|
+
});
|
|
325
|
+
inFlight.add(job);
|
|
326
|
+
job.finally(() => inFlight.delete(job));
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
await Promise.all(inFlight);
|
|
330
|
+
}
|
package/src/sandbox.mjs
CHANGED
|
@@ -13,8 +13,9 @@ import { lstatSync } from 'node:fs';
|
|
|
13
13
|
import { request as httpRequest } from 'node:http';
|
|
14
14
|
import { request as httpsRequest } from 'node:https';
|
|
15
15
|
import { basename, join } from 'node:path';
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
16
|
+
import { account } from './auth.mjs';
|
|
17
|
+
import { api, call, ApiError, unreachable } from './api.mjs';
|
|
18
|
+
import { betaStatus, formatCreditDeadline } from './beta.mjs';
|
|
18
19
|
import { ask, confirm, interactive } from './prompt.mjs';
|
|
19
20
|
import * as local from './local-sandbox.mjs';
|
|
20
21
|
|
|
@@ -27,50 +28,26 @@ const MAX_BYTES = 200 * MIB; // all files, before compression
|
|
|
27
28
|
const MAX_FILES = 20_000;
|
|
28
29
|
const MAX_ARCHIVE = 100 * MIB; // the packed upload
|
|
29
30
|
const ID = /^rtp-[a-f0-9]{32}$/;
|
|
30
|
-
const API = 'https://api.raytracer.si';
|
|
31
|
-
const unreachable = (url) => new Error(`Cannot reach RayTrace at ${url.origin}. Check your connection; `
|
|
32
|
-
+ 'networks that inspect HTTPS (some company Wi-Fi) may block it.');
|
|
33
31
|
|
|
34
32
|
// Never packed: version control, dependencies and build output (rebuilt in the
|
|
35
33
|
// sandbox), and files that usually hold credentials.
|
|
36
|
-
const EXCLUDED = new Set(['.git', '.raytace', '.raytrace', '.ssh', '.aws', '.azure', '.config', 'node_modules', '.venv',
|
|
34
|
+
const EXCLUDED = new Set(['.git', '.raytace', '.raytrace', '.ssh', '.aws', '.azure', '.config', '.claude', 'node_modules', '.venv',
|
|
37
35
|
'__pycache__', '.next', '.vinext', 'dist', 'coverage', '.wrangler', '.DS_Store']);
|
|
38
|
-
const SECRET_NAMES = new Set([
|
|
36
|
+
const SECRET_NAMES = new Set([
|
|
37
|
+
'.npmrc', '.netrc', '.pypirc', '.htpasswd', '.dockercfg', 'credentials', 'credentials.json', 'credentials.ini',
|
|
38
|
+
'auth.json', 'service-account.json', 'service_account.json', 'serviceAccountKey.json',
|
|
39
|
+
'client_secret.json', 'client_secrets.json', 'token.json', 'id_rsa', 'id_dsa', 'id_ecdsa',
|
|
40
|
+
'id_ed25519', 'id_ecdsa_sk', 'id_ed25519_sk', 'known_hosts',
|
|
41
|
+
]);
|
|
39
42
|
const SECRET_EXTENSIONS = /\.(pem|key|p12|pfx)$/i;
|
|
40
43
|
|
|
41
44
|
export function packable(path) {
|
|
42
45
|
const parts = path.split('/');
|
|
43
46
|
const name = parts.at(-1);
|
|
47
|
+
const lower = name.toLowerCase();
|
|
44
48
|
return !parts.some((part) => EXCLUDED.has(part) || part === '..') && !path.startsWith('/')
|
|
45
|
-
&& !
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
async function api() {
|
|
49
|
-
const config = readConfig();
|
|
50
|
-
const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
|
|
51
|
-
let key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
|
|
52
|
-
if (!key) {
|
|
53
|
-
if (!interactive()) throw new Error('Not signed in. Run: raytrace auth login');
|
|
54
|
-
say('You are not signed in to RayTrace yet.');
|
|
55
|
-
await login();
|
|
56
|
-
key = await accessToken();
|
|
57
|
-
if (!key) throw new Error('Not signed in. Run: raytrace auth login');
|
|
58
|
-
say();
|
|
59
|
-
}
|
|
60
|
-
return { url: new URL(url), key };
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
async function call(method, path, { body, headers = {} } = {}) {
|
|
64
|
-
const { url, key } = await api();
|
|
65
|
-
let response;
|
|
66
|
-
try {
|
|
67
|
-
response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
|
|
68
|
-
} catch {
|
|
69
|
-
throw unreachable(url);
|
|
70
|
-
}
|
|
71
|
-
const data = await response.json().catch(() => ({}));
|
|
72
|
-
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
|
|
73
|
-
return data;
|
|
49
|
+
&& !lower.startsWith('.env') && !lower.startsWith('.secret')
|
|
50
|
+
&& !SECRET_EXTENSIONS.test(name) && !SECRET_NAMES.has(lower);
|
|
74
51
|
}
|
|
75
52
|
|
|
76
53
|
/** The project's files git would track, minus what must not leave this machine. */
|
|
@@ -112,38 +89,110 @@ function pack(root, files) {
|
|
|
112
89
|
});
|
|
113
90
|
}
|
|
114
91
|
|
|
92
|
+
/** The signed-in workspace's cloud sandboxes, minus deleted ones. */
|
|
93
|
+
export async function liveSandboxes() {
|
|
94
|
+
return (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function checkId(id) {
|
|
98
|
+
if (!ID.test(id)) throw new Error(`Not a sandbox id: ${id}`);
|
|
99
|
+
return id;
|
|
100
|
+
}
|
|
101
|
+
|
|
115
102
|
async function pickId(id) {
|
|
116
|
-
if (id)
|
|
117
|
-
|
|
118
|
-
return id;
|
|
119
|
-
}
|
|
120
|
-
const live = (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
|
|
103
|
+
if (id) return checkId(id);
|
|
104
|
+
const live = await liveSandboxes();
|
|
121
105
|
if (live.length === 1) return live[0].id;
|
|
122
106
|
throw new Error(live.length ? 'More than one sandbox; name one (raytrace sandbox list).'
|
|
123
107
|
: `No sandboxes${account() ? ` in ${account()}'s workspace` : ''} yet: raytrace sandbox create`);
|
|
124
108
|
}
|
|
125
109
|
|
|
110
|
+
/** The top of the Git repository holding `dir`, or null. */
|
|
111
|
+
export function repoRoot(dir = process.cwd()) {
|
|
112
|
+
const top = spawnSync('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });
|
|
113
|
+
return top.status === 0 ? top.stdout.trim() : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The files of the repository at `root` that may be uploaded, checked against the limits. */
|
|
117
|
+
export function listProject(root) {
|
|
118
|
+
const project = projectFiles(root);
|
|
119
|
+
if (!project.files.length) throw new Error('Nothing to upload.');
|
|
120
|
+
return project;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Pack listed files into the gzip archive a sandbox is created from. */
|
|
124
|
+
export async function packArchive(root, files) {
|
|
125
|
+
const archive = await pack(root, files);
|
|
126
|
+
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.`);
|
|
127
|
+
return archive;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** What beta credit does for the next cloud sandbox: 'use' it, it has
|
|
131
|
+
* 'expired' (unused, past its hard 3 days), or 'none'. Credit is consumed by
|
|
132
|
+
* the first cloud sandbox created after redemption. An older backend (or no
|
|
133
|
+
* entitlement) never blocks a plain one, so no answer means 'none'; the
|
|
134
|
+
* create call surfaces any real auth/network failure. */
|
|
135
|
+
export async function creditPlan() {
|
|
136
|
+
let beta;
|
|
137
|
+
try { beta = await betaStatus(); } catch { return { plan: 'none', beta: null }; }
|
|
138
|
+
const deadlinePassed = beta?.credit_expires_at && Date.parse(beta.credit_expires_at) <= Date.now();
|
|
139
|
+
if (beta && !beta.sandbox_consumed && deadlinePassed && (beta.entitled || beta.credit_usd)) return { plan: 'expired', beta };
|
|
140
|
+
if (beta?.entitled && !beta.sandbox_consumed) return { plan: 'use', beta };
|
|
141
|
+
return { plan: 'none', beta };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Create a cloud sandbox from a packed project. A credit refusal comes back
|
|
145
|
+
* as an ApiError (see isCreditRefusal) for the caller to decide on. */
|
|
146
|
+
export function upload(archive, name, useCredit) {
|
|
147
|
+
const headers = { 'content-type': 'application/gzip', 'x-raytrace-name': name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) };
|
|
148
|
+
return call('POST', '/v1/sandboxes', { body: archive, headers: useCredit ? { ...headers, 'x-raytrace-beta-credit': '1' } : headers });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The API refused the credit: 409 already used on another sandbox, 410 expired. */
|
|
152
|
+
export const isCreditRefusal = (error) => error instanceof ApiError && [409, 410].includes(error.status);
|
|
153
|
+
|
|
126
154
|
export async function create(flags) {
|
|
127
|
-
const
|
|
128
|
-
if (
|
|
129
|
-
const root = top.stdout.trim();
|
|
155
|
+
const root = repoRoot();
|
|
156
|
+
if (!root) throw new Error('Run this from inside a Git repository.');
|
|
130
157
|
const name = flags.name || basename(root);
|
|
131
158
|
// What the machine lacks is said before the project is read, and Lima fetched if agreed.
|
|
132
159
|
const localName = flags.local ? local.sandboxName(flags, root) : null;
|
|
133
160
|
if (flags.local) await local.preflight(flags, { confirm, interactive });
|
|
134
|
-
const { files, skipped, total } =
|
|
135
|
-
if (!files.length) throw new Error('Nothing to upload.');
|
|
161
|
+
const { files, skipped, total } = listProject(root);
|
|
136
162
|
// The same files, packed the same way, as a cloud sandbox gets: only the copy stays here.
|
|
137
163
|
if (flags.local) return local.create(localName, { root, files, skipped, total, archive: await pack(root, files) });
|
|
164
|
+
|
|
165
|
+
// A local sandbox never uses beta credit.
|
|
166
|
+
const { plan, beta } = await creditPlan();
|
|
167
|
+
if (plan === 'expired') {
|
|
168
|
+
say('Your $10 beta credit has expired: the 3 days ran out, and unused credit does not carry over.');
|
|
169
|
+
if (!interactive()) throw new Error('Beta credit expired; no sandbox was created. Ask RayTrace for a new code to try again.');
|
|
170
|
+
if (!(await confirm('Create a plain sandbox without beta credit?', false))) { say('Not created.'); return; }
|
|
171
|
+
} else if (plan === 'use') {
|
|
172
|
+
say(`Using your $${beta.credit_usd ?? 10} beta credit (OpenRouter) on this sandbox`
|
|
173
|
+
+ `${beta.credit_expires_at ? ` — credit ends ${formatCreditDeadline(beta.credit_expires_at)}` : ''}.`);
|
|
174
|
+
}
|
|
175
|
+
const useCredit = plan === 'use';
|
|
138
176
|
say(`Packing ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}`);
|
|
139
177
|
if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
|
|
140
|
-
const archive = await
|
|
141
|
-
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.`);
|
|
178
|
+
const archive = await packArchive(root, files);
|
|
142
179
|
say('Creating the sandbox (the first one on a host takes a little longer)...');
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
180
|
+
let box;
|
|
181
|
+
try {
|
|
182
|
+
box = await upload(archive, name, useCredit);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (!useCredit || !isCreditRefusal(error)) throw error;
|
|
185
|
+
say(error.status === 410 ? 'Your beta credit expired before the sandbox was created.'
|
|
186
|
+
: 'Your beta credit was already used on another sandbox.');
|
|
187
|
+
if (!interactive() || !(await confirm('Create a plain sandbox without beta credit?', false))) {
|
|
188
|
+
throw new Error('Beta credit not applied; no sandbox was created.');
|
|
189
|
+
}
|
|
190
|
+
box = await upload(archive, name, false);
|
|
191
|
+
}
|
|
146
192
|
say(`\nSandbox ${box.id} is running.`);
|
|
193
|
+
if (box.credit_applied) {
|
|
194
|
+
say(`Beta credit applied: $${box.credit_usd ?? 10} (OpenRouter)${box.credit_expires_at ? `, ends ${formatCreditDeadline(box.credit_expires_at)}` : ''}. This sandbox shows as Beta in the dashboard.`);
|
|
195
|
+
}
|
|
147
196
|
say(box.transcripts ? 'Claude Code sessions in it are recorded.'
|
|
148
197
|
: `Claude Code transcripts are off: ${box.transcripts_off}. Commands are still recorded.`);
|
|
149
198
|
say(`Open it: raytrace connect ${box.id}`);
|
|
@@ -151,13 +200,14 @@ export async function create(flags) {
|
|
|
151
200
|
|
|
152
201
|
export async function list(flags = {}) {
|
|
153
202
|
if (flags.local) return local.list();
|
|
154
|
-
const boxes =
|
|
203
|
+
const boxes = await liveSandboxes();
|
|
155
204
|
if (!boxes.length) { say('No sandboxes. Create one from a Git repository: raytrace sandbox create'); return; }
|
|
156
205
|
for (const box of boxes) {
|
|
157
206
|
// The sandbox's creation time (seconds), or its container's once that is known.
|
|
158
207
|
const created = typeof box.created === 'number' ? box.created * 1000 : Date.parse(box.created);
|
|
159
208
|
const age = Math.round((Date.now() - created) / 60000);
|
|
160
|
-
|
|
209
|
+
const beta = box.beta ? ` Beta${typeof box.credit_usd === 'number' ? ` ($${Math.max(0, box.credit_usd - (box.credit_spent_usd ?? 0)).toFixed(2)} of $${box.credit_usd} left${box.credit_expires_at ? `, ends ${formatCreditDeadline(box.credit_expires_at)}` : ''})` : ''}` : '';
|
|
210
|
+
say(`${box.id} ${String(box.status).padEnd(8)} ${box.name}${beta} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
|
|
161
211
|
}
|
|
162
212
|
}
|
|
163
213
|
|
|
@@ -192,6 +242,17 @@ export async function destroy(id, flags) {
|
|
|
192
242
|
else if (result.traces_deleted === false) say('Note: its traces could not be deleted; they may still show on the dashboard.');
|
|
193
243
|
}
|
|
194
244
|
|
|
245
|
+
/** Exported for tests: the warning shown when connecting to a beta sandbox
|
|
246
|
+
* whose 3 days are up, or null. Model calls inside are refused by the
|
|
247
|
+
* backend; the sandbox itself still opens. */
|
|
248
|
+
export function betaExpiryWarning(beta, id, now = Date.now()) {
|
|
249
|
+
if (!beta || beta.credited_sandbox_id !== id) return null;
|
|
250
|
+
const deadline = beta.credit_expires_at ? Date.parse(beta.credit_expires_at) : NaN;
|
|
251
|
+
if (!beta.expired && !(deadline <= now)) return null;
|
|
252
|
+
return `Warning: your beta credit for this sandbox expired${beta.credit_expires_at ? ` (${formatCreditDeadline(beta.credit_expires_at, now)})` : ''}; `
|
|
253
|
+
+ 'model calls in this sandbox will be refused. The sandbox itself still opens.';
|
|
254
|
+
}
|
|
255
|
+
|
|
195
256
|
/** An interactive terminal in the sandbox, carried over one upgraded HTTP request.
|
|
196
257
|
* `raytrace connect <id>` and `raytrace sandbox shell [id]` are the same thing. */
|
|
197
258
|
export async function shell(id, flags = {}) {
|
|
@@ -199,6 +260,10 @@ export async function shell(id, flags = {}) {
|
|
|
199
260
|
// With no id and no cloud sign-in, the one local sandbox is the likely one.
|
|
200
261
|
if (flags.local || local.isLocal(id) || (!id && Object.keys(local.registry()).length && !account())) return local.shell(id);
|
|
201
262
|
id = await pickId(id);
|
|
263
|
+
try {
|
|
264
|
+
const warning = betaExpiryWarning(await betaStatus(), id);
|
|
265
|
+
if (warning) say(warning);
|
|
266
|
+
} catch { /* no beta answer: connecting must not depend on it */ }
|
|
202
267
|
const { url, key } = await api();
|
|
203
268
|
const { stdin, stdout } = process;
|
|
204
269
|
const path = `/v1/sandboxes/${id}/shell?rows=${stdout.rows || 24}&cols=${stdout.columns || 80}`;
|